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