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