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