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