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