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