]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Old fix for Cydia failing to save Source changes.
[cydia.git] / MobileCydia.mm
1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2012 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
42
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
46
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
49
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
52
53 #if 0
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
57 #endif
58
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
61
62 #include <SystemConfiguration/SystemConfiguration.h>
63
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
66
67 #include <IOKit/IOKitLib.h>
68
69 #include <QuartzCore/CALayer.h>
70
71 #include <WebCore/WebCoreThread.h>
72 #include <WebKit/DOMHTMLIFrameElement.h>
73
74 #include <algorithm>
75 #include <iomanip>
76 #include <sstream>
77 #include <string>
78
79 #include <ext/stdio_filebuf.h>
80
81 #undef ABS
82
83 #include <apt-pkg/acquire.h>
84 #include <apt-pkg/acquire-item.h>
85 #include <apt-pkg/algorithms.h>
86 #include <apt-pkg/cachefile.h>
87 #include <apt-pkg/clean.h>
88 #include <apt-pkg/configuration.h>
89 #include <apt-pkg/debindexfile.h>
90 #include <apt-pkg/debmetaindex.h>
91 #include <apt-pkg/error.h>
92 #include <apt-pkg/init.h>
93 #include <apt-pkg/mmap.h>
94 #include <apt-pkg/pkgrecords.h>
95 #include <apt-pkg/sha1.h>
96 #include <apt-pkg/sourcelist.h>
97 #include <apt-pkg/sptr.h>
98 #include <apt-pkg/strutl.h>
99 #include <apt-pkg/tagfile.h>
100
101 #include <apr-1/apr_pools.h>
102
103 #include <sys/types.h>
104 #include <sys/stat.h>
105 #include <sys/sysctl.h>
106 #include <sys/param.h>
107 #include <sys/mount.h>
108 #include <sys/reboot.h>
109
110 #include <fcntl.h>
111 #include <notify.h>
112 #include <dlfcn.h>
113
114 extern "C" {
115 #include <mach-o/nlist.h>
116 }
117
118 #include <cstdio>
119 #include <cstdlib>
120 #include <cstring>
121
122 #include <errno.h>
123
124 #include <Cytore.hpp>
125 #include "Sources.h"
126
127 #include <CydiaSubstrate/CydiaSubstrate.h>
128 #include "Menes/Menes.h"
129
130 #include "CyteKit/IndirectDelegate.h"
131 #include "CyteKit/PerlCompatibleRegEx.hpp"
132 #include "CyteKit/TableViewCell.h"
133 #include "CyteKit/WebScriptObject-Cyte.h"
134 #include "CyteKit/WebViewController.h"
135 #include "CyteKit/WebViewTableViewCell.h"
136 #include "CyteKit/stringWithUTF8Bytes.h"
137
138 #include "Cydia/MIMEAddress.h"
139 #include "Cydia/LoadingViewController.h"
140 #include "Cydia/ProgressEvent.h"
141
142 #include "SDURLCache/SDURLCache.h"
143 /* }}} */
144
145 /* Profiler {{{ */
146 struct timeval _ltv;
147 bool _itv;
148
149 #define _timestamp ({ \
150 struct timeval tv; \
151 gettimeofday(&tv, NULL); \
152 tv.tv_sec * 1000000 + tv.tv_usec; \
153 })
154
155 typedef std::vector<class ProfileTime *> TimeList;
156 TimeList times_;
157
158 class ProfileTime {
159 private:
160 const char *name_;
161 uint64_t total_;
162 uint64_t count_;
163
164 public:
165 ProfileTime(const char *name) :
166 name_(name),
167 total_(0)
168 {
169 times_.push_back(this);
170 }
171
172 void AddTime(uint64_t time) {
173 total_ += time;
174 ++count_;
175 }
176
177 void Print() {
178 if (total_ != 0)
179 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
180 total_ = 0;
181 count_ = 0;
182 }
183 };
184
185 class ProfileTimer {
186 private:
187 ProfileTime &time_;
188 uint64_t start_;
189
190 public:
191 ProfileTimer(ProfileTime &time) :
192 time_(time),
193 start_(_timestamp)
194 {
195 }
196
197 ~ProfileTimer() {
198 time_.AddTime(_timestamp - start_);
199 }
200 };
201
202 void PrintTimes() {
203 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
204 (*i)->Print();
205 std::cerr << "========" << std::endl;
206 }
207
208 #define _profile(name) { \
209 static ProfileTime name(#name); \
210 ProfileTimer _ ## name(name);
211
212 #define _end }
213 /* }}} */
214
215 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
216 #define synchronized(lock) \
217 synchronized(static_cast<NSObject *>(lock))
218
219 extern NSString *Cydia_;
220
221 #define lprintf(args...) fprintf(stderr, args)
222
223 #define ForRelease 1
224 #define TraceLogging (1 && !ForRelease)
225 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
226 #define ProfileTimes (0 && !ForRelease)
227 #define ForSaurik (0 && !ForRelease)
228 #define LogBrowser (0 && !ForRelease)
229 #define TrackResize (0 && !ForRelease)
230 #define ManualRefresh (1 && !ForRelease)
231 #define ShowInternals (0 && !ForRelease)
232 #define AlwaysReload (0 && !ForRelease)
233 #define TryIndexedCollation (0 && !ForRelease)
234
235 #if !TraceLogging
236 #undef _trace
237 #define _trace(args...)
238 #endif
239
240 #if !ProfileTimes
241 #undef _profile
242 #define _profile(name) {
243 #undef _end
244 #define _end }
245 #define PrintTimes() do {} while (false)
246 #endif
247
248 // Hash Functions/Structures {{{
249 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
250
251 union SplitHash {
252 uint32_t u32;
253 uint16_t u16[2];
254 };
255 // }}}
256
257 static bool ShowPromoted_;
258
259 static NSString *Colon_;
260 NSString *Elision_;
261 static NSString *Error_;
262 static NSString *Warning_;
263
264 static NSString *Cache_;
265
266 static bool AprilFools_;
267
268 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
269
270 static bool IsReachable(const char *name) {
271 SCNetworkReachabilityFlags flags; {
272 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
273 SCNetworkReachabilityGetFlags(reachability, &flags);
274 CFRelease(reachability);
275 }
276
277 // XXX: this elaborate mess is what Apple is using to determine this? :(
278 // XXX: do we care if the user has to intervene? maybe that's ok?
279 return
280 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
281 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
282 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
283 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
284 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
285 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
286 )
287 ;
288 }
289
290 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
291
292 static _finline NSString *CydiaURL(NSString *path) {
293 char page[26];
294 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
295 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
296 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
297 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
298 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
299 page[25] = '\0';
300 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
301 }
302
303 static void ReapZombie(pid_t pid) {
304 int status;
305 wait:
306 if (waitpid(pid, &status, 0) == -1)
307 if (errno == EINTR)
308 goto wait;
309 else _assert(false);
310 }
311
312 static _finline void UpdateExternalStatus(uint64_t newStatus) {
313 int notify_token;
314 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
315 notify_set_state(notify_token, newStatus);
316 notify_cancel(notify_token);
317 }
318 notify_post("com.saurik.Cydia.status");
319 }
320
321 static CGFloat CYStatusBarHeight() {
322 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
323 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
324 }
325
326 /* NSForcedOrderingSearch doesn't work on the iPhone */
327 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
328 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
329 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
330
331 /* Insertion Sort {{{ */
332
333 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
334 const char *ptr = (const char *)list;
335 while (0 < count) {
336 CFIndex half = count / 2;
337 const char *probe = ptr + elementSize * half;
338 CFComparisonResult cr = comparator(element, probe, context);
339 if (0 == cr) return (probe - (const char *)list) / elementSize;
340 ptr = (cr < 0) ? ptr : probe + elementSize;
341 count = (cr < 0) ? half : (half + (count & 1) - 1);
342 }
343 return (ptr - (const char *)list) / elementSize;
344 }
345
346 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
347 const char *ptr = (const char *)list;
348 while (0 < count) {
349 CFIndex half = count / 2;
350 const char *probe = ptr + elementSize * half;
351 CFComparisonResult cr = comparator(element, probe, context);
352 if (0 == cr) return (probe - (const char *)list) / elementSize;
353 ptr = (cr < 0) ? ptr : probe + elementSize;
354 count = (cr < 0) ? half : (half + (count & 1) - 1);
355 }
356 return (ptr - (const char *)list) / elementSize;
357 }
358
359 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
360 if (range.length == 0)
361 return;
362 const void **values(new const void *[range.length]);
363 CFArrayGetValues(array, range, values);
364
365 #if HistogramInsertionSort > 0
366 uint32_t total(0), *offsets(new uint32_t[range.length]);
367 #endif
368
369 for (CFIndex index(1); index != range.length; ++index) {
370 const void *value(values[index]);
371 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
372 CFIndex correct(index);
373 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
374 #if HistogramInsertionSort > 1
375 NSLog(@"%@ < %@", value, values[correct - 1]);
376 #endif
377 if (--correct == 0)
378 break;
379 }
380 if (correct != index) {
381 size_t offset(index - correct);
382 #if HistogramInsertionSort
383 total += offset;
384 ++offsets[offset];
385 if (offset > 10)
386 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
387 #endif
388 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
389 values[correct] = value;
390 }
391 }
392
393 CFArrayReplaceValues(array, range, values, range.length);
394 delete [] values;
395
396 #if HistogramInsertionSort > 0
397 for (CFIndex index(0); index != range.length; ++index)
398 if (offsets[index] != 0)
399 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
400 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
401 delete [] offsets;
402 #endif
403 }
404
405 /* }}} */
406
407 /* Apple Bug Fixes {{{ */
408 @implementation UIWebDocumentView (Cydia)
409
410 - (void) _setScrollerOffset:(CGPoint)offset {
411 UIScroller *scroller([self _scroller]);
412
413 CGSize size([scroller contentSize]);
414 CGSize bounds([scroller bounds].size);
415
416 CGPoint max;
417 max.x = size.width - bounds.width;
418 max.y = size.height - bounds.height;
419
420 // wtf Apple?!
421 if (max.x < 0)
422 max.x = 0;
423 if (max.y < 0)
424 max.y = 0;
425
426 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
427 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
428
429 [scroller setOffset:offset];
430 }
431
432 @end
433 /* }}} */
434
435 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
436 size_t length([self length] - state->state);
437 if (length <= 0)
438 return 0;
439 else if (length > count)
440 length = count;
441 for (size_t i(0); i != length; ++i)
442 objects[i] = [self item:state->state++];
443 state->itemsPtr = objects;
444 state->mutationsPtr = (unsigned long *) self;
445 return length;
446 }
447
448 /* Cydia NSString Additions {{{ */
449 @interface NSString (Cydia)
450 - (NSComparisonResult) compareByPath:(NSString *)other;
451 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
452 @end
453
454 @implementation NSString (Cydia)
455
456 - (NSComparisonResult) compareByPath:(NSString *)other {
457 NSString *prefix = [self commonPrefixWithString:other options:0];
458 size_t length = [prefix length];
459
460 NSRange lrange = NSMakeRange(length, [self length] - length);
461 NSRange rrange = NSMakeRange(length, [other length] - length);
462
463 lrange = [self rangeOfString:@"/" options:0 range:lrange];
464 rrange = [other rangeOfString:@"/" options:0 range:rrange];
465
466 NSComparisonResult value;
467
468 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
469 value = NSOrderedSame;
470 else if (lrange.location == NSNotFound)
471 value = NSOrderedAscending;
472 else if (rrange.location == NSNotFound)
473 value = NSOrderedDescending;
474 else
475 value = NSOrderedSame;
476
477 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
478 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
479 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
480 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
481
482 NSComparisonResult result = [lpath compare:rpath];
483 return result == NSOrderedSame ? value : result;
484 }
485
486 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
487 return [(id)CFURLCreateStringByAddingPercentEscapes(
488 kCFAllocatorDefault,
489 (CFStringRef) self,
490 NULL,
491 CFSTR(";/?:@&=+$,"),
492 kCFStringEncodingUTF8
493 ) autorelease];
494 }
495
496 @end
497 /* }}} */
498
499 /* C++ NSString Wrapper Cache {{{ */
500 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
501 return size == 0 ? NULL :
502 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
503 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
504 }
505
506 static _finline CFStringRef CYStringCreate(const char *data) {
507 return CYStringCreate(data, strlen(data));
508 }
509
510 class CYString {
511 private:
512 char *data_;
513 size_t size_;
514 CFStringRef cache_;
515
516 _finline void clear_() {
517 if (cache_ != NULL) {
518 CFRelease(cache_);
519 cache_ = NULL;
520 }
521 }
522
523 public:
524 _finline bool empty() const {
525 return size_ == 0;
526 }
527
528 _finline size_t size() const {
529 return size_;
530 }
531
532 _finline char *data() const {
533 return data_;
534 }
535
536 _finline void clear() {
537 size_ = 0;
538 clear_();
539 }
540
541 _finline CYString() :
542 data_(0),
543 size_(0),
544 cache_(NULL)
545 {
546 }
547
548 _finline ~CYString() {
549 clear_();
550 }
551
552 void operator =(const CYString &rhs) {
553 data_ = rhs.data_;
554 size_ = rhs.size_;
555
556 if (rhs.cache_ == nil)
557 cache_ = NULL;
558 else
559 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
560 }
561
562 void copy(apr_pool_t *pool) {
563 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
564 memcpy(temp, data_, size_);
565 temp[size_] = '\0';
566 data_ = temp;
567 }
568
569 void set(apr_pool_t *pool, const char *data, size_t size) {
570 if (size == 0)
571 clear();
572 else {
573 clear_();
574
575 data_ = const_cast<char *>(data);
576 size_ = size;
577
578 if (pool != NULL)
579 copy(pool);
580 }
581 }
582
583 _finline void set(apr_pool_t *pool, const char *data) {
584 set(pool, data, data == NULL ? 0 : strlen(data));
585 }
586
587 _finline void set(apr_pool_t *pool, const std::string &rhs) {
588 set(pool, rhs.data(), rhs.size());
589 }
590
591 bool operator ==(const CYString &rhs) const {
592 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
593 }
594
595 _finline operator CFStringRef() {
596 if (cache_ == NULL)
597 cache_ = CYStringCreate(data_, size_);
598 return cache_;
599 }
600
601 _finline operator id() {
602 return (NSString *) static_cast<CFStringRef>(*this);
603 }
604
605 _finline operator const char *() {
606 return reinterpret_cast<const char *>(data_);
607 }
608 };
609 /* }}} */
610 /* C++ NSString Algorithm Adapters {{{ */
611 extern "C" {
612 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
613 }
614
615 struct NSStringMapHash :
616 std::unary_function<NSString *, size_t>
617 {
618 _finline size_t operator ()(NSString *value) const {
619 return CFStringHashNSString((CFStringRef) value);
620 }
621 };
622
623 struct NSStringMapLess :
624 std::binary_function<NSString *, NSString *, bool>
625 {
626 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
627 return [lhs compare:rhs] == NSOrderedAscending;
628 }
629 };
630
631 struct NSStringMapEqual :
632 std::binary_function<NSString *, NSString *, bool>
633 {
634 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
635 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
636 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
637 //[lhs isEqualToString:rhs];
638 }
639 };
640 /* }}} */
641
642 /* CoreGraphics Primitives {{{ */
643 class CYColor {
644 private:
645 CGColorRef color_;
646
647 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
648 CGFloat color[] = {red, green, blue, alpha};
649 return CGColorCreate(space, color);
650 }
651
652 public:
653 CYColor() :
654 color_(NULL)
655 {
656 }
657
658 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
659 color_(Create_(space, red, green, blue, alpha))
660 {
661 Set(space, red, green, blue, alpha);
662 }
663
664 void Clear() {
665 if (color_ != NULL)
666 CGColorRelease(color_);
667 }
668
669 ~CYColor() {
670 Clear();
671 }
672
673 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
674 Clear();
675 color_ = Create_(space, red, green, blue, alpha);
676 }
677
678 operator CGColorRef() {
679 return color_;
680 }
681 };
682 /* }}} */
683
684 /* Random Global Variables {{{ */
685 static int PulseInterval_ = 500000;
686
687 static const NSString *UI_;
688
689 static int Finish_;
690 static bool RestartSubstrate_;
691 static NSArray *Finishes_;
692
693 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
694 #define NotifyConfig_ "/etc/notify.conf"
695
696 static bool Queuing_;
697
698 static CYColor Blue_;
699 static CYColor Blueish_;
700 static CYColor Black_;
701 static CYColor Off_;
702 static CYColor White_;
703 static CYColor Gray_;
704 static CYColor Green_;
705 static CYColor Purple_;
706 static CYColor Purplish_;
707
708 static UIColor *InstallingColor_;
709 static UIColor *RemovingColor_;
710
711 static NSString *App_;
712
713 static BOOL Advanced_;
714 static BOOL Ignored_;
715
716 static _H<UIFont> Font12_;
717 static _H<UIFont> Font12Bold_;
718 static _H<UIFont> Font14_;
719 static _H<UIFont> Font18Bold_;
720 static _H<UIFont> Font22Bold_;
721
722 static const char *Machine_ = NULL;
723 static _H<NSString> System_;
724 static NSString *SerialNumber_ = nil;
725 static NSString *ChipID_ = nil;
726 static NSString *BBSNum_ = nil;
727 static _H<NSString> Token_;
728 static NSString *UniqueID_ = nil;
729 static _H<NSString> UserAgent_;
730 static _H<NSString> Product_;
731 static _H<NSString> Safari_;
732
733 static CFLocaleRef Locale_;
734 static NSArray *Languages_;
735 static CGColorSpaceRef space_;
736
737 static NSDictionary *SectionMap_;
738 static NSMutableDictionary *Metadata_;
739 static _transient NSMutableDictionary *Settings_;
740 static _transient NSString *Role_;
741 static _transient NSMutableDictionary *Packages_;
742 static _transient NSMutableDictionary *Values_;
743 static _transient NSMutableDictionary *Sections_;
744 _H<NSMutableDictionary> Sources_;
745 static _transient NSNumber *Version_;
746 bool Changed_;
747 static time_t now_;
748
749 bool IsWildcat_;
750 static CGFloat ScreenScale_;
751 static NSString *Idiom_;
752 static _H<NSString> Firmware_;
753 static NSString *Major_;
754
755 static _H<NSMutableDictionary> SessionData_;
756 static _H<NSObject> HostConfig_;
757 static _H<NSMutableSet> BridgedHosts_;
758 static _H<NSMutableSet> TokenHosts_;
759 static _H<NSMutableSet> InsecureHosts_;
760 static _H<NSMutableSet> PipelinedHosts_;
761 static _H<NSMutableSet> CachedURLs_;
762
763 static NSString *kCydiaProgressEventTypeError = @"Error";
764 static NSString *kCydiaProgressEventTypeInformation = @"Information";
765 static NSString *kCydiaProgressEventTypeStatus = @"Status";
766 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
767 /* }}} */
768
769 /* Display Helpers {{{ */
770 inline float Interpolate(float begin, float end, float fraction) {
771 return (end - begin) * fraction + begin;
772 }
773
774 static _finline const char *StripVersion_(const char *version) {
775 const char *colon(strchr(version, ':'));
776 return colon == NULL ? version : colon + 1;
777 }
778
779 NSString *LocalizeSection(NSString *section) {
780 static Pcre title_r("^(.*?) \\((.*)\\)$");
781 if (title_r(section)) {
782 NSString *parent(title_r[1]);
783 NSString *child(title_r[2]);
784
785 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
786 LocalizeSection(parent),
787 LocalizeSection(child)
788 ];
789 }
790
791 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
792 }
793
794 NSString *Simplify(NSString *title) {
795 const char *data = [title UTF8String];
796 size_t size = [title length];
797
798 static Pcre square_r("^\\[(.*)\\]$");
799 if (square_r(data, size))
800 return Simplify(square_r[1]);
801
802 static Pcre paren_r("^\\((.*)\\)$");
803 if (paren_r(data, size))
804 return Simplify(paren_r[1]);
805
806 static Pcre title_r("^(.*?) \\((.*)\\)$");
807 if (title_r(data, size))
808 return Simplify(title_r[1]);
809
810 return title;
811 }
812 /* }}} */
813
814 NSString *GetLastUpdate() {
815 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
816
817 if (update == nil)
818 return UCLocalize("NEVER_OR_UNKNOWN");
819
820 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
821 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
822
823 CFRelease(formatter);
824
825 return [(NSString *) formatted autorelease];
826 }
827
828 bool isSectionVisible(NSString *section) {
829 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
830 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
831 return hidden == nil || ![hidden boolValue];
832 }
833
834 static NSObject *CYIOGetValue(const char *path, NSString *property) {
835 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
836 if (entry == MACH_PORT_NULL)
837 return nil;
838
839 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
840 IOObjectRelease(entry);
841
842 if (value == NULL)
843 return nil;
844 return [(id) value autorelease];
845 }
846
847 static NSString *CYHex(NSData *data, bool reverse = false) {
848 if (data == nil)
849 return nil;
850
851 size_t length([data length]);
852 uint8_t bytes[length];
853 [data getBytes:bytes];
854
855 char string[length * 2 + 1];
856 for (size_t i(0); i != length; ++i)
857 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
858
859 return [NSString stringWithUTF8String:string];
860 }
861
862 @class Cydia;
863
864 /* Delegate Prototypes {{{ */
865 @class Package;
866 @class Source;
867 @class CydiaProgressEvent;
868
869 @protocol DatabaseDelegate
870 - (void) repairWithSelector:(SEL)selector;
871 - (void) setConfigurationData:(NSString *)data;
872 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
873 @end
874
875 @class CYPackageController;
876
877 @protocol CydiaDelegate
878 - (void) returnToCydia;
879 - (void) saveState;
880 - (void) retainNetworkActivityIndicator;
881 - (void) releaseNetworkActivityIndicator;
882 - (void) clearPackage:(Package *)package;
883 - (void) installPackage:(Package *)package;
884 - (void) installPackages:(NSArray *)packages;
885 - (void) removePackage:(Package *)package;
886 - (void) beginUpdate;
887 - (BOOL) updating;
888 - (void) distUpgrade;
889 - (void) loadData;
890 - (void) updateData;
891 - (void) _saveConfig;
892 - (void) syncData;
893 - (void) addSource:(NSDictionary *)source;
894 - (void) addTrivialSource:(NSString *)href;
895 - (void) showSettings;
896 - (UIProgressHUD *) addProgressHUD;
897 - (void) removeProgressHUD:(UIProgressHUD *)hud;
898 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
899 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
900 @end
901 /* }}} */
902
903 /* Status Delegation {{{ */
904 class Status :
905 public pkgAcquireStatus
906 {
907 private:
908 _transient NSObject<ProgressDelegate> *delegate_;
909 bool cancelled_;
910
911 public:
912 Status() :
913 delegate_(nil),
914 cancelled_(false)
915 {
916 }
917
918 void setDelegate(NSObject<ProgressDelegate> *delegate) {
919 delegate_ = delegate;
920 }
921
922 NSObject<ProgressDelegate> *getDelegate() const {
923 return delegate_;
924 }
925
926 virtual bool MediaChange(std::string media, std::string drive) {
927 return false;
928 }
929
930 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
931 Done(item);
932 }
933
934 virtual void Fetch(pkgAcquire::ItemDesc &item) {
935 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
936 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
937 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
938 }
939
940 virtual void Done(pkgAcquire::ItemDesc &item) {
941 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
942 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
943 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
944 }
945
946 virtual void Fail(pkgAcquire::ItemDesc &item) {
947 if (
948 item.Owner->Status == pkgAcquire::Item::StatIdle ||
949 item.Owner->Status == pkgAcquire::Item::StatDone
950 )
951 return;
952
953 std::string &error(item.Owner->ErrorText);
954 if (error.empty())
955 return;
956
957 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
958 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
959 }
960
961 virtual bool Pulse(pkgAcquire *Owner) {
962 bool value = pkgAcquireStatus::Pulse(Owner);
963
964 double percent(
965 double(CurrentBytes + CurrentItems) /
966 double(TotalBytes + TotalItems)
967 );
968
969 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
970 [NSNumber numberWithDouble:percent], @"Percent",
971
972 [NSNumber numberWithDouble:CurrentBytes], @"Current",
973 [NSNumber numberWithDouble:TotalBytes], @"Total",
974 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
975 nil] waitUntilDone:YES];
976
977 if (value && ![delegate_ isProgressCancelled])
978 return true;
979 else {
980 cancelled_ = true;
981 return false;
982 }
983 }
984
985 _finline bool WasCancelled() const {
986 return cancelled_;
987 }
988
989 virtual void Start() {
990 pkgAcquireStatus::Start();
991 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
992 }
993
994 virtual void Stop() {
995 pkgAcquireStatus::Stop();
996 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
997 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
998 }
999 };
1000 /* }}} */
1001 /* Database Interface {{{ */
1002 typedef std::map< unsigned long, _H<Source> > SourceMap;
1003
1004 @interface Database : NSObject {
1005 NSZone *zone_;
1006 apr_pool_t *pool_;
1007
1008 unsigned era_;
1009
1010 pkgCacheFile cache_;
1011 pkgDepCache::Policy *policy_;
1012 pkgRecords *records_;
1013 pkgProblemResolver *resolver_;
1014 pkgAcquire *fetcher_;
1015 FileFd *lock_;
1016 SPtr<pkgPackageManager> manager_;
1017 pkgSourceList *list_;
1018
1019 SourceMap sourceMap_;
1020 _H<NSMutableArray> sourceList_;
1021
1022 CFMutableArrayRef packages_;
1023
1024 _transient NSObject<DatabaseDelegate> *delegate_;
1025 _transient NSObject<ProgressDelegate> *progress_;
1026
1027 Status status_;
1028
1029 int cydiafd_;
1030 int statusfd_;
1031 FILE *input_;
1032
1033 std::map<const char *, _H<NSString> > sections_;
1034 }
1035
1036 + (Database *) sharedInstance;
1037 - (unsigned) era;
1038
1039 - (void) _readCydia:(NSNumber *)fd;
1040 - (void) _readStatus:(NSNumber *)fd;
1041 - (void) _readOutput:(NSNumber *)fd;
1042
1043 - (FILE *) input;
1044
1045 - (Package *) packageWithName:(NSString *)name;
1046
1047 - (pkgCacheFile &) cache;
1048 - (pkgDepCache::Policy *) policy;
1049 - (pkgRecords *) records;
1050 - (pkgProblemResolver *) resolver;
1051 - (pkgAcquire &) fetcher;
1052 - (pkgSourceList &) list;
1053 - (NSArray *) packages;
1054 - (NSArray *) sources;
1055 - (Source *) sourceWithKey:(NSString *)key;
1056 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1057
1058 - (void) configure;
1059 - (bool) prepare;
1060 - (void) perform;
1061 - (bool) upgrade;
1062 - (void) update;
1063
1064 - (void) updateWithStatus:(Status &)status;
1065
1066 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1067
1068 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1069 - (NSObject<ProgressDelegate> *) progressDelegate;
1070
1071 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1072
1073 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1074
1075 @end
1076 /* }}} */
1077 /* ProgressEvent Implementation {{{ */
1078 @implementation CydiaProgressEvent
1079
1080 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1081 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1082 }
1083
1084 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1085 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1086 [event setPackage:package];
1087 return event;
1088 }
1089
1090 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1091 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1092
1093 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1094 NSArray *fields([description componentsSeparatedByString:@" "]);
1095 [event setItem:fields];
1096
1097 if ([fields count] > 3) {
1098 [event setPackage:[fields objectAtIndex:2]];
1099 [event setVersion:[fields objectAtIndex:3]];
1100 }
1101
1102 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1103
1104 return event;
1105 }
1106
1107 + (NSArray *) _attributeKeys {
1108 return [NSArray arrayWithObjects:
1109 @"item",
1110 @"message",
1111 @"package",
1112 @"type",
1113 @"url",
1114 @"version",
1115 nil];
1116 }
1117
1118 - (NSArray *) attributeKeys {
1119 return [[self class] _attributeKeys];
1120 }
1121
1122 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1123 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1124 }
1125
1126 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1127 if ((self = [super init]) != nil) {
1128 message_ = message;
1129 type_ = type;
1130 } return self;
1131 }
1132
1133 - (NSString *) message {
1134 return message_;
1135 }
1136
1137 - (NSString *) type {
1138 return type_;
1139 }
1140
1141 - (NSArray *) item {
1142 return (id) item_ ?: [NSNull null];
1143 }
1144
1145 - (void) setItem:(NSArray *)item {
1146 item_ = item;
1147 }
1148
1149 - (NSString *) package {
1150 return (id) package_ ?: [NSNull null];
1151 }
1152
1153 - (void) setPackage:(NSString *)package {
1154 package_ = package;
1155 }
1156
1157 - (NSString *) url {
1158 return (id) url_ ?: [NSNull null];
1159 }
1160
1161 - (void) setURL:(NSString *)url {
1162 url_ = url;
1163 }
1164
1165 - (void) setVersion:(NSString *)version {
1166 version_ = version;
1167 }
1168
1169 - (NSString *) version {
1170 return (id) version_ ?: [NSNull null];
1171 }
1172
1173 - (NSString *) compound:(NSString *)value {
1174 if (value != nil) {
1175 NSString *mode(nil); {
1176 NSString *type([self type]);
1177 if ([type isEqualToString:kCydiaProgressEventTypeError])
1178 mode = UCLocalize("ERROR");
1179 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1180 mode = UCLocalize("WARNING");
1181 }
1182
1183 if (mode != nil)
1184 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1185 }
1186
1187 return value;
1188 }
1189
1190 - (NSString *) compoundMessage {
1191 return [self compound:[self message]];
1192 }
1193
1194 - (NSString *) compoundTitle {
1195 NSString *title;
1196
1197 if (package_ == nil)
1198 title = nil;
1199 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1200 title = [package name];
1201 else
1202 title = package_;
1203
1204 return [self compound:title];
1205 }
1206
1207 @end
1208 /* }}} */
1209
1210 // Cytore Definitions {{{
1211 struct PackageValue :
1212 Cytore::Block
1213 {
1214 Cytore::Offset<PackageValue> next_;
1215
1216 uint32_t index_ : 23;
1217 uint32_t subscribed_ : 1;
1218 uint32_t : 8;
1219
1220 int32_t first_;
1221 int32_t last_;
1222
1223 uint16_t vhash_;
1224 uint16_t nhash_;
1225
1226 char version_[8];
1227 char name_[];
1228 };
1229
1230 struct MetaValue :
1231 Cytore::Block
1232 {
1233 uint32_t active_;
1234 Cytore::Offset<PackageValue> packages_[1 << 16];
1235 };
1236
1237 static Cytore::File<MetaValue> MetaFile_;
1238 // }}}
1239 // Cytore Helper Functions {{{
1240 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1241 SplitHash nhash = { hashlittle(name, length) };
1242
1243 PackageValue *metadata;
1244
1245 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1246 offset: if (offset->IsNull()) {
1247 *offset = MetaFile_.New<PackageValue>(length + 1);
1248 metadata = &MetaFile_.Get(*offset);
1249
1250 if (metadata == NULL) {
1251 if (fail != NULL)
1252 *fail = true;
1253
1254 metadata = new PackageValue();
1255 memset(metadata, 0, sizeof(*metadata));
1256 }
1257
1258 memcpy(metadata->name_, name, length + 1);
1259 metadata->nhash_ = nhash.u16[1];
1260 } else {
1261 metadata = &MetaFile_.Get(*offset);
1262
1263 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1264 offset = &metadata->next_;
1265 goto offset;
1266 }
1267 }
1268
1269 return metadata;
1270 }
1271
1272 static void PackageImport(const void *key, const void *value, void *context) {
1273 bool &fail(*reinterpret_cast<bool *>(context));
1274
1275 char buffer[1024];
1276 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1277 NSLog(@"failed to import package %@", key);
1278 return;
1279 }
1280
1281 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1282 NSDictionary *package((NSDictionary *) value);
1283
1284 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1285 if ([subscribed boolValue] && !metadata->subscribed_)
1286 metadata->subscribed_ = true;
1287
1288 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1289 time_t time([date timeIntervalSince1970]);
1290 if (metadata->first_ > time || metadata->first_ == 0)
1291 metadata->first_ = time;
1292 }
1293
1294 NSDate *date([package objectForKey:@"LastSeen"]);
1295 NSString *version([package objectForKey:@"LastVersion"]);
1296
1297 if (date != nil && version != nil) {
1298 time_t time([date timeIntervalSince1970]);
1299 if (metadata->last_ < time || metadata->last_ == 0)
1300 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1301 size_t length(strlen(buffer));
1302 uint16_t vhash(hashlittle(buffer, length));
1303
1304 size_t capped(std::min<size_t>(8, length));
1305 char *latest(buffer + length - capped);
1306
1307 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1308 metadata->vhash_ = vhash;
1309
1310 metadata->last_ = time;
1311 }
1312 }
1313 }
1314 // }}}
1315
1316 /* Source Class {{{ */
1317 @interface Source : NSObject {
1318 unsigned era_;
1319 Database *database_;
1320 metaIndex *index_;
1321
1322 CYString depiction_;
1323 CYString description_;
1324 CYString label_;
1325 CYString origin_;
1326 CYString support_;
1327
1328 CYString uri_;
1329 CYString distribution_;
1330 CYString type_;
1331 CYString base_;
1332 CYString version_;
1333
1334 _H<NSString> host_;
1335 _H<NSString> authority_;
1336
1337 CYString defaultIcon_;
1338
1339 _H<NSMutableDictionary> record_;
1340 BOOL trusted_;
1341 }
1342
1343 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1344
1345 - (NSComparisonResult) compareByName:(Source *)source;
1346
1347 - (NSString *) depictionForPackage:(NSString *)package;
1348 - (NSString *) supportForPackage:(NSString *)package;
1349
1350 - (metaIndex *) metaIndex;
1351 - (NSDictionary *) record;
1352 - (BOOL) trusted;
1353
1354 - (NSString *) rooturi;
1355 - (NSString *) distribution;
1356 - (NSString *) type;
1357
1358 - (NSString *) key;
1359 - (NSString *) host;
1360
1361 - (NSString *) name;
1362 - (NSString *) shortDescription;
1363 - (NSString *) label;
1364 - (NSString *) origin;
1365 - (NSString *) version;
1366
1367 - (NSString *) defaultIcon;
1368 - (NSURL *) iconURL;
1369
1370 @end
1371
1372 @implementation Source
1373
1374 - (void) _clear {
1375 uri_.clear();
1376 distribution_.clear();
1377 type_.clear();
1378
1379 base_.clear();
1380
1381 description_.clear();
1382 label_.clear();
1383 origin_.clear();
1384 depiction_.clear();
1385 support_.clear();
1386 version_.clear();
1387 defaultIcon_.clear();
1388
1389 record_ = nil;
1390 host_ = nil;
1391 authority_ = nil;
1392 }
1393
1394 + (NSString *) webScriptNameForSelector:(SEL)selector {
1395 if (false);
1396 else if (selector == @selector(addSection:))
1397 return @"addSection";
1398 else if (selector == @selector(getField:))
1399 return @"getField";
1400 else if (selector == @selector(removeSection:))
1401 return @"removeSection";
1402 else if (selector == @selector(remove))
1403 return @"remove";
1404 else
1405 return nil;
1406 }
1407
1408 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1409 return [self webScriptNameForSelector:selector] == nil;
1410 }
1411
1412 + (NSArray *) _attributeKeys {
1413 return [NSArray arrayWithObjects:
1414 @"baseuri",
1415 @"distribution",
1416 @"host",
1417 @"key",
1418 @"iconuri",
1419 @"label",
1420 @"name",
1421 @"origin",
1422 @"rooturi",
1423 @"sections",
1424 @"shortDescription",
1425 @"trusted",
1426 @"type",
1427 @"version",
1428 nil];
1429 }
1430
1431 - (NSArray *) attributeKeys {
1432 return [[self class] _attributeKeys];
1433 }
1434
1435 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1436 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1437 }
1438
1439 - (metaIndex *) metaIndex {
1440 return index_;
1441 }
1442
1443 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1444 [self _clear];
1445
1446 trusted_ = index->IsTrusted();
1447
1448 uri_.set(pool, index->GetURI());
1449 distribution_.set(pool, index->GetDist());
1450 type_.set(pool, index->GetType());
1451
1452 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1453 if (dindex != NULL) {
1454 base_.set(pool, dindex->MetaIndexURI(""));
1455
1456 FileFd fd;
1457 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1458 _error->Discard();
1459 else {
1460 pkgTagFile tags(&fd);
1461
1462 pkgTagSection section;
1463 tags.Step(section);
1464
1465 struct {
1466 const char *name_;
1467 CYString *value_;
1468 } names[] = {
1469 {"default-icon", &defaultIcon_},
1470 {"depiction", &depiction_},
1471 {"description", &description_},
1472 {"label", &label_},
1473 {"origin", &origin_},
1474 {"support", &support_},
1475 {"version", &version_},
1476 };
1477
1478 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1479 const char *start, *end;
1480
1481 if (section.Find(names[i].name_, start, end)) {
1482 CYString &value(*names[i].value_);
1483 value.set(pool, start, end - start);
1484 }
1485 }
1486 }
1487 }
1488
1489 record_ = [Sources_ objectForKey:[self key]];
1490
1491 NSURL *url([NSURL URLWithString:uri_]);
1492
1493 host_ = [url host];
1494 if (host_ != nil)
1495 host_ = [host_ lowercaseString];
1496
1497 if (host_ != nil)
1498 authority_ = host_;
1499 else
1500 authority_ = [url path];
1501 }
1502
1503 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1504 if ((self = [super init]) != nil) {
1505 era_ = [database era];
1506 database_ = database;
1507 index_ = index;
1508
1509 [self setMetaIndex:index inPool:pool];
1510 } return self;
1511 }
1512
1513 - (NSString *) getField:(NSString *)name {
1514 @synchronized (database_) {
1515 if ([database_ era] != era_ || index_ == NULL)
1516 return nil;
1517
1518 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1519 if (dindex == NULL)
1520 return nil;
1521
1522 FileFd fd;
1523 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1524 _error->Discard();
1525 return nil;
1526 }
1527
1528 pkgTagFile tags(&fd);
1529
1530 pkgTagSection section;
1531 tags.Step(section);
1532
1533 const char *start, *end;
1534 if (!section.Find([name UTF8String], start, end))
1535 return (NSString *) [NSNull null];
1536
1537 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1538 } }
1539
1540 - (NSComparisonResult) compareByName:(Source *)source {
1541 NSString *lhs = [self name];
1542 NSString *rhs = [source name];
1543
1544 if ([lhs length] != 0 && [rhs length] != 0) {
1545 unichar lhc = [lhs characterAtIndex:0];
1546 unichar rhc = [rhs characterAtIndex:0];
1547
1548 if (isalpha(lhc) && !isalpha(rhc))
1549 return NSOrderedAscending;
1550 else if (!isalpha(lhc) && isalpha(rhc))
1551 return NSOrderedDescending;
1552 }
1553
1554 return [lhs compare:rhs options:LaxCompareOptions_];
1555 }
1556
1557 - (NSString *) depictionForPackage:(NSString *)package {
1558 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1559 }
1560
1561 - (NSString *) supportForPackage:(NSString *)package {
1562 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1563 }
1564
1565 - (NSArray *) sections {
1566 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1567 }
1568
1569 - (void) _addSection:(NSString *)section {
1570 if (record_ == nil)
1571 return;
1572 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1573 if (![sections containsObject:section]) {
1574 [sections addObject:section];
1575 Changed_ = true;
1576 }
1577 } else {
1578 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1579 Changed_ = true;
1580 }
1581 }
1582
1583 - (bool) addSection:(NSString *)section {
1584 if (record_ == nil)
1585 return false;
1586
1587 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1588 return true;
1589 }
1590
1591 - (void) _removeSection:(NSString *)section {
1592 if (record_ == nil)
1593 return;
1594
1595 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1596 if ([sections containsObject:section]) {
1597 [sections removeObject:section];
1598 Changed_ = true;
1599 }
1600 }
1601
1602 - (bool) removeSection:(NSString *)section {
1603 if (record_ == nil)
1604 return false;
1605
1606 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1607 return true;
1608 }
1609
1610 - (void) _remove {
1611 [Sources_ removeObjectForKey:[self key]];
1612 Changed_ = true;
1613 }
1614
1615 - (bool) remove {
1616 bool value(record_ != nil);
1617 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1618 return value;
1619 }
1620
1621 - (NSDictionary *) record {
1622 return record_;
1623 }
1624
1625 - (BOOL) trusted {
1626 return trusted_;
1627 }
1628
1629 - (NSString *) rooturi {
1630 return uri_;
1631 }
1632
1633 - (NSString *) distribution {
1634 return distribution_;
1635 }
1636
1637 - (NSString *) type {
1638 return type_;
1639 }
1640
1641 - (NSString *) baseuri {
1642 return base_.empty() ? nil : (id) base_;
1643 }
1644
1645 - (NSString *) iconuri {
1646 if (NSString *base = [self baseuri])
1647 return [base stringByAppendingString:@"CydiaIcon.png"];
1648
1649 return nil;
1650 }
1651
1652 - (NSURL *) iconURL {
1653 if (NSString *uri = [self iconuri])
1654 return [NSURL URLWithString:uri];
1655 return nil;
1656 }
1657
1658 - (NSString *) key {
1659 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1660 }
1661
1662 - (NSString *) host {
1663 return host_;
1664 }
1665
1666 - (NSString *) name {
1667 return origin_.empty() ? (id) authority_ : origin_;
1668 }
1669
1670 - (NSString *) shortDescription {
1671 return description_;
1672 }
1673
1674 - (NSString *) label {
1675 return label_.empty() ? (id) authority_ : label_;
1676 }
1677
1678 - (NSString *) origin {
1679 return origin_;
1680 }
1681
1682 - (NSString *) version {
1683 return version_;
1684 }
1685
1686 - (NSString *) defaultIcon {
1687 return defaultIcon_;
1688 }
1689
1690 @end
1691 /* }}} */
1692 /* CydiaOperation Class {{{ */
1693 @interface CydiaOperation : NSObject {
1694 _H<NSString> operator_;
1695 _H<NSString> value_;
1696 }
1697
1698 - (NSString *) operator;
1699 - (NSString *) value;
1700
1701 @end
1702
1703 @implementation CydiaOperation
1704
1705 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1706 if ((self = [super init]) != nil) {
1707 operator_ = [NSString stringWithUTF8String:_operator];
1708 value_ = [NSString stringWithUTF8String:value];
1709 } return self;
1710 }
1711
1712 + (NSArray *) _attributeKeys {
1713 return [NSArray arrayWithObjects:
1714 @"operator",
1715 @"value",
1716 nil];
1717 }
1718
1719 - (NSArray *) attributeKeys {
1720 return [[self class] _attributeKeys];
1721 }
1722
1723 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1724 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1725 }
1726
1727 - (NSString *) operator {
1728 return operator_;
1729 }
1730
1731 - (NSString *) value {
1732 return value_;
1733 }
1734
1735 @end
1736 /* }}} */
1737 /* CydiaClause Class {{{ */
1738 @interface CydiaClause : NSObject {
1739 _H<NSString> package_;
1740 _H<CydiaOperation> version_;
1741 }
1742
1743 - (NSString *) package;
1744 - (CydiaOperation *) version;
1745
1746 @end
1747
1748 @implementation CydiaClause
1749
1750 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1751 if ((self = [super init]) != nil) {
1752 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1753
1754 if (const char *version = dep.TargetVer())
1755 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1756 else
1757 version_ = (id) [NSNull null];
1758 } return self;
1759 }
1760
1761 + (NSArray *) _attributeKeys {
1762 return [NSArray arrayWithObjects:
1763 @"package",
1764 @"version",
1765 nil];
1766 }
1767
1768 - (NSArray *) attributeKeys {
1769 return [[self class] _attributeKeys];
1770 }
1771
1772 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1773 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1774 }
1775
1776 - (NSString *) package {
1777 return package_;
1778 }
1779
1780 - (CydiaOperation *) version {
1781 return version_;
1782 }
1783
1784 @end
1785 /* }}} */
1786 /* CydiaRelation Class {{{ */
1787 @interface CydiaRelation : NSObject {
1788 _H<NSString> relationship_;
1789 _H<NSMutableArray> clauses_;
1790 }
1791
1792 - (NSString *) relationship;
1793 - (NSArray *) clauses;
1794
1795 @end
1796
1797 @implementation CydiaRelation
1798
1799 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1800 if ((self = [super init]) != nil) {
1801 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1802 clauses_ = [NSMutableArray arrayWithCapacity:8];
1803
1804 pkgCache::DepIterator start;
1805 pkgCache::DepIterator end;
1806 dep.GlobOr(start, end); // ++dep
1807
1808 _forever {
1809 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1810
1811 // yes, seriously. (wtf?)
1812 if (start == end)
1813 break;
1814 ++start;
1815 }
1816 } return self;
1817 }
1818
1819 + (NSArray *) _attributeKeys {
1820 return [NSArray arrayWithObjects:
1821 @"clauses",
1822 @"relationship",
1823 nil];
1824 }
1825
1826 - (NSArray *) attributeKeys {
1827 return [[self class] _attributeKeys];
1828 }
1829
1830 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1831 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1832 }
1833
1834 - (NSString *) relationship {
1835 return relationship_;
1836 }
1837
1838 - (NSArray *) clauses {
1839 return clauses_;
1840 }
1841
1842 - (void) addClause:(CydiaClause *)clause {
1843 [clauses_ addObject:clause];
1844 }
1845
1846 @end
1847 /* }}} */
1848 /* Package Class {{{ */
1849 struct ParsedPackage {
1850 CYString md5sum_;
1851 CYString tagline_;
1852
1853 CYString architecture_;
1854 CYString icon_;
1855
1856 CYString depiction_;
1857 CYString homepage_;
1858
1859 CYString sponsor_;
1860 CYString author_;
1861
1862 CYString bugs_;
1863 CYString support_;
1864 };
1865
1866 @interface Package : NSObject {
1867 uint32_t era_ : 25;
1868 uint32_t role_ : 3;
1869 uint32_t essential_ : 1;
1870 uint32_t obsolete_ : 1;
1871 uint32_t ignored_ : 1;
1872 uint32_t pooled_ : 1;
1873
1874 apr_pool_t *pool_;
1875
1876 uint32_t rank_;
1877
1878 _transient Database *database_;
1879
1880 pkgCache::VerIterator version_;
1881 pkgCache::PkgIterator iterator_;
1882 pkgCache::VerFileIterator file_;
1883
1884 CYString id_;
1885 CYString name_;
1886
1887 CYString latest_;
1888 CYString installed_;
1889
1890 const char *section_;
1891 _transient NSString *section$_;
1892
1893 _H<Source> source_;
1894
1895 PackageValue *metadata_;
1896 ParsedPackage *parsed_;
1897
1898 _H<NSMutableArray> tags_;
1899 }
1900
1901 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1902 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1903
1904 - (pkgCache::PkgIterator) iterator;
1905 - (void) parse;
1906
1907 - (NSString *) section;
1908 - (NSString *) simpleSection;
1909
1910 - (NSString *) longSection;
1911 - (NSString *) shortSection;
1912
1913 - (NSString *) uri;
1914
1915 - (MIMEAddress *) maintainer;
1916 - (size_t) size;
1917 - (NSString *) longDescription;
1918 - (NSString *) shortDescription;
1919 - (unichar) index;
1920
1921 - (PackageValue *) metadata;
1922 - (time_t) seen;
1923
1924 - (bool) subscribed;
1925 - (bool) setSubscribed:(bool)subscribed;
1926
1927 - (BOOL) ignored;
1928
1929 - (NSString *) latest;
1930 - (NSString *) installed;
1931 - (BOOL) uninstalled;
1932
1933 - (BOOL) valid;
1934 - (BOOL) upgradableAndEssential:(BOOL)essential;
1935 - (BOOL) essential;
1936 - (BOOL) broken;
1937 - (BOOL) unfiltered;
1938 - (BOOL) visible;
1939
1940 - (BOOL) half;
1941 - (BOOL) halfConfigured;
1942 - (BOOL) halfInstalled;
1943 - (BOOL) hasMode;
1944 - (NSString *) mode;
1945
1946 - (NSString *) id;
1947 - (NSString *) name;
1948 - (UIImage *) icon;
1949 - (NSString *) homepage;
1950 - (NSString *) depiction;
1951 - (MIMEAddress *) author;
1952
1953 - (NSString *) support;
1954
1955 - (NSArray *) files;
1956 - (NSArray *) warnings;
1957 - (NSArray *) applications;
1958
1959 - (Source *) source;
1960
1961 - (uint32_t) rank;
1962 - (BOOL) matches:(NSArray *)query;
1963
1964 - (bool) hasSupportingRole;
1965 - (BOOL) hasTag:(NSString *)tag;
1966 - (NSString *) primaryPurpose;
1967 - (NSArray *) purposes;
1968 - (bool) isCommercial;
1969
1970 - (void) setIndex:(size_t)index;
1971
1972 - (CYString &) cyname;
1973
1974 - (uint32_t) compareBySection:(NSArray *)sections;
1975
1976 - (void) install;
1977 - (void) remove;
1978
1979 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1980 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1981 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1982 - (bool) isVisibleInSection:(NSString *)section;
1983 - (bool) isVisibleInSource:(Source *)source;
1984
1985 @end
1986
1987 uint32_t PackageChangesRadix(Package *self, void *) {
1988 union {
1989 uint32_t key;
1990
1991 struct {
1992 uint32_t timestamp : 30;
1993 uint32_t ignored : 1;
1994 uint32_t upgradable : 1;
1995 } bits;
1996 } value;
1997
1998 bool upgradable([self upgradableAndEssential:YES]);
1999 value.bits.upgradable = upgradable ? 1 : 0;
2000
2001 if (upgradable) {
2002 value.bits.timestamp = 0;
2003 value.bits.ignored = [self ignored] ? 0 : 1;
2004 value.bits.upgradable = 1;
2005 } else {
2006 value.bits.timestamp = [self seen] >> 2;
2007 value.bits.ignored = 0;
2008 value.bits.upgradable = 0;
2009 }
2010
2011 return _not(uint32_t) - value.key;
2012 }
2013
2014 uint32_t PackagePrefixRadix(Package *self, void *context) {
2015 size_t offset(reinterpret_cast<size_t>(context));
2016 CYString &name([self cyname]);
2017
2018 size_t size(name.size());
2019 if (size == 0)
2020 return 0;
2021 char *text(name.data());
2022
2023 size_t zeros;
2024 if (!isdigit(text[0]))
2025 zeros = 0;
2026 else {
2027 size_t digits(1);
2028 while (size != digits && isdigit(text[digits]))
2029 if (++digits == 4)
2030 break;
2031 zeros = 4 - digits;
2032 }
2033
2034 uint8_t data[4];
2035
2036 if (offset == 0 && zeros != 0) {
2037 memset(data, '0', zeros);
2038 memcpy(data + zeros, text, 4 - zeros);
2039 } else {
2040 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2041 if (size <= offset - zeros)
2042 return 0;
2043
2044 text += offset - zeros;
2045 size -= offset - zeros;
2046
2047 if (size >= 4)
2048 memcpy(data, text, 4);
2049 else {
2050 memcpy(data, text, size);
2051 memset(data + size, 0, 4 - size);
2052 }
2053
2054 for (size_t i(0); i != 4; ++i)
2055 if (isalpha(data[i]))
2056 data[i] |= 0x20;
2057 }
2058
2059 if (offset == 0)
2060 if (data[0] == '@')
2061 data[0] = 0x7f;
2062 else
2063 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2064
2065 /* XXX: ntohl may be more honest */
2066 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2067 }
2068
2069 CYString &(*PackageName)(Package *self, SEL sel);
2070
2071 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2072 _profile(PackageNameCompare)
2073 CYString &lhi(PackageName(lhs, @selector(cyname)));
2074 CYString &rhi(PackageName(rhs, @selector(cyname)));
2075 CFStringRef lhn(lhi), rhn(rhi);
2076
2077 if (lhn == NULL)
2078 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2079 else if (rhn == NULL)
2080 return NSOrderedDescending;
2081
2082 _profile(PackageNameCompare$NumbersLast)
2083 if (!lhi.empty() && !rhi.empty()) {
2084 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2085 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2086 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2087 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2088 return lha ? NSOrderedAscending : NSOrderedDescending;
2089 }
2090 _end
2091
2092 CFIndex length = CFStringGetLength(lhn);
2093
2094 _profile(PackageNameCompare$Compare)
2095 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2096 _end
2097 _end
2098 }
2099
2100 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2101 return PackageNameCompare(*lhs, *rhs, context);
2102 }
2103
2104 struct PackageNameOrdering :
2105 std::binary_function<Package *, Package *, bool>
2106 {
2107 _finline bool operator ()(Package *lhs, Package *rhs) const {
2108 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2109 }
2110 };
2111
2112 @implementation Package
2113
2114 - (NSString *) description {
2115 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2116 }
2117
2118 - (void) dealloc {
2119 if (!pooled_)
2120 apr_pool_destroy(pool_);
2121 if (parsed_ != NULL)
2122 delete parsed_;
2123 [super dealloc];
2124 }
2125
2126 + (NSString *) webScriptNameForSelector:(SEL)selector {
2127 if (false);
2128 else if (selector == @selector(clear))
2129 return @"clear";
2130 else if (selector == @selector(getField:))
2131 return @"getField";
2132 else if (selector == @selector(hasTag:))
2133 return @"hasTag";
2134 else if (selector == @selector(install))
2135 return @"install";
2136 else if (selector == @selector(remove))
2137 return @"remove";
2138 else
2139 return nil;
2140 }
2141
2142 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2143 return [self webScriptNameForSelector:selector] == nil;
2144 }
2145
2146 + (NSArray *) _attributeKeys {
2147 return [NSArray arrayWithObjects:
2148 @"applications",
2149 @"architecture",
2150 @"author",
2151 @"depiction",
2152 @"essential",
2153 @"homepage",
2154 @"icon",
2155 @"id",
2156 @"installed",
2157 @"latest",
2158 @"longDescription",
2159 @"longSection",
2160 @"maintainer",
2161 @"md5sum",
2162 @"mode",
2163 @"name",
2164 @"purposes",
2165 @"relations",
2166 @"section",
2167 @"selection",
2168 @"shortDescription",
2169 @"shortSection",
2170 @"simpleSection",
2171 @"size",
2172 @"source",
2173 @"sponsor",
2174 @"state",
2175 @"support",
2176 @"tags",
2177 @"warnings",
2178 nil];
2179 }
2180
2181 - (NSArray *) attributeKeys {
2182 return [[self class] _attributeKeys];
2183 }
2184
2185 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2186 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2187 }
2188
2189 - (NSArray *) relations {
2190 @synchronized (database_) {
2191 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2192 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2193 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2194 return relations;
2195 } }
2196
2197 - (NSString *) architecture {
2198 [self parse];
2199 @synchronized (database_) {
2200 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2201 } }
2202
2203 - (NSString *) getField:(NSString *)name {
2204 @synchronized (database_) {
2205 if ([database_ era] != era_ || file_.end())
2206 return nil;
2207
2208 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2209
2210 const char *start, *end;
2211 if (!parser.Find([name UTF8String], start, end))
2212 return (NSString *) [NSNull null];
2213
2214 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2215 } }
2216
2217 - (void) parse {
2218 if (parsed_ != NULL)
2219 return;
2220 @synchronized (database_) {
2221 if ([database_ era] != era_ || file_.end())
2222 return;
2223
2224 ParsedPackage *parsed(new ParsedPackage);
2225 parsed_ = parsed;
2226
2227 _profile(Package$parse)
2228 pkgRecords::Parser *parser;
2229
2230 _profile(Package$parse$Lookup)
2231 parser = &[database_ records]->Lookup(file_);
2232 _end
2233
2234 CYString website;
2235
2236 _profile(Package$parse$Find)
2237 struct {
2238 const char *name_;
2239 CYString *value_;
2240 } names[] = {
2241 {"architecture", &parsed->architecture_},
2242 {"icon", &parsed->icon_},
2243 {"depiction", &parsed->depiction_},
2244 {"homepage", &parsed->homepage_},
2245 {"website", &website},
2246 {"bugs", &parsed->bugs_},
2247 {"support", &parsed->support_},
2248 {"sponsor", &parsed->sponsor_},
2249 {"author", &parsed->author_},
2250 {"md5sum", &parsed->md5sum_},
2251 };
2252
2253 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2254 const char *start, *end;
2255
2256 if (parser->Find(names[i].name_, start, end)) {
2257 CYString &value(*names[i].value_);
2258 _profile(Package$parse$Value)
2259 value.set(pool_, start, end - start);
2260 _end
2261 }
2262 }
2263 _end
2264
2265 _profile(Package$parse$Tagline)
2266 const char *start, *end;
2267 if (parser->ShortDesc(start, end)) {
2268 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2269 if (stop == NULL)
2270 stop = end;
2271 while (stop != start && stop[-1] == '\r')
2272 --stop;
2273 parsed->tagline_.set(pool_, start, stop - start);
2274 }
2275 _end
2276
2277 _profile(Package$parse$Retain)
2278 if (parsed->homepage_.empty())
2279 parsed->homepage_ = website;
2280 if (parsed->homepage_ == parsed->depiction_)
2281 parsed->homepage_.clear();
2282 _end
2283 _end
2284 } }
2285
2286 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2287 if ((self = [super init]) != nil) {
2288 _profile(Package$initWithVersion)
2289 if (pool == NULL)
2290 apr_pool_create(&pool_, NULL);
2291 else {
2292 pool_ = pool;
2293 pooled_ = true;
2294 }
2295
2296 database_ = database;
2297 era_ = [database era];
2298
2299 version_ = version;
2300
2301 pkgCache::PkgIterator iterator(version.ParentPkg());
2302 iterator_ = iterator;
2303
2304 _profile(Package$initWithVersion$Version)
2305 if (!version_.end())
2306 file_ = version_.FileList();
2307 else {
2308 pkgCache &cache([database_ cache]);
2309 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2310 }
2311 _end
2312
2313 _profile(Package$initWithVersion$Cache)
2314 name_.set(NULL, iterator.Display());
2315
2316 latest_.set(NULL, StripVersion_(version_.VerStr()));
2317
2318 pkgCache::VerIterator current(iterator.CurrentVer());
2319 if (!current.end())
2320 installed_.set(NULL, StripVersion_(current.VerStr()));
2321 _end
2322
2323 _profile(Package$initWithVersion$Tags)
2324 pkgCache::TagIterator tag(iterator.TagList());
2325 if (!tag.end()) {
2326 tags_ = [NSMutableArray arrayWithCapacity:8];
2327
2328 goto tag; for (; !tag.end(); ++tag) tag: {
2329 const char *name(tag.Name());
2330 NSString *string((NSString *) CYStringCreate(name));
2331 if (string == nil)
2332 continue;
2333
2334 [tags_ addObject:[string autorelease]];
2335
2336 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2337 if (strcmp(name + 6, "enduser") == 0)
2338 role_ = 1;
2339 else if (strcmp(name + 6, "hacker") == 0)
2340 role_ = 2;
2341 else if (strcmp(name + 6, "developer") == 0)
2342 role_ = 3;
2343 else if (strcmp(name + 6, "cydia") == 0)
2344 role_ = 7;
2345 else
2346 role_ = 4;
2347 }
2348
2349 if (strncmp(name, "cydia::", 7) == 0) {
2350 if (strcmp(name + 7, "essential") == 0)
2351 essential_ = true;
2352 else if (strcmp(name + 7, "obsolete") == 0)
2353 obsolete_ = true;
2354 }
2355 }
2356 }
2357 _end
2358
2359 _profile(Package$initWithVersion$Metadata)
2360 const char *mixed(iterator.Name());
2361 size_t size(strlen(mixed));
2362 char lower[size + 1];
2363
2364 for (size_t i(0); i != size; ++i)
2365 lower[i] = mixed[i] | 0x20;
2366 lower[size] = '\0';
2367
2368 PackageValue *metadata(PackageFind(lower, size));
2369 metadata_ = metadata;
2370
2371 id_.set(NULL, metadata->name_, size);
2372
2373 const char *latest(version_.VerStr());
2374 size_t length(strlen(latest));
2375
2376 uint16_t vhash(hashlittle(latest, length));
2377
2378 size_t capped(std::min<size_t>(8, length));
2379 latest = latest + length - capped;
2380
2381 if (metadata->first_ == 0)
2382 metadata->first_ = now_;
2383
2384 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2385 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2386 metadata->vhash_ = vhash;
2387 metadata->last_ = now_;
2388 } else if (metadata->last_ == 0)
2389 metadata->last_ = metadata->first_;
2390 _end
2391
2392 _profile(Package$initWithVersion$Section)
2393 section_ = version_.Section();
2394 _end
2395
2396 _profile(Package$initWithVersion$Flags)
2397 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2398 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2399 _end
2400 _end } return self;
2401 }
2402
2403 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2404 pkgCache::VerIterator version;
2405
2406 _profile(Package$packageWithIterator$GetCandidateVer)
2407 version = [database policy]->GetCandidateVer(iterator);
2408 _end
2409
2410 if (version.end())
2411 return nil;
2412
2413 Package *package;
2414
2415 _profile(Package$packageWithIterator$Allocate)
2416 package = [Package allocWithZone:zone];
2417 _end
2418
2419 _profile(Package$packageWithIterator$Initialize)
2420 package = [package
2421 initWithVersion:version
2422 withZone:zone
2423 inPool:pool
2424 database:database
2425 ];
2426 _end
2427
2428 _profile(Package$packageWithIterator$Autorelease)
2429 package = [package autorelease];
2430 _end
2431
2432 return package;
2433 }
2434
2435 - (pkgCache::PkgIterator) iterator {
2436 return iterator_;
2437 }
2438
2439 - (NSString *) section {
2440 if (section$_ == nil) {
2441 if (section_ == NULL)
2442 return nil;
2443
2444 _profile(Package$section$mappedSectionForPointer)
2445 section$_ = [database_ mappedSectionForPointer:section_];
2446 _end
2447 } return section$_;
2448 }
2449
2450 - (NSString *) simpleSection {
2451 if (NSString *section = [self section])
2452 return Simplify(section);
2453 else
2454 return nil;
2455 }
2456
2457 - (NSString *) longSection {
2458 return LocalizeSection([self section]);
2459 }
2460
2461 - (NSString *) shortSection {
2462 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2463 }
2464
2465 - (NSString *) uri {
2466 return nil;
2467 #if 0
2468 pkgIndexFile *index;
2469 pkgCache::PkgFileIterator file(file_.File());
2470 if (![database_ list].FindIndex(file, index))
2471 return nil;
2472 return [NSString stringWithUTF8String:iterator_->Path];
2473 //return [NSString stringWithUTF8String:file.Site()];
2474 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2475 #endif
2476 }
2477
2478 - (MIMEAddress *) maintainer {
2479 @synchronized (database_) {
2480 if ([database_ era] != era_ || file_.end())
2481 return nil;
2482
2483 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2484 const std::string &maintainer(parser->Maintainer());
2485 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2486 } }
2487
2488 - (NSString *) md5sum {
2489 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2490 }
2491
2492 - (size_t) size {
2493 @synchronized (database_) {
2494 if ([database_ era] != era_ || version_.end())
2495 return 0;
2496
2497 return version_->InstalledSize;
2498 } }
2499
2500 - (NSString *) longDescription {
2501 @synchronized (database_) {
2502 if ([database_ era] != era_ || file_.end())
2503 return nil;
2504
2505 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2506 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2507
2508 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2509 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2510 if ([lines count] < 2)
2511 return nil;
2512
2513 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2514 for (size_t i(1), e([lines count]); i != e; ++i) {
2515 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2516 [trimmed addObject:trim];
2517 }
2518
2519 return [trimmed componentsJoinedByString:@"\n"];
2520 } }
2521
2522 - (NSString *) shortDescription {
2523 if (parsed_ != NULL)
2524 return static_cast<NSString *>(parsed_->tagline_);
2525
2526 @synchronized (database_) {
2527 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2528
2529 const char *start, *end;
2530 if (!parser.ShortDesc(start, end))
2531 return nil;
2532
2533 if (end - start > 200)
2534 end = start + 200;
2535
2536 /*
2537 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2538 end = stop;
2539
2540 while (end != start && end[-1] == '\r')
2541 --end;
2542 */
2543
2544 return [(id) CYStringCreate(start, end - start) autorelease];
2545 } }
2546
2547 - (unichar) index {
2548 _profile(Package$index)
2549 CFStringRef name((CFStringRef) [self name]);
2550 if (CFStringGetLength(name) == 0)
2551 return '#';
2552 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2553 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2554 return '#';
2555 return toupper(character);
2556 _end
2557 }
2558
2559 - (PackageValue *) metadata {
2560 return metadata_;
2561 }
2562
2563 - (time_t) seen {
2564 PackageValue *metadata([self metadata]);
2565 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2566 }
2567
2568 - (bool) subscribed {
2569 return [self metadata]->subscribed_;
2570 }
2571
2572 - (bool) setSubscribed:(bool)subscribed {
2573 PackageValue *metadata([self metadata]);
2574 if (metadata->subscribed_ == subscribed)
2575 return false;
2576 metadata->subscribed_ = subscribed;
2577 return true;
2578 }
2579
2580 - (BOOL) ignored {
2581 return ignored_;
2582 }
2583
2584 - (NSString *) latest {
2585 return latest_;
2586 }
2587
2588 - (NSString *) installed {
2589 return installed_;
2590 }
2591
2592 - (BOOL) uninstalled {
2593 return installed_.empty();
2594 }
2595
2596 - (BOOL) valid {
2597 return !version_.end();
2598 }
2599
2600 - (BOOL) upgradableAndEssential:(BOOL)essential {
2601 _profile(Package$upgradableAndEssential)
2602 pkgCache::VerIterator current(iterator_.CurrentVer());
2603 if (current.end())
2604 return essential && essential_;
2605 else
2606 return !version_.end() && version_ != current;
2607 _end
2608 }
2609
2610 - (BOOL) essential {
2611 return essential_;
2612 }
2613
2614 - (BOOL) broken {
2615 return [database_ cache][iterator_].InstBroken();
2616 }
2617
2618 - (BOOL) unfiltered {
2619 _profile(Package$unfiltered$obsolete)
2620 if (_unlikely(obsolete_))
2621 return false;
2622 _end
2623
2624 _profile(Package$unfiltered$hasSupportingRole)
2625 if (_unlikely(![self hasSupportingRole]))
2626 return false;
2627 _end
2628
2629 return true;
2630 }
2631
2632 - (BOOL) visible {
2633 if (![self unfiltered])
2634 return false;
2635
2636 NSString *section;
2637
2638 _profile(Package$visible$section)
2639 section = [self section];
2640 _end
2641
2642 _profile(Package$visible$isSectionVisible)
2643 if (!isSectionVisible(section))
2644 return false;
2645 _end
2646
2647 return true;
2648 }
2649
2650 - (BOOL) half {
2651 unsigned char current(iterator_->CurrentState);
2652 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2653 }
2654
2655 - (BOOL) halfConfigured {
2656 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2657 }
2658
2659 - (BOOL) halfInstalled {
2660 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2661 }
2662
2663 - (BOOL) hasMode {
2664 @synchronized (database_) {
2665 if ([database_ era] != era_ || iterator_.end())
2666 return nil;
2667
2668 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2669 return state.Mode != pkgDepCache::ModeKeep;
2670 } }
2671
2672 - (NSString *) mode {
2673 @synchronized (database_) {
2674 if ([database_ era] != era_ || iterator_.end())
2675 return nil;
2676
2677 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2678
2679 switch (state.Mode) {
2680 case pkgDepCache::ModeDelete:
2681 if ((state.iFlags & pkgDepCache::Purge) != 0)
2682 return @"PURGE";
2683 else
2684 return @"REMOVE";
2685 case pkgDepCache::ModeKeep:
2686 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2687 return @"REINSTALL";
2688 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2689 return nil;*/
2690 else
2691 return nil;
2692 case pkgDepCache::ModeInstall:
2693 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2694 return @"REINSTALL";
2695 else*/ switch (state.Status) {
2696 case -1:
2697 return @"DOWNGRADE";
2698 case 0:
2699 return @"INSTALL";
2700 case 1:
2701 return @"UPGRADE";
2702 case 2:
2703 return @"NEW_INSTALL";
2704 _nodefault
2705 }
2706 _nodefault
2707 }
2708 } }
2709
2710 - (NSString *) id {
2711 return id_;
2712 }
2713
2714 - (NSString *) name {
2715 return name_.empty() ? id_ : name_;
2716 }
2717
2718 - (UIImage *) icon {
2719 NSString *section = [self simpleSection];
2720
2721 UIImage *icon(nil);
2722 if (parsed_ != NULL)
2723 if (NSString *href = parsed_->icon_)
2724 if ([href hasPrefix:@"file:///"])
2725 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2726 if (icon == nil) if (section != nil)
2727 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2728 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2729 if ([dicon hasPrefix:@"file:///"])
2730 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2731 if (icon == nil)
2732 icon = [UIImage applicationImageNamed:@"unknown.png"];
2733 return icon;
2734 }
2735
2736 - (NSString *) homepage {
2737 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2738 }
2739
2740 - (NSString *) depiction {
2741 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2742 }
2743
2744 - (MIMEAddress *) sponsor {
2745 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2746 }
2747
2748 - (MIMEAddress *) author {
2749 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2750 }
2751
2752 - (NSString *) support {
2753 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2754 }
2755
2756 - (NSArray *) files {
2757 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2758 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2759
2760 std::ifstream fin;
2761 fin.open([path UTF8String]);
2762 if (!fin.is_open())
2763 return nil;
2764
2765 std::string line;
2766 while (std::getline(fin, line))
2767 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2768
2769 return files;
2770 }
2771
2772 - (NSString *) state {
2773 @synchronized (database_) {
2774 if ([database_ era] != era_ || file_.end())
2775 return nil;
2776
2777 switch (iterator_->CurrentState) {
2778 case pkgCache::State::NotInstalled:
2779 return @"NotInstalled";
2780 case pkgCache::State::UnPacked:
2781 return @"UnPacked";
2782 case pkgCache::State::HalfConfigured:
2783 return @"HalfConfigured";
2784 case pkgCache::State::HalfInstalled:
2785 return @"HalfInstalled";
2786 case pkgCache::State::ConfigFiles:
2787 return @"ConfigFiles";
2788 case pkgCache::State::Installed:
2789 return @"Installed";
2790 case pkgCache::State::TriggersAwaited:
2791 return @"TriggersAwaited";
2792 case pkgCache::State::TriggersPending:
2793 return @"TriggersPending";
2794 }
2795
2796 return (NSString *) [NSNull null];
2797 } }
2798
2799 - (NSString *) selection {
2800 @synchronized (database_) {
2801 if ([database_ era] != era_ || file_.end())
2802 return nil;
2803
2804 switch (iterator_->SelectedState) {
2805 case pkgCache::State::Unknown:
2806 return @"Unknown";
2807 case pkgCache::State::Install:
2808 return @"Install";
2809 case pkgCache::State::Hold:
2810 return @"Hold";
2811 case pkgCache::State::DeInstall:
2812 return @"DeInstall";
2813 case pkgCache::State::Purge:
2814 return @"Purge";
2815 }
2816
2817 return (NSString *) [NSNull null];
2818 } }
2819
2820 - (NSArray *) warnings {
2821 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2822 const char *name(iterator_.Name());
2823
2824 size_t length(strlen(name));
2825 if (length < 2) invalid:
2826 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2827 else for (size_t i(0); i != length; ++i)
2828 if (
2829 /* XXX: technically this is not allowed */
2830 (name[i] < 'A' || name[i] > 'Z') &&
2831 (name[i] < 'a' || name[i] > 'z') &&
2832 (name[i] < '0' || name[i] > '9') &&
2833 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2834 ) goto invalid;
2835
2836 if (strcmp(name, "cydia") != 0) {
2837 bool cydia = false;
2838 bool user = false;
2839 bool _private = false;
2840 bool stash = false;
2841
2842 bool repository = [[self section] isEqualToString:@"Repositories"];
2843
2844 if (NSArray *files = [self files])
2845 for (NSString *file in files)
2846 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2847 cydia = true;
2848 else if (!user && [file isEqualToString:@"/User"])
2849 user = true;
2850 else if (!_private && [file isEqualToString:@"/private"])
2851 _private = true;
2852 else if (!stash && [file isEqualToString:@"/var/stash"])
2853 stash = true;
2854
2855 /* XXX: this is not sensitive enough. only some folders are valid. */
2856 if (cydia && !repository)
2857 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2858 if (user)
2859 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2860 if (_private)
2861 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2862 if (stash)
2863 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2864 }
2865
2866 return [warnings count] == 0 ? nil : warnings;
2867 }
2868
2869 - (NSArray *) applications {
2870 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2871
2872 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2873
2874 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2875 if (NSArray *files = [self files])
2876 for (NSString *file in files)
2877 if (application_r(file)) {
2878 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2879 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2880 if ([id isEqualToString:me])
2881 continue;
2882
2883 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2884 if (display == nil)
2885 display = application_r[1];
2886
2887 NSString *bundle([file stringByDeletingLastPathComponent]);
2888 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2889 // XXX: maybe this should check if this is really a string, not just for length
2890 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2891 icon = @"icon.png";
2892 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2893
2894 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2895 [applications addObject:application];
2896
2897 [application addObject:id];
2898 [application addObject:display];
2899 [application addObject:url];
2900 }
2901
2902 return [applications count] == 0 ? nil : applications;
2903 }
2904
2905 - (Source *) source {
2906 if (source_ == nil) {
2907 @synchronized (database_) {
2908 if ([database_ era] != era_ || file_.end())
2909 source_ = (Source *) [NSNull null];
2910 else
2911 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2912 }
2913 }
2914
2915 return source_ == (Source *) [NSNull null] ? nil : source_;
2916 }
2917
2918 - (uint32_t) rank {
2919 return rank_;
2920 }
2921
2922 - (BOOL) matches:(NSArray *)query {
2923 if (query == nil || [query count] == 0)
2924 return NO;
2925
2926 rank_ = 0;
2927
2928 NSString *string;
2929 NSRange range;
2930 NSUInteger length;
2931
2932 string = [self name];
2933 length = [string length];
2934
2935 for (NSString *term in query) {
2936 range = [string rangeOfString:term options:MatchCompareOptions_];
2937 if (range.location != NSNotFound)
2938 rank_ -= 6 * 1000000 / length;
2939 }
2940
2941 if (rank_ == 0) {
2942 string = [self id];
2943 length = [string length];
2944
2945 for (NSString *term in query) {
2946 range = [string rangeOfString:term options:MatchCompareOptions_];
2947 if (range.location != NSNotFound)
2948 rank_ -= 6 * 1000000 / length;
2949 }
2950 }
2951
2952 string = [self shortDescription];
2953 length = [string length];
2954 NSUInteger stop(std::min<NSUInteger>(length, 200));
2955
2956 for (NSString *term in query) {
2957 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2958 if (range.location != NSNotFound)
2959 rank_ -= 2 * 100000;
2960 }
2961
2962 return rank_ != 0;
2963 }
2964
2965 - (bool) hasSupportingRole {
2966 if (role_ == 0)
2967 return true;
2968 if (role_ == 1)
2969 return true;
2970 if ([Role_ isEqualToString:@"User"])
2971 return false;
2972 if (role_ == 2)
2973 return true;
2974 if ([Role_ isEqualToString:@"Hacker"])
2975 return false;
2976 if (role_ == 3)
2977 return true;
2978 if ([Role_ isEqualToString:@"Developer"])
2979 return false;
2980 _assert(false);
2981 }
2982
2983 - (NSArray *) tags {
2984 return tags_;
2985 }
2986
2987 - (BOOL) hasTag:(NSString *)tag {
2988 return tags_ == nil ? NO : [tags_ containsObject:tag];
2989 }
2990
2991 - (NSString *) primaryPurpose {
2992 for (NSString *tag in (NSArray *) tags_)
2993 if ([tag hasPrefix:@"purpose::"])
2994 return [tag substringFromIndex:9];
2995 return nil;
2996 }
2997
2998 - (NSArray *) purposes {
2999 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3000 for (NSString *tag in (NSArray *) tags_)
3001 if ([tag hasPrefix:@"purpose::"])
3002 [purposes addObject:[tag substringFromIndex:9]];
3003 return [purposes count] == 0 ? nil : purposes;
3004 }
3005
3006 - (bool) isCommercial {
3007 return [self hasTag:@"cydia::commercial"];
3008 }
3009
3010 - (void) setIndex:(size_t)index {
3011 if (metadata_->index_ != index)
3012 metadata_->index_ = index;
3013 }
3014
3015 - (CYString &) cyname {
3016 return name_.empty() ? id_ : name_;
3017 }
3018
3019 - (uint32_t) compareBySection:(NSArray *)sections {
3020 NSString *section([self section]);
3021 for (size_t i(0), e([sections count]); i != e; ++i) {
3022 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3023 return i;
3024 }
3025
3026 return _not(uint32_t);
3027 }
3028
3029 - (void) clear {
3030 @synchronized (database_) {
3031 pkgProblemResolver *resolver = [database_ resolver];
3032 resolver->Clear(iterator_);
3033
3034 pkgCacheFile &cache([database_ cache]);
3035 cache->SetReInstall(iterator_, false);
3036 cache->MarkKeep(iterator_, false);
3037 } }
3038
3039 - (void) install {
3040 @synchronized (database_) {
3041 pkgProblemResolver *resolver = [database_ resolver];
3042 resolver->Clear(iterator_);
3043 resolver->Protect(iterator_);
3044
3045 pkgCacheFile &cache([database_ cache]);
3046 cache->SetReInstall(iterator_, false);
3047 cache->MarkInstall(iterator_, false);
3048
3049 pkgDepCache::StateCache &state((*cache)[iterator_]);
3050 if (!state.Install())
3051 cache->SetReInstall(iterator_, true);
3052 } }
3053
3054 - (void) remove {
3055 @synchronized (database_) {
3056 pkgProblemResolver *resolver = [database_ resolver];
3057 resolver->Clear(iterator_);
3058 resolver->Remove(iterator_);
3059 resolver->Protect(iterator_);
3060
3061 pkgCacheFile &cache([database_ cache]);
3062 cache->SetReInstall(iterator_, false);
3063 cache->MarkDelete(iterator_, true);
3064 } }
3065
3066 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3067 _profile(Package$isUnfilteredAndSearchedForBy)
3068 bool value(true);
3069
3070 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3071 value &= [self unfiltered];
3072 _end
3073
3074 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3075 value &= [self matches:query];
3076 _end
3077
3078 return value;
3079 _end
3080 }
3081
3082 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3083 if ([search length] == 0)
3084 return false;
3085
3086 _profile(Package$isUnfilteredAndSelectedForBy)
3087 bool value(true);
3088
3089 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3090 value &= [self unfiltered];
3091 _end
3092
3093 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3094 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3095 _end
3096
3097 return value;
3098 _end
3099 }
3100
3101 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3102 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3103 }
3104
3105 - (bool) isVisibleInSection:(NSString *)name {
3106 NSString *section([self section]);
3107
3108 return (
3109 name == nil ||
3110 section == nil && [name length] == 0 ||
3111 [name isEqualToString:section]
3112 ) && [self visible];
3113 }
3114
3115 - (bool) isVisibleInSource:(Source *)source {
3116 return [self source] == source && [self visible];
3117 }
3118
3119 @end
3120 /* }}} */
3121 /* Section Class {{{ */
3122 @interface Section : NSObject {
3123 _H<NSString> name_;
3124 unichar index_;
3125 size_t row_;
3126 size_t count_;
3127 _H<NSString> localized_;
3128 }
3129
3130 - (NSComparisonResult) compareByLocalized:(Section *)section;
3131 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3132 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3133 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3134 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3135 - (NSString *) name;
3136 - (unichar) index;
3137
3138 - (size_t) row;
3139 - (size_t) count;
3140
3141 - (void) addToRow;
3142 - (void) addToCount;
3143
3144 - (void) setCount:(size_t)count;
3145 - (NSString *) localized;
3146
3147 @end
3148
3149 @implementation Section
3150
3151 - (NSComparisonResult) compareByLocalized:(Section *)section {
3152 NSString *lhs(localized_);
3153 NSString *rhs([section localized]);
3154
3155 /*if ([lhs length] != 0 && [rhs length] != 0) {
3156 unichar lhc = [lhs characterAtIndex:0];
3157 unichar rhc = [rhs characterAtIndex:0];
3158
3159 if (isalpha(lhc) && !isalpha(rhc))
3160 return NSOrderedAscending;
3161 else if (!isalpha(lhc) && isalpha(rhc))
3162 return NSOrderedDescending;
3163 }*/
3164
3165 return [lhs compare:rhs options:LaxCompareOptions_];
3166 }
3167
3168 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3169 if ((self = [self initWithName:name localize:NO]) != nil) {
3170 if (localized != nil)
3171 localized_ = localized;
3172 } return self;
3173 }
3174
3175 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3176 return [self initWithName:name row:0 localize:localize];
3177 }
3178
3179 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3180 if ((self = [super init]) != nil) {
3181 name_ = name;
3182 index_ = '\0';
3183 row_ = row;
3184 if (localize)
3185 localized_ = LocalizeSection(name_);
3186 } return self;
3187 }
3188
3189 /* XXX: localize the index thingees */
3190 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3191 if ((self = [super init]) != nil) {
3192 name_ = [NSString stringWithCharacters:&index length:1];
3193 index_ = index;
3194 row_ = row;
3195 } return self;
3196 }
3197
3198 - (NSString *) name {
3199 return name_;
3200 }
3201
3202 - (unichar) index {
3203 return index_;
3204 }
3205
3206 - (size_t) row {
3207 return row_;
3208 }
3209
3210 - (size_t) count {
3211 return count_;
3212 }
3213
3214 - (void) addToRow {
3215 ++row_;
3216 }
3217
3218 - (void) addToCount {
3219 ++count_;
3220 }
3221
3222 - (void) setCount:(size_t)count {
3223 count_ = count;
3224 }
3225
3226 - (NSString *) localized {
3227 return localized_;
3228 }
3229
3230 @end
3231 /* }}} */
3232
3233 class CydiaLogCleaner :
3234 public pkgArchiveCleaner
3235 {
3236 protected:
3237 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3238 unlink(File);
3239 }
3240 };
3241
3242 /* Database Implementation {{{ */
3243 @implementation Database
3244
3245 + (Database *) sharedInstance {
3246 static _H<Database> instance;
3247 if (instance == nil)
3248 instance = [[[Database alloc] init] autorelease];
3249 return instance;
3250 }
3251
3252 - (unsigned) era {
3253 return era_;
3254 }
3255
3256 - (void) releasePackages {
3257 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3258 CFArrayRemoveAllValues(packages_);
3259 }
3260
3261 - (void) dealloc {
3262 // XXX: actually implement this thing
3263 _assert(false);
3264 [self releasePackages];
3265 apr_pool_destroy(pool_);
3266 NSRecycleZone(zone_);
3267 [super dealloc];
3268 }
3269
3270 - (void) _readCydia:(NSNumber *)fd {
3271 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3272 std::istream is(&ib);
3273 std::string line;
3274
3275 static Pcre finish_r("^finish:([^:]*)$");
3276
3277 while (std::getline(is, line)) {
3278 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3279
3280 const char *data(line.c_str());
3281 size_t size = line.size();
3282 lprintf("C:%s\n", data);
3283
3284 if (finish_r(data, size)) {
3285 NSString *finish = finish_r[1];
3286 int index = [Finishes_ indexOfObject:finish];
3287 if (index != INT_MAX && index > Finish_)
3288 Finish_ = index;
3289 }
3290
3291 [pool release];
3292 }
3293
3294 _assume(false);
3295 }
3296
3297 - (void) _readStatus:(NSNumber *)fd {
3298 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3299 std::istream is(&ib);
3300 std::string line;
3301
3302 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3303 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3304
3305 while (std::getline(is, line)) {
3306 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3307
3308 const char *data(line.c_str());
3309 size_t size(line.size());
3310 lprintf("S:%s\n", data);
3311
3312 if (conffile_r(data, size)) {
3313 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3314 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3315 } else if (strncmp(data, "status: ", 8) == 0) {
3316 // status: <package>: {unpacked,half-configured,installed}
3317 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3318 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3319 } else if (strncmp(data, "processing: ", 12) == 0) {
3320 // processing: configure: config-test
3321 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3322 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3323 } else if (pmstatus_r(data, size)) {
3324 std::string type([pmstatus_r[1] UTF8String]);
3325
3326 NSString *package = pmstatus_r[2];
3327 if ([package isEqualToString:@"dpkg-exec"])
3328 package = nil;
3329
3330 float percent([pmstatus_r[3] floatValue]);
3331 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3332
3333 NSString *string = pmstatus_r[4];
3334
3335 if (type == "pmerror") {
3336 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3337 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3338 } else if (type == "pmstatus") {
3339 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3340 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3341 } else if (type == "pmconffile")
3342 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3343 else
3344 lprintf("E:unknown pmstatus\n");
3345 } else
3346 lprintf("E:unknown status\n");
3347
3348 [pool release];
3349 }
3350
3351 _assume(false);
3352 }
3353
3354 - (void) _readOutput:(NSNumber *)fd {
3355 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3356 std::istream is(&ib);
3357 std::string line;
3358
3359 while (std::getline(is, line)) {
3360 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3361
3362 lprintf("O:%s\n", line.c_str());
3363
3364 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3365 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3366
3367 [pool release];
3368 }
3369
3370 _assume(false);
3371 }
3372
3373 - (FILE *) input {
3374 return input_;
3375 }
3376
3377 - (Package *) packageWithName:(NSString *)name {
3378 if (name == nil)
3379 return nil;
3380 @synchronized (self) {
3381 if (static_cast<pkgDepCache *>(cache_) == NULL)
3382 return nil;
3383 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3384 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3385 } }
3386
3387 - (id) init {
3388 if ((self = [super init]) != nil) {
3389 policy_ = NULL;
3390 records_ = NULL;
3391 resolver_ = NULL;
3392 fetcher_ = NULL;
3393 lock_ = NULL;
3394
3395 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3396 apr_pool_create(&pool_, NULL);
3397
3398 size_t capacity(MetaFile_->active_);
3399 if (capacity == 0)
3400 capacity = 16384;
3401 else
3402 capacity += 1024;
3403
3404 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3405 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3406
3407 int fds[2];
3408
3409 _assert(pipe(fds) != -1);
3410 cydiafd_ = fds[1];
3411
3412 _config->Set("APT::Keep-Fds::", cydiafd_);
3413 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3414
3415 [NSThread
3416 detachNewThreadSelector:@selector(_readCydia:)
3417 toTarget:self
3418 withObject:[NSNumber numberWithInt:fds[0]]
3419 ];
3420
3421 _assert(pipe(fds) != -1);
3422 statusfd_ = fds[1];
3423
3424 [NSThread
3425 detachNewThreadSelector:@selector(_readStatus:)
3426 toTarget:self
3427 withObject:[NSNumber numberWithInt:fds[0]]
3428 ];
3429
3430 _assert(pipe(fds) != -1);
3431 _assert(dup2(fds[0], 0) != -1);
3432 _assert(close(fds[0]) != -1);
3433
3434 input_ = fdopen(fds[1], "a");
3435
3436 _assert(pipe(fds) != -1);
3437 _assert(dup2(fds[1], 1) != -1);
3438 _assert(close(fds[1]) != -1);
3439
3440 [NSThread
3441 detachNewThreadSelector:@selector(_readOutput:)
3442 toTarget:self
3443 withObject:[NSNumber numberWithInt:fds[0]]
3444 ];
3445 } return self;
3446 }
3447
3448 - (pkgCacheFile &) cache {
3449 return cache_;
3450 }
3451
3452 - (pkgDepCache::Policy *) policy {
3453 return policy_;
3454 }
3455
3456 - (pkgRecords *) records {
3457 return records_;
3458 }
3459
3460 - (pkgProblemResolver *) resolver {
3461 return resolver_;
3462 }
3463
3464 - (pkgAcquire &) fetcher {
3465 return *fetcher_;
3466 }
3467
3468 - (pkgSourceList &) list {
3469 return *list_;
3470 }
3471
3472 - (NSArray *) packages {
3473 return (NSArray *) packages_;
3474 }
3475
3476 - (NSArray *) sources {
3477 return sourceList_;
3478 }
3479
3480 - (Source *) sourceWithKey:(NSString *)key {
3481 for (Source *source in [self sources]) {
3482 if ([[source key] isEqualToString:key])
3483 return source;
3484 } return nil;
3485 }
3486
3487 - (bool) popErrorWithTitle:(NSString *)title {
3488 bool fatal(false);
3489
3490 while (!_error->empty()) {
3491 std::string error;
3492 bool warning(!_error->PopMessage(error));
3493 if (!warning)
3494 fatal = true;
3495
3496 for (;;) {
3497 size_t size(error.size());
3498 if (size == 0 || error[size - 1] != '\n')
3499 break;
3500 error.resize(size - 1);
3501 }
3502
3503 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3504
3505 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3506 if (warning && no_pubkey(error.c_str()))
3507 continue;
3508
3509 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3510 }
3511
3512 return fatal;
3513 }
3514
3515 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3516 return [self popErrorWithTitle:title] || !success;
3517 }
3518
3519 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3520 @synchronized (self) {
3521 ++era_;
3522
3523 [self releasePackages];
3524
3525 sourceMap_.clear();
3526 [sourceList_ removeAllObjects];
3527
3528 _error->Discard();
3529
3530 delete list_;
3531 list_ = NULL;
3532 manager_ = NULL;
3533 delete lock_;
3534 lock_ = NULL;
3535 delete fetcher_;
3536 fetcher_ = NULL;
3537 delete resolver_;
3538 resolver_ = NULL;
3539 delete records_;
3540 records_ = NULL;
3541 delete policy_;
3542 policy_ = NULL;
3543
3544 cache_.Close();
3545
3546 apr_pool_clear(pool_);
3547
3548 NSRecycleZone(zone_);
3549 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3550
3551 int chk(creat("/tmp/cydia.chk", 0644));
3552 if (chk != -1)
3553 close(chk);
3554
3555 if (invocation != nil)
3556 [invocation invoke];
3557
3558 NSString *title(UCLocalize("DATABASE"));
3559
3560 list_ = new pkgSourceList();
3561 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3562 return;
3563
3564 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3565 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3566 [sourceList_ addObject:object];
3567 }
3568
3569 _trace();
3570 OpProgress progress;
3571 open:
3572 if (!cache_.Open(progress, true)) {
3573 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3574 while (!_error->empty()) {
3575 std::string error;
3576 bool warning(!_error->PopMessage(error));
3577
3578 lprintf("cache_.Open():[%s]\n", error.c_str());
3579
3580 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3581
3582 SEL repair(NULL);
3583 if (false);
3584 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3585 repair = @selector(configure);
3586 //else if (error == "The package lists or status file could not be parsed or opened.")
3587 // repair = @selector(update);
3588 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3589 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3590 // else if (error == "Malformed Status line")
3591 // else if (error == "The list of sources could not be read.")
3592
3593 if (repair != NULL) {
3594 _error->Discard();
3595 [delegate_ repairWithSelector:repair];
3596 goto open;
3597 }
3598 }
3599
3600 return;
3601 }
3602 _trace();
3603
3604 unlink("/tmp/cydia.chk");
3605
3606 now_ = [[NSDate date] timeIntervalSince1970];
3607
3608 policy_ = new pkgDepCache::Policy();
3609 records_ = new pkgRecords(cache_);
3610 resolver_ = new pkgProblemResolver(cache_);
3611 fetcher_ = new pkgAcquire(&status_);
3612 lock_ = NULL;
3613
3614 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3615 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3616 return;
3617 }
3618
3619 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3620 return;
3621
3622 if (cache_->BrokenCount() != 0) {
3623 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3624 return;
3625
3626 if (cache_->BrokenCount() != 0) {
3627 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3628 return;
3629 }
3630
3631 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3632 return;
3633 }
3634
3635 for (Source *object in (id) sourceList_) {
3636 metaIndex *source([object metaIndex]);
3637 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3638 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3639 // XXX: this could be more intelligent
3640 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3641 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3642 if (!cached.end())
3643 sourceMap_[cached->ID] = object;
3644 }
3645 }
3646
3647 {
3648 /*std::vector<Package *> packages;
3649 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3650 packages_ = nil;*/
3651
3652 _trace();
3653
3654 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3655 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3656 //packages.push_back(package);
3657 CFArrayAppendValue(packages_, CFRetain(package));
3658
3659 _trace();
3660
3661 /*if (packages.empty())
3662 packages_ = [[NSArray alloc] init];
3663 else
3664 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3665 _trace();*/
3666
3667 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3668 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3669 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3670
3671 /*_trace();
3672 PrintTimes();
3673 _trace();*/
3674
3675 _trace();
3676
3677 /*if (!packages.empty())
3678 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3679 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3680
3681 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3682
3683 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3684
3685 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3686
3687 _trace();
3688
3689 size_t count(CFArrayGetCount(packages_));
3690 MetaFile_->active_ = count;
3691
3692 for (size_t index(0); index != count; ++index)
3693 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3694
3695 _trace();
3696 }
3697 } }
3698
3699 - (void) clear {
3700 @synchronized (self) {
3701 delete resolver_;
3702 resolver_ = new pkgProblemResolver(cache_);
3703
3704 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3705 if (!cache_[iterator].Keep())
3706 cache_->MarkKeep(iterator, false);
3707 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3708 cache_->SetReInstall(iterator, false);
3709 } }
3710
3711 - (void) configure {
3712 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3713 _trace();
3714 system([dpkg UTF8String]);
3715 _trace();
3716 }
3717
3718 - (bool) clean {
3719 @synchronized (self) {
3720 // XXX: I don't remember this condition
3721 if (lock_ != NULL)
3722 return false;
3723
3724 FileFd Lock;
3725 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3726
3727 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3728
3729 if ([self popErrorWithTitle:title])
3730 return false;
3731
3732 pkgAcquire fetcher;
3733 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3734
3735 CydiaLogCleaner cleaner;
3736 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3737 return false;
3738
3739 return true;
3740 } }
3741
3742 - (bool) prepare {
3743 fetcher_->Shutdown();
3744
3745 pkgRecords records(cache_);
3746
3747 lock_ = new FileFd();
3748 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3749
3750 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3751
3752 if ([self popErrorWithTitle:title])
3753 return false;
3754
3755 pkgSourceList list;
3756 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3757 return false;
3758
3759 manager_ = (_system->CreatePM(cache_));
3760 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3761 return false;
3762
3763 return true;
3764 }
3765
3766 - (void) perform {
3767 bool substrate(RestartSubstrate_);
3768 RestartSubstrate_ = false;
3769
3770 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3771
3772 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3773 pkgSourceList list;
3774 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3775 return;
3776 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3777 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3778 }
3779
3780 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3781
3782 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3783 _trace();
3784 [self popErrorWithTitle:title];
3785 return;
3786 }
3787
3788 bool failed = false;
3789 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3790 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3791 continue;
3792 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3793 continue;
3794
3795 std::string uri = (*item)->DescURI();
3796 std::string error = (*item)->ErrorText;
3797
3798 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3799 failed = true;
3800
3801 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3802 [delegate_ addProgressEventOnMainThread:event forTask:title];
3803 }
3804
3805 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3806
3807 if (failed) {
3808 _trace();
3809 return;
3810 }
3811
3812 if (substrate)
3813 RestartSubstrate_ = true;
3814
3815 _system->UnLock();
3816 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3817 if ([self popErrorWithTitle:title])
3818 return;
3819
3820 if (result == pkgPackageManager::Failed) {
3821 _trace();
3822 return;
3823 }
3824
3825 if (result != pkgPackageManager::Completed) {
3826 _trace();
3827 return;
3828 }
3829
3830 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3831 pkgSourceList list;
3832 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3833 return;
3834 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3835 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3836 }
3837
3838 if (![before isEqualToArray:after])
3839 [self update];
3840 }
3841
3842 - (bool) upgrade {
3843 NSString *title(UCLocalize("UPGRADE"));
3844 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3845 return false;
3846 return true;
3847 }
3848
3849 - (void) update {
3850 [self updateWithStatus:status_];
3851 }
3852
3853 - (void) updateWithStatus:(Status &)status {
3854 NSString *title(UCLocalize("REFRESHING_DATA"));
3855
3856 pkgSourceList list;
3857 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3858 return;
3859
3860 FileFd lock;
3861 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3862 if ([self popErrorWithTitle:title])
3863 return;
3864
3865 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3866
3867 bool success(ListUpdate(status, list, PulseInterval_));
3868 if (status.WasCancelled())
3869 _error->Discard();
3870 else {
3871 [self popErrorWithTitle:title forOperation:success];
3872 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3873 Changed_ = true;
3874 }
3875
3876 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3877 }
3878
3879 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3880 delegate_ = delegate;
3881 }
3882
3883 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3884 progress_ = delegate;
3885 status_.setDelegate(delegate);
3886 }
3887
3888 - (NSObject<ProgressDelegate> *) progressDelegate {
3889 return progress_;
3890 }
3891
3892 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3893 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3894 return i == sourceMap_.end() ? nil : i->second;
3895 }
3896
3897 - (NSString *) mappedSectionForPointer:(const char *)section {
3898 _H<NSString> *mapped;
3899
3900 _profile(Database$mappedSectionForPointer$Cache)
3901 mapped = &sections_[section];
3902 _end
3903
3904 if (*mapped == NULL) {
3905 size_t length(strlen(section));
3906 char spaced[length + 1];
3907
3908 _profile(Database$mappedSectionForPointer$Replace)
3909 for (size_t index(0); index != length; ++index)
3910 spaced[index] = section[index] == '_' ? ' ' : section[index];
3911 spaced[length] = '\0';
3912 _end
3913
3914 NSString *string;
3915
3916 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3917 string = [NSString stringWithUTF8String:spaced];
3918 _end
3919
3920 _profile(Database$mappedSectionForPointer$Map)
3921 string = [SectionMap_ objectForKey:string] ?: string;
3922 _end
3923
3924 *mapped = string;
3925 } return *mapped;
3926 }
3927
3928 @end
3929 /* }}} */
3930
3931 static _H<NSMutableSet> Diversions_;
3932
3933 @interface Diversion : NSObject {
3934 Pcre pattern_;
3935 _H<NSString> key_;
3936 _H<NSString> format_;
3937 }
3938
3939 @end
3940
3941 @implementation Diversion
3942
3943 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3944 if ((self = [super init]) != nil) {
3945 pattern_ = [from UTF8String];
3946 key_ = from;
3947 format_ = to;
3948 } return self;
3949 }
3950
3951 - (NSString *) divert:(NSString *)url {
3952 return !pattern_(url) ? nil : pattern_->*format_;
3953 }
3954
3955 + (NSURL *) divertURL:(NSURL *)url {
3956 divert:
3957 NSString *href([url absoluteString]);
3958
3959 for (Diversion *diversion in (id) Diversions_)
3960 if (NSString *diverted = [diversion divert:href]) {
3961 #if !ForRelease
3962 NSLog(@"div: %@", diverted);
3963 #endif
3964 url = [NSURL URLWithString:diverted];
3965 goto divert;
3966 }
3967
3968 return url;
3969 }
3970
3971 - (NSString *) key {
3972 return key_;
3973 }
3974
3975 - (NSUInteger) hash {
3976 return [key_ hash];
3977 }
3978
3979 - (BOOL) isEqual:(Diversion *)object {
3980 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3981 }
3982
3983 @end
3984
3985 @interface CydiaObject : NSObject {
3986 _H<CyteWebViewController> indirect_;
3987 _transient id delegate_;
3988 }
3989
3990 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3991
3992 @end
3993
3994 @class CydiaObject;
3995
3996 @interface CydiaWebViewController : CyteWebViewController {
3997 _H<CydiaObject> cydia_;
3998 }
3999
4000 + (void) addDiversion:(Diversion *)diversion;
4001 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4002 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4003 - (void) setDelegate:(id)delegate;
4004
4005 @end
4006
4007 /* Web Scripting {{{ */
4008 @implementation CydiaObject
4009
4010 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4011 if ((self = [super init]) != nil) {
4012 indirect_ = (CyteWebViewController *) indirect;
4013 } return self;
4014 }
4015
4016 - (void) setDelegate:(id)delegate {
4017 delegate_ = delegate;
4018 }
4019
4020 + (NSArray *) _attributeKeys {
4021 return [NSArray arrayWithObjects:
4022 @"bbsnum",
4023 @"build",
4024 @"coreFoundationVersionNumber",
4025 @"device",
4026 @"ecid",
4027 @"firmware",
4028 @"hostname",
4029 @"idiom",
4030 @"mcc",
4031 @"mnc",
4032 @"model",
4033 @"operator",
4034 @"role",
4035 @"serial",
4036 @"token",
4037 @"version",
4038 nil];
4039 }
4040
4041 - (NSArray *) attributeKeys {
4042 return [[self class] _attributeKeys];
4043 }
4044
4045 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4046 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4047 }
4048
4049 - (NSString *) version {
4050 return Cydia_;
4051 }
4052
4053 - (NSString *) build {
4054 return System_;
4055 }
4056
4057 - (NSString *) coreFoundationVersionNumber {
4058 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4059 }
4060
4061 - (NSString *) device {
4062 return [[UIDevice currentDevice] uniqueIdentifier];
4063 }
4064
4065 - (NSString *) firmware {
4066 return [[UIDevice currentDevice] systemVersion];
4067 }
4068
4069 - (NSString *) hostname {
4070 return [[UIDevice currentDevice] name];
4071 }
4072
4073 - (NSString *) idiom {
4074 return (id) Idiom_ ?: [NSNull null];
4075 }
4076
4077 - (NSString *) mcc {
4078 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4079 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4080 return nil;
4081 }
4082
4083 - (NSString *) mnc {
4084 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4085 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4086 return nil;
4087 }
4088
4089 - (NSString *) operator {
4090 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4091 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4092 return nil;
4093 }
4094
4095 - (NSString *) bbsnum {
4096 return (id) BBSNum_ ?: [NSNull null];
4097 }
4098
4099 - (NSString *) ecid {
4100 return (id) ChipID_ ?: [NSNull null];
4101 }
4102
4103 - (NSString *) serial {
4104 return SerialNumber_;
4105 }
4106
4107 - (NSString *) role {
4108 return (id) Role_ ?: [NSNull null];
4109 }
4110
4111 - (NSString *) model {
4112 return [NSString stringWithUTF8String:Machine_];
4113 }
4114
4115 - (NSString *) token {
4116 return (id) Token_ ?: [NSNull null];
4117 }
4118
4119 + (NSString *) webScriptNameForSelector:(SEL)selector {
4120 if (false);
4121 else if (selector == @selector(addBridgedHost:))
4122 return @"addBridgedHost";
4123 else if (selector == @selector(addInsecureHost:))
4124 return @"addInsecureHost";
4125 else if (selector == @selector(addInternalRedirect::))
4126 return @"addInternalRedirect";
4127 else if (selector == @selector(addPipelinedHost:scheme:))
4128 return @"addPipelinedHost";
4129 else if (selector == @selector(addSource:::))
4130 return @"addSource";
4131 else if (selector == @selector(addTokenHost:))
4132 return @"addTokenHost";
4133 else if (selector == @selector(addTrivialSource:))
4134 return @"addTrivialSource";
4135 else if (selector == @selector(close))
4136 return @"close";
4137 else if (selector == @selector(du:))
4138 return @"du";
4139 else if (selector == @selector(stringWithFormat:arguments:))
4140 return @"format";
4141 else if (selector == @selector(getAllSources))
4142 return @"getAllSources";
4143 else if (selector == @selector(getKernelNumber:))
4144 return @"getKernelNumber";
4145 else if (selector == @selector(getKernelString:))
4146 return @"getKernelString";
4147 else if (selector == @selector(getInstalledPackages))
4148 return @"getInstalledPackages";
4149 else if (selector == @selector(getIORegistryEntry::))
4150 return @"getIORegistryEntry";
4151 else if (selector == @selector(getLocaleIdentifier))
4152 return @"getLocaleIdentifier";
4153 else if (selector == @selector(getPreferredLanguages))
4154 return @"getPreferredLanguages";
4155 else if (selector == @selector(getPackageById:))
4156 return @"getPackageById";
4157 else if (selector == @selector(getMetadataKeys))
4158 return @"getMetadataKeys";
4159 else if (selector == @selector(getMetadataValue:))
4160 return @"getMetadataValue";
4161 else if (selector == @selector(getSessionValue:))
4162 return @"getSessionValue";
4163 else if (selector == @selector(installPackages:))
4164 return @"installPackages";
4165 else if (selector == @selector(isReachable:))
4166 return @"isReachable";
4167 else if (selector == @selector(localizedStringForKey:value:table:))
4168 return @"localize";
4169 else if (selector == @selector(popViewController:))
4170 return @"popViewController";
4171 else if (selector == @selector(refreshSources))
4172 return @"refreshSources";
4173 else if (selector == @selector(registerFrame:))
4174 return @"registerFrame";
4175 else if (selector == @selector(removeButton))
4176 return @"removeButton";
4177 else if (selector == @selector(saveConfig))
4178 return @"saveConfig";
4179 else if (selector == @selector(setMetadataValue::))
4180 return @"setMetadataValue";
4181 else if (selector == @selector(setSessionValue::))
4182 return @"setSessionValue";
4183 else if (selector == @selector(setShowPromoted:))
4184 return @"setShowPromoted";
4185 else if (selector == @selector(substitutePackageNames:))
4186 return @"substitutePackageNames";
4187 else if (selector == @selector(scrollToBottom:))
4188 return @"scrollToBottom";
4189 else if (selector == @selector(setAllowsNavigationAction:))
4190 return @"setAllowsNavigationAction";
4191 else if (selector == @selector(setBadgeValue:))
4192 return @"setBadgeValue";
4193 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4194 return @"setButtonImage";
4195 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4196 return @"setButtonTitle";
4197 else if (selector == @selector(setHidesBackButton:))
4198 return @"setHidesBackButton";
4199 else if (selector == @selector(setHidesNavigationBar:))
4200 return @"setHidesNavigationBar";
4201 else if (selector == @selector(setNavigationBarStyle:))
4202 return @"setNavigationBarStyle";
4203 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4204 return @"setNavigationBarTintColor";
4205 else if (selector == @selector(setPasteboardString:))
4206 return @"setPasteboardString";
4207 else if (selector == @selector(setPasteboardURL:))
4208 return @"setPasteboardURL";
4209 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4210 return @"setScrollAlwaysBounceVertical";
4211 else if (selector == @selector(setScrollIndicatorStyle:))
4212 return @"setScrollIndicatorStyle";
4213 else if (selector == @selector(setToken:))
4214 return @"setToken";
4215 else if (selector == @selector(setViewportWidth:))
4216 return @"setViewportWidth";
4217 else if (selector == @selector(statfs:))
4218 return @"statfs";
4219 else if (selector == @selector(supports:))
4220 return @"supports";
4221 else if (selector == @selector(unload))
4222 return @"unload";
4223 else
4224 return nil;
4225 }
4226
4227 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4228 return [self webScriptNameForSelector:selector] == nil;
4229 }
4230
4231 - (BOOL) supports:(NSString *)feature {
4232 return [feature isEqualToString:@"window.open"];
4233 }
4234
4235 - (void) unload {
4236 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4237 }
4238
4239 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4240 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4241 }
4242
4243 - (void) setScrollIndicatorStyle:(NSString *)style {
4244 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4245 }
4246
4247 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4248 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4249 }
4250
4251 - (NSNumber *) getKernelNumber:(NSString *)name {
4252 const char *string([name UTF8String]);
4253
4254 size_t size;
4255 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4256 return (id) [NSNull null];
4257
4258 if (size != sizeof(int))
4259 return (id) [NSNull null];
4260
4261 int value;
4262 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4263 return (id) [NSNull null];
4264
4265 return [NSNumber numberWithInt:value];
4266 }
4267
4268 - (NSString *) getKernelString:(NSString *)name {
4269 const char *string([name UTF8String]);
4270
4271 size_t size;
4272 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4273 return (id) [NSNull null];
4274
4275 char value[size + 1];
4276 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4277 return (id) [NSNull null];
4278
4279 // XXX: just in case you request something ludicrous
4280 value[size] = '\0';
4281
4282 return [NSString stringWithCString:value];
4283 }
4284
4285 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4286 NSObject *value(CYIOGetValue([path UTF8String], entry));
4287
4288 if (value != nil)
4289 if ([value isKindOfClass:[NSData class]])
4290 value = CYHex((NSData *) value);
4291
4292 return value;
4293 }
4294
4295 - (NSArray *) getMetadataKeys {
4296 @synchronized (Values_) {
4297 return [Values_ allKeys];
4298 } }
4299
4300 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4301 WebFrame *frame([iframe contentFrame]);
4302 [indirect_ registerFrame:frame];
4303 }
4304
4305 - (void) _setShowPromoted:(NSNumber *)value {
4306 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4307 Changed_ = true;
4308 }
4309
4310 - (void) setShowPromoted:(NSNumber *)value {
4311 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4312 }
4313
4314 - (id) getMetadataValue:(NSString *)key {
4315 @synchronized (Values_) {
4316 return [Values_ objectForKey:key];
4317 } }
4318
4319 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4320 @synchronized (Values_) {
4321 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4322 [Values_ removeObjectForKey:key];
4323 else
4324 [Values_ setObject:value forKey:key];
4325
4326 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4327 } }
4328
4329 - (id) getSessionValue:(NSString *)key {
4330 @synchronized (SessionData_) {
4331 return [SessionData_ objectForKey:key];
4332 } }
4333
4334 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4335 @synchronized (SessionData_) {
4336 if (value == (id) [WebUndefined undefined])
4337 [SessionData_ removeObjectForKey:key];
4338 else
4339 [SessionData_ setObject:value forKey:key];
4340 } }
4341
4342 - (void) addBridgedHost:(NSString *)host {
4343 @synchronized (HostConfig_) {
4344 [BridgedHosts_ addObject:host];
4345 } }
4346
4347 - (void) addInsecureHost:(NSString *)host {
4348 @synchronized (HostConfig_) {
4349 [InsecureHosts_ addObject:host];
4350 } }
4351
4352 - (void) addTokenHost:(NSString *)host {
4353 @synchronized (HostConfig_) {
4354 [TokenHosts_ addObject:host];
4355 } }
4356
4357 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4358 @synchronized (HostConfig_) {
4359 if (scheme != (id) [WebUndefined undefined])
4360 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4361
4362 [PipelinedHosts_ addObject:host];
4363 } }
4364
4365 - (void) popViewController:(NSNumber *)value {
4366 if (value == (id) [WebUndefined undefined])
4367 value = [NSNumber numberWithBool:YES];
4368 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4369 }
4370
4371 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4372 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4373
4374 for (NSString *section in sections)
4375 [array addObject:section];
4376
4377 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4378 @"deb", @"Type",
4379 href, @"URI",
4380 distribution, @"Distribution",
4381 array, @"Sections",
4382 nil] waitUntilDone:NO];
4383 }
4384
4385 - (void) addTrivialSource:(NSString *)href {
4386 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4387 }
4388
4389 - (void) refreshSources {
4390 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4391 }
4392
4393 - (void) saveConfig {
4394 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4395 }
4396
4397 - (NSArray *) getAllSources {
4398 return [[Database sharedInstance] sources];
4399 }
4400
4401 - (NSArray *) getInstalledPackages {
4402 Database *database([Database sharedInstance]);
4403 @synchronized (database) {
4404 NSArray *packages([database packages]);
4405 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4406 for (Package *package in packages)
4407 if (![package uninstalled])
4408 [installed addObject:package];
4409 return installed;
4410 } }
4411
4412 - (Package *) getPackageById:(NSString *)id {
4413 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4414 [package parse];
4415 return package;
4416 } else
4417 return (Package *) [NSNull null];
4418 }
4419
4420 - (NSString *) getLocaleIdentifier {
4421 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4422 }
4423
4424 - (NSArray *) getPreferredLanguages {
4425 return Languages_;
4426 }
4427
4428 - (NSArray *) statfs:(NSString *)path {
4429 struct statfs stat;
4430
4431 if (path == nil || statfs([path UTF8String], &stat) == -1)
4432 return nil;
4433
4434 return [NSArray arrayWithObjects:
4435 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4436 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4437 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4438 nil];
4439 }
4440
4441 - (NSNumber *) du:(NSString *)path {
4442 NSNumber *value(nil);
4443
4444 int fds[2];
4445 _assert(pipe(fds) != -1);
4446
4447 pid_t pid(ExecFork());
4448 if (pid == 0) {
4449 _assert(dup2(fds[1], 1) != -1);
4450 _assert(close(fds[0]) != -1);
4451 _assert(close(fds[1]) != -1);
4452 /* XXX: this should probably not use du */
4453 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4454 exit(1);
4455 _assert(false);
4456 }
4457
4458 _assert(close(fds[1]) != -1);
4459
4460 if (FILE *du = fdopen(fds[0], "r")) {
4461 char line[1024];
4462 while (fgets(line, sizeof(line), du) != NULL) {
4463 size_t length(strlen(line));
4464 while (length != 0 && line[length - 1] == '\n')
4465 line[--length] = '\0';
4466 if (char *tab = strchr(line, '\t')) {
4467 *tab = '\0';
4468 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4469 }
4470 }
4471
4472 fclose(du);
4473 } else _assert(close(fds[0]));
4474
4475 ReapZombie(pid);
4476
4477 return value;
4478 }
4479
4480 - (void) close {
4481 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4482 }
4483
4484 - (NSNumber *) isReachable:(NSString *)name {
4485 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4486 }
4487
4488 - (void) installPackages:(NSArray *)packages {
4489 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4490 }
4491
4492 - (NSString *) substitutePackageNames:(NSString *)message {
4493 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4494 for (size_t i(0), e([words count]); i != e; ++i) {
4495 NSString *word([words objectAtIndex:i]);
4496 if (Package *package = [[Database sharedInstance] packageWithName:word])
4497 [words replaceObjectAtIndex:i withObject:[package name]];
4498 }
4499
4500 return [words componentsJoinedByString:@" "];
4501 }
4502
4503 - (void) removeButton {
4504 [indirect_ removeButton];
4505 }
4506
4507 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4508 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4509 }
4510
4511 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4512 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4513 }
4514
4515 - (void) setBadgeValue:(id)value {
4516 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4517 }
4518
4519 - (void) setAllowsNavigationAction:(NSString *)value {
4520 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4521 }
4522
4523 - (void) setHidesBackButton:(NSString *)value {
4524 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4525 }
4526
4527 - (void) setHidesNavigationBar:(NSString *)value {
4528 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4529 }
4530
4531 - (void) setNavigationBarStyle:(NSString *)value {
4532 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4533 }
4534
4535 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4536 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4537 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4538 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4539 }
4540
4541 - (void) setPasteboardString:(NSString *)value {
4542 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4543 }
4544
4545 - (void) setPasteboardURL:(NSString *)value {
4546 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4547 }
4548
4549 - (void) _setToken:(NSString *)token {
4550 Token_ = token;
4551
4552 if (token == nil)
4553 [Metadata_ removeObjectForKey:@"Token"];
4554 else
4555 [Metadata_ setObject:Token_ forKey:@"Token"];
4556
4557 Changed_ = true;
4558 }
4559
4560 - (void) setToken:(NSString *)token {
4561 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4562 }
4563
4564 - (void) scrollToBottom:(NSNumber *)animated {
4565 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4566 }
4567
4568 - (void) setViewportWidth:(float)width {
4569 [indirect_ setViewportWidthOnMainThread:width];
4570 }
4571
4572 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4573 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4574 unsigned count([arguments count]);
4575 id values[count];
4576 for (unsigned i(0); i != count; ++i)
4577 values[i] = [arguments objectAtIndex:i];
4578 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4579 }
4580
4581 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4582 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4583 value = nil;
4584 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4585 table = nil;
4586 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4587 }
4588
4589 @end
4590 /* }}} */
4591
4592 @interface NSURL (CydiaSecure)
4593 @end
4594
4595 @implementation NSURL (CydiaSecure)
4596
4597 - (bool) isCydiaSecure {
4598 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4599 return true;
4600
4601 @synchronized (HostConfig_) {
4602 if ([InsecureHosts_ containsObject:[self host]])
4603 return true;
4604 }
4605
4606 return false;
4607 }
4608
4609 @end
4610
4611 /* Cydia Browser Controller {{{ */
4612 @implementation CydiaWebViewController
4613
4614 - (NSURL *) navigationURL {
4615 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4616 }
4617
4618 + (void) _initialize {
4619 [super _initialize];
4620
4621 Diversions_ = [NSMutableSet setWithCapacity:0];
4622 }
4623
4624 + (void) addDiversion:(Diversion *)diversion {
4625 [Diversions_ addObject:diversion];
4626 }
4627
4628 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4629 [super webView:view didClearWindowObject:window forFrame:frame];
4630 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4631 }
4632
4633 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4634 WebDataSource *source([frame dataSource]);
4635 NSURLResponse *response([source response]);
4636 NSURL *url([response URL]);
4637 NSString *scheme([[url scheme] lowercaseString]);
4638
4639 bool bridged(false);
4640
4641 @synchronized (HostConfig_) {
4642 if ([scheme isEqualToString:@"file"])
4643 bridged = true;
4644 else if ([scheme isEqualToString:@"https"])
4645 if ([BridgedHosts_ containsObject:[url host]])
4646 bridged = true;
4647 }
4648
4649 if (bridged)
4650 [window setValue:cydia forKey:@"cydia"];
4651 }
4652
4653 - (void) _setupMail:(MFMailComposeViewController *)controller {
4654 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4655
4656 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4657 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4658 }
4659
4660 - (NSURL *) URLWithURL:(NSURL *)url {
4661 return [Diversion divertURL:url];
4662 }
4663
4664 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4665 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4666 }
4667
4668 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4669 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4670
4671 NSURL *url([copy URL]);
4672 NSString *href([url absoluteString]);
4673 NSString *host([url host]);
4674
4675 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4676 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4677 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4678 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4679 }
4680
4681 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4682 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4683
4684 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4685 return copy;
4686 }
4687
4688 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4689 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4690 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4691 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4692
4693 bool bridged;
4694 bool token;
4695
4696 @synchronized (HostConfig_) {
4697 bridged = [BridgedHosts_ containsObject:host];
4698 token = [TokenHosts_ containsObject:host];
4699 }
4700
4701 if ([url isCydiaSecure]) {
4702 if (bridged) {
4703 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4704 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4705 } else if (token) {
4706 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4707 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4708 }
4709 }
4710
4711 return copy;
4712 }
4713
4714 - (void) setDelegate:(id)delegate {
4715 [super setDelegate:delegate];
4716 [cydia_ setDelegate:delegate];
4717 }
4718
4719 - (NSString *) applicationNameForUserAgent {
4720 return UserAgent_;
4721 }
4722
4723 - (id) init {
4724 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4725 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4726 } return self;
4727 }
4728
4729 @end
4730
4731 @interface AppCacheController : CydiaWebViewController {
4732 }
4733
4734 @end
4735
4736 @implementation AppCacheController
4737
4738 - (void) didReceiveMemoryWarning {
4739 // XXX: this doesn't work
4740 }
4741
4742 - (bool) retainsNetworkActivityIndicator {
4743 return false;
4744 }
4745
4746 @end
4747 /* }}} */
4748
4749 // CydiaScript {{{
4750 @interface NSObject (CydiaScript)
4751 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4752 @end
4753
4754 @implementation NSObject (CydiaScript)
4755
4756 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4757 return self;
4758 }
4759
4760 @end
4761
4762 @implementation NSArray (CydiaScript)
4763
4764 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4765 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4766 for (size_t i(0), e([self count]); i != e; ++i)
4767 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4768 return object;
4769 }
4770
4771 @end
4772
4773 @implementation NSDictionary (CydiaScript)
4774
4775 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4776 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4777 for (id i in self)
4778 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4779 return object;
4780 }
4781
4782 @end
4783 // }}}
4784
4785 /* Confirmation Controller {{{ */
4786 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4787 if (!iterator.end())
4788 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4789 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4790 continue;
4791 pkgCache::PkgIterator package(dep.TargetPkg());
4792 if (package.end())
4793 continue;
4794 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4795 return true;
4796 }
4797
4798 return false;
4799 }
4800
4801 @protocol ConfirmationControllerDelegate
4802 - (void) cancelAndClear:(bool)clear;
4803 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4804 - (void) queue;
4805 @end
4806
4807 @interface ConfirmationController : CydiaWebViewController {
4808 _transient Database *database_;
4809
4810 _H<UIAlertView> essential_;
4811
4812 _H<NSDictionary> changes_;
4813 _H<NSMutableArray> issues_;
4814 _H<NSDictionary> sizes_;
4815
4816 BOOL substrate_;
4817 }
4818
4819 - (id) initWithDatabase:(Database *)database;
4820
4821 @end
4822
4823 @implementation ConfirmationController
4824
4825 - (void) complete {
4826 if (substrate_)
4827 RestartSubstrate_ = true;
4828 [delegate_ confirmWithNavigationController:[self navigationController]];
4829 }
4830
4831 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4832 NSString *context([alert context]);
4833
4834 if ([context isEqualToString:@"remove"]) {
4835 if (button == [alert cancelButtonIndex])
4836 [self dismissModalViewControllerAnimated:YES];
4837 else if (button == [alert firstOtherButtonIndex]) {
4838 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4839 }
4840
4841 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4842 } else if ([context isEqualToString:@"unable"]) {
4843 [self dismissModalViewControllerAnimated:YES];
4844 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4845 } else {
4846 [super alertView:alert clickedButtonAtIndex:button];
4847 }
4848 }
4849
4850 - (void) _doContinue {
4851 [delegate_ cancelAndClear:NO];
4852 [self dismissModalViewControllerAnimated:YES];
4853 }
4854
4855 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4856 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4857 return nil;
4858 }
4859
4860 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4861 [super webView:view didClearWindowObject:window forFrame:frame];
4862
4863 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4864 (id) changes_, @"changes",
4865 (id) issues_, @"issues",
4866 (id) sizes_, @"sizes",
4867 self, @"queue",
4868 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4869 }
4870
4871 - (id) initWithDatabase:(Database *)database {
4872 if ((self = [super init]) != nil) {
4873 database_ = database;
4874
4875 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4876 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4877 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4878 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4879 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4880
4881 bool remove(false);
4882
4883 pkgCacheFile &cache([database_ cache]);
4884 NSArray *packages([database_ packages]);
4885 pkgDepCache::Policy *policy([database_ policy]);
4886
4887 issues_ = [NSMutableArray arrayWithCapacity:4];
4888
4889 for (Package *package in packages) {
4890 pkgCache::PkgIterator iterator([package iterator]);
4891 NSString *name([package id]);
4892
4893 if ([package broken]) {
4894 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4895
4896 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4897 name, @"package",
4898 reasons, @"reasons",
4899 nil]];
4900
4901 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4902 if (ver.end())
4903 continue;
4904
4905 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4906 pkgCache::DepIterator start;
4907 pkgCache::DepIterator end;
4908 dep.GlobOr(start, end); // ++dep
4909
4910 if (!cache->IsImportantDep(end))
4911 continue;
4912 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4913 continue;
4914
4915 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4916
4917 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4918 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4919 clauses, @"clauses",
4920 nil]];
4921
4922 _forever {
4923 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4924
4925 pkgCache::PkgIterator target(start.TargetPkg());
4926 if (target->ProvidesList != 0)
4927 reason = @"missing";
4928 else {
4929 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4930 if (!ver.end()) {
4931 reason = @"installed";
4932 installed = [NSString stringWithUTF8String:ver.VerStr()];
4933 } else if (!cache[target].CandidateVerIter(cache).end())
4934 reason = @"uninstalled";
4935 else if (target->ProvidesList == 0)
4936 reason = @"uninstallable";
4937 else
4938 reason = @"virtual";
4939 }
4940
4941 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4942 [NSString stringWithUTF8String:start.CompType()], @"operator",
4943 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4944 nil]);
4945
4946 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4947 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4948 version, @"version",
4949 reason, @"reason",
4950 installed, @"installed",
4951 nil]];
4952
4953 // yes, seriously. (wtf?)
4954 if (start == end)
4955 break;
4956 ++start;
4957 }
4958 }
4959 }
4960
4961 pkgDepCache::StateCache &state(cache[iterator]);
4962
4963 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4964
4965 if (state.NewInstall())
4966 [installs addObject:name];
4967 // XXX: else if (state.Install())
4968 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4969 [reinstalls addObject:name];
4970 // XXX: move before previous if
4971 else if (state.Upgrade())
4972 [upgrades addObject:name];
4973 else if (state.Downgrade())
4974 [downgrades addObject:name];
4975 else if (!state.Delete())
4976 // XXX: _assert(state.Keep());
4977 continue;
4978 else if (special_r(name))
4979 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4980 [NSNull null], @"package",
4981 [NSArray arrayWithObjects:
4982 [NSDictionary dictionaryWithObjectsAndKeys:
4983 @"Conflicts", @"relationship",
4984 [NSArray arrayWithObjects:
4985 [NSDictionary dictionaryWithObjectsAndKeys:
4986 name, @"package",
4987 [NSNull null], @"version",
4988 @"installed", @"reason",
4989 nil],
4990 nil], @"clauses",
4991 nil],
4992 nil], @"reasons",
4993 nil]];
4994 else {
4995 if ([package essential])
4996 remove = true;
4997 [removes addObject:name];
4998 }
4999
5000 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5001 substrate_ |= DepSubstrate(iterator.CurrentVer());
5002 }
5003
5004 if (!remove)
5005 essential_ = nil;
5006 else if (Advanced_) {
5007 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5008
5009 essential_ = [[[UIAlertView alloc]
5010 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5011 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5012 delegate:self
5013 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5014 otherButtonTitles:
5015 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5016 nil
5017 ] autorelease];
5018
5019 [essential_ setContext:@"remove"];
5020 [essential_ setNumberOfRows:2];
5021 } else {
5022 essential_ = [[[UIAlertView alloc]
5023 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5024 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5025 delegate:self
5026 cancelButtonTitle:UCLocalize("OKAY")
5027 otherButtonTitles:nil
5028 ] autorelease];
5029
5030 [essential_ setContext:@"unable"];
5031 }
5032
5033 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5034 installs, @"installs",
5035 reinstalls, @"reinstalls",
5036 upgrades, @"upgrades",
5037 downgrades, @"downgrades",
5038 removes, @"removes",
5039 nil];
5040
5041 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5042 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5043 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5044 nil];
5045
5046 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5047 } return self;
5048 }
5049
5050 - (UIBarButtonItem *) leftButton {
5051 return [[[UIBarButtonItem alloc]
5052 initWithTitle:UCLocalize("CANCEL")
5053 style:UIBarButtonItemStylePlain
5054 target:self
5055 action:@selector(cancelButtonClicked)
5056 ] autorelease];
5057 }
5058
5059 #if !AlwaysReload
5060 - (void) applyRightButton {
5061 if ([issues_ count] == 0 && ![self isLoading])
5062 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5063 initWithTitle:UCLocalize("CONFIRM")
5064 style:UIBarButtonItemStyleDone
5065 target:self
5066 action:@selector(confirmButtonClicked)
5067 ] autorelease]];
5068 else
5069 [[self navigationItem] setRightBarButtonItem:nil];
5070 }
5071 #endif
5072
5073 - (void) cancelButtonClicked {
5074 [delegate_ cancelAndClear:YES];
5075 [self dismissModalViewControllerAnimated:YES];
5076 }
5077
5078 #if !AlwaysReload
5079 - (void) confirmButtonClicked {
5080 if (essential_ != nil)
5081 [essential_ show];
5082 else
5083 [self complete];
5084 }
5085 #endif
5086
5087 @end
5088 /* }}} */
5089
5090 /* Progress Data {{{ */
5091 @interface CydiaProgressData : NSObject {
5092 _transient id delegate_;
5093
5094 bool running_;
5095 float percent_;
5096
5097 float current_;
5098 float total_;
5099 float speed_;
5100
5101 _H<NSMutableArray> events_;
5102 _H<NSString> title_;
5103
5104 _H<NSString> status_;
5105 _H<NSString> finish_;
5106 }
5107
5108 @end
5109
5110 @implementation CydiaProgressData
5111
5112 + (NSArray *) _attributeKeys {
5113 return [NSArray arrayWithObjects:
5114 @"current",
5115 @"events",
5116 @"finish",
5117 @"percent",
5118 @"running",
5119 @"speed",
5120 @"title",
5121 @"total",
5122 nil];
5123 }
5124
5125 - (NSArray *) attributeKeys {
5126 return [[self class] _attributeKeys];
5127 }
5128
5129 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5130 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5131 }
5132
5133 - (id) init {
5134 if ((self = [super init]) != nil) {
5135 events_ = [NSMutableArray arrayWithCapacity:32];
5136 } return self;
5137 }
5138
5139 - (id) delegate {
5140 return delegate_;
5141 }
5142
5143 - (void) setDelegate:(id)delegate {
5144 delegate_ = delegate;
5145 }
5146
5147 - (void) setPercent:(float)value {
5148 percent_ = value;
5149 }
5150
5151 - (NSNumber *) percent {
5152 return [NSNumber numberWithFloat:percent_];
5153 }
5154
5155 - (void) setCurrent:(float)value {
5156 current_ = value;
5157 }
5158
5159 - (NSNumber *) current {
5160 return [NSNumber numberWithFloat:current_];
5161 }
5162
5163 - (void) setTotal:(float)value {
5164 total_ = value;
5165 }
5166
5167 - (NSNumber *) total {
5168 return [NSNumber numberWithFloat:total_];
5169 }
5170
5171 - (void) setSpeed:(float)value {
5172 speed_ = value;
5173 }
5174
5175 - (NSNumber *) speed {
5176 return [NSNumber numberWithFloat:speed_];
5177 }
5178
5179 - (NSArray *) events {
5180 return events_;
5181 }
5182
5183 - (void) removeAllEvents {
5184 [events_ removeAllObjects];
5185 }
5186
5187 - (void) addEvent:(CydiaProgressEvent *)event {
5188 [events_ addObject:event];
5189 }
5190
5191 - (void) setTitle:(NSString *)text {
5192 title_ = text;
5193 }
5194
5195 - (NSString *) title {
5196 return title_;
5197 }
5198
5199 - (void) setFinish:(NSString *)text {
5200 finish_ = text;
5201 }
5202
5203 - (NSString *) finish {
5204 return (id) finish_ ?: [NSNull null];
5205 }
5206
5207 - (void) setRunning:(bool)running {
5208 running_ = running;
5209 }
5210
5211 - (NSNumber *) running {
5212 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5213 }
5214
5215 @end
5216 /* }}} */
5217 /* Progress Controller {{{ */
5218 @interface ProgressController : CydiaWebViewController <
5219 ProgressDelegate
5220 > {
5221 _transient Database *database_;
5222 _H<CydiaProgressData, 1> progress_;
5223 unsigned cancel_;
5224 }
5225
5226 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5227
5228 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5229
5230 - (void) setTitle:(NSString *)title;
5231 - (void) setCancellable:(bool)cancellable;
5232
5233 @end
5234
5235 @implementation ProgressController
5236
5237 - (void) dealloc {
5238 [database_ setProgressDelegate:nil];
5239 [super dealloc];
5240 }
5241
5242 - (UIBarButtonItem *) leftButton {
5243 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5244 initWithTitle:UCLocalize("CANCEL")
5245 style:UIBarButtonItemStylePlain
5246 target:self
5247 action:@selector(cancel)
5248 ] autorelease] : nil;
5249 }
5250
5251 - (void) updateCancel {
5252 [super applyLeftButton];
5253 }
5254
5255 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5256 if ((self = [super init]) != nil) {
5257 database_ = database;
5258 delegate_ = delegate;
5259
5260 [database_ setProgressDelegate:self];
5261
5262 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5263 [progress_ setDelegate:self];
5264
5265 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5266
5267 [scroller_ setBackgroundColor:[UIColor blackColor]];
5268
5269 [[self navigationItem] setHidesBackButton:YES];
5270
5271 [self updateCancel];
5272 } return self;
5273 }
5274
5275 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5276 [super webView:view didClearWindowObject:window forFrame:frame];
5277 [window setValue:progress_ forKey:@"cydiaProgress"];
5278 }
5279
5280 - (void) updateProgress {
5281 [self dispatchEvent:@"CydiaProgressUpdate"];
5282 }
5283
5284 - (void) viewWillAppear:(BOOL)animated {
5285 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5286 [super viewWillAppear:animated];
5287 }
5288
5289 - (void) reloadSpringBoard {
5290 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5291 system("/bin/launchctl stop com.apple.backboardd");
5292 sleep(15);
5293 system("/usr/bin/killall backboardd SpringBoard sbreload");
5294 return;
5295 }
5296
5297 pid_t pid(ExecFork());
5298 if (pid == 0) {
5299 pid_t pid(ExecFork());
5300 if (pid == 0) {
5301 execl("/usr/bin/sbreload", "sbreload", NULL);
5302 perror("sbreload");
5303 exit(0);
5304 }
5305
5306 exit(0);
5307 }
5308
5309 ReapZombie(pid);
5310
5311 sleep(15);
5312 system("/usr/bin/killall backboardd SpringBoard sbreload");
5313 }
5314
5315 - (void) close {
5316 UpdateExternalStatus(0);
5317
5318 if (Finish_ > 1)
5319 [delegate_ saveState];
5320
5321 switch (Finish_) {
5322 case 0:
5323 [delegate_ returnToCydia];
5324 break;
5325
5326 case 1:
5327 [delegate_ terminateWithSuccess];
5328 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5329 [delegate_ suspendWithAnimation:YES];
5330 else
5331 [delegate_ suspend];*/
5332 break;
5333
5334 case 2:
5335 _trace();
5336 goto reload;
5337
5338 case 3:
5339 _trace();
5340 goto reload;
5341
5342 reload: {
5343 UIProgressHUD *hud([delegate_ addProgressHUD]);
5344 [hud setText:UCLocalize("LOADING")];
5345 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5346 return;
5347 }
5348
5349 case 4:
5350 _trace();
5351 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5352 SBReboot(SBSSpringBoardServerPort());
5353 else
5354 reboot2(RB_AUTOBOOT);
5355 break;
5356 }
5357
5358 [super close];
5359 }
5360
5361 - (void) setTitle:(NSString *)title {
5362 [progress_ setTitle:title];
5363 [self updateProgress];
5364 }
5365
5366 - (UIBarButtonItem *) rightButton {
5367 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5368 initWithTitle:UCLocalize("CLOSE")
5369 style:UIBarButtonItemStylePlain
5370 target:self
5371 action:@selector(close)
5372 ] autorelease];
5373 }
5374
5375 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5376 UpdateExternalStatus(1);
5377
5378 [progress_ setRunning:true];
5379 [self setTitle:title];
5380 // implicit updateProgress
5381
5382 SHA1SumValue notifyconf; {
5383 FileFd file;
5384 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5385 _error->Discard();
5386 else {
5387 MMap mmap(file, MMap::ReadOnly);
5388 SHA1Summation sha1;
5389 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5390 notifyconf = sha1.Result();
5391 }
5392 }
5393
5394 SHA1SumValue springlist; {
5395 FileFd file;
5396 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5397 _error->Discard();
5398 else {
5399 MMap mmap(file, MMap::ReadOnly);
5400 SHA1Summation sha1;
5401 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5402 springlist = sha1.Result();
5403 }
5404 }
5405
5406 if (invocation != nil) {
5407 [invocation yieldToSelector:@selector(invoke)];
5408 [self setTitle:@"COMPLETE"];
5409 }
5410
5411 if (Finish_ < 4) {
5412 FileFd file;
5413 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5414 _error->Discard();
5415 else {
5416 MMap mmap(file, MMap::ReadOnly);
5417 SHA1Summation sha1;
5418 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5419 if (!(notifyconf == sha1.Result()))
5420 Finish_ = 4;
5421 }
5422 }
5423
5424 if (Finish_ < 3) {
5425 FileFd file;
5426 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5427 _error->Discard();
5428 else {
5429 MMap mmap(file, MMap::ReadOnly);
5430 SHA1Summation sha1;
5431 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5432 if (!(springlist == sha1.Result()))
5433 Finish_ = 3;
5434 }
5435 }
5436
5437 if (Finish_ < 2) {
5438 if (RestartSubstrate_)
5439 Finish_ = 2;
5440 }
5441
5442 RestartSubstrate_ = false;
5443
5444 switch (Finish_) {
5445 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5446 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5447 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5448 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5449 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5450 }
5451
5452 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5453
5454 [progress_ setRunning:false];
5455 [self updateProgress];
5456
5457 [self applyRightButton];
5458 }
5459
5460 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5461 [progress_ addEvent:event];
5462 [self updateProgress];
5463 }
5464
5465 - (bool) isProgressCancelled {
5466 return cancel_ == 2;
5467 }
5468
5469 - (void) cancel {
5470 cancel_ = 2;
5471 [self updateCancel];
5472 }
5473
5474 - (void) setCancellable:(bool)cancellable {
5475 unsigned cancel(cancel_);
5476
5477 if (!cancellable)
5478 cancel_ = 0;
5479 else if (cancel_ == 0)
5480 cancel_ = 1;
5481
5482 if (cancel != cancel_)
5483 [self updateCancel];
5484 }
5485
5486 - (void) setProgressCancellable:(NSNumber *)cancellable {
5487 [self setCancellable:[cancellable boolValue]];
5488 }
5489
5490 - (void) setProgressPercent:(NSNumber *)percent {
5491 [progress_ setPercent:[percent floatValue]];
5492 [self updateProgress];
5493 }
5494
5495 - (void) setProgressStatus:(NSDictionary *)status {
5496 if (status == nil) {
5497 [progress_ setCurrent:0];
5498 [progress_ setTotal:0];
5499 [progress_ setSpeed:0];
5500 } else {
5501 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5502
5503 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5504 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5505 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5506 }
5507
5508 [self updateProgress];
5509 }
5510
5511 @end
5512 /* }}} */
5513
5514 /* Package Cell {{{ */
5515 @interface PackageCell : CyteTableViewCell <
5516 CyteTableViewCellDelegate
5517 > {
5518 _H<UIImage> icon_;
5519 _H<NSString> name_;
5520 _H<NSString> description_;
5521 bool commercial_;
5522 _H<NSString> source_;
5523 _H<UIImage> badge_;
5524 _H<UIImage> placard_;
5525 bool summarized_;
5526 }
5527
5528 - (PackageCell *) init;
5529 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5530
5531 - (void) drawContentRect:(CGRect)rect;
5532
5533 @end
5534
5535 @implementation PackageCell
5536
5537 - (PackageCell *) init {
5538 CGRect frame(CGRectMake(0, 0, 320, 74));
5539 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5540 UIView *content([self contentView]);
5541 CGRect bounds([content bounds]);
5542
5543 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5544 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5545 [content addSubview:content_];
5546
5547 [content_ setDelegate:self];
5548 [content_ setOpaque:YES];
5549 } return self;
5550 }
5551
5552 - (NSString *) accessibilityLabel {
5553 return name_;
5554 }
5555
5556 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5557 summarized_ = summary;
5558
5559 icon_ = nil;
5560 name_ = nil;
5561 description_ = nil;
5562 source_ = nil;
5563 badge_ = nil;
5564 placard_ = nil;
5565
5566 if (package == nil)
5567 [content_ setBackgroundColor:[UIColor whiteColor]];
5568 else {
5569 [package parse];
5570
5571 Source *source = [package source];
5572
5573 icon_ = [package icon];
5574
5575 if (NSString *name = [package name])
5576 name_ = [NSString stringWithString:name];
5577
5578 NSString *description(nil);
5579
5580 if (description == nil && IsWildcat_)
5581 description = [package longDescription];
5582 if (description == nil)
5583 description = [package shortDescription];
5584
5585 if (description != nil)
5586 description_ = [NSString stringWithString:description];
5587
5588 commercial_ = [package isCommercial];
5589
5590 NSString *label = nil;
5591 bool trusted = false;
5592
5593 if (source != nil) {
5594 label = [source label];
5595 trusted = [source trusted];
5596 } else if ([[package id] isEqualToString:@"firmware"])
5597 label = UCLocalize("APPLE");
5598 else
5599 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5600
5601 NSString *from(label);
5602
5603 NSString *section = [package simpleSection];
5604 if (section != nil && ![section isEqualToString:label]) {
5605 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5606 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5607 }
5608
5609 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5610
5611 if (NSString *purpose = [package primaryPurpose])
5612 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5613
5614 UIColor *color;
5615 NSString *placard;
5616
5617 if (NSString *mode = [package mode]) {
5618 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5619 color = RemovingColor_;
5620 //placard = @"removing";
5621 } else {
5622 color = InstallingColor_;
5623 //placard = @"installing";
5624 }
5625
5626 // XXX: the removing/installing placards are not @2x
5627 placard = nil;
5628 } else {
5629 color = [UIColor whiteColor];
5630
5631 if ([package installed] != nil)
5632 placard = @"installed";
5633 else
5634 placard = nil;
5635 }
5636
5637 [content_ setBackgroundColor:color];
5638
5639 if (placard != nil)
5640 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5641 }
5642
5643 [self setNeedsDisplay];
5644 [content_ setNeedsDisplay];
5645 }
5646
5647 - (void) drawSummaryContentRect:(CGRect)rect {
5648 bool highlighted(highlighted_);
5649 float width([self bounds].size.width);
5650
5651 if (icon_ != nil) {
5652 CGRect rect;
5653 rect.size = [(UIImage *) icon_ size];
5654
5655 while (rect.size.width > 16 || rect.size.height > 16) {
5656 rect.size.width /= 2;
5657 rect.size.height /= 2;
5658 }
5659
5660 rect.origin.x = 18 - rect.size.width / 2;
5661 rect.origin.y = 18 - rect.size.height / 2;
5662
5663 [icon_ drawInRect:rect];
5664 }
5665
5666 if (badge_ != nil) {
5667 CGRect rect;
5668 rect.size = [(UIImage *) badge_ size];
5669
5670 rect.size.width /= 4;
5671 rect.size.height /= 4;
5672
5673 rect.origin.x = 23 - rect.size.width / 2;
5674 rect.origin.y = 23 - rect.size.height / 2;
5675
5676 [badge_ drawInRect:rect];
5677 }
5678
5679 if (highlighted)
5680 UISetColor(White_);
5681
5682 if (!highlighted)
5683 UISetColor(commercial_ ? Purple_ : Black_);
5684 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5685
5686 if (placard_ != nil)
5687 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5688 }
5689
5690 - (void) drawNormalContentRect:(CGRect)rect {
5691 bool highlighted(highlighted_);
5692 float width([self bounds].size.width);
5693
5694 if (icon_ != nil) {
5695 CGRect rect;
5696 rect.size = [(UIImage *) icon_ size];
5697
5698 while (rect.size.width > 32 || rect.size.height > 32) {
5699 rect.size.width /= 2;
5700 rect.size.height /= 2;
5701 }
5702
5703 rect.origin.x = 25 - rect.size.width / 2;
5704 rect.origin.y = 25 - rect.size.height / 2;
5705
5706 [icon_ drawInRect:rect];
5707 }
5708
5709 if (badge_ != nil) {
5710 CGRect rect;
5711 rect.size = [(UIImage *) badge_ size];
5712
5713 rect.size.width /= 2;
5714 rect.size.height /= 2;
5715
5716 rect.origin.x = 36 - rect.size.width / 2;
5717 rect.origin.y = 36 - rect.size.height / 2;
5718
5719 [badge_ drawInRect:rect];
5720 }
5721
5722 if (highlighted)
5723 UISetColor(White_);
5724
5725 if (!highlighted)
5726 UISetColor(commercial_ ? Purple_ : Black_);
5727 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5728 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5729
5730 if (!highlighted)
5731 UISetColor(commercial_ ? Purplish_ : Gray_);
5732 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5733
5734 if (placard_ != nil)
5735 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5736 }
5737
5738 - (void) drawContentRect:(CGRect)rect {
5739 if (summarized_)
5740 [self drawSummaryContentRect:rect];
5741 else
5742 [self drawNormalContentRect:rect];
5743 }
5744
5745 @end
5746 /* }}} */
5747 /* Section Cell {{{ */
5748 @interface SectionCell : CyteTableViewCell <
5749 CyteTableViewCellDelegate
5750 > {
5751 _H<NSString> basic_;
5752 _H<NSString> section_;
5753 _H<NSString> name_;
5754 _H<NSString> count_;
5755 _H<UIImage> icon_;
5756 _H<UISwitch> switch_;
5757 BOOL editing_;
5758 }
5759
5760 - (void) setSection:(Section *)section editing:(BOOL)editing;
5761
5762 @end
5763
5764 @implementation SectionCell
5765
5766 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5767 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5768 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5769 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5770 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5771
5772 UIView *content([self contentView]);
5773 CGRect bounds([content bounds]);
5774
5775 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5776 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5777 [content addSubview:content_];
5778 [content_ setBackgroundColor:[UIColor whiteColor]];
5779
5780 [content_ setDelegate:self];
5781 } return self;
5782 }
5783
5784 - (void) onSwitch:(id)sender {
5785 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5786 if (metadata == nil) {
5787 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5788 [Sections_ setObject:metadata forKey:basic_];
5789 }
5790
5791 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5792 Changed_ = true;
5793 }
5794
5795 - (void) setSection:(Section *)section editing:(BOOL)editing {
5796 if (editing != editing_) {
5797 if (editing_)
5798 [switch_ removeFromSuperview];
5799 else
5800 [self addSubview:switch_];
5801 editing_ = editing;
5802 }
5803
5804 basic_ = nil;
5805 section_ = nil;
5806 name_ = nil;
5807 count_ = nil;
5808
5809 if (section == nil) {
5810 name_ = UCLocalize("ALL_PACKAGES");
5811 count_ = nil;
5812 } else {
5813 basic_ = [section name];
5814 section_ = [section localized];
5815
5816 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5817 count_ = [NSString stringWithFormat:@"%d", [section count]];
5818
5819 if (editing_)
5820 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5821 }
5822
5823 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5824 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5825
5826 [content_ setNeedsDisplay];
5827 }
5828
5829 - (void) setFrame:(CGRect)frame {
5830 [super setFrame:frame];
5831
5832 CGRect rect([switch_ frame]);
5833 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5834 }
5835
5836 - (NSString *) accessibilityLabel {
5837 return name_;
5838 }
5839
5840 - (void) drawContentRect:(CGRect)rect {
5841 bool highlighted(highlighted_ && !editing_);
5842
5843 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5844
5845 if (highlighted)
5846 UISetColor(White_);
5847
5848 float width(rect.size.width);
5849 if (editing_)
5850 width -= 87;
5851
5852 if (!highlighted)
5853 UISetColor(Black_);
5854 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5855
5856 CGSize size = [count_ sizeWithFont:Font14_];
5857
5858 UISetColor(White_);
5859 if (count_ != nil)
5860 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5861 }
5862
5863 @end
5864 /* }}} */
5865
5866 /* File Table {{{ */
5867 @interface FileTable : CyteViewController <
5868 UITableViewDataSource,
5869 UITableViewDelegate
5870 > {
5871 _transient Database *database_;
5872 _H<Package> package_;
5873 _H<NSString> name_;
5874 _H<NSMutableArray> files_;
5875 _H<UITableView, 2> list_;
5876 }
5877
5878 - (id) initWithDatabase:(Database *)database;
5879 - (void) setPackage:(Package *)package;
5880
5881 @end
5882
5883 @implementation FileTable
5884
5885 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5886 return files_ == nil ? 0 : [files_ count];
5887 }
5888
5889 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5890 return 24.0f;
5891 }*/
5892
5893 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5894 static NSString *reuseIdentifier = @"Cell";
5895
5896 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5897 if (cell == nil) {
5898 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5899 [cell setFont:[UIFont systemFontOfSize:16]];
5900 }
5901 [cell setText:[files_ objectAtIndex:indexPath.row]];
5902 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5903
5904 return cell;
5905 }
5906
5907 - (NSURL *) navigationURL {
5908 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5909 }
5910
5911 - (void) loadView {
5912 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5913 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5914 [list_ setRowHeight:24.0f];
5915 [(UITableView *) list_ setDataSource:self];
5916 [list_ setDelegate:self];
5917 [self setView:list_];
5918 }
5919
5920 - (void) viewDidLoad {
5921 [super viewDidLoad];
5922
5923 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5924 }
5925
5926 - (void) releaseSubviews {
5927 list_ = nil;
5928
5929 package_ = nil;
5930 files_ = nil;
5931
5932 [super releaseSubviews];
5933 }
5934
5935 - (id) initWithDatabase:(Database *)database {
5936 if ((self = [super init]) != nil) {
5937 database_ = database;
5938 } return self;
5939 }
5940
5941 - (void) setPackage:(Package *)package {
5942 package_ = nil;
5943 name_ = nil;
5944
5945 files_ = [NSMutableArray arrayWithCapacity:32];
5946
5947 if (package != nil) {
5948 package_ = package;
5949 name_ = [package id];
5950
5951 if (NSArray *files = [package files])
5952 [files_ addObjectsFromArray:files];
5953
5954 if ([files_ count] != 0) {
5955 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5956 [files_ removeObjectAtIndex:0];
5957 [files_ sortUsingSelector:@selector(compareByPath:)];
5958
5959 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5960 [stack addObject:@"/"];
5961
5962 for (int i(0), e([files_ count]); i != e; ++i) {
5963 NSString *file = [files_ objectAtIndex:i];
5964 while (![file hasPrefix:[stack lastObject]])
5965 [stack removeLastObject];
5966 NSString *directory = [stack lastObject];
5967 [stack addObject:[file stringByAppendingString:@"/"]];
5968 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5969 ([stack count] - 2) * 3, "",
5970 [file substringFromIndex:[directory length]]
5971 ]];
5972 }
5973 }
5974 }
5975
5976 [list_ reloadData];
5977 }
5978
5979 - (void) reloadData {
5980 [super reloadData];
5981
5982 [self setPackage:[database_ packageWithName:name_]];
5983 }
5984
5985 @end
5986 /* }}} */
5987 /* Package Controller {{{ */
5988 @interface CYPackageController : CydiaWebViewController <
5989 UIActionSheetDelegate
5990 > {
5991 _transient Database *database_;
5992 _H<Package> package_;
5993 _H<NSString> name_;
5994 bool commercial_;
5995 _H<NSMutableArray> buttons_;
5996 _H<UIBarButtonItem> button_;
5997 }
5998
5999 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6000
6001 @end
6002
6003 @implementation CYPackageController
6004
6005 - (NSURL *) navigationURL {
6006 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6007 }
6008
6009 /* XXX: this is not safe at all... localization of /fail/ */
6010 - (void) _clickButtonWithName:(NSString *)name {
6011 if ([name isEqualToString:UCLocalize("CLEAR")])
6012 [delegate_ clearPackage:package_];
6013 else if ([name isEqualToString:UCLocalize("INSTALL")])
6014 [delegate_ installPackage:package_];
6015 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6016 [delegate_ installPackage:package_];
6017 else if ([name isEqualToString:UCLocalize("REMOVE")])
6018 [delegate_ removePackage:package_];
6019 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6020 [delegate_ installPackage:package_];
6021 else _assert(false);
6022 }
6023
6024 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6025 NSString *context([sheet context]);
6026
6027 if ([context isEqualToString:@"modify"]) {
6028 if (button != [sheet cancelButtonIndex]) {
6029 NSString *buttonName = [buttons_ objectAtIndex:button];
6030 [self _clickButtonWithName:buttonName];
6031 }
6032
6033 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6034 }
6035 }
6036
6037 - (bool) _allowJavaScriptPanel {
6038 return commercial_;
6039 }
6040
6041 #if !AlwaysReload
6042 - (void) _customButtonClicked {
6043 int count([buttons_ count]);
6044 if (count == 0)
6045 return;
6046
6047 if (count == 1)
6048 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6049 else {
6050 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6051 [buttons addObjectsFromArray:buttons_];
6052
6053 UIActionSheet *sheet = [[[UIActionSheet alloc]
6054 initWithTitle:nil
6055 delegate:self
6056 cancelButtonTitle:nil
6057 destructiveButtonTitle:nil
6058 otherButtonTitles:nil
6059 ] autorelease];
6060
6061 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6062 if (!IsWildcat_) {
6063 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6064 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6065 }
6066 [sheet setContext:@"modify"];
6067
6068 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6069 }
6070 }
6071
6072 - (void) reloadButtonClicked {
6073 if (commercial_ && function_ == nil && [package_ uninstalled])
6074 return;
6075 [self customButtonClicked];
6076 }
6077
6078 - (void) applyLoadingTitle {
6079 // Don't show "Loading" as the title. Ever.
6080 }
6081
6082 - (UIBarButtonItem *) rightButton {
6083 return button_;
6084 }
6085 #endif
6086
6087 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6088 if ((self = [super init]) != nil) {
6089 database_ = database;
6090 buttons_ = [NSMutableArray arrayWithCapacity:4];
6091 name_ = name == nil ? @"" : [NSString stringWithString:name];
6092 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6093 } return self;
6094 }
6095
6096 - (void) reloadData {
6097 [super reloadData];
6098
6099 package_ = [database_ packageWithName:name_];
6100
6101 [buttons_ removeAllObjects];
6102
6103 if (package_ != nil) {
6104 [(Package *) package_ parse];
6105
6106 commercial_ = [package_ isCommercial];
6107
6108 if ([package_ mode] != nil)
6109 [buttons_ addObject:UCLocalize("CLEAR")];
6110 if ([package_ source] == nil);
6111 else if ([package_ upgradableAndEssential:NO])
6112 [buttons_ addObject:UCLocalize("UPGRADE")];
6113 else if ([package_ uninstalled])
6114 [buttons_ addObject:UCLocalize("INSTALL")];
6115 else
6116 [buttons_ addObject:UCLocalize("REINSTALL")];
6117 if (![package_ uninstalled])
6118 [buttons_ addObject:UCLocalize("REMOVE")];
6119 }
6120
6121 NSString *title;
6122 switch ([buttons_ count]) {
6123 case 0: title = nil; break;
6124 case 1: title = [buttons_ objectAtIndex:0]; break;
6125 default: title = UCLocalize("MODIFY"); break;
6126 }
6127
6128 button_ = [[[UIBarButtonItem alloc]
6129 initWithTitle:title
6130 style:UIBarButtonItemStylePlain
6131 target:self
6132 action:@selector(customButtonClicked)
6133 ] autorelease];
6134 }
6135
6136 - (bool) isLoading {
6137 return commercial_ ? [super isLoading] : false;
6138 }
6139
6140 @end
6141 /* }}} */
6142
6143 /* Package List Controller {{{ */
6144 @interface PackageListController : CyteViewController <
6145 UITableViewDataSource,
6146 UITableViewDelegate
6147 > {
6148 _transient Database *database_;
6149 unsigned era_;
6150 _H<NSArray> packages_;
6151 _H<NSMutableArray> sections_;
6152 _H<UITableView, 2> list_;
6153 _H<NSMutableArray> index_;
6154 _H<NSMutableDictionary> indices_;
6155 _H<NSString> title_;
6156 unsigned reloading_;
6157 }
6158
6159 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6160 - (void) setDelegate:(id)delegate;
6161 - (void) resetCursor;
6162 - (void) clearData;
6163
6164 @end
6165
6166 @implementation PackageListController
6167
6168 - (NSURL *) referrerURL {
6169 return [self navigationURL];
6170 }
6171
6172 - (bool) isSummarized {
6173 return false;
6174 }
6175
6176 - (bool) showsSections {
6177 return true;
6178 }
6179
6180 - (void) deselectWithAnimation:(BOOL)animated {
6181 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6182 }
6183
6184 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6185 CGRect base = [[self view] bounds];
6186 base.size.height -= bounds.size.height;
6187 base.origin = [list_ frame].origin;
6188
6189 [UIView beginAnimations:nil context:NULL];
6190 [UIView setAnimationBeginsFromCurrentState:YES];
6191 [UIView setAnimationCurve:curve];
6192 [UIView setAnimationDuration:duration];
6193 [list_ setFrame:base];
6194 [UIView commitAnimations];
6195 }
6196
6197 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6198 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6199 }
6200
6201 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6202 [self resizeForKeyboardBounds:bounds duration:0];
6203 }
6204
6205 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6206 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6207 *curve = UIViewAnimationCurveEaseInOut;
6208 else
6209 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6210
6211 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6212 *duration = 0.3;
6213 else
6214 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6215 }
6216
6217 - (void) keyboardWillShow:(NSNotification *)notification {
6218 CGRect bounds;
6219 CGPoint center;
6220 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6221 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6222
6223 NSTimeInterval duration;
6224 UIViewAnimationCurve curve;
6225 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6226
6227 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6228 UIViewController *base = self;
6229 while ([base parentOrPresentingViewController] != nil)
6230 base = [base parentOrPresentingViewController];
6231 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6232 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6233
6234 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6235 intersection.size.height += CYStatusBarHeight();
6236
6237 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6238 }
6239
6240 - (void) keyboardWillHide:(NSNotification *)notification {
6241 NSTimeInterval duration;
6242 UIViewAnimationCurve curve;
6243 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6244
6245 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6246 }
6247
6248 - (void) viewWillAppear:(BOOL)animated {
6249 [super viewWillAppear:animated];
6250
6251 [self resizeForKeyboardBounds:CGRectZero];
6252 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6253 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6254 }
6255
6256 - (void) viewWillDisappear:(BOOL)animated {
6257 [super viewWillDisappear:animated];
6258
6259 [self resizeForKeyboardBounds:CGRectZero];
6260 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6261 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6262 }
6263
6264 - (void) viewDidAppear:(BOOL)animated {
6265 [super viewDidAppear:animated];
6266 [self deselectWithAnimation:animated];
6267 }
6268
6269 - (void) didSelectPackage:(Package *)package {
6270 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6271 [view setDelegate:delegate_];
6272 [[self navigationController] pushViewController:view animated:YES];
6273 }
6274
6275 #if TryIndexedCollation
6276 + (BOOL) hasIndexedCollation {
6277 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6278 }
6279 #endif
6280
6281 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6282 NSInteger count([sections_ count]);
6283 return count == 0 ? 1 : count;
6284 }
6285
6286 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6287 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6288 return nil;
6289 return [[sections_ objectAtIndex:section] name];
6290 }
6291
6292 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6293 if ([sections_ count] == 0)
6294 return 0;
6295 return [[sections_ objectAtIndex:section] count];
6296 }
6297
6298 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6299 @synchronized (database_) {
6300 if ([database_ era] != era_)
6301 return nil;
6302
6303 Section *section([sections_ objectAtIndex:[path section]]);
6304 NSInteger row([path row]);
6305 Package *package([packages_ objectAtIndex:([section row] + row)]);
6306 return [[package retain] autorelease];
6307 } }
6308
6309 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6310 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6311 if (cell == nil)
6312 cell = [[[PackageCell alloc] init] autorelease];
6313
6314 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6315 [cell setPackage:package asSummary:[self isSummarized]];
6316 return cell;
6317 }
6318
6319 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6320 Package *package([self packageAtIndexPath:path]);
6321 package = [database_ packageWithName:[package id]];
6322 [self didSelectPackage:package];
6323 }
6324
6325 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6326 if (![self showsSections])
6327 return nil;
6328
6329 return index_;
6330 }
6331
6332 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6333 #if TryIndexedCollation
6334 if ([[self class] hasIndexedCollation]) {
6335 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6336 }
6337 #endif
6338
6339 return index;
6340 }
6341
6342 - (void) updateHeight {
6343 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6344 }
6345
6346 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6347 if ((self = [super init]) != nil) {
6348 database_ = database;
6349 title_ = [title copy];
6350 [[self navigationItem] setTitle:title_];
6351 } return self;
6352 }
6353
6354 - (void) loadView {
6355 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6356 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6357 [self setView:view];
6358
6359 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6360 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6361 [view addSubview:list_];
6362
6363 // XXX: is 20 the most optimal number here?
6364 [list_ setSectionIndexMinimumDisplayRowCount:20];
6365
6366 [(UITableView *) list_ setDataSource:self];
6367 [list_ setDelegate:self];
6368
6369 [self updateHeight];
6370 }
6371
6372 - (void) releaseSubviews {
6373 list_ = nil;
6374
6375 packages_ = nil;
6376 sections_ = nil;
6377 index_ = nil;
6378 indices_ = nil;
6379
6380 [super releaseSubviews];
6381 }
6382
6383 - (void) setDelegate:(id)delegate {
6384 delegate_ = delegate;
6385 }
6386
6387 - (bool) shouldYield {
6388 return false;
6389 }
6390
6391 - (bool) shouldBlock {
6392 return false;
6393 }
6394
6395 - (NSMutableArray *) _reloadPackages {
6396 @synchronized (database_) {
6397 era_ = [database_ era];
6398 NSArray *packages([database_ packages]);
6399
6400 return [NSMutableArray arrayWithArray:packages];
6401 } }
6402
6403 - (void) _reloadData {
6404 if (reloading_ != 0) {
6405 reloading_ = 2;
6406 return;
6407 }
6408
6409 NSArray *packages;
6410
6411 reload:
6412 if ([self shouldYield]) {
6413 do {
6414 UIProgressHUD *hud;
6415
6416 if (![self shouldBlock])
6417 hud = nil;
6418 else {
6419 hud = [delegate_ addProgressHUD];
6420 [hud setText:UCLocalize("LOADING")];
6421 }
6422
6423 reloading_ = 1;
6424 packages = [self yieldToSelector:@selector(_reloadPackages)];
6425
6426 if (hud != nil)
6427 [delegate_ removeProgressHUD:hud];
6428 } while (reloading_ == 2);
6429 } else {
6430 packages = [self _reloadPackages];
6431 }
6432
6433 @synchronized (database_) {
6434 if (era_ != [database_ era])
6435 goto reload;
6436 reloading_ = 0;
6437
6438 packages_ = packages;
6439
6440 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6441 sections_ = [NSMutableArray arrayWithCapacity:16];
6442
6443 Section *section = nil;
6444
6445 #if TryIndexedCollation
6446 if ([[self class] hasIndexedCollation]) {
6447 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6448
6449 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6450 NSArray *titles = [collation sectionIndexTitles];
6451 int secidx = -1;
6452
6453 _profile(PackageTable$reloadData$Section)
6454 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6455 Package *package;
6456 int index;
6457
6458 _profile(PackageTable$reloadData$Section$Package)
6459 package = [packages_ objectAtIndex:offset];
6460 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6461 _end
6462
6463 while (secidx < index) {
6464 secidx += 1;
6465
6466 _profile(PackageTable$reloadData$Section$Allocate)
6467 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6468 _end
6469
6470 _profile(PackageTable$reloadData$Section$Add)
6471 [sections_ addObject:section];
6472 _end
6473 }
6474
6475 [section addToCount];
6476 }
6477 _end
6478 } else
6479 #endif
6480 {
6481 index_ = [NSMutableArray arrayWithCapacity:32];
6482
6483 bool sectioned([self showsSections]);
6484 if (!sectioned) {
6485 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6486 [sections_ addObject:section];
6487 }
6488
6489 _profile(PackageTable$reloadData$Section)
6490 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6491 Package *package;
6492 unichar index;
6493
6494 _profile(PackageTable$reloadData$Section$Package)
6495 package = [packages_ objectAtIndex:offset];
6496 index = [package index];
6497 _end
6498
6499 if (sectioned && (section == nil || [section index] != index)) {
6500 _profile(PackageTable$reloadData$Section$Allocate)
6501 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6502 _end
6503
6504 [index_ addObject:[section name]];
6505 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6506
6507 _profile(PackageTable$reloadData$Section$Add)
6508 [sections_ addObject:section];
6509 _end
6510 }
6511
6512 [section addToCount];
6513 }
6514 _end
6515 }
6516
6517 [self updateHeight];
6518
6519 _profile(PackageTable$reloadData$List)
6520 [(UITableView *) list_ setDataSource:self];
6521 [list_ reloadData];
6522 _end
6523 } }
6524
6525 - (void) reloadData {
6526 [super reloadData];
6527
6528 if ([self shouldYield])
6529 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6530 else
6531 [self _reloadData];
6532 }
6533
6534 - (void) resetCursor {
6535 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6536 }
6537
6538 - (void) clearData {
6539 [self updateHeight];
6540
6541 [list_ setDataSource:nil];
6542 [list_ reloadData];
6543
6544 [self resetCursor];
6545 }
6546
6547 @end
6548 /* }}} */
6549 /* Filtered Package List Controller {{{ */
6550 @interface FilteredPackageListController : PackageListController {
6551 SEL filter_;
6552 IMP imp_;
6553 _H<NSObject> object_;
6554 }
6555
6556 - (void) setObject:(id)object;
6557 - (void) setObject:(id)object forFilter:(SEL)filter;
6558
6559 - (SEL) filter;
6560 - (void) setFilter:(SEL)filter;
6561
6562 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6563
6564 @end
6565
6566 @implementation FilteredPackageListController
6567
6568 - (SEL) filter {
6569 return filter_;
6570 }
6571
6572 - (void) setFilter:(SEL)filter {
6573 @synchronized (self) {
6574 filter_ = filter;
6575
6576 /* XXX: this is an unsafe optimization of doomy hell */
6577 Method method(class_getInstanceMethod([Package class], filter));
6578 _assert(method != NULL);
6579 imp_ = method_getImplementation(method);
6580 _assert(imp_ != NULL);
6581 } }
6582
6583 - (void) setObject:(id)object {
6584 @synchronized (self) {
6585 object_ = object;
6586 } }
6587
6588 - (void) setObject:(id)object forFilter:(SEL)filter {
6589 @synchronized (self) {
6590 [self setFilter:filter];
6591 [self setObject:object];
6592 } }
6593
6594 - (NSMutableArray *) _reloadPackages {
6595 @synchronized (database_) {
6596 era_ = [database_ era];
6597 NSArray *packages([database_ packages]);
6598
6599 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6600
6601 IMP imp;
6602 SEL filter;
6603 _H<NSObject> object;
6604
6605 @synchronized (self) {
6606 imp = imp_;
6607 filter = filter_;
6608 object = object_;
6609 }
6610
6611 _profile(PackageTable$reloadData$Filter)
6612 for (Package *package in packages)
6613 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6614 [filtered addObject:package];
6615 _end
6616
6617 return filtered;
6618 } }
6619
6620 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6621 if ((self = [super initWithDatabase:database title:title]) != nil) {
6622 [self setFilter:filter];
6623 [self setObject:object];
6624 } return self;
6625 }
6626
6627 @end
6628 /* }}} */
6629
6630 /* Home Controller {{{ */
6631 @interface HomeController : CydiaWebViewController {
6632 CFRunLoopRef runloop_;
6633 SCNetworkReachabilityRef reachability_;
6634 }
6635
6636 @end
6637
6638 @implementation HomeController
6639
6640 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6641 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6642 }
6643
6644 - (id) init {
6645 if ((self = [super init]) != nil) {
6646 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6647 [self reloadData];
6648
6649 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6650 if (reachability_ != NULL) {
6651 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6652 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6653
6654 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6655 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6656 runloop_ = runloop;
6657 }
6658 } return self;
6659 }
6660
6661 - (void) dealloc {
6662 if (reachability_ != NULL && runloop_ != NULL)
6663 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6664 [super dealloc];
6665 }
6666
6667 - (NSURL *) navigationURL {
6668 return [NSURL URLWithString:@"cydia://home"];
6669 }
6670
6671 - (void) aboutButtonClicked {
6672 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6673
6674 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6675 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6676 [alert setCancelButtonIndex:0];
6677
6678 [alert setMessage:
6679 @"Copyright \u00a9 2008-2012\n"
6680 "SaurikIT, LLC\n"
6681 "\n"
6682 "Jay Freeman (saurik)\n"
6683 "saurik@saurik.com\n"
6684 "http://www.saurik.com/"
6685 ];
6686
6687 [alert show];
6688 }
6689
6690 - (UIBarButtonItem *) leftButton {
6691 return [[[UIBarButtonItem alloc]
6692 initWithTitle:UCLocalize("ABOUT")
6693 style:UIBarButtonItemStylePlain
6694 target:self
6695 action:@selector(aboutButtonClicked)
6696 ] autorelease];
6697 }
6698
6699 @end
6700 /* }}} */
6701 /* Manage Controller {{{ */
6702 @interface ManageController : CydiaWebViewController {
6703 }
6704
6705 - (void) queueStatusDidChange;
6706
6707 @end
6708
6709 @implementation ManageController
6710
6711 - (id) init {
6712 if ((self = [super init]) != nil) {
6713 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6714 } return self;
6715 }
6716
6717 - (NSURL *) navigationURL {
6718 return [NSURL URLWithString:@"cydia://manage"];
6719 }
6720
6721 - (UIBarButtonItem *) leftButton {
6722 return [[[UIBarButtonItem alloc]
6723 initWithTitle:UCLocalize("SETTINGS")
6724 style:UIBarButtonItemStylePlain
6725 target:self
6726 action:@selector(settingsButtonClicked)
6727 ] autorelease];
6728 }
6729
6730 - (void) settingsButtonClicked {
6731 [delegate_ showSettings];
6732 }
6733
6734 - (void) queueButtonClicked {
6735 [delegate_ queue];
6736 }
6737
6738 - (UIBarButtonItem *) rightButton {
6739 return Queuing_ ? [[[UIBarButtonItem alloc]
6740 initWithTitle:UCLocalize("QUEUE")
6741 style:UIBarButtonItemStyleDone
6742 target:self
6743 action:@selector(queueButtonClicked)
6744 ] autorelease] : nil;
6745 }
6746
6747 - (void) queueStatusDidChange {
6748 [self applyRightButton];
6749 }
6750
6751 - (bool) isLoading {
6752 return !Queuing_ && [super isLoading];
6753 }
6754
6755 @end
6756 /* }}} */
6757
6758 /* Refresh Bar {{{ */
6759 @interface RefreshBar : UINavigationBar {
6760 _H<UIProgressIndicator> indicator_;
6761 _H<UITextLabel> prompt_;
6762 _H<UINavigationButton> cancel_;
6763 }
6764
6765 @end
6766
6767 @implementation RefreshBar
6768
6769 - (void) positionViews {
6770 CGRect frame = [cancel_ frame];
6771 frame.size = [cancel_ sizeThatFits:frame.size];
6772 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6773 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6774 [cancel_ setFrame:frame];
6775
6776 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6777 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6778 CGRect indrect = {{indoffset, indoffset}, indsize};
6779 [indicator_ setFrame:indrect];
6780
6781 CGSize prmsize = {215, indsize.height + 4};
6782 CGRect prmrect = {{
6783 indoffset * 2 + indsize.width,
6784 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6785 }, prmsize};
6786 [prompt_ setFrame:prmrect];
6787 }
6788
6789 - (void) setFrame:(CGRect)frame {
6790 [super setFrame:frame];
6791 [self positionViews];
6792 }
6793
6794 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6795 if ((self = [super initWithFrame:frame]) != nil) {
6796 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6797
6798 [self setBarStyle:UIBarStyleBlack];
6799
6800 UIBarStyle barstyle([self _barStyle:NO]);
6801 bool ugly(barstyle == UIBarStyleDefault);
6802
6803 UIProgressIndicatorStyle style = ugly ?
6804 UIProgressIndicatorStyleMediumBrown :
6805 UIProgressIndicatorStyleMediumWhite;
6806
6807 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6808 [(UIProgressIndicator *) indicator_ setStyle:style];
6809 [indicator_ startAnimation];
6810 [self addSubview:indicator_];
6811
6812 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6813 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6814 [prompt_ setBackgroundColor:[UIColor clearColor]];
6815 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6816 [self addSubview:prompt_];
6817
6818 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6819 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6820 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6821 [cancel_ setBarStyle:barstyle];
6822
6823 [self positionViews];
6824 } return self;
6825 }
6826
6827 - (void) setCancellable:(bool)cancellable {
6828 if (cancellable)
6829 [self addSubview:cancel_];
6830 else
6831 [cancel_ removeFromSuperview];
6832 }
6833
6834 - (void) start {
6835 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6836 }
6837
6838 - (void) stop {
6839 [self setCancellable:NO];
6840 }
6841
6842 - (void) setPrompt:(NSString *)prompt {
6843 [prompt_ setText:prompt];
6844 }
6845
6846 - (void) setProgress:(float)progress {
6847 }
6848
6849 @end
6850 /* }}} */
6851
6852 /* Cydia Navigation Controller Interface {{{ */
6853 @interface UINavigationController (Cydia)
6854
6855 - (NSArray *) navigationURLCollection;
6856 - (void) unloadData;
6857
6858 @end
6859 /* }}} */
6860
6861 /* Cydia Tab Bar Controller {{{ */
6862 @interface CYTabBarController : UITabBarController <
6863 UITabBarControllerDelegate,
6864 ProgressDelegate
6865 > {
6866 _transient Database *database_;
6867 _H<RefreshBar, 1> refreshbar_;
6868
6869 bool dropped_;
6870 bool updating_;
6871 // XXX: ok, "updatedelegate_"?...
6872 _transient NSObject<CydiaDelegate> *updatedelegate_;
6873
6874 _H<UIViewController> remembered_;
6875 _transient UIViewController *transient_;
6876 }
6877
6878 - (NSArray *) navigationURLCollection;
6879 - (void) dropBar:(BOOL)animated;
6880 - (void) beginUpdate;
6881 - (void) raiseBar:(BOOL)animated;
6882 - (BOOL) updating;
6883 - (void) unloadData;
6884
6885 @end
6886
6887 @implementation CYTabBarController
6888
6889 - (void) didReceiveMemoryWarning {
6890 [super didReceiveMemoryWarning];
6891
6892 // presenting a UINavigationController on 2.x does not update its transitionView
6893 // it thereby will not allow its topViewController to be unloaded by memory pressure
6894 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6895 UIViewController *selected([self selectedViewController]);
6896 for (UINavigationController *controller in [self viewControllers])
6897 if (controller != selected)
6898 if (UIViewController *top = [controller topViewController])
6899 [top unloadView];
6900 }
6901 }
6902
6903 - (void) setUnselectedViewController:(UIViewController *)transient {
6904 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6905 if (transient != nil) {
6906 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6907 [self setSelectedIndex:0];
6908 } return;
6909 }
6910
6911 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6912 if (transient != nil) {
6913 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6914 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6915 transient = navigation;
6916
6917 if (transient_ == nil)
6918 remembered_ = [controllers objectAtIndex:0];
6919 transient_ = transient;
6920 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6921 [controllers replaceObjectAtIndex:0 withObject:transient_];
6922 [self setSelectedIndex:0];
6923 [self setViewControllers:controllers];
6924 [self concealTabBarSelection];
6925 } else if (remembered_ != nil) {
6926 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6927 transient_ = transient;
6928 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6929 remembered_ = nil;
6930 [self setViewControllers:controllers];
6931 [self revealTabBarSelection];
6932 }
6933 }
6934
6935 - (UIViewController *) unselectedViewController {
6936 return transient_;
6937 }
6938
6939 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6940 if ([self unselectedViewController])
6941 [self setUnselectedViewController:nil];
6942
6943 // presenting a UINavigationController on 2.x does not update its transitionView
6944 // if this view was unloaded, the tranitionView may currently be presenting nothing
6945 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6946 UINavigationController *navigation((UINavigationController *) viewController);
6947 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6948 [navigation popViewControllerAnimated:NO];
6949 }
6950 }
6951
6952 - (NSArray *) navigationURLCollection {
6953 NSMutableArray *items([NSMutableArray array]);
6954
6955 // XXX: Should this deal with transient view controllers?
6956 for (id navigation in [self viewControllers]) {
6957 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6958 if (stack != nil)
6959 [items addObject:stack];
6960 }
6961
6962 return items;
6963 }
6964
6965 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6966 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6967 [self setUnselectedViewController:nil];
6968 else
6969 [super dismissModalViewControllerAnimated:YES];
6970 }
6971
6972 - (void) unloadData {
6973 [super unloadData];
6974
6975 for (UINavigationController *controller in [self viewControllers])
6976 [controller unloadData];
6977
6978 if (UIViewController *selected = [self selectedViewController])
6979 [selected reloadData];
6980
6981 if (UIViewController *unselected = [self unselectedViewController]) {
6982 [unselected unloadData];
6983 [unselected reloadData];
6984 }
6985 }
6986
6987 - (void) dealloc {
6988 [[NSNotificationCenter defaultCenter] removeObserver:self];
6989
6990 [super dealloc];
6991 }
6992
6993 - (id) initWithDatabase:(Database *)database {
6994 if ((self = [super init]) != nil) {
6995 database_ = database;
6996 [self setDelegate:self];
6997
6998 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6999 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7000
7001 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7002 } return self;
7003 }
7004
7005 - (void) setUpdate:(NSDate *)date {
7006 [self beginUpdate];
7007 }
7008
7009 - (void) beginUpdate {
7010 [(RefreshBar *) refreshbar_ start];
7011 [self dropBar:YES];
7012
7013 [updatedelegate_ retainNetworkActivityIndicator];
7014 updating_ = true;
7015
7016 [NSThread
7017 detachNewThreadSelector:@selector(performUpdate)
7018 toTarget:self
7019 withObject:nil
7020 ];
7021 }
7022
7023 - (void) performUpdate {
7024 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7025
7026 Status status;
7027 status.setDelegate(self);
7028 [database_ updateWithStatus:status];
7029
7030 [self
7031 performSelectorOnMainThread:@selector(completeUpdate)
7032 withObject:nil
7033 waitUntilDone:NO
7034 ];
7035
7036 [pool release];
7037 }
7038
7039 - (void) stopUpdateWithSelector:(SEL)selector {
7040 updating_ = false;
7041 [updatedelegate_ releaseNetworkActivityIndicator];
7042
7043 [self raiseBar:YES];
7044 [refreshbar_ stop];
7045
7046 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7047 }
7048
7049 - (void) completeUpdate {
7050 if (!updating_)
7051 return;
7052 [self stopUpdateWithSelector:@selector(reloadData)];
7053 }
7054
7055 - (void) cancelUpdate {
7056 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7057 }
7058
7059 - (void) cancelPressed {
7060 [self cancelUpdate];
7061 }
7062
7063 - (BOOL) updating {
7064 return updating_;
7065 }
7066
7067 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7068 [refreshbar_ setPrompt:[event compoundMessage]];
7069 }
7070
7071 - (bool) isProgressCancelled {
7072 return !updating_;
7073 }
7074
7075 - (void) setProgressCancellable:(NSNumber *)cancellable {
7076 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7077 }
7078
7079 - (void) setProgressPercent:(NSNumber *)percent {
7080 [refreshbar_ setProgress:[percent floatValue]];
7081 }
7082
7083 - (void) setProgressStatus:(NSDictionary *)status {
7084 if (status != nil)
7085 [self setProgressPercent:[status objectForKey:@"Percent"]];
7086 }
7087
7088 - (void) setUpdateDelegate:(id)delegate {
7089 updatedelegate_ = delegate;
7090 }
7091
7092 - (UIView *) transitionView {
7093 if ([self respondsToSelector:@selector(_transitionView)])
7094 return [self _transitionView];
7095 else
7096 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7097 }
7098
7099 - (void) dropBar:(BOOL)animated {
7100 if (dropped_)
7101 return;
7102 dropped_ = true;
7103
7104 UIView *transition([self transitionView]);
7105 [[self view] addSubview:refreshbar_];
7106
7107 CGRect barframe([refreshbar_ frame]);
7108
7109 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7110 barframe.origin.y = CYStatusBarHeight();
7111 else
7112 barframe.origin.y = 0;
7113
7114 [refreshbar_ setFrame:barframe];
7115
7116 if (animated)
7117 [UIView beginAnimations:nil context:NULL];
7118
7119 CGRect viewframe = [transition frame];
7120 viewframe.origin.y += barframe.size.height;
7121 viewframe.size.height -= barframe.size.height;
7122 [transition setFrame:viewframe];
7123
7124 if (animated)
7125 [UIView commitAnimations];
7126
7127 // Ensure bar has the proper width for our view, it might have changed
7128 barframe.size.width = viewframe.size.width;
7129 [refreshbar_ setFrame:barframe];
7130 }
7131
7132 - (void) raiseBar:(BOOL)animated {
7133 if (!dropped_)
7134 return;
7135 dropped_ = false;
7136
7137 UIView *transition([self transitionView]);
7138 [refreshbar_ removeFromSuperview];
7139
7140 CGRect barframe([refreshbar_ frame]);
7141
7142 if (animated)
7143 [UIView beginAnimations:nil context:NULL];
7144
7145 CGRect viewframe = [transition frame];
7146 viewframe.origin.y -= barframe.size.height;
7147 viewframe.size.height += barframe.size.height;
7148 [transition setFrame:viewframe];
7149
7150 if (animated)
7151 [UIView commitAnimations];
7152 }
7153
7154 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7155 bool dropped(dropped_);
7156
7157 if (dropped)
7158 [self raiseBar:NO];
7159
7160 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7161
7162 if (dropped)
7163 [self dropBar:NO];
7164 }
7165
7166 - (void) statusBarFrameChanged:(NSNotification *)notification {
7167 if (dropped_) {
7168 [self raiseBar:NO];
7169 [self dropBar:NO];
7170 }
7171 }
7172
7173 @end
7174 /* }}} */
7175
7176 /* Cydia Navigation Controller Implementation {{{ */
7177 @implementation UINavigationController (Cydia)
7178
7179 - (NSArray *) navigationURLCollection {
7180 NSMutableArray *stack([NSMutableArray array]);
7181
7182 for (CyteViewController *controller in [self viewControllers]) {
7183 NSString *url = [[controller navigationURL] absoluteString];
7184 if (url != nil)
7185 [stack addObject:url];
7186 }
7187
7188 return stack;
7189 }
7190
7191 - (void) reloadData {
7192 [super reloadData];
7193
7194 UIViewController *visible([self visibleViewController]);
7195 if (visible != nil)
7196 [visible reloadData];
7197
7198 // on the iPad, this view controller is ALSO visible. :(
7199 if (IsWildcat_)
7200 if (UIViewController *top = [self topViewController])
7201 if (top != visible)
7202 [top reloadData];
7203 }
7204
7205 - (void) unloadData {
7206 for (CyteViewController *page in [self viewControllers])
7207 [page unloadData];
7208
7209 [super unloadData];
7210 }
7211
7212 @end
7213 /* }}} */
7214
7215 /* Cydia:// Protocol {{{ */
7216 @interface CydiaURLProtocol : NSURLProtocol {
7217 }
7218
7219 @end
7220
7221 @implementation CydiaURLProtocol
7222
7223 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7224 NSURL *url([request URL]);
7225 if (url == nil)
7226 return NO;
7227
7228 NSString *scheme([[url scheme] lowercaseString]);
7229 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7230 return YES;
7231 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7232 return YES;
7233
7234 return NO;
7235 }
7236
7237 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7238 return request;
7239 }
7240
7241 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7242 id<NSURLProtocolClient> client([self client]);
7243 if (icon == nil)
7244 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7245 else {
7246 NSData *data(UIImagePNGRepresentation(icon));
7247
7248 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7249 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7250 [client URLProtocol:self didLoadData:data];
7251 [client URLProtocolDidFinishLoading:self];
7252 }
7253 }
7254
7255 - (void) startLoading {
7256 id<NSURLProtocolClient> client([self client]);
7257 NSURLRequest *request([self request]);
7258
7259 NSURL *url([request URL]);
7260 NSString *href([url absoluteString]);
7261 NSString *scheme([[url scheme] lowercaseString]);
7262
7263 NSString *path;
7264
7265 if ([scheme isEqualToString:@"cydia"])
7266 path = [href substringFromIndex:8];
7267 else if ([scheme isEqualToString:@"about"])
7268 path = [href substringFromIndex:12];
7269 else _assert(false);
7270
7271 NSRange slash([path rangeOfString:@"/"]);
7272
7273 NSString *command;
7274 if (slash.location == NSNotFound) {
7275 command = path;
7276 path = nil;
7277 } else {
7278 command = [path substringToIndex:slash.location];
7279 path = [path substringFromIndex:(slash.location + 1)];
7280 }
7281
7282 Database *database([Database sharedInstance]);
7283
7284 if ([command isEqualToString:@"package-icon"]) {
7285 if (path == nil)
7286 goto fail;
7287 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7288 Package *package([database packageWithName:path]);
7289 if (package == nil)
7290 goto fail;
7291 [package parse];
7292 UIImage *icon([package icon]);
7293 [self _returnPNGWithImage:icon forRequest:request];
7294 } else if ([command isEqualToString:@"uikit-image"]) {
7295 if (path == nil)
7296 goto fail;
7297 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7298 UIImage *icon(_UIImageWithName(path));
7299 [self _returnPNGWithImage:icon forRequest:request];
7300 } else if ([command isEqualToString:@"section-icon"]) {
7301 if (path == nil)
7302 goto fail;
7303 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7304 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7305 if (icon == nil)
7306 icon = [UIImage applicationImageNamed:@"unknown.png"];
7307 [self _returnPNGWithImage:icon forRequest:request];
7308 } else fail: {
7309 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7310 }
7311 }
7312
7313 - (void) stopLoading {
7314 }
7315
7316 @end
7317 /* }}} */
7318
7319 /* Section Controller {{{ */
7320 @interface SectionController : FilteredPackageListController {
7321 _H<IndirectDelegate, 1> indirect_;
7322 _H<CydiaObject> cydia_;
7323 _H<NSString> section_;
7324 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7325 }
7326
7327 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7328
7329 @end
7330
7331 @implementation SectionController
7332
7333 - (NSURL *) referrerURL {
7334 NSString *name = section_;
7335 if (name == nil)
7336 name = @"all";
7337
7338 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7339 }
7340
7341 - (NSURL *) navigationURL {
7342 NSString *name = section_;
7343 if (name == nil)
7344 name = @"all";
7345
7346 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7347 }
7348
7349 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7350 NSString *title;
7351 if (name == nil)
7352 title = UCLocalize("ALL_PACKAGES");
7353 else if (![name isEqual:@""])
7354 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7355 else
7356 title = UCLocalize("NO_SECTION");
7357
7358 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7359 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7360 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7361 section_ = name;
7362 } return self;
7363 }
7364
7365 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7366 return [super numberOfSectionsInTableView:list] + 1;
7367 }
7368
7369 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7370 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7371 }
7372
7373 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7374 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7375 }
7376
7377 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7378 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7379 }
7380
7381 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7382 if ([path section] != 0)
7383 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7384
7385 return promoted_[[path row]];
7386 }
7387
7388 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7389 if ([path section] != 0)
7390 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7391 }
7392
7393 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7394 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7395 return section == 0 ? 0 : section + 1;
7396 }
7397
7398 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7399 NSURL *url([request URL]);
7400 if (url == nil)
7401 return;
7402
7403 if ([frame isEqualToString:@"_open"])
7404 [delegate_ openURL:url];
7405 else {
7406 WebFrame *frame(nil);
7407 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7408 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7409 if (frame == nil)
7410 frame = [view mainFrame];
7411
7412 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7413
7414 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7415 [controller setDelegate:delegate_];
7416 [[self navigationController] pushViewController:controller animated:YES];
7417 }
7418
7419 [listener ignore];
7420 }
7421
7422 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7423 return [CydiaWebViewController requestWithHeaders:request];
7424 }
7425
7426 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7427 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7428 }
7429
7430 - (void) loadView {
7431 [super loadView];
7432
7433 // XXX: this code is horrible. I mean, wtf Jay?
7434 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7435 promoted_.resize(1);
7436
7437 for (unsigned i(0); i != promoted_.size(); ++i) {
7438 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7439 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7440 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7441 ]]
7442
7443 cachePolicy:NSURLRequestUseProtocolCachePolicy
7444 timeoutInterval:120
7445 ]]);
7446
7447 [promoted setDelegate:self];
7448 promoted_[i] = promoted;
7449 }
7450 }
7451 }
7452
7453 - (void) setDelegate:(id)delegate {
7454 [super setDelegate:delegate];
7455 [cydia_ setDelegate:delegate];
7456 }
7457
7458 - (void) releaseSubviews {
7459 promoted_.clear();
7460 [super releaseSubviews];
7461 }
7462
7463 @end
7464 /* }}} */
7465 /* Sections Controller {{{ */
7466 @interface SectionsController : CyteViewController <
7467 UITableViewDataSource,
7468 UITableViewDelegate
7469 > {
7470 _transient Database *database_;
7471 _H<NSMutableArray> sections_;
7472 _H<NSMutableArray> filtered_;
7473 _H<UITableView, 2> list_;
7474 }
7475
7476 - (id) initWithDatabase:(Database *)database;
7477 - (void) editButtonClicked;
7478
7479 @end
7480
7481 @implementation SectionsController
7482
7483 - (NSURL *) navigationURL {
7484 return [NSURL URLWithString:@"cydia://sections"];
7485 }
7486
7487 - (void) updateNavigationItem {
7488 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7489 if ([sections_ count] == 0) {
7490 [[self navigationItem] setRightBarButtonItem:nil];
7491 } else {
7492 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7493 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7494 target:self
7495 action:@selector(editButtonClicked)
7496 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7497 }
7498 }
7499
7500 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7501 [super setEditing:editing animated:animated];
7502
7503 if (editing)
7504 [list_ reloadData];
7505 else
7506 [delegate_ updateData];
7507
7508 [self updateNavigationItem];
7509 }
7510
7511 - (void) viewDidAppear:(BOOL)animated {
7512 [super viewDidAppear:animated];
7513 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7514 }
7515
7516 - (void) viewWillDisappear:(BOOL)animated {
7517 [super viewWillDisappear:animated];
7518 [self setEditing:NO];
7519 }
7520
7521 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7522 Section *section = nil;
7523 int index = [indexPath row];
7524 if (![self isEditing]) {
7525 index -= 1;
7526 if (index >= 0)
7527 section = [filtered_ objectAtIndex:index];
7528 } else {
7529 section = [sections_ objectAtIndex:index];
7530 }
7531 return section;
7532 }
7533
7534 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7535 if ([self isEditing])
7536 return [sections_ count];
7537 else
7538 return [filtered_ count] + 1;
7539 }
7540
7541 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7542 return 45.0f;
7543 }*/
7544
7545 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7546 static NSString *reuseIdentifier = @"SectionCell";
7547
7548 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7549 if (cell == nil)
7550 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7551
7552 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7553
7554 return cell;
7555 }
7556
7557 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7558 if ([self isEditing])
7559 return;
7560
7561 Section *section = [self sectionAtIndexPath:indexPath];
7562
7563 SectionController *controller = [[[SectionController alloc]
7564 initWithDatabase:database_
7565 section:[section name]
7566 ] autorelease];
7567 [controller setDelegate:delegate_];
7568
7569 [[self navigationController] pushViewController:controller animated:YES];
7570 }
7571
7572 - (void) loadView {
7573 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7574 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7575 [list_ setRowHeight:45.0f];
7576 [(UITableView *) list_ setDataSource:self];
7577 [list_ setDelegate:self];
7578 [self setView:list_];
7579 }
7580
7581 - (void) viewDidLoad {
7582 [super viewDidLoad];
7583
7584 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7585 }
7586
7587 - (void) releaseSubviews {
7588 list_ = nil;
7589
7590 sections_ = nil;
7591 filtered_ = nil;
7592
7593 [super releaseSubviews];
7594 }
7595
7596 - (id) initWithDatabase:(Database *)database {
7597 if ((self = [super init]) != nil) {
7598 database_ = database;
7599 } return self;
7600 }
7601
7602 - (void) reloadData {
7603 [super reloadData];
7604
7605 NSArray *packages = [database_ packages];
7606
7607 sections_ = [NSMutableArray arrayWithCapacity:16];
7608 filtered_ = [NSMutableArray arrayWithCapacity:16];
7609
7610 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7611
7612 _trace();
7613 for (Package *package in packages) {
7614 NSString *name([package section]);
7615 NSString *key(name == nil ? @"" : name);
7616
7617 Section *section;
7618
7619 _profile(SectionsView$reloadData$Section)
7620 section = [sections objectForKey:key];
7621 if (section == nil) {
7622 _profile(SectionsView$reloadData$Section$Allocate)
7623 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7624 [sections setObject:section forKey:key];
7625 _end
7626 }
7627 _end
7628
7629 [section addToCount];
7630
7631 _profile(SectionsView$reloadData$Filter)
7632 if (![package valid] || ![package visible])
7633 continue;
7634 _end
7635
7636 [section addToRow];
7637 }
7638 _trace();
7639
7640 [sections_ addObjectsFromArray:[sections allValues]];
7641
7642 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7643
7644 for (Section *section in (id) sections_) {
7645 size_t count([section row]);
7646 if (count == 0)
7647 continue;
7648
7649 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7650 [section setCount:count];
7651 [filtered_ addObject:section];
7652 }
7653
7654 [self updateNavigationItem];
7655 [list_ reloadData];
7656 _trace();
7657 }
7658
7659 - (void) editButtonClicked {
7660 [self setEditing:![self isEditing] animated:YES];
7661 }
7662
7663 @end
7664 /* }}} */
7665
7666 /* Changes Controller {{{ */
7667 @interface ChangesController : CyteViewController <
7668 CyteWebViewDelegate,
7669 UITableViewDataSource,
7670 UITableViewDelegate
7671 > {
7672 _transient Database *database_;
7673 unsigned era_;
7674 _H<NSMutableArray> packages_;
7675 _H<NSMutableArray> sections_;
7676 _H<UITableView, 2> list_;
7677 _H<CyteWebView, 1> dickbar_;
7678 unsigned upgrades_;
7679 _H<IndirectDelegate, 1> indirect_;
7680 _H<CydiaObject> cydia_;
7681 }
7682
7683 - (id) initWithDatabase:(Database *)database;
7684
7685 @end
7686
7687 @implementation ChangesController
7688
7689 - (NSURL *) navigationURL {
7690 return [NSURL URLWithString:@"cydia://changes"];
7691 }
7692
7693 - (void) viewDidAppear:(BOOL)animated {
7694 [super viewDidAppear:animated];
7695 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7696 }
7697
7698 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7699 NSInteger count([sections_ count]);
7700 return count == 0 ? 1 : count;
7701 }
7702
7703 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7704 if ([sections_ count] == 0)
7705 return nil;
7706 return [[sections_ objectAtIndex:section] name];
7707 }
7708
7709 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7710 if ([sections_ count] == 0)
7711 return 0;
7712 return [[sections_ objectAtIndex:section] count];
7713 }
7714
7715 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7716 @synchronized (database_) {
7717 if ([database_ era] != era_)
7718 return nil;
7719
7720 NSUInteger sectionIndex([path section]);
7721 if (sectionIndex >= [sections_ count])
7722 return nil;
7723 Section *section([sections_ objectAtIndex:sectionIndex]);
7724 NSInteger row([path row]);
7725 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7726 } }
7727
7728 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7729 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7730 if (cell == nil)
7731 cell = [[[PackageCell alloc] init] autorelease];
7732
7733 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7734 [cell setPackage:package asSummary:false];
7735 return cell;
7736 }
7737
7738 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7739 Package *package([self packageAtIndexPath:path]);
7740 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7741 [view setDelegate:delegate_];
7742 [[self navigationController] pushViewController:view animated:YES];
7743 return path;
7744 }
7745
7746 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7747 NSString *context([alert context]);
7748
7749 if ([context isEqualToString:@"norefresh"])
7750 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7751 }
7752
7753 - (void) refreshButtonClicked {
7754 if (IsReachable("cydia.saurik.com")) {
7755 [delegate_ beginUpdate];
7756 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7757 } else {
7758 UIAlertView *alert = [[[UIAlertView alloc]
7759 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7760 message:@"Host Unreachable" // XXX: Localize
7761 delegate:self
7762 cancelButtonTitle:UCLocalize("OK")
7763 otherButtonTitles:nil
7764 ] autorelease];
7765
7766 [alert setContext:@"norefresh"];
7767 [alert show];
7768 }
7769 }
7770
7771 - (void) upgradeButtonClicked {
7772 [delegate_ distUpgrade];
7773 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7774 }
7775
7776 - (void) loadView {
7777 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7778 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7779 [self setView:view];
7780
7781 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7782 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7783 [list_ setRowHeight:73];
7784 [(UITableView *) list_ setDataSource:self];
7785 [list_ setDelegate:self];
7786 [view addSubview:list_];
7787
7788 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7789 CGRect dickframe([view bounds]);
7790 dickframe.size.height = 44;
7791
7792 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7793 [dickbar_ setDelegate:self];
7794 [view addSubview:dickbar_];
7795
7796 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7797 [dickbar_ setScalesPageToFit:YES];
7798
7799 UIWebDocumentView *document([dickbar_ _documentView]);
7800 [document setBackgroundColor:[UIColor clearColor]];
7801 [document setDrawsBackground:NO];
7802
7803 WebView *webview([document webView]);
7804 [webview setShouldUpdateWhileOffscreen:NO];
7805
7806 UIScrollView *scroller([dickbar_ scrollView]);
7807 [scroller setScrollingEnabled:NO];
7808 [scroller setFixedBackgroundPattern:YES];
7809 [scroller setBackgroundColor:[UIColor clearColor]];
7810
7811 WebPreferences *preferences([webview preferences]);
7812 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7813 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7814 [preferences setOfflineWebApplicationCacheEnabled:YES];
7815
7816 [dickbar_ loadRequest:[NSURLRequest
7817 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7818 cachePolicy:NSURLRequestUseProtocolCachePolicy
7819 timeoutInterval:120
7820 ]];
7821
7822 UIEdgeInsets inset = {44, 0, 0, 0};
7823 [list_ setContentInset:inset];
7824
7825 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7826 }
7827 }
7828
7829 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7830 NSURL *url([request URL]);
7831 if (url == nil)
7832 return;
7833
7834 if ([frame isEqualToString:@"_open"])
7835 [delegate_ openURL:url];
7836 else {
7837 WebFrame *frame(nil);
7838 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7839 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7840 if (frame == nil)
7841 frame = [view mainFrame];
7842
7843 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7844
7845 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7846 [controller setDelegate:delegate_];
7847 [[self navigationController] pushViewController:controller animated:YES];
7848 }
7849
7850 [listener ignore];
7851 }
7852
7853 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7854 return [CydiaWebViewController requestWithHeaders:request];
7855 }
7856
7857 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7858 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7859 }
7860
7861 - (void) setDelegate:(id)delegate {
7862 [super setDelegate:delegate];
7863 [cydia_ setDelegate:delegate];
7864 }
7865
7866 - (void) viewDidLoad {
7867 [super viewDidLoad];
7868
7869 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7870 }
7871
7872 - (void) releaseSubviews {
7873 list_ = nil;
7874
7875 packages_ = nil;
7876 sections_ = nil;
7877 dickbar_ = nil;
7878
7879 [super releaseSubviews];
7880 }
7881
7882 - (id) initWithDatabase:(Database *)database {
7883 if ((self = [super init]) != nil) {
7884 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7885 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7886 database_ = database;
7887 } return self;
7888 }
7889
7890 - (NSMutableArray *) _reloadPackages {
7891 @synchronized (database_) {
7892 era_ = [database_ era];
7893 NSArray *packages([database_ packages]);
7894
7895 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7896
7897 _trace();
7898 _profile(ChangesController$_reloadPackages$Filter)
7899 for (Package *package in packages)
7900 if ([package upgradableAndEssential:YES] || [package visible])
7901 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7902 _end
7903 _trace();
7904 _profile(ChangesController$_reloadPackages$radixSort)
7905 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7906 _end
7907 _trace();
7908
7909 return filtered;
7910 } }
7911
7912 - (void) _reloadData {
7913 NSMutableArray *packages;
7914
7915 reload:
7916 if (true) {
7917 UIProgressHUD *hud([delegate_ addProgressHUD]);
7918 [hud setText:UCLocalize("LOADING")];
7919 //NSLog(@"HUD:%@::%@", delegate_, hud);
7920 packages = [self yieldToSelector:@selector(_reloadPackages)];
7921 [delegate_ removeProgressHUD:hud];
7922 } else {
7923 packages = [self _reloadPackages];
7924 }
7925
7926 @synchronized (database_) {
7927 if (era_ != [database_ era])
7928 goto reload;
7929
7930 packages_ = packages;
7931 sections_ = [NSMutableArray arrayWithCapacity:16];
7932
7933 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7934 Section *ignored = nil;
7935 Section *section = nil;
7936 time_t last = 0;
7937
7938 upgrades_ = 0;
7939 bool unseens = false;
7940
7941 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7942
7943 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7944 Package *package = [packages_ objectAtIndex:offset];
7945
7946 BOOL uae = [package upgradableAndEssential:YES];
7947
7948 if (!uae) {
7949 unseens = true;
7950 time_t seen([package seen]);
7951
7952 if (section == nil || last != seen) {
7953 last = seen;
7954
7955 NSString *name;
7956 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7957 [name autorelease];
7958
7959 _profile(ChangesController$reloadData$Allocate)
7960 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7961 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7962 [sections_ addObject:section];
7963 _end
7964 }
7965
7966 [section addToCount];
7967 } else if ([package ignored]) {
7968 if (ignored == nil) {
7969 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7970 }
7971 [ignored addToCount];
7972 } else {
7973 ++upgrades_;
7974 [upgradable addToCount];
7975 }
7976 }
7977 _trace();
7978
7979 CFRelease(formatter);
7980
7981 if (unseens) {
7982 Section *last = [sections_ lastObject];
7983 size_t count = [last count];
7984 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7985 [sections_ removeLastObject];
7986 }
7987
7988 if ([ignored count] != 0)
7989 [sections_ insertObject:ignored atIndex:0];
7990 if (upgrades_ != 0)
7991 [sections_ insertObject:upgradable atIndex:0];
7992
7993 [list_ reloadData];
7994
7995 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7996 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7997 style:UIBarButtonItemStylePlain
7998 target:self
7999 action:@selector(upgradeButtonClicked)
8000 ] autorelease]) animated:YES];
8001
8002 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
8003 initWithTitle:UCLocalize("REFRESH")
8004 style:UIBarButtonItemStylePlain
8005 target:self
8006 action:@selector(refreshButtonClicked)
8007 ] autorelease]) animated:YES];
8008
8009 PrintTimes();
8010 } }
8011
8012 - (void) reloadData {
8013 [super reloadData];
8014 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8015 }
8016
8017 @end
8018 /* }}} */
8019 /* Search Controller {{{ */
8020 @interface SearchController : FilteredPackageListController <
8021 UISearchBarDelegate
8022 > {
8023 _H<UISearchBar, 1> search_;
8024 BOOL searchloaded_;
8025 }
8026
8027 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8028 - (void) reloadData;
8029
8030 @end
8031
8032 @implementation SearchController
8033
8034 - (NSURL *) referrerURL {
8035 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8036 }
8037
8038 - (NSURL *) navigationURL {
8039 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8040 return [NSURL URLWithString:@"cydia://search"];
8041 else
8042 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8043 }
8044
8045 - (NSArray *) termsForQuery:(NSString *)query {
8046 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8047 for (NSString *component in [query componentsSeparatedByString:@" "])
8048 if ([component length] != 0)
8049 [terms addObject:component];
8050
8051 return terms;
8052 }
8053
8054 - (void) useSearch {
8055 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8056 [self clearData];
8057 [self reloadData];
8058 }
8059
8060 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8061 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8062 [self clearData];
8063 [self reloadData];
8064 }
8065
8066 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8067 [search_ resignFirstResponder];
8068 [self useSearch];
8069 }
8070
8071 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8072 [search_ setText:@""];
8073 [self searchBarButtonClicked:searchBar];
8074 }
8075
8076 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8077 [self searchBarButtonClicked:searchBar];
8078 }
8079
8080 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8081 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8082 [self reloadData];
8083 }
8084
8085 - (bool) shouldYield {
8086 return YES;
8087 }
8088
8089 - (bool) shouldBlock {
8090 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8091 }
8092
8093 - (bool) isSummarized {
8094 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8095 }
8096
8097 - (bool) showsSections {
8098 return false;
8099 }
8100
8101 - (NSMutableArray *) _reloadPackages {
8102 NSMutableArray *packages([super _reloadPackages]);
8103 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8104 [packages radixSortUsingSelector:@selector(rank)];
8105 return packages;
8106 }
8107
8108 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8109 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8110 search_ = [[[UISearchBar alloc] init] autorelease];
8111 [search_ setDelegate:self];
8112
8113 if (query != nil)
8114 [search_ setText:query];
8115 } return self;
8116 }
8117
8118 - (void) viewDidAppear:(BOOL)animated {
8119 [super viewDidAppear:animated];
8120
8121 if (!searchloaded_) {
8122 searchloaded_ = YES;
8123 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8124 [search_ layoutSubviews];
8125 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8126
8127 UITextField *textField;
8128 if ([search_ respondsToSelector:@selector(searchField)])
8129 textField = [search_ searchField];
8130 else
8131 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8132
8133 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8134 [textField setEnablesReturnKeyAutomatically:NO];
8135 [[self navigationItem] setTitleView:textField];
8136 }
8137
8138 if ([self isSummarized])
8139 [search_ becomeFirstResponder];
8140 }
8141
8142 - (void) reloadData {
8143 id object([search_ text]);
8144 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8145 object = [self termsForQuery:object];
8146
8147 [self setObject:object];
8148 [self resetCursor];
8149
8150 [super reloadData];
8151 }
8152
8153 - (void) didSelectPackage:(Package *)package {
8154 [search_ resignFirstResponder];
8155 [super didSelectPackage:package];
8156 }
8157
8158 @end
8159 /* }}} */
8160 /* Package Settings Controller {{{ */
8161 @interface PackageSettingsController : CyteViewController <
8162 UITableViewDataSource,
8163 UITableViewDelegate
8164 > {
8165 _transient Database *database_;
8166 _H<NSString> name_;
8167 _H<Package> package_;
8168 _H<UITableView, 2> table_;
8169 _H<UISwitch> subscribedSwitch_;
8170 _H<UISwitch> ignoredSwitch_;
8171 _H<UITableViewCell> subscribedCell_;
8172 _H<UITableViewCell> ignoredCell_;
8173 }
8174
8175 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8176
8177 @end
8178
8179 @implementation PackageSettingsController
8180
8181 - (NSURL *) navigationURL {
8182 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8183 }
8184
8185 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8186 if (package_ == nil)
8187 return 0;
8188
8189 if ([package_ installed] == nil)
8190 return 1;
8191 else
8192 return 2;
8193 }
8194
8195 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8196 if (package_ == nil)
8197 return 0;
8198
8199 // both sections contain just one item right now.
8200 return 1;
8201 }
8202
8203 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8204 return nil;
8205 }
8206
8207 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8208 if (section == 0)
8209 return UCLocalize("SHOW_ALL_CHANGES_EX");
8210 else
8211 return UCLocalize("IGNORE_UPGRADES_EX");
8212 }
8213
8214 - (void) onSubscribed:(id)control {
8215 bool value([control isOn]);
8216 if (package_ == nil)
8217 return;
8218 if ([package_ setSubscribed:value])
8219 [delegate_ updateData];
8220 }
8221
8222 - (void) _updateIgnored {
8223 const char *package([name_ UTF8String]);
8224 bool on([ignoredSwitch_ isOn]);
8225
8226 pid_t pid(ExecFork());
8227 if (pid == 0) {
8228 FILE *dpkg(popen("dpkg --set-selections", "w"));
8229 fwrite(package, strlen(package), 1, dpkg);
8230
8231 if (on)
8232 fwrite(" hold\n", 6, 1, dpkg);
8233 else
8234 fwrite(" install\n", 9, 1, dpkg);
8235
8236 pclose(dpkg);
8237
8238 exit(0);
8239 _assert(false);
8240 }
8241
8242 ReapZombie(pid);
8243 }
8244
8245 - (void) onIgnored:(id)control {
8246 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8247 [invocation setTarget:self];
8248 [invocation setSelector:@selector(_updateIgnored)];
8249
8250 [delegate_ reloadDataWithInvocation:invocation];
8251 }
8252
8253 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8254 if (package_ == nil)
8255 return nil;
8256
8257 switch ([indexPath section]) {
8258 case 0: return subscribedCell_;
8259 case 1: return ignoredCell_;
8260
8261 _nodefault
8262 }
8263
8264 return nil;
8265 }
8266
8267 - (void) loadView {
8268 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8269 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8270 [self setView:view];
8271
8272 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8273 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8274 [(UITableView *) table_ setDataSource:self];
8275 [table_ setDelegate:self];
8276 [view addSubview:table_];
8277
8278 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8279 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8280 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8281
8282 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8283 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8284 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8285
8286 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8287 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8288 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8289 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8290
8291 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8292 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8293 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8294 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8295 }
8296
8297 - (void) viewDidLoad {
8298 [super viewDidLoad];
8299
8300 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8301 }
8302
8303 - (void) releaseSubviews {
8304 ignoredCell_ = nil;
8305 subscribedCell_ = nil;
8306 table_ = nil;
8307 ignoredSwitch_ = nil;
8308 subscribedSwitch_ = nil;
8309
8310 [super releaseSubviews];
8311 }
8312
8313 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8314 if ((self = [super init]) != nil) {
8315 database_ = database;
8316 name_ = package;
8317 } return self;
8318 }
8319
8320 - (void) reloadData {
8321 [super reloadData];
8322
8323 package_ = [database_ packageWithName:name_];
8324
8325 if (package_ != nil) {
8326 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8327 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8328 } // XXX: what now, G?
8329
8330 [table_ reloadData];
8331 }
8332
8333 @end
8334 /* }}} */
8335
8336 /* Installed Controller {{{ */
8337 @interface InstalledController : FilteredPackageListController {
8338 BOOL expert_;
8339 }
8340
8341 - (id) initWithDatabase:(Database *)database;
8342
8343 - (void) updateRoleButton;
8344 - (void) queueStatusDidChange;
8345
8346 @end
8347
8348 @implementation InstalledController
8349
8350 - (NSURL *) referrerURL {
8351 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8352 }
8353
8354 - (NSURL *) navigationURL {
8355 return [NSURL URLWithString:@"cydia://installed"];
8356 }
8357
8358 - (id) initWithDatabase:(Database *)database {
8359 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8360 [self updateRoleButton];
8361 [self queueStatusDidChange];
8362 } return self;
8363 }
8364
8365 #if !AlwaysReload
8366 - (void) queueButtonClicked {
8367 [delegate_ queue];
8368 }
8369 #endif
8370
8371 - (void) queueStatusDidChange {
8372 #if !AlwaysReload
8373 if (IsWildcat_) {
8374 if (Queuing_) {
8375 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8376 initWithTitle:UCLocalize("QUEUE")
8377 style:UIBarButtonItemStyleDone
8378 target:self
8379 action:@selector(queueButtonClicked)
8380 ] autorelease]];
8381 } else {
8382 [[self navigationItem] setLeftBarButtonItem:nil];
8383 }
8384 }
8385 #endif
8386 }
8387
8388 - (void) updateRoleButton {
8389 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8390 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8391 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8392 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8393 target:self
8394 action:@selector(roleButtonClicked)
8395 ] autorelease]];
8396 }
8397
8398 - (void) roleButtonClicked {
8399 [self setObject:[NSNumber numberWithBool:expert_]];
8400 [self reloadData];
8401 expert_ = !expert_;
8402
8403 [self updateRoleButton];
8404 }
8405
8406 @end
8407 /* }}} */
8408
8409 /* Source Cell {{{ */
8410 @interface SourceCell : CyteTableViewCell <
8411 CyteTableViewCellDelegate
8412 > {
8413 _H<NSURL> url_;
8414 _H<UIImage> icon_;
8415 _H<NSString> origin_;
8416 _H<NSString> label_;
8417 }
8418
8419 - (void) setSource:(Source *)source;
8420
8421 @end
8422
8423 @implementation SourceCell
8424
8425 - (void) _setImage:(NSArray *)data {
8426 if ([url_ isEqual:[data objectAtIndex:0]]) {
8427 icon_ = [data objectAtIndex:1];
8428 [content_ setNeedsDisplay];
8429 }
8430 }
8431
8432 - (void) _setSource:(NSURL *) url {
8433 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8434
8435 if (NSData *data = [NSURLConnection
8436 sendSynchronousRequest:[NSURLRequest
8437 requestWithURL:url
8438 cachePolicy:NSURLRequestUseProtocolCachePolicy
8439 timeoutInterval:10
8440 ]
8441
8442 returningResponse:NULL
8443 error:NULL
8444 ])
8445 if (UIImage *image = [UIImage imageWithData:data])
8446 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8447
8448 [pool release];
8449 }
8450
8451 - (void) setSource:(Source *)source {
8452 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8453
8454 origin_ = [source name];
8455 label_ = [source rooturi];
8456
8457 [content_ setNeedsDisplay];
8458
8459 url_ = [source iconURL];
8460 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8461 }
8462
8463 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8464 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8465 UIView *content([self contentView]);
8466 CGRect bounds([content bounds]);
8467
8468 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8469 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8470 [content_ setBackgroundColor:[UIColor whiteColor]];
8471 [content addSubview:content_];
8472
8473 [content_ setDelegate:self];
8474 [content_ setOpaque:YES];
8475
8476 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8477 } return self;
8478 }
8479
8480 - (NSString *) accessibilityLabel {
8481 return label_;
8482 }
8483
8484 - (void) drawContentRect:(CGRect)rect {
8485 bool highlighted(highlighted_);
8486 float width(rect.size.width);
8487
8488 if (icon_ != nil) {
8489 CGRect rect;
8490 rect.size = [(UIImage *) icon_ size];
8491
8492 while (rect.size.width > 32 || rect.size.height > 32) {
8493 rect.size.width /= 2;
8494 rect.size.height /= 2;
8495 }
8496
8497 rect.origin.x = 25 - rect.size.width / 2;
8498 rect.origin.y = 25 - rect.size.height / 2;
8499
8500 [icon_ drawInRect:rect];
8501 }
8502
8503 if (highlighted)
8504 UISetColor(White_);
8505
8506 if (!highlighted)
8507 UISetColor(Black_);
8508 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8509
8510 if (!highlighted)
8511 UISetColor(Gray_);
8512 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8513 }
8514
8515 @end
8516 /* }}} */
8517 /* Source Controller {{{ */
8518 @interface SourceController : FilteredPackageListController {
8519 _transient Source *source_;
8520 _H<NSString> key_;
8521 }
8522
8523 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8524
8525 @end
8526
8527 @implementation SourceController
8528
8529 - (NSURL *) referrerURL {
8530 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8531 }
8532
8533 - (NSURL *) navigationURL {
8534 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8535 }
8536
8537 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8538 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8539 source_ = source;
8540 key_ = [source key];
8541 } return self;
8542 }
8543
8544 - (void) reloadData {
8545 source_ = [database_ sourceWithKey:key_];
8546 key_ = [source_ key];
8547 [self setObject:source_];
8548
8549 [[self navigationItem] setTitle:[source_ label]];
8550
8551 [super reloadData];
8552 }
8553
8554 @end
8555 /* }}} */
8556 /* Sources Controller {{{ */
8557 @interface SourcesController : CyteViewController <
8558 UITableViewDataSource,
8559 UITableViewDelegate
8560 > {
8561 _transient Database *database_;
8562 unsigned era_;
8563
8564 _H<UITableView, 2> list_;
8565 _H<NSMutableArray> sources_;
8566 int offset_;
8567
8568 _H<NSString> href_;
8569 _H<UIProgressHUD> hud_;
8570 _H<NSError> error_;
8571
8572 //NSURLConnection *installer_;
8573 NSURLConnection *trivial_bz2_;
8574 NSURLConnection *trivial_gz_;
8575 //NSURLConnection *automatic_;
8576
8577 BOOL cydia_;
8578 }
8579
8580 - (id) initWithDatabase:(Database *)database;
8581 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8582
8583 @end
8584
8585 @implementation SourcesController
8586
8587 - (void) _releaseConnection:(NSURLConnection *)connection {
8588 if (connection != nil) {
8589 [connection cancel];
8590 //[connection setDelegate:nil];
8591 [connection release];
8592 }
8593 }
8594
8595 - (void) dealloc {
8596 //[self _releaseConnection:installer_];
8597 [self _releaseConnection:trivial_gz_];
8598 [self _releaseConnection:trivial_bz2_];
8599 //[self _releaseConnection:automatic_];
8600
8601 [super dealloc];
8602 }
8603
8604 - (NSURL *) navigationURL {
8605 return [NSURL URLWithString:@"cydia://sources"];
8606 }
8607
8608 - (void) viewDidAppear:(BOOL)animated {
8609 [super viewDidAppear:animated];
8610 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8611 }
8612
8613 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8614 return 1;
8615 }
8616
8617 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8618 return nil;
8619 }
8620
8621 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8622 return [sources_ count];
8623 }
8624
8625 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8626 @synchronized (database_) {
8627 if ([database_ era] != era_)
8628 return nil;
8629
8630 NSUInteger index([indexPath row]);
8631 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8632 } }
8633
8634 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8635 static NSString *cellIdentifier = @"SourceCell";
8636
8637 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8638 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8639 [cell setSource:[self sourceAtIndexPath:indexPath]];
8640 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8641
8642 return cell;
8643 }
8644
8645 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8646 Source *source = [self sourceAtIndexPath:indexPath];
8647 if (source == nil) return;
8648
8649 SourceController *controller = [[[SourceController alloc]
8650 initWithDatabase:database_
8651 source:source
8652 ] autorelease];
8653
8654 [controller setDelegate:delegate_];
8655
8656 [[self navigationController] pushViewController:controller animated:YES];
8657 }
8658
8659 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8660 Source *source = [self sourceAtIndexPath:indexPath];
8661 return [source record] != nil;
8662 }
8663
8664 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8665 if (editingStyle == UITableViewCellEditingStyleDelete) {
8666 Source *source = [self sourceAtIndexPath:indexPath];
8667 if (source == nil) return;
8668
8669 [Sources_ removeObjectForKey:[source key]];
8670 Changed_ = true;
8671
8672 [delegate_ _saveConfig];
8673 [delegate_ reloadDataWithInvocation:nil];
8674 }
8675 }
8676
8677 - (void) complete {
8678 [delegate_ addTrivialSource:href_];
8679 href_ = nil;
8680
8681 [delegate_ syncData];
8682 }
8683
8684 - (NSString *) getWarning {
8685 NSString *href(href_);
8686 NSRange colon([href rangeOfString:@"://"]);
8687 if (colon.location != NSNotFound)
8688 href = [href substringFromIndex:(colon.location + 3)];
8689 href = [href stringByAddingPercentEscapes];
8690 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8691
8692 NSURL *url([NSURL URLWithString:href]);
8693
8694 NSStringEncoding encoding;
8695 NSError *error(nil);
8696
8697 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8698 return [warning length] == 0 ? nil : warning;
8699 return nil;
8700 }
8701
8702 - (void) _endConnection:(NSURLConnection *)connection {
8703 // XXX: the memory management in this method is horribly awkward
8704
8705 NSURLConnection **field = NULL;
8706 if (connection == trivial_bz2_)
8707 field = &trivial_bz2_;
8708 else if (connection == trivial_gz_)
8709 field = &trivial_gz_;
8710 _assert(field != NULL);
8711 [connection release];
8712 *field = nil;
8713
8714 if (
8715 trivial_bz2_ == nil &&
8716 trivial_gz_ == nil
8717 ) {
8718 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8719
8720 [delegate_ releaseNetworkActivityIndicator];
8721
8722 [delegate_ removeProgressHUD:hud_];
8723 hud_ = nil;
8724
8725 if (cydia_) {
8726 if (warning != nil) {
8727 UIAlertView *alert = [[[UIAlertView alloc]
8728 initWithTitle:UCLocalize("SOURCE_WARNING")
8729 message:warning
8730 delegate:self
8731 cancelButtonTitle:UCLocalize("CANCEL")
8732 otherButtonTitles:
8733 UCLocalize("ADD_ANYWAY"),
8734 nil
8735 ] autorelease];
8736
8737 [alert setContext:@"warning"];
8738 [alert setNumberOfRows:1];
8739 [alert show];
8740
8741 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8742 error_ = nil;
8743 return;
8744 }
8745
8746 [self complete];
8747 } else if (error_ != nil) {
8748 UIAlertView *alert = [[[UIAlertView alloc]
8749 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8750 message:[error_ localizedDescription]
8751 delegate:self
8752 cancelButtonTitle:UCLocalize("OK")
8753 otherButtonTitles:nil
8754 ] autorelease];
8755
8756 [alert setContext:@"urlerror"];
8757 [alert show];
8758
8759 href_ = nil;
8760 } else {
8761 UIAlertView *alert = [[[UIAlertView alloc]
8762 initWithTitle:UCLocalize("NOT_REPOSITORY")
8763 message:UCLocalize("NOT_REPOSITORY_EX")
8764 delegate:self
8765 cancelButtonTitle:UCLocalize("OK")
8766 otherButtonTitles:nil
8767 ] autorelease];
8768
8769 [alert setContext:@"trivial"];
8770 [alert show];
8771
8772 href_ = nil;
8773 }
8774
8775 error_ = nil;
8776 }
8777 }
8778
8779 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8780 switch ([response statusCode]) {
8781 case 200:
8782 cydia_ = YES;
8783 }
8784 }
8785
8786 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8787 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8788 error_ = error;
8789 [self _endConnection:connection];
8790 }
8791
8792 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8793 [self _endConnection:connection];
8794 }
8795
8796 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8797 NSURL *url([NSURL URLWithString:href]);
8798
8799 NSMutableURLRequest *request = [NSMutableURLRequest
8800 requestWithURL:url
8801 cachePolicy:NSURLRequestUseProtocolCachePolicy
8802 timeoutInterval:10
8803 ];
8804
8805 [request setHTTPMethod:method];
8806
8807 if (Machine_ != NULL)
8808 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8809
8810 if (UniqueID_ != nil)
8811 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8812
8813 if ([url isCydiaSecure]) {
8814 if (UniqueID_ != nil)
8815 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8816 }
8817
8818 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8819 }
8820
8821 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8822 NSString *context([alert context]);
8823
8824 if ([context isEqualToString:@"source"]) {
8825 switch (button) {
8826 case 1: {
8827 NSString *href = [[alert textField] text];
8828
8829 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8830
8831 if (![href hasSuffix:@"/"])
8832 href_ = [href stringByAppendingString:@"/"];
8833 else
8834 href_ = href;
8835
8836 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8837 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8838 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8839
8840 cydia_ = false;
8841
8842 // XXX: this is stupid
8843 hud_ = [delegate_ addProgressHUD];
8844 [hud_ setText:UCLocalize("VERIFYING_URL")];
8845 [delegate_ retainNetworkActivityIndicator];
8846 } break;
8847
8848 case 0:
8849 break;
8850
8851 _nodefault
8852 }
8853
8854 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8855 } else if ([context isEqualToString:@"trivial"])
8856 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8857 else if ([context isEqualToString:@"urlerror"])
8858 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8859 else if ([context isEqualToString:@"warning"]) {
8860 switch (button) {
8861 case 1:
8862 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8863 break;
8864
8865 case 0:
8866 break;
8867
8868 _nodefault
8869 }
8870
8871 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8872 }
8873 }
8874
8875 - (void) loadView {
8876 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8877 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8878 [list_ setRowHeight:53];
8879 [(UITableView *) list_ setDataSource:self];
8880 [list_ setDelegate:self];
8881 [self setView:list_];
8882 }
8883
8884 - (void) viewDidLoad {
8885 [super viewDidLoad];
8886
8887 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8888 [self updateButtonsForEditingStatusAnimated:NO];
8889 }
8890
8891 - (void) viewWillAppear:(BOOL)animated {
8892 [super viewWillAppear:animated];
8893
8894 [list_ setEditing:NO];
8895 [self updateButtonsForEditingStatusAnimated:NO];
8896 }
8897
8898 - (void) releaseSubviews {
8899 list_ = nil;
8900
8901 sources_ = nil;
8902
8903 [super releaseSubviews];
8904 }
8905
8906 - (id) initWithDatabase:(Database *)database {
8907 if ((self = [super init]) != nil) {
8908 database_ = database;
8909 } return self;
8910 }
8911
8912 - (void) reloadData {
8913 [super reloadData];
8914
8915 @synchronized (database_) {
8916 era_ = [database_ era];
8917
8918 sources_ = [NSMutableArray arrayWithCapacity:16];
8919 [sources_ addObjectsFromArray:[database_ sources]];
8920 _trace();
8921 [sources_ sortUsingSelector:@selector(compareByName:)];
8922 _trace();
8923
8924 int count([sources_ count]);
8925 offset_ = 0;
8926 for (int i = 0; i != count; i++) {
8927 if ([[sources_ objectAtIndex:i] record] == nil)
8928 break;
8929 offset_++;
8930 }
8931
8932 [list_ reloadData];
8933 } }
8934
8935 - (void) showAddSourcePrompt {
8936 UIAlertView *alert = [[[UIAlertView alloc]
8937 initWithTitle:UCLocalize("ENTER_APT_URL")
8938 message:nil
8939 delegate:self
8940 cancelButtonTitle:UCLocalize("CANCEL")
8941 otherButtonTitles:
8942 UCLocalize("ADD_SOURCE"),
8943 nil
8944 ] autorelease];
8945
8946 [alert setContext:@"source"];
8947
8948 [alert setNumberOfRows:1];
8949 [alert addTextFieldWithValue:@"http://" label:@""];
8950
8951 UITextInputTraits *traits = [[alert textField] textInputTraits];
8952 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8953 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8954 [traits setKeyboardType:UIKeyboardTypeURL];
8955 // XXX: UIReturnKeyDone
8956 [traits setReturnKeyType:UIReturnKeyNext];
8957
8958 [alert show];
8959 }
8960
8961 - (void) addButtonClicked {
8962 [self showAddSourcePrompt];
8963 }
8964
8965 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8966 BOOL editing([list_ isEditing]);
8967
8968 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8969 initWithTitle:UCLocalize("ADD")
8970 style:UIBarButtonItemStylePlain
8971 target:self
8972 action:@selector(addButtonClicked)
8973 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8974
8975 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8976 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8977 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8978 target:self
8979 action:@selector(editButtonClicked)
8980 ] autorelease] animated:animated];
8981
8982 if (IsWildcat_ && !editing)
8983 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8984 initWithTitle:UCLocalize("SETTINGS")
8985 style:UIBarButtonItemStylePlain
8986 target:self
8987 action:@selector(settingsButtonClicked)
8988 ] autorelease]];
8989 }
8990
8991 - (void) settingsButtonClicked {
8992 [delegate_ showSettings];
8993 }
8994
8995 - (void) editButtonClicked {
8996 [list_ setEditing:![list_ isEditing] animated:YES];
8997 [self updateButtonsForEditingStatusAnimated:YES];
8998 }
8999
9000 @end
9001 /* }}} */
9002
9003 /* Settings Controller {{{ */
9004 @interface SettingsController : CyteViewController <
9005 UITableViewDataSource,
9006 UITableViewDelegate
9007 > {
9008 _transient Database *database_;
9009 // XXX: ok, "roledelegate_"?...
9010 _transient id roledelegate_;
9011 _H<UITableView, 2> table_;
9012 _H<UISegmentedControl> segment_;
9013 _H<UIView> container_;
9014 }
9015
9016 - (void) showDoneButton;
9017 - (void) resizeSegmentedControl;
9018
9019 @end
9020
9021 @implementation SettingsController
9022
9023 - (void) loadView {
9024 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9025 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9026 [table_ setDelegate:self];
9027 [(UITableView *) table_ setDataSource:self];
9028 [self setView:table_];
9029
9030 NSArray *items = [NSArray arrayWithObjects:
9031 UCLocalize("USER"),
9032 UCLocalize("HACKER"),
9033 UCLocalize("DEVELOPER"),
9034 nil];
9035 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9036 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9037 [container_ addSubview:segment_];
9038 }
9039
9040 - (void) viewDidLoad {
9041 [super viewDidLoad];
9042
9043 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9044
9045 int index = -1;
9046 if ([Role_ isEqualToString:@"User"]) index = 0;
9047 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9048 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9049 if (index != -1) {
9050 [segment_ setSelectedSegmentIndex:index];
9051 [self showDoneButton];
9052 }
9053
9054 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9055 [self resizeSegmentedControl];
9056 }
9057
9058 - (void) releaseSubviews {
9059 table_ = nil;
9060 segment_ = nil;
9061 container_ = nil;
9062
9063 [super releaseSubviews];
9064 }
9065
9066 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9067 if ((self = [super init]) != nil) {
9068 database_ = database;
9069 roledelegate_ = delegate;
9070 } return self;
9071 }
9072
9073 - (void) resizeSegmentedControl {
9074 CGFloat width = [[self view] frame].size.width;
9075 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9076 }
9077
9078 - (void) viewWillAppear:(BOOL)animated {
9079 [super viewWillAppear:animated];
9080 [self resizeSegmentedControl];
9081 }
9082
9083 - (void) viewDidAppear:(BOOL)animated {
9084 [super viewDidAppear:animated];
9085 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9086 [self resizeSegmentedControl];
9087 }
9088
9089 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9090 [self resizeSegmentedControl];
9091 }
9092
9093 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9094 [self resizeSegmentedControl];
9095 }
9096
9097 - (void) save {
9098 NSString *role(nil);
9099
9100 switch ([segment_ selectedSegmentIndex]) {
9101 case 0: role = @"User"; break;
9102 case 1: role = @"Hacker"; break;
9103 case 2: role = @"Developer"; break;
9104
9105 _nodefault
9106 }
9107
9108 if (![role isEqualToString:Role_]) {
9109 bool rolling(Role_ == nil);
9110 Role_ = role;
9111
9112 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9113 Role_, @"Role",
9114 nil];
9115
9116 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9117 Changed_ = true;
9118
9119 if (rolling)
9120 [roledelegate_ loadData];
9121 else
9122 [roledelegate_ updateData];
9123 }
9124 }
9125
9126 - (void) segmentChanged:(UISegmentedControl *)control {
9127 [self showDoneButton];
9128 }
9129
9130 - (void) saveAndClose {
9131 [self save];
9132
9133 [[self navigationItem] setRightBarButtonItem:nil];
9134 [[self navigationController] dismissModalViewControllerAnimated:YES];
9135 }
9136
9137 - (void) doneButtonClicked {
9138 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9139 [spinner startAnimating];
9140 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9141 [[self navigationItem] setRightBarButtonItem:spinItem];
9142
9143 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9144 }
9145
9146 - (void) showDoneButton {
9147 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9148 initWithTitle:UCLocalize("DONE")
9149 style:UIBarButtonItemStyleDone
9150 target:self
9151 action:@selector(doneButtonClicked)
9152 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9153 }
9154
9155 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9156 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9157 return 6;
9158 }
9159
9160 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9161 return 0; // :(
9162 }
9163
9164 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9165 return nil; // This method is required by the protocol.
9166 }
9167
9168 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9169 if (section == 1)
9170 return UCLocalize("ROLE_EX");
9171 if (section == 4)
9172 return [NSString stringWithFormat:
9173 @"%@: %@\n%@: %@\n%@: %@",
9174 UCLocalize("USER"), UCLocalize("USER_EX"),
9175 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9176 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9177 ];
9178 else return nil;
9179 }
9180
9181 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9182 return section == 3 ? 44.0f : 0;
9183 }
9184
9185 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9186 return section == 3 ? container_ : nil;
9187 }
9188
9189 - (void) reloadData {
9190 [super reloadData];
9191
9192 [table_ reloadData];
9193 }
9194
9195 @end
9196 /* }}} */
9197 /* Stash Controller {{{ */
9198 @interface StashController : CyteViewController {
9199 _H<UIActivityIndicatorView> spinner_;
9200 _H<UILabel> status_;
9201 _H<UILabel> caption_;
9202 }
9203
9204 @end
9205
9206 @implementation StashController
9207
9208 - (void) loadView {
9209 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9210 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9211 [self setView:view];
9212
9213 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9214
9215 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9216 CGRect spinrect = [spinner_ frame];
9217 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9218 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9219 [spinner_ setFrame:spinrect];
9220 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9221 [view addSubview:spinner_];
9222 [spinner_ startAnimating];
9223
9224 CGRect captrect;
9225 captrect.size.width = [[self view] frame].size.width;
9226 captrect.size.height = 40.0f;
9227 captrect.origin.x = 0;
9228 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9229 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9230 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9231 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9232 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9233 [caption_ setTextColor:[UIColor whiteColor]];
9234 [caption_ setBackgroundColor:[UIColor clearColor]];
9235 [caption_ setShadowColor:[UIColor blackColor]];
9236 [caption_ setTextAlignment:UITextAlignmentCenter];
9237 [view addSubview:caption_];
9238
9239 CGRect statusrect;
9240 statusrect.size.width = [[self view] frame].size.width;
9241 statusrect.size.height = 30.0f;
9242 statusrect.origin.x = 0;
9243 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9244 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9245 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9246 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9247 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9248 [status_ setTextColor:[UIColor whiteColor]];
9249 [status_ setBackgroundColor:[UIColor clearColor]];
9250 [status_ setShadowColor:[UIColor blackColor]];
9251 [status_ setTextAlignment:UITextAlignmentCenter];
9252 [view addSubview:status_];
9253 }
9254
9255 - (void) releaseSubviews {
9256 spinner_ = nil;
9257 status_ = nil;
9258 caption_ = nil;
9259
9260 [super releaseSubviews];
9261 }
9262
9263 @end
9264 /* }}} */
9265
9266 @interface CYURLCache : SDURLCache {
9267 }
9268
9269 @end
9270
9271 @implementation CYURLCache
9272
9273 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9274 #if !ForRelease
9275 if (false);
9276 else if ([event isEqualToString:@"no-cache"])
9277 event = @"!!!";
9278 else if ([event isEqualToString:@"store"])
9279 event = @">>>";
9280 else if ([event isEqualToString:@"invalid"])
9281 event = @"???";
9282 else if ([event isEqualToString:@"memory"])
9283 event = @"mem";
9284 else if ([event isEqualToString:@"disk"])
9285 event = @"ssd";
9286 else if ([event isEqualToString:@"miss"])
9287 event = @"---";
9288
9289 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9290 #endif
9291 }
9292
9293 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9294 if (NSURLResponse *response = [cached response])
9295 if (NSString *mime = [response MIMEType])
9296 if ([mime isEqualToString:@"text/cache-manifest"]) {
9297 NSURL *url([response URL]);
9298
9299 #if !ForRelease
9300 NSLog(@"###: %@", [url absoluteString]);
9301 #endif
9302
9303 @synchronized (HostConfig_) {
9304 [CachedURLs_ addObject:url];
9305 }
9306 }
9307
9308 [super storeCachedResponse:cached forRequest:request];
9309 }
9310
9311 @end
9312
9313 @interface Cydia : UIApplication <
9314 ConfirmationControllerDelegate,
9315 DatabaseDelegate,
9316 CydiaDelegate,
9317 UINavigationControllerDelegate,
9318 UITabBarControllerDelegate
9319 > {
9320 _H<UIWindow> window_;
9321 _H<CYTabBarController> tabbar_;
9322 _H<CydiaLoadingViewController> emulated_;
9323
9324 _H<NSMutableArray> essential_;
9325 _H<NSMutableArray> broken_;
9326
9327 Database *database_;
9328
9329 _H<NSURL> starturl_;
9330
9331 unsigned locked_;
9332 unsigned activity_;
9333
9334 _H<StashController> stash_;
9335
9336 bool loaded_;
9337 }
9338
9339 - (void) loadData;
9340
9341 @end
9342
9343 @implementation Cydia
9344
9345 - (void) lockSuspend {
9346 if (locked_++ == 0) {
9347 if ($SBSSetInterceptsMenuButtonForever != NULL)
9348 (*$SBSSetInterceptsMenuButtonForever)(true);
9349
9350 [self setIdleTimerDisabled:YES];
9351 }
9352 }
9353
9354 - (void) unlockSuspend {
9355 if (--locked_ == 0) {
9356 [self setIdleTimerDisabled:NO];
9357
9358 if ($SBSSetInterceptsMenuButtonForever != NULL)
9359 (*$SBSSetInterceptsMenuButtonForever)(false);
9360 }
9361 }
9362
9363 - (void) beginUpdate {
9364 [tabbar_ beginUpdate];
9365 }
9366
9367 - (BOOL) updating {
9368 return [tabbar_ updating];
9369 }
9370
9371 - (void) _loaded {
9372 if ([broken_ count] != 0) {
9373 int count = [broken_ count];
9374
9375 UIAlertView *alert = [[[UIAlertView alloc]
9376 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9377 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9378 delegate:self
9379 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9380 otherButtonTitles:
9381 UCLocalize("TEMPORARY_IGNORE"),
9382 nil
9383 ] autorelease];
9384
9385 [alert setContext:@"fixhalf"];
9386 [alert setNumberOfRows:2];
9387 [alert show];
9388 } else if (!Ignored_ && [essential_ count] != 0) {
9389 int count = [essential_ count];
9390
9391 UIAlertView *alert = [[[UIAlertView alloc]
9392 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9393 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9394 delegate:self
9395 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9396 otherButtonTitles:
9397 UCLocalize("UPGRADE_ESSENTIAL"),
9398 UCLocalize("COMPLETE_UPGRADE"),
9399 nil
9400 ] autorelease];
9401
9402 [alert setContext:@"upgrade"];
9403 [alert show];
9404 }
9405 }
9406
9407 - (void) returnToCydia {
9408 [self _loaded];
9409 }
9410
9411 - (void) _saveConfig {
9412 @synchronized (database_) {
9413 _trace();
9414 MetaFile_.Sync();
9415 _trace();
9416 }
9417
9418 if (Changed_) {
9419 NSString *error(nil);
9420
9421 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9422 _trace();
9423 NSError *error(nil);
9424 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9425 NSLog(@"failure to save metadata data: %@", error);
9426 _trace();
9427
9428 Changed_ = false;
9429 } else {
9430 NSLog(@"failure to serialize metadata: %@", error);
9431 }
9432 }
9433
9434 CydiaWriteSources();
9435 }
9436
9437 // Navigation controller for the queuing badge.
9438 - (UINavigationController *) queueNavigationController {
9439 NSArray *controllers = [tabbar_ viewControllers];
9440 return [controllers objectAtIndex:3];
9441 }
9442
9443 - (void) unloadData {
9444 [tabbar_ unloadData];
9445 }
9446
9447 - (void) _updateData {
9448 [self _saveConfig];
9449 [self unloadData];
9450
9451 UINavigationController *navigation = [self queueNavigationController];
9452
9453 id queuedelegate = nil;
9454 if ([[navigation viewControllers] count] > 0)
9455 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9456
9457 [queuedelegate queueStatusDidChange];
9458 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9459 }
9460
9461 - (void) _refreshIfPossible:(NSDate *)update {
9462 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9463
9464 bool recently = false;
9465 if (update != nil) {
9466 NSTimeInterval interval([update timeIntervalSinceNow]);
9467 if (interval <= 0 && interval > -(15*60))
9468 recently = true;
9469 }
9470
9471 // Don't automatic refresh if:
9472 // - We already refreshed recently.
9473 // - We already auto-refreshed this launch.
9474 // - Auto-refresh is disabled.
9475 // - Cydia's server is not reachable
9476 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9477 // If we are cancelling, we need to make sure it knows it's already loaded.
9478 loaded_ = true;
9479
9480 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9481 } else {
9482 // We are going to load, so remember that.
9483 loaded_ = true;
9484
9485 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9486 }
9487
9488 [pool release];
9489 }
9490
9491 - (void) refreshIfPossible {
9492 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9493 }
9494
9495 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9496 @synchronized (self) {
9497 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9498 if (hud != nil)
9499 [hud setText:UCLocalize("RELOADING_DATA")];
9500
9501 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9502
9503 size_t changes(0);
9504
9505 [essential_ removeAllObjects];
9506 [broken_ removeAllObjects];
9507
9508 NSArray *packages([database_ packages]);
9509 for (Package *package in packages) {
9510 if ([package half])
9511 [broken_ addObject:package];
9512 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9513 if ([package essential] && [package installed] != nil)
9514 [essential_ addObject:package];
9515 ++changes;
9516 }
9517 }
9518
9519 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9520 if (changes != 0) {
9521 _trace();
9522 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9523 [changesItem setBadgeValue:badge];
9524 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9525 [self setApplicationIconBadgeNumber:changes];
9526 } else {
9527 _trace();
9528 [changesItem setBadgeValue:nil];
9529 [changesItem setAnimatedBadge:NO];
9530 [self setApplicationIconBadgeNumber:0];
9531 }
9532
9533 [self _updateData];
9534
9535 if (hud != nil)
9536 [self removeProgressHUD:hud];
9537 } }
9538
9539 - (void) updateData {
9540 [self _updateData];
9541 }
9542
9543 - (void) updateDataAndLoad {
9544 [self _updateData];
9545 if ([database_ progressDelegate] == nil)
9546 [self _loaded];
9547 }
9548
9549 - (void) update_ {
9550 [database_ update];
9551 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9552 }
9553
9554 - (void) disemulate {
9555 if (emulated_ == nil)
9556 return;
9557
9558 [window_ addSubview:[tabbar_ view]];
9559 [[emulated_ view] removeFromSuperview];
9560 emulated_ = nil;
9561 [window_ setUserInteractionEnabled:YES];
9562 }
9563
9564 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9565 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9566 if (IsWildcat_)
9567 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9568
9569 UIViewController *parent;
9570 if (emulated_ == nil)
9571 parent = tabbar_;
9572 else if (!force)
9573 parent = emulated_;
9574 else {
9575 [self disemulate];
9576 parent = tabbar_;
9577 }
9578
9579 [parent presentModalViewController:navigation animated:YES];
9580 }
9581
9582 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9583 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9584
9585 if (navigation != nil)
9586 [navigation pushViewController:progress animated:YES];
9587 else
9588 [self presentModalViewController:progress force:YES];
9589
9590 [progress invoke:invocation withTitle:title];
9591 return progress;
9592 }
9593
9594 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9595 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9596 }
9597
9598 - (void) repairWithInvocation:(NSInvocation *)invocation {
9599 _trace();
9600 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9601 _trace();
9602 }
9603
9604 - (void) repairWithSelector:(SEL)selector {
9605 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9606 }
9607
9608 - (void) reloadData {
9609 [self reloadDataWithInvocation:nil];
9610 if ([database_ progressDelegate] == nil)
9611 [self _loaded];
9612 }
9613
9614 - (void) syncData {
9615 [self _saveConfig];
9616 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9617 }
9618
9619 - (void) addSource:(NSDictionary *) source {
9620 CydiaAddSource(source);
9621 }
9622
9623 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9624 CydiaAddSource(href, distribution, sections);
9625 }
9626
9627 - (void) addTrivialSource:(NSString *)href {
9628 CydiaAddSource(href, @"./");
9629 }
9630
9631 - (void) updateValues {
9632 Changed_ = true;
9633 }
9634
9635 - (void) resolve {
9636 pkgProblemResolver *resolver = [database_ resolver];
9637
9638 resolver->InstallProtect();
9639 if (!resolver->Resolve(true))
9640 _error->Discard();
9641 }
9642
9643 - (bool) perform {
9644 // XXX: this is a really crappy way of doing this.
9645 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9646 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9647 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9648 if ([tabbar_ updating])
9649 [tabbar_ cancelUpdate];
9650
9651 if (![database_ prepare])
9652 return false;
9653
9654 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9655 [page setDelegate:self];
9656 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9657
9658 if (IsWildcat_)
9659 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9660 [tabbar_ presentModalViewController:confirm_ animated:YES];
9661
9662 return true;
9663 }
9664
9665 - (void) queue {
9666 @synchronized (self) {
9667 [self perform];
9668 }
9669 }
9670
9671 - (void) clearPackage:(Package *)package {
9672 @synchronized (self) {
9673 [package clear];
9674 [self resolve];
9675 [self perform];
9676 }
9677 }
9678
9679 - (void) installPackages:(NSArray *)packages {
9680 @synchronized (self) {
9681 for (Package *package in packages)
9682 [package install];
9683 [self resolve];
9684 [self perform];
9685 }
9686 }
9687
9688 - (void) installPackage:(Package *)package {
9689 @synchronized (self) {
9690 [package install];
9691 [self resolve];
9692 [self perform];
9693 }
9694 }
9695
9696 - (void) removePackage:(Package *)package {
9697 @synchronized (self) {
9698 [package remove];
9699 [self resolve];
9700 [self perform];
9701 }
9702 }
9703
9704 - (void) distUpgrade {
9705 @synchronized (self) {
9706 if (![database_ upgrade])
9707 return;
9708 [self perform];
9709 }
9710 }
9711
9712 - (void) _uicache {
9713 _trace();
9714 system("su -c /usr/bin/uicache mobile");
9715 _trace();
9716 }
9717
9718 - (void) uicache {
9719 UIProgressHUD *hud([self addProgressHUD]);
9720 [hud setText:UCLocalize("LOADING")];
9721 [self yieldToSelector:@selector(_uicache)];
9722 [self removeProgressHUD:hud];
9723 }
9724
9725 - (void) perform_ {
9726 [database_ perform];
9727 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9728 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9729 }
9730
9731 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9732 Queuing_ = false;
9733 [self lockSuspend];
9734 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9735 [self unlockSuspend];
9736 }
9737
9738 - (void) showSettings {
9739 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9740 }
9741
9742 - (void) retainNetworkActivityIndicator {
9743 if (activity_++ == 0)
9744 [self setNetworkActivityIndicatorVisible:YES];
9745
9746 #if TraceLogging
9747 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9748 #endif
9749 }
9750
9751 - (void) releaseNetworkActivityIndicator {
9752 if (--activity_ == 0)
9753 [self setNetworkActivityIndicatorVisible:NO];
9754
9755 #if TraceLogging
9756 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9757 #endif
9758
9759 }
9760
9761 - (void) cancelAndClear:(bool)clear {
9762 @synchronized (self) {
9763 if (clear) {
9764 [database_ clear];
9765 Queuing_ = false;
9766 } else {
9767 Queuing_ = true;
9768 }
9769
9770 [self _updateData];
9771 }
9772 }
9773
9774 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9775 NSString *context([alert context]);
9776
9777 if ([context isEqualToString:@"conffile"]) {
9778 FILE *input = [database_ input];
9779 if (button == [alert cancelButtonIndex])
9780 fprintf(input, "N\n");
9781 else if (button == [alert firstOtherButtonIndex])
9782 fprintf(input, "Y\n");
9783 fflush(input);
9784
9785 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9786 } else if ([context isEqualToString:@"fixhalf"]) {
9787 if (button == [alert cancelButtonIndex]) {
9788 @synchronized (self) {
9789 for (Package *broken in (id) broken_) {
9790 [broken remove];
9791
9792 NSString *id = [broken id];
9793 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9794 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9795 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9796 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9797 }
9798
9799 [self resolve];
9800 [self perform];
9801 }
9802 } else if (button == [alert firstOtherButtonIndex]) {
9803 [broken_ removeAllObjects];
9804 [self _loaded];
9805 }
9806
9807 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9808 } else if ([context isEqualToString:@"upgrade"]) {
9809 if (button == [alert firstOtherButtonIndex]) {
9810 @synchronized (self) {
9811 for (Package *essential in (id) essential_)
9812 [essential install];
9813
9814 [self resolve];
9815 [self perform];
9816 }
9817 } else if (button == [alert firstOtherButtonIndex] + 1) {
9818 [self distUpgrade];
9819 } else if (button == [alert cancelButtonIndex]) {
9820 Ignored_ = YES;
9821 }
9822
9823 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9824 }
9825 }
9826
9827 - (void) system:(NSString *)command {
9828 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9829
9830 _trace();
9831 system([command UTF8String]);
9832 _trace();
9833
9834 [pool release];
9835 }
9836
9837 - (void) applicationWillSuspend {
9838 [database_ clean];
9839 [super applicationWillSuspend];
9840 }
9841
9842 - (BOOL) isSafeToSuspend {
9843 if (locked_ != 0) {
9844 #if !ForRelease
9845 NSLog(@"isSafeToSuspend: locked_ != 0");
9846 #endif
9847 return false;
9848 }
9849
9850 // Use external process status API internally.
9851 // This is probably a really bad idea.
9852 // XXX: what is the point of this? does this solve anything at all?
9853 uint64_t status = 0;
9854 int notify_token;
9855 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9856 notify_get_state(notify_token, &status);
9857 notify_cancel(notify_token);
9858 }
9859
9860 if (status != 0) {
9861 #if !ForRelease
9862 NSLog(@"isSafeToSuspend: status != 0");
9863 #endif
9864 return false;
9865 }
9866
9867 #if !ForRelease
9868 NSLog(@"isSafeToSuspend: -> true");
9869 #endif
9870 return true;
9871 }
9872
9873 - (void) applicationSuspend:(__GSEvent *)event {
9874 if ([self isSafeToSuspend])
9875 [super applicationSuspend:event];
9876 }
9877
9878 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9879 if ([self isSafeToSuspend])
9880 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9881 }
9882
9883 - (void) _setSuspended:(BOOL)value {
9884 if ([self isSafeToSuspend])
9885 [super _setSuspended:value];
9886 }
9887
9888 - (UIProgressHUD *) addProgressHUD {
9889 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9890 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9891
9892 [window_ setUserInteractionEnabled:NO];
9893
9894 UIViewController *target(tabbar_);
9895 if (UIViewController *modal = [target modalViewController])
9896 target = modal;
9897
9898 [hud showInView:[target view]];
9899
9900 [self lockSuspend];
9901 return hud;
9902 }
9903
9904 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9905 [self unlockSuspend];
9906 [hud hide];
9907 [hud removeFromSuperview];
9908 [window_ setUserInteractionEnabled:YES];
9909 }
9910
9911 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9912 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9913 }
9914
9915 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9916 NSString *scheme([[url scheme] lowercaseString]);
9917 if ([[url absoluteString] length] <= [scheme length] + 3)
9918 return nil;
9919 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9920 NSArray *components([path componentsSeparatedByString:@"/"]);
9921
9922 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9923 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9924 if (controller != nil)
9925 [controller setDelegate:self];
9926 return controller;
9927 }
9928
9929 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9930 return nil;
9931
9932 NSString *base([components objectAtIndex:0]);
9933
9934 CyteViewController *controller = nil;
9935
9936 if ([base isEqualToString:@"url"]) {
9937 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9938 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9939 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9940 } else if (!external && [components count] == 1) {
9941 if ([base isEqualToString:@"manage"]) {
9942 controller = [[[ManageController alloc] init] autorelease];
9943 }
9944
9945 if ([base isEqualToString:@"storage"]) {
9946 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9947 }
9948
9949 if ([base isEqualToString:@"sources"]) {
9950 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9951 }
9952
9953 if ([base isEqualToString:@"home"]) {
9954 controller = [[[HomeController alloc] init] autorelease];
9955 }
9956
9957 if ([base isEqualToString:@"sections"]) {
9958 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9959 }
9960
9961 if ([base isEqualToString:@"search"]) {
9962 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9963 }
9964
9965 if ([base isEqualToString:@"changes"]) {
9966 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9967 }
9968
9969 if ([base isEqualToString:@"installed"]) {
9970 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9971 }
9972 } else if ([components count] == 2) {
9973 NSString *argument = [components objectAtIndex:1];
9974
9975 if ([base isEqualToString:@"package"]) {
9976 controller = [self pageForPackage:argument withReferrer:referrer];
9977 }
9978
9979 if (!external && [base isEqualToString:@"search"]) {
9980 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9981 }
9982
9983 if (!external && [base isEqualToString:@"sections"]) {
9984 if ([argument isEqualToString:@"all"])
9985 argument = nil;
9986 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9987 }
9988
9989 if (!external && [base isEqualToString:@"sources"]) {
9990 if ([argument isEqualToString:@"add"]) {
9991 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9992 [(SourcesController *)controller showAddSourcePrompt];
9993 } else {
9994 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9995 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9996 }
9997 }
9998
9999 if (!external && [base isEqualToString:@"launch"]) {
10000 [self launchApplicationWithIdentifier:argument suspended:NO];
10001 return nil;
10002 }
10003 } else if (!external && [components count] == 3) {
10004 NSString *arg1 = [components objectAtIndex:1];
10005 NSString *arg2 = [components objectAtIndex:2];
10006
10007 if ([base isEqualToString:@"package"]) {
10008 if ([arg2 isEqualToString:@"settings"]) {
10009 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
10010 } else if ([arg2 isEqualToString:@"files"]) {
10011 if (Package *package = [database_ packageWithName:arg1]) {
10012 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
10013 [(FileTable *)controller setPackage:package];
10014 }
10015 }
10016 }
10017 }
10018
10019 [controller setDelegate:self];
10020 return controller;
10021 }
10022
10023 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10024 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10025
10026 if (page != nil)
10027 [tabbar_ setUnselectedViewController:page];
10028
10029 return page != nil;
10030 }
10031
10032 - (void) applicationOpenURL:(NSURL *)url {
10033 [super applicationOpenURL:url];
10034
10035 if (!loaded_)
10036 starturl_ = url;
10037 else
10038 [self openCydiaURL:url forExternal:YES];
10039 }
10040
10041 - (void) applicationWillResignActive:(UIApplication *)application {
10042 // Stop refreshing if you get a phone call or lock the device.
10043 if ([tabbar_ updating])
10044 [tabbar_ cancelUpdate];
10045
10046 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10047 [super applicationWillResignActive:application];
10048 }
10049
10050 - (void) saveState {
10051 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10052 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10053 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10054 Changed_ = true;
10055
10056 [self _saveConfig];
10057 }
10058
10059 - (void) applicationWillTerminate:(UIApplication *)application {
10060 [self saveState];
10061 }
10062
10063 - (void) setConfigurationData:(NSString *)data {
10064 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10065
10066 if (!conffile_r(data)) {
10067 lprintf("E:invalid conffile\n");
10068 return;
10069 }
10070
10071 NSString *ofile = conffile_r[1];
10072 //NSString *nfile = conffile_r[2];
10073
10074 UIAlertView *alert = [[[UIAlertView alloc]
10075 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10076 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10077 delegate:self
10078 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10079 otherButtonTitles:
10080 UCLocalize("ACCEPT_NEW_COPY"),
10081 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10082 nil
10083 ] autorelease];
10084
10085 [alert setContext:@"conffile"];
10086 [alert setNumberOfRows:2];
10087 [alert show];
10088 }
10089
10090 - (void) addStashController {
10091 [self lockSuspend];
10092 stash_ = [[[StashController alloc] init] autorelease];
10093 [window_ addSubview:[stash_ view]];
10094 }
10095
10096 - (void) removeStashController {
10097 [[stash_ view] removeFromSuperview];
10098 stash_ = nil;
10099 [self unlockSuspend];
10100 }
10101
10102 - (void) stash {
10103 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10104 UpdateExternalStatus(1);
10105 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10106 UpdateExternalStatus(0);
10107
10108 [self removeStashController];
10109
10110 pid_t pid(ExecFork());
10111 if (pid == 0) {
10112 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10113 perror("launchctl stop");
10114 exit(0);
10115 }
10116
10117 ReapZombie(pid);
10118 }
10119
10120 - (void) setupViewControllers {
10121 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10122
10123 NSMutableArray *items([NSMutableArray arrayWithObjects:
10124 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10125 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10126 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10127 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10128 nil]);
10129
10130 if (IsWildcat_) {
10131 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10132 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10133 } else {
10134 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10135 }
10136
10137 NSMutableArray *controllers([NSMutableArray array]);
10138 for (UITabBarItem *item in items) {
10139 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10140 [controller setTabBarItem:item];
10141 [controllers addObject:controller];
10142 }
10143 [tabbar_ setViewControllers:controllers];
10144
10145 [tabbar_ setUpdateDelegate:self];
10146 }
10147
10148 - (void) _sendMemoryWarningNotification {
10149 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10150 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10151 else
10152 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10153 }
10154
10155 - (void) _sendMemoryWarningNotifications {
10156 while (true) {
10157 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10158 sleep(2);
10159 //usleep(2000000);
10160 }
10161 }
10162
10163 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10164 NSLog(@"--");
10165 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10166 }
10167
10168 - (void) applicationDidFinishLaunching:(id)unused {
10169 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10170
10171 _trace();
10172 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10173 [self setApplicationSupportsShakeToEdit:NO];
10174
10175 @synchronized (HostConfig_) {
10176 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10177 }
10178
10179 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10180 initWithMemoryCapacity:524288
10181 diskCapacity:10485760
10182 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
10183 ] autorelease]];
10184
10185 [CydiaWebViewController _initialize];
10186
10187 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10188
10189 // this would disallow http{,s} URLs from accessing this data
10190 //[WebView registerURLSchemeAsLocal:@"cydia"];
10191
10192 Font12_ = [UIFont systemFontOfSize:12];
10193 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10194 Font14_ = [UIFont systemFontOfSize:14];
10195 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10196 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10197
10198 essential_ = [NSMutableArray arrayWithCapacity:4];
10199 broken_ = [NSMutableArray arrayWithCapacity:4];
10200
10201 // XXX: I really need this thing... like, seriously... I'm sorry
10202 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10203
10204 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10205 [window_ orderFront:self];
10206 [window_ makeKey:self];
10207 [window_ setHidden:NO];
10208
10209 if (false) stash: {
10210 [self addStashController];
10211 // XXX: this would be much cleaner as a yieldToSelector:
10212 // that way the removeStashController could happen right here inline
10213 // we also could no longer require the useless stash_ field anymore
10214 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10215 return;
10216 }
10217
10218 struct stat root;
10219 int error(stat("/", &root));
10220 _assert(error != -1);
10221
10222 #define Stash_(path) do { \
10223 struct stat folder; \
10224 int error(lstat((path), &folder)); \
10225 if (error != -1 && ( \
10226 folder.st_dev == root.st_dev && \
10227 S_ISDIR(folder.st_mode) \
10228 ) || error == -1 && ( \
10229 errno == ENOENT || \
10230 errno == ENOTDIR \
10231 )) goto stash; \
10232 } while (false)
10233
10234 Stash_("/Applications");
10235 Stash_("/Library/Ringtones");
10236 Stash_("/Library/Wallpaper");
10237 //Stash_("/usr/bin");
10238 Stash_("/usr/include");
10239 Stash_("/usr/lib/pam");
10240 Stash_("/usr/libexec");
10241 Stash_("/usr/share");
10242 //Stash_("/var/lib");
10243
10244 database_ = [Database sharedInstance];
10245 [database_ setDelegate:self];
10246
10247 [window_ setUserInteractionEnabled:NO];
10248 [self setupViewControllers];
10249
10250 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10251 [window_ addSubview:[emulated_ view]];
10252
10253 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10254 _trace();
10255 }
10256
10257 - (NSArray *) defaultStartPages {
10258 NSMutableArray *standard = [NSMutableArray array];
10259 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10260 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10261 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10262 if (!IsWildcat_) {
10263 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10264 } else {
10265 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10266 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10267 }
10268 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10269 return standard;
10270 }
10271
10272 - (void) loadData {
10273 _trace();
10274 if (Role_ == nil) {
10275 [window_ setUserInteractionEnabled:YES];
10276 [self showSettings];
10277 return;
10278 } else {
10279 if ([emulated_ modalViewController] != nil)
10280 [emulated_ dismissModalViewControllerAnimated:YES];
10281 [window_ setUserInteractionEnabled:NO];
10282 }
10283
10284 [self reloadDataWithInvocation:nil];
10285 [self refreshIfPossible];
10286 PrintTimes();
10287
10288 [self disemulate];
10289
10290 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10291 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10292 int standardIndex = 0;
10293 NSArray *standard = [self defaultStartPages];
10294
10295 BOOL valid = YES;
10296
10297 if (saved == nil)
10298 valid = NO;
10299
10300 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10301 if (valid && closed != nil) {
10302 NSTimeInterval interval([closed timeIntervalSinceNow]);
10303 // XXX: Is 30 minutes the optimal time here?
10304 if (interval <= -(30*60))
10305 valid = NO;
10306 }
10307
10308 if (valid && [saved count] != [standard count])
10309 valid = NO;
10310
10311 if (valid) {
10312 for (unsigned int i = 0; i < [standard count]; i++) {
10313 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10314 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10315 // but it's good enough for now.
10316 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10317 valid = NO;
10318 break;
10319 }
10320 }
10321 }
10322
10323 NSArray *items = nil;
10324 if (valid) {
10325 [tabbar_ setSelectedIndex:savedIndex];
10326 items = saved;
10327 } else {
10328 [tabbar_ setSelectedIndex:standardIndex];
10329 items = standard;
10330 }
10331
10332 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10333 NSArray *stack = [items objectAtIndex:tab];
10334 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10335 NSMutableArray *current = [NSMutableArray array];
10336
10337 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10338 NSString *addr = [stack objectAtIndex:nav];
10339 NSURL *url = [NSURL URLWithString:addr];
10340 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10341 if (page != nil)
10342 [current addObject:page];
10343 }
10344
10345 [navigation setViewControllers:current];
10346 }
10347
10348 // (Try to) show the startup URL.
10349 if (starturl_ != nil) {
10350 [self openCydiaURL:starturl_ forExternal:NO];
10351 starturl_ = nil;
10352 }
10353 }
10354
10355 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10356 if (item != nil && IsWildcat_) {
10357 [sheet showFromBarButtonItem:item animated:YES];
10358 } else {
10359 [sheet showInView:window_];
10360 }
10361 }
10362
10363 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10364 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10365 [progress setTitle:task];
10366 [progress addProgressEvent:event];
10367 }
10368
10369 - (void) addProgressEventForTask:(NSArray *)data {
10370 CydiaProgressEvent *event([data objectAtIndex:0]);
10371 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10372 [self addProgressEvent:event forTask:task];
10373 }
10374
10375 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10376 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10377 }
10378
10379 @end
10380
10381 /*IMP alloc_;
10382 id Alloc_(id self, SEL selector) {
10383 id object = alloc_(self, selector);
10384 lprintf("[%s]A-%p\n", self->isa->name, object);
10385 return object;
10386 }*/
10387
10388 /*IMP dealloc_;
10389 id Dealloc_(id self, SEL selector) {
10390 id object = dealloc_(self, selector);
10391 lprintf("[%s]D-%p\n", self->isa->name, object);
10392 return object;
10393 }*/
10394
10395 static NSSet *MobilizedFiles_;
10396
10397 static NSURL *MobilizeURL(NSURL *url) {
10398 NSString *path([url path]);
10399 if ([path hasPrefix:@"/var/root/"]) {
10400 NSString *file([path substringFromIndex:10]);
10401 if ([MobilizedFiles_ containsObject:file])
10402 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10403 }
10404
10405 return url;
10406 }
10407
10408 Class $CFXPreferencesPropertyListSource;
10409 @class CFXPreferencesPropertyListSource;
10410
10411 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10412 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10413 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10414 url = MobilizeURL(url);
10415 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10416 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10417 url = old;
10418 [pool release];
10419 return value;
10420 }
10421
10422 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10423 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10424 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10425 url = MobilizeURL(url);
10426 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10427 //NSLog(@"%@ %@", [url absoluteString], value);
10428 url = old;
10429 [pool release];
10430 return value;
10431 }
10432
10433 Class $NSURLConnection;
10434
10435 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10436 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10437
10438 NSURL *url([copy URL]);
10439
10440 NSString *host([url host]);
10441 NSString *scheme([[url scheme] lowercaseString]);
10442
10443 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10444
10445 @synchronized (HostConfig_) {
10446 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10447 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10448 [copy setHTTPShouldUsePipelining:YES];
10449
10450 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10451 if ([control isEqualToString:@"max-age=0"])
10452 if ([CachedURLs_ containsObject:url]) {
10453 #if !ForRelease
10454 NSLog(@"~~~: %@", url);
10455 #endif
10456
10457 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10458
10459 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10460 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10461 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10462 }
10463 }
10464
10465 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10466 } return self;
10467 }
10468
10469 Class $WAKWindow;
10470
10471 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10472 CGSize size([[UIScreen mainScreen] bounds].size);
10473 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10474 if ([$WAKWindow hasLandscapeOrientation])
10475 std::swap(size.width, size.height);*/
10476 return size;
10477 }
10478
10479 Class $NSUserDefaults;
10480
10481 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10482 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10483 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10484 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10485 }
10486
10487 int main(int argc, char *argv[]) {
10488 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10489
10490 _trace();
10491
10492 UpdateExternalStatus(0);
10493
10494 if (Class $UIDevice = objc_getClass("UIDevice")) {
10495 UIDevice *device([$UIDevice currentDevice]);
10496 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10497 } else
10498 IsWildcat_ = false;
10499
10500 UIScreen *screen([UIScreen mainScreen]);
10501 if ([screen respondsToSelector:@selector(scale)])
10502 ScreenScale_ = [screen scale];
10503 else
10504 ScreenScale_ = 1;
10505
10506 UIDevice *device([UIDevice currentDevice]);
10507 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10508 Idiom_ = @"iphone";
10509 else {
10510 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10511 if (idiom == UIUserInterfaceIdiomPhone)
10512 Idiom_ = @"iphone";
10513 else if (idiom == UIUserInterfaceIdiomPad)
10514 Idiom_ = @"ipad";
10515 else
10516 NSLog(@"unknown UIUserInterfaceIdiom!");
10517 }
10518
10519 Pcre pattern("^([0-9]+\\.[0-9]+)");
10520
10521 if (pattern([device systemVersion]))
10522 Firmware_ = pattern[1];
10523 if (pattern(Cydia_))
10524 Major_ = pattern[1];
10525
10526 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10527
10528 HostConfig_ = [[[NSObject alloc] init] autorelease];
10529 @synchronized (HostConfig_) {
10530 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10531 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10532 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10533 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10534 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10535 }
10536
10537 NSString *ui(@"ui/ios");
10538 if (Idiom_ != nil)
10539 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10540 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10541 UI_ = CydiaURL(ui);
10542
10543 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10544
10545 MobilizedFiles_ = [NSMutableSet setWithObjects:
10546 @"Library/Preferences/com.apple.Accessibility.plist",
10547 @"Library/Preferences/com.apple.preferences.sounds.plist",
10548 nil];
10549
10550 /* Library Hacks {{{ */
10551 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10552
10553 $WAKWindow = objc_getClass("WAKWindow");
10554 if ($WAKWindow != NULL)
10555 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10556 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10557
10558 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10559
10560 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10561 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10562 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10563 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10564 }
10565
10566 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10567 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10568 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10569 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10570 }
10571
10572 $NSURLConnection = objc_getClass("NSURLConnection");
10573 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10574 if (NSURLConnection$init$ != NULL) {
10575 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10576 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10577 }
10578
10579 $NSUserDefaults = objc_getClass("NSUserDefaults");
10580 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10581 if (NSUserDefaults$objectForKey$ != NULL) {
10582 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10583 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10584 }
10585 /* }}} */
10586 /* Set Locale {{{ */
10587 Locale_ = CFLocaleCopyCurrent();
10588 Languages_ = [NSLocale preferredLanguages];
10589
10590 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10591 //NSLog(@"%@", [Languages_ description]);
10592
10593 const char *lang;
10594 if (Locale_ != NULL)
10595 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10596 else if (Languages_ != nil && [Languages_ count] != 0)
10597 lang = [[Languages_ objectAtIndex:0] UTF8String];
10598 else
10599 // XXX: consider just setting to C and then falling through?
10600 lang = NULL;
10601
10602 if (lang != NULL) {
10603 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10604 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10605 }
10606
10607 NSLog(@"Setting Language: %s", lang);
10608
10609 if (lang != NULL) {
10610 setenv("LANG", lang, true);
10611 std::setlocale(LC_ALL, lang);
10612 }
10613 /* }}} */
10614
10615 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10616
10617 /* Parse Arguments {{{ */
10618 bool substrate(false);
10619
10620 if (argc != 0) {
10621 char **args(argv);
10622 int arge(1);
10623
10624 for (int argi(1); argi != argc; ++argi)
10625 if (strcmp(argv[argi], "--") == 0) {
10626 arge = argi;
10627 argv[argi] = argv[0];
10628 argv += argi;
10629 argc -= argi;
10630 break;
10631 }
10632
10633 for (int argi(1); argi != arge; ++argi)
10634 if (strcmp(args[argi], "--substrate") == 0)
10635 substrate = true;
10636 else
10637 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10638 }
10639 /* }}} */
10640
10641 App_ = [[NSBundle mainBundle] bundlePath];
10642 Advanced_ = YES;
10643
10644 setuid(0);
10645 setgid(0);
10646
10647 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10648 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10649
10650 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10651
10652 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10653 alloc_ = alloc->method_imp;
10654 alloc->method_imp = (IMP) &Alloc_;*/
10655
10656 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10657 dealloc_ = dealloc->method_imp;
10658 dealloc->method_imp = (IMP) &Dealloc_;*/
10659
10660 /* System Information {{{ */
10661 size_t size;
10662
10663 int maxproc;
10664 size = sizeof(maxproc);
10665 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10666 perror("sysctlbyname(\"kern.maxproc\", ?)");
10667 else if (maxproc < 64) {
10668 maxproc = 64;
10669 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10670 perror("sysctlbyname(\"kern.maxproc\", #)");
10671 }
10672
10673 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10674 char *osversion = new char[size];
10675 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10676 perror("sysctlbyname(\"kern.osversion\", ?)");
10677 else
10678 System_ = [NSString stringWithUTF8String:osversion];
10679
10680 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10681 char *machine = new char[size];
10682 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10683 perror("sysctlbyname(\"hw.machine\", ?)");
10684 else
10685 Machine_ = machine;
10686
10687 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10688 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10689 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10690
10691 UniqueID_ = [device uniqueIdentifier];
10692
10693 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10694 Product_ = [info objectForKey:@"SafariProductVersion"];
10695 Safari_ = [info objectForKey:@"CFBundleVersion"];
10696 }
10697
10698 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10699
10700 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10701 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10702 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10703 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10704 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10705 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10706
10707 UserAgent_ = agent;
10708 /* }}} */
10709 /* Load Database {{{ */
10710 _trace();
10711 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10712 _trace();
10713 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10714
10715 if (Metadata_ == NULL)
10716 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10717 else {
10718 Settings_ = [Metadata_ objectForKey:@"Settings"];
10719
10720 Packages_ = [Metadata_ objectForKey:@"Packages"];
10721
10722 Values_ = [Metadata_ objectForKey:@"Values"];
10723 Sections_ = [Metadata_ objectForKey:@"Sections"];
10724 Sources_ = [Metadata_ objectForKey:@"Sources"];
10725
10726 Token_ = [Metadata_ objectForKey:@"Token"];
10727
10728 Version_ = [Metadata_ objectForKey:@"Version"];
10729 }
10730
10731 if (Settings_ != nil)
10732 Role_ = [Settings_ objectForKey:@"Role"];
10733
10734 if (Values_ == nil) {
10735 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10736 [Metadata_ setObject:Values_ forKey:@"Values"];
10737 }
10738
10739 if (Sections_ == nil) {
10740 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10741 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10742 }
10743
10744 if (Sources_ == nil) {
10745 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10746 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10747 }
10748
10749 if (Version_ == nil) {
10750 Version_ = [NSNumber numberWithUnsignedInt:0];
10751 [Metadata_ setObject:Version_ forKey:@"Version"];
10752 }
10753
10754 if ([Version_ unsignedIntValue] == 0) {
10755 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10756 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10757 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10758 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10759
10760 Version_ = [NSNumber numberWithUnsignedInt:1];
10761 [Metadata_ setObject:Version_ forKey:@"Version"];
10762
10763 [Metadata_ removeObjectForKey:@"LastUpdate"];
10764
10765 Changed_ = true;
10766 }
10767 /* }}} */
10768
10769 CydiaWriteSources();
10770
10771 _trace();
10772 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10773 _trace();
10774
10775 if (Packages_ != nil) {
10776 bool fail(false);
10777 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10778 _trace();
10779
10780 if (!fail) {
10781 [Metadata_ removeObjectForKey:@"Packages"];
10782 Packages_ = nil;
10783 Changed_ = true;
10784 }
10785 }
10786
10787 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10788
10789 #define MobileSubstrate_(name) \
10790 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10791 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10792 if (handle == NULL) \
10793 NSLog(@"%s", dlerror()); \
10794 }
10795
10796 MobileSubstrate_(Activator)
10797 MobileSubstrate_(libstatusbar)
10798 MobileSubstrate_(SimulatedKeyEvents)
10799 MobileSubstrate_(WinterBoard)
10800
10801 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10802 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10803
10804 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10805
10806 if (access("/User", F_OK) != 0 || version != 6) {
10807 _trace();
10808 system("/usr/libexec/cydia/firmware.sh");
10809 _trace();
10810 }
10811
10812 _assert([[NSFileManager defaultManager]
10813 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10814 withIntermediateDirectories:YES
10815 attributes:nil
10816 error:NULL
10817 ]);
10818
10819 if (access("/tmp/cydia.chk", F_OK) == 0) {
10820 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10821 _assert(errno == ENOENT);
10822 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10823 _assert(errno == ENOENT);
10824 }
10825
10826 /* APT Initialization {{{ */
10827 _assert(pkgInitConfig(*_config));
10828 _assert(pkgInitSystem(*_config, _system));
10829
10830 if (lang != NULL)
10831 _config->Set("APT::Acquire::Translation", lang);
10832
10833 // XXX: this timeout might be important :(
10834 //_config->Set("Acquire::http::Timeout", 15);
10835
10836 _config->Set("Acquire::http::MaxParallel", 3);
10837 /* }}} */
10838 /* Color Choices {{{ */
10839 space_ = CGColorSpaceCreateDeviceRGB();
10840
10841 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10842 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10843 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10844 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10845 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10846 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10847 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10848 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10849 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10850
10851 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10852 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10853 /* }}}*/
10854 /* UIKit Configuration {{{ */
10855 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10856 if ($GSFontSetUseLegacyFontMetrics != NULL)
10857 $GSFontSetUseLegacyFontMetrics(YES);
10858
10859 // XXX: I have a feeling this was important
10860 //UIKeyboardDisableAutomaticAppearance();
10861 /* }}} */
10862
10863 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10864
10865 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10866 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10867
10868 ShowPromoted_ = fast;
10869 PulseInterval_ = fast ? 50000 : 500000;
10870
10871 Colon_ = UCLocalize("COLON_DELIMITED");
10872 Elision_ = UCLocalize("ELISION");
10873 Error_ = UCLocalize("ERROR");
10874 Warning_ = UCLocalize("WARNING");
10875
10876 AprilFools_ = false;
10877
10878 _trace();
10879 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10880
10881 CGColorSpaceRelease(space_);
10882 CFRelease(Locale_);
10883
10884 [pool release];
10885 return value;
10886 }