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