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