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