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