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