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