]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Improve icon image quality on non-Retina displays.
[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 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6283 if ((self = [super init]) != nil) {
6284 database_ = database;
6285 buttons_ = [NSMutableArray arrayWithCapacity:4];
6286 name_ = name == nil ? @"" : [NSString stringWithString:name];
6287 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6288 } return self;
6289 }
6290
6291 - (void) reloadData {
6292 [super reloadData];
6293
6294 package_ = [database_ packageWithName:name_];
6295
6296 [buttons_ removeAllObjects];
6297
6298 if (package_ != nil) {
6299 [(Package *) package_ parse];
6300
6301 commercial_ = [package_ isCommercial];
6302
6303 if ([package_ mode] != nil)
6304 [buttons_ addObject:UCLocalize("CLEAR")];
6305 if ([package_ source] == nil);
6306 else if ([package_ upgradableAndEssential:NO])
6307 [buttons_ addObject:UCLocalize("UPGRADE")];
6308 else if ([package_ uninstalled])
6309 [buttons_ addObject:UCLocalize("INSTALL")];
6310 else
6311 [buttons_ addObject:UCLocalize("REINSTALL")];
6312 if (![package_ uninstalled])
6313 [buttons_ addObject:UCLocalize("REMOVE")];
6314 }
6315
6316 NSString *title;
6317 switch ([buttons_ count]) {
6318 case 0: title = nil; break;
6319 case 1: title = [buttons_ objectAtIndex:0]; break;
6320 default: title = UCLocalize("MODIFY"); break;
6321 }
6322
6323 button_ = [[[UIBarButtonItem alloc]
6324 initWithTitle:title
6325 style:UIBarButtonItemStylePlain
6326 target:self
6327 action:@selector(customButtonClicked)
6328 ] autorelease];
6329 }
6330
6331 - (bool) isLoading {
6332 return commercial_ ? [super isLoading] : false;
6333 }
6334
6335 @end
6336 /* }}} */
6337
6338 /* Package List Controller {{{ */
6339 @interface PackageListController : CyteViewController <
6340 UITableViewDataSource,
6341 UITableViewDelegate
6342 > {
6343 _transient Database *database_;
6344 unsigned era_;
6345 _H<NSArray> packages_;
6346 _H<NSArray> sections_;
6347 _H<UITableView, 2> list_;
6348
6349 _H<NSArray> thumbs_;
6350 std::vector<NSInteger> offset_;
6351
6352 _H<NSString> title_;
6353 unsigned reloading_;
6354 }
6355
6356 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6357 - (void) setDelegate:(id)delegate;
6358 - (void) resetCursor;
6359 - (void) clearData;
6360
6361 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6362
6363 @end
6364
6365 @implementation PackageListController
6366
6367 - (NSURL *) referrerURL {
6368 return [self navigationURL];
6369 }
6370
6371 - (bool) isSummarized {
6372 return false;
6373 }
6374
6375 - (bool) showsSections {
6376 return true;
6377 }
6378
6379 - (void) deselectWithAnimation:(BOOL)animated {
6380 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6381 }
6382
6383 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6384 CGRect base = [[self view] bounds];
6385 base.size.height -= bounds.size.height;
6386 base.origin = [list_ frame].origin;
6387
6388 [UIView beginAnimations:nil context:NULL];
6389 [UIView setAnimationBeginsFromCurrentState:YES];
6390 [UIView setAnimationCurve:curve];
6391 [UIView setAnimationDuration:duration];
6392 [list_ setFrame:base];
6393 [UIView commitAnimations];
6394 }
6395
6396 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6397 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6398 }
6399
6400 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6401 [self resizeForKeyboardBounds:bounds duration:0];
6402 }
6403
6404 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6405 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6406 *curve = UIViewAnimationCurveEaseInOut;
6407 else
6408 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6409
6410 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6411 *duration = 0.3;
6412 else
6413 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6414 }
6415
6416 - (void) keyboardWillShow:(NSNotification *)notification {
6417 CGRect bounds;
6418 CGPoint center;
6419 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6420 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6421
6422 NSTimeInterval duration;
6423 UIViewAnimationCurve curve;
6424 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6425
6426 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6427 UIViewController *base = self;
6428 while ([base parentOrPresentingViewController] != nil)
6429 base = [base parentOrPresentingViewController];
6430 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6431 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6432
6433 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6434 intersection.size.height += CYStatusBarHeight();
6435
6436 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6437 }
6438
6439 - (void) keyboardWillHide:(NSNotification *)notification {
6440 NSTimeInterval duration;
6441 UIViewAnimationCurve curve;
6442 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6443
6444 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6445 }
6446
6447 - (void) viewWillAppear:(BOOL)animated {
6448 [super viewWillAppear:animated];
6449
6450 [self resizeForKeyboardBounds:CGRectZero];
6451 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6452 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6453 }
6454
6455 - (void) viewWillDisappear:(BOOL)animated {
6456 [super viewWillDisappear:animated];
6457
6458 [self resizeForKeyboardBounds:CGRectZero];
6459 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6460 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6461 }
6462
6463 - (void) viewDidAppear:(BOOL)animated {
6464 [super viewDidAppear:animated];
6465 [self deselectWithAnimation:animated];
6466 }
6467
6468 - (void) didSelectPackage:(Package *)package {
6469 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6470 [view setDelegate:delegate_];
6471 [[self navigationController] pushViewController:view animated:YES];
6472 }
6473
6474 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6475 NSInteger count([sections_ count]);
6476 return count == 0 ? 1 : count;
6477 }
6478
6479 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6480 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6481 return nil;
6482 return [[sections_ objectAtIndex:section] name];
6483 }
6484
6485 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6486 if ([sections_ count] == 0)
6487 return 0;
6488 return [[sections_ objectAtIndex:section] count];
6489 }
6490
6491 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6492 @synchronized (database_) {
6493 if ([database_ era] != era_)
6494 return nil;
6495
6496 Section *section([sections_ objectAtIndex:[path section]]);
6497 NSInteger row([path row]);
6498 Package *package([packages_ objectAtIndex:([section row] + row)]);
6499 return [[package retain] autorelease];
6500 } }
6501
6502 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6503 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6504 if (cell == nil)
6505 cell = [[[PackageCell alloc] init] autorelease];
6506
6507 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6508 [cell setPackage:package asSummary:[self isSummarized]];
6509 return cell;
6510 }
6511
6512 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6513 Package *package([self packageAtIndexPath:path]);
6514 package = [database_ packageWithName:[package id]];
6515 [self didSelectPackage:package];
6516 }
6517
6518 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6519 return thumbs_;
6520 }
6521
6522 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6523 return offset_[index];
6524 }
6525
6526 - (void) updateHeight {
6527 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6528 }
6529
6530 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6531 if ((self = [super init]) != nil) {
6532 database_ = database;
6533 title_ = [title copy];
6534 [[self navigationItem] setTitle:title_];
6535 } return self;
6536 }
6537
6538 - (void) loadView {
6539 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6540 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6541 [self setView:view];
6542
6543 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6544 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6545 [view addSubview:list_];
6546
6547 // XXX: is 20 the most optimal number here?
6548 [list_ setSectionIndexMinimumDisplayRowCount:20];
6549
6550 [(UITableView *) list_ setDataSource:self];
6551 [list_ setDelegate:self];
6552
6553 [self updateHeight];
6554 }
6555
6556 - (void) releaseSubviews {
6557 list_ = nil;
6558
6559 packages_ = nil;
6560 sections_ = nil;
6561
6562 thumbs_ = nil;
6563 offset_.clear();
6564
6565 [super releaseSubviews];
6566 }
6567
6568 - (void) setDelegate:(id)delegate {
6569 delegate_ = delegate;
6570 }
6571
6572 - (bool) shouldYield {
6573 return false;
6574 }
6575
6576 - (bool) shouldBlock {
6577 return false;
6578 }
6579
6580 - (NSMutableArray *) _reloadPackages {
6581 @synchronized (database_) {
6582 era_ = [database_ era];
6583 NSArray *packages([database_ packages]);
6584
6585 return [NSMutableArray arrayWithArray:packages];
6586 } }
6587
6588 - (void) _reloadData {
6589 if (reloading_ != 0) {
6590 reloading_ = 2;
6591 return;
6592 }
6593
6594 NSMutableArray *packages;
6595
6596 reload:
6597 if ([self shouldYield]) {
6598 do {
6599 UIProgressHUD *hud;
6600
6601 if (![self shouldBlock])
6602 hud = nil;
6603 else {
6604 hud = [delegate_ addProgressHUD];
6605 [hud setText:UCLocalize("LOADING")];
6606 }
6607
6608 reloading_ = 1;
6609 packages = [self yieldToSelector:@selector(_reloadPackages)];
6610
6611 if (hud != nil)
6612 [delegate_ removeProgressHUD:hud];
6613 } while (reloading_ == 2);
6614 } else {
6615 packages = [self _reloadPackages];
6616 }
6617
6618 @synchronized (database_) {
6619 if (era_ != [database_ era])
6620 goto reload;
6621 reloading_ = 0;
6622
6623 thumbs_ = nil;
6624 offset_.clear();
6625
6626 packages_ = packages;
6627
6628 if ([self showsSections])
6629 sections_ = [self sectionsForPackages:packages];
6630 else {
6631 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6632 [section setCount:[packages_ count]];
6633 sections_ = [NSArray arrayWithObject:section];
6634 }
6635
6636 [self updateHeight];
6637
6638 _profile(PackageTable$reloadData$List)
6639 [(UITableView *) list_ setDataSource:self];
6640 [list_ reloadData];
6641 _end
6642 }
6643
6644 PrintTimes();
6645 }
6646
6647 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6648 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6649 size_t end([packages count]);
6650
6651 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6652 Section *section(prefix);
6653
6654 thumbs_ = CollationThumbs_;
6655 offset_ = CollationOffset_;
6656
6657 size_t offset(0);
6658 size_t offsets([CollationStarts_ count]);
6659
6660 NSString *start([CollationStarts_ objectAtIndex:offset]);
6661 size_t length([start length]);
6662
6663 for (size_t index(0); index != end; ++index) {
6664 if (start != nil) {
6665 Package *package([packages objectAtIndex:index]);
6666 NSString *name(PackageName(package, @selector(cyname)));
6667
6668 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6669 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6670 NSString *title([CollationTitles_ objectAtIndex:offset]);
6671 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6672 [sections addObject:section];
6673
6674 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6675 if (start == nil)
6676 break;
6677 length = [start length];
6678 }
6679 }
6680
6681 [section addToCount];
6682 }
6683
6684 for (; offset != offsets; ++offset) {
6685 NSString *title([CollationTitles_ objectAtIndex:offset]);
6686 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6687 [sections addObject:section];
6688 }
6689
6690 if ([prefix count] != 0) {
6691 Section *suffix([sections lastObject]);
6692 [prefix setName:[suffix name]];
6693 [suffix setName:nil];
6694 [sections insertObject:prefix atIndex:(offsets - 1)];
6695 }
6696
6697 return sections;
6698 }
6699
6700 - (void) reloadData {
6701 [super reloadData];
6702
6703 if ([self shouldYield])
6704 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6705 else
6706 [self _reloadData];
6707 }
6708
6709 - (void) resetCursor {
6710 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6711 }
6712
6713 - (void) clearData {
6714 [self updateHeight];
6715
6716 [list_ setDataSource:nil];
6717 [list_ reloadData];
6718
6719 [self resetCursor];
6720 }
6721
6722 @end
6723 /* }}} */
6724 /* Filtered Package List Controller {{{ */
6725 typedef Function<bool, Package *> PackageFilter;
6726 typedef Function<void, NSMutableArray *> PackageSorter;
6727 @interface FilteredPackageListController : PackageListController {
6728 PackageFilter filter_;
6729 PackageSorter sorter_;
6730 }
6731
6732 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6733
6734 - (void) setFilter:(PackageFilter)filter;
6735 - (void) setSorter:(PackageSorter)sorter;
6736
6737 @end
6738
6739 @implementation FilteredPackageListController
6740
6741 - (void) setFilter:(PackageFilter)filter {
6742 @synchronized (self) {
6743 filter_ = filter;
6744 } }
6745
6746 - (void) setSorter:(PackageSorter)sorter {
6747 @synchronized (self) {
6748 sorter_ = sorter;
6749 } }
6750
6751 - (NSMutableArray *) _reloadPackages {
6752 @synchronized (database_) {
6753 era_ = [database_ era];
6754
6755 NSArray *packages([database_ packages]);
6756 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6757
6758 PackageFilter filter;
6759 PackageSorter sorter;
6760
6761 @synchronized (self) {
6762 filter = filter_;
6763 sorter = sorter_;
6764 }
6765
6766 _profile(PackageTable$reloadData$Filter)
6767 for (Package *package in packages)
6768 if ([package valid] && filter(package))
6769 [filtered addObject:package];
6770 _end
6771
6772 if (sorter)
6773 sorter(filtered);
6774 return filtered;
6775 } }
6776
6777 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6778 if ((self = [super initWithDatabase:database title:title]) != nil) {
6779 [self setFilter:filter];
6780 } return self;
6781 }
6782
6783 @end
6784 /* }}} */
6785
6786 /* Home Controller {{{ */
6787 @interface HomeController : CydiaWebViewController {
6788 CFRunLoopRef runloop_;
6789 SCNetworkReachabilityRef reachability_;
6790 }
6791
6792 @end
6793
6794 @implementation HomeController
6795
6796 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6797 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6798 }
6799
6800 - (id) init {
6801 if ((self = [super init]) != nil) {
6802 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6803 [self reloadData];
6804
6805 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6806 if (reachability_ != NULL) {
6807 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6808 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6809
6810 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6811 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6812 runloop_ = runloop;
6813 }
6814 } return self;
6815 }
6816
6817 - (void) dealloc {
6818 if (reachability_ != NULL && runloop_ != NULL)
6819 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6820 [super dealloc];
6821 }
6822
6823 - (NSURL *) navigationURL {
6824 return [NSURL URLWithString:@"cydia://home"];
6825 }
6826
6827 - (void) aboutButtonClicked {
6828 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6829
6830 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6831 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6832 [alert setCancelButtonIndex:0];
6833
6834 [alert setMessage:
6835 @"Copyright \u00a9 2008-2014\n"
6836 "SaurikIT, LLC\n"
6837 "\n"
6838 "Jay Freeman (saurik)\n"
6839 "saurik@saurik.com\n"
6840 "http://www.saurik.com/"
6841 ];
6842
6843 [alert show];
6844 }
6845
6846 - (UIBarButtonItem *) leftButton {
6847 return [[[UIBarButtonItem alloc]
6848 initWithTitle:UCLocalize("ABOUT")
6849 style:UIBarButtonItemStylePlain
6850 target:self
6851 action:@selector(aboutButtonClicked)
6852 ] autorelease];
6853 }
6854
6855 @end
6856 /* }}} */
6857
6858 /* Cydia Navigation Controller Interface {{{ */
6859 @interface UINavigationController (Cydia)
6860
6861 - (NSArray *) navigationURLCollection;
6862 - (void) unloadData;
6863
6864 @end
6865 /* }}} */
6866
6867 /* Cydia Tab Bar Controller {{{ */
6868 @interface CydiaTabBarController : CyteTabBarController <
6869 UITabBarControllerDelegate,
6870 FetchDelegate
6871 > {
6872 _transient Database *database_;
6873
6874 _H<UIActivityIndicatorView> indicator_;
6875
6876 bool updating_;
6877 // XXX: ok, "updatedelegate_"?...
6878 _transient NSObject<CydiaDelegate> *updatedelegate_;
6879 }
6880
6881 - (NSArray *) navigationURLCollection;
6882 - (void) beginUpdate;
6883 - (BOOL) updating;
6884
6885 @end
6886
6887 @implementation CydiaTabBarController
6888
6889 - (NSArray *) navigationURLCollection {
6890 NSMutableArray *items([NSMutableArray array]);
6891
6892 // XXX: Should this deal with transient view controllers?
6893 for (id navigation in [self viewControllers]) {
6894 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6895 if (stack != nil)
6896 [items addObject:stack];
6897 }
6898
6899 return items;
6900 }
6901
6902 - (id) initWithDatabase:(Database *)database {
6903 if ((self = [super init]) != nil) {
6904 database_ = database;
6905 [self setDelegate:self];
6906
6907 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6908 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6909
6910 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6911 } return self;
6912 }
6913
6914 - (void) setUpdate:(NSDate *)date {
6915 [self beginUpdate];
6916 }
6917
6918 - (void) beginUpdate {
6919 if (updating_)
6920 return;
6921
6922 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6923 UITabBarItem *item([controller tabBarItem]);
6924
6925 [item setBadgeValue:@""];
6926 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6927
6928 [indicator_ startAnimating];
6929 [badge addSubview:indicator_];
6930
6931 [updatedelegate_ retainNetworkActivityIndicator];
6932 updating_ = true;
6933
6934 [NSThread
6935 detachNewThreadSelector:@selector(performUpdate)
6936 toTarget:self
6937 withObject:nil
6938 ];
6939 }
6940
6941 - (void) performUpdate {
6942 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6943
6944 SourceStatus status(self, database_);
6945 [database_ updateWithStatus:status];
6946
6947 [self
6948 performSelectorOnMainThread:@selector(completeUpdate)
6949 withObject:nil
6950 waitUntilDone:NO
6951 ];
6952
6953 [pool release];
6954 }
6955
6956 - (void) stopUpdateWithSelector:(SEL)selector {
6957 updating_ = false;
6958 [updatedelegate_ releaseNetworkActivityIndicator];
6959
6960 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6961 [[controller tabBarItem] setBadgeValue:nil];
6962
6963 [indicator_ removeFromSuperview];
6964 [indicator_ stopAnimating];
6965
6966 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6967 }
6968
6969 - (void) completeUpdate {
6970 if (!updating_)
6971 return;
6972 [self stopUpdateWithSelector:@selector(reloadData)];
6973 }
6974
6975 - (void) cancelUpdate {
6976 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6977 }
6978
6979 - (void) cancelPressed {
6980 [self cancelUpdate];
6981 }
6982
6983 - (BOOL) updating {
6984 return updating_;
6985 }
6986
6987 - (bool) isSourceCancelled {
6988 return !updating_;
6989 }
6990
6991 - (void) startSourceFetch:(NSString *)uri {
6992 }
6993
6994 - (void) stopSourceFetch:(NSString *)uri {
6995 }
6996
6997 - (void) setUpdateDelegate:(id)delegate {
6998 updatedelegate_ = delegate;
6999 }
7000
7001 @end
7002 /* }}} */
7003
7004 /* Cydia Navigation Controller Implementation {{{ */
7005 @implementation UINavigationController (Cydia)
7006
7007 - (NSArray *) navigationURLCollection {
7008 NSMutableArray *stack([NSMutableArray array]);
7009
7010 for (CyteViewController *controller in [self viewControllers]) {
7011 NSString *url = [[controller navigationURL] absoluteString];
7012 if (url != nil)
7013 [stack addObject:url];
7014 }
7015
7016 return stack;
7017 }
7018
7019 - (void) reloadData {
7020 [super reloadData];
7021
7022 UIViewController *visible([self visibleViewController]);
7023 if (visible != nil)
7024 [visible reloadData];
7025
7026 // on the iPad, this view controller is ALSO visible. :(
7027 if (IsWildcat_)
7028 if (UIViewController *top = [self topViewController])
7029 if (top != visible)
7030 [top reloadData];
7031 }
7032
7033 - (void) unloadData {
7034 for (CyteViewController *page in [self viewControllers])
7035 [page unloadData];
7036
7037 [super unloadData];
7038 }
7039
7040 @end
7041 /* }}} */
7042
7043 /* Cydia:// Protocol {{{ */
7044 @interface CydiaURLProtocol : NSURLProtocol {
7045 }
7046
7047 @end
7048
7049 @implementation CydiaURLProtocol
7050
7051 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7052 NSURL *url([request URL]);
7053 if (url == nil)
7054 return NO;
7055
7056 NSString *scheme([[url scheme] lowercaseString]);
7057 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7058 return YES;
7059 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7060 return YES;
7061
7062 return NO;
7063 }
7064
7065 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7066 return request;
7067 }
7068
7069 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7070 id<NSURLProtocolClient> client([self client]);
7071 if (icon == nil)
7072 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7073 else {
7074 NSData *data(UIImagePNGRepresentation(icon));
7075
7076 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7077 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7078 [client URLProtocol:self didLoadData:data];
7079 [client URLProtocolDidFinishLoading:self];
7080 }
7081 }
7082
7083 - (void) startLoading {
7084 id<NSURLProtocolClient> client([self client]);
7085 NSURLRequest *request([self request]);
7086
7087 NSURL *url([request URL]);
7088 NSString *href([url absoluteString]);
7089 NSString *scheme([[url scheme] lowercaseString]);
7090
7091 NSString *path;
7092
7093 if ([scheme isEqualToString:@"cydia"])
7094 path = [href substringFromIndex:8];
7095 else if ([scheme isEqualToString:@"about"])
7096 path = [href substringFromIndex:12];
7097 else _assert(false);
7098
7099 NSRange slash([path rangeOfString:@"/"]);
7100
7101 NSString *command;
7102 if (slash.location == NSNotFound) {
7103 command = path;
7104 path = nil;
7105 } else {
7106 command = [path substringToIndex:slash.location];
7107 path = [path substringFromIndex:(slash.location + 1)];
7108 }
7109
7110 Database *database([Database sharedInstance]);
7111
7112 if ([command isEqualToString:@"package-icon"]) {
7113 if (path == nil)
7114 goto fail;
7115 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7116 Package *package([database packageWithName:path]);
7117 if (package == nil)
7118 goto fail;
7119 [package parse];
7120 UIImage *icon([package icon]);
7121 [self _returnPNGWithImage:icon forRequest:request];
7122 } else if ([command isEqualToString:@"uikit-image"]) {
7123 if (path == nil)
7124 goto fail;
7125 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7126 UIImage *icon(_UIImageWithName(path));
7127 [self _returnPNGWithImage:icon forRequest:request];
7128 } else if ([command isEqualToString:@"section-icon"]) {
7129 if (path == nil)
7130 goto fail;
7131 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7132 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7133 if (icon == nil)
7134 icon = [UIImage applicationImageNamed:@"unknown.png"];
7135 [self _returnPNGWithImage:icon forRequest:request];
7136 } else fail: {
7137 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7138 }
7139 }
7140
7141 - (void) stopLoading {
7142 }
7143
7144 @end
7145 /* }}} */
7146
7147 /* Section Controller {{{ */
7148 @interface SectionController : FilteredPackageListController {
7149 _H<NSString> key_;
7150 _H<NSString> section_;
7151 }
7152
7153 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7154
7155 @end
7156
7157 @implementation SectionController
7158
7159 - (NSURL *) referrerURL {
7160 NSString *name(section_);
7161 name = name ?: @"*";
7162 NSString *key(key_);
7163 key = key ?: @"*";
7164 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7165 }
7166
7167 - (NSURL *) navigationURL {
7168 NSString *name(section_);
7169 name = name ?: @"*";
7170 NSString *key(key_);
7171 key = key ?: @"*";
7172 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7173 }
7174
7175 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7176 NSString *title;
7177 if (section == nil)
7178 title = UCLocalize("ALL_PACKAGES");
7179 else if (![section isEqual:@""])
7180 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7181 else
7182 title = UCLocalize("NO_SECTION");
7183
7184 if ((self = [super initWithDatabase:database title:title]) != nil) {
7185 key_ = [source key];
7186 section_ = section;
7187 } return self;
7188 }
7189
7190 - (void) reloadData {
7191 Source *source([database_ sourceWithKey:key_]);
7192 _H<NSString> name(section_);
7193
7194 [self setFilter:[=](Package *package) {
7195 NSString *section([package section]);
7196
7197 return (
7198 name == nil ||
7199 section == nil && [name length] == 0 ||
7200 [name isEqualToString:section]
7201 ) && (
7202 source == nil ||
7203 [package source] == source
7204 ) && [package visible];
7205 }];
7206
7207 [super reloadData];
7208 }
7209
7210 @end
7211 /* }}} */
7212 /* Sections Controller {{{ */
7213 @interface SectionsController : CyteViewController <
7214 UITableViewDataSource,
7215 UITableViewDelegate
7216 > {
7217 _transient Database *database_;
7218 _H<NSString> key_;
7219 _H<NSMutableArray> sections_;
7220 _H<NSMutableArray> filtered_;
7221 _H<UITableView, 2> list_;
7222 }
7223
7224 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7225 - (void) editButtonClicked;
7226
7227 @end
7228
7229 @implementation SectionsController
7230
7231 - (NSURL *) navigationURL {
7232 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7233 }
7234
7235 - (Source *) source {
7236 if (key_ == nil)
7237 return nil;
7238 return [database_ sourceWithKey:key_];
7239 }
7240
7241 - (void) updateNavigationItem {
7242 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7243 if ([sections_ count] == 0) {
7244 [[self navigationItem] setRightBarButtonItem:nil];
7245 } else {
7246 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7247 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7248 target:self
7249 action:@selector(editButtonClicked)
7250 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7251 }
7252 }
7253
7254 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7255 [super setEditing:editing animated:animated];
7256
7257 if (editing)
7258 [list_ reloadData];
7259 else
7260 [delegate_ updateData];
7261
7262 [self updateNavigationItem];
7263 }
7264
7265 - (void) viewDidAppear:(BOOL)animated {
7266 [super viewDidAppear:animated];
7267 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7268 }
7269
7270 - (void) viewWillDisappear:(BOOL)animated {
7271 [super viewWillDisappear:animated];
7272 [self setEditing:NO];
7273 }
7274
7275 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7276 Section *section = nil;
7277 int index = [indexPath row];
7278 if (![self isEditing]) {
7279 index -= 1;
7280 if (index >= 0)
7281 section = [filtered_ objectAtIndex:index];
7282 } else {
7283 section = [sections_ objectAtIndex:index];
7284 }
7285 return section;
7286 }
7287
7288 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7289 if ([self isEditing])
7290 return [sections_ count];
7291 else
7292 return [filtered_ count] + 1;
7293 }
7294
7295 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7296 return 45.0f;
7297 }*/
7298
7299 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7300 static NSString *reuseIdentifier = @"SectionCell";
7301
7302 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7303 if (cell == nil)
7304 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7305
7306 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7307
7308 return cell;
7309 }
7310
7311 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7312 if ([self isEditing])
7313 return;
7314
7315 Section *section = [self sectionAtIndexPath:indexPath];
7316
7317 SectionController *controller = [[[SectionController alloc]
7318 initWithDatabase:database_
7319 source:[self source]
7320 section:[section name]
7321 ] autorelease];
7322 [controller setDelegate:delegate_];
7323
7324 [[self navigationController] pushViewController:controller animated:YES];
7325 }
7326
7327 - (void) loadView {
7328 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7329 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7330 [list_ setRowHeight:46];
7331 [(UITableView *) list_ setDataSource:self];
7332 [list_ setDelegate:self];
7333 [self setView:list_];
7334 }
7335
7336 - (void) viewDidLoad {
7337 [super viewDidLoad];
7338
7339 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7340 }
7341
7342 - (void) releaseSubviews {
7343 list_ = nil;
7344
7345 sections_ = nil;
7346 filtered_ = nil;
7347
7348 [super releaseSubviews];
7349 }
7350
7351 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7352 if ((self = [super init]) != nil) {
7353 database_ = database;
7354 key_ = [source key];
7355 } return self;
7356 }
7357
7358 - (void) reloadData {
7359 [super reloadData];
7360
7361 NSArray *packages = [database_ packages];
7362
7363 sections_ = [NSMutableArray arrayWithCapacity:16];
7364 filtered_ = [NSMutableArray arrayWithCapacity:16];
7365
7366 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7367
7368 Source *source([self source]);
7369
7370 _trace();
7371 for (Package *package in packages) {
7372 if (source != nil && [package source] != source)
7373 continue;
7374
7375 NSString *name([package section]);
7376 NSString *key(name == nil ? @"" : name);
7377
7378 Section *section;
7379
7380 _profile(SectionsView$reloadData$Section)
7381 section = [sections objectForKey:key];
7382 if (section == nil) {
7383 _profile(SectionsView$reloadData$Section$Allocate)
7384 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7385 [sections setObject:section forKey:key];
7386 _end
7387 }
7388 _end
7389
7390 [section addToCount];
7391
7392 _profile(SectionsView$reloadData$Filter)
7393 if (![package valid] || ![package visible])
7394 continue;
7395 _end
7396
7397 [section addToRow];
7398 }
7399 _trace();
7400
7401 [sections_ addObjectsFromArray:[sections allValues]];
7402
7403 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7404
7405 for (Section *section in (id) sections_) {
7406 size_t count([section row]);
7407 if (count == 0)
7408 continue;
7409
7410 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7411 [section setCount:count];
7412 [filtered_ addObject:section];
7413 }
7414
7415 [self updateNavigationItem];
7416 [list_ reloadData];
7417 _trace();
7418 }
7419
7420 - (void) editButtonClicked {
7421 [self setEditing:![self isEditing] animated:YES];
7422 }
7423
7424 @end
7425 /* }}} */
7426
7427 /* Changes Controller {{{ */
7428 @interface ChangesController : FilteredPackageListController {
7429 unsigned upgrades_;
7430 }
7431
7432 - (id) initWithDatabase:(Database *)database;
7433
7434 @end
7435
7436 @implementation ChangesController
7437
7438 - (NSURL *) referrerURL {
7439 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7440 }
7441
7442 - (NSURL *) navigationURL {
7443 return [NSURL URLWithString:@"cydia://changes"];
7444 }
7445
7446 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7447 @synchronized (database_) {
7448 if ([database_ era] != era_)
7449 return nil;
7450
7451 NSUInteger sectionIndex([path section]);
7452 if (sectionIndex >= [sections_ count])
7453 return nil;
7454 Section *section([sections_ objectAtIndex:sectionIndex]);
7455 NSInteger row([path row]);
7456 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7457 } }
7458
7459 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7460 NSString *context([alert context]);
7461
7462 if ([context isEqualToString:@"norefresh"])
7463 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7464 }
7465
7466 - (void) setLeftBarButtonItem {
7467 if ([delegate_ updating])
7468 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7469 initWithTitle:UCLocalize("CANCEL")
7470 style:UIBarButtonItemStyleDone
7471 target:self
7472 action:@selector(cancelButtonClicked)
7473 ] autorelease] animated:YES];
7474 else
7475 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7476 initWithTitle:UCLocalize("REFRESH")
7477 style:UIBarButtonItemStylePlain
7478 target:self
7479 action:@selector(refreshButtonClicked)
7480 ] autorelease] animated:YES];
7481 }
7482
7483 - (void) refreshButtonClicked {
7484 if ([delegate_ requestUpdate])
7485 [self setLeftBarButtonItem];
7486 }
7487
7488 - (void) cancelButtonClicked {
7489 [delegate_ cancelUpdate];
7490 }
7491
7492 - (void) upgradeButtonClicked {
7493 [delegate_ distUpgrade];
7494 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7495 }
7496
7497 - (bool) shouldYield {
7498 return true;
7499 }
7500
7501 - (bool) shouldBlock {
7502 return true;
7503 }
7504
7505 - (void) useFilter {
7506 @synchronized (self) {
7507 [self setFilter:[](Package *package) {
7508 return [package upgradableAndEssential:YES] || [package visible];
7509 }];
7510
7511 [self setSorter:[](NSMutableArray *packages) {
7512 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7513 }];
7514 } }
7515
7516 - (id) initWithDatabase:(Database *)database {
7517 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7518 [self useFilter];
7519 } return self;
7520 }
7521
7522 - (void) viewDidLoad {
7523 [super viewDidLoad];
7524 [self setLeftBarButtonItem];
7525 }
7526
7527 - (void) viewWillAppear:(BOOL)animated {
7528 [super viewWillAppear:animated];
7529 [self setLeftBarButtonItem];
7530 }
7531
7532 - (void) reloadData {
7533 [self setLeftBarButtonItem];
7534 [super reloadData];
7535 }
7536
7537 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7538 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7539
7540 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7541 Section *ignored = nil;
7542 Section *section = nil;
7543 time_t last = 0;
7544
7545 upgrades_ = 0;
7546 bool unseens = false;
7547
7548 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7549
7550 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7551 Package *package = [packages objectAtIndex:offset];
7552
7553 BOOL uae = [package upgradableAndEssential:YES];
7554
7555 if (!uae) {
7556 unseens = true;
7557 time_t seen([package seen]);
7558
7559 if (section == nil || last != seen) {
7560 last = seen;
7561
7562 NSString *name;
7563 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7564 [name autorelease];
7565
7566 _profile(ChangesController$reloadData$Allocate)
7567 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7568 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7569 [sections addObject:section];
7570 _end
7571 }
7572
7573 [section addToCount];
7574 } else if ([package ignored]) {
7575 if (ignored == nil) {
7576 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7577 }
7578 [ignored addToCount];
7579 } else {
7580 ++upgrades_;
7581 [upgradable addToCount];
7582 }
7583 }
7584 _trace();
7585
7586 CFRelease(formatter);
7587
7588 if (unseens) {
7589 Section *last = [sections lastObject];
7590 size_t count = [last count];
7591 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7592 [sections removeLastObject];
7593 }
7594
7595 if ([ignored count] != 0)
7596 [sections insertObject:ignored atIndex:0];
7597 if (upgrades_ != 0)
7598 [sections insertObject:upgradable atIndex:0];
7599
7600 [list_ reloadData];
7601
7602 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7603 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7604 style:UIBarButtonItemStylePlain
7605 target:self
7606 action:@selector(upgradeButtonClicked)
7607 ] autorelease]) animated:YES];
7608
7609 return sections;
7610 }
7611
7612 @end
7613 /* }}} */
7614 /* Search Controller {{{ */
7615 @interface SearchController : FilteredPackageListController <
7616 UISearchBarDelegate
7617 > {
7618 _H<UISearchBar, 1> search_;
7619 BOOL searchloaded_;
7620 bool summary_;
7621 }
7622
7623 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7624 - (void) reloadData;
7625
7626 @end
7627
7628 @implementation SearchController
7629
7630 - (NSURL *) referrerURL {
7631 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7632 }
7633
7634 - (NSURL *) navigationURL {
7635 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7636 return [NSURL URLWithString:@"cydia://search"];
7637 else
7638 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7639 }
7640
7641 - (NSArray *) termsForQuery:(NSString *)query {
7642 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7643 for (NSString *component in [query componentsSeparatedByString:@" "])
7644 if ([component length] != 0)
7645 [terms addObject:component];
7646
7647 return terms;
7648 }
7649
7650 - (void) useSearch {
7651 _H<NSArray> query([self termsForQuery:[search_ text]]);
7652 summary_ = false;
7653
7654 @synchronized (self) {
7655 [self setFilter:[=](Package *package) {
7656 if (![package unfiltered])
7657 return false;
7658 if (![package matches:query])
7659 return false;
7660 return true;
7661 }];
7662
7663 [self setSorter:[](NSMutableArray *packages) {
7664 [packages radixSortUsingSelector:@selector(rank)];
7665 }];
7666 }
7667
7668 [self clearData];
7669 [self reloadData];
7670 }
7671
7672 - (void) usePrefix:(NSString *)prefix {
7673 _H<NSString> query(prefix);
7674 summary_ = true;
7675
7676 @synchronized (self) {
7677 [self setFilter:[=](Package *package) {
7678 if ([query length] == 0)
7679 return false;
7680 if (![package unfiltered])
7681 return false;
7682 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7683 return false;
7684 return true;
7685 }];
7686
7687 [self setSorter:nullptr];
7688 }
7689
7690 [self reloadData];
7691 }
7692
7693 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7694 [self clearData];
7695 [self usePrefix:[search_ text]];
7696 }
7697
7698 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7699 [search_ resignFirstResponder];
7700 [self useSearch];
7701 }
7702
7703 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7704 [search_ setText:@""];
7705 [self searchBarButtonClicked:searchBar];
7706 }
7707
7708 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7709 [self searchBarButtonClicked:searchBar];
7710 }
7711
7712 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7713 [self usePrefix:text];
7714 }
7715
7716 - (bool) shouldYield {
7717 return YES;
7718 }
7719
7720 - (bool) shouldBlock {
7721 return !summary_;
7722 }
7723
7724 - (bool) isSummarized {
7725 return summary_;
7726 }
7727
7728 - (bool) showsSections {
7729 return false;
7730 }
7731
7732 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7733 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7734 search_ = [[[UISearchBar alloc] init] autorelease];
7735 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7736 [search_ setDelegate:self];
7737
7738 UITextField *textField;
7739 if ([search_ respondsToSelector:@selector(searchField)])
7740 textField = [search_ searchField];
7741 else
7742 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7743
7744 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7745 [textField setEnablesReturnKeyAutomatically:NO];
7746 [[self navigationItem] setTitleView:textField];
7747
7748 if (query != nil)
7749 [search_ setText:query];
7750 [self useSearch];
7751 } return self;
7752 }
7753
7754 - (void) viewDidAppear:(BOOL)animated {
7755 [super viewDidAppear:animated];
7756
7757 if (!searchloaded_) {
7758 searchloaded_ = YES;
7759 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7760 [search_ layoutSubviews];
7761 }
7762
7763 if ([self isSummarized])
7764 [search_ becomeFirstResponder];
7765 }
7766
7767 - (void) reloadData {
7768 [self resetCursor];
7769 [super reloadData];
7770 }
7771
7772 - (void) didSelectPackage:(Package *)package {
7773 [search_ resignFirstResponder];
7774 [super didSelectPackage:package];
7775 }
7776
7777 @end
7778 /* }}} */
7779 /* Package Settings Controller {{{ */
7780 @interface PackageSettingsController : CyteViewController <
7781 UITableViewDataSource,
7782 UITableViewDelegate
7783 > {
7784 _transient Database *database_;
7785 _H<NSString> name_;
7786 _H<Package> package_;
7787 _H<UITableView, 2> table_;
7788 _H<UISwitch> subscribedSwitch_;
7789 _H<UISwitch> ignoredSwitch_;
7790 _H<UITableViewCell> subscribedCell_;
7791 _H<UITableViewCell> ignoredCell_;
7792 }
7793
7794 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7795
7796 @end
7797
7798 @implementation PackageSettingsController
7799
7800 - (NSURL *) navigationURL {
7801 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7802 }
7803
7804 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7805 if (package_ == nil)
7806 return 0;
7807
7808 if ([package_ installed] == nil)
7809 return 1;
7810 else
7811 return 2;
7812 }
7813
7814 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7815 if (package_ == nil)
7816 return 0;
7817
7818 // both sections contain just one item right now.
7819 return 1;
7820 }
7821
7822 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7823 return nil;
7824 }
7825
7826 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7827 if (section == 0)
7828 return UCLocalize("SHOW_ALL_CHANGES_EX");
7829 else
7830 return UCLocalize("IGNORE_UPGRADES_EX");
7831 }
7832
7833 - (void) onSubscribed:(id)control {
7834 bool value([control isOn]);
7835 if (package_ == nil)
7836 return;
7837 if ([package_ setSubscribed:value])
7838 [delegate_ updateData];
7839 }
7840
7841 - (void) _updateIgnored {
7842 const char *package([name_ UTF8String]);
7843 bool on([ignoredSwitch_ isOn]);
7844
7845 pid_t pid(ExecFork());
7846 if (pid == 0) {
7847 FILE *dpkg(popen("dpkg --set-selections", "w"));
7848 fwrite(package, strlen(package), 1, dpkg);
7849
7850 if (on)
7851 fwrite(" hold\n", 6, 1, dpkg);
7852 else
7853 fwrite(" install\n", 9, 1, dpkg);
7854
7855 pclose(dpkg);
7856
7857 exit(0);
7858 } ReapZombie(pid);
7859 }
7860
7861 - (void) onIgnored:(id)control {
7862 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7863 [invocation setTarget:self];
7864 [invocation setSelector:@selector(_updateIgnored)];
7865
7866 [delegate_ reloadDataWithInvocation:invocation];
7867 }
7868
7869 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7870 if (package_ == nil)
7871 return nil;
7872
7873 switch ([indexPath section]) {
7874 case 0: return subscribedCell_;
7875 case 1: return ignoredCell_;
7876
7877 _nodefault
7878 }
7879
7880 return nil;
7881 }
7882
7883 - (void) loadView {
7884 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7885 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7886 [self setView:view];
7887
7888 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7889 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7890 [(UITableView *) table_ setDataSource:self];
7891 [table_ setDelegate:self];
7892 [view addSubview:table_];
7893
7894 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7895 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7896 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7897
7898 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7899 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7900 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7901
7902 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7903 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7904 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7905 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7906
7907 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7908 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7909 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7910 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7911 }
7912
7913 - (void) viewDidLoad {
7914 [super viewDidLoad];
7915
7916 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7917 }
7918
7919 - (void) releaseSubviews {
7920 ignoredCell_ = nil;
7921 subscribedCell_ = nil;
7922 table_ = nil;
7923 ignoredSwitch_ = nil;
7924 subscribedSwitch_ = nil;
7925
7926 [super releaseSubviews];
7927 }
7928
7929 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7930 if ((self = [super init]) != nil) {
7931 database_ = database;
7932 name_ = package;
7933 } return self;
7934 }
7935
7936 - (void) reloadData {
7937 [super reloadData];
7938
7939 package_ = [database_ packageWithName:name_];
7940
7941 if (package_ != nil) {
7942 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7943 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7944 } // XXX: what now, G?
7945
7946 [table_ reloadData];
7947 }
7948
7949 @end
7950 /* }}} */
7951
7952 /* Installed Controller {{{ */
7953 @interface InstalledController : FilteredPackageListController {
7954 bool sectioned_;
7955 }
7956
7957 - (id) initWithDatabase:(Database *)database;
7958 - (void) queueStatusDidChange;
7959
7960 @end
7961
7962 @implementation InstalledController
7963
7964 - (NSURL *) referrerURL {
7965 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7966 }
7967
7968 - (NSURL *) navigationURL {
7969 return [NSURL URLWithString:@"cydia://installed"];
7970 }
7971
7972 - (void) useRecent {
7973 sectioned_ = false;
7974
7975 @synchronized (self) {
7976 [self setFilter:[](Package *package) {
7977 return ![package uninstalled] && package->role_ < 7;
7978 }];
7979
7980 [self setSorter:[](NSMutableArray *packages) {
7981 [packages radixSortUsingSelector:@selector(recent)];
7982 }];
7983 } }
7984
7985 - (void) useFilter:(UISegmentedControl *)segmented {
7986 NSInteger selected([segmented selectedSegmentIndex]);
7987 if (selected == 2)
7988 return [self useRecent];
7989 bool simple(selected == 0);
7990 sectioned_ = true;
7991
7992 @synchronized (self) {
7993 [self setFilter:[=](Package *package) {
7994 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7995 }];
7996
7997 [self setSorter:nullptr];
7998 } }
7999
8000 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8001 if (sectioned_)
8002 return [super sectionsForPackages:packages];
8003
8004 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8005
8006 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8007 Section *section(nil);
8008 time_t last(0);
8009
8010 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8011 Package *package([packages objectAtIndex:offset]);
8012
8013 time_t upgraded([package upgraded]);
8014 if (upgraded < 1168364520)
8015 upgraded = 0;
8016 else
8017 upgraded -= upgraded % (60 * 60 * 24);
8018
8019 if (section == nil || upgraded != last) {
8020 last = upgraded;
8021
8022 NSString *name;
8023 if (upgraded == 0)
8024 continue; // XXX: name = UCLocalize("...");
8025 else {
8026 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8027 [name autorelease];
8028 }
8029
8030 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8031 [sections addObject:section];
8032 }
8033
8034 [section addToCount];
8035 }
8036
8037 CFRelease(formatter);
8038 return sections;
8039 }
8040
8041 - (id) initWithDatabase:(Database *)database {
8042 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8043 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8044 [segmented setSelectedSegmentIndex:0];
8045 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8046 [[self navigationItem] setTitleView:segmented];
8047
8048 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8049 [self useFilter:segmented];
8050
8051 [self queueStatusDidChange];
8052 } return self;
8053 }
8054
8055 #if !AlwaysReload
8056 - (void) queueButtonClicked {
8057 [delegate_ queue];
8058 }
8059 #endif
8060
8061 - (void) queueStatusDidChange {
8062 #if !AlwaysReload
8063 if (Queuing_) {
8064 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8065 initWithTitle:UCLocalize("QUEUE")
8066 style:UIBarButtonItemStyleDone
8067 target:self
8068 action:@selector(queueButtonClicked)
8069 ] autorelease]];
8070 } else {
8071 [[self navigationItem] setLeftBarButtonItem:nil];
8072 }
8073 #endif
8074 }
8075
8076 - (void) modeChanged:(UISegmentedControl *)segmented {
8077 [self useFilter:segmented];
8078 [self reloadData];
8079 }
8080
8081 @end
8082 /* }}} */
8083
8084 /* Source Cell {{{ */
8085 @interface SourceCell : CyteTableViewCell <
8086 CyteTableViewCellDelegate,
8087 SourceDelegate
8088 > {
8089 _H<Source, 1> source_;
8090 _H<NSURL> url_;
8091 _H<UIImage> icon_;
8092 _H<NSString> origin_;
8093 _H<NSString> label_;
8094 _H<UIActivityIndicatorView> indicator_;
8095 }
8096
8097 - (void) setSource:(Source *)source;
8098 - (void) setFetch:(NSNumber *)fetch;
8099
8100 @end
8101
8102 @implementation SourceCell
8103
8104 - (void) _setImage:(NSArray *)data {
8105 if ([url_ isEqual:[data objectAtIndex:0]]) {
8106 icon_ = [data objectAtIndex:1];
8107 [content_ setNeedsDisplay];
8108 }
8109 }
8110
8111 - (void) _setSource:(NSURL *) url {
8112 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8113
8114 if (NSData *data = [NSURLConnection
8115 sendSynchronousRequest:[NSURLRequest
8116 requestWithURL:url
8117 cachePolicy:NSURLRequestUseProtocolCachePolicy
8118 timeoutInterval:10
8119 ]
8120
8121 returningResponse:NULL
8122 error:NULL
8123 ])
8124 if (UIImage *image = [UIImage imageWithData:data])
8125 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8126
8127 [pool release];
8128 }
8129
8130 - (void) setSource:(Source *)source {
8131 source_ = source;
8132 [source_ setDelegate:self];
8133
8134 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8135
8136 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8137
8138 origin_ = [source name];
8139 label_ = [source rooturi];
8140
8141 [content_ setNeedsDisplay];
8142
8143 url_ = [source iconURL];
8144 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8145 }
8146
8147 - (void) setAllSource {
8148 source_ = nil;
8149 [indicator_ stopAnimating];
8150
8151 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8152 origin_ = UCLocalize("ALL_SOURCES");
8153 label_ = UCLocalize("ALL_SOURCES_EX");
8154 [content_ setNeedsDisplay];
8155 }
8156
8157 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8158 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8159 UIView *content([self contentView]);
8160 CGRect bounds([content bounds]);
8161
8162 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8163 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8164 [content_ setBackgroundColor:[UIColor whiteColor]];
8165 [content addSubview:content_];
8166
8167 [content_ setDelegate:self];
8168 [content_ setOpaque:YES];
8169
8170 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8171 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8172 [content addSubview:indicator_];
8173
8174 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8175 } return self;
8176 }
8177
8178 - (void) layoutSubviews {
8179 [super layoutSubviews];
8180
8181 UIView *content([self contentView]);
8182 CGRect bounds([content bounds]);
8183
8184 CGRect frame([indicator_ frame]);
8185 frame.origin.x = bounds.size.width - frame.size.width;
8186 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8187
8188 if (kCFCoreFoundationVersionNumber < 800)
8189 frame.origin.x -= 8;
8190 [indicator_ setFrame:frame];
8191 }
8192
8193 - (NSString *) accessibilityLabel {
8194 return origin_;
8195 }
8196
8197 - (void) drawContentRect:(CGRect)rect {
8198 bool highlighted(highlighted_);
8199 float width(rect.size.width);
8200
8201 if (icon_ != nil) {
8202 CGRect rect;
8203 rect.size = [(UIImage *) icon_ size];
8204
8205 while (rect.size.width > 32 || rect.size.height > 32) {
8206 rect.size.width /= 2;
8207 rect.size.height /= 2;
8208 }
8209
8210 rect.origin.x = 26 - rect.size.width / 2;
8211 rect.origin.y = 26 - rect.size.height / 2;
8212
8213 [icon_ drawInRect:Retina(rect)];
8214 }
8215
8216 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8217 UISetColor(White_);
8218
8219 if (!highlighted)
8220 UISetColor(Black_);
8221 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8222
8223 if (!highlighted)
8224 UISetColor(Gray_);
8225 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8226 }
8227
8228 - (void) setFetch:(NSNumber *)fetch {
8229 if ([fetch boolValue])
8230 [indicator_ startAnimating];
8231 else
8232 [indicator_ stopAnimating];
8233 }
8234
8235 @end
8236 /* }}} */
8237 /* Sources Controller {{{ */
8238 @interface SourcesController : CyteViewController <
8239 UITableViewDataSource,
8240 UITableViewDelegate
8241 > {
8242 _transient Database *database_;
8243 unsigned era_;
8244
8245 _H<UITableView, 2> list_;
8246 _H<NSMutableArray> sources_;
8247 int offset_;
8248
8249 _H<NSString> href_;
8250 _H<UIProgressHUD> hud_;
8251 _H<NSError> error_;
8252
8253 NSURLConnection *trivial_bz2_;
8254 NSURLConnection *trivial_gz_;
8255
8256 BOOL cydia_;
8257 }
8258
8259 - (id) initWithDatabase:(Database *)database;
8260 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8261
8262 @end
8263
8264 @implementation SourcesController
8265
8266 - (void) _releaseConnection:(NSURLConnection *)connection {
8267 if (connection != nil) {
8268 [connection cancel];
8269 //[connection setDelegate:nil];
8270 [connection release];
8271 }
8272 }
8273
8274 - (void) dealloc {
8275 [self _releaseConnection:trivial_gz_];
8276 [self _releaseConnection:trivial_bz2_];
8277
8278 [super dealloc];
8279 }
8280
8281 - (NSURL *) navigationURL {
8282 return [NSURL URLWithString:@"cydia://sources"];
8283 }
8284
8285 - (void) viewDidAppear:(BOOL)animated {
8286 [super viewDidAppear:animated];
8287 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8288 }
8289
8290 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8291 return 2;
8292 }
8293
8294 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8295 if (section == 1)
8296 return UCLocalize("INDIVIDUAL_SOURCES");
8297 return nil;
8298 }
8299
8300 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8301 switch (section) {
8302 case 0: return 1;
8303 case 1: return [sources_ count];
8304 default: return 0;
8305 }
8306 }
8307
8308 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8309 @synchronized (database_) {
8310 if ([database_ era] != era_)
8311 return nil;
8312 if ([indexPath section] != 1)
8313 return nil;
8314 NSUInteger index([indexPath row]);
8315 if (index >= [sources_ count])
8316 return nil;
8317 return [sources_ objectAtIndex:index];
8318 } }
8319
8320 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8321 static NSString *cellIdentifier = @"SourceCell";
8322
8323 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8324 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8325 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8326
8327 Source *source([self sourceAtIndexPath:indexPath]);
8328 if (source == nil)
8329 [cell setAllSource];
8330 else
8331 [cell setSource:source];
8332
8333 return cell;
8334 }
8335
8336 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8337 SectionsController *controller([[[SectionsController alloc]
8338 initWithDatabase:database_
8339 source:[self sourceAtIndexPath:indexPath]
8340 ] autorelease]);
8341
8342 [controller setDelegate:delegate_];
8343 [[self navigationController] pushViewController:controller animated:YES];
8344 }
8345
8346 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8347 if ([indexPath section] != 1)
8348 return false;
8349 Source *source = [self sourceAtIndexPath:indexPath];
8350 return [source record] != nil;
8351 }
8352
8353 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8354 _assert([indexPath section] == 1);
8355 if (editingStyle == UITableViewCellEditingStyleDelete) {
8356 Source *source = [self sourceAtIndexPath:indexPath];
8357 if (source == nil) return;
8358
8359 [Sources_ removeObjectForKey:[source key]];
8360 Changed_ = true;
8361
8362 [delegate_ _saveConfig];
8363 [delegate_ reloadDataWithInvocation:nil];
8364 }
8365 }
8366
8367 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8368 [self updateButtonsForEditingStatusAnimated:YES];
8369 }
8370
8371 - (void) complete {
8372 [delegate_ addTrivialSource:href_];
8373 href_ = nil;
8374
8375 [delegate_ syncData];
8376 }
8377
8378 - (NSString *) getWarning {
8379 NSString *href(href_);
8380 NSRange colon([href rangeOfString:@"://"]);
8381 if (colon.location != NSNotFound)
8382 href = [href substringFromIndex:(colon.location + 3)];
8383 href = [href stringByAddingPercentEscapes];
8384 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8385
8386 NSURL *url([NSURL URLWithString:href]);
8387
8388 NSStringEncoding encoding;
8389 NSError *error(nil);
8390
8391 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8392 return [warning length] == 0 ? nil : warning;
8393 return nil;
8394 }
8395
8396 - (void) _endConnection:(NSURLConnection *)connection {
8397 // XXX: the memory management in this method is horribly awkward
8398
8399 NSURLConnection **field = NULL;
8400 if (connection == trivial_bz2_)
8401 field = &trivial_bz2_;
8402 else if (connection == trivial_gz_)
8403 field = &trivial_gz_;
8404 _assert(field != NULL);
8405 [connection release];
8406 *field = nil;
8407
8408 if (
8409 trivial_bz2_ == nil &&
8410 trivial_gz_ == nil
8411 ) {
8412 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8413
8414 [delegate_ releaseNetworkActivityIndicator];
8415
8416 [delegate_ removeProgressHUD:hud_];
8417 hud_ = nil;
8418
8419 if (cydia_) {
8420 if (warning != nil) {
8421 UIAlertView *alert = [[[UIAlertView alloc]
8422 initWithTitle:UCLocalize("SOURCE_WARNING")
8423 message:warning
8424 delegate:self
8425 cancelButtonTitle:UCLocalize("CANCEL")
8426 otherButtonTitles:
8427 UCLocalize("ADD_ANYWAY"),
8428 nil
8429 ] autorelease];
8430
8431 [alert setContext:@"warning"];
8432 [alert setNumberOfRows:1];
8433 [alert show];
8434
8435 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8436 error_ = nil;
8437 return;
8438 }
8439
8440 [self complete];
8441 } else if (error_ != nil) {
8442 UIAlertView *alert = [[[UIAlertView alloc]
8443 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8444 message:[error_ localizedDescription]
8445 delegate:self
8446 cancelButtonTitle:UCLocalize("OK")
8447 otherButtonTitles:nil
8448 ] autorelease];
8449
8450 [alert setContext:@"urlerror"];
8451 [alert show];
8452
8453 href_ = nil;
8454 } else {
8455 UIAlertView *alert = [[[UIAlertView alloc]
8456 initWithTitle:UCLocalize("NOT_REPOSITORY")
8457 message:UCLocalize("NOT_REPOSITORY_EX")
8458 delegate:self
8459 cancelButtonTitle:UCLocalize("OK")
8460 otherButtonTitles:nil
8461 ] autorelease];
8462
8463 [alert setContext:@"trivial"];
8464 [alert show];
8465
8466 href_ = nil;
8467 }
8468
8469 error_ = nil;
8470 }
8471 }
8472
8473 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8474 switch ([response statusCode]) {
8475 case 200:
8476 cydia_ = YES;
8477 }
8478 }
8479
8480 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8481 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8482 error_ = error;
8483 [self _endConnection:connection];
8484 }
8485
8486 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8487 [self _endConnection:connection];
8488 }
8489
8490 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8491 NSURL *url([NSURL URLWithString:href]);
8492
8493 NSMutableURLRequest *request = [NSMutableURLRequest
8494 requestWithURL:url
8495 cachePolicy:NSURLRequestUseProtocolCachePolicy
8496 timeoutInterval:10
8497 ];
8498
8499 [request setHTTPMethod:method];
8500
8501 if (Machine_ != NULL)
8502 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8503
8504 if (UniqueID_ != nil)
8505 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8506
8507 if ([url isCydiaSecure]) {
8508 if (UniqueID_ != nil)
8509 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8510 }
8511
8512 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8513 }
8514
8515 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8516 NSString *context([alert context]);
8517
8518 if ([context isEqualToString:@"source"]) {
8519 switch (button) {
8520 case 1: {
8521 NSString *href = [[alert textField] text];
8522
8523 static Pcre href_r("^http(s?)://[^# ]*$");
8524 if (!href_r(href)) {
8525 UIAlertView *alert = [[[UIAlertView alloc]
8526 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8527 message:UCLocalize("INVALID_URL_EX")
8528 delegate:self
8529 cancelButtonTitle:UCLocalize("OK")
8530 otherButtonTitles:nil
8531 ] autorelease];
8532
8533 [alert setContext:@"badurl"];
8534 [alert show];
8535
8536 break;
8537 }
8538
8539 if (![href hasSuffix:@"/"])
8540 href_ = [href stringByAppendingString:@"/"];
8541 else
8542 href_ = href;
8543
8544 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8545 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8546
8547 cydia_ = false;
8548
8549 // XXX: this is stupid
8550 hud_ = [delegate_ addProgressHUD];
8551 [hud_ setText:UCLocalize("VERIFYING_URL")];
8552 [delegate_ retainNetworkActivityIndicator];
8553 } break;
8554
8555 case 0:
8556 break;
8557
8558 _nodefault
8559 }
8560
8561 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8562 } else if ([context isEqualToString:@"trivial"])
8563 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8564 else if ([context isEqualToString:@"urlerror"])
8565 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8566 else if ([context isEqualToString:@"warning"]) {
8567 switch (button) {
8568 case 1:
8569 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8570 break;
8571
8572 case 0:
8573 break;
8574
8575 _nodefault
8576 }
8577
8578 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8579 }
8580 }
8581
8582 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8583 BOOL editing([list_ isEditing]);
8584
8585 if (editing)
8586 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8587 initWithTitle:UCLocalize("ADD")
8588 style:UIBarButtonItemStylePlain
8589 target:self
8590 action:@selector(addButtonClicked)
8591 ] autorelease] animated:animated];
8592 else if ([delegate_ updating])
8593 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8594 initWithTitle:UCLocalize("CANCEL")
8595 style:UIBarButtonItemStyleDone
8596 target:self
8597 action:@selector(cancelButtonClicked)
8598 ] autorelease] animated:animated];
8599 else
8600 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8601 initWithTitle:UCLocalize("REFRESH")
8602 style:UIBarButtonItemStylePlain
8603 target:self
8604 action:@selector(refreshButtonClicked)
8605 ] autorelease] animated:animated];
8606
8607 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8608 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8609 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8610 target:self
8611 action:@selector(editButtonClicked)
8612 ] autorelease] animated:animated];
8613 }
8614
8615 - (void) loadView {
8616 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8617 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8618 [list_ setRowHeight:53];
8619 [(UITableView *) list_ setDataSource:self];
8620 [list_ setDelegate:self];
8621 [self setView:list_];
8622 }
8623
8624 - (void) viewDidLoad {
8625 [super viewDidLoad];
8626
8627 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8628 [self updateButtonsForEditingStatusAnimated:NO];
8629 }
8630
8631 - (void) viewWillAppear:(BOOL)animated {
8632 [super viewWillAppear:animated];
8633
8634 [list_ setEditing:NO];
8635 [self updateButtonsForEditingStatusAnimated:NO];
8636 }
8637
8638 - (void) releaseSubviews {
8639 list_ = nil;
8640
8641 sources_ = nil;
8642
8643 [super releaseSubviews];
8644 }
8645
8646 - (id) initWithDatabase:(Database *)database {
8647 if ((self = [super init]) != nil) {
8648 database_ = database;
8649 } return self;
8650 }
8651
8652 - (void) reloadData {
8653 [super reloadData];
8654 [self updateButtonsForEditingStatusAnimated:YES];
8655
8656 @synchronized (database_) {
8657 era_ = [database_ era];
8658
8659 sources_ = [NSMutableArray arrayWithCapacity:16];
8660 [sources_ addObjectsFromArray:[database_ sources]];
8661 _trace();
8662 [sources_ sortUsingSelector:@selector(compareByName:)];
8663 _trace();
8664
8665 int count([sources_ count]);
8666 offset_ = 0;
8667 for (int i = 0; i != count; i++) {
8668 if ([[sources_ objectAtIndex:i] record] == nil)
8669 break;
8670 offset_++;
8671 }
8672
8673 [list_ reloadData];
8674 } }
8675
8676 - (void) showAddSourcePrompt {
8677 UIAlertView *alert = [[[UIAlertView alloc]
8678 initWithTitle:UCLocalize("ENTER_APT_URL")
8679 message:nil
8680 delegate:self
8681 cancelButtonTitle:UCLocalize("CANCEL")
8682 otherButtonTitles:
8683 UCLocalize("ADD_SOURCE"),
8684 nil
8685 ] autorelease];
8686
8687 [alert setContext:@"source"];
8688
8689 [alert setNumberOfRows:1];
8690 [alert addTextFieldWithValue:@"http://" label:@""];
8691
8692 UITextInputTraits *traits = [[alert textField] textInputTraits];
8693 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8694 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8695 [traits setKeyboardType:UIKeyboardTypeURL];
8696 // XXX: UIReturnKeyDone
8697 [traits setReturnKeyType:UIReturnKeyNext];
8698
8699 [alert show];
8700 }
8701
8702 - (void) addButtonClicked {
8703 [self showAddSourcePrompt];
8704 }
8705
8706 - (void) refreshButtonClicked {
8707 if ([delegate_ requestUpdate])
8708 [self updateButtonsForEditingStatusAnimated:YES];
8709 }
8710
8711 - (void) cancelButtonClicked {
8712 [delegate_ cancelUpdate];
8713 }
8714
8715 - (void) editButtonClicked {
8716 [list_ setEditing:![list_ isEditing] animated:YES];
8717 [self updateButtonsForEditingStatusAnimated:YES];
8718 }
8719
8720 @end
8721 /* }}} */
8722
8723 /* Stash Controller {{{ */
8724 @interface StashController : CyteViewController {
8725 _H<UIActivityIndicatorView> spinner_;
8726 _H<UILabel> status_;
8727 _H<UILabel> caption_;
8728 }
8729
8730 @end
8731
8732 @implementation StashController
8733
8734 - (void) loadView {
8735 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8736 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8737 [self setView:view];
8738
8739 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8740
8741 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8742 CGRect spinrect = [spinner_ frame];
8743 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8744 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8745 [spinner_ setFrame:spinrect];
8746 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8747 [view addSubview:spinner_];
8748 [spinner_ startAnimating];
8749
8750 CGRect captrect;
8751 captrect.size.width = [[self view] frame].size.width;
8752 captrect.size.height = 40.0f;
8753 captrect.origin.x = 0;
8754 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8755 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8756 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8757 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8758 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8759 [caption_ setTextColor:[UIColor whiteColor]];
8760 [caption_ setBackgroundColor:[UIColor clearColor]];
8761 [caption_ setShadowColor:[UIColor blackColor]];
8762 [caption_ setTextAlignment:NSTextAlignmentCenter];
8763 [view addSubview:caption_];
8764
8765 CGRect statusrect;
8766 statusrect.size.width = [[self view] frame].size.width;
8767 statusrect.size.height = 30.0f;
8768 statusrect.origin.x = 0;
8769 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8770 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8771 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8772 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8773 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8774 [status_ setTextColor:[UIColor whiteColor]];
8775 [status_ setBackgroundColor:[UIColor clearColor]];
8776 [status_ setShadowColor:[UIColor blackColor]];
8777 [status_ setTextAlignment:NSTextAlignmentCenter];
8778 [view addSubview:status_];
8779 }
8780
8781 - (void) releaseSubviews {
8782 spinner_ = nil;
8783 status_ = nil;
8784 caption_ = nil;
8785
8786 [super releaseSubviews];
8787 }
8788
8789 @end
8790 /* }}} */
8791
8792 @interface CYURLCache : SDURLCache {
8793 }
8794
8795 @end
8796
8797 @implementation CYURLCache
8798
8799 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8800 #if !ForRelease
8801 if (false);
8802 else if ([event isEqualToString:@"no-cache"])
8803 event = @"!!!";
8804 else if ([event isEqualToString:@"store"])
8805 event = @">>>";
8806 else if ([event isEqualToString:@"invalid"])
8807 event = @"???";
8808 else if ([event isEqualToString:@"memory"])
8809 event = @"mem";
8810 else if ([event isEqualToString:@"disk"])
8811 event = @"ssd";
8812 else if ([event isEqualToString:@"miss"])
8813 event = @"---";
8814
8815 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8816 #endif
8817 }
8818
8819 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8820 if (NSURLResponse *response = [cached response])
8821 if (NSString *mime = [response MIMEType])
8822 if ([mime isEqualToString:@"text/cache-manifest"]) {
8823 NSURL *url([response URL]);
8824
8825 #if !ForRelease
8826 NSLog(@"###: %@", [url absoluteString]);
8827 #endif
8828
8829 @synchronized (HostConfig_) {
8830 [CachedURLs_ addObject:url];
8831 }
8832 }
8833
8834 [super storeCachedResponse:cached forRequest:request];
8835 }
8836
8837 @end
8838
8839 @interface Cydia : UIApplication <
8840 ConfirmationControllerDelegate,
8841 DatabaseDelegate,
8842 CydiaDelegate
8843 > {
8844 _H<UIWindow> window_;
8845 _H<CydiaTabBarController> tabbar_;
8846 _H<CyteTabBarController> emulated_;
8847
8848 _H<NSMutableArray> essential_;
8849 _H<NSMutableArray> broken_;
8850
8851 Database *database_;
8852
8853 _H<NSURL> starturl_;
8854
8855 unsigned locked_;
8856 unsigned activity_;
8857
8858 _H<StashController> stash_;
8859
8860 bool loaded_;
8861 }
8862
8863 - (void) loadData;
8864
8865 @end
8866
8867 @implementation Cydia
8868
8869 - (void) lockSuspend {
8870 if (locked_++ == 0) {
8871 if ($SBSSetInterceptsMenuButtonForever != NULL)
8872 (*$SBSSetInterceptsMenuButtonForever)(true);
8873
8874 [self setIdleTimerDisabled:YES];
8875 }
8876 }
8877
8878 - (void) unlockSuspend {
8879 if (--locked_ == 0) {
8880 [self setIdleTimerDisabled:NO];
8881
8882 if ($SBSSetInterceptsMenuButtonForever != NULL)
8883 (*$SBSSetInterceptsMenuButtonForever)(false);
8884 }
8885 }
8886
8887 - (void) beginUpdate {
8888 [tabbar_ beginUpdate];
8889 }
8890
8891 - (void) cancelUpdate {
8892 [tabbar_ cancelUpdate];
8893 }
8894
8895 - (bool) requestUpdate {
8896 if (IsReachable("cydia.saurik.com")) {
8897 [self beginUpdate];
8898 return true;
8899 } else {
8900 UIAlertView *alert = [[[UIAlertView alloc]
8901 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8902 message:@"Host Unreachable" // XXX: Localize
8903 delegate:self
8904 cancelButtonTitle:UCLocalize("OK")
8905 otherButtonTitles:nil
8906 ] autorelease];
8907
8908 [alert setContext:@"norefresh"];
8909 [alert show];
8910
8911 return false;
8912 }
8913 }
8914
8915 - (BOOL) updating {
8916 return [tabbar_ updating];
8917 }
8918
8919 - (void) _loaded {
8920 if ([broken_ count] != 0) {
8921 int count = [broken_ count];
8922
8923 UIAlertView *alert = [[[UIAlertView alloc]
8924 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8925 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8926 delegate:self
8927 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8928 otherButtonTitles:
8929 UCLocalize("TEMPORARY_IGNORE"),
8930 nil
8931 ] autorelease];
8932
8933 [alert setContext:@"fixhalf"];
8934 [alert setNumberOfRows:2];
8935 [alert show];
8936 } else if (!Ignored_ && [essential_ count] != 0) {
8937 int count = [essential_ count];
8938
8939 UIAlertView *alert = [[[UIAlertView alloc]
8940 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8941 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8942 delegate:self
8943 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8944 otherButtonTitles:
8945 UCLocalize("UPGRADE_ESSENTIAL"),
8946 UCLocalize("COMPLETE_UPGRADE"),
8947 nil
8948 ] autorelease];
8949
8950 [alert setContext:@"upgrade"];
8951 [alert show];
8952 }
8953 }
8954
8955 - (void) returnToCydia {
8956 [self _loaded];
8957 }
8958
8959 - (void) _saveConfig {
8960 @synchronized (database_) {
8961 _trace();
8962 MetaFile_.Sync();
8963 _trace();
8964 }
8965
8966 if (Changed_) {
8967 NSString *error(nil);
8968
8969 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8970 _trace();
8971 NSError *error(nil);
8972 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8973 NSLog(@"failure to save metadata data: %@", error);
8974 _trace();
8975
8976 Changed_ = false;
8977 } else {
8978 NSLog(@"failure to serialize metadata: %@", error);
8979 }
8980 }
8981
8982 CydiaWriteSources();
8983 }
8984
8985 // Navigation controller for the queuing badge.
8986 - (UINavigationController *) queueNavigationController {
8987 NSArray *controllers = [tabbar_ viewControllers];
8988 return [controllers objectAtIndex:3];
8989 }
8990
8991 - (void) unloadData {
8992 [tabbar_ unloadData];
8993 }
8994
8995 - (void) _updateData {
8996 [self _saveConfig];
8997 [self unloadData];
8998
8999 UINavigationController *navigation = [self queueNavigationController];
9000
9001 id queuedelegate = nil;
9002 if ([[navigation viewControllers] count] > 0)
9003 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9004
9005 [queuedelegate queueStatusDidChange];
9006 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9007 }
9008
9009 - (void) _refreshIfPossible:(NSDate *)update {
9010 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9011
9012 bool recently = false;
9013 if (update != nil) {
9014 NSTimeInterval interval([update timeIntervalSinceNow]);
9015 if (interval <= 0 && interval > -(15*60))
9016 recently = true;
9017 }
9018
9019 // Don't automatic refresh if:
9020 // - We already refreshed recently.
9021 // - We already auto-refreshed this launch.
9022 // - Auto-refresh is disabled.
9023 // - Cydia's server is not reachable
9024 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9025 // If we are cancelling, we need to make sure it knows it's already loaded.
9026 loaded_ = true;
9027
9028 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9029 } else {
9030 // We are going to load, so remember that.
9031 loaded_ = true;
9032
9033 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9034 }
9035
9036 [pool release];
9037 }
9038
9039 - (void) refreshIfPossible {
9040 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9041 }
9042
9043 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9044 _profile(reloadDataWithInvocation)
9045 @synchronized (self) {
9046 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9047 if (hud != nil)
9048 [hud setText:UCLocalize("RELOADING_DATA")];
9049
9050 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9051
9052 size_t changes(0);
9053
9054 [essential_ removeAllObjects];
9055 [broken_ removeAllObjects];
9056
9057 _profile(reloadDataWithInvocation$Essential)
9058 NSArray *packages([database_ packages]);
9059 for (Package *package in packages) {
9060 if ([package half])
9061 [broken_ addObject:package];
9062 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9063 if ([package essential] && [package installed] != nil)
9064 [essential_ addObject:package];
9065 ++changes;
9066 }
9067 }
9068 _end
9069
9070 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9071 if (changes != 0) {
9072 _trace();
9073 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9074 [changesItem setBadgeValue:badge];
9075 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9076 [self setApplicationIconBadgeNumber:changes];
9077 } else {
9078 _trace();
9079 [changesItem setBadgeValue:nil];
9080 [changesItem setAnimatedBadge:NO];
9081 [self setApplicationIconBadgeNumber:0];
9082 }
9083
9084 [self _updateData];
9085
9086 if (hud != nil)
9087 [self removeProgressHUD:hud];
9088 }
9089 _end
9090
9091 PrintTimes();
9092 }
9093
9094 - (void) updateData {
9095 [self _updateData];
9096 }
9097
9098 - (void) updateDataAndLoad {
9099 [self _updateData];
9100 if ([database_ progressDelegate] == nil)
9101 [self _loaded];
9102 }
9103
9104 - (void) update_ {
9105 [database_ update];
9106 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9107 }
9108
9109 - (void) disemulate {
9110 if (emulated_ == nil)
9111 return;
9112
9113 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9114 [window_ setRootViewController:tabbar_];
9115 else {
9116 [window_ addSubview:[tabbar_ view]];
9117 [[emulated_ view] removeFromSuperview];
9118 }
9119
9120 emulated_ = nil;
9121 [window_ setUserInteractionEnabled:YES];
9122 }
9123
9124 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9125 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9126 if (IsWildcat_)
9127 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9128
9129 UIViewController *parent;
9130 if (emulated_ == nil)
9131 parent = tabbar_;
9132 else if (!force)
9133 parent = emulated_;
9134 else {
9135 [self disemulate];
9136 parent = tabbar_;
9137 }
9138
9139 [parent presentModalViewController:navigation animated:YES];
9140 }
9141
9142 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9143 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9144
9145 if (navigation != nil)
9146 [navigation pushViewController:progress animated:YES];
9147 else
9148 [self presentModalViewController:progress force:YES];
9149
9150 [progress invoke:invocation withTitle:title];
9151 return progress;
9152 }
9153
9154 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9155 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9156 }
9157
9158 - (void) repairWithInvocation:(NSInvocation *)invocation {
9159 _trace();
9160 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9161 _trace();
9162 }
9163
9164 - (void) repairWithSelector:(SEL)selector {
9165 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9166 }
9167
9168 - (void) reloadData {
9169 [self reloadDataWithInvocation:nil];
9170 if ([database_ progressDelegate] == nil)
9171 [self _loaded];
9172 }
9173
9174 - (void) syncData {
9175 [self _saveConfig];
9176 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9177 }
9178
9179 - (void) addSource:(NSDictionary *) source {
9180 CydiaAddSource(source);
9181 }
9182
9183 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9184 CydiaAddSource(href, distribution, sections);
9185 }
9186
9187 - (void) addTrivialSource:(NSString *)href {
9188 CydiaAddSource(href, @"./");
9189 }
9190
9191 - (void) updateValues {
9192 Changed_ = true;
9193 }
9194
9195 - (void) resolve {
9196 pkgProblemResolver *resolver = [database_ resolver];
9197
9198 resolver->InstallProtect();
9199 if (!resolver->Resolve(true))
9200 _error->Discard();
9201 }
9202
9203 - (bool) perform {
9204 // XXX: this is a really crappy way of doing this.
9205 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9206 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9207 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9208 if ([tabbar_ updating])
9209 [tabbar_ cancelUpdate];
9210
9211 if (![database_ prepare])
9212 return false;
9213
9214 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9215 [page setDelegate:self];
9216 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9217
9218 if (IsWildcat_)
9219 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9220 [tabbar_ presentModalViewController:confirm_ animated:YES];
9221
9222 return true;
9223 }
9224
9225 - (void) queue {
9226 @synchronized (self) {
9227 [self perform];
9228 }
9229 }
9230
9231 - (void) clearPackage:(Package *)package {
9232 @synchronized (self) {
9233 [package clear];
9234 [self resolve];
9235 [self perform];
9236 }
9237 }
9238
9239 - (void) installPackages:(NSArray *)packages {
9240 @synchronized (self) {
9241 for (Package *package in packages)
9242 [package install];
9243 [self resolve];
9244 [self perform];
9245 }
9246 }
9247
9248 - (void) installPackage:(Package *)package {
9249 @synchronized (self) {
9250 [package install];
9251 [self resolve];
9252 [self perform];
9253 }
9254 }
9255
9256 - (void) removePackage:(Package *)package {
9257 @synchronized (self) {
9258 [package remove];
9259 [self resolve];
9260 [self perform];
9261 }
9262 }
9263
9264 - (void) distUpgrade {
9265 @synchronized (self) {
9266 if (![database_ upgrade])
9267 return;
9268 [self perform];
9269 }
9270 }
9271
9272 - (void) _uicache {
9273 _trace();
9274 system("su -c /usr/bin/uicache mobile");
9275 _trace();
9276 }
9277
9278 - (void) uicache {
9279 UIProgressHUD *hud([self addProgressHUD]);
9280 [hud setText:UCLocalize("LOADING")];
9281 [self yieldToSelector:@selector(_uicache)];
9282 [self removeProgressHUD:hud];
9283 }
9284
9285 - (void) perform_ {
9286 [database_ perform];
9287 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9288 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9289 }
9290
9291 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9292 Queuing_ = false;
9293 [self lockSuspend];
9294 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9295 [self unlockSuspend];
9296 }
9297
9298 - (void) retainNetworkActivityIndicator {
9299 if (activity_++ == 0)
9300 [self setNetworkActivityIndicatorVisible:YES];
9301
9302 #if TraceLogging
9303 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9304 #endif
9305 }
9306
9307 - (void) releaseNetworkActivityIndicator {
9308 if (--activity_ == 0)
9309 [self setNetworkActivityIndicatorVisible:NO];
9310
9311 #if TraceLogging
9312 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9313 #endif
9314
9315 }
9316
9317 - (void) cancelAndClear:(bool)clear {
9318 @synchronized (self) {
9319 if (clear) {
9320 [database_ clear];
9321 Queuing_ = false;
9322 } else {
9323 Queuing_ = true;
9324 }
9325
9326 [self _updateData];
9327 }
9328 }
9329
9330 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9331 NSString *context([alert context]);
9332
9333 if ([context isEqualToString:@"conffile"]) {
9334 FILE *input = [database_ input];
9335 if (button == [alert cancelButtonIndex])
9336 fprintf(input, "N\n");
9337 else if (button == [alert firstOtherButtonIndex])
9338 fprintf(input, "Y\n");
9339 fflush(input);
9340
9341 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9342 } else if ([context isEqualToString:@"fixhalf"]) {
9343 if (button == [alert cancelButtonIndex]) {
9344 @synchronized (self) {
9345 for (Package *broken in (id) broken_) {
9346 [broken remove];
9347
9348 NSString *id = [broken id];
9349 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9350 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9351 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9352 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9353 }
9354
9355 [self resolve];
9356 [self perform];
9357 }
9358 } else if (button == [alert firstOtherButtonIndex]) {
9359 [broken_ removeAllObjects];
9360 [self _loaded];
9361 }
9362
9363 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9364 } else if ([context isEqualToString:@"upgrade"]) {
9365 if (button == [alert firstOtherButtonIndex]) {
9366 @synchronized (self) {
9367 for (Package *essential in (id) essential_)
9368 [essential install];
9369
9370 [self resolve];
9371 [self perform];
9372 }
9373 } else if (button == [alert firstOtherButtonIndex] + 1) {
9374 [self distUpgrade];
9375 } else if (button == [alert cancelButtonIndex]) {
9376 Ignored_ = YES;
9377 }
9378
9379 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9380 }
9381 }
9382
9383 - (void) system:(NSString *)command {
9384 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9385
9386 _trace();
9387 system([command UTF8String]);
9388 _trace();
9389
9390 [pool release];
9391 }
9392
9393 - (void) applicationWillSuspend {
9394 [database_ clean];
9395 [super applicationWillSuspend];
9396 }
9397
9398 - (BOOL) isSafeToSuspend {
9399 if (locked_ != 0) {
9400 #if !ForRelease
9401 NSLog(@"isSafeToSuspend: locked_ != 0");
9402 #endif
9403 return false;
9404 }
9405
9406 if ([tabbar_ modalViewController] != nil)
9407 return false;
9408
9409 // Use external process status API internally.
9410 // This is probably a really bad idea.
9411 // XXX: what is the point of this? does this solve anything at all?
9412 uint64_t status = 0;
9413 int notify_token;
9414 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9415 notify_get_state(notify_token, &status);
9416 notify_cancel(notify_token);
9417 }
9418
9419 if (status != 0) {
9420 #if !ForRelease
9421 NSLog(@"isSafeToSuspend: status != 0");
9422 #endif
9423 return false;
9424 }
9425
9426 #if !ForRelease
9427 NSLog(@"isSafeToSuspend: -> true");
9428 #endif
9429 return true;
9430 }
9431
9432 - (void) applicationSuspend:(__GSEvent *)event {
9433 if ([self isSafeToSuspend])
9434 [super applicationSuspend:event];
9435 }
9436
9437 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9438 if ([self isSafeToSuspend])
9439 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9440 }
9441
9442 - (void) _setSuspended:(BOOL)value {
9443 if ([self isSafeToSuspend])
9444 [super _setSuspended:value];
9445 }
9446
9447 - (UIProgressHUD *) addProgressHUD {
9448 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9449 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9450
9451 [window_ setUserInteractionEnabled:NO];
9452
9453 UIViewController *target(tabbar_);
9454 if (UIViewController *modal = [target modalViewController])
9455 target = modal;
9456
9457 [hud showInView:[target view]];
9458
9459 [self lockSuspend];
9460 return hud;
9461 }
9462
9463 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9464 [self unlockSuspend];
9465 [hud hide];
9466 [hud removeFromSuperview];
9467 [window_ setUserInteractionEnabled:YES];
9468 }
9469
9470 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9471 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9472 }
9473
9474 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9475 NSString *scheme([[url scheme] lowercaseString]);
9476 if ([[url absoluteString] length] <= [scheme length] + 3)
9477 return nil;
9478 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9479 NSArray *components([path componentsSeparatedByString:@"/"]);
9480
9481 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9482 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9483 if (controller != nil)
9484 [controller setDelegate:self];
9485 return controller;
9486 }
9487
9488 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9489 return nil;
9490
9491 NSString *base([components objectAtIndex:0]);
9492
9493 CyteViewController *controller = nil;
9494
9495 if ([base isEqualToString:@"url"]) {
9496 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9497 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9498 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9499 } else if (!external && [components count] == 1) {
9500 if ([base isEqualToString:@"sources"]) {
9501 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9502 }
9503
9504 if ([base isEqualToString:@"home"]) {
9505 controller = [[[HomeController alloc] init] autorelease];
9506 }
9507
9508 if ([base isEqualToString:@"sections"]) {
9509 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9510 }
9511
9512 if ([base isEqualToString:@"search"]) {
9513 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9514 }
9515
9516 if ([base isEqualToString:@"changes"]) {
9517 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9518 }
9519
9520 if ([base isEqualToString:@"installed"]) {
9521 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9522 }
9523 } else if ([components count] == 2) {
9524 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9525
9526 if ([base isEqualToString:@"package"]) {
9527 controller = [self pageForPackage:argument withReferrer:referrer];
9528 }
9529
9530 if (!external && [base isEqualToString:@"search"]) {
9531 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9532 }
9533
9534 if (!external && [base isEqualToString:@"sections"]) {
9535 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9536 argument = nil;
9537 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9538 }
9539
9540 if (!external && [base isEqualToString:@"sources"]) {
9541 if ([argument isEqualToString:@"add"]) {
9542 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9543 [(SourcesController *)controller showAddSourcePrompt];
9544 } else {
9545 Source *source([database_ sourceWithKey:argument]);
9546 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9547 }
9548 }
9549
9550 if (!external && [base isEqualToString:@"launch"]) {
9551 [self launchApplicationWithIdentifier:argument suspended:NO];
9552 return nil;
9553 }
9554 } else if (!external && [components count] == 3) {
9555 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9556 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9557
9558 if ([base isEqualToString:@"package"]) {
9559 if ([arg2 isEqualToString:@"settings"]) {
9560 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9561 } else if ([arg2 isEqualToString:@"files"]) {
9562 if (Package *package = [database_ packageWithName:arg1]) {
9563 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9564 [(FileTable *)controller setPackage:package];
9565 }
9566 }
9567 }
9568
9569 if ([base isEqualToString:@"sections"]) {
9570 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9571 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9572 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9573 }
9574 }
9575
9576 [controller setDelegate:self];
9577 return controller;
9578 }
9579
9580 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9581 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9582
9583 if (page != nil)
9584 [tabbar_ setUnselectedViewController:page];
9585
9586 return page != nil;
9587 }
9588
9589 - (void) applicationOpenURL:(NSURL *)url {
9590 [super applicationOpenURL:url];
9591
9592 if (!loaded_)
9593 starturl_ = url;
9594 else
9595 [self openCydiaURL:url forExternal:YES];
9596 }
9597
9598 - (void) applicationWillResignActive:(UIApplication *)application {
9599 // Stop refreshing if you get a phone call or lock the device.
9600 if ([tabbar_ updating])
9601 [tabbar_ cancelUpdate];
9602
9603 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9604 [super applicationWillResignActive:application];
9605 }
9606
9607 - (void) saveState {
9608 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9609 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9610 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9611 Changed_ = true;
9612
9613 [self _saveConfig];
9614 }
9615
9616 - (void) applicationWillTerminate:(UIApplication *)application {
9617 [self saveState];
9618 }
9619
9620 - (void) setConfigurationData:(NSString *)data {
9621 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9622
9623 if (!conffile_r(data)) {
9624 lprintf("E:invalid conffile\n");
9625 return;
9626 }
9627
9628 NSString *ofile = conffile_r[1];
9629 //NSString *nfile = conffile_r[2];
9630
9631 UIAlertView *alert = [[[UIAlertView alloc]
9632 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9633 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9634 delegate:self
9635 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9636 otherButtonTitles:
9637 UCLocalize("ACCEPT_NEW_COPY"),
9638 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9639 nil
9640 ] autorelease];
9641
9642 [alert setContext:@"conffile"];
9643 [alert setNumberOfRows:2];
9644 [alert show];
9645 }
9646
9647 - (void) addStashController {
9648 [self lockSuspend];
9649 stash_ = [[[StashController alloc] init] autorelease];
9650 [window_ addSubview:[stash_ view]];
9651 }
9652
9653 - (void) removeStashController {
9654 [[stash_ view] removeFromSuperview];
9655 stash_ = nil;
9656 [self unlockSuspend];
9657 }
9658
9659 - (void) stash {
9660 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9661 UpdateExternalStatus(1);
9662 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9663 UpdateExternalStatus(0);
9664
9665 [self removeStashController];
9666
9667 pid_t pid(ExecFork());
9668 if (pid == 0) {
9669 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9670 perror("launchctl stop");
9671
9672 exit(0);
9673 } ReapZombie(pid);
9674 }
9675
9676 - (void) setupViewControllers {
9677 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9678
9679 NSMutableArray *items;
9680 if (kCFCoreFoundationVersionNumber < 800) {
9681 items = [NSMutableArray arrayWithObjects:
9682 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9683 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9684 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9685 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9686 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9687 nil];
9688 } else {
9689 items = [NSMutableArray arrayWithObjects:
9690 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9691 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9692 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9693 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9694 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9695 nil];
9696 }
9697
9698 NSMutableArray *controllers([NSMutableArray array]);
9699 for (UITabBarItem *item in items) {
9700 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9701 [controller setTabBarItem:item];
9702 [controllers addObject:controller];
9703 }
9704 [tabbar_ setViewControllers:controllers];
9705
9706 [tabbar_ setUpdateDelegate:self];
9707 }
9708
9709 - (void) _sendMemoryWarningNotification {
9710 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9711 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9712 else
9713 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9714 }
9715
9716 - (void) _sendMemoryWarningNotifications {
9717 while (true) {
9718 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9719 sleep(2);
9720 //usleep(2000000);
9721 }
9722 }
9723
9724 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9725 NSLog(@"--");
9726 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9727 }
9728
9729 - (void) applicationDidFinishLaunching:(id)unused {
9730 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9731
9732 _trace();
9733 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9734 [self setApplicationSupportsShakeToEdit:NO];
9735
9736 @synchronized (HostConfig_) {
9737 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9738 }
9739
9740 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9741 initWithMemoryCapacity:524288
9742 diskCapacity:10485760
9743 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9744 ] autorelease]];
9745
9746 [CydiaWebViewController _initialize];
9747
9748 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9749
9750 // this would disallow http{,s} URLs from accessing this data
9751 //[WebView registerURLSchemeAsLocal:@"cydia"];
9752
9753 Font12_ = [UIFont systemFontOfSize:12];
9754 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9755 Font14_ = [UIFont systemFontOfSize:14];
9756 Font18_ = [UIFont systemFontOfSize:18];
9757 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9758 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9759
9760 essential_ = [NSMutableArray arrayWithCapacity:4];
9761 broken_ = [NSMutableArray arrayWithCapacity:4];
9762
9763 // XXX: I really need this thing... like, seriously... I'm sorry
9764 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9765
9766 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9767 [window_ orderFront:self];
9768 [window_ makeKey:self];
9769 [window_ setHidden:NO];
9770
9771 if (false) stash: {
9772 [self addStashController];
9773 // XXX: this would be much cleaner as a yieldToSelector:
9774 // that way the removeStashController could happen right here inline
9775 // we also could no longer require the useless stash_ field anymore
9776 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9777 return;
9778 }
9779
9780 struct stat root;
9781 int error(stat("/", &root));
9782 _assert(error != -1);
9783
9784 #define Stash_(path) do { \
9785 struct stat folder; \
9786 int error(lstat((path), &folder)); \
9787 if (error != -1 && ( \
9788 folder.st_dev == root.st_dev && \
9789 S_ISDIR(folder.st_mode) \
9790 ) || error == -1 && ( \
9791 errno == ENOENT || \
9792 errno == ENOTDIR \
9793 )) goto stash; \
9794 } while (false)
9795
9796 Stash_("/Applications");
9797 Stash_("/Library/Ringtones");
9798 Stash_("/Library/Wallpaper");
9799 //Stash_("/usr/bin");
9800 Stash_("/usr/include");
9801 Stash_("/usr/lib/pam");
9802 Stash_("/usr/share");
9803 //Stash_("/var/lib");
9804
9805 database_ = [Database sharedInstance];
9806 [database_ setDelegate:self];
9807
9808 [window_ setUserInteractionEnabled:NO];
9809 [self setupViewControllers];
9810
9811 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9812 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9813 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9814
9815 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9816 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9817 [emulated_ setSelectedIndex:0];
9818 [emulated_ concealTabBarSelection];
9819
9820 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9821 [window_ setRootViewController:emulated_];
9822 else
9823 [window_ addSubview:[emulated_ view]];
9824
9825 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9826 _trace();
9827 }
9828
9829 - (NSArray *) defaultStartPages {
9830 NSMutableArray *standard = [NSMutableArray array];
9831 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9832 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9833 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9834 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9835 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9836 return standard;
9837 }
9838
9839 - (void) loadData {
9840 _trace();
9841 if ([emulated_ modalViewController] != nil)
9842 [emulated_ dismissModalViewControllerAnimated:YES];
9843 [window_ setUserInteractionEnabled:NO];
9844
9845 [self reloadDataWithInvocation:nil];
9846 [self refreshIfPossible];
9847 [self disemulate];
9848
9849 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9850 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9851 int standardIndex = 0;
9852 NSArray *standard = [self defaultStartPages];
9853
9854 BOOL valid = YES;
9855
9856 if (saved == nil)
9857 valid = NO;
9858
9859 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9860 if (valid && closed != nil) {
9861 NSTimeInterval interval([closed timeIntervalSinceNow]);
9862 // XXX: Is 30 minutes the optimal time here?
9863 if (interval <= -(30*60))
9864 valid = NO;
9865 }
9866
9867 if (valid && [saved count] != [standard count])
9868 valid = NO;
9869
9870 if (valid) {
9871 for (unsigned int i = 0; i < [standard count]; i++) {
9872 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9873 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9874 // but it's good enough for now.
9875 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9876 valid = NO;
9877 break;
9878 }
9879 }
9880 }
9881
9882 NSArray *items = nil;
9883 if (valid) {
9884 [tabbar_ setSelectedIndex:savedIndex];
9885 items = saved;
9886 } else {
9887 [tabbar_ setSelectedIndex:standardIndex];
9888 items = standard;
9889 }
9890
9891 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9892 NSArray *stack = [items objectAtIndex:tab];
9893 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9894 NSMutableArray *current = [NSMutableArray array];
9895
9896 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9897 NSString *addr = [stack objectAtIndex:nav];
9898 NSURL *url = [NSURL URLWithString:addr];
9899 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9900 if (page != nil)
9901 [current addObject:page];
9902 }
9903
9904 [navigation setViewControllers:current];
9905 }
9906
9907 // (Try to) show the startup URL.
9908 if (starturl_ != nil) {
9909 [self openCydiaURL:starturl_ forExternal:YES];
9910 starturl_ = nil;
9911 }
9912 }
9913
9914 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9915 if (item != nil && IsWildcat_) {
9916 [sheet showFromBarButtonItem:item animated:YES];
9917 } else {
9918 [sheet showInView:window_];
9919 }
9920 }
9921
9922 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9923 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9924 [progress setTitle:task];
9925 [progress addProgressEvent:event];
9926 }
9927
9928 - (void) addProgressEventForTask:(NSArray *)data {
9929 CydiaProgressEvent *event([data objectAtIndex:0]);
9930 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9931 [self addProgressEvent:event forTask:task];
9932 }
9933
9934 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9935 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9936 }
9937
9938 @end
9939
9940 /*IMP alloc_;
9941 id Alloc_(id self, SEL selector) {
9942 id object = alloc_(self, selector);
9943 lprintf("[%s]A-%p\n", self->isa->name, object);
9944 return object;
9945 }*/
9946
9947 /*IMP dealloc_;
9948 id Dealloc_(id self, SEL selector) {
9949 id object = dealloc_(self, selector);
9950 lprintf("[%s]D-%p\n", self->isa->name, object);
9951 return object;
9952 }*/
9953
9954 static NSSet *MobilizedFiles_;
9955
9956 static NSURL *MobilizeURL(NSURL *url) {
9957 NSString *path([url path]);
9958 if ([path hasPrefix:@"/var/root/"]) {
9959 NSString *file([path substringFromIndex:10]);
9960 if ([MobilizedFiles_ containsObject:file])
9961 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9962 }
9963
9964 return url;
9965 }
9966
9967 Class $CFXPreferencesPropertyListSource;
9968 @class CFXPreferencesPropertyListSource;
9969
9970 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9971 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9972 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9973
9974 url = MobilizeURL(url);
9975 BOOL value; @try {
9976 value = _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd);
9977 //NSLog(@"CFX %@ %s", [url absoluteString], value ? "YES" : "NO");
9978 } @finally {
9979 url = old;
9980 }
9981
9982 [pool release];
9983 return value;
9984 }
9985
9986 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9987 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9988 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9989
9990 url = MobilizeURL(url);
9991 void *value; @try {
9992 value = _CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd);
9993 //NSLog(@"CFX %@ %@", [url absoluteString], value);
9994 } @finally {
9995 url = old;
9996 }
9997
9998 [pool release];
9999 return value;
10000 }
10001
10002 Class $NSURLConnection;
10003
10004 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10005 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10006
10007 NSURL *url([copy URL]);
10008
10009 NSString *host([url host]);
10010 NSString *scheme([[url scheme] lowercaseString]);
10011
10012 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10013
10014 @synchronized (HostConfig_) {
10015 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10016 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10017 [copy setHTTPShouldUsePipelining:YES];
10018
10019 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10020 if ([control isEqualToString:@"max-age=0"])
10021 if ([CachedURLs_ containsObject:url]) {
10022 #if !ForRelease
10023 NSLog(@"~~~: %@", url);
10024 #endif
10025
10026 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10027
10028 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10029 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10030 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10031 }
10032 }
10033
10034 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10035 } return self;
10036 }
10037
10038 Class $WAKWindow;
10039
10040 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10041 CGSize size([[UIScreen mainScreen] bounds].size);
10042 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10043 if ([$WAKWindow hasLandscapeOrientation])
10044 std::swap(size.width, size.height);*/
10045 return size;
10046 }
10047
10048 Class $NSUserDefaults;
10049
10050 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10051 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10052 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10053 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10054 }
10055
10056 int main(int argc, char *argv[]) {
10057 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10058
10059 _trace();
10060
10061 UpdateExternalStatus(0);
10062
10063 UIScreen *screen([UIScreen mainScreen]);
10064 if ([screen respondsToSelector:@selector(scale)])
10065 ScreenScale_ = [screen scale];
10066 else
10067 ScreenScale_ = 1;
10068
10069 UIDevice *device([UIDevice currentDevice]);
10070 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10071 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10072 if (idiom == UIUserInterfaceIdiomPad)
10073 IsWildcat_ = true;
10074 }
10075
10076 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10077
10078 Pcre pattern("^([0-9]+\\.[0-9]+)");
10079
10080 if (pattern([device systemVersion]))
10081 Firmware_ = pattern[1];
10082 if (pattern(Cydia_))
10083 Major_ = pattern[1];
10084
10085 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10086
10087 HostConfig_ = [[[NSObject alloc] init] autorelease];
10088 @synchronized (HostConfig_) {
10089 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10090 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10091 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10092 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10093 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10094 }
10095
10096 NSString *ui(@"ui/ios");
10097 if (Idiom_ != nil)
10098 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10099 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10100 UI_ = CydiaURL(ui);
10101
10102 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10103
10104 MobilizedFiles_ = [NSMutableSet setWithObjects:
10105 @"Library/Preferences/.GlobalPreferences.plist",
10106 @"Library/Preferences/com.apple.Accessibility.plist",
10107 @"Library/Preferences/com.apple.preferences.sounds.plist",
10108 nil];
10109
10110 /* Library Hacks {{{ */
10111 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10112
10113 $WAKWindow = objc_getClass("WAKWindow");
10114 if ($WAKWindow != NULL)
10115 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10116 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10117
10118 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSourceSynchronizer");
10119 if ($CFXPreferencesPropertyListSource == Nil)
10120 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10121
10122 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10123 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10124 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10125 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10126 }
10127
10128 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10129 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10130 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10131 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10132 }
10133
10134 $NSURLConnection = objc_getClass("NSURLConnection");
10135 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10136 if (NSURLConnection$init$ != NULL) {
10137 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10138 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10139 }
10140
10141 $NSUserDefaults = objc_getClass("NSUserDefaults");
10142 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10143 if (NSUserDefaults$objectForKey$ != NULL) {
10144 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10145 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10146 }
10147 /* }}} */
10148 /* Set Locale {{{ */
10149 Locale_ = CFLocaleCopyCurrent();
10150 Languages_ = [NSLocale preferredLanguages];
10151
10152 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10153 //NSLog(@"%@", [Languages_ description]);
10154
10155 const char *lang;
10156 if (Locale_ != NULL)
10157 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10158 else if (Languages_ != nil && [Languages_ count] != 0)
10159 lang = [[Languages_ objectAtIndex:0] UTF8String];
10160 else
10161 // XXX: consider just setting to C and then falling through?
10162 lang = NULL;
10163
10164 if (lang != NULL) {
10165 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10166 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10167 }
10168
10169 NSLog(@"Setting Language: %s", lang);
10170
10171 if (lang != NULL) {
10172 setenv("LANG", lang, true);
10173 std::setlocale(LC_ALL, lang);
10174 }
10175 /* }}} */
10176 /* Index Collation {{{ */
10177 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) {
10178 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10179 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10180 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10181 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10182 _H<UILocalizedIndexedCollation> collation([[[UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10183
10184 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10185
10186 CollationThumbs_ = [collation sectionIndexTitles];
10187 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10188 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10189
10190 CollationTitles_ = [collation sectionTitles];
10191 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10192
10193 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10194 if (&transform != NULL && transform != nil) {
10195 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10196 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10197 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10198 UErrorCode code(U_ZERO_ERROR);
10199 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10200 if (!U_SUCCESS(code))
10201 NSLog(@"%s", u_errorName(code));
10202 }
10203 } else {
10204 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10205
10206 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];
10207 for (NSInteger offset(0); offset != 28; ++offset)
10208 CollationOffset_.push_back(offset);
10209
10210 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];
10211 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];
10212 }
10213 /* }}} */
10214
10215 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10216
10217 /* Parse Arguments {{{ */
10218 bool substrate(false);
10219
10220 if (argc != 0) {
10221 char **args(argv);
10222 int arge(1);
10223
10224 for (int argi(1); argi != argc; ++argi)
10225 if (strcmp(argv[argi], "--") == 0) {
10226 arge = argi;
10227 argv[argi] = argv[0];
10228 argv += argi;
10229 argc -= argi;
10230 break;
10231 }
10232
10233 for (int argi(1); argi != arge; ++argi)
10234 if (strcmp(args[argi], "--substrate") == 0)
10235 substrate = true;
10236 else
10237 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10238 }
10239 /* }}} */
10240
10241 App_ = [[NSBundle mainBundle] bundlePath];
10242 Advanced_ = YES;
10243
10244 setuid(0);
10245 setgid(0);
10246
10247 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10248 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10249
10250 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10251
10252 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10253 alloc_ = alloc->method_imp;
10254 alloc->method_imp = (IMP) &Alloc_;*/
10255
10256 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10257 dealloc_ = dealloc->method_imp;
10258 dealloc->method_imp = (IMP) &Dealloc_;*/
10259
10260 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10261 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10262
10263 /* System Information {{{ */
10264 size_t size;
10265
10266 int maxproc;
10267 size = sizeof(maxproc);
10268 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10269 perror("sysctlbyname(\"kern.maxproc\", ?)");
10270 else if (maxproc < 64) {
10271 maxproc = 64;
10272 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10273 perror("sysctlbyname(\"kern.maxproc\", #)");
10274 }
10275
10276 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10277 char *osversion = new char[size];
10278 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10279 perror("sysctlbyname(\"kern.osversion\", ?)");
10280 else
10281 System_ = [NSString stringWithUTF8String:osversion];
10282
10283 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10284 char *machine = new char[size];
10285 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10286 perror("sysctlbyname(\"hw.machine\", ?)");
10287 else
10288 Machine_ = machine;
10289
10290 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10291 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10292 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10293
10294 UniqueID_ = UniqueIdentifier(device);
10295
10296 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10297 Product_ = [info objectForKey:@"SafariProductVersion"];
10298 Safari_ = [info objectForKey:@"CFBundleVersion"];
10299 }
10300
10301 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10302
10303 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10304 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10305 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10306 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10307 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10308 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10309
10310 UserAgent_ = agent;
10311 /* }}} */
10312 /* Load Database {{{ */
10313 _trace();
10314 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10315 _trace();
10316 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10317
10318 if (Metadata_ == NULL)
10319 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10320 else {
10321 Settings_ = [Metadata_ objectForKey:@"Settings"];
10322
10323 Packages_ = [Metadata_ objectForKey:@"Packages"];
10324
10325 Values_ = [Metadata_ objectForKey:@"Values"];
10326 Sections_ = [Metadata_ objectForKey:@"Sections"];
10327 Sources_ = [Metadata_ objectForKey:@"Sources"];
10328
10329 Token_ = [Metadata_ objectForKey:@"Token"];
10330
10331 Version_ = [Metadata_ objectForKey:@"Version"];
10332 }
10333
10334 if (Values_ == nil) {
10335 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10336 [Metadata_ setObject:Values_ forKey:@"Values"];
10337 }
10338
10339 if (Sections_ == nil) {
10340 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10341 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10342 }
10343
10344 if (Sources_ == nil) {
10345 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10346 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10347 }
10348
10349 if (Version_ == nil) {
10350 Version_ = [NSNumber numberWithUnsignedInt:0];
10351 [Metadata_ setObject:Version_ forKey:@"Version"];
10352 }
10353
10354 if ([Version_ unsignedIntValue] == 0) {
10355 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10356 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10357 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10358 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10359
10360 Version_ = [NSNumber numberWithUnsignedInt:1];
10361 [Metadata_ setObject:Version_ forKey:@"Version"];
10362
10363 [Metadata_ removeObjectForKey:@"LastUpdate"];
10364
10365 Changed_ = true;
10366 }
10367
10368 _H<NSMutableArray> broken([NSMutableArray array]);
10369 for (NSString *key in (id) Sources_)
10370 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10371 [broken addObject:key];
10372 if ([broken count] != 0) {
10373 for (NSString *key in (id) broken)
10374 [Sources_ removeObjectForKey:key];
10375 Changed_ = true;
10376 } broken = nil;
10377 /* }}} */
10378
10379 CydiaWriteSources();
10380
10381 _trace();
10382 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10383 _trace();
10384
10385 if (Packages_ != nil) {
10386 bool fail(false);
10387 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10388 _trace();
10389
10390 if (!fail) {
10391 [Metadata_ removeObjectForKey:@"Packages"];
10392 Packages_ = nil;
10393 Changed_ = true;
10394 }
10395 }
10396
10397 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10398
10399 #define MobileSubstrate_(name) \
10400 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10401 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10402 if (handle == NULL) \
10403 NSLog(@"%s", dlerror()); \
10404 }
10405
10406 MobileSubstrate_(Activator)
10407 MobileSubstrate_(libstatusbar)
10408 MobileSubstrate_(SimulatedKeyEvents)
10409 MobileSubstrate_(WinterBoard)
10410
10411 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10412 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10413
10414 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10415
10416 if (access("/User", F_OK) != 0 || version != 6) {
10417 _trace();
10418 system("/usr/libexec/cydia/firmware.sh");
10419 _trace();
10420 }
10421
10422 _assert([[NSFileManager defaultManager]
10423 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10424 withIntermediateDirectories:YES
10425 attributes:nil
10426 error:NULL
10427 ]);
10428
10429 if (access("/tmp/cydia.chk", F_OK) == 0) {
10430 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10431 _assert(errno == ENOENT);
10432 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10433 _assert(errno == ENOENT);
10434 }
10435
10436 /* APT Initialization {{{ */
10437 _assert(pkgInitConfig(*_config));
10438 _assert(pkgInitSystem(*_config, _system));
10439
10440 if (lang != NULL)
10441 _config->Set("APT::Acquire::Translation", lang);
10442
10443 // XXX: this timeout might be important :(
10444 //_config->Set("Acquire::http::Timeout", 15);
10445
10446 _config->Set("Acquire::http::MaxParallel", 3);
10447 /* }}} */
10448 /* Color Choices {{{ */
10449 space_ = CGColorSpaceCreateDeviceRGB();
10450
10451 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10452 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10453 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10454 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10455 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10456 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10457 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10458 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10459 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10460 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10461
10462 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10463 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10464 /* }}}*/
10465 /* UIKit Configuration {{{ */
10466 // XXX: I have a feeling this was important
10467 //UIKeyboardDisableAutomaticAppearance();
10468 /* }}} */
10469
10470 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10471
10472 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10473 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10474 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10475
10476 PulseInterval_ = fast ? 50000 : 500000;
10477
10478 Colon_ = UCLocalize("COLON_DELIMITED");
10479 Elision_ = UCLocalize("ELISION");
10480 Error_ = UCLocalize("ERROR");
10481 Warning_ = UCLocalize("WARNING");
10482
10483 _trace();
10484 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10485
10486 CGColorSpaceRelease(space_);
10487 CFRelease(Locale_);
10488
10489 [pool release];
10490 return value;
10491 }