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