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