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