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