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