]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
53df43e95b60081019658af30f74543fb0639a1c
[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 - (NSArray *) downgrades {
2739 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2740
2741 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2742 if (version == version_)
2743 continue;
2744 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2745 if ([package source] == nil)
2746 continue;
2747 [versions addObject:package];
2748 }
2749
2750 return versions;
2751 }
2752
2753 - (NSString *) section {
2754 if (section$_ == nil) {
2755 if (section_ == NULL)
2756 return nil;
2757
2758 _profile(Package$section$mappedSectionForPointer)
2759 section$_ = [database_ mappedSectionForPointer:section_];
2760 _end
2761 } return section$_;
2762 }
2763
2764 - (NSString *) simpleSection {
2765 if (NSString *section = [self section])
2766 return Simplify(section);
2767 else
2768 return nil;
2769 }
2770
2771 - (NSString *) longSection {
2772 if (NSString *section = [self section])
2773 return LocalizeSection(section);
2774 else
2775 return nil;
2776 }
2777
2778 - (NSString *) shortSection {
2779 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2780 }
2781
2782 - (NSString *) uri {
2783 return nil;
2784 #if 0
2785 pkgIndexFile *index;
2786 pkgCache::PkgFileIterator file(file_.File());
2787 if (![database_ list].FindIndex(file, index))
2788 return nil;
2789 return [NSString stringWithUTF8String:iterator_->Path];
2790 //return [NSString stringWithUTF8String:file.Site()];
2791 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2792 #endif
2793 }
2794
2795 - (MIMEAddress *) maintainer {
2796 @synchronized (database_) {
2797 if ([database_ era] != era_ || file_.end())
2798 return nil;
2799
2800 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2801 const std::string &maintainer(parser->Maintainer());
2802 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2803 } }
2804
2805 - (NSString *) md5sum {
2806 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2807 }
2808
2809 - (size_t) size {
2810 @synchronized (database_) {
2811 if ([database_ era] != era_ || version_.end())
2812 return 0;
2813
2814 return version_->InstalledSize;
2815 } }
2816
2817 - (NSString *) longDescription {
2818 @synchronized (database_) {
2819 if ([database_ era] != era_ || file_.end())
2820 return nil;
2821
2822 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2823 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2824
2825 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2826 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2827 if ([lines count] < 2)
2828 return nil;
2829
2830 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2831 for (size_t i(1), e([lines count]); i != e; ++i) {
2832 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2833 [trimmed addObject:trim];
2834 }
2835
2836 return [trimmed componentsJoinedByString:@"\n"];
2837 } }
2838
2839 - (NSString *) shortDescription {
2840 if (parsed_ != NULL)
2841 return static_cast<NSString *>(parsed_->tagline_);
2842
2843 @synchronized (database_) {
2844 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2845
2846 const char *start, *end;
2847 if (!parser.ShortDesc(start, end))
2848 return nil;
2849
2850 if (end - start > 200)
2851 end = start + 200;
2852
2853 /*
2854 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2855 end = stop;
2856
2857 while (end != start && end[-1] == '\r')
2858 --end;
2859 */
2860
2861 return [(id) CYStringCreate(start, end - start) autorelease];
2862 } }
2863
2864 - (unichar) index {
2865 _profile(Package$index)
2866 CFStringRef name((CFStringRef) [self name]);
2867 if (CFStringGetLength(name) == 0)
2868 return '#';
2869 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2870 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2871 return '#';
2872 return toupper(character);
2873 _end
2874 }
2875
2876 - (PackageValue *) metadata {
2877 return metadata_;
2878 }
2879
2880 - (time_t) seen {
2881 PackageValue *metadata([self metadata]);
2882 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2883 }
2884
2885 - (bool) subscribed {
2886 return [self metadata]->subscribed_;
2887 }
2888
2889 - (bool) setSubscribed:(bool)subscribed {
2890 PackageValue *metadata([self metadata]);
2891 if (metadata->subscribed_ == subscribed)
2892 return false;
2893 metadata->subscribed_ = subscribed;
2894 return true;
2895 }
2896
2897 - (BOOL) ignored {
2898 return ignored_;
2899 }
2900
2901 - (NSString *) latest {
2902 return latest_;
2903 }
2904
2905 - (NSString *) installed {
2906 return installed_;
2907 }
2908
2909 - (BOOL) uninstalled {
2910 return installed_.empty();
2911 }
2912
2913 - (BOOL) upgradableAndEssential:(BOOL)essential {
2914 _profile(Package$upgradableAndEssential)
2915 pkgCache::VerIterator current(iterator_.CurrentVer());
2916 if (current.end())
2917 return essential && essential_;
2918 else
2919 return version_ != current;
2920 _end
2921 }
2922
2923 - (BOOL) essential {
2924 return essential_;
2925 }
2926
2927 - (BOOL) broken {
2928 return [database_ cache][iterator_].InstBroken();
2929 }
2930
2931 - (BOOL) unfiltered {
2932 _profile(Package$unfiltered$obsolete)
2933 if (_unlikely(obsolete_))
2934 return false;
2935 _end
2936
2937 _profile(Package$unfiltered$role)
2938 if (_unlikely(role_ > 3))
2939 return false;
2940 _end
2941
2942 return true;
2943 }
2944
2945 - (BOOL) visible {
2946 if (![self unfiltered])
2947 return false;
2948
2949 NSString *section;
2950
2951 _profile(Package$visible$section)
2952 section = [self section];
2953 _end
2954
2955 _profile(Package$visible$isSectionVisible)
2956 if (!isSectionVisible(section))
2957 return false;
2958 _end
2959
2960 return true;
2961 }
2962
2963 - (BOOL) half {
2964 unsigned char current(iterator_->CurrentState);
2965 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2966 }
2967
2968 - (BOOL) halfConfigured {
2969 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2970 }
2971
2972 - (BOOL) halfInstalled {
2973 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2974 }
2975
2976 - (BOOL) hasMode {
2977 @synchronized (database_) {
2978 if ([database_ era] != era_ || iterator_.end())
2979 return NO;
2980
2981 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2982 return state.Mode != pkgDepCache::ModeKeep;
2983 } }
2984
2985 - (NSString *) mode {
2986 @synchronized (database_) {
2987 if ([database_ era] != era_ || iterator_.end())
2988 return nil;
2989
2990 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2991
2992 switch (state.Mode) {
2993 case pkgDepCache::ModeDelete:
2994 if ((state.iFlags & pkgDepCache::Purge) != 0)
2995 return @"PURGE";
2996 else
2997 return @"REMOVE";
2998 case pkgDepCache::ModeKeep:
2999 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3000 return @"REINSTALL";
3001 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3002 return nil;*/
3003 else
3004 return nil;
3005 case pkgDepCache::ModeInstall:
3006 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3007 return @"REINSTALL";
3008 else*/ switch (state.Status) {
3009 case -1:
3010 return @"DOWNGRADE";
3011 case 0:
3012 return @"INSTALL";
3013 case 1:
3014 return @"UPGRADE";
3015 case 2:
3016 return @"NEW_INSTALL";
3017 _nodefault
3018 }
3019 _nodefault
3020 }
3021 } }
3022
3023 - (NSString *) id {
3024 return id_;
3025 }
3026
3027 - (NSString *) name {
3028 return name_.empty() ? id_ : name_;
3029 }
3030
3031 - (UIImage *) icon {
3032 NSString *section = [self simpleSection];
3033
3034 UIImage *icon(nil);
3035 if (parsed_ != NULL)
3036 if (NSString *href = parsed_->icon_)
3037 if ([href hasPrefix:@"file:///"])
3038 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3039 if (icon == nil) if (section != nil)
3040 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3041 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3042 if ([dicon hasPrefix:@"file:///"])
3043 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3044 if (icon == nil)
3045 icon = [UIImage imageNamed:@"unknown.png"];
3046 return icon;
3047 }
3048
3049 - (NSString *) homepage {
3050 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3051 }
3052
3053 - (NSString *) depiction {
3054 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3055 }
3056
3057 - (MIMEAddress *) author {
3058 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3059 }
3060
3061 - (NSString *) support {
3062 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3063 }
3064
3065 - (NSArray *) files {
3066 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3067 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3068
3069 std::ifstream fin;
3070 fin.open([path UTF8String]);
3071 if (!fin.is_open())
3072 return nil;
3073
3074 std::string line;
3075 while (std::getline(fin, line))
3076 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3077
3078 return files;
3079 }
3080
3081 - (NSString *) state {
3082 @synchronized (database_) {
3083 if ([database_ era] != era_ || file_.end())
3084 return nil;
3085
3086 switch (iterator_->CurrentState) {
3087 case pkgCache::State::NotInstalled:
3088 return @"NotInstalled";
3089 case pkgCache::State::UnPacked:
3090 return @"UnPacked";
3091 case pkgCache::State::HalfConfigured:
3092 return @"HalfConfigured";
3093 case pkgCache::State::HalfInstalled:
3094 return @"HalfInstalled";
3095 case pkgCache::State::ConfigFiles:
3096 return @"ConfigFiles";
3097 case pkgCache::State::Installed:
3098 return @"Installed";
3099 case pkgCache::State::TriggersAwaited:
3100 return @"TriggersAwaited";
3101 case pkgCache::State::TriggersPending:
3102 return @"TriggersPending";
3103 }
3104
3105 return (NSString *) [NSNull null];
3106 } }
3107
3108 - (NSString *) selection {
3109 @synchronized (database_) {
3110 if ([database_ era] != era_ || file_.end())
3111 return nil;
3112
3113 switch (iterator_->SelectedState) {
3114 case pkgCache::State::Unknown:
3115 return @"Unknown";
3116 case pkgCache::State::Install:
3117 return @"Install";
3118 case pkgCache::State::Hold:
3119 return @"Hold";
3120 case pkgCache::State::DeInstall:
3121 return @"DeInstall";
3122 case pkgCache::State::Purge:
3123 return @"Purge";
3124 }
3125
3126 return (NSString *) [NSNull null];
3127 } }
3128
3129 - (NSArray *) warnings {
3130 @synchronized (database_) {
3131 if ([database_ era] != era_ || file_.end())
3132 return nil;
3133
3134 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3135 const char *name(iterator_.Name());
3136
3137 size_t length(strlen(name));
3138 if (length < 2) invalid:
3139 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3140 else for (size_t i(0); i != length; ++i)
3141 if (
3142 /* XXX: technically this is not allowed */
3143 (name[i] < 'A' || name[i] > 'Z') &&
3144 (name[i] < 'a' || name[i] > 'z') &&
3145 (name[i] < '0' || name[i] > '9') &&
3146 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3147 ) goto invalid;
3148
3149 if (strcmp(name, "cydia") != 0) {
3150 bool cydia = false;
3151 bool user = false;
3152 bool _private = false;
3153 bool stash = false;
3154 bool dbstash = false;
3155 bool dsstore = false;
3156
3157 bool repository = [[self section] isEqualToString:@"Repositories"];
3158
3159 if (NSArray *files = [self files])
3160 for (NSString *file in files)
3161 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3162 cydia = true;
3163 else if (!user && [file isEqualToString:@"/User"])
3164 user = true;
3165 else if (!_private && [file isEqualToString:@"/private"])
3166 _private = true;
3167 else if (!stash && [file isEqualToString:@"/var/stash"])
3168 stash = true;
3169 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3170 dbstash = true;
3171 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3172 dsstore = true;
3173
3174 /* XXX: this is not sensitive enough. only some folders are valid. */
3175 if (cydia && !repository)
3176 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3177 if (user)
3178 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3179 if (_private)
3180 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3181 if (stash)
3182 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3183 if (dbstash)
3184 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3185 if (dsstore)
3186 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3187 }
3188
3189 return [warnings count] == 0 ? nil : warnings;
3190 } }
3191
3192 - (NSArray *) applications {
3193 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3194
3195 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3196
3197 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3198 if (NSArray *files = [self files])
3199 for (NSString *file in files)
3200 if (application_r(file)) {
3201 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3202 if (info == nil)
3203 continue;
3204 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3205 if (id == nil || [id isEqualToString:me])
3206 continue;
3207
3208 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3209 if (display == nil)
3210 display = application_r[1];
3211
3212 NSString *bundle([file stringByDeletingLastPathComponent]);
3213 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3214 // XXX: maybe this should check if this is really a string, not just for length
3215 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3216 icon = @"icon.png";
3217 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3218
3219 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3220 [applications addObject:application];
3221
3222 [application addObject:id];
3223 [application addObject:display];
3224 [application addObject:url];
3225 }
3226
3227 return [applications count] == 0 ? nil : applications;
3228 }
3229
3230 - (Source *) source {
3231 if (source_ == nil) {
3232 @synchronized (database_) {
3233 if ([database_ era] != era_ || file_.end())
3234 source_ = (Source *) [NSNull null];
3235 else
3236 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3237 }
3238 }
3239
3240 return source_ == (Source *) [NSNull null] ? nil : source_;
3241 }
3242
3243 - (time_t) upgraded {
3244 return upgraded_;
3245 }
3246
3247 - (uint32_t) recent {
3248 return std::numeric_limits<uint32_t>::max() - upgraded_;
3249 }
3250
3251 - (uint32_t) rank {
3252 return rank_;
3253 }
3254
3255 - (BOOL) matches:(NSArray *)query {
3256 if (query == nil || [query count] == 0)
3257 return NO;
3258
3259 rank_ = 0;
3260
3261 NSString *string;
3262 NSRange range;
3263 NSUInteger length;
3264
3265 string = [self name];
3266 length = [string length];
3267
3268 if (length != 0)
3269 for (NSString *term in query) {
3270 range = [string rangeOfString:term options:MatchCompareOptions_];
3271 if (range.location != NSNotFound)
3272 rank_ -= 6 * 1000000 / length;
3273 }
3274
3275 if (rank_ == 0) {
3276 string = [self id];
3277 length = [string length];
3278
3279 if (length != 0)
3280 for (NSString *term in query) {
3281 range = [string rangeOfString:term options:MatchCompareOptions_];
3282 if (range.location != NSNotFound)
3283 rank_ -= 6 * 1000000 / length;
3284 }
3285 }
3286
3287 string = [self shortDescription];
3288 length = [string length];
3289 NSUInteger stop(std::min<NSUInteger>(length, 200));
3290
3291 if (length != 0)
3292 for (NSString *term in query) {
3293 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3294 if (range.location != NSNotFound)
3295 rank_ -= 2 * 100000;
3296 }
3297
3298 return rank_ != 0;
3299 }
3300
3301 - (NSArray *) tags {
3302 return tags_;
3303 }
3304
3305 - (BOOL) hasTag:(NSString *)tag {
3306 return tags_ == nil ? NO : [tags_ containsObject:tag];
3307 }
3308
3309 - (NSString *) primaryPurpose {
3310 for (NSString *tag in (NSArray *) tags_)
3311 if ([tag hasPrefix:@"purpose::"])
3312 return [tag substringFromIndex:9];
3313 return nil;
3314 }
3315
3316 - (NSArray *) purposes {
3317 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3318 for (NSString *tag in (NSArray *) tags_)
3319 if ([tag hasPrefix:@"purpose::"])
3320 [purposes addObject:[tag substringFromIndex:9]];
3321 return [purposes count] == 0 ? nil : purposes;
3322 }
3323
3324 - (bool) isCommercial {
3325 return [self hasTag:@"cydia::commercial"];
3326 }
3327
3328 - (void) setIndex:(size_t)index {
3329 if (metadata_->index_ != index)
3330 metadata_->index_ = index;
3331 }
3332
3333 - (CYString &) cyname {
3334 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3335 }
3336
3337 - (uint32_t) compareBySection:(NSArray *)sections {
3338 NSString *section([self section]);
3339 for (size_t i(0), e([sections count]); i != e; ++i) {
3340 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3341 return i;
3342 }
3343
3344 return _not(uint32_t);
3345 }
3346
3347 - (void) clear {
3348 @synchronized (database_) {
3349 if ([database_ era] != era_ || file_.end())
3350 return;
3351
3352 pkgProblemResolver *resolver = [database_ resolver];
3353 resolver->Clear(iterator_);
3354
3355 pkgCacheFile &cache([database_ cache]);
3356 cache->SetReInstall(iterator_, false);
3357 cache->MarkKeep(iterator_, false);
3358 } }
3359
3360 - (void) install {
3361 @synchronized (database_) {
3362 if ([database_ era] != era_ || file_.end())
3363 return;
3364
3365 pkgProblemResolver *resolver = [database_ resolver];
3366 resolver->Clear(iterator_);
3367 resolver->Protect(iterator_);
3368
3369 pkgCacheFile &cache([database_ cache]);
3370 cache->SetCandidateVersion(version_);
3371 cache->SetReInstall(iterator_, false);
3372 cache->MarkInstall(iterator_, false);
3373
3374 pkgDepCache::StateCache &state((*cache)[iterator_]);
3375 if (!state.Install())
3376 cache->SetReInstall(iterator_, true);
3377 } }
3378
3379 - (void) remove {
3380 @synchronized (database_) {
3381 if ([database_ era] != era_ || file_.end())
3382 return;
3383
3384 pkgProblemResolver *resolver = [database_ resolver];
3385 resolver->Clear(iterator_);
3386 resolver->Remove(iterator_);
3387 resolver->Protect(iterator_);
3388
3389 pkgCacheFile &cache([database_ cache]);
3390 cache->SetReInstall(iterator_, false);
3391 cache->MarkDelete(iterator_, true);
3392 } }
3393
3394 @end
3395 /* }}} */
3396 /* Section Class {{{ */
3397 @interface Section : NSObject {
3398 _H<NSString> name_;
3399 size_t row_;
3400 size_t count_;
3401 _H<NSString> localized_;
3402 }
3403
3404 - (NSComparisonResult) compareByLocalized:(Section *)section;
3405 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3406 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3407 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3408
3409 - (NSString *) name;
3410 - (void) setName:(NSString *)name;
3411
3412 - (size_t) row;
3413 - (size_t) count;
3414
3415 - (void) addToRow;
3416 - (void) addToCount;
3417
3418 - (void) setCount:(size_t)count;
3419 - (NSString *) localized;
3420
3421 @end
3422
3423 @implementation Section
3424
3425 - (NSComparisonResult) compareByLocalized:(Section *)section {
3426 NSString *lhs(localized_);
3427 NSString *rhs([section localized]);
3428
3429 /*if ([lhs length] != 0 && [rhs length] != 0) {
3430 unichar lhc = [lhs characterAtIndex:0];
3431 unichar rhc = [rhs characterAtIndex:0];
3432
3433 if (isalpha(lhc) && !isalpha(rhc))
3434 return NSOrderedAscending;
3435 else if (!isalpha(lhc) && isalpha(rhc))
3436 return NSOrderedDescending;
3437 }*/
3438
3439 return [lhs compare:rhs options:LaxCompareOptions_];
3440 }
3441
3442 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3443 if ((self = [self initWithName:name localize:NO]) != nil) {
3444 if (localized != nil)
3445 localized_ = localized;
3446 } return self;
3447 }
3448
3449 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3450 return [self initWithName:name row:0 localize:localize];
3451 }
3452
3453 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3454 if ((self = [super init]) != nil) {
3455 name_ = name;
3456 row_ = row;
3457 if (localize)
3458 localized_ = LocalizeSection(name_);
3459 } return self;
3460 }
3461
3462 - (NSString *) name {
3463 return name_;
3464 }
3465
3466 - (void) setName:(NSString *)name {
3467 name_ = name;
3468 }
3469
3470 - (size_t) row {
3471 return row_;
3472 }
3473
3474 - (size_t) count {
3475 return count_;
3476 }
3477
3478 - (void) addToRow {
3479 ++row_;
3480 }
3481
3482 - (void) addToCount {
3483 ++count_;
3484 }
3485
3486 - (void) setCount:(size_t)count {
3487 count_ = count;
3488 }
3489
3490 - (NSString *) localized {
3491 return localized_;
3492 }
3493
3494 @end
3495 /* }}} */
3496
3497 class CydiaLogCleaner :
3498 public pkgArchiveCleaner
3499 {
3500 protected:
3501 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3502 unlink(File);
3503 }
3504 };
3505
3506 /* Database Implementation {{{ */
3507 @implementation Database
3508
3509 + (Database *) sharedInstance {
3510 static _H<Database> instance;
3511 if (instance == nil)
3512 instance = [[[Database alloc] init] autorelease];
3513 return instance;
3514 }
3515
3516 - (unsigned) era {
3517 return era_;
3518 }
3519
3520 - (void) releasePackages {
3521 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3522 CFArrayRemoveAllValues(packages_);
3523 }
3524
3525 - (void) dealloc {
3526 // XXX: actually implement this thing
3527 _assert(false);
3528 [self releasePackages];
3529 NSRecycleZone(zone_);
3530 [super dealloc];
3531 }
3532
3533 - (void) _readCydia:(NSNumber *)fd {
3534 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3535 std::istream is(&ib);
3536 std::string line;
3537
3538 static RegEx finish_r("finish:([^:]*)");
3539
3540 while (std::getline(is, line)) {
3541 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3542
3543 const char *data(line.c_str());
3544 size_t size = line.size();
3545 lprintf("C:%s\n", data);
3546
3547 if (finish_r(data, size)) {
3548 NSString *finish = finish_r[1];
3549 int index = [Finishes_ indexOfObject:finish];
3550 if (index != INT_MAX && index > Finish_)
3551 Finish_ = index;
3552 }
3553
3554 [pool release];
3555 }
3556
3557 _assume(false);
3558 }
3559
3560 - (void) _readStatus:(NSNumber *)fd {
3561 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3562 std::istream is(&ib);
3563 std::string line;
3564
3565 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3566 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3567
3568 while (std::getline(is, line)) {
3569 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3570
3571 const char *data(line.c_str());
3572 size_t size(line.size());
3573 lprintf("S:%s\n", data);
3574
3575 if (conffile_r(data, size)) {
3576 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3577 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3578 } else if (strncmp(data, "status: ", 8) == 0) {
3579 // status: <package>: {unpacked,half-configured,installed}
3580 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3581 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3582 } else if (strncmp(data, "processing: ", 12) == 0) {
3583 // processing: configure: config-test
3584 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3585 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3586 } else if (pmstatus_r(data, size)) {
3587 std::string type([pmstatus_r[1] UTF8String]);
3588
3589 NSString *package = pmstatus_r[2];
3590 if ([package isEqualToString:@"dpkg-exec"])
3591 package = nil;
3592
3593 float percent([pmstatus_r[3] floatValue]);
3594 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3595
3596 NSString *string = pmstatus_r[4];
3597
3598 if (type == "pmerror") {
3599 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3600 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3601 } else if (type == "pmstatus") {
3602 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3603 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3604 } else if (type == "pmconffile")
3605 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3606 else
3607 lprintf("E:unknown pmstatus\n");
3608 } else
3609 lprintf("E:unknown status\n");
3610
3611 [pool release];
3612 }
3613
3614 _assume(false);
3615 }
3616
3617 - (void) _readOutput:(NSNumber *)fd {
3618 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3619 std::istream is(&ib);
3620 std::string line;
3621
3622 while (std::getline(is, line)) {
3623 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3624
3625 lprintf("O:%s\n", line.c_str());
3626
3627 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3628 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3629
3630 [pool release];
3631 }
3632
3633 _assume(false);
3634 }
3635
3636 - (FILE *) input {
3637 return input_;
3638 }
3639
3640 - (Package *) packageWithName:(NSString *)name {
3641 if (name == nil)
3642 return nil;
3643 @synchronized (self) {
3644 if (static_cast<pkgDepCache *>(cache_) == NULL)
3645 return nil;
3646 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3647 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3648 } }
3649
3650 - (id) init {
3651 if ((self = [super init]) != nil) {
3652 policy_ = NULL;
3653 records_ = NULL;
3654 resolver_ = NULL;
3655 fetcher_ = NULL;
3656 lock_ = NULL;
3657
3658 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3659
3660 size_t capacity(MetaFile_->active_);
3661 if (capacity == 0)
3662 capacity = 16384;
3663 else
3664 capacity += 1024;
3665
3666 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3667 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3668
3669 int fds[2];
3670
3671 _assert(pipe(fds) != -1);
3672 cydiafd_ = fds[1];
3673
3674 _config->Set("APT::Keep-Fds::", cydiafd_);
3675 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3676
3677 [NSThread
3678 detachNewThreadSelector:@selector(_readCydia:)
3679 toTarget:self
3680 withObject:[NSNumber numberWithInt:fds[0]]
3681 ];
3682
3683 _assert(pipe(fds) != -1);
3684 statusfd_ = fds[1];
3685
3686 [NSThread
3687 detachNewThreadSelector:@selector(_readStatus:)
3688 toTarget:self
3689 withObject:[NSNumber numberWithInt:fds[0]]
3690 ];
3691
3692 _assert(pipe(fds) != -1);
3693 _assert(dup2(fds[0], 0) != -1);
3694 _assert(close(fds[0]) != -1);
3695
3696 input_ = fdopen(fds[1], "a");
3697
3698 _assert(pipe(fds) != -1);
3699 _assert(dup2(fds[1], 1) != -1);
3700 _assert(close(fds[1]) != -1);
3701
3702 [NSThread
3703 detachNewThreadSelector:@selector(_readOutput:)
3704 toTarget:self
3705 withObject:[NSNumber numberWithInt:fds[0]]
3706 ];
3707 } return self;
3708 }
3709
3710 - (pkgCacheFile &) cache {
3711 return cache_;
3712 }
3713
3714 - (pkgDepCache::Policy *) policy {
3715 return policy_;
3716 }
3717
3718 - (pkgRecords *) records {
3719 return records_;
3720 }
3721
3722 - (pkgProblemResolver *) resolver {
3723 return resolver_;
3724 }
3725
3726 - (pkgAcquire &) fetcher {
3727 return *fetcher_;
3728 }
3729
3730 - (pkgSourceList &) list {
3731 return *list_;
3732 }
3733
3734 - (NSArray *) packages {
3735 return (NSArray *) packages_;
3736 }
3737
3738 - (NSArray *) sources {
3739 return sourceList_;
3740 }
3741
3742 - (Source *) sourceWithKey:(NSString *)key {
3743 for (Source *source in [self sources]) {
3744 if ([[source key] isEqualToString:key])
3745 return source;
3746 } return nil;
3747 }
3748
3749 - (bool) popErrorWithTitle:(NSString *)title {
3750 bool fatal(false);
3751
3752 while (!_error->empty()) {
3753 std::string error;
3754 bool warning(!_error->PopMessage(error));
3755 if (!warning)
3756 fatal = true;
3757
3758 for (;;) {
3759 size_t size(error.size());
3760 if (size == 0 || error[size - 1] != '\n')
3761 break;
3762 error.resize(size - 1);
3763 }
3764
3765 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3766
3767 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3768 if (warning && no_pubkey(error.c_str()))
3769 continue;
3770
3771 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3772 }
3773
3774 return fatal;
3775 }
3776
3777 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3778 return [self popErrorWithTitle:title] || !success;
3779 }
3780
3781 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3782 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3783 return true;
3784 return false;
3785
3786 list.Reset();
3787
3788 bool error(false);
3789
3790 if (access("/etc/apt/sources.list", F_OK) == 0)
3791 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3792
3793 std::string base("/etc/apt/sources.list.d");
3794 if (DIR *sources = opendir(base.c_str())) {
3795 while (dirent *source = readdir(sources))
3796 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)
3797 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3798 closedir(sources);
3799 }
3800
3801 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3802
3803 return error;
3804 }
3805
3806 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3807 @synchronized (self) {
3808 ++era_;
3809
3810 [self releasePackages];
3811
3812 sourceMap_.clear();
3813 [sourceList_ removeAllObjects];
3814
3815 _error->Discard();
3816
3817 delete list_;
3818 list_ = NULL;
3819 manager_ = NULL;
3820 delete lock_;
3821 lock_ = NULL;
3822 delete fetcher_;
3823 fetcher_ = NULL;
3824 delete resolver_;
3825 resolver_ = NULL;
3826 delete records_;
3827 records_ = NULL;
3828 delete policy_;
3829 policy_ = NULL;
3830
3831 cache_.Close();
3832
3833 pool_.~CYPool();
3834 new (&pool_) CYPool();
3835
3836 NSRecycleZone(zone_);
3837 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3838
3839 int chk(creat("/tmp/cydia.chk", 0644));
3840 if (chk != -1)
3841 close(chk);
3842
3843 if (invocation != nil)
3844 [invocation invoke];
3845
3846 NSString *title(UCLocalize("DATABASE"));
3847
3848 list_ = new pkgSourceList();
3849 _profile(reloadDataWithInvocation$ReadMainList)
3850 if ([self popErrorWithTitle:title forReadList:*list_])
3851 return;
3852 _end
3853
3854 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3855 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3856 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3857 [sourceList_ addObject:object];
3858 }
3859 _end
3860
3861 _trace();
3862 OpProgress progress;
3863 bool opened;
3864 open:
3865 delock_ = GetStatusDate();
3866 _profile(reloadDataWithInvocation$pkgCacheFile)
3867 opened = cache_.Open(progress, false);
3868 _end
3869 if (!opened) {
3870 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3871 while (!_error->empty()) {
3872 std::string error;
3873 bool warning(!_error->PopMessage(error));
3874
3875 lprintf("cache_.Open():[%s]\n", error.c_str());
3876
3877 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3878
3879 SEL repair(NULL);
3880 if (false);
3881 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3882 repair = @selector(configure);
3883 //else if (error == "The package lists or status file could not be parsed or opened.")
3884 // repair = @selector(update);
3885 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3886 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3887 // else if (error == "Malformed Status line")
3888 // else if (error == "The list of sources could not be read.")
3889
3890 if (repair != NULL) {
3891 _error->Discard();
3892 [delegate_ repairWithSelector:repair];
3893 goto open;
3894 }
3895 }
3896
3897 return;
3898 }
3899 _trace();
3900
3901 unlink("/tmp/cydia.chk");
3902
3903 now_ = [[NSDate date] timeIntervalSince1970];
3904
3905 policy_ = new pkgDepCache::Policy();
3906 records_ = new pkgRecords(cache_);
3907 resolver_ = new pkgProblemResolver(cache_);
3908 fetcher_ = new pkgAcquire(&status_);
3909 lock_ = NULL;
3910
3911 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3912 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3913 return;
3914 }
3915
3916 _profile(reloadDataWithInvocation$pkgApplyStatus)
3917 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3918 return;
3919 _end
3920
3921 if (cache_->BrokenCount() != 0) {
3922 _profile(pkgApplyStatus$pkgFixBroken)
3923 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3924 return;
3925 _end
3926
3927 if (cache_->BrokenCount() != 0) {
3928 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3929 return;
3930 }
3931
3932 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3933 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3934 return;
3935 _end
3936 }
3937
3938 for (Source *object in (id) sourceList_) {
3939 metaIndex *source([object metaIndex]);
3940 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3941 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3942 // XXX: this could be more intelligent
3943 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3944 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3945 if (!cached.end())
3946 sourceMap_[cached->ID] = object;
3947 }
3948 }
3949
3950 {
3951 /*std::vector<Package *> packages;
3952 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3953 packages_ = nil;*/
3954
3955 _profile(reloadDataWithInvocation$packageWithIterator)
3956 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3957 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3958 //packages.push_back(package);
3959 CFArrayAppendValue(packages_, CFRetain(package));
3960 _end
3961
3962
3963 /*if (packages.empty())
3964 packages_ = [[NSArray alloc] init];
3965 else
3966 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3967 _trace();*/
3968
3969 _profile(reloadDataWithInvocation$radix$8)
3970 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3971 _end
3972
3973 _profile(reloadDataWithInvocation$radix$4)
3974 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3975 _end
3976
3977 _profile(reloadDataWithInvocation$radix$0)
3978 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3979 _end
3980
3981 _profile(reloadDataWithInvocation$insertion)
3982 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3983 _end
3984
3985 /*_profile(reloadDataWithInvocation$CFQSortArray)
3986 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3987 _end*/
3988
3989 /*_profile(reloadDataWithInvocation$stdsort)
3990 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3991 _end*/
3992
3993 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3994 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3995 _end*/
3996
3997 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3998 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3999 _end*/
4000
4001
4002 size_t count(CFArrayGetCount(packages_));
4003 MetaFile_->active_ = count;
4004 for (size_t index(0); index != count; ++index)
4005 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
4006 }
4007 } }
4008
4009 - (void) clear {
4010 @synchronized (self) {
4011 delete resolver_;
4012 resolver_ = new pkgProblemResolver(cache_);
4013
4014 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4015 if (!cache_[iterator].Keep())
4016 cache_->MarkKeep(iterator, false);
4017 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4018 cache_->SetReInstall(iterator, false);
4019 } }
4020
4021 - (void) configure {
4022 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4023 _trace();
4024 system([dpkg UTF8String]);
4025 _trace();
4026 }
4027
4028 - (bool) clean {
4029 @synchronized (self) {
4030 // XXX: I don't remember this condition
4031 if (lock_ != NULL)
4032 return false;
4033
4034 FileFd Lock;
4035 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4036
4037 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4038
4039 if ([self popErrorWithTitle:title])
4040 return false;
4041
4042 pkgAcquire fetcher;
4043 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4044
4045 CydiaLogCleaner cleaner;
4046 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4047 return false;
4048
4049 return true;
4050 } }
4051
4052 - (bool) prepare {
4053 fetcher_->Shutdown();
4054
4055 pkgRecords records(cache_);
4056
4057 lock_ = new FileFd();
4058 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4059
4060 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4061
4062 if ([self popErrorWithTitle:title])
4063 return false;
4064
4065 pkgSourceList list;
4066 if ([self popErrorWithTitle:title forReadList:list])
4067 return false;
4068
4069 manager_ = (_system->CreatePM(cache_));
4070 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4071 return false;
4072
4073 return true;
4074 }
4075
4076 - (void) perform {
4077 bool substrate(RestartSubstrate_);
4078 RestartSubstrate_ = false;
4079
4080 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4081
4082 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4083 pkgSourceList list;
4084 if ([self popErrorWithTitle:title forReadList:list])
4085 return;
4086 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4087 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4088 }
4089
4090 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4091
4092 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4093 _trace();
4094 [self popErrorWithTitle:title];
4095 return;
4096 }
4097
4098 bool failed = false;
4099 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4100 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4101 continue;
4102 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4103 continue;
4104
4105 std::string uri = (*item)->DescURI();
4106 std::string error = (*item)->ErrorText;
4107
4108 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4109 failed = true;
4110
4111 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4112 [delegate_ addProgressEventOnMainThread:event forTask:title];
4113 }
4114
4115 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4116
4117 if (failed) {
4118 _trace();
4119 return;
4120 }
4121
4122 if (substrate)
4123 RestartSubstrate_ = true;
4124
4125 if (![delock_ isEqual:GetStatusDate()]) {
4126 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4127 return;
4128 }
4129
4130 delock_ = nil;
4131
4132 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4133
4134 NSString *oextended(@"/var/lib/apt/extended_states");
4135 NSString *nextended(Cache("extended_states"));
4136
4137 struct stat info;
4138 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4139 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4140
4141 unlink([nextended UTF8String]);
4142 symlink([oextended UTF8String], [nextended UTF8String]);
4143
4144 if ([self popErrorWithTitle:title])
4145 return;
4146
4147 if (result == pkgPackageManager::Failed) {
4148 _trace();
4149 return;
4150 }
4151
4152 if (result != pkgPackageManager::Completed) {
4153 _trace();
4154 return;
4155 }
4156
4157 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4158 pkgSourceList list;
4159 if ([self popErrorWithTitle:title forReadList:list])
4160 return;
4161 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4162 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4163 }
4164
4165 if (![before isEqualToArray:after])
4166 [self update];
4167 }
4168
4169 - (bool) delocked {
4170 return ![delock_ isEqual:GetStatusDate()];
4171 }
4172
4173 - (bool) upgrade {
4174 NSString *title(UCLocalize("UPGRADE"));
4175 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4176 return false;
4177 return true;
4178 }
4179
4180 - (void) update {
4181 [self updateWithStatus:status_];
4182 }
4183
4184 - (void) updateWithStatus:(CancelStatus &)status {
4185 NSString *title(UCLocalize("REFRESHING_DATA"));
4186
4187 pkgSourceList list;
4188 if ([self popErrorWithTitle:title forReadList:list])
4189 return;
4190
4191 FileFd lock;
4192 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4193 if ([self popErrorWithTitle:title])
4194 return;
4195
4196 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4197
4198 bool success(ListUpdate(status, list, PulseInterval_));
4199 if (status.WasCancelled())
4200 _error->Discard();
4201 else {
4202 [self popErrorWithTitle:title forOperation:success];
4203
4204 [[NSDictionary dictionaryWithObjectsAndKeys:
4205 [NSDate date], @"LastUpdate",
4206 nil] writeToFile:@ CacheState_ atomically:YES];
4207 }
4208
4209 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4210 }
4211
4212 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4213 delegate_ = delegate;
4214 }
4215
4216 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4217 progress_ = delegate;
4218 status_.setDelegate(delegate);
4219 }
4220
4221 - (NSObject<ProgressDelegate> *) progressDelegate {
4222 return progress_;
4223 }
4224
4225 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4226 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4227 return i == sourceMap_.end() ? nil : i->second;
4228 }
4229
4230 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4231 for (Source *source in (id) sourceList_)
4232 [source setFetch:fetch forURI:uri];
4233 }
4234
4235 - (void) resetFetch {
4236 for (Source *source in (id) sourceList_)
4237 [source resetFetch];
4238 }
4239
4240 - (NSString *) mappedSectionForPointer:(const char *)section {
4241 _H<NSString> *mapped;
4242
4243 _profile(Database$mappedSectionForPointer$Cache)
4244 mapped = &sections_[section];
4245 _end
4246
4247 if (*mapped == NULL) {
4248 size_t length(strlen(section));
4249 char spaced[length + 1];
4250
4251 _profile(Database$mappedSectionForPointer$Replace)
4252 for (size_t index(0); index != length; ++index)
4253 spaced[index] = section[index] == '_' ? ' ' : section[index];
4254 spaced[length] = '\0';
4255 _end
4256
4257 NSString *string;
4258
4259 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4260 string = [NSString stringWithUTF8String:spaced];
4261 _end
4262
4263 _profile(Database$mappedSectionForPointer$Map)
4264 string = [SectionMap_ objectForKey:string] ?: string;
4265 _end
4266
4267 *mapped = string;
4268 } return *mapped;
4269 }
4270
4271 @end
4272 /* }}} */
4273
4274 static _H<NSMutableSet> Diversions_;
4275
4276 @interface Diversion : NSObject {
4277 RegEx pattern_;
4278 _H<NSString> key_;
4279 _H<NSString> format_;
4280 }
4281
4282 @end
4283
4284 @implementation Diversion
4285
4286 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4287 if ((self = [super init]) != nil) {
4288 pattern_ = [from UTF8String];
4289 key_ = from;
4290 format_ = to;
4291 } return self;
4292 }
4293
4294 - (NSString *) divert:(NSString *)url {
4295 return !pattern_(url) ? nil : pattern_->*format_;
4296 }
4297
4298 + (NSURL *) divertURL:(NSURL *)url {
4299 divert:
4300 NSString *href([url absoluteString]);
4301
4302 for (Diversion *diversion in (id) Diversions_)
4303 if (NSString *diverted = [diversion divert:href]) {
4304 #if !ForRelease
4305 NSLog(@"div: %@", diverted);
4306 #endif
4307 url = [NSURL URLWithString:diverted];
4308 goto divert;
4309 }
4310
4311 return url;
4312 }
4313
4314 - (NSString *) key {
4315 return key_;
4316 }
4317
4318 - (NSUInteger) hash {
4319 return [key_ hash];
4320 }
4321
4322 - (BOOL) isEqual:(Diversion *)object {
4323 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4324 }
4325
4326 @end
4327
4328 @interface CydiaObject : NSObject {
4329 _H<CyteWebViewController> indirect_;
4330 _transient id delegate_;
4331 }
4332
4333 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4334
4335 @end
4336
4337 @class CydiaObject;
4338
4339 @interface CydiaWebViewController : CyteWebViewController {
4340 _H<CydiaObject> cydia_;
4341 }
4342
4343 + (void) addDiversion:(Diversion *)diversion;
4344 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4345 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4346 - (void) setDelegate:(id)delegate;
4347
4348 @end
4349
4350 /* Web Scripting {{{ */
4351 @implementation CydiaObject
4352
4353 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4354 if ((self = [super init]) != nil) {
4355 indirect_ = (CyteWebViewController *) indirect;
4356 } return self;
4357 }
4358
4359 - (void) setDelegate:(id)delegate {
4360 delegate_ = delegate;
4361 }
4362
4363 + (NSArray *) _attributeKeys {
4364 return [NSArray arrayWithObjects:
4365 @"bbsnum",
4366 @"build",
4367 @"coreFoundationVersionNumber",
4368 @"device",
4369 @"ecid",
4370 @"firmware",
4371 @"hostname",
4372 @"idiom",
4373 @"mcc",
4374 @"mnc",
4375 @"model",
4376 @"operator",
4377 @"role",
4378 @"serial",
4379 @"version",
4380 nil];
4381 }
4382
4383 - (NSArray *) attributeKeys {
4384 return [[self class] _attributeKeys];
4385 }
4386
4387 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4388 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4389 }
4390
4391 - (NSString *) version {
4392 return Cydia_;
4393 }
4394
4395 - (NSString *) build {
4396 return System_;
4397 }
4398
4399 - (NSString *) coreFoundationVersionNumber {
4400 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4401 }
4402
4403 - (NSString *) device {
4404 return UniqueIdentifier();
4405 }
4406
4407 - (NSString *) firmware {
4408 return [[UIDevice currentDevice] systemVersion];
4409 }
4410
4411 - (NSString *) hostname {
4412 return [[UIDevice currentDevice] name];
4413 }
4414
4415 - (NSString *) idiom {
4416 return (id) Idiom_ ?: [NSNull null];
4417 }
4418
4419 - (NSString *) mcc {
4420 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4421 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4422 return nil;
4423 }
4424
4425 - (NSString *) mnc {
4426 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4427 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4428 return nil;
4429 }
4430
4431 - (NSString *) operator {
4432 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4433 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4434 return nil;
4435 }
4436
4437 - (NSString *) bbsnum {
4438 return (id) BBSNum_ ?: [NSNull null];
4439 }
4440
4441 - (NSString *) ecid {
4442 return (id) ChipID_ ?: [NSNull null];
4443 }
4444
4445 - (NSString *) serial {
4446 return SerialNumber_;
4447 }
4448
4449 - (NSString *) role {
4450 return (id) [NSNull null];
4451 }
4452
4453 - (NSString *) model {
4454 return [NSString stringWithUTF8String:Machine_];
4455 }
4456
4457 + (NSString *) webScriptNameForSelector:(SEL)selector {
4458 if (false);
4459 else if (selector == @selector(addBridgedHost:))
4460 return @"addBridgedHost";
4461 else if (selector == @selector(addInsecureHost:))
4462 return @"addInsecureHost";
4463 else if (selector == @selector(addInternalRedirect::))
4464 return @"addInternalRedirect";
4465 else if (selector == @selector(addPipelinedHost:scheme:))
4466 return @"addPipelinedHost";
4467 else if (selector == @selector(addSource:::))
4468 return @"addSource";
4469 else if (selector == @selector(addTrivialSource:))
4470 return @"addTrivialSource";
4471 else if (selector == @selector(close))
4472 return @"close";
4473 else if (selector == @selector(du:))
4474 return @"du";
4475 else if (selector == @selector(stringWithFormat:arguments:))
4476 return @"format";
4477 else if (selector == @selector(getAllSources))
4478 return @"getAllSources";
4479 else if (selector == @selector(getApplicationInfo:value:))
4480 return @"getApplicationInfoValue";
4481 else if (selector == @selector(getDisplayIdentifiers))
4482 return @"getDisplayIdentifiers";
4483 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4484 return @"getLocalizedNameForDisplayIdentifier";
4485 else if (selector == @selector(getKernelNumber:))
4486 return @"getKernelNumber";
4487 else if (selector == @selector(getKernelString:))
4488 return @"getKernelString";
4489 else if (selector == @selector(getInstalledPackages))
4490 return @"getInstalledPackages";
4491 else if (selector == @selector(getIORegistryEntry::))
4492 return @"getIORegistryEntry";
4493 else if (selector == @selector(getLocaleIdentifier))
4494 return @"getLocaleIdentifier";
4495 else if (selector == @selector(getPreferredLanguages))
4496 return @"getPreferredLanguages";
4497 else if (selector == @selector(getPackageById:))
4498 return @"getPackageById";
4499 else if (selector == @selector(getMetadataKeys))
4500 return @"getMetadataKeys";
4501 else if (selector == @selector(getMetadataValue:))
4502 return @"getMetadataValue";
4503 else if (selector == @selector(getSessionValue:))
4504 return @"getSessionValue";
4505 else if (selector == @selector(installPackages:))
4506 return @"installPackages";
4507 else if (selector == @selector(isReachable:))
4508 return @"isReachable";
4509 else if (selector == @selector(localizedStringForKey:value:table:))
4510 return @"localize";
4511 else if (selector == @selector(popViewController:))
4512 return @"popViewController";
4513 else if (selector == @selector(refreshSources))
4514 return @"refreshSources";
4515 else if (selector == @selector(registerFrame:))
4516 return @"registerFrame";
4517 else if (selector == @selector(removeButton))
4518 return @"removeButton";
4519 else if (selector == @selector(saveConfig))
4520 return @"saveConfig";
4521 else if (selector == @selector(setMetadataValue::))
4522 return @"setMetadataValue";
4523 else if (selector == @selector(setSessionValue::))
4524 return @"setSessionValue";
4525 else if (selector == @selector(substitutePackageNames:))
4526 return @"substitutePackageNames";
4527 else if (selector == @selector(scrollToBottom:))
4528 return @"scrollToBottom";
4529 else if (selector == @selector(setAllowsNavigationAction:))
4530 return @"setAllowsNavigationAction";
4531 else if (selector == @selector(setBadgeValue:))
4532 return @"setBadgeValue";
4533 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4534 return @"setButtonImage";
4535 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4536 return @"setButtonTitle";
4537 else if (selector == @selector(setHidesBackButton:))
4538 return @"setHidesBackButton";
4539 else if (selector == @selector(setHidesNavigationBar:))
4540 return @"setHidesNavigationBar";
4541 else if (selector == @selector(setNavigationBarStyle:))
4542 return @"setNavigationBarStyle";
4543 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4544 return @"setNavigationBarTintColor";
4545 else if (selector == @selector(setPasteboardString:))
4546 return @"setPasteboardString";
4547 else if (selector == @selector(setPasteboardURL:))
4548 return @"setPasteboardURL";
4549 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4550 return @"setScrollAlwaysBounceVertical";
4551 else if (selector == @selector(setScrollIndicatorStyle:))
4552 return @"setScrollIndicatorStyle";
4553 else if (selector == @selector(setToken:))
4554 return @"setToken";
4555 else if (selector == @selector(setViewportWidth:))
4556 return @"setViewportWidth";
4557 else if (selector == @selector(statfs:))
4558 return @"statfs";
4559 else if (selector == @selector(supports:))
4560 return @"supports";
4561 else if (selector == @selector(unload))
4562 return @"unload";
4563 else
4564 return nil;
4565 }
4566
4567 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4568 return [self webScriptNameForSelector:selector] == nil;
4569 }
4570
4571 - (BOOL) supports:(NSString *)feature {
4572 return [feature isEqualToString:@"window.open"];
4573 }
4574
4575 - (void) unload {
4576 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4577 }
4578
4579 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4580 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4581 }
4582
4583 - (void) setScrollIndicatorStyle:(NSString *)style {
4584 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4585 }
4586
4587 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4588 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4589 }
4590
4591 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4592 char path[1024];
4593 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4594 return (id) [NSNull null];
4595 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4596 if (info == nil)
4597 return (id) [NSNull null];
4598 return [info objectForKey:key];
4599 }
4600
4601 - (NSArray *) getDisplayIdentifiers {
4602 NSSet *set([SBSCopyApplicationDisplayIdentifiers() autorelease]);
4603 if (set == nil || ![set isKindOfClass:[NSSet class]])
4604 return [NSArray array];
4605 return [set allObjects];
4606 }
4607
4608 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4609 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4610 }
4611
4612 - (NSNumber *) getKernelNumber:(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 if (size != sizeof(int))
4620 return (id) [NSNull null];
4621
4622 int value;
4623 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4624 return (id) [NSNull null];
4625
4626 return [NSNumber numberWithInt:value];
4627 }
4628
4629 - (NSString *) getKernelString:(NSString *)name {
4630 const char *string([name UTF8String]);
4631
4632 size_t size;
4633 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4634 return (id) [NSNull null];
4635
4636 char value[size + 1];
4637 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4638 return (id) [NSNull null];
4639
4640 // XXX: just in case you request something ludicrous
4641 value[size] = '\0';
4642
4643 return [NSString stringWithCString:value];
4644 }
4645
4646 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4647 NSObject *value(CYIOGetValue([path UTF8String], entry));
4648
4649 if (value != nil)
4650 if ([value isKindOfClass:[NSData class]])
4651 value = CYHex((NSData *) value);
4652
4653 return value;
4654 }
4655
4656 - (NSArray *) getMetadataKeys {
4657 @synchronized (Values_) {
4658 return [Values_ allKeys];
4659 } }
4660
4661 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4662 WebFrame *frame([iframe contentFrame]);
4663 [indirect_ registerFrame:frame];
4664 }
4665
4666 - (id) getMetadataValue:(NSString *)key {
4667 @synchronized (Values_) {
4668 return [Values_ objectForKey:key];
4669 } }
4670
4671 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4672 @synchronized (Values_) {
4673 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4674 [Values_ removeObjectForKey:key];
4675 else
4676 [Values_ setObject:value forKey:key];
4677 } }
4678
4679 - (id) getSessionValue:(NSString *)key {
4680 @synchronized (SessionData_) {
4681 return [SessionData_ objectForKey:key];
4682 } }
4683
4684 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4685 @synchronized (SessionData_) {
4686 if (value == (id) [WebUndefined undefined])
4687 [SessionData_ removeObjectForKey:key];
4688 else
4689 [SessionData_ setObject:value forKey:key];
4690 } }
4691
4692 - (void) addBridgedHost:(NSString *)host {
4693 @synchronized (HostConfig_) {
4694 [BridgedHosts_ addObject:host];
4695 } }
4696
4697 - (void) addInsecureHost:(NSString *)host {
4698 @synchronized (HostConfig_) {
4699 [InsecureHosts_ addObject:host];
4700 } }
4701
4702 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4703 @synchronized (HostConfig_) {
4704 if (scheme != (id) [WebUndefined undefined])
4705 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4706
4707 [PipelinedHosts_ addObject:host];
4708 } }
4709
4710 - (void) popViewController:(NSNumber *)value {
4711 if (value == (id) [WebUndefined undefined])
4712 value = [NSNumber numberWithBool:YES];
4713 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4714 }
4715
4716 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4717 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4718
4719 for (NSString *section in sections)
4720 [array addObject:section];
4721
4722 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4723 @"deb", @"Type",
4724 href, @"URI",
4725 distribution, @"Distribution",
4726 array, @"Sections",
4727 nil] waitUntilDone:NO];
4728 }
4729
4730 - (BOOL) addTrivialSource:(NSString *)href {
4731 href = VerifySource(href);
4732 if (href == nil)
4733 return NO;
4734 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4735 return YES;
4736 }
4737
4738 - (void) refreshSources {
4739 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4740 }
4741
4742 - (void) saveConfig {
4743 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4744 }
4745
4746 - (NSArray *) getAllSources {
4747 return [[Database sharedInstance] sources];
4748 }
4749
4750 - (NSArray *) getInstalledPackages {
4751 Database *database([Database sharedInstance]);
4752 @synchronized (database) {
4753 NSArray *packages([database packages]);
4754 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4755 for (Package *package in packages)
4756 if (![package uninstalled])
4757 [installed addObject:package];
4758 return installed;
4759 } }
4760
4761 - (Package *) getPackageById:(NSString *)id {
4762 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4763 [package parse];
4764 return package;
4765 } else
4766 return (Package *) [NSNull null];
4767 }
4768
4769 - (NSString *) getLocaleIdentifier {
4770 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4771 }
4772
4773 - (NSArray *) getPreferredLanguages {
4774 return Languages_;
4775 }
4776
4777 - (NSArray *) statfs:(NSString *)path {
4778 struct statfs stat;
4779
4780 if (path == nil || statfs([path UTF8String], &stat) == -1)
4781 return nil;
4782
4783 return [NSArray arrayWithObjects:
4784 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4785 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4786 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4787 nil];
4788 }
4789
4790 - (NSNumber *) du:(NSString *)path {
4791 NSNumber *value(nil);
4792
4793 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4794 if (du != NULL) {
4795 char line[1024];
4796 while (fgets(line, sizeof(line), du) != NULL) {
4797 size_t length(strlen(line));
4798 while (length != 0 && line[length - 1] == '\n')
4799 line[--length] = '\0';
4800 if (char *tab = strchr(line, '\t')) {
4801 *tab = '\0';
4802 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4803 }
4804 }
4805 pclose(du);
4806 }
4807
4808 return value;
4809 }
4810
4811 - (void) close {
4812 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4813 }
4814
4815 - (NSNumber *) isReachable:(NSString *)name {
4816 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4817 }
4818
4819 - (void) installPackages:(NSArray *)packages {
4820 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4821 }
4822
4823 - (NSString *) substitutePackageNames:(NSString *)message {
4824 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4825 for (size_t i(0), e([words count]); i != e; ++i) {
4826 NSString *word([words objectAtIndex:i]);
4827 if (Package *package = [[Database sharedInstance] packageWithName:word])
4828 [words replaceObjectAtIndex:i withObject:[package name]];
4829 }
4830
4831 return [words componentsJoinedByString:@" "];
4832 }
4833
4834 - (void) removeButton {
4835 [indirect_ removeButton];
4836 }
4837
4838 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4839 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4840 }
4841
4842 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4843 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4844 }
4845
4846 - (void) setBadgeValue:(id)value {
4847 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4848 }
4849
4850 - (void) setAllowsNavigationAction:(NSString *)value {
4851 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4852 }
4853
4854 - (void) setHidesBackButton:(NSString *)value {
4855 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4856 }
4857
4858 - (void) setHidesNavigationBar:(NSString *)value {
4859 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4860 }
4861
4862 - (void) setNavigationBarStyle:(NSString *)value {
4863 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4864 }
4865
4866 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4867 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4868 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4869 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4870 }
4871
4872 - (void) setPasteboardString:(NSString *)value {
4873 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4874 }
4875
4876 - (void) setPasteboardURL:(NSString *)value {
4877 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4878 }
4879
4880 - (void) setToken:(NSString *)token {
4881 // XXX: the website expects this :/
4882 }
4883
4884 - (void) scrollToBottom:(NSNumber *)animated {
4885 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4886 }
4887
4888 - (void) setViewportWidth:(float)width {
4889 [indirect_ setViewportWidthOnMainThread:width];
4890 }
4891
4892 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4893 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4894 unsigned count([arguments count]);
4895 id values[count];
4896 for (unsigned i(0); i != count; ++i)
4897 values[i] = [arguments objectAtIndex:i];
4898 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4899 }
4900
4901 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4902 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4903 value = nil;
4904 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4905 table = nil;
4906 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4907 }
4908
4909 @end
4910 /* }}} */
4911
4912 @interface NSURL (CydiaSecure)
4913 @end
4914
4915 @implementation NSURL (CydiaSecure)
4916
4917 - (bool) isCydiaSecure {
4918 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4919 return true;
4920
4921 @synchronized (HostConfig_) {
4922 if ([InsecureHosts_ containsObject:[self host]])
4923 return true;
4924 }
4925
4926 return false;
4927 }
4928
4929 @end
4930
4931 /* Cydia Browser Controller {{{ */
4932 @implementation CydiaWebViewController
4933
4934 - (NSURL *) navigationURL {
4935 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4936 }
4937
4938 + (void) _initialize {
4939 [super _initialize];
4940
4941 Diversions_ = [NSMutableSet setWithCapacity:0];
4942 }
4943
4944 + (void) addDiversion:(Diversion *)diversion {
4945 [Diversions_ addObject:diversion];
4946 }
4947
4948 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4949 [super webView:view didClearWindowObject:window forFrame:frame];
4950 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4951 }
4952
4953 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4954 WebDataSource *source([frame dataSource]);
4955 NSURLResponse *response([source response]);
4956 NSURL *url([response URL]);
4957 NSString *scheme([[url scheme] lowercaseString]);
4958
4959 bool bridged(false);
4960
4961 @synchronized (HostConfig_) {
4962 if ([scheme isEqualToString:@"file"])
4963 bridged = true;
4964 else if ([scheme isEqualToString:@"https"])
4965 if ([BridgedHosts_ containsObject:[url host]])
4966 bridged = true;
4967 }
4968
4969 if (bridged)
4970 [window setValue:cydia forKey:@"cydia"];
4971 }
4972
4973 - (void) _setupMail:(MFMailComposeViewController *)controller {
4974 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4975
4976 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4977 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4978 }
4979
4980 - (NSURL *) URLWithURL:(NSURL *)url {
4981 return [Diversion divertURL:url];
4982 }
4983
4984 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4985 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4986 }
4987
4988 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4989 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4990 }
4991
4992 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4993 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4994
4995 NSURL *url([copy URL]);
4996 NSString *href([url absoluteString]);
4997 NSString *host([url host]);
4998
4999 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5000 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5001 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5002 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5003 }
5004
5005 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5006 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5007
5008 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5009 return copy;
5010 }
5011
5012 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5013 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5014 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5015 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5016
5017 bool bridged; @synchronized (HostConfig_) {
5018 bridged = [BridgedHosts_ containsObject:host];
5019 }
5020
5021 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5022 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5023
5024 return copy;
5025 }
5026
5027 - (void) setDelegate:(id)delegate {
5028 [super setDelegate:delegate];
5029 [cydia_ setDelegate:delegate];
5030 }
5031
5032 - (NSString *) applicationNameForUserAgent {
5033 return UserAgent_;
5034 }
5035
5036 - (id) init {
5037 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5038 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5039 } return self;
5040 }
5041
5042 @end
5043
5044 @interface AppCacheController : CydiaWebViewController {
5045 }
5046
5047 @end
5048
5049 @implementation AppCacheController
5050
5051 - (void) didReceiveMemoryWarning {
5052 // XXX: this doesn't work
5053 }
5054
5055 - (bool) retainsNetworkActivityIndicator {
5056 return false;
5057 }
5058
5059 @end
5060 /* }}} */
5061
5062 // CydiaScript {{{
5063 @interface NSObject (CydiaScript)
5064 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5065 @end
5066
5067 @implementation NSObject (CydiaScript)
5068
5069 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5070 return self;
5071 }
5072
5073 @end
5074
5075 @implementation NSArray (CydiaScript)
5076
5077 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5078 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5079 for (size_t i(0), e([self count]); i != e; ++i)
5080 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5081 return object;
5082 }
5083
5084 @end
5085
5086 @implementation NSDictionary (CydiaScript)
5087
5088 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5089 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5090 for (id i in self)
5091 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5092 return object;
5093 }
5094
5095 @end
5096 // }}}
5097
5098 /* Confirmation Controller {{{ */
5099 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5100 if (!iterator.end())
5101 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5102 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5103 continue;
5104 pkgCache::PkgIterator package(dep.TargetPkg());
5105 if (package.end())
5106 continue;
5107 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5108 return true;
5109 }
5110
5111 return false;
5112 }
5113
5114 @protocol ConfirmationControllerDelegate
5115 - (void) cancelAndClear:(bool)clear;
5116 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5117 - (void) queue;
5118 @end
5119
5120 @interface ConfirmationController : CydiaWebViewController {
5121 _transient Database *database_;
5122
5123 _H<UIAlertView> essential_;
5124
5125 _H<NSDictionary> changes_;
5126 _H<NSMutableArray> issues_;
5127 _H<NSDictionary> sizes_;
5128
5129 BOOL substrate_;
5130 }
5131
5132 - (id) initWithDatabase:(Database *)database;
5133
5134 @end
5135
5136 @implementation ConfirmationController
5137
5138 - (void) complete {
5139 if (substrate_)
5140 RestartSubstrate_ = true;
5141 [delegate_ confirmWithNavigationController:[self navigationController]];
5142 }
5143
5144 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5145 NSString *context([alert context]);
5146
5147 if ([context isEqualToString:@"remove"]) {
5148 if (button == [alert cancelButtonIndex])
5149 [self _doContinue];
5150 else if (button == [alert firstOtherButtonIndex]) {
5151 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5152 }
5153
5154 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5155 } else if ([context isEqualToString:@"unable"]) {
5156 [self dismissModalViewControllerAnimated:YES];
5157 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5158 } else {
5159 [super alertView:alert clickedButtonAtIndex:button];
5160 }
5161 }
5162
5163 - (void) _doContinue {
5164 [delegate_ cancelAndClear:NO];
5165 [self dismissModalViewControllerAnimated:YES];
5166 }
5167
5168 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5169 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5170 return nil;
5171 }
5172
5173 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5174 [super webView:view didClearWindowObject:window forFrame:frame];
5175
5176 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5177 (id) changes_, @"changes",
5178 (id) issues_, @"issues",
5179 (id) sizes_, @"sizes",
5180 self, @"queue",
5181 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5182 }
5183
5184 - (id) initWithDatabase:(Database *)database {
5185 if ((self = [super init]) != nil) {
5186 database_ = database;
5187
5188 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5189 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5190 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5191 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5192 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5193
5194 bool remove(false);
5195
5196 pkgCacheFile &cache([database_ cache]);
5197 NSArray *packages([database_ packages]);
5198 pkgDepCache::Policy *policy([database_ policy]);
5199
5200 issues_ = [NSMutableArray arrayWithCapacity:4];
5201
5202 for (Package *package in packages) {
5203 pkgCache::PkgIterator iterator([package iterator]);
5204 NSString *name([package id]);
5205
5206 if ([package broken]) {
5207 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5208
5209 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5210 name, @"package",
5211 reasons, @"reasons",
5212 nil]];
5213
5214 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5215 if (ver.end())
5216 continue;
5217
5218 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5219 pkgCache::DepIterator start;
5220 pkgCache::DepIterator end;
5221 dep.GlobOr(start, end); // ++dep
5222
5223 if (!cache->IsImportantDep(end))
5224 continue;
5225 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5226 continue;
5227
5228 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5229
5230 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5231 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5232 clauses, @"clauses",
5233 nil]];
5234
5235 _forever {
5236 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5237
5238 pkgCache::PkgIterator target(start.TargetPkg());
5239 if (target->ProvidesList != 0)
5240 reason = @"missing";
5241 else {
5242 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5243 if (!ver.end()) {
5244 reason = @"installed";
5245 installed = [NSString stringWithUTF8String:ver.VerStr()];
5246 } else if (!cache[target].CandidateVerIter(cache).end())
5247 reason = @"uninstalled";
5248 else if (target->ProvidesList == 0)
5249 reason = @"uninstallable";
5250 else
5251 reason = @"virtual";
5252 }
5253
5254 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5255 [NSString stringWithUTF8String:start.CompType()], @"operator",
5256 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5257 nil]);
5258
5259 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5260 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5261 version, @"version",
5262 reason, @"reason",
5263 installed, @"installed",
5264 nil]];
5265
5266 // yes, seriously. (wtf?)
5267 if (start == end)
5268 break;
5269 ++start;
5270 }
5271 }
5272 }
5273
5274 pkgDepCache::StateCache &state(cache[iterator]);
5275
5276 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5277
5278 if (state.NewInstall())
5279 [installs addObject:name];
5280 // XXX: else if (state.Install())
5281 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5282 [reinstalls addObject:name];
5283 // XXX: move before previous if
5284 else if (state.Upgrade())
5285 [upgrades addObject:name];
5286 else if (state.Downgrade())
5287 [downgrades addObject:name];
5288 else if (!state.Delete())
5289 // XXX: _assert(state.Keep());
5290 continue;
5291 else if (special_r(name))
5292 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5293 [NSNull null], @"package",
5294 [NSArray arrayWithObjects:
5295 [NSDictionary dictionaryWithObjectsAndKeys:
5296 @"Conflicts", @"relationship",
5297 [NSArray arrayWithObjects:
5298 [NSDictionary dictionaryWithObjectsAndKeys:
5299 name, @"package",
5300 [NSNull null], @"version",
5301 @"installed", @"reason",
5302 nil],
5303 nil], @"clauses",
5304 nil],
5305 nil], @"reasons",
5306 nil]];
5307 else {
5308 if ([package essential])
5309 remove = true;
5310 [removes addObject:name];
5311 }
5312
5313 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5314 substrate_ |= DepSubstrate(iterator.CurrentVer());
5315 }
5316
5317 if (!remove)
5318 essential_ = nil;
5319 else if (Advanced_) {
5320 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5321
5322 essential_ = [[[UIAlertView alloc]
5323 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5324 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5325 delegate:self
5326 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5327 otherButtonTitles:
5328 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5329 nil
5330 ] autorelease];
5331
5332 [essential_ setContext:@"remove"];
5333 [essential_ setNumberOfRows:2];
5334 } else {
5335 essential_ = [[[UIAlertView alloc]
5336 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5337 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5338 delegate:self
5339 cancelButtonTitle:UCLocalize("OKAY")
5340 otherButtonTitles:nil
5341 ] autorelease];
5342
5343 [essential_ setContext:@"unable"];
5344 }
5345
5346 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5347 installs, @"installs",
5348 reinstalls, @"reinstalls",
5349 upgrades, @"upgrades",
5350 downgrades, @"downgrades",
5351 removes, @"removes",
5352 nil];
5353
5354 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5355 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5356 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5357 nil];
5358
5359 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5360 } return self;
5361 }
5362
5363 - (UIBarButtonItem *) leftButton {
5364 return [[[UIBarButtonItem alloc]
5365 initWithTitle:UCLocalize("CANCEL")
5366 style:UIBarButtonItemStylePlain
5367 target:self
5368 action:@selector(cancelButtonClicked)
5369 ] autorelease];
5370 }
5371
5372 #if !AlwaysReload
5373 - (void) applyRightButton {
5374 if ([issues_ count] == 0 && ![self isLoading])
5375 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5376 initWithTitle:UCLocalize("CONFIRM")
5377 style:UIBarButtonItemStyleDone
5378 target:self
5379 action:@selector(confirmButtonClicked)
5380 ] autorelease]];
5381 else
5382 [[self navigationItem] setRightBarButtonItem:nil];
5383 }
5384 #endif
5385
5386 - (void) cancelButtonClicked {
5387 [delegate_ cancelAndClear:YES];
5388 [self dismissModalViewControllerAnimated:YES];
5389 }
5390
5391 #if !AlwaysReload
5392 - (void) confirmButtonClicked {
5393 if (essential_ != nil)
5394 [essential_ show];
5395 else
5396 [self complete];
5397 }
5398 #endif
5399
5400 @end
5401 /* }}} */
5402
5403 /* Progress Data {{{ */
5404 @interface CydiaProgressData : NSObject {
5405 _transient id delegate_;
5406
5407 bool running_;
5408 float percent_;
5409
5410 float current_;
5411 float total_;
5412 float speed_;
5413
5414 _H<NSMutableArray> events_;
5415 _H<NSString> title_;
5416
5417 _H<NSString> status_;
5418 _H<NSString> finish_;
5419 }
5420
5421 @end
5422
5423 @implementation CydiaProgressData
5424
5425 + (NSArray *) _attributeKeys {
5426 return [NSArray arrayWithObjects:
5427 @"current",
5428 @"events",
5429 @"finish",
5430 @"percent",
5431 @"running",
5432 @"speed",
5433 @"title",
5434 @"total",
5435 nil];
5436 }
5437
5438 - (NSArray *) attributeKeys {
5439 return [[self class] _attributeKeys];
5440 }
5441
5442 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5443 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5444 }
5445
5446 - (id) init {
5447 if ((self = [super init]) != nil) {
5448 events_ = [NSMutableArray arrayWithCapacity:32];
5449 } return self;
5450 }
5451
5452 - (id) delegate {
5453 return delegate_;
5454 }
5455
5456 - (void) setDelegate:(id)delegate {
5457 delegate_ = delegate;
5458 }
5459
5460 - (void) setPercent:(float)value {
5461 percent_ = value;
5462 }
5463
5464 - (NSNumber *) percent {
5465 return [NSNumber numberWithFloat:percent_];
5466 }
5467
5468 - (void) setCurrent:(float)value {
5469 current_ = value;
5470 }
5471
5472 - (NSNumber *) current {
5473 return [NSNumber numberWithFloat:current_];
5474 }
5475
5476 - (void) setTotal:(float)value {
5477 total_ = value;
5478 }
5479
5480 - (NSNumber *) total {
5481 return [NSNumber numberWithFloat:total_];
5482 }
5483
5484 - (void) setSpeed:(float)value {
5485 speed_ = value;
5486 }
5487
5488 - (NSNumber *) speed {
5489 return [NSNumber numberWithFloat:speed_];
5490 }
5491
5492 - (NSArray *) events {
5493 return events_;
5494 }
5495
5496 - (void) removeAllEvents {
5497 [events_ removeAllObjects];
5498 }
5499
5500 - (void) addEvent:(CydiaProgressEvent *)event {
5501 [events_ addObject:event];
5502 }
5503
5504 - (void) setTitle:(NSString *)text {
5505 title_ = text;
5506 }
5507
5508 - (NSString *) title {
5509 return title_;
5510 }
5511
5512 - (void) setFinish:(NSString *)text {
5513 finish_ = text;
5514 }
5515
5516 - (NSString *) finish {
5517 return (id) finish_ ?: [NSNull null];
5518 }
5519
5520 - (void) setRunning:(bool)running {
5521 running_ = running;
5522 }
5523
5524 - (NSNumber *) running {
5525 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5526 }
5527
5528 @end
5529 /* }}} */
5530 /* Progress Controller {{{ */
5531 @interface ProgressController : CydiaWebViewController <
5532 ProgressDelegate
5533 > {
5534 _transient Database *database_;
5535 _H<CydiaProgressData, 1> progress_;
5536 unsigned cancel_;
5537 }
5538
5539 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5540
5541 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5542
5543 - (void) setTitle:(NSString *)title;
5544 - (void) setCancellable:(bool)cancellable;
5545
5546 @end
5547
5548 @implementation ProgressController
5549
5550 - (void) dealloc {
5551 [database_ setProgressDelegate:nil];
5552 [super dealloc];
5553 }
5554
5555 - (UIBarButtonItem *) leftButton {
5556 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5557 initWithTitle:UCLocalize("CANCEL")
5558 style:UIBarButtonItemStylePlain
5559 target:self
5560 action:@selector(cancel)
5561 ] autorelease] : nil;
5562 }
5563
5564 - (void) updateCancel {
5565 [super applyLeftButton];
5566 }
5567
5568 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5569 if ((self = [super init]) != nil) {
5570 database_ = database;
5571 delegate_ = delegate;
5572
5573 [database_ setProgressDelegate:self];
5574
5575 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5576 [progress_ setDelegate:self];
5577
5578 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5579
5580 [scroller_ setBackgroundColor:[UIColor blackColor]];
5581
5582 [[self navigationItem] setHidesBackButton:YES];
5583
5584 [self updateCancel];
5585 } return self;
5586 }
5587
5588 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5589 [super webView:view didClearWindowObject:window forFrame:frame];
5590 [window setValue:progress_ forKey:@"cydiaProgress"];
5591 }
5592
5593 - (void) updateProgress {
5594 [self dispatchEvent:@"CydiaProgressUpdate"];
5595 }
5596
5597 - (void) viewWillAppear:(BOOL)animated {
5598 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5599 [super viewWillAppear:animated];
5600 }
5601
5602 - (void) close {
5603 UpdateExternalStatus(0);
5604
5605 if (Finish_ > 1)
5606 [delegate_ saveState];
5607
5608 switch (Finish_) {
5609 case 0:
5610 [delegate_ returnToCydia];
5611 break;
5612
5613 case 1:
5614 [delegate_ terminateWithSuccess];
5615 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5616 [delegate_ suspendWithAnimation:YES];
5617 else
5618 [delegate_ suspend];*/
5619 break;
5620
5621 case 2:
5622 _trace();
5623 goto reload;
5624
5625 case 3:
5626 _trace();
5627 goto reload;
5628
5629 reload: {
5630 UIProgressHUD *hud([delegate_ addProgressHUD]);
5631 [hud setText:UCLocalize("LOADING")];
5632 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5633 return;
5634 }
5635
5636 case 4:
5637 _trace();
5638 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5639 SBReboot(SBSSpringBoardServerPort());
5640 else
5641 reboot2(RB_AUTOBOOT);
5642 break;
5643 }
5644
5645 [super close];
5646 }
5647
5648 - (void) setTitle:(NSString *)title {
5649 [progress_ setTitle:title];
5650 [self updateProgress];
5651 }
5652
5653 - (UIBarButtonItem *) rightButton {
5654 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5655 initWithTitle:UCLocalize("CLOSE")
5656 style:UIBarButtonItemStylePlain
5657 target:self
5658 action:@selector(close)
5659 ] autorelease];
5660 }
5661
5662 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5663 UpdateExternalStatus(1);
5664
5665 [progress_ setRunning:true];
5666 [self setTitle:title];
5667 // implicit updateProgress
5668
5669 SHA1SumValue notifyconf; {
5670 FileFd file;
5671 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5672 _error->Discard();
5673 else {
5674 MMap mmap(file, MMap::ReadOnly);
5675 SHA1Summation sha1;
5676 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5677 notifyconf = sha1.Result();
5678 }
5679 }
5680
5681 SHA1SumValue springlist; {
5682 FileFd file;
5683 if (!file.Open(SpringBoard_, 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 springlist = sha1.Result();
5690 }
5691 }
5692
5693 if (invocation != nil) {
5694 [invocation yieldToSelector:@selector(invoke)];
5695 [self setTitle:@"COMPLETE"];
5696 }
5697
5698 if (Finish_ < 4) {
5699 FileFd file;
5700 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5701 _error->Discard();
5702 else {
5703 MMap mmap(file, MMap::ReadOnly);
5704 SHA1Summation sha1;
5705 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5706 if (!(notifyconf == sha1.Result()))
5707 Finish_ = 4;
5708 }
5709 }
5710
5711 if (Finish_ < 3) {
5712 FileFd file;
5713 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5714 _error->Discard();
5715 else {
5716 MMap mmap(file, MMap::ReadOnly);
5717 SHA1Summation sha1;
5718 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5719 if (!(springlist == sha1.Result()))
5720 Finish_ = 3;
5721 }
5722 }
5723
5724 if (Finish_ < 2) {
5725 if (RestartSubstrate_)
5726 Finish_ = 2;
5727 }
5728
5729 RestartSubstrate_ = false;
5730
5731 switch (Finish_) {
5732 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5733 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5734 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5735 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5736 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5737 }
5738
5739 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5740
5741 [progress_ setRunning:false];
5742 [self updateProgress];
5743
5744 [self applyRightButton];
5745 }
5746
5747 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5748 [progress_ addEvent:event];
5749 [self updateProgress];
5750 }
5751
5752 - (bool) isProgressCancelled {
5753 return cancel_ == 2;
5754 }
5755
5756 - (void) cancel {
5757 cancel_ = 2;
5758 [self updateCancel];
5759 }
5760
5761 - (void) setCancellable:(bool)cancellable {
5762 unsigned cancel(cancel_);
5763
5764 if (!cancellable)
5765 cancel_ = 0;
5766 else if (cancel_ == 0)
5767 cancel_ = 1;
5768
5769 if (cancel != cancel_)
5770 [self updateCancel];
5771 }
5772
5773 - (void) setProgressCancellable:(NSNumber *)cancellable {
5774 [self setCancellable:[cancellable boolValue]];
5775 }
5776
5777 - (void) setProgressPercent:(NSNumber *)percent {
5778 [progress_ setPercent:[percent floatValue]];
5779 [self updateProgress];
5780 }
5781
5782 - (void) setProgressStatus:(NSDictionary *)status {
5783 if (status == nil) {
5784 [progress_ setCurrent:0];
5785 [progress_ setTotal:0];
5786 [progress_ setSpeed:0];
5787 } else {
5788 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5789
5790 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5791 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5792 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5793 }
5794
5795 [self updateProgress];
5796 }
5797
5798 @end
5799 /* }}} */
5800
5801 /* Package Cell {{{ */
5802 @interface PackageCell : CyteTableViewCell <
5803 CyteTableViewCellDelegate
5804 > {
5805 _H<UIImage> icon_;
5806 _H<NSString> name_;
5807 _H<NSString> description_;
5808 bool commercial_;
5809 _H<NSString> source_;
5810 _H<UIImage> badge_;
5811 _H<UIImage> placard_;
5812 bool summarized_;
5813 }
5814
5815 - (PackageCell *) init;
5816 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5817
5818 - (void) drawContentRect:(CGRect)rect;
5819
5820 @end
5821
5822 @implementation PackageCell
5823
5824 - (PackageCell *) init {
5825 CGRect frame(CGRectMake(0, 0, 320, 74));
5826 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5827 UIView *content([self contentView]);
5828 CGRect bounds([content bounds]);
5829
5830 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5831 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5832 [content addSubview:content_];
5833
5834 [content_ setDelegate:self];
5835 [content_ setOpaque:YES];
5836 } return self;
5837 }
5838
5839 - (NSString *) accessibilityLabel {
5840 return name_;
5841 }
5842
5843 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5844 summarized_ = summary;
5845
5846 icon_ = nil;
5847 name_ = nil;
5848 description_ = nil;
5849 source_ = nil;
5850 badge_ = nil;
5851 placard_ = nil;
5852
5853 if (package == nil)
5854 [content_ setBackgroundColor:[UIColor whiteColor]];
5855 else {
5856 [package parse];
5857
5858 Source *source = [package source];
5859
5860 icon_ = [package icon];
5861
5862 if (NSString *name = [package name])
5863 name_ = [NSString stringWithString:name];
5864
5865 if (NSString *description = [package shortDescription])
5866 description_ = [NSString stringWithString:description];
5867
5868 commercial_ = [package isCommercial];
5869
5870 NSString *label = nil;
5871 bool trusted = false;
5872
5873 if (source != nil) {
5874 label = [source label];
5875 trusted = [source trusted];
5876 } else if ([[package id] isEqualToString:@"firmware"])
5877 label = UCLocalize("APPLE");
5878 else
5879 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5880
5881 NSString *from(label);
5882
5883 NSString *section = [package simpleSection];
5884 if (section != nil && ![section isEqualToString:label]) {
5885 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5886 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5887 }
5888
5889 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5890
5891 if (NSString *purpose = [package primaryPurpose])
5892 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5893
5894 UIColor *color;
5895 NSString *placard;
5896
5897 if (NSString *mode = [package mode]) {
5898 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5899 color = RemovingColor_;
5900 placard = @"removing";
5901 } else {
5902 color = InstallingColor_;
5903 placard = @"installing";
5904 }
5905 } else {
5906 color = [UIColor whiteColor];
5907
5908 if ([package installed] != nil)
5909 placard = @"installed";
5910 else
5911 placard = nil;
5912 }
5913
5914 [content_ setBackgroundColor:color];
5915
5916 if (placard != nil)
5917 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5918 }
5919
5920 [self setNeedsDisplay];
5921 [content_ setNeedsDisplay];
5922 }
5923
5924 - (void) drawSummaryContentRect:(CGRect)rect {
5925 bool highlighted(highlighted_);
5926 float width([self bounds].size.width);
5927
5928 if (icon_ != nil) {
5929 CGRect rect;
5930 rect.size = [(UIImage *) icon_ size];
5931
5932 while (rect.size.width > 16 || rect.size.height > 16) {
5933 rect.size.width /= 2;
5934 rect.size.height /= 2;
5935 }
5936
5937 rect.origin.x = 19 - rect.size.width / 2;
5938 rect.origin.y = 19 - rect.size.height / 2;
5939
5940 [icon_ drawInRect:Retina(rect)];
5941 }
5942
5943 if (badge_ != nil) {
5944 CGRect rect;
5945 rect.size = [(UIImage *) badge_ size];
5946
5947 rect.size.width /= 4;
5948 rect.size.height /= 4;
5949
5950 rect.origin.x = 25 - rect.size.width / 2;
5951 rect.origin.y = 25 - rect.size.height / 2;
5952
5953 [badge_ drawInRect:Retina(rect)];
5954 }
5955
5956 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5957 UISetColor(White_);
5958
5959 if (!highlighted)
5960 UISetColor(commercial_ ? Purple_ : Black_);
5961 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5962
5963 if (placard_ != nil)
5964 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5965 }
5966
5967 - (void) drawNormalContentRect:(CGRect)rect {
5968 bool highlighted(highlighted_);
5969 float width([self bounds].size.width);
5970
5971 if (icon_ != nil) {
5972 CGRect rect;
5973 rect.size = [(UIImage *) icon_ size];
5974
5975 while (rect.size.width > 32 || rect.size.height > 32) {
5976 rect.size.width /= 2;
5977 rect.size.height /= 2;
5978 }
5979
5980 rect.origin.x = 25 - rect.size.width / 2;
5981 rect.origin.y = 25 - rect.size.height / 2;
5982
5983 [icon_ drawInRect:Retina(rect)];
5984 }
5985
5986 if (badge_ != nil) {
5987 CGRect rect;
5988 rect.size = [(UIImage *) badge_ size];
5989
5990 rect.size.width /= 2;
5991 rect.size.height /= 2;
5992
5993 rect.origin.x = 36 - rect.size.width / 2;
5994 rect.origin.y = 36 - rect.size.height / 2;
5995
5996 [badge_ drawInRect:Retina(rect)];
5997 }
5998
5999 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6000 UISetColor(White_);
6001
6002 if (!highlighted)
6003 UISetColor(commercial_ ? Purple_ : Black_);
6004 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6005 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6006
6007 if (!highlighted)
6008 UISetColor(commercial_ ? Purplish_ : Gray_);
6009 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6010
6011 if (placard_ != nil)
6012 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6013 }
6014
6015 - (void) drawContentRect:(CGRect)rect {
6016 if (summarized_)
6017 [self drawSummaryContentRect:rect];
6018 else
6019 [self drawNormalContentRect:rect];
6020 }
6021
6022 @end
6023 /* }}} */
6024 /* Section Cell {{{ */
6025 @interface SectionCell : CyteTableViewCell <
6026 CyteTableViewCellDelegate
6027 > {
6028 _H<NSString> basic_;
6029 _H<NSString> section_;
6030 _H<NSString> name_;
6031 _H<NSString> count_;
6032 _H<UIImage> icon_;
6033 _H<UISwitch> switch_;
6034 BOOL editing_;
6035 }
6036
6037 - (void) setSection:(Section *)section editing:(BOOL)editing;
6038
6039 @end
6040
6041 @implementation SectionCell
6042
6043 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6044 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6045 icon_ = [UIImage imageNamed:@"folder.png"];
6046 // XXX: this initial frame is wrong, but is fixed later
6047 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6048 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6049
6050 UIView *content([self contentView]);
6051 CGRect bounds([content bounds]);
6052
6053 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6054 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6055 [content addSubview:content_];
6056 [content_ setBackgroundColor:[UIColor whiteColor]];
6057
6058 [content_ setDelegate:self];
6059 } return self;
6060 }
6061
6062 - (void) onSwitch:(id)sender {
6063 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6064 if (metadata == nil) {
6065 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6066 [Sections_ setObject:metadata forKey:basic_];
6067 }
6068
6069 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6070 }
6071
6072 - (void) setSection:(Section *)section editing:(BOOL)editing {
6073 if (editing != editing_) {
6074 if (editing_)
6075 [switch_ removeFromSuperview];
6076 else
6077 [self addSubview:switch_];
6078 editing_ = editing;
6079 }
6080
6081 basic_ = nil;
6082 section_ = nil;
6083 name_ = nil;
6084 count_ = nil;
6085
6086 if (section == nil) {
6087 name_ = UCLocalize("ALL_PACKAGES");
6088 count_ = nil;
6089 } else {
6090 basic_ = [section name];
6091 section_ = [section localized];
6092
6093 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6094 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6095
6096 if (editing_)
6097 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6098 }
6099
6100 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6101 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6102
6103 [content_ setNeedsDisplay];
6104 }
6105
6106 - (void) setFrame:(CGRect)frame {
6107 [super setFrame:frame];
6108
6109 CGRect rect([switch_ frame]);
6110 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6111 }
6112
6113 - (NSString *) accessibilityLabel {
6114 return name_;
6115 }
6116
6117 - (void) drawContentRect:(CGRect)rect {
6118 bool highlighted(highlighted_ && !editing_);
6119
6120 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6121
6122 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6123 UISetColor(White_);
6124
6125 float width(rect.size.width);
6126 if (editing_)
6127 width -= 9 + [switch_ frame].size.width;
6128
6129 if (!highlighted)
6130 UISetColor(Black_);
6131 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6132
6133 CGSize size = [count_ sizeWithFont:Font14_];
6134
6135 UISetColor(Folder_);
6136 if (count_ != nil)
6137 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6138 }
6139
6140 @end
6141 /* }}} */
6142
6143 /* File Table {{{ */
6144 @interface FileTable : CyteViewController <
6145 UITableViewDataSource,
6146 UITableViewDelegate
6147 > {
6148 _transient Database *database_;
6149 _H<Package> package_;
6150 _H<NSString> name_;
6151 _H<NSMutableArray> files_;
6152 _H<UITableView, 2> list_;
6153 }
6154
6155 - (id) initWithDatabase:(Database *)database;
6156 - (void) setPackage:(Package *)package;
6157
6158 @end
6159
6160 @implementation FileTable
6161
6162 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6163 return files_ == nil ? 0 : [files_ count];
6164 }
6165
6166 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6167 return 24.0f;
6168 }*/
6169
6170 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6171 static NSString *reuseIdentifier = @"Cell";
6172
6173 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6174 if (cell == nil) {
6175 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6176 [cell setFont:[UIFont systemFontOfSize:16]];
6177 }
6178 [cell setText:[files_ objectAtIndex:indexPath.row]];
6179 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6180
6181 return cell;
6182 }
6183
6184 - (NSURL *) navigationURL {
6185 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6186 }
6187
6188 - (void) loadView {
6189 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6190 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6191 [list_ setRowHeight:24.0f];
6192 [(UITableView *) list_ setDataSource:self];
6193 [list_ setDelegate:self];
6194 [self setView:list_];
6195 }
6196
6197 - (void) viewDidLoad {
6198 [super viewDidLoad];
6199
6200 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6201 }
6202
6203 - (void) releaseSubviews {
6204 list_ = nil;
6205
6206 package_ = nil;
6207 files_ = nil;
6208
6209 [super releaseSubviews];
6210 }
6211
6212 - (id) initWithDatabase:(Database *)database {
6213 if ((self = [super init]) != nil) {
6214 database_ = database;
6215 } return self;
6216 }
6217
6218 - (void) setPackage:(Package *)package {
6219 package_ = nil;
6220 name_ = nil;
6221
6222 files_ = [NSMutableArray arrayWithCapacity:32];
6223
6224 if (package != nil) {
6225 package_ = package;
6226 name_ = [package id];
6227
6228 if (NSArray *files = [package files])
6229 [files_ addObjectsFromArray:files];
6230
6231 if ([files_ count] != 0) {
6232 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6233 [files_ removeObjectAtIndex:0];
6234 [files_ sortUsingSelector:@selector(compareByPath:)];
6235
6236 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6237 [stack addObject:@"/"];
6238
6239 for (int i(0), e([files_ count]); i != e; ++i) {
6240 NSString *file = [files_ objectAtIndex:i];
6241 while (![file hasPrefix:[stack lastObject]])
6242 [stack removeLastObject];
6243 NSString *directory = [stack lastObject];
6244 [stack addObject:[file stringByAppendingString:@"/"]];
6245 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6246 ([stack count] - 2) * 3, "",
6247 [file substringFromIndex:[directory length]]
6248 ]];
6249 }
6250 }
6251 }
6252
6253 [list_ reloadData];
6254 }
6255
6256 - (void) reloadData {
6257 [super reloadData];
6258
6259 [self setPackage:[database_ packageWithName:name_]];
6260 }
6261
6262 @end
6263 /* }}} */
6264 /* Package Controller {{{ */
6265 @interface CYPackageController : CydiaWebViewController <
6266 UIActionSheetDelegate
6267 > {
6268 _transient Database *database_;
6269 _H<Package> package_;
6270 _H<NSString> name_;
6271 bool commercial_;
6272 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6273 _H<UIActionSheet> sheet_;
6274 _H<UIBarButtonItem> button_;
6275 _H<NSArray> versions_;
6276 }
6277
6278 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6279
6280 @end
6281
6282 @implementation CYPackageController
6283
6284 - (NSURL *) navigationURL {
6285 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6286 }
6287
6288 - (void) _clickButtonWithPackage:(Package *)package {
6289 [delegate_ installPackage:package];
6290 }
6291
6292 - (void) _clickButtonWithName:(NSString *)name {
6293 if ([name isEqualToString:@"CLEAR"])
6294 return [delegate_ clearPackage:package_];
6295 else if ([name isEqualToString:@"REMOVE"])
6296 return [delegate_ removePackage:package_];
6297 else if ([name isEqualToString:@"DOWNGRADE"]) {
6298 sheet_ = [[[UIActionSheet alloc]
6299 initWithTitle:nil
6300 delegate:self
6301 cancelButtonTitle:nil
6302 destructiveButtonTitle:nil
6303 otherButtonTitles:nil
6304 ] autorelease];
6305
6306 for (Package *version in (id) versions_)
6307 [sheet_ addButtonWithTitle:[version latest]];
6308 [sheet_ setContext:@"version"];
6309
6310 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6311 return;
6312 }
6313
6314 else if ([name isEqualToString:@"INSTALL"]);
6315 else if ([name isEqualToString:@"REINSTALL"]);
6316 else if ([name isEqualToString:@"UPGRADE"]);
6317 else _assert(false);
6318
6319 [delegate_ installPackage:package_];
6320 }
6321
6322 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6323 NSString *context([sheet context]);
6324 if (sheet_ == sheet)
6325 sheet_ = nil;
6326
6327 if ([context isEqualToString:@"modify"]) {
6328 if (button != [sheet cancelButtonIndex]) {
6329 if (IsWildcat_)
6330 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6331 else
6332 [self _clickButtonWithName:buttons_[button].first];
6333 }
6334
6335 [sheet dismissWithClickedButtonIndex:button animated:YES];
6336 } else if ([context isEqualToString:@"version"]) {
6337 if (button != [sheet cancelButtonIndex]) {
6338 Package *version([versions_ objectAtIndex:button]);
6339 if (IsWildcat_)
6340 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6341 else
6342 [self _clickButtonWithPackage:version];
6343 }
6344
6345 [sheet dismissWithClickedButtonIndex:button animated:YES];
6346 }
6347 }
6348
6349 - (bool) _allowJavaScriptPanel {
6350 return commercial_;
6351 }
6352
6353 #if !AlwaysReload
6354 - (void) _customButtonClicked {
6355 size_t count(buttons_.size());
6356 if (count == 0)
6357 return;
6358
6359 if (count == 1)
6360 [self _clickButtonWithName:buttons_[0].first];
6361 else {
6362 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6363 for (const auto &button : buttons_)
6364 [buttons addObject:button.second];
6365
6366 sheet_ = [[[UIActionSheet alloc]
6367 initWithTitle:nil
6368 delegate:self
6369 cancelButtonTitle:nil
6370 destructiveButtonTitle:nil
6371 otherButtonTitles:nil
6372 ] autorelease];
6373
6374 for (NSString *button in buttons)
6375 [sheet_ addButtonWithTitle:button];
6376 [sheet_ setContext:@"modify"];
6377
6378 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6379 }
6380 }
6381
6382 - (void) reloadButtonClicked {
6383 if (commercial_ && function_ == nil && [package_ uninstalled])
6384 return;
6385 [self customButtonClicked];
6386 }
6387
6388 - (void) applyLoadingTitle {
6389 // Don't show "Loading" as the title. Ever.
6390 }
6391
6392 - (UIBarButtonItem *) rightButton {
6393 return button_;
6394 }
6395 #endif
6396
6397 - (void) setPageColor:(UIColor *)color {
6398 return [super setPageColor:nil];
6399 }
6400
6401 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6402 if ((self = [super init]) != nil) {
6403 database_ = database;
6404 name_ = name == nil ? @"" : [NSString stringWithString:name];
6405 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6406 } return self;
6407 }
6408
6409 - (void) reloadData {
6410 [super reloadData];
6411
6412 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6413 sheet_ = nil;
6414
6415 package_ = [database_ packageWithName:name_];
6416 versions_ = [package_ downgrades];
6417
6418 buttons_.clear();
6419
6420 if (package_ != nil) {
6421 [(Package *) package_ parse];
6422
6423 commercial_ = [package_ isCommercial];
6424
6425 if ([package_ mode] != nil)
6426 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6427 if ([package_ source] == nil);
6428 else if ([package_ upgradableAndEssential:NO])
6429 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6430 else if ([package_ uninstalled])
6431 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6432 else
6433 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6434 if (![package_ uninstalled])
6435 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6436 if ([versions_ count] != 0)
6437 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6438 }
6439
6440 NSString *title;
6441 switch (buttons_.size()) {
6442 case 0: title = nil; break;
6443 case 1: title = buttons_[0].second; break;
6444 default: title = UCLocalize("MODIFY"); break;
6445 }
6446
6447 button_ = [[[UIBarButtonItem alloc]
6448 initWithTitle:title
6449 style:UIBarButtonItemStylePlain
6450 target:self
6451 action:@selector(customButtonClicked)
6452 ] autorelease];
6453 }
6454
6455 - (bool) isLoading {
6456 return commercial_ ? [super isLoading] : false;
6457 }
6458
6459 @end
6460 /* }}} */
6461
6462 /* Package List Controller {{{ */
6463 @interface PackageListController : CyteViewController <
6464 UITableViewDataSource,
6465 UITableViewDelegate
6466 > {
6467 _transient Database *database_;
6468 unsigned era_;
6469 _H<NSArray> packages_;
6470 _H<NSArray> sections_;
6471 _H<UITableView, 2> list_;
6472
6473 _H<NSArray> thumbs_;
6474 std::vector<NSInteger> offset_;
6475
6476 _H<NSString> title_;
6477 unsigned reloading_;
6478 }
6479
6480 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6481 - (void) setDelegate:(id)delegate;
6482 - (void) resetCursor;
6483 - (void) clearData;
6484
6485 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6486
6487 @end
6488
6489 @implementation PackageListController
6490
6491 - (NSURL *) referrerURL {
6492 return [self navigationURL];
6493 }
6494
6495 - (bool) isSummarized {
6496 return false;
6497 }
6498
6499 - (bool) showsSections {
6500 return true;
6501 }
6502
6503 - (void) deselectWithAnimation:(BOOL)animated {
6504 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6505 }
6506
6507 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6508 CGRect base = [[self view] bounds];
6509 base.size.height -= bounds.size.height;
6510 base.origin = [list_ frame].origin;
6511
6512 [UIView beginAnimations:nil context:NULL];
6513 [UIView setAnimationBeginsFromCurrentState:YES];
6514 [UIView setAnimationCurve:curve];
6515 [UIView setAnimationDuration:duration];
6516 [list_ setFrame:base];
6517 [UIView commitAnimations];
6518 }
6519
6520 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6521 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6522 }
6523
6524 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6525 [self resizeForKeyboardBounds:bounds duration:0];
6526 }
6527
6528 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6529 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6530 *curve = UIViewAnimationCurveEaseInOut;
6531 else
6532 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6533
6534 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6535 *duration = 0.3;
6536 else
6537 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6538 }
6539
6540 - (void) keyboardWillShow:(NSNotification *)notification {
6541 CGRect bounds;
6542 CGPoint center;
6543 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6544 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6545
6546 NSTimeInterval duration;
6547 UIViewAnimationCurve curve;
6548 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6549
6550 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6551 UIViewController *base = self;
6552 while ([base parentOrPresentingViewController] != nil)
6553 base = [base parentOrPresentingViewController];
6554 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6555 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6556
6557 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6558 intersection.size.height += CYStatusBarHeight();
6559
6560 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6561 }
6562
6563 - (void) keyboardWillHide:(NSNotification *)notification {
6564 NSTimeInterval duration;
6565 UIViewAnimationCurve curve;
6566 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6567
6568 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6569 }
6570
6571 - (void) viewWillAppear:(BOOL)animated {
6572 [super viewWillAppear:animated];
6573
6574 [self resizeForKeyboardBounds:CGRectZero];
6575 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6576 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6577 }
6578
6579 - (void) viewWillDisappear:(BOOL)animated {
6580 [super viewWillDisappear:animated];
6581
6582 [self resizeForKeyboardBounds:CGRectZero];
6583 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6584 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6585 }
6586
6587 - (void) viewDidAppear:(BOOL)animated {
6588 [super viewDidAppear:animated];
6589 [self deselectWithAnimation:animated];
6590 }
6591
6592 - (void) didSelectPackage:(Package *)package {
6593 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6594 [view setDelegate:delegate_];
6595 [[self navigationController] pushViewController:view animated:YES];
6596 }
6597
6598 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6599 NSInteger count([sections_ count]);
6600 return count == 0 ? 1 : count;
6601 }
6602
6603 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6604 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6605 return nil;
6606 return [[sections_ objectAtIndex:section] name];
6607 }
6608
6609 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6610 if ([sections_ count] == 0)
6611 return 0;
6612 return [[sections_ objectAtIndex:section] count];
6613 }
6614
6615 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6616 @synchronized (database_) {
6617 if ([database_ era] != era_)
6618 return nil;
6619
6620 Section *section([sections_ objectAtIndex:[path section]]);
6621 NSInteger row([path row]);
6622 Package *package([packages_ objectAtIndex:([section row] + row)]);
6623 return [[package retain] autorelease];
6624 } }
6625
6626 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6627 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6628 if (cell == nil)
6629 cell = [[[PackageCell alloc] init] autorelease];
6630
6631 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6632 [cell setPackage:package asSummary:[self isSummarized]];
6633 return cell;
6634 }
6635
6636 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6637 Package *package([self packageAtIndexPath:path]);
6638 package = [database_ packageWithName:[package id]];
6639 [self didSelectPackage:package];
6640 }
6641
6642 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6643 return thumbs_;
6644 }
6645
6646 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6647 return offset_[index];
6648 }
6649
6650 - (void) updateHeight {
6651 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6652 }
6653
6654 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6655 if ((self = [super init]) != nil) {
6656 database_ = database;
6657 title_ = [title copy];
6658 [[self navigationItem] setTitle:title_];
6659 } return self;
6660 }
6661
6662 - (void) loadView {
6663 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6664 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6665 [self setView:view];
6666
6667 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6668 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6669 [view addSubview:list_];
6670
6671 // XXX: is 20 the most optimal number here?
6672 [list_ setSectionIndexMinimumDisplayRowCount:20];
6673
6674 [(UITableView *) list_ setDataSource:self];
6675 [list_ setDelegate:self];
6676
6677 [self updateHeight];
6678 }
6679
6680 - (void) releaseSubviews {
6681 list_ = nil;
6682
6683 packages_ = nil;
6684 sections_ = nil;
6685
6686 thumbs_ = nil;
6687 offset_.clear();
6688
6689 [super releaseSubviews];
6690 }
6691
6692 - (void) setDelegate:(id)delegate {
6693 delegate_ = delegate;
6694 }
6695
6696 - (bool) shouldYield {
6697 return false;
6698 }
6699
6700 - (bool) shouldBlock {
6701 return false;
6702 }
6703
6704 - (NSMutableArray *) _reloadPackages {
6705 @synchronized (database_) {
6706 era_ = [database_ era];
6707 NSArray *packages([database_ packages]);
6708
6709 return [NSMutableArray arrayWithArray:packages];
6710 } }
6711
6712 - (void) _reloadData {
6713 if (reloading_ != 0) {
6714 reloading_ = 2;
6715 return;
6716 }
6717
6718 NSMutableArray *packages;
6719
6720 reload:
6721 if ([self shouldYield]) {
6722 do {
6723 UIProgressHUD *hud;
6724
6725 if (![self shouldBlock])
6726 hud = nil;
6727 else {
6728 hud = [delegate_ addProgressHUD];
6729 [hud setText:UCLocalize("LOADING")];
6730 }
6731
6732 reloading_ = 1;
6733 packages = [self yieldToSelector:@selector(_reloadPackages)];
6734
6735 if (hud != nil)
6736 [delegate_ removeProgressHUD:hud];
6737 } while (reloading_ == 2);
6738 } else {
6739 packages = [self _reloadPackages];
6740 }
6741
6742 @synchronized (database_) {
6743 if (era_ != [database_ era])
6744 goto reload;
6745 reloading_ = 0;
6746
6747 thumbs_ = nil;
6748 offset_.clear();
6749
6750 packages_ = packages;
6751
6752 if ([self showsSections])
6753 sections_ = [self sectionsForPackages:packages];
6754 else {
6755 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6756 [section setCount:[packages_ count]];
6757 sections_ = [NSArray arrayWithObject:section];
6758 }
6759
6760 [self updateHeight];
6761
6762 _profile(PackageTable$reloadData$List)
6763 [(UITableView *) list_ setDataSource:self];
6764 [list_ reloadData];
6765 _end
6766 }
6767
6768 PrintTimes();
6769 }
6770
6771 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6772 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6773 size_t end([packages count]);
6774
6775 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6776 Section *section(prefix);
6777
6778 thumbs_ = CollationThumbs_;
6779 offset_ = CollationOffset_;
6780
6781 size_t offset(0);
6782 size_t offsets([CollationStarts_ count]);
6783
6784 NSString *start([CollationStarts_ objectAtIndex:offset]);
6785 size_t length([start length]);
6786
6787 for (size_t index(0); index != end; ++index) {
6788 if (start != nil) {
6789 Package *package([packages objectAtIndex:index]);
6790 NSString *name(PackageName(package, @selector(cyname)));
6791
6792 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6793 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6794 NSString *title([CollationTitles_ objectAtIndex:offset]);
6795 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6796 [sections addObject:section];
6797
6798 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6799 if (start == nil)
6800 break;
6801 length = [start length];
6802 }
6803 }
6804
6805 [section addToCount];
6806 }
6807
6808 for (; offset != offsets; ++offset) {
6809 NSString *title([CollationTitles_ objectAtIndex:offset]);
6810 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6811 [sections addObject:section];
6812 }
6813
6814 if ([prefix count] != 0) {
6815 Section *suffix([sections lastObject]);
6816 [prefix setName:[suffix name]];
6817 [suffix setName:nil];
6818 [sections insertObject:prefix atIndex:(offsets - 1)];
6819 }
6820
6821 return sections;
6822 }
6823
6824 - (void) reloadData {
6825 [super reloadData];
6826
6827 if ([self shouldYield])
6828 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6829 else
6830 [self _reloadData];
6831 }
6832
6833 - (void) resetCursor {
6834 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6835 }
6836
6837 - (void) clearData {
6838 [self updateHeight];
6839
6840 [list_ setDataSource:nil];
6841 [list_ reloadData];
6842
6843 [self resetCursor];
6844 }
6845
6846 @end
6847 /* }}} */
6848 /* Filtered Package List Controller {{{ */
6849 typedef Function<bool, Package *> PackageFilter;
6850 typedef Function<void, NSMutableArray *> PackageSorter;
6851 @interface FilteredPackageListController : PackageListController {
6852 PackageFilter filter_;
6853 PackageSorter sorter_;
6854 }
6855
6856 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6857
6858 - (void) setFilter:(PackageFilter)filter;
6859 - (void) setSorter:(PackageSorter)sorter;
6860
6861 @end
6862
6863 @implementation FilteredPackageListController
6864
6865 - (void) setFilter:(PackageFilter)filter {
6866 @synchronized (self) {
6867 filter_ = filter;
6868 } }
6869
6870 - (void) setSorter:(PackageSorter)sorter {
6871 @synchronized (self) {
6872 sorter_ = sorter;
6873 } }
6874
6875 - (NSMutableArray *) _reloadPackages {
6876 @synchronized (database_) {
6877 era_ = [database_ era];
6878
6879 NSArray *packages([database_ packages]);
6880 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6881
6882 PackageFilter filter;
6883 PackageSorter sorter;
6884
6885 @synchronized (self) {
6886 filter = filter_;
6887 sorter = sorter_;
6888 }
6889
6890 _profile(PackageTable$reloadData$Filter)
6891 for (Package *package in packages)
6892 if (filter(package))
6893 [filtered addObject:package];
6894 _end
6895
6896 if (sorter)
6897 sorter(filtered);
6898 return filtered;
6899 } }
6900
6901 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6902 if ((self = [super initWithDatabase:database title:title]) != nil) {
6903 [self setFilter:filter];
6904 } return self;
6905 }
6906
6907 @end
6908 /* }}} */
6909
6910 /* Home Controller {{{ */
6911 @interface HomeController : CydiaWebViewController {
6912 CFRunLoopRef runloop_;
6913 SCNetworkReachabilityRef reachability_;
6914 }
6915
6916 @end
6917
6918 @implementation HomeController
6919
6920 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6921 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6922 }
6923
6924 - (id) init {
6925 if ((self = [super init]) != nil) {
6926 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6927 [self reloadData];
6928
6929 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6930 if (reachability_ != NULL) {
6931 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6932 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6933
6934 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6935 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6936 runloop_ = runloop;
6937 }
6938 } return self;
6939 }
6940
6941 - (void) dealloc {
6942 if (reachability_ != NULL && runloop_ != NULL)
6943 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6944 [super dealloc];
6945 }
6946
6947 - (NSURL *) navigationURL {
6948 return [NSURL URLWithString:@"cydia://home"];
6949 }
6950
6951 - (void) aboutButtonClicked {
6952 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6953
6954 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6955 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6956 [alert setCancelButtonIndex:0];
6957
6958 [alert setMessage:
6959 @"Copyright \u00a9 2008-2015\n"
6960 "SaurikIT, LLC\n"
6961 "\n"
6962 "Jay Freeman (saurik)\n"
6963 "saurik@saurik.com\n"
6964 "http://www.saurik.com/"
6965 ];
6966
6967 [alert show];
6968 }
6969
6970 - (UIBarButtonItem *) leftButton {
6971 return [[[UIBarButtonItem alloc]
6972 initWithTitle:UCLocalize("ABOUT")
6973 style:UIBarButtonItemStylePlain
6974 target:self
6975 action:@selector(aboutButtonClicked)
6976 ] autorelease];
6977 }
6978
6979 @end
6980 /* }}} */
6981
6982 /* Cydia Navigation Controller Interface {{{ */
6983 @interface UINavigationController (Cydia)
6984
6985 - (NSArray *) navigationURLCollection;
6986 - (void) unloadData;
6987
6988 @end
6989 /* }}} */
6990
6991 /* Cydia Tab Bar Controller {{{ */
6992 @interface CydiaTabBarController : CyteTabBarController <
6993 UITabBarControllerDelegate,
6994 FetchDelegate
6995 > {
6996 _transient Database *database_;
6997
6998 _H<UIActivityIndicatorView> indicator_;
6999
7000 bool updating_;
7001 // XXX: ok, "updatedelegate_"?...
7002 _transient NSObject<CydiaDelegate> *updatedelegate_;
7003 }
7004
7005 - (NSArray *) navigationURLCollection;
7006 - (void) beginUpdate;
7007 - (BOOL) updating;
7008
7009 @end
7010
7011 @implementation CydiaTabBarController
7012
7013 - (NSArray *) navigationURLCollection {
7014 NSMutableArray *items([NSMutableArray array]);
7015
7016 // XXX: Should this deal with transient view controllers?
7017 for (id navigation in [self viewControllers]) {
7018 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
7019 if (stack != nil)
7020 [items addObject:stack];
7021 }
7022
7023 return items;
7024 }
7025
7026 - (id) initWithDatabase:(Database *)database {
7027 if ((self = [super init]) != nil) {
7028 database_ = database;
7029 [self setDelegate:self];
7030
7031 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7032 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7033
7034 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7035 } return self;
7036 }
7037
7038 - (void) beginUpdate {
7039 if (updating_)
7040 return;
7041
7042 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7043 UITabBarItem *item([controller tabBarItem]);
7044
7045 [item setBadgeValue:@""];
7046 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7047
7048 [indicator_ startAnimating];
7049 [badge addSubview:indicator_];
7050
7051 [updatedelegate_ retainNetworkActivityIndicator];
7052 updating_ = true;
7053
7054 [NSThread
7055 detachNewThreadSelector:@selector(performUpdate)
7056 toTarget:self
7057 withObject:nil
7058 ];
7059 }
7060
7061 - (void) performUpdate {
7062 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7063
7064 SourceStatus status(self, database_);
7065 [database_ updateWithStatus:status];
7066
7067 [self
7068 performSelectorOnMainThread:@selector(completeUpdate)
7069 withObject:nil
7070 waitUntilDone:NO
7071 ];
7072
7073 [pool release];
7074 }
7075
7076 - (void) stopUpdateWithSelector:(SEL)selector {
7077 updating_ = false;
7078 [updatedelegate_ releaseNetworkActivityIndicator];
7079
7080 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7081 [[controller tabBarItem] setBadgeValue:nil];
7082
7083 [indicator_ removeFromSuperview];
7084 [indicator_ stopAnimating];
7085
7086 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7087 }
7088
7089 - (void) completeUpdate {
7090 if (!updating_)
7091 return;
7092 [self stopUpdateWithSelector:@selector(reloadData)];
7093 }
7094
7095 - (void) cancelUpdate {
7096 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7097 }
7098
7099 - (void) cancelPressed {
7100 [self cancelUpdate];
7101 }
7102
7103 - (BOOL) updating {
7104 return updating_;
7105 }
7106
7107 - (bool) isSourceCancelled {
7108 return !updating_;
7109 }
7110
7111 - (void) startSourceFetch:(NSString *)uri {
7112 }
7113
7114 - (void) stopSourceFetch:(NSString *)uri {
7115 }
7116
7117 - (void) setUpdateDelegate:(id)delegate {
7118 updatedelegate_ = delegate;
7119 }
7120
7121 @end
7122 /* }}} */
7123
7124 /* Cydia Navigation Controller Implementation {{{ */
7125 @implementation UINavigationController (Cydia)
7126
7127 - (NSArray *) navigationURLCollection {
7128 NSMutableArray *stack([NSMutableArray array]);
7129
7130 for (CyteViewController *controller in [self viewControllers]) {
7131 NSString *url = [[controller navigationURL] absoluteString];
7132 if (url != nil)
7133 [stack addObject:url];
7134 }
7135
7136 return stack;
7137 }
7138
7139 - (void) reloadData {
7140 [super reloadData];
7141
7142 UIViewController *visible([self visibleViewController]);
7143 if (visible != nil)
7144 [visible reloadData];
7145
7146 // on the iPad, this view controller is ALSO visible. :(
7147 if (IsWildcat_)
7148 if (UIViewController *modal = [self modalViewController])
7149 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7150 if (UIViewController *top = [self topViewController])
7151 if (top != visible)
7152 [top reloadData];
7153 }
7154
7155 - (void) unloadData {
7156 for (CyteViewController *page in [self viewControllers])
7157 [page unloadData];
7158
7159 [super unloadData];
7160 }
7161
7162 @end
7163 /* }}} */
7164
7165 /* Cydia:// Protocol {{{ */
7166 @interface CydiaURLProtocol : NSURLProtocol {
7167 }
7168
7169 @end
7170
7171 @implementation CydiaURLProtocol
7172
7173 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7174 NSURL *url([request URL]);
7175 if (url == nil)
7176 return NO;
7177
7178 NSString *scheme([[url scheme] lowercaseString]);
7179 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7180 return YES;
7181 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7182 return YES;
7183
7184 return NO;
7185 }
7186
7187 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7188 return request;
7189 }
7190
7191 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7192 id<NSURLProtocolClient> client([self client]);
7193 if (icon == nil)
7194 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7195 else {
7196 NSData *data(UIImagePNGRepresentation(icon));
7197
7198 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7199 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7200 [client URLProtocol:self didLoadData:data];
7201 [client URLProtocolDidFinishLoading:self];
7202 }
7203 }
7204
7205 - (void) startLoading {
7206 id<NSURLProtocolClient> client([self client]);
7207 NSURLRequest *request([self request]);
7208
7209 NSURL *url([request URL]);
7210 NSString *href([url absoluteString]);
7211 NSString *scheme([[url scheme] lowercaseString]);
7212
7213 NSString *path;
7214
7215 if ([scheme isEqualToString:@"cydia"])
7216 path = [href substringFromIndex:8];
7217 else if ([scheme isEqualToString:@"about"])
7218 path = [href substringFromIndex:12];
7219 else _assert(false);
7220
7221 NSRange slash([path rangeOfString:@"/"]);
7222
7223 NSString *command;
7224 if (slash.location == NSNotFound) {
7225 command = path;
7226 path = nil;
7227 } else {
7228 command = [path substringToIndex:slash.location];
7229 path = [path substringFromIndex:(slash.location + 1)];
7230 }
7231
7232 Database *database([Database sharedInstance]);
7233
7234 if (false);
7235 else if ([command isEqualToString:@"application-icon"]) {
7236 if (path == nil)
7237 goto fail;
7238 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7239
7240 UIImage *icon(nil);
7241
7242 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7243 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7244 icon = [UIImage imageWithData:data];
7245 }
7246
7247 if (icon == nil)
7248 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7249 icon = [UIImage imageAtPath:file];
7250
7251 if (icon == nil)
7252 icon = [UIImage imageNamed:@"unknown.png"];
7253
7254 [self _returnPNGWithImage:icon forRequest:request];
7255 } else if ([command isEqualToString:@"package-icon"]) {
7256 if (path == nil)
7257 goto fail;
7258 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7259 Package *package([database packageWithName:path]);
7260 if (package == nil)
7261 goto fail;
7262 [package parse];
7263 UIImage *icon([package icon]);
7264 [self _returnPNGWithImage:icon forRequest:request];
7265 } else if ([command isEqualToString:@"uikit-image"]) {
7266 if (path == nil)
7267 goto fail;
7268 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7269 UIImage *icon(_UIImageWithName(path));
7270 [self _returnPNGWithImage:icon forRequest:request];
7271 } else if ([command isEqualToString:@"section-icon"]) {
7272 if (path == nil)
7273 goto fail;
7274 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7275 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7276 if (icon == nil)
7277 icon = [UIImage imageNamed:@"unknown.png"];
7278 [self _returnPNGWithImage:icon forRequest:request];
7279 } else fail: {
7280 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7281 }
7282 }
7283
7284 - (void) stopLoading {
7285 }
7286
7287 @end
7288 /* }}} */
7289
7290 /* Section Controller {{{ */
7291 @interface SectionController : FilteredPackageListController {
7292 _H<NSString> key_;
7293 _H<NSString> section_;
7294 }
7295
7296 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7297
7298 @end
7299
7300 @implementation SectionController
7301
7302 - (NSURL *) referrerURL {
7303 NSString *name(section_);
7304 name = name ?: @"*";
7305 NSString *key(key_);
7306 key = key ?: @"*";
7307 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7308 }
7309
7310 - (NSURL *) navigationURL {
7311 NSString *name(section_);
7312 name = name ?: @"*";
7313 NSString *key(key_);
7314 key = key ?: @"*";
7315 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7316 }
7317
7318 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7319 NSString *title;
7320 if (section == nil)
7321 title = UCLocalize("ALL_PACKAGES");
7322 else if (![section isEqual:@""])
7323 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7324 else
7325 title = UCLocalize("NO_SECTION");
7326
7327 if ((self = [super initWithDatabase:database title:title]) != nil) {
7328 key_ = [source key];
7329 section_ = section;
7330 } return self;
7331 }
7332
7333 - (void) reloadData {
7334 Source *source([database_ sourceWithKey:key_]);
7335 _H<NSString> name(section_);
7336
7337 [self setFilter:[=](Package *package) {
7338 NSString *section([package section]);
7339
7340 return (
7341 name == nil ||
7342 section == nil && [name length] == 0 ||
7343 [name isEqualToString:section]
7344 ) && (
7345 source == nil ||
7346 [package source] == source
7347 ) && [package visible];
7348 }];
7349
7350 [super reloadData];
7351 }
7352
7353 @end
7354 /* }}} */
7355 /* Sections Controller {{{ */
7356 @interface SectionsController : CyteViewController <
7357 UITableViewDataSource,
7358 UITableViewDelegate
7359 > {
7360 _transient Database *database_;
7361 _H<NSString> key_;
7362 _H<NSMutableArray> sections_;
7363 _H<NSMutableArray> filtered_;
7364 _H<UITableView, 2> list_;
7365 }
7366
7367 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7368 - (void) editButtonClicked;
7369
7370 @end
7371
7372 @implementation SectionsController
7373
7374 - (NSURL *) navigationURL {
7375 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7376 }
7377
7378 - (Source *) source {
7379 if (key_ == nil)
7380 return nil;
7381 return [database_ sourceWithKey:key_];
7382 }
7383
7384 - (void) updateNavigationItem {
7385 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7386 if ([sections_ count] == 0) {
7387 [[self navigationItem] setRightBarButtonItem:nil];
7388 } else {
7389 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7390 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7391 target:self
7392 action:@selector(editButtonClicked)
7393 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7394 }
7395 }
7396
7397 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7398 [super setEditing:editing animated:animated];
7399
7400 if (editing)
7401 [list_ reloadData];
7402 else
7403 [delegate_ updateData];
7404
7405 [self updateNavigationItem];
7406 }
7407
7408 - (void) viewDidAppear:(BOOL)animated {
7409 [super viewDidAppear:animated];
7410 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7411 }
7412
7413 - (void) viewWillDisappear:(BOOL)animated {
7414 [super viewWillDisappear:animated];
7415 [self setEditing:NO];
7416 }
7417
7418 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7419 Section *section = nil;
7420 int index = [indexPath row];
7421 if (![self isEditing]) {
7422 index -= 1;
7423 if (index >= 0)
7424 section = [filtered_ objectAtIndex:index];
7425 } else {
7426 section = [sections_ objectAtIndex:index];
7427 }
7428 return section;
7429 }
7430
7431 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7432 if ([self isEditing])
7433 return [sections_ count];
7434 else
7435 return [filtered_ count] + 1;
7436 }
7437
7438 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7439 return 45.0f;
7440 }*/
7441
7442 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7443 static NSString *reuseIdentifier = @"SectionCell";
7444
7445 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7446 if (cell == nil)
7447 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7448
7449 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7450
7451 return cell;
7452 }
7453
7454 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7455 if ([self isEditing])
7456 return;
7457
7458 Section *section = [self sectionAtIndexPath:indexPath];
7459
7460 SectionController *controller = [[[SectionController alloc]
7461 initWithDatabase:database_
7462 source:[self source]
7463 section:[section name]
7464 ] autorelease];
7465 [controller setDelegate:delegate_];
7466
7467 [[self navigationController] pushViewController:controller animated:YES];
7468 }
7469
7470 - (void) loadView {
7471 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7472 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7473 [list_ setRowHeight:46];
7474 [(UITableView *) list_ setDataSource:self];
7475 [list_ setDelegate:self];
7476 [self setView:list_];
7477 }
7478
7479 - (void) viewDidLoad {
7480 [super viewDidLoad];
7481
7482 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7483 }
7484
7485 - (void) releaseSubviews {
7486 list_ = nil;
7487
7488 sections_ = nil;
7489 filtered_ = nil;
7490
7491 [super releaseSubviews];
7492 }
7493
7494 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7495 if ((self = [super init]) != nil) {
7496 database_ = database;
7497 key_ = [source key];
7498 } return self;
7499 }
7500
7501 - (void) reloadData {
7502 [super reloadData];
7503
7504 NSArray *packages = [database_ packages];
7505
7506 sections_ = [NSMutableArray arrayWithCapacity:16];
7507 filtered_ = [NSMutableArray arrayWithCapacity:16];
7508
7509 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7510
7511 Source *source([self source]);
7512
7513 _trace();
7514 for (Package *package in packages) {
7515 if (source != nil && [package source] != source)
7516 continue;
7517
7518 NSString *name([package section]);
7519 NSString *key(name == nil ? @"" : name);
7520
7521 Section *section;
7522
7523 _profile(SectionsView$reloadData$Section)
7524 section = [sections objectForKey:key];
7525 if (section == nil) {
7526 _profile(SectionsView$reloadData$Section$Allocate)
7527 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7528 [sections setObject:section forKey:key];
7529 _end
7530 }
7531 _end
7532
7533 [section addToCount];
7534
7535 _profile(SectionsView$reloadData$Filter)
7536 if (![package visible])
7537 continue;
7538 _end
7539
7540 [section addToRow];
7541 }
7542 _trace();
7543
7544 [sections_ addObjectsFromArray:[sections allValues]];
7545
7546 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7547
7548 for (Section *section in (id) sections_) {
7549 size_t count([section row]);
7550 if (count == 0)
7551 continue;
7552
7553 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7554 [section setCount:count];
7555 [filtered_ addObject:section];
7556 }
7557
7558 [self updateNavigationItem];
7559 [list_ reloadData];
7560 _trace();
7561 }
7562
7563 - (void) editButtonClicked {
7564 [self setEditing:![self isEditing] animated:YES];
7565 }
7566
7567 @end
7568 /* }}} */
7569
7570 /* Changes Controller {{{ */
7571 @interface ChangesController : FilteredPackageListController {
7572 unsigned upgrades_;
7573 }
7574
7575 - (id) initWithDatabase:(Database *)database;
7576
7577 @end
7578
7579 @implementation ChangesController
7580
7581 - (NSURL *) referrerURL {
7582 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7583 }
7584
7585 - (NSURL *) navigationURL {
7586 return [NSURL URLWithString:@"cydia://changes"];
7587 }
7588
7589 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7590 @synchronized (database_) {
7591 if ([database_ era] != era_)
7592 return nil;
7593
7594 NSUInteger sectionIndex([path section]);
7595 if (sectionIndex >= [sections_ count])
7596 return nil;
7597 Section *section([sections_ objectAtIndex:sectionIndex]);
7598 NSInteger row([path row]);
7599 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7600 } }
7601
7602 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7603 NSString *context([alert context]);
7604
7605 if ([context isEqualToString:@"norefresh"])
7606 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7607 }
7608
7609 - (void) setLeftBarButtonItem {
7610 if ([delegate_ updating])
7611 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7612 initWithTitle:UCLocalize("CANCEL")
7613 style:UIBarButtonItemStyleDone
7614 target:self
7615 action:@selector(cancelButtonClicked)
7616 ] autorelease] animated:YES];
7617 else
7618 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7619 initWithTitle:UCLocalize("REFRESH")
7620 style:UIBarButtonItemStylePlain
7621 target:self
7622 action:@selector(refreshButtonClicked)
7623 ] autorelease] animated:YES];
7624 }
7625
7626 - (void) refreshButtonClicked {
7627 if ([delegate_ requestUpdate])
7628 [self setLeftBarButtonItem];
7629 }
7630
7631 - (void) cancelButtonClicked {
7632 [delegate_ cancelUpdate];
7633 }
7634
7635 - (void) upgradeButtonClicked {
7636 [delegate_ distUpgrade];
7637 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7638 }
7639
7640 - (bool) shouldYield {
7641 return true;
7642 }
7643
7644 - (bool) shouldBlock {
7645 return true;
7646 }
7647
7648 - (void) useFilter {
7649 @synchronized (self) {
7650 [self setFilter:[](Package *package) {
7651 return [package upgradableAndEssential:YES] || [package visible];
7652 }];
7653
7654 [self setSorter:[](NSMutableArray *packages) {
7655 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7656 }];
7657 } }
7658
7659 - (id) initWithDatabase:(Database *)database {
7660 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7661 [self useFilter];
7662 } return self;
7663 }
7664
7665 - (void) viewDidLoad {
7666 [super viewDidLoad];
7667 [self setLeftBarButtonItem];
7668 }
7669
7670 - (void) viewWillAppear:(BOOL)animated {
7671 [super viewWillAppear:animated];
7672 [self setLeftBarButtonItem];
7673 }
7674
7675 - (void) reloadData {
7676 [self setLeftBarButtonItem];
7677 [super reloadData];
7678 }
7679
7680 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7681 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7682
7683 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7684 Section *ignored = nil;
7685 Section *section = nil;
7686 time_t last = 0;
7687
7688 upgrades_ = 0;
7689 bool unseens = false;
7690
7691 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7692
7693 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7694 Package *package = [packages objectAtIndex:offset];
7695
7696 BOOL uae = [package upgradableAndEssential:YES];
7697
7698 if (!uae) {
7699 unseens = true;
7700 time_t seen([package seen]);
7701
7702 if (section == nil || last != seen) {
7703 last = seen;
7704
7705 NSString *name;
7706 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7707 [name autorelease];
7708
7709 _profile(ChangesController$reloadData$Allocate)
7710 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7711 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7712 [sections addObject:section];
7713 _end
7714 }
7715
7716 [section addToCount];
7717 } else if ([package ignored]) {
7718 if (ignored == nil) {
7719 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7720 }
7721 [ignored addToCount];
7722 } else {
7723 ++upgrades_;
7724 [upgradable addToCount];
7725 }
7726 }
7727 _trace();
7728
7729 CFRelease(formatter);
7730
7731 if (unseens) {
7732 Section *last = [sections lastObject];
7733 size_t count = [last count];
7734 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7735 [sections removeLastObject];
7736 }
7737
7738 if ([ignored count] != 0)
7739 [sections insertObject:ignored atIndex:0];
7740 if (upgrades_ != 0)
7741 [sections insertObject:upgradable atIndex:0];
7742
7743 [list_ reloadData];
7744
7745 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7746 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7747 style:UIBarButtonItemStylePlain
7748 target:self
7749 action:@selector(upgradeButtonClicked)
7750 ] autorelease]) animated:YES];
7751
7752 return sections;
7753 }
7754
7755 @end
7756 /* }}} */
7757 /* Search Controller {{{ */
7758 @interface SearchController : FilteredPackageListController <
7759 UISearchBarDelegate
7760 > {
7761 _H<UISearchBar, 1> search_;
7762 BOOL searchloaded_;
7763 bool summary_;
7764 }
7765
7766 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7767 - (void) reloadData;
7768
7769 @end
7770
7771 @implementation SearchController
7772
7773 - (NSURL *) referrerURL {
7774 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7775 }
7776
7777 - (NSURL *) navigationURL {
7778 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7779 return [NSURL URLWithString:@"cydia://search"];
7780 else
7781 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7782 }
7783
7784 - (NSArray *) termsForQuery:(NSString *)query {
7785 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7786 for (NSString *component in [query componentsSeparatedByString:@" "])
7787 if ([component length] != 0)
7788 [terms addObject:component];
7789
7790 return terms;
7791 }
7792
7793 - (void) useSearch {
7794 _H<NSArray> query([self termsForQuery:[search_ text]]);
7795 summary_ = false;
7796
7797 @synchronized (self) {
7798 [self setFilter:[=](Package *package) {
7799 if (![package unfiltered])
7800 return false;
7801 if (![package matches:query])
7802 return false;
7803 return true;
7804 }];
7805
7806 [self setSorter:[](NSMutableArray *packages) {
7807 [packages radixSortUsingSelector:@selector(rank)];
7808 }];
7809 }
7810
7811 [self clearData];
7812 [self reloadData];
7813 }
7814
7815 - (void) usePrefix:(NSString *)prefix {
7816 _H<NSString> query(prefix);
7817 summary_ = true;
7818
7819 @synchronized (self) {
7820 [self setFilter:[=](Package *package) {
7821 if ([query length] == 0)
7822 return false;
7823 if (![package unfiltered])
7824 return false;
7825 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7826 return false;
7827 return true;
7828 }];
7829
7830 [self setSorter:nullptr];
7831 }
7832
7833 [self reloadData];
7834 }
7835
7836 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7837 [self clearData];
7838 [self usePrefix:[search_ text]];
7839 }
7840
7841 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7842 [search_ resignFirstResponder];
7843 [self useSearch];
7844 }
7845
7846 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7847 [search_ setText:@""];
7848 [self searchBarButtonClicked:searchBar];
7849 }
7850
7851 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7852 [self searchBarButtonClicked:searchBar];
7853 }
7854
7855 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7856 [self usePrefix:text];
7857 }
7858
7859 - (bool) shouldYield {
7860 return YES;
7861 }
7862
7863 - (bool) shouldBlock {
7864 return !summary_;
7865 }
7866
7867 - (bool) isSummarized {
7868 return summary_;
7869 }
7870
7871 - (bool) showsSections {
7872 return false;
7873 }
7874
7875 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7876 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7877 search_ = [[[UISearchBar alloc] init] autorelease];
7878 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7879 [search_ setDelegate:self];
7880
7881 UITextField *textField;
7882 if ([search_ respondsToSelector:@selector(searchField)])
7883 textField = [search_ searchField];
7884 else
7885 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7886
7887 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7888 [textField setEnablesReturnKeyAutomatically:NO];
7889 [[self navigationItem] setTitleView:textField];
7890
7891 if (query != nil)
7892 [search_ setText:query];
7893 [self useSearch];
7894 } return self;
7895 }
7896
7897 - (void) viewDidAppear:(BOOL)animated {
7898 [super viewDidAppear:animated];
7899
7900 if (!searchloaded_) {
7901 searchloaded_ = YES;
7902 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7903 [search_ layoutSubviews];
7904 }
7905
7906 if ([self isSummarized])
7907 [search_ becomeFirstResponder];
7908 }
7909
7910 - (void) reloadData {
7911 [self resetCursor];
7912 [super reloadData];
7913 }
7914
7915 - (void) didSelectPackage:(Package *)package {
7916 [search_ resignFirstResponder];
7917 [super didSelectPackage:package];
7918 }
7919
7920 @end
7921 /* }}} */
7922 /* Package Settings Controller {{{ */
7923 @interface PackageSettingsController : CyteViewController <
7924 UITableViewDataSource,
7925 UITableViewDelegate
7926 > {
7927 _transient Database *database_;
7928 _H<NSString> name_;
7929 _H<Package> package_;
7930 _H<UITableView, 2> table_;
7931 _H<UISwitch> subscribedSwitch_;
7932 _H<UISwitch> ignoredSwitch_;
7933 _H<UITableViewCell> subscribedCell_;
7934 _H<UITableViewCell> ignoredCell_;
7935 }
7936
7937 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7938
7939 @end
7940
7941 @implementation PackageSettingsController
7942
7943 - (NSURL *) navigationURL {
7944 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7945 }
7946
7947 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7948 if (package_ == nil)
7949 return 0;
7950
7951 if ([package_ installed] == nil)
7952 return 1;
7953 else
7954 return 2;
7955 }
7956
7957 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7958 if (package_ == nil)
7959 return 0;
7960
7961 // both sections contain just one item right now.
7962 return 1;
7963 }
7964
7965 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7966 return nil;
7967 }
7968
7969 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7970 if (section == 0)
7971 return UCLocalize("SHOW_ALL_CHANGES_EX");
7972 else
7973 return UCLocalize("IGNORE_UPGRADES_EX");
7974 }
7975
7976 - (void) onSubscribed:(id)control {
7977 bool value([control isOn]);
7978 if (package_ == nil)
7979 return;
7980 if ([package_ setSubscribed:value])
7981 [delegate_ updateData];
7982 }
7983
7984 - (void) _updateIgnored {
7985 const char *package([name_ UTF8String]);
7986 bool on([ignoredSwitch_ isOn]);
7987
7988 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7989 fwrite(package, strlen(package), 1, dpkg);
7990
7991 if (on)
7992 fwrite(" hold\n", 6, 1, dpkg);
7993 else
7994 fwrite(" install\n", 9, 1, dpkg);
7995
7996 pclose(dpkg);
7997 }
7998
7999 - (void) onIgnored:(id)control {
8000 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8001 [invocation setTarget:self];
8002 [invocation setSelector:@selector(_updateIgnored)];
8003
8004 [delegate_ reloadDataWithInvocation:invocation];
8005 }
8006
8007 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8008 if (package_ == nil)
8009 return nil;
8010
8011 switch ([indexPath section]) {
8012 case 0: return subscribedCell_;
8013 case 1: return ignoredCell_;
8014
8015 _nodefault
8016 }
8017
8018 return nil;
8019 }
8020
8021 - (void) loadView {
8022 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8023 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8024 [self setView:view];
8025
8026 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8027 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8028 [(UITableView *) table_ setDataSource:self];
8029 [table_ setDelegate:self];
8030 [view addSubview:table_];
8031
8032 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8033 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8034 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8035
8036 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8037 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8038 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8039
8040 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8041 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8042 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8043 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8044
8045 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8046 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8047 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8048 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8049 }
8050
8051 - (void) viewDidLoad {
8052 [super viewDidLoad];
8053
8054 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8055 }
8056
8057 - (void) releaseSubviews {
8058 ignoredCell_ = nil;
8059 subscribedCell_ = nil;
8060 table_ = nil;
8061 ignoredSwitch_ = nil;
8062 subscribedSwitch_ = nil;
8063
8064 [super releaseSubviews];
8065 }
8066
8067 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8068 if ((self = [super init]) != nil) {
8069 database_ = database;
8070 name_ = package;
8071 } return self;
8072 }
8073
8074 - (void) reloadData {
8075 [super reloadData];
8076
8077 package_ = [database_ packageWithName:name_];
8078
8079 if (package_ != nil) {
8080 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8081 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8082 } // XXX: what now, G?
8083
8084 [table_ reloadData];
8085 }
8086
8087 @end
8088 /* }}} */
8089
8090 /* Installed Controller {{{ */
8091 @interface InstalledController : FilteredPackageListController {
8092 bool sectioned_;
8093 }
8094
8095 - (id) initWithDatabase:(Database *)database;
8096 - (void) queueStatusDidChange;
8097
8098 @end
8099
8100 @implementation InstalledController
8101
8102 - (NSURL *) referrerURL {
8103 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8104 }
8105
8106 - (NSURL *) navigationURL {
8107 return [NSURL URLWithString:@"cydia://installed"];
8108 }
8109
8110 - (void) useRecent {
8111 sectioned_ = false;
8112
8113 @synchronized (self) {
8114 [self setFilter:[](Package *package) {
8115 return ![package uninstalled] && package->role_ < 7;
8116 }];
8117
8118 [self setSorter:[](NSMutableArray *packages) {
8119 [packages radixSortUsingSelector:@selector(recent)];
8120 }];
8121 } }
8122
8123 - (void) useFilter:(UISegmentedControl *)segmented {
8124 NSInteger selected([segmented selectedSegmentIndex]);
8125 if (selected == 2)
8126 return [self useRecent];
8127 bool simple(selected == 0);
8128 sectioned_ = true;
8129
8130 @synchronized (self) {
8131 [self setFilter:[=](Package *package) {
8132 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8133 }];
8134
8135 [self setSorter:nullptr];
8136 } }
8137
8138 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8139 if (sectioned_)
8140 return [super sectionsForPackages:packages];
8141
8142 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8143
8144 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8145 Section *section(nil);
8146 time_t last(0);
8147
8148 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8149 Package *package([packages objectAtIndex:offset]);
8150
8151 time_t upgraded([package upgraded]);
8152 if (upgraded < 1168364520)
8153 upgraded = 0;
8154 else
8155 upgraded -= upgraded % (60 * 60 * 24);
8156
8157 if (section == nil || upgraded != last) {
8158 last = upgraded;
8159
8160 NSString *name;
8161 if (upgraded == 0)
8162 continue; // XXX: name = UCLocalize("...");
8163 else {
8164 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8165 [name autorelease];
8166 }
8167
8168 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8169 [sections addObject:section];
8170 }
8171
8172 [section addToCount];
8173 }
8174
8175 CFRelease(formatter);
8176 return sections;
8177 }
8178
8179 - (id) initWithDatabase:(Database *)database {
8180 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8181 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8182 [segmented setSelectedSegmentIndex:0];
8183 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8184 [[self navigationItem] setTitleView:segmented];
8185
8186 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8187 [self useFilter:segmented];
8188
8189 [self queueStatusDidChange];
8190 } return self;
8191 }
8192
8193 #if !AlwaysReload
8194 - (void) queueButtonClicked {
8195 [delegate_ queue];
8196 }
8197 #endif
8198
8199 - (void) queueStatusDidChange {
8200 #if !AlwaysReload
8201 if (Queuing_) {
8202 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8203 initWithTitle:UCLocalize("QUEUE")
8204 style:UIBarButtonItemStyleDone
8205 target:self
8206 action:@selector(queueButtonClicked)
8207 ] autorelease]];
8208 } else {
8209 [[self navigationItem] setRightBarButtonItem:nil];
8210 }
8211 #endif
8212 }
8213
8214 - (void) modeChanged:(UISegmentedControl *)segmented {
8215 [self useFilter:segmented];
8216 [self reloadData];
8217 }
8218
8219 @end
8220 /* }}} */
8221
8222 /* Source Cell {{{ */
8223 @interface SourceCell : CyteTableViewCell <
8224 CyteTableViewCellDelegate,
8225 SourceDelegate
8226 > {
8227 _H<Source, 1> source_;
8228 _H<NSURL> url_;
8229 _H<UIImage> icon_;
8230 _H<NSString> origin_;
8231 _H<NSString> label_;
8232 _H<UIActivityIndicatorView> indicator_;
8233 }
8234
8235 - (void) setSource:(Source *)source;
8236 - (void) setFetch:(NSNumber *)fetch;
8237
8238 @end
8239
8240 @implementation SourceCell
8241
8242 - (void) _setImage:(NSArray *)data {
8243 if ([url_ isEqual:[data objectAtIndex:0]]) {
8244 icon_ = [data objectAtIndex:1];
8245 [content_ setNeedsDisplay];
8246 }
8247 }
8248
8249 - (void) _setSource:(NSURL *) url {
8250 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8251
8252 if (NSData *data = [NSURLConnection
8253 sendSynchronousRequest:[NSURLRequest
8254 requestWithURL:url
8255 cachePolicy:NSURLRequestUseProtocolCachePolicy
8256 timeoutInterval:10
8257 ]
8258
8259 returningResponse:NULL
8260 error:NULL
8261 ])
8262 if (UIImage *image = [UIImage imageWithData:data])
8263 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8264
8265 [pool release];
8266 }
8267
8268 - (void) setSource:(Source *)source {
8269 source_ = source;
8270 [source_ setDelegate:self];
8271
8272 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8273
8274 icon_ = [UIImage imageNamed:@"unknown.png"];
8275
8276 origin_ = [source name];
8277 label_ = [source rooturi];
8278
8279 [content_ setNeedsDisplay];
8280
8281 url_ = [source iconURL];
8282 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8283 }
8284
8285 - (void) setAllSource {
8286 source_ = nil;
8287 [indicator_ stopAnimating];
8288
8289 icon_ = [UIImage imageNamed:@"folder.png"];
8290 origin_ = UCLocalize("ALL_SOURCES");
8291 label_ = UCLocalize("ALL_SOURCES_EX");
8292 [content_ setNeedsDisplay];
8293 }
8294
8295 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8296 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8297 UIView *content([self contentView]);
8298 CGRect bounds([content bounds]);
8299
8300 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8301 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8302 [content_ setBackgroundColor:[UIColor whiteColor]];
8303 [content addSubview:content_];
8304
8305 [content_ setDelegate:self];
8306 [content_ setOpaque:YES];
8307
8308 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8309 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8310 [content addSubview:indicator_];
8311
8312 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8313 } return self;
8314 }
8315
8316 - (void) layoutSubviews {
8317 [super layoutSubviews];
8318
8319 UIView *content([self contentView]);
8320 CGRect bounds([content bounds]);
8321
8322 CGRect frame([indicator_ frame]);
8323 frame.origin.x = bounds.size.width - frame.size.width;
8324 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8325
8326 if (kCFCoreFoundationVersionNumber < 800)
8327 frame.origin.x -= 8;
8328 [indicator_ setFrame:frame];
8329 }
8330
8331 - (NSString *) accessibilityLabel {
8332 return origin_;
8333 }
8334
8335 - (void) drawContentRect:(CGRect)rect {
8336 bool highlighted(highlighted_);
8337 float width(rect.size.width);
8338
8339 if (icon_ != nil) {
8340 CGRect rect;
8341 rect.size = [(UIImage *) icon_ size];
8342
8343 while (rect.size.width > 32 || rect.size.height > 32) {
8344 rect.size.width /= 2;
8345 rect.size.height /= 2;
8346 }
8347
8348 rect.origin.x = 26 - rect.size.width / 2;
8349 rect.origin.y = 26 - rect.size.height / 2;
8350
8351 [icon_ drawInRect:Retina(rect)];
8352 }
8353
8354 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8355 UISetColor(White_);
8356
8357 if (!highlighted)
8358 UISetColor(Black_);
8359 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8360
8361 if (!highlighted)
8362 UISetColor(Gray_);
8363 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8364 }
8365
8366 - (void) setFetch:(NSNumber *)fetch {
8367 if ([fetch boolValue])
8368 [indicator_ startAnimating];
8369 else
8370 [indicator_ stopAnimating];
8371 }
8372
8373 @end
8374 /* }}} */
8375 /* Sources Controller {{{ */
8376 @interface SourcesController : CyteViewController <
8377 UITableViewDataSource,
8378 UITableViewDelegate
8379 > {
8380 _transient Database *database_;
8381 unsigned era_;
8382
8383 _H<UITableView, 2> list_;
8384 _H<NSMutableArray> sources_;
8385 int offset_;
8386
8387 _H<NSString> href_;
8388 _H<UIProgressHUD> hud_;
8389 _H<NSError> error_;
8390
8391 NSURLConnection *trivial_bz2_;
8392 NSURLConnection *trivial_gz_;
8393
8394 BOOL cydia_;
8395 }
8396
8397 - (id) initWithDatabase:(Database *)database;
8398 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8399
8400 @end
8401
8402 @implementation SourcesController
8403
8404 - (void) _releaseConnection:(NSURLConnection *)connection {
8405 if (connection != nil) {
8406 [connection cancel];
8407 //[connection setDelegate:nil];
8408 [connection release];
8409 }
8410 }
8411
8412 - (void) dealloc {
8413 [self _releaseConnection:trivial_gz_];
8414 [self _releaseConnection:trivial_bz2_];
8415
8416 [super dealloc];
8417 }
8418
8419 - (NSURL *) navigationURL {
8420 return [NSURL URLWithString:@"cydia://sources"];
8421 }
8422
8423 - (void) viewDidAppear:(BOOL)animated {
8424 [super viewDidAppear:animated];
8425 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8426 }
8427
8428 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8429 return 2;
8430 }
8431
8432 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8433 if (section == 1)
8434 return UCLocalize("INDIVIDUAL_SOURCES");
8435 return nil;
8436 }
8437
8438 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8439 switch (section) {
8440 case 0: return 1;
8441 case 1: return [sources_ count];
8442 default: return 0;
8443 }
8444 }
8445
8446 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8447 @synchronized (database_) {
8448 if ([database_ era] != era_)
8449 return nil;
8450 if ([indexPath section] != 1)
8451 return nil;
8452 NSUInteger index([indexPath row]);
8453 if (index >= [sources_ count])
8454 return nil;
8455 return [sources_ objectAtIndex:index];
8456 } }
8457
8458 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8459 static NSString *cellIdentifier = @"SourceCell";
8460
8461 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8462 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8463 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8464
8465 Source *source([self sourceAtIndexPath:indexPath]);
8466 if (source == nil)
8467 [cell setAllSource];
8468 else
8469 [cell setSource:source];
8470
8471 return cell;
8472 }
8473
8474 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8475 SectionsController *controller([[[SectionsController alloc]
8476 initWithDatabase:database_
8477 source:[self sourceAtIndexPath:indexPath]
8478 ] autorelease]);
8479
8480 [controller setDelegate:delegate_];
8481 [[self navigationController] pushViewController:controller animated:YES];
8482 }
8483
8484 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8485 if ([indexPath section] != 1)
8486 return false;
8487 Source *source = [self sourceAtIndexPath:indexPath];
8488 return [source record] != nil;
8489 }
8490
8491 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8492 _assert([indexPath section] == 1);
8493 if (editingStyle == UITableViewCellEditingStyleDelete) {
8494 Source *source = [self sourceAtIndexPath:indexPath];
8495 if (source == nil) return;
8496
8497 [Sources_ removeObjectForKey:[source key]];
8498
8499 [delegate_ _saveConfig];
8500 [delegate_ reloadDataWithInvocation:nil];
8501 }
8502 }
8503
8504 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8505 [self updateButtonsForEditingStatusAnimated:YES];
8506 }
8507
8508 - (void) complete {
8509 [delegate_ addTrivialSource:href_];
8510 href_ = nil;
8511
8512 [delegate_ syncData];
8513 }
8514
8515 - (NSString *) getWarning {
8516 NSString *href(href_);
8517 NSRange colon([href rangeOfString:@"://"]);
8518 if (colon.location != NSNotFound)
8519 href = [href substringFromIndex:(colon.location + 3)];
8520 href = [href stringByAddingPercentEscapes];
8521 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8522
8523 NSURL *url([NSURL URLWithString:href]);
8524
8525 NSStringEncoding encoding;
8526 NSError *error(nil);
8527
8528 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8529 return [warning length] == 0 ? nil : warning;
8530 return nil;
8531 }
8532
8533 - (void) _endConnection:(NSURLConnection *)connection {
8534 // XXX: the memory management in this method is horribly awkward
8535
8536 NSURLConnection **field = NULL;
8537 if (connection == trivial_bz2_)
8538 field = &trivial_bz2_;
8539 else if (connection == trivial_gz_)
8540 field = &trivial_gz_;
8541 _assert(field != NULL);
8542 [connection release];
8543 *field = nil;
8544
8545 if (
8546 trivial_bz2_ == nil &&
8547 trivial_gz_ == nil
8548 ) {
8549 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8550
8551 [delegate_ releaseNetworkActivityIndicator];
8552
8553 [delegate_ removeProgressHUD:hud_];
8554 hud_ = nil;
8555
8556 if (cydia_) {
8557 if (warning != nil) {
8558 UIAlertView *alert = [[[UIAlertView alloc]
8559 initWithTitle:UCLocalize("SOURCE_WARNING")
8560 message:warning
8561 delegate:self
8562 cancelButtonTitle:UCLocalize("CANCEL")
8563 otherButtonTitles:
8564 UCLocalize("ADD_ANYWAY"),
8565 nil
8566 ] autorelease];
8567
8568 [alert setContext:@"warning"];
8569 [alert setNumberOfRows:1];
8570 [alert show];
8571
8572 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8573 error_ = nil;
8574 return;
8575 }
8576
8577 [self complete];
8578 } else if (error_ != nil) {
8579 UIAlertView *alert = [[[UIAlertView alloc]
8580 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8581 message:[error_ localizedDescription]
8582 delegate:self
8583 cancelButtonTitle:UCLocalize("OK")
8584 otherButtonTitles:nil
8585 ] autorelease];
8586
8587 [alert setContext:@"urlerror"];
8588 [alert show];
8589
8590 href_ = nil;
8591 } else {
8592 UIAlertView *alert = [[[UIAlertView alloc]
8593 initWithTitle:UCLocalize("NOT_REPOSITORY")
8594 message:UCLocalize("NOT_REPOSITORY_EX")
8595 delegate:self
8596 cancelButtonTitle:UCLocalize("OK")
8597 otherButtonTitles:nil
8598 ] autorelease];
8599
8600 [alert setContext:@"trivial"];
8601 [alert show];
8602
8603 href_ = nil;
8604 }
8605
8606 error_ = nil;
8607 }
8608 }
8609
8610 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8611 switch ([response statusCode]) {
8612 case 200:
8613 cydia_ = YES;
8614 }
8615 }
8616
8617 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8618 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8619 error_ = error;
8620 [self _endConnection:connection];
8621 }
8622
8623 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8624 [self _endConnection:connection];
8625 }
8626
8627 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8628 NSURL *url([NSURL URLWithString:href]);
8629
8630 NSMutableURLRequest *request = [NSMutableURLRequest
8631 requestWithURL:url
8632 cachePolicy:NSURLRequestUseProtocolCachePolicy
8633 timeoutInterval:10
8634 ];
8635
8636 [request setHTTPMethod:method];
8637
8638 if (Machine_ != NULL)
8639 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8640
8641 if (UniqueID_ != nil)
8642 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8643
8644 if ([url isCydiaSecure]) {
8645 if (UniqueID_ != nil)
8646 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8647 }
8648
8649 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8650 }
8651
8652 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8653 NSString *context([alert context]);
8654
8655 if ([context isEqualToString:@"source"]) {
8656 switch (button) {
8657 case 1: {
8658 NSString *href = [[alert textField] text];
8659 href = VerifySource(href);
8660 if (href == nil)
8661 break;
8662 href_ = href;
8663
8664 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8665 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8666
8667 cydia_ = false;
8668
8669 // XXX: this is stupid
8670 hud_ = [delegate_ addProgressHUD];
8671 [hud_ setText:UCLocalize("VERIFYING_URL")];
8672 [delegate_ retainNetworkActivityIndicator];
8673 } break;
8674
8675 case 0:
8676 break;
8677
8678 _nodefault
8679 }
8680
8681 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8682 } else if ([context isEqualToString:@"trivial"])
8683 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8684 else if ([context isEqualToString:@"urlerror"])
8685 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8686 else if ([context isEqualToString:@"warning"]) {
8687 switch (button) {
8688 case 1:
8689 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8690 break;
8691
8692 case 0:
8693 break;
8694
8695 _nodefault
8696 }
8697
8698 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8699 }
8700 }
8701
8702 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8703 BOOL editing([list_ isEditing]);
8704
8705 if (editing)
8706 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8707 initWithTitle:UCLocalize("ADD")
8708 style:UIBarButtonItemStylePlain
8709 target:self
8710 action:@selector(addButtonClicked)
8711 ] autorelease] animated:animated];
8712 else if ([delegate_ updating])
8713 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8714 initWithTitle:UCLocalize("CANCEL")
8715 style:UIBarButtonItemStyleDone
8716 target:self
8717 action:@selector(cancelButtonClicked)
8718 ] autorelease] animated:animated];
8719 else
8720 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8721 initWithTitle:UCLocalize("REFRESH")
8722 style:UIBarButtonItemStylePlain
8723 target:self
8724 action:@selector(refreshButtonClicked)
8725 ] autorelease] animated:animated];
8726
8727 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8728 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8729 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8730 target:self
8731 action:@selector(editButtonClicked)
8732 ] autorelease] animated:animated];
8733 }
8734
8735 - (void) loadView {
8736 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8737 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8738 [list_ setRowHeight:53];
8739 [(UITableView *) list_ setDataSource:self];
8740 [list_ setDelegate:self];
8741 [self setView:list_];
8742 }
8743
8744 - (void) viewDidLoad {
8745 [super viewDidLoad];
8746
8747 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8748 [self updateButtonsForEditingStatusAnimated:NO];
8749 }
8750
8751 - (void) viewWillAppear:(BOOL)animated {
8752 [super viewWillAppear:animated];
8753
8754 [list_ setEditing:NO];
8755 [self updateButtonsForEditingStatusAnimated:NO];
8756 }
8757
8758 - (void) releaseSubviews {
8759 list_ = nil;
8760
8761 sources_ = nil;
8762
8763 [super releaseSubviews];
8764 }
8765
8766 - (id) initWithDatabase:(Database *)database {
8767 if ((self = [super init]) != nil) {
8768 database_ = database;
8769 } return self;
8770 }
8771
8772 - (void) reloadData {
8773 [super reloadData];
8774 [self updateButtonsForEditingStatusAnimated:YES];
8775
8776 @synchronized (database_) {
8777 era_ = [database_ era];
8778
8779 sources_ = [NSMutableArray arrayWithCapacity:16];
8780 [sources_ addObjectsFromArray:[database_ sources]];
8781 _trace();
8782 [sources_ sortUsingSelector:@selector(compareByName:)];
8783 _trace();
8784
8785 int count([sources_ count]);
8786 offset_ = 0;
8787 for (int i = 0; i != count; i++) {
8788 if ([[sources_ objectAtIndex:i] record] == nil)
8789 break;
8790 offset_++;
8791 }
8792
8793 [list_ reloadData];
8794 } }
8795
8796 - (void) showAddSourcePrompt {
8797 UIAlertView *alert = [[[UIAlertView alloc]
8798 initWithTitle:UCLocalize("ENTER_APT_URL")
8799 message:nil
8800 delegate:self
8801 cancelButtonTitle:UCLocalize("CANCEL")
8802 otherButtonTitles:
8803 UCLocalize("ADD_SOURCE"),
8804 nil
8805 ] autorelease];
8806
8807 [alert setContext:@"source"];
8808
8809 [alert setNumberOfRows:1];
8810 [alert addTextFieldWithValue:@"http://" label:@""];
8811
8812 UITextInputTraits *traits = [[alert textField] textInputTraits];
8813 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8814 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8815 [traits setKeyboardType:UIKeyboardTypeURL];
8816 // XXX: UIReturnKeyDone
8817 [traits setReturnKeyType:UIReturnKeyNext];
8818
8819 [alert show];
8820 }
8821
8822 - (void) addButtonClicked {
8823 [self showAddSourcePrompt];
8824 }
8825
8826 - (void) refreshButtonClicked {
8827 if ([delegate_ requestUpdate])
8828 [self updateButtonsForEditingStatusAnimated:YES];
8829 }
8830
8831 - (void) cancelButtonClicked {
8832 [delegate_ cancelUpdate];
8833 }
8834
8835 - (void) editButtonClicked {
8836 [list_ setEditing:![list_ isEditing] animated:YES];
8837 [self updateButtonsForEditingStatusAnimated:YES];
8838 }
8839
8840 @end
8841 /* }}} */
8842
8843 /* Stash Controller {{{ */
8844 @interface StashController : CyteViewController {
8845 _H<UIActivityIndicatorView> spinner_;
8846 _H<UILabel> status_;
8847 _H<UILabel> caption_;
8848 }
8849
8850 @end
8851
8852 @implementation StashController
8853
8854 - (void) loadView {
8855 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8856 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8857 [self setView:view];
8858
8859 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8860
8861 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8862 CGRect spinrect = [spinner_ frame];
8863 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8864 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8865 [spinner_ setFrame:spinrect];
8866 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8867 [view addSubview:spinner_];
8868 [spinner_ startAnimating];
8869
8870 CGRect captrect;
8871 captrect.size.width = [[self view] frame].size.width;
8872 captrect.size.height = 40.0f;
8873 captrect.origin.x = 0;
8874 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8875 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8876 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8877 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8878 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8879 [caption_ setTextColor:[UIColor whiteColor]];
8880 [caption_ setBackgroundColor:[UIColor clearColor]];
8881 [caption_ setShadowColor:[UIColor blackColor]];
8882 [caption_ setTextAlignment:NSTextAlignmentCenter];
8883 [view addSubview:caption_];
8884
8885 CGRect statusrect;
8886 statusrect.size.width = [[self view] frame].size.width;
8887 statusrect.size.height = 30.0f;
8888 statusrect.origin.x = 0;
8889 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8890 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8891 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8892 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8893 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8894 [status_ setTextColor:[UIColor whiteColor]];
8895 [status_ setBackgroundColor:[UIColor clearColor]];
8896 [status_ setShadowColor:[UIColor blackColor]];
8897 [status_ setTextAlignment:NSTextAlignmentCenter];
8898 [view addSubview:status_];
8899 }
8900
8901 - (void) releaseSubviews {
8902 spinner_ = nil;
8903 status_ = nil;
8904 caption_ = nil;
8905
8906 [super releaseSubviews];
8907 }
8908
8909 @end
8910 /* }}} */
8911
8912 @interface CYURLCache : SDURLCache {
8913 }
8914
8915 @end
8916
8917 @implementation CYURLCache
8918
8919 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8920 #if !ForRelease
8921 if (false);
8922 else if ([event isEqualToString:@"no-cache"])
8923 event = @"!!!";
8924 else if ([event isEqualToString:@"store"])
8925 event = @">>>";
8926 else if ([event isEqualToString:@"invalid"])
8927 event = @"???";
8928 else if ([event isEqualToString:@"memory"])
8929 event = @"mem";
8930 else if ([event isEqualToString:@"disk"])
8931 event = @"ssd";
8932 else if ([event isEqualToString:@"miss"])
8933 event = @"---";
8934
8935 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8936 #endif
8937 }
8938
8939 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8940 if (NSURLResponse *response = [cached response])
8941 if (NSString *mime = [response MIMEType])
8942 if ([mime isEqualToString:@"text/cache-manifest"]) {
8943 NSURL *url([response URL]);
8944
8945 #if !ForRelease
8946 NSLog(@"###: %@", [url absoluteString]);
8947 #endif
8948
8949 @synchronized (HostConfig_) {
8950 [CachedURLs_ addObject:url];
8951 }
8952 }
8953
8954 [super storeCachedResponse:cached forRequest:request];
8955 }
8956
8957 - (void) createDiskCachePath {
8958 [super createDiskCachePath];
8959 }
8960
8961 @end
8962
8963 @interface Cydia : UIApplication <
8964 ConfirmationControllerDelegate,
8965 DatabaseDelegate,
8966 CydiaDelegate
8967 > {
8968 _H<UIWindow> window_;
8969 _H<CydiaTabBarController> tabbar_;
8970 _H<CyteTabBarController> emulated_;
8971 _H<AppCacheController> appcache_;
8972
8973 _H<NSMutableArray> essential_;
8974 _H<NSMutableArray> broken_;
8975
8976 Database *database_;
8977
8978 _H<NSURL> starturl_;
8979
8980 unsigned locked_;
8981 unsigned activity_;
8982
8983 _H<StashController> stash_;
8984
8985 bool loaded_;
8986 }
8987
8988 - (void) loadData;
8989
8990 @end
8991
8992 @implementation Cydia
8993
8994 - (void) lockSuspend {
8995 if (locked_++ == 0) {
8996 if ($SBSSetInterceptsMenuButtonForever != NULL)
8997 (*$SBSSetInterceptsMenuButtonForever)(true);
8998
8999 [self setIdleTimerDisabled:YES];
9000 }
9001 }
9002
9003 - (void) unlockSuspend {
9004 if (--locked_ == 0) {
9005 [self setIdleTimerDisabled:NO];
9006
9007 if ($SBSSetInterceptsMenuButtonForever != NULL)
9008 (*$SBSSetInterceptsMenuButtonForever)(false);
9009 }
9010 }
9011
9012 - (void) beginUpdate {
9013 [tabbar_ beginUpdate];
9014 }
9015
9016 - (void) cancelUpdate {
9017 [tabbar_ cancelUpdate];
9018 }
9019
9020 - (bool) requestUpdate {
9021 if (IsReachable("cydia.saurik.com")) {
9022 [self beginUpdate];
9023 return true;
9024 } else {
9025 UIAlertView *alert = [[[UIAlertView alloc]
9026 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9027 message:@"Host Unreachable" // XXX: Localize
9028 delegate:self
9029 cancelButtonTitle:UCLocalize("OK")
9030 otherButtonTitles:nil
9031 ] autorelease];
9032
9033 [alert setContext:@"norefresh"];
9034 [alert show];
9035
9036 return false;
9037 }
9038 }
9039
9040 - (BOOL) updating {
9041 return [tabbar_ updating];
9042 }
9043
9044 - (void) _loaded {
9045 if ([broken_ count] != 0) {
9046 int count = [broken_ count];
9047
9048 UIAlertView *alert = [[[UIAlertView alloc]
9049 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9050 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9051 delegate:self
9052 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9053 otherButtonTitles:
9054 UCLocalize("TEMPORARY_IGNORE"),
9055 nil
9056 ] autorelease];
9057
9058 [alert setContext:@"fixhalf"];
9059 [alert setNumberOfRows:2];
9060 [alert show];
9061 } else if (!Ignored_ && [essential_ count] != 0) {
9062 int count = [essential_ count];
9063
9064 UIAlertView *alert = [[[UIAlertView alloc]
9065 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9066 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9067 delegate:self
9068 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9069 otherButtonTitles:
9070 UCLocalize("UPGRADE_ESSENTIAL"),
9071 UCLocalize("COMPLETE_UPGRADE"),
9072 nil
9073 ] autorelease];
9074
9075 [alert setContext:@"upgrade"];
9076 [alert show];
9077 }
9078 }
9079
9080 - (void) returnToCydia {
9081 [self _loaded];
9082 }
9083
9084 - (void) reloadSpringBoard {
9085 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9086 system("/bin/launchctl stop com.apple.backboardd");
9087 else
9088 system("/bin/launchctl stop com.apple.SpringBoard");
9089 sleep(15);
9090 system("/usr/bin/killall backboardd SpringBoard");
9091 }
9092
9093 - (void) _saveConfig {
9094 SaveConfig(database_);
9095 }
9096
9097 // Navigation controller for the queuing badge.
9098 - (UINavigationController *) queueNavigationController {
9099 NSArray *controllers = [tabbar_ viewControllers];
9100 return [controllers objectAtIndex:3];
9101 }
9102
9103 - (void) unloadData {
9104 [tabbar_ unloadData];
9105 }
9106
9107 - (void) _updateData {
9108 [self _saveConfig];
9109 [self unloadData];
9110
9111 UINavigationController *navigation = [self queueNavigationController];
9112
9113 id queuedelegate = nil;
9114 if ([[navigation viewControllers] count] > 0)
9115 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9116
9117 [queuedelegate queueStatusDidChange];
9118 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9119 }
9120
9121 - (void) _refreshIfPossible {
9122 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9123
9124 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9125
9126 bool recently = false;
9127 if (update != nil) {
9128 NSTimeInterval interval([update timeIntervalSinceNow]);
9129 if (interval > -(15*60))
9130 recently = true;
9131 }
9132
9133 // Don't automatic refresh if:
9134 // - We already refreshed recently.
9135 // - We already auto-refreshed this launch.
9136 // - Auto-refresh is disabled.
9137 // - Cydia's server is not reachable
9138 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9139 // If we are cancelling, we need to make sure it knows it's already loaded.
9140 loaded_ = true;
9141
9142 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9143 } else {
9144 // We are going to load, so remember that.
9145 loaded_ = true;
9146
9147 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9148 }
9149
9150 [pool release];
9151 }
9152
9153 - (void) refreshIfPossible {
9154 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9155 }
9156
9157 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9158 _profile(reloadDataWithInvocation)
9159 @synchronized (self) {
9160 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9161 if (hud != nil)
9162 [hud setText:UCLocalize("RELOADING_DATA")];
9163
9164 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9165
9166 size_t changes(0);
9167
9168 [essential_ removeAllObjects];
9169 [broken_ removeAllObjects];
9170
9171 _profile(reloadDataWithInvocation$Essential)
9172 NSArray *packages([database_ packages]);
9173 for (Package *package in packages) {
9174 if ([package half])
9175 [broken_ addObject:package];
9176 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9177 if ([package essential] && [package installed] != nil)
9178 [essential_ addObject:package];
9179 ++changes;
9180 }
9181 }
9182 _end
9183
9184 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9185 if (changes != 0) {
9186 _trace();
9187 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9188 [changesItem setBadgeValue:badge];
9189 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9190 [self setApplicationIconBadgeNumber:changes];
9191 } else {
9192 _trace();
9193 [changesItem setBadgeValue:nil];
9194 [changesItem setAnimatedBadge:NO];
9195 [self setApplicationIconBadgeNumber:0];
9196 }
9197
9198 Queuing_ = false;
9199 [self _updateData];
9200
9201 if (hud != nil)
9202 [self removeProgressHUD:hud];
9203 }
9204 _end
9205
9206 PrintTimes();
9207 }
9208
9209 - (void) updateData {
9210 [self _updateData];
9211 }
9212
9213 - (void) updateDataAndLoad {
9214 [self _updateData];
9215 if ([database_ progressDelegate] == nil)
9216 [self _loaded];
9217 }
9218
9219 - (void) update_ {
9220 [database_ update];
9221 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9222 }
9223
9224 - (void) disemulate {
9225 if (emulated_ == nil)
9226 return;
9227
9228 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9229 [window_ setRootViewController:tabbar_];
9230 else {
9231 [window_ addSubview:[tabbar_ view]];
9232 [[emulated_ view] removeFromSuperview];
9233 }
9234
9235 emulated_ = nil;
9236 [window_ setUserInteractionEnabled:YES];
9237 }
9238
9239 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9240 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9241
9242 UIViewController *parent;
9243 if (emulated_ == nil)
9244 parent = tabbar_;
9245 else if (!force)
9246 parent = emulated_;
9247 else {
9248 [self disemulate];
9249 parent = tabbar_;
9250 }
9251
9252 if (IsWildcat_)
9253 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9254 [parent presentModalViewController:navigation animated:YES];
9255 }
9256
9257 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9258 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9259
9260 if (navigation != nil)
9261 [navigation pushViewController:progress animated:YES];
9262 else
9263 [self presentModalViewController:progress force:YES];
9264
9265 [progress invoke:invocation withTitle:title];
9266 return progress;
9267 }
9268
9269 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9270 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9271 }
9272
9273 - (void) repairWithInvocation:(NSInvocation *)invocation {
9274 _trace();
9275 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9276 _trace();
9277 }
9278
9279 - (void) repairWithSelector:(SEL)selector {
9280 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9281 }
9282
9283 - (void) reloadData {
9284 [self reloadDataWithInvocation:nil];
9285 if ([database_ progressDelegate] == nil)
9286 [self _loaded];
9287 }
9288
9289 - (void) syncData {
9290 [self _saveConfig];
9291 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9292 }
9293
9294 - (void) addSource:(NSDictionary *) source {
9295 CydiaAddSource(source);
9296 }
9297
9298 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9299 CydiaAddSource(href, distribution, sections);
9300 }
9301
9302 // XXX: this method should not return anything
9303 - (BOOL) addTrivialSource:(NSString *)href {
9304 CydiaAddSource(href, @"./");
9305 return YES;
9306 }
9307
9308 - (void) resolve {
9309 pkgProblemResolver *resolver = [database_ resolver];
9310
9311 resolver->InstallProtect();
9312 if (!resolver->Resolve(true))
9313 _error->Discard();
9314 }
9315
9316 - (bool) perform {
9317 // XXX: this is a really crappy way of doing this.
9318 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9319 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9320 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9321 if ([tabbar_ updating])
9322 [tabbar_ cancelUpdate];
9323
9324 if (![database_ prepare])
9325 return false;
9326
9327 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9328 [page setDelegate:self];
9329 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9330
9331 if (IsWildcat_)
9332 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9333 [tabbar_ presentModalViewController:confirm_ animated:YES];
9334
9335 return true;
9336 }
9337
9338 - (void) queue {
9339 @synchronized (self) {
9340 [self perform];
9341 }
9342 }
9343
9344 - (void) clearPackage:(Package *)package {
9345 @synchronized (self) {
9346 [package clear];
9347 [self resolve];
9348 [self perform];
9349 }
9350 }
9351
9352 - (void) installPackages:(NSArray *)packages {
9353 @synchronized (self) {
9354 for (Package *package in packages)
9355 [package install];
9356 [self resolve];
9357 [self perform];
9358 }
9359 }
9360
9361 - (void) installPackage:(Package *)package {
9362 @synchronized (self) {
9363 [package install];
9364 [self resolve];
9365 [self perform];
9366 }
9367 }
9368
9369 - (void) removePackage:(Package *)package {
9370 @synchronized (self) {
9371 [package remove];
9372 [self resolve];
9373 [self perform];
9374 }
9375 }
9376
9377 - (void) distUpgrade {
9378 @synchronized (self) {
9379 if (![database_ upgrade])
9380 return;
9381 [self perform];
9382 }
9383 }
9384
9385 - (void) _uicache {
9386 _trace();
9387 system("/usr/bin/uicache");
9388 _trace();
9389 }
9390
9391 - (void) uicache {
9392 UIProgressHUD *hud([self addProgressHUD]);
9393 [hud setText:UCLocalize("LOADING")];
9394 [self yieldToSelector:@selector(_uicache)];
9395 [self removeProgressHUD:hud];
9396 }
9397
9398 - (void) perform_ {
9399 [database_ perform];
9400 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9401 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9402 }
9403
9404 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9405 Queuing_ = false;
9406 [self lockSuspend];
9407 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9408 [self unlockSuspend];
9409 }
9410
9411 - (void) retainNetworkActivityIndicator {
9412 if (activity_++ == 0)
9413 [self setNetworkActivityIndicatorVisible:YES];
9414
9415 #if TraceLogging
9416 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9417 #endif
9418 }
9419
9420 - (void) releaseNetworkActivityIndicator {
9421 if (--activity_ == 0)
9422 [self setNetworkActivityIndicatorVisible:NO];
9423
9424 #if TraceLogging
9425 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9426 #endif
9427
9428 }
9429
9430 - (void) cancelAndClear:(bool)clear {
9431 @synchronized (self) {
9432 if (clear) {
9433 [database_ clear];
9434 Queuing_ = false;
9435 } else {
9436 Queuing_ = true;
9437 }
9438
9439 [self _updateData];
9440 }
9441 }
9442
9443 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9444 NSString *context([alert context]);
9445
9446 if ([context isEqualToString:@"conffile"]) {
9447 FILE *input = [database_ input];
9448 if (button == [alert cancelButtonIndex])
9449 fprintf(input, "N\n");
9450 else if (button == [alert firstOtherButtonIndex])
9451 fprintf(input, "Y\n");
9452 fflush(input);
9453
9454 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9455 } else if ([context isEqualToString:@"fixhalf"]) {
9456 if (button == [alert cancelButtonIndex]) {
9457 @synchronized (self) {
9458 for (Package *broken in (id) broken_) {
9459 [broken remove];
9460 NSString *id(ShellEscape([broken id]));
9461 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9462 " /var/lib/dpkg/info/%@.prerm"
9463 " /var/lib/dpkg/info/%@.postrm"
9464 " /var/lib/dpkg/info/%@.preinst"
9465 " /var/lib/dpkg/info/%@.postinst"
9466 " /var/lib/dpkg/info/%@.extrainst_"
9467 "", id, id, id, id, id] UTF8String]);
9468 }
9469
9470 [self resolve];
9471 [self perform];
9472 }
9473 } else if (button == [alert firstOtherButtonIndex]) {
9474 [broken_ removeAllObjects];
9475 [self _loaded];
9476 }
9477
9478 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9479 } else if ([context isEqualToString:@"upgrade"]) {
9480 if (button == [alert firstOtherButtonIndex]) {
9481 @synchronized (self) {
9482 for (Package *essential in (id) essential_)
9483 [essential install];
9484
9485 [self resolve];
9486 [self perform];
9487 }
9488 } else if (button == [alert firstOtherButtonIndex] + 1) {
9489 [self distUpgrade];
9490 } else if (button == [alert cancelButtonIndex]) {
9491 Ignored_ = YES;
9492 }
9493
9494 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9495 }
9496 }
9497
9498 - (void) system:(NSString *)command {
9499 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9500
9501 _trace();
9502 system([command UTF8String]);
9503 _trace();
9504
9505 [pool release];
9506 }
9507
9508 - (void) applicationWillSuspend {
9509 [database_ clean];
9510 [super applicationWillSuspend];
9511 }
9512
9513 - (BOOL) isSafeToSuspend {
9514 if (locked_ != 0) {
9515 #if !ForRelease
9516 NSLog(@"isSafeToSuspend: locked_ != 0");
9517 #endif
9518 return false;
9519 }
9520
9521 if ([tabbar_ modalViewController] != nil)
9522 return false;
9523
9524 // Use external process status API internally.
9525 // This is probably a really bad idea.
9526 // XXX: what is the point of this? does this solve anything at all?
9527 uint64_t status = 0;
9528 int notify_token;
9529 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9530 notify_get_state(notify_token, &status);
9531 notify_cancel(notify_token);
9532 }
9533
9534 if (status != 0) {
9535 #if !ForRelease
9536 NSLog(@"isSafeToSuspend: status != 0");
9537 #endif
9538 return false;
9539 }
9540
9541 #if !ForRelease
9542 NSLog(@"isSafeToSuspend: -> true");
9543 #endif
9544 return true;
9545 }
9546
9547 - (void) suspendReturningToLastApp:(BOOL)returning {
9548 if ([self isSafeToSuspend])
9549 [super suspendReturningToLastApp:returning];
9550 }
9551
9552 - (void) suspend {
9553 if ([self isSafeToSuspend])
9554 [super suspend];
9555 }
9556
9557 - (void) applicationSuspend {
9558 if ([self isSafeToSuspend])
9559 [super applicationSuspend];
9560 }
9561
9562 - (void) applicationSuspend:(__GSEvent *)event {
9563 if ([self isSafeToSuspend])
9564 [super applicationSuspend:event];
9565 }
9566
9567 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9568 if ([self isSafeToSuspend])
9569 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9570 }
9571
9572 - (void) _setSuspended:(BOOL)value {
9573 if ([self isSafeToSuspend])
9574 [super _setSuspended:value];
9575 }
9576
9577 - (UIProgressHUD *) addProgressHUD {
9578 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9579 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9580
9581 [window_ setUserInteractionEnabled:NO];
9582
9583 UIViewController *target(tabbar_);
9584 if (UIViewController *modal = [target modalViewController])
9585 target = modal;
9586
9587 [hud showInView:[target view]];
9588
9589 [self lockSuspend];
9590 return hud;
9591 }
9592
9593 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9594 [self unlockSuspend];
9595 [hud hide];
9596 [hud removeFromSuperview];
9597 [window_ setUserInteractionEnabled:YES];
9598 }
9599
9600 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9601 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9602 }
9603
9604 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9605 NSString *scheme([[url scheme] lowercaseString]);
9606 if ([[url absoluteString] length] <= [scheme length] + 3)
9607 return nil;
9608 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9609 NSArray *components([path componentsSeparatedByString:@"/"]);
9610
9611 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9612 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9613 if (controller != nil)
9614 [controller setDelegate:self];
9615 return controller;
9616 }
9617
9618 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9619 return nil;
9620
9621 NSString *base([components objectAtIndex:0]);
9622
9623 CyteViewController *controller = nil;
9624
9625 if ([base isEqualToString:@"url"]) {
9626 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9627 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9628 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9629 } else if (!external && [components count] == 1) {
9630 if ([base isEqualToString:@"sources"]) {
9631 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9632 }
9633
9634 if ([base isEqualToString:@"home"]) {
9635 controller = [[[HomeController alloc] init] autorelease];
9636 }
9637
9638 if ([base isEqualToString:@"sections"]) {
9639 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9640 }
9641
9642 if ([base isEqualToString:@"search"]) {
9643 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9644 }
9645
9646 if ([base isEqualToString:@"changes"]) {
9647 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9648 }
9649
9650 if ([base isEqualToString:@"installed"]) {
9651 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9652 }
9653 } else if ([components count] == 2) {
9654 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9655
9656 if ([base isEqualToString:@"package"]) {
9657 controller = [self pageForPackage:argument withReferrer:referrer];
9658 }
9659
9660 if (!external && [base isEqualToString:@"search"]) {
9661 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9662 }
9663
9664 if (!external && [base isEqualToString:@"sections"]) {
9665 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9666 argument = nil;
9667 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9668 }
9669
9670 if ([base isEqualToString:@"sources"]) {
9671 if ([argument isEqualToString:@"add"]) {
9672 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9673 [(SourcesController *)controller showAddSourcePrompt];
9674 } else {
9675 Source *source([database_ sourceWithKey:argument]);
9676 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9677 }
9678 }
9679
9680 if (!external && [base isEqualToString:@"launch"]) {
9681 [self launchApplicationWithIdentifier:argument suspended:NO];
9682 return nil;
9683 }
9684 } else if (!external && [components count] == 3) {
9685 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9686 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9687
9688 if ([base isEqualToString:@"package"]) {
9689 if ([arg2 isEqualToString:@"settings"]) {
9690 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9691 } else if ([arg2 isEqualToString:@"files"]) {
9692 if (Package *package = [database_ packageWithName:arg1]) {
9693 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9694 [(FileTable *)controller setPackage:package];
9695 }
9696 }
9697 }
9698
9699 if ([base isEqualToString:@"sections"]) {
9700 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9701 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9702 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9703 }
9704 }
9705
9706 [controller setDelegate:self];
9707 return controller;
9708 }
9709
9710 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9711 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9712
9713 if (page != nil)
9714 [tabbar_ setUnselectedViewController:page];
9715
9716 return page != nil;
9717 }
9718
9719 - (void) applicationOpenURL:(NSURL *)url {
9720 [super applicationOpenURL:url];
9721
9722 if (!loaded_)
9723 starturl_ = url;
9724 else
9725 [self openCydiaURL:url forExternal:YES];
9726 }
9727
9728 - (void) applicationWillResignActive:(UIApplication *)application {
9729 // Stop refreshing if you get a phone call or lock the device.
9730 if ([tabbar_ updating])
9731 [tabbar_ cancelUpdate];
9732
9733 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9734 [super applicationWillResignActive:application];
9735 }
9736
9737 - (void) saveState {
9738 [[NSDictionary dictionaryWithObjectsAndKeys:
9739 @"InterfaceState", [tabbar_ navigationURLCollection],
9740 @"LastClosed", [NSDate date],
9741 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9742 nil] writeToFile:@ SavedState_ atomically:YES];
9743
9744 [self _saveConfig];
9745 }
9746
9747 - (void) applicationWillTerminate:(UIApplication *)application {
9748 [self saveState];
9749 }
9750
9751 - (void) applicationDidEnterBackground:(UIApplication *)application {
9752 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9753 return [self terminateWithSuccess];
9754 Backgrounded_ = [NSDate date];
9755 [self saveState];
9756 }
9757
9758 - (void) applicationWillEnterForeground:(UIApplication *)application {
9759 if (Backgrounded_ == nil)
9760 return;
9761
9762 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9763
9764 if (interval <= -(30*60)) {
9765 [tabbar_ setSelectedIndex:0];
9766 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9767 }
9768
9769 if (interval <= -(15*60)) {
9770 if (IsReachable("cydia.saurik.com")) {
9771 [tabbar_ beginUpdate];
9772 [appcache_ reloadURLWithCache:YES];
9773 }
9774 }
9775
9776 if ([database_ delocked])
9777 [self reloadData];
9778 }
9779
9780 - (void) setConfigurationData:(NSString *)data {
9781 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9782
9783 if (!conffile_r(data)) {
9784 lprintf("E:invalid conffile\n");
9785 return;
9786 }
9787
9788 NSString *ofile = conffile_r[1];
9789 //NSString *nfile = conffile_r[2];
9790
9791 UIAlertView *alert = [[[UIAlertView alloc]
9792 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9793 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9794 delegate:self
9795 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9796 otherButtonTitles:
9797 UCLocalize("ACCEPT_NEW_COPY"),
9798 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9799 nil
9800 ] autorelease];
9801
9802 [alert setContext:@"conffile"];
9803 [alert setNumberOfRows:2];
9804 [alert show];
9805 }
9806
9807 - (void) addStashController {
9808 [self lockSuspend];
9809 stash_ = [[[StashController alloc] init] autorelease];
9810 [window_ addSubview:[stash_ view]];
9811 }
9812
9813 - (void) removeStashController {
9814 [[stash_ view] removeFromSuperview];
9815 stash_ = nil;
9816 [self unlockSuspend];
9817 }
9818
9819 - (void) stash {
9820 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9821 UpdateExternalStatus(1);
9822 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9823 UpdateExternalStatus(0);
9824
9825 [self removeStashController];
9826 [self reloadSpringBoard];
9827 }
9828
9829 - (void) setupViewControllers {
9830 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9831
9832 NSMutableArray *items;
9833 if (kCFCoreFoundationVersionNumber < 800) {
9834 items = [NSMutableArray arrayWithObjects:
9835 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9836 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9837 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9838 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9839 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9840 nil];
9841 } else {
9842 items = [NSMutableArray arrayWithObjects:
9843 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9844 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9845 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9846 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9847 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9848 nil];
9849 }
9850
9851 NSMutableArray *controllers([NSMutableArray array]);
9852 for (UITabBarItem *item in items) {
9853 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9854 [controller setTabBarItem:item];
9855 [controllers addObject:controller];
9856 }
9857 [tabbar_ setViewControllers:controllers];
9858
9859 [tabbar_ setUpdateDelegate:self];
9860 }
9861
9862 - (void) _sendMemoryWarningNotification {
9863 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9864 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9865 else
9866 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9867 }
9868
9869 - (void) _sendMemoryWarningNotifications {
9870 while (true) {
9871 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9872 sleep(2);
9873 //usleep(2000000);
9874 }
9875 }
9876
9877 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9878 NSLog(@"--");
9879 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9880 }
9881
9882 - (void) applicationDidFinishLaunching:(id)unused {
9883 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9884
9885 _trace();
9886 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9887 [self setApplicationSupportsShakeToEdit:NO];
9888
9889 @synchronized (HostConfig_) {
9890 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9891 }
9892
9893 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9894 initWithMemoryCapacity:524288
9895 diskCapacity:10485760
9896 diskPath:Cache("SDURLCache")
9897 ] autorelease]];
9898
9899 [CydiaWebViewController _initialize];
9900
9901 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9902
9903 // this would disallow http{,s} URLs from accessing this data
9904 //[WebView registerURLSchemeAsLocal:@"cydia"];
9905
9906 Font12_ = [UIFont systemFontOfSize:12];
9907 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9908 Font14_ = [UIFont systemFontOfSize:14];
9909 Font18_ = [UIFont systemFontOfSize:18];
9910 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9911 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9912
9913 essential_ = [NSMutableArray arrayWithCapacity:4];
9914 broken_ = [NSMutableArray arrayWithCapacity:4];
9915
9916 // XXX: I really need this thing... like, seriously... I'm sorry
9917 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9918 [appcache_ reloadData];
9919
9920 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9921 [window_ orderFront:self];
9922 [window_ makeKey:self];
9923 [window_ setHidden:NO];
9924
9925 if (access("/.cydia_no_stash", F_OK) == 0);
9926 else {
9927
9928 if (false) stash: {
9929 [self addStashController];
9930 // XXX: this would be much cleaner as a yieldToSelector:
9931 // that way the removeStashController could happen right here inline
9932 // we also could no longer require the useless stash_ field anymore
9933 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9934 return;
9935 }
9936
9937 struct stat root;
9938 int error(stat("/", &root));
9939 _assert(error != -1);
9940
9941 #define Stash_(path) do { \
9942 struct stat folder; \
9943 int error(lstat((path), &folder)); \
9944 if (error != -1 && ( \
9945 folder.st_dev == root.st_dev && \
9946 S_ISDIR(folder.st_mode) \
9947 ) || error == -1 && ( \
9948 errno == ENOENT || \
9949 errno == ENOTDIR \
9950 )) goto stash; \
9951 } while (false)
9952
9953 Stash_("/Applications");
9954 Stash_("/Library/Ringtones");
9955 Stash_("/Library/Wallpaper");
9956 //Stash_("/usr/bin");
9957 Stash_("/usr/include");
9958 Stash_("/usr/share");
9959 //Stash_("/var/lib");
9960
9961 }
9962
9963 database_ = [Database sharedInstance];
9964 [database_ setDelegate:self];
9965
9966 [window_ setUserInteractionEnabled:NO];
9967 [self setupViewControllers];
9968
9969 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9970 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9971 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9972
9973 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9974 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9975 [emulated_ setSelectedIndex:0];
9976
9977 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9978 [emulated_ concealTabBarSelection];
9979
9980 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9981 [window_ setRootViewController:emulated_];
9982 else
9983 [window_ addSubview:[emulated_ view]];
9984
9985 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9986 _trace();
9987 }
9988
9989 - (NSArray *) defaultStartPages {
9990 NSMutableArray *standard = [NSMutableArray array];
9991 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9992 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9993 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9994 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9995 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9996 return standard;
9997 }
9998
9999 - (void) loadData {
10000 _trace();
10001 if ([emulated_ modalViewController] != nil)
10002 [emulated_ dismissModalViewControllerAnimated:YES];
10003 [window_ setUserInteractionEnabled:NO];
10004
10005 [self reloadDataWithInvocation:nil];
10006 [self refreshIfPossible];
10007 [self disemulate];
10008
10009 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10010
10011 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10012 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10013 int standardIndex = 0;
10014 NSArray *standard = [self defaultStartPages];
10015
10016 BOOL valid = YES;
10017
10018 if (saved == nil)
10019 valid = NO;
10020
10021 NSDate *closed = [state objectForKey:@"LastClosed"];
10022 if (valid && closed != nil) {
10023 NSTimeInterval interval([closed timeIntervalSinceNow]);
10024 if (interval <= -(30*60))
10025 valid = NO;
10026 }
10027
10028 if (valid && [saved count] != [standard count])
10029 valid = NO;
10030
10031 if (valid) {
10032 for (unsigned int i = 0; i < [standard count]; i++) {
10033 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10034 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10035 // but it's good enough for now.
10036 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10037 valid = NO;
10038 break;
10039 }
10040 }
10041 }
10042
10043 NSArray *items = nil;
10044 if (valid) {
10045 [tabbar_ setSelectedIndex:savedIndex];
10046 items = saved;
10047 } else {
10048 [tabbar_ setSelectedIndex:standardIndex];
10049 items = standard;
10050 }
10051
10052 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10053 NSArray *stack = [items objectAtIndex:tab];
10054 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10055 NSMutableArray *current = [NSMutableArray array];
10056
10057 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10058 NSString *addr = [stack objectAtIndex:nav];
10059 NSURL *url = [NSURL URLWithString:addr];
10060 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10061 if (page != nil)
10062 [current addObject:page];
10063 }
10064
10065 [navigation setViewControllers:current];
10066 }
10067
10068 // (Try to) show the startup URL.
10069 if (starturl_ != nil) {
10070 [self openCydiaURL:starturl_ forExternal:YES];
10071 starturl_ = nil;
10072 }
10073 }
10074
10075 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10076 if (!IsWildcat_) {
10077 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10078 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10079 }
10080
10081 if (item != nil && IsWildcat_) {
10082 [sheet showFromBarButtonItem:item animated:YES];
10083 } else {
10084 [sheet showInView:window_];
10085 }
10086 }
10087
10088 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10089 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10090 [progress setTitle:task];
10091 [progress addProgressEvent:event];
10092 }
10093
10094 - (void) addProgressEventForTask:(NSArray *)data {
10095 CydiaProgressEvent *event([data objectAtIndex:0]);
10096 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10097 [self addProgressEvent:event forTask:task];
10098 }
10099
10100 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10101 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10102 }
10103
10104 @end
10105
10106 /*IMP alloc_;
10107 id Alloc_(id self, SEL selector) {
10108 id object = alloc_(self, selector);
10109 lprintf("[%s]A-%p\n", self->isa->name, object);
10110 return object;
10111 }*/
10112
10113 /*IMP dealloc_;
10114 id Dealloc_(id self, SEL selector) {
10115 id object = dealloc_(self, selector);
10116 lprintf("[%s]D-%p\n", self->isa->name, object);
10117 return object;
10118 }*/
10119
10120 Class $NSURLConnection;
10121
10122 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10123 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10124
10125 NSURL *url([copy URL]);
10126
10127 NSString *host([url host]);
10128 NSString *scheme([[url scheme] lowercaseString]);
10129
10130 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10131
10132 @synchronized (HostConfig_) {
10133 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10134 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10135 [copy setHTTPShouldUsePipelining:YES];
10136
10137 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10138 if ([control isEqualToString:@"max-age=0"])
10139 if ([CachedURLs_ containsObject:url]) {
10140 #if !ForRelease
10141 NSLog(@"~~~: %@", url);
10142 #endif
10143
10144 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10145
10146 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10147 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10148 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10149 }
10150 }
10151
10152 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10153 } return self;
10154 }
10155
10156 Class $WAKWindow;
10157
10158 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10159 CGSize size([[UIScreen mainScreen] bounds].size);
10160 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10161 if ([$WAKWindow hasLandscapeOrientation])
10162 std::swap(size.width, size.height);*/
10163 return size;
10164 }
10165
10166 Class $NSUserDefaults;
10167
10168 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10169 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10170 return Cache("LocalStorage");
10171 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10172 }
10173
10174 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10175 if (type == NULL)
10176 return nil;
10177 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10178 return nil;
10179 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10180 CFRelease(type);
10181 return [(NSMutableDictionary *) copy autorelease];
10182 }
10183
10184 int main(int argc, char *argv[]) {
10185 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10186 dup2(fd, 2);
10187 close(fd);
10188
10189 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10190
10191 _trace();
10192
10193 UpdateExternalStatus(0);
10194
10195 UIScreen *screen([UIScreen mainScreen]);
10196 if ([screen respondsToSelector:@selector(scale)])
10197 ScreenScale_ = [screen scale];
10198 else
10199 ScreenScale_ = 1;
10200
10201 UIDevice *device([UIDevice currentDevice]);
10202 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10203 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10204 if (idiom == UIUserInterfaceIdiomPad)
10205 IsWildcat_ = true;
10206 }
10207
10208 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10209
10210 RegEx pattern("([0-9]+\\.[0-9]+).*");
10211
10212 if (pattern([device systemVersion]))
10213 Firmware_ = pattern[1];
10214 if (pattern(Cydia_))
10215 Major_ = pattern[1];
10216
10217 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10218
10219 HostConfig_ = [[[NSObject alloc] init] autorelease];
10220 @synchronized (HostConfig_) {
10221 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10222 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10223 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10224 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10225 }
10226
10227 NSString *ui(@"ui/ios");
10228 if (Idiom_ != nil)
10229 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10230 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10231 UI_ = CydiaURL(ui);
10232
10233 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10234
10235 /* Library Hacks {{{ */
10236 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10237
10238 $WAKWindow = objc_getClass("WAKWindow");
10239 if ($WAKWindow != NULL)
10240 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10241 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10242
10243 $NSURLConnection = objc_getClass("NSURLConnection");
10244 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10245 if (NSURLConnection$init$ != NULL) {
10246 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10247 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10248 }
10249
10250 $NSUserDefaults = objc_getClass("NSUserDefaults");
10251 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10252 if (NSUserDefaults$objectForKey$ != NULL) {
10253 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10254 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10255 }
10256 /* }}} */
10257 /* Set Locale {{{ */
10258 Locale_ = CFLocaleCopyCurrent();
10259 Languages_ = [NSLocale preferredLanguages];
10260
10261 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10262 //NSLog(@"%@", [Languages_ description]);
10263
10264 const char *lang;
10265 if (Locale_ != NULL)
10266 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10267 else if (Languages_ != nil && [Languages_ count] != 0)
10268 lang = [[Languages_ objectAtIndex:0] UTF8String];
10269 else
10270 // XXX: consider just setting to C and then falling through?
10271 lang = NULL;
10272
10273 if (lang != NULL) {
10274 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10275 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10276 }
10277
10278 NSLog(@"Setting Language: %s", lang);
10279
10280 if (lang != NULL) {
10281 setenv("LANG", lang, true);
10282 std::setlocale(LC_ALL, lang);
10283 }
10284 /* }}} */
10285 /* Index Collation {{{ */
10286 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10287 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10288 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10289 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10290 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10291 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10292
10293 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10294
10295 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10296 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10297 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})
10298 CollationOffset_.push_back(offset);
10299 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];
10300 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];
10301 } else {
10302
10303 CollationThumbs_ = [collation sectionIndexTitles];
10304 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10305 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10306
10307 CollationTitles_ = [collation sectionTitles];
10308 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10309
10310 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10311 if (&transform != NULL && transform != nil) {
10312 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10313 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10314 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10315 UErrorCode code(U_ZERO_ERROR);
10316 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10317 if (!U_SUCCESS(code))
10318 NSLog(@"%s", u_errorName(code));
10319 }
10320
10321 }
10322 } @catch (NSException *e) {
10323 NSLog(@"%@", e);
10324 goto hard;
10325 } } else hard: {
10326 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10327
10328 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];
10329 for (NSInteger offset(0); offset != 28; ++offset)
10330 CollationOffset_.push_back(offset);
10331
10332 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];
10333 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];
10334 }
10335 /* }}} */
10336 /* Parse Arguments {{{ */
10337 bool substrate(false);
10338
10339 if (argc != 0) {
10340 char **args(argv);
10341 int arge(1);
10342
10343 for (int argi(1); argi != argc; ++argi)
10344 if (strcmp(argv[argi], "--") == 0) {
10345 arge = argi;
10346 argv[argi] = argv[0];
10347 argv += argi;
10348 argc -= argi;
10349 break;
10350 }
10351
10352 for (int argi(1); argi != arge; ++argi)
10353 if (strcmp(args[argi], "--substrate") == 0)
10354 substrate = true;
10355 else
10356 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10357 }
10358 /* }}} */
10359
10360 App_ = [[NSBundle mainBundle] bundlePath];
10361 Advanced_ = YES;
10362
10363 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10364 mkdir([Cache_ UTF8String], 0755);
10365
10366 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10367 alloc_ = alloc->method_imp;
10368 alloc->method_imp = (IMP) &Alloc_;*/
10369
10370 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10371 dealloc_ = dealloc->method_imp;
10372 dealloc->method_imp = (IMP) &Dealloc_;*/
10373
10374 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10375 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10376
10377 /* System Information {{{ */
10378 size_t size;
10379
10380 int maxproc;
10381 size = sizeof(maxproc);
10382 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10383 perror("sysctlbyname(\"kern.maxproc\", ?)");
10384 else if (maxproc < 64) {
10385 maxproc = 64;
10386 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10387 perror("sysctlbyname(\"kern.maxproc\", #)");
10388 }
10389
10390 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10391 char *osversion = new char[size];
10392 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10393 perror("sysctlbyname(\"kern.osversion\", ?)");
10394 else
10395 System_ = [NSString stringWithUTF8String:osversion];
10396
10397 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10398 char *machine = new char[size];
10399 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10400 perror("sysctlbyname(\"hw.machine\", ?)");
10401 else
10402 Machine_ = machine;
10403
10404 int64_t usermem(0);
10405 size = sizeof(usermem);
10406 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10407 usermem = 0;
10408
10409 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10410 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10411 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10412
10413 UniqueID_ = UniqueIdentifier(device);
10414
10415 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10416 Product_ = [info objectForKey:@"SafariProductVersion"];
10417 Safari_ = [info objectForKey:@"CFBundleVersion"];
10418 }
10419
10420 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10421
10422 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10423 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10424 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10425 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10426 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10427 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10428
10429 UserAgent_ = agent;
10430 /* }}} */
10431 /* Load Database {{{ */
10432 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10433
10434 _trace();
10435 mkdir("/var/mobile/Library/Cydia", 0755);
10436 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10437 _trace();
10438
10439 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10440 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10441 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10442 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10443
10444 _trace();
10445 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10446
10447 if (Values_ == nil)
10448 Values_ = [metadata objectForKey:@"Values"];
10449 if (Values_ == nil)
10450 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10451
10452 if (Sections_ == nil)
10453 Sections_ = [metadata objectForKey:@"Sections"];
10454 if (Sections_ == nil)
10455 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10456
10457 if (Sources_ == nil)
10458 Sources_ = [metadata objectForKey:@"Sources"];
10459 if (Sources_ == nil)
10460 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10461
10462 // XXX: this wrong, but in a way that doesn't matter :/
10463 if (Version_ == nil)
10464 Version_ = [metadata objectForKey:@"Version"];
10465 if (Version_ == nil)
10466 Version_ = [NSNumber numberWithUnsignedInt:0];
10467
10468 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10469 bool fail(false);
10470 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10471 _trace();
10472 if (fail)
10473 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10474 }
10475
10476 if ([Version_ unsignedIntValue] == 0) {
10477 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10478 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10479 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10480 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10481
10482 Version_ = [NSNumber numberWithUnsignedInt:1];
10483
10484 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10485 [cache removeObjectForKey:@"LastUpdate"];
10486 [cache writeToFile:@ CacheState_ atomically:YES];
10487 }
10488 }
10489
10490 _H<NSMutableArray> broken([NSMutableArray array]);
10491 for (NSString *key in (id) Sources_)
10492 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10493 [broken addObject:key];
10494 if ([broken count] != 0)
10495 for (NSString *key in (id) broken)
10496 [Sources_ removeObjectForKey:key];
10497 broken = nil;
10498
10499 SaveConfig(nil);
10500 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10501 /* }}} */
10502
10503 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10504
10505 if (kCFCoreFoundationVersionNumber > 1000)
10506 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10507
10508 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10509
10510 if (access("/User", F_OK) != 0 || version != 6) {
10511 _trace();
10512 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10513 _trace();
10514 }
10515
10516 if (access("/tmp/cydia.chk", F_OK) == 0) {
10517 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10518 _assert(errno == ENOENT);
10519 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10520 _assert(errno == ENOENT);
10521 }
10522
10523 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10524
10525 /* APT Initialization {{{ */
10526 _assert(pkgInitConfig(*_config));
10527 _assert(pkgInitSystem(*_config, _system));
10528
10529 if (lang != NULL)
10530 _config->Set("APT::Acquire::Translation", lang);
10531
10532 // XXX: this timeout might be important :(
10533 //_config->Set("Acquire::http::Timeout", 15);
10534
10535 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10536
10537 mkdir([Cache("archives") UTF8String], 0755);
10538 mkdir([Cache("archives/partial") UTF8String], 0755);
10539 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10540
10541 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10542 _config->Set("Dir::State", [Cache_ UTF8String]);
10543
10544 mkdir([Cache("lists") UTF8String], 0755);
10545 mkdir([Cache("lists/partial") UTF8String], 0755);
10546 mkdir([Cache("periodic") UTF8String], 0755);
10547 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10548
10549 std::string logs("/var/mobile/Library/Logs/Cydia");
10550 mkdir(logs.c_str(), 0755);
10551 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10552
10553 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10554 /* }}} */
10555 /* Color Choices {{{ */
10556 space_ = CGColorSpaceCreateDeviceRGB();
10557
10558 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10559 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10560 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10561 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10562 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10563 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10564 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10565 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10566 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10567 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10568
10569 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10570 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10571 /* }}}*/
10572 /* UIKit Configuration {{{ */
10573 // XXX: I have a feeling this was important
10574 //UIKeyboardDisableAutomaticAppearance();
10575 /* }}} */
10576
10577 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10578 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10579
10580 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10581 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10582 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10583
10584 PulseInterval_ = fast ? 50000 : 500000;
10585
10586 Colon_ = UCLocalize("COLON_DELIMITED");
10587 Elision_ = UCLocalize("ELISION");
10588 Error_ = UCLocalize("ERROR");
10589 Warning_ = UCLocalize("WARNING");
10590
10591 _trace();
10592 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10593
10594 CGColorSpaceRelease(space_);
10595 CFRelease(Locale_);
10596
10597 [pool release];
10598 return value;
10599 }