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