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