]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Use the argument from commitEditingStyle.
[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 [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 - (void) reloadData {
6247 [super reloadData];
6248
6249 era_ = [database_ era];
6250 NSArray *packages = [database_ packages];
6251
6252 [packages_ removeAllObjects];
6253 [sections_ removeAllObjects];
6254
6255 _profile(PackageTable$reloadData$Filter)
6256 for (Package *package in packages)
6257 if ([self hasPackage:package])
6258 [packages_ addObject:package];
6259 _end
6260
6261 [indices_ removeAllObjects];
6262
6263 Section *section = nil;
6264
6265 #if TryIndexedCollation
6266 if ([[self class] hasIndexedCollation]) {
6267 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6268 NSArray *titles = [collation sectionIndexTitles];
6269 int secidx = -1;
6270
6271 _profile(PackageTable$reloadData$Section)
6272 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6273 Package *package;
6274 int index;
6275
6276 _profile(PackageTable$reloadData$Section$Package)
6277 package = [packages_ objectAtIndex:offset];
6278 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6279 _end
6280
6281 while (secidx < index) {
6282 secidx += 1;
6283
6284 _profile(PackageTable$reloadData$Section$Allocate)
6285 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6286 _end
6287
6288 _profile(PackageTable$reloadData$Section$Add)
6289 [sections_ addObject:section];
6290 _end
6291 }
6292
6293 [section addToCount];
6294 }
6295 _end
6296 } else
6297 #endif
6298 {
6299 [index_ removeAllObjects];
6300
6301 _profile(PackageTable$reloadData$Section)
6302 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6303 Package *package;
6304 unichar index;
6305
6306 _profile(PackageTable$reloadData$Section$Package)
6307 package = [packages_ objectAtIndex:offset];
6308 index = [package index];
6309 _end
6310
6311 if (section == nil || [section index] != index) {
6312 _profile(PackageTable$reloadData$Section$Allocate)
6313 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6314 _end
6315
6316 [index_ addObject:[section name]];
6317 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6318
6319 _profile(PackageTable$reloadData$Section$Add)
6320 [sections_ addObject:section];
6321 _end
6322 }
6323
6324 [section addToCount];
6325 }
6326 _end
6327 }
6328
6329 _profile(PackageTable$reloadData$List)
6330 [list_ reloadData];
6331 _end
6332 }
6333
6334 - (void) resetCursor {
6335 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6336 }
6337
6338 @end
6339 /* }}} */
6340 /* Filtered Package List Controller {{{ */
6341 @interface FilteredPackageListController : PackageListController {
6342 SEL filter_;
6343 IMP imp_;
6344 id object_;
6345 }
6346
6347 - (void) setObject:(id)object;
6348 - (void) setObject:(id)object forFilter:(SEL)filter;
6349
6350 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6351
6352 @end
6353
6354 @implementation FilteredPackageListController
6355
6356 - (void) dealloc {
6357 if (object_ != nil)
6358 [object_ release];
6359 [super dealloc];
6360 }
6361
6362 - (void) setFilter:(SEL)filter {
6363 filter_ = filter;
6364
6365 /* XXX: this is an unsafe optimization of doomy hell */
6366 Method method(class_getInstanceMethod([Package class], filter));
6367 _assert(method != NULL);
6368 imp_ = method_getImplementation(method);
6369 _assert(imp_ != NULL);
6370 }
6371
6372 - (void) setObject:(id)object {
6373 if (object_ != nil)
6374 [object_ release];
6375 if (object == nil)
6376 object_ = nil;
6377 else
6378 object_ = [object retain];
6379 }
6380
6381 - (void) setObject:(id)object forFilter:(SEL)filter {
6382 [self setFilter:filter];
6383 [self setObject:object];
6384 }
6385
6386 - (bool) hasPackage:(Package *)package {
6387 _profile(FilteredPackageTable$hasPackage)
6388 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6389 _end
6390 }
6391
6392 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6393 if ((self = [super initWithDatabase:database title:title]) != nil) {
6394 [self setFilter:filter];
6395 [self setObject:object];
6396 } return self;
6397 }
6398
6399 @end
6400 /* }}} */
6401
6402 /* Home Controller {{{ */
6403 @interface HomeController : CydiaWebViewController {
6404 }
6405
6406 @end
6407
6408 @implementation HomeController
6409
6410 - (id) init {
6411 if ((self = [super init]) != nil) {
6412 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6413 [self reloadData];
6414 } return self;
6415 }
6416
6417 - (NSURL *) navigationURL {
6418 return [NSURL URLWithString:@"cydia://home"];
6419 }
6420
6421 - (void) aboutButtonClicked {
6422 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6423
6424 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6425 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6426 [alert setCancelButtonIndex:0];
6427
6428 [alert setMessage:
6429 @"Copyright \u00a9 2008-2011\n"
6430 "SaurikIT, LLC\n"
6431 "\n"
6432 "Jay Freeman (saurik)\n"
6433 "saurik@saurik.com\n"
6434 "http://www.saurik.com/"
6435 ];
6436
6437 [alert show];
6438 }
6439
6440 - (UIBarButtonItem *) leftButton {
6441 return [[[UIBarButtonItem alloc]
6442 initWithTitle:UCLocalize("ABOUT")
6443 style:UIBarButtonItemStylePlain
6444 target:self
6445 action:@selector(aboutButtonClicked)
6446 ] autorelease];
6447 }
6448
6449 - (void) unloadData {
6450 [super unloadData];
6451 [self reloadData];
6452 }
6453
6454 @end
6455 /* }}} */
6456 /* Manage Controller {{{ */
6457 @interface ManageController : CydiaWebViewController {
6458 }
6459
6460 - (void) queueStatusDidChange;
6461
6462 @end
6463
6464 @implementation ManageController
6465
6466 - (id) init {
6467 if ((self = [super init]) != nil) {
6468 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6469 } return self;
6470 }
6471
6472 - (NSURL *) navigationURL {
6473 return [NSURL URLWithString:@"cydia://manage"];
6474 }
6475
6476 - (UIBarButtonItem *) leftButton {
6477 return [[[UIBarButtonItem alloc]
6478 initWithTitle:UCLocalize("SETTINGS")
6479 style:UIBarButtonItemStylePlain
6480 target:self
6481 action:@selector(settingsButtonClicked)
6482 ] autorelease];
6483 }
6484
6485 - (void) settingsButtonClicked {
6486 [delegate_ showSettings];
6487 }
6488
6489 - (void) queueButtonClicked {
6490 [delegate_ queue];
6491 }
6492
6493 - (UIBarButtonItem *) customButton {
6494 return Queuing_ ? [[[UIBarButtonItem alloc]
6495 initWithTitle:UCLocalize("QUEUE")
6496 style:UIBarButtonItemStyleDone
6497 target:self
6498 action:@selector(queueButtonClicked)
6499 ] autorelease] : [super customButton];
6500 }
6501
6502 - (void) queueStatusDidChange {
6503 [self applyRightButton];
6504 }
6505
6506 - (bool) isLoading {
6507 return !Queuing_ && [super isLoading];
6508 }
6509
6510 @end
6511 /* }}} */
6512
6513 /* Refresh Bar {{{ */
6514 @interface RefreshBar : UINavigationBar {
6515 UIProgressIndicator *indicator_;
6516 UITextLabel *prompt_;
6517 UIProgressBar *progress_;
6518 UINavigationButton *cancel_;
6519 }
6520
6521 @end
6522
6523 @implementation RefreshBar
6524
6525 - (void) dealloc {
6526 [indicator_ release];
6527 [prompt_ release];
6528 [progress_ release];
6529 [cancel_ release];
6530 [super dealloc];
6531 }
6532
6533 - (void) positionViews {
6534 CGRect frame = [cancel_ frame];
6535 frame.size = [cancel_ sizeThatFits:frame.size];
6536 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6537 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6538 [cancel_ setFrame:frame];
6539
6540 CGSize prgsize = {75, 100};
6541 CGRect prgrect = {{
6542 [self frame].size.width - prgsize.width - 10,
6543 ([self frame].size.height - prgsize.height) / 2
6544 } , prgsize};
6545 [progress_ setFrame:prgrect];
6546
6547 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6548 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6549 CGRect indrect = {{indoffset, indoffset}, indsize};
6550 [indicator_ setFrame:indrect];
6551
6552 CGSize prmsize = {215, indsize.height + 4};
6553 CGRect prmrect = {{
6554 indoffset * 2 + indsize.width,
6555 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6556 }, prmsize};
6557 [prompt_ setFrame:prmrect];
6558 }
6559
6560 - (void) setFrame:(CGRect)frame {
6561 [super setFrame:frame];
6562 [self positionViews];
6563 }
6564
6565 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6566 if ((self = [super initWithFrame:frame]) != nil) {
6567 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6568
6569 [self setBarStyle:UIBarStyleBlack];
6570
6571 UIBarStyle barstyle([self _barStyle:NO]);
6572 bool ugly(barstyle == UIBarStyleDefault);
6573
6574 UIProgressIndicatorStyle style = ugly ?
6575 UIProgressIndicatorStyleMediumBrown :
6576 UIProgressIndicatorStyleMediumWhite;
6577
6578 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6579 [indicator_ setStyle:style];
6580 [indicator_ startAnimation];
6581 [self addSubview:indicator_];
6582
6583 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6584 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6585 [prompt_ setBackgroundColor:[UIColor clearColor]];
6586 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6587 [self addSubview:prompt_];
6588
6589 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6590 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6591 [progress_ setStyle:0];
6592 [self addSubview:progress_];
6593
6594 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6595 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6596 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6597 [cancel_ setBarStyle:barstyle];
6598
6599 [self positionViews];
6600 } return self;
6601 }
6602
6603 - (void) setCancellable:(bool)cancellable {
6604 if (cancellable)
6605 [self addSubview:cancel_];
6606 else
6607 [cancel_ removeFromSuperview];
6608 }
6609
6610 - (void) start {
6611 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6612 [progress_ setProgress:0];
6613 }
6614
6615 - (void) stop {
6616 [self setCancellable:NO];
6617 }
6618
6619 - (void) setPrompt:(NSString *)prompt {
6620 [prompt_ setText:prompt];
6621 }
6622
6623 - (void) setProgress:(float)progress {
6624 [progress_ setProgress:progress];
6625 }
6626
6627 @end
6628 /* }}} */
6629
6630 /* Cydia Navigation Controller Interface {{{ */
6631 @interface UINavigationController (Cydia)
6632
6633 - (NSArray *) navigationURLCollection;
6634 - (void) unloadData;
6635
6636 @end
6637 /* }}} */
6638
6639 /* Cydia Tab Bar Controller {{{ */
6640 @interface CYTabBarController : UITabBarController <
6641 UITabBarControllerDelegate,
6642 ProgressDelegate
6643 > {
6644 _transient Database *database_;
6645 RefreshBar *refreshbar_;
6646
6647 bool dropped_;
6648 bool updating_;
6649 // XXX: ok, "updatedelegate_"?...
6650 _transient NSObject<CydiaDelegate> *updatedelegate_;
6651
6652 id root_;
6653 UIViewController *remembered_;
6654 _transient UIViewController *transient_;
6655 }
6656
6657 - (NSArray *) navigationURLCollection;
6658 - (void) dropBar:(BOOL)animated;
6659 - (void) beginUpdate;
6660 - (void) raiseBar:(BOOL)animated;
6661 - (BOOL) updating;
6662 - (void) unloadData;
6663
6664 @end
6665
6666 @implementation CYTabBarController
6667
6668 - (void) setUnselectedViewController:(UIViewController *)transient {
6669 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6670 if (transient != nil) {
6671 if (transient_ == nil)
6672 remembered_ = [[controllers objectAtIndex:0] retain];
6673 transient_ = transient;
6674 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6675 [controllers replaceObjectAtIndex:0 withObject:transient_];
6676 [self setSelectedIndex:0];
6677 [self setViewControllers:controllers];
6678 [self concealTabBarSelection];
6679 } else if (remembered_ != nil) {
6680 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6681 transient_ = transient;
6682 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6683 [remembered_ release];
6684 remembered_ = nil;
6685 [self setViewControllers:controllers];
6686 [self revealTabBarSelection];
6687 }
6688 }
6689
6690 - (UIViewController *) unselectedViewController {
6691 return transient_;
6692 }
6693
6694 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6695 if ([self unselectedViewController])
6696 [self setUnselectedViewController:nil];
6697 }
6698
6699 - (NSArray *) navigationURLCollection {
6700 NSMutableArray *items([NSMutableArray array]);
6701
6702 // XXX: Should this deal with transient view controllers?
6703 for (id navigation in [self viewControllers]) {
6704 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6705 if (stack != nil)
6706 [items addObject:stack];
6707 }
6708
6709 return items;
6710 }
6711
6712 - (void) unloadData {
6713 UIViewController *selected([self selectedViewController]);
6714 for (UINavigationController *controller in [self viewControllers])
6715 [controller unloadData];
6716
6717 [selected reloadData];
6718
6719 if (UIViewController *unselected = [self unselectedViewController])
6720 [unselected reloadData];
6721
6722 [super unloadData];
6723 }
6724
6725 - (void) dealloc {
6726 [refreshbar_ release];
6727 [[NSNotificationCenter defaultCenter] removeObserver:self];
6728
6729 [super dealloc];
6730 }
6731
6732 - (id) initWithDatabase:(Database *)database {
6733 if ((self = [super init]) != nil) {
6734 database_ = database;
6735 [self setDelegate:self];
6736
6737 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6738 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6739
6740 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6741 } return self;
6742 }
6743
6744 - (void) setUpdate:(NSDate *)date {
6745 [self beginUpdate];
6746 }
6747
6748 - (void) beginUpdate {
6749 [refreshbar_ start];
6750 [self dropBar:YES];
6751
6752 [updatedelegate_ retainNetworkActivityIndicator];
6753 updating_ = true;
6754
6755 [NSThread
6756 detachNewThreadSelector:@selector(performUpdate)
6757 toTarget:self
6758 withObject:nil
6759 ];
6760 }
6761
6762 - (void) performUpdate { _pooled
6763 Status status;
6764 status.setDelegate(self);
6765 [database_ updateWithStatus:status];
6766
6767 [self
6768 performSelectorOnMainThread:@selector(completeUpdate)
6769 withObject:nil
6770 waitUntilDone:NO
6771 ];
6772 }
6773
6774 - (void) stopUpdateWithSelector:(SEL)selector {
6775 updating_ = false;
6776 [updatedelegate_ releaseNetworkActivityIndicator];
6777
6778 [self raiseBar:YES];
6779 [refreshbar_ stop];
6780
6781 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6782 }
6783
6784 - (void) completeUpdate {
6785 if (!updating_)
6786 return;
6787 [self stopUpdateWithSelector:@selector(reloadData)];
6788 }
6789
6790 - (void) cancelUpdate {
6791 [self stopUpdateWithSelector:@selector(updateData)];
6792 }
6793
6794 - (void) cancelPressed {
6795 [self cancelUpdate];
6796 }
6797
6798 - (BOOL) updating {
6799 return updating_;
6800 }
6801
6802 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6803 [refreshbar_ setPrompt:[event compoundMessage]];
6804 }
6805
6806 - (bool) isProgressCancelled {
6807 return !updating_;
6808 }
6809
6810 - (void) setProgressCancellable:(NSNumber *)cancellable {
6811 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6812 }
6813
6814 - (void) setProgressPercent:(NSNumber *)percent {
6815 [refreshbar_ setProgress:[percent floatValue]];
6816 }
6817
6818 - (void) setProgressStatus:(NSDictionary *)status {
6819 if (status != nil)
6820 [self setProgressPercent:[status objectForKey:@"Percent"]];
6821 }
6822
6823 - (void) setUpdateDelegate:(id)delegate {
6824 updatedelegate_ = delegate;
6825 }
6826
6827 - (CGFloat) statusBarHeight {
6828 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6829 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6830 } else {
6831 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6832 }
6833 }
6834
6835 - (UIView *) transitionView {
6836 if ([self respondsToSelector:@selector(_transitionView)])
6837 return [self _transitionView];
6838 else
6839 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6840 }
6841
6842 - (void) dropBar:(BOOL)animated {
6843 if (dropped_)
6844 return;
6845 dropped_ = true;
6846
6847 UIView *transition([self transitionView]);
6848 [[self view] addSubview:refreshbar_];
6849
6850 CGRect barframe([refreshbar_ frame]);
6851
6852 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6853 barframe.origin.y = [self statusBarHeight];
6854 else
6855 barframe.origin.y = 0;
6856
6857 [refreshbar_ setFrame:barframe];
6858
6859 if (animated)
6860 [UIView beginAnimations:nil context:NULL];
6861
6862 CGRect viewframe = [transition frame];
6863 viewframe.origin.y += barframe.size.height;
6864 viewframe.size.height -= barframe.size.height;
6865 [transition setFrame:viewframe];
6866
6867 if (animated)
6868 [UIView commitAnimations];
6869
6870 // Ensure bar has the proper width for our view, it might have changed
6871 barframe.size.width = viewframe.size.width;
6872 [refreshbar_ setFrame:barframe];
6873
6874 // XXX: fix Apple's layout bug
6875 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6876 }
6877
6878 - (void) raiseBar:(BOOL)animated {
6879 if (!dropped_)
6880 return;
6881 dropped_ = false;
6882
6883 UIView *transition([self transitionView]);
6884 [refreshbar_ removeFromSuperview];
6885
6886 CGRect barframe([refreshbar_ frame]);
6887
6888 if (animated)
6889 [UIView beginAnimations:nil context:NULL];
6890
6891 CGRect viewframe = [transition frame];
6892 viewframe.origin.y -= barframe.size.height;
6893 viewframe.size.height += barframe.size.height;
6894 [transition setFrame:viewframe];
6895
6896 if (animated)
6897 [UIView commitAnimations];
6898
6899 // XXX: fix Apple's layout bug
6900 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6901 }
6902
6903 #if 0
6904 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6905 // XXX: fix Apple's layout bug
6906 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6907 }
6908 #endif
6909
6910 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6911 bool dropped(dropped_);
6912
6913 if (dropped)
6914 [self raiseBar:NO];
6915
6916 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6917
6918 if (dropped)
6919 [self dropBar:NO];
6920
6921 // XXX: fix Apple's layout bug
6922 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6923 }
6924
6925 - (void) statusBarFrameChanged:(NSNotification *)notification {
6926 if (dropped_) {
6927 [self raiseBar:NO];
6928 [self dropBar:NO];
6929 }
6930 }
6931
6932 @end
6933 /* }}} */
6934
6935 /* Cydia Navigation Controller Implementation {{{ */
6936 @implementation UINavigationController (Cydia)
6937
6938 - (NSArray *) navigationURLCollection {
6939 NSMutableArray *stack([NSMutableArray array]);
6940
6941 for (CyteViewController *controller in [self viewControllers]) {
6942 NSString *url = [[controller navigationURL] absoluteString];
6943 if (url != nil)
6944 [stack addObject:url];
6945 }
6946
6947 return stack;
6948 }
6949
6950 - (void) reloadData {
6951 [super reloadData];
6952
6953 if (UIViewController *visible = [self visibleViewController])
6954 [visible reloadData];
6955 }
6956
6957 - (void) unloadData {
6958 for (CyteViewController *page in [self viewControllers])
6959 [page unloadData];
6960
6961 [super unloadData];
6962 }
6963
6964 @end
6965 /* }}} */
6966
6967 /* Cydia:// Protocol {{{ */
6968 @interface CydiaURLProtocol : NSURLProtocol {
6969 }
6970
6971 @end
6972
6973 @implementation CydiaURLProtocol
6974
6975 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6976 NSURL *url([request URL]);
6977 if (url == nil)
6978 return NO;
6979
6980 NSString *scheme([[url scheme] lowercaseString]);
6981 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6982 return YES;
6983 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6984 return YES;
6985
6986 return NO;
6987 }
6988
6989 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6990 return request;
6991 }
6992
6993 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6994 id<NSURLProtocolClient> client([self client]);
6995 if (icon == nil)
6996 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6997 else {
6998 NSData *data(UIImagePNGRepresentation(icon));
6999
7000 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7001 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7002 [client URLProtocol:self didLoadData:data];
7003 [client URLProtocolDidFinishLoading:self];
7004 }
7005 }
7006
7007 - (void) startLoading {
7008 id<NSURLProtocolClient> client([self client]);
7009 NSURLRequest *request([self request]);
7010
7011 NSURL *url([request URL]);
7012 NSString *href([url absoluteString]);
7013 NSString *scheme([[url scheme] lowercaseString]);
7014
7015 NSString *path;
7016
7017 if ([scheme isEqualToString:@"cydia"])
7018 path = [href substringFromIndex:8];
7019 else if ([scheme isEqualToString:@"about"])
7020 path = [href substringFromIndex:12];
7021 else _assert(false);
7022
7023 NSRange slash([path rangeOfString:@"/"]);
7024
7025 NSString *command;
7026 if (slash.location == NSNotFound) {
7027 command = path;
7028 path = nil;
7029 } else {
7030 command = [path substringToIndex:slash.location];
7031 path = [path substringFromIndex:(slash.location + 1)];
7032 }
7033
7034 Database *database([Database sharedInstance]);
7035
7036 if ([command isEqualToString:@"package-icon"]) {
7037 if (path == nil)
7038 goto fail;
7039 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7040 Package *package([database packageWithName:path]);
7041 if (package == nil)
7042 goto fail;
7043 UIImage *icon([package icon]);
7044 [self _returnPNGWithImage:icon forRequest:request];
7045 } else if ([command isEqualToString:@"source-icon"]) {
7046 if (path == nil)
7047 goto fail;
7048 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7049 NSString *source(Simplify(path));
7050 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7051 if (icon == nil)
7052 icon = [UIImage applicationImageNamed:@"unknown.png"];
7053 [self _returnPNGWithImage:icon forRequest:request];
7054 } else if ([command isEqualToString:@"uikit-image"]) {
7055 if (path == nil)
7056 goto fail;
7057 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7058 UIImage *icon(_UIImageWithName(path));
7059 [self _returnPNGWithImage:icon forRequest:request];
7060 } else if ([command isEqualToString:@"section-icon"]) {
7061 if (path == nil)
7062 goto fail;
7063 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7064 NSString *section(Simplify(path));
7065 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7066 if (icon == nil)
7067 icon = [UIImage applicationImageNamed:@"unknown.png"];
7068 [self _returnPNGWithImage:icon forRequest:request];
7069 } else fail: {
7070 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7071 }
7072 }
7073
7074 - (void) stopLoading {
7075 }
7076
7077 @end
7078 /* }}} */
7079
7080 /* Section Controller {{{ */
7081 @interface SectionController : FilteredPackageListController {
7082 _H<NSString> section_;
7083 }
7084
7085 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7086
7087 @end
7088
7089 @implementation SectionController
7090
7091 - (NSURL *) navigationURL {
7092 NSString *name = section_;
7093 if (name == nil)
7094 name = @"all";
7095
7096 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7097 }
7098
7099 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7100 NSString *title;
7101 if (name == nil)
7102 title = UCLocalize("ALL_PACKAGES");
7103 else if (![name isEqual:@""])
7104 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7105 else
7106 title = UCLocalize("NO_SECTION");
7107
7108 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7109 section_ = name;
7110 } return self;
7111 }
7112
7113 @end
7114 /* }}} */
7115 /* Sections Controller {{{ */
7116 @interface SectionsController : CyteViewController <
7117 UITableViewDataSource,
7118 UITableViewDelegate
7119 > {
7120 _transient Database *database_;
7121 NSMutableArray *sections_;
7122 NSMutableArray *filtered_;
7123 UITableView *list_;
7124 }
7125
7126 - (id) initWithDatabase:(Database *)database;
7127 - (void) editButtonClicked;
7128
7129 @end
7130
7131 @implementation SectionsController
7132
7133 - (void) dealloc {
7134 [self releaseSubviews];
7135 [sections_ release];
7136 [filtered_ release];
7137
7138 [super dealloc];
7139 }
7140
7141 - (NSURL *) navigationURL {
7142 return [NSURL URLWithString:@"cydia://sections"];
7143 }
7144
7145 - (void) updateNavigationItem {
7146 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7147 if ([sections_ count] == 0) {
7148 [[self navigationItem] setRightBarButtonItem:nil];
7149 } else {
7150 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7151 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7152 target:self
7153 action:@selector(editButtonClicked)
7154 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7155 }
7156 }
7157
7158 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7159 [super setEditing:editing animated:animated];
7160
7161 if (editing)
7162 [list_ reloadData];
7163 else
7164 [delegate_ updateData];
7165
7166 [self updateNavigationItem];
7167 }
7168
7169 - (void) viewDidAppear:(BOOL)animated {
7170 [super viewDidAppear:animated];
7171 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7172 }
7173
7174 - (void) viewWillDisappear:(BOOL)animated {
7175 [super viewWillDisappear:animated];
7176 if ([self isEditing]) [self setEditing:NO];
7177 }
7178
7179 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7180 Section *section = nil;
7181 int index = [indexPath row];
7182 if (![self isEditing]) {
7183 index -= 1;
7184 if (index >= 0)
7185 section = [filtered_ objectAtIndex:index];
7186 } else {
7187 section = [sections_ objectAtIndex:index];
7188 }
7189 return section;
7190 }
7191
7192 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7193 if ([self isEditing])
7194 return [sections_ count];
7195 else
7196 return [filtered_ count] + 1;
7197 }
7198
7199 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7200 return 45.0f;
7201 }*/
7202
7203 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7204 static NSString *reuseIdentifier = @"SectionCell";
7205
7206 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7207 if (cell == nil)
7208 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7209
7210 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7211
7212 return cell;
7213 }
7214
7215 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7216 if ([self isEditing])
7217 return;
7218
7219 Section *section = [self sectionAtIndexPath:indexPath];
7220
7221 SectionController *controller = [[[SectionController alloc]
7222 initWithDatabase:database_
7223 section:[section name]
7224 ] autorelease];
7225 [controller setDelegate:delegate_];
7226
7227 [[self navigationController] pushViewController:controller animated:YES];
7228 }
7229
7230 - (void) loadView {
7231 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7232
7233 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7234 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7235 [list_ setRowHeight:45.0f];
7236 [list_ setDataSource:self];
7237 [list_ setDelegate:self];
7238 [[self view] addSubview:list_];
7239 }
7240
7241 - (void) viewDidLoad {
7242 [super viewDidLoad];
7243
7244 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7245 }
7246
7247 - (void) releaseSubviews {
7248 [list_ release];
7249 list_ = nil;
7250 }
7251
7252 - (id) initWithDatabase:(Database *)database {
7253 if ((self = [super init]) != nil) {
7254 database_ = database;
7255
7256 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7257 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7258 } return self;
7259 }
7260
7261 - (void) reloadData {
7262 [super reloadData];
7263
7264 NSArray *packages = [database_ packages];
7265
7266 [sections_ removeAllObjects];
7267 [filtered_ removeAllObjects];
7268
7269 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7270
7271 _trace();
7272 for (Package *package in packages) {
7273 NSString *name([package section]);
7274 NSString *key(name == nil ? @"" : name);
7275
7276 Section *section;
7277
7278 _profile(SectionsView$reloadData$Section)
7279 section = [sections objectForKey:key];
7280 if (section == nil) {
7281 _profile(SectionsView$reloadData$Section$Allocate)
7282 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7283 [sections setObject:section forKey:key];
7284 _end
7285 }
7286 _end
7287
7288 [section addToCount];
7289
7290 _profile(SectionsView$reloadData$Filter)
7291 if (![package valid] || ![package visible])
7292 continue;
7293 _end
7294
7295 [section addToRow];
7296 }
7297 _trace();
7298
7299 [sections_ addObjectsFromArray:[sections allValues]];
7300
7301 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7302
7303 for (Section *section in sections_) {
7304 size_t count([section row]);
7305 if (count == 0)
7306 continue;
7307
7308 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7309 [section setCount:count];
7310 [filtered_ addObject:section];
7311 }
7312
7313 [self updateNavigationItem];
7314 [list_ reloadData];
7315 _trace();
7316 }
7317
7318 - (void) editButtonClicked {
7319 [self setEditing:![self isEditing] animated:YES];
7320 }
7321
7322 @end
7323 /* }}} */
7324
7325 /* Changes Controller {{{ */
7326 @interface ChangesController : CyteViewController <
7327 UITableViewDataSource,
7328 UITableViewDelegate
7329 > {
7330 _transient Database *database_;
7331 unsigned era_;
7332 CFMutableArrayRef packages_;
7333 NSMutableArray *sections_;
7334 UITableView *list_;
7335 unsigned upgrades_;
7336 }
7337
7338 - (id) initWithDatabase:(Database *)database;
7339
7340 @end
7341
7342 @implementation ChangesController
7343
7344 - (void) dealloc {
7345 [self releaseSubviews];
7346 CFRelease(packages_);
7347 [sections_ release];
7348
7349 [super dealloc];
7350 }
7351
7352 - (NSURL *) navigationURL {
7353 return [NSURL URLWithString:@"cydia://changes"];
7354 }
7355
7356 - (void) viewDidAppear:(BOOL)animated {
7357 [super viewDidAppear:animated];
7358 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7359 }
7360
7361 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7362 NSInteger count([sections_ count]);
7363 return count == 0 ? 1 : count;
7364 }
7365
7366 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7367 if ([sections_ count] == 0)
7368 return nil;
7369 return [[sections_ objectAtIndex:section] name];
7370 }
7371
7372 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7373 if ([sections_ count] == 0)
7374 return 0;
7375 return [[sections_ objectAtIndex:section] count];
7376 }
7377
7378 - (Package *) packageAtIndex:(NSUInteger)index {
7379 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7380 }
7381
7382 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7383 @synchronized (database_) {
7384 if ([database_ era] != era_)
7385 return nil;
7386
7387 NSUInteger sectionIndex([path section]);
7388 if (sectionIndex >= [sections_ count])
7389 return nil;
7390 Section *section([sections_ objectAtIndex:sectionIndex]);
7391 NSInteger row([path row]);
7392 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7393 } }
7394
7395 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7396 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7397 if (cell == nil)
7398 cell = [[[PackageCell alloc] init] autorelease];
7399 [cell setPackage:[self packageAtIndexPath:path]];
7400 return cell;
7401 }
7402
7403 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7404 Package *package([self packageAtIndexPath:path]);
7405 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7406 [view setDelegate:delegate_];
7407 [[self navigationController] pushViewController:view animated:YES];
7408 return path;
7409 }
7410
7411 - (void) refreshButtonClicked {
7412 [delegate_ beginUpdate];
7413 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7414 }
7415
7416 - (void) upgradeButtonClicked {
7417 [delegate_ distUpgrade];
7418 }
7419
7420 - (void) loadView {
7421 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7422
7423 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7424 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7425 [list_ setRowHeight:73];
7426 [list_ setDataSource:self];
7427 [list_ setDelegate:self];
7428 [[self view] addSubview:list_];
7429 }
7430
7431 - (void) viewDidLoad {
7432 [super viewDidLoad];
7433
7434 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7435 }
7436
7437 - (void) releaseSubviews {
7438 [list_ release];
7439 list_ = nil;
7440 }
7441
7442 - (id) initWithDatabase:(Database *)database {
7443 if ((self = [super init]) != nil) {
7444 database_ = database;
7445
7446 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7447 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7448 } return self;
7449 }
7450
7451 // this mostly works because reloadData (below) is @synchronized (database_)
7452 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7453 - (void) _reloadPackages:(NSArray *)packages {
7454 CFRelease(packages_);
7455 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7456
7457 _trace();
7458 _profile(ChangesController$_reloadPackages$Filter)
7459 for (Package *package in packages)
7460 if ([package upgradableAndEssential:YES] || [package visible])
7461 CFArrayAppendValue(packages_, package);
7462 _end
7463 _trace();
7464 _profile(ChangesController$_reloadPackages$radixSort)
7465 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7466 _end
7467 _trace();
7468 }
7469
7470 - (void) _reloadData {
7471 @synchronized (database_) {
7472 era_ = [database_ era];
7473 NSArray *packages = [database_ packages];
7474
7475 [sections_ removeAllObjects];
7476
7477 #if 1
7478 UIProgressHUD *hud([delegate_ addProgressHUD]);
7479 [hud setText:UCLocalize("LOADING")];
7480 //NSLog(@"HUD:%@::%@", delegate_, hud);
7481 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7482 [delegate_ removeProgressHUD:hud];
7483 #else
7484 [self _reloadPackages:packages];
7485 #endif
7486
7487 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7488 Section *ignored = nil;
7489 Section *section = nil;
7490 time_t last = 0;
7491
7492 upgrades_ = 0;
7493 bool unseens = false;
7494
7495 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7496
7497 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7498 Package *package = [self packageAtIndex:offset];
7499
7500 BOOL uae = [package upgradableAndEssential:YES];
7501
7502 if (!uae) {
7503 unseens = true;
7504 time_t seen([package seen]);
7505
7506 if (section == nil || last != seen) {
7507 last = seen;
7508
7509 NSString *name;
7510 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7511 [name autorelease];
7512
7513 _profile(ChangesController$reloadData$Allocate)
7514 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7515 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7516 [sections_ addObject:section];
7517 _end
7518 }
7519
7520 [section addToCount];
7521 } else if ([package ignored]) {
7522 if (ignored == nil) {
7523 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7524 }
7525 [ignored addToCount];
7526 } else {
7527 ++upgrades_;
7528 [upgradable addToCount];
7529 }
7530 }
7531 _trace();
7532
7533 CFRelease(formatter);
7534
7535 if (unseens) {
7536 Section *last = [sections_ lastObject];
7537 size_t count = [last count];
7538 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7539 [sections_ removeLastObject];
7540 }
7541
7542 if ([ignored count] != 0)
7543 [sections_ insertObject:ignored atIndex:0];
7544 if (upgrades_ != 0)
7545 [sections_ insertObject:upgradable atIndex:0];
7546
7547 [list_ reloadData];
7548
7549 if (upgrades_ > 0)
7550 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7551 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7552 style:UIBarButtonItemStylePlain
7553 target:self
7554 action:@selector(upgradeButtonClicked)
7555 ] autorelease]];
7556
7557 if (![delegate_ updating])
7558 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7559 initWithTitle:UCLocalize("REFRESH")
7560 style:UIBarButtonItemStylePlain
7561 target:self
7562 action:@selector(refreshButtonClicked)
7563 ] autorelease]];
7564
7565 PrintTimes();
7566 } }
7567
7568 - (void) reloadData {
7569 [super reloadData];
7570 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7571 }
7572
7573 @end
7574 /* }}} */
7575 /* Search Controller {{{ */
7576 @interface SearchController : FilteredPackageListController <
7577 UISearchBarDelegate
7578 > {
7579 _H<UISearchBar> search_;
7580 BOOL searchloaded_;
7581 }
7582
7583 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7584 - (void) reloadData;
7585
7586 @end
7587
7588 @implementation SearchController
7589
7590 - (void) dealloc {
7591 [search_ setDelegate:nil];
7592 [super dealloc];
7593 }
7594
7595 - (NSURL *) navigationURL {
7596 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7597 return [NSURL URLWithString:@"cydia://search"];
7598 else
7599 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7600 }
7601
7602 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7603 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7604 [search_ resignFirstResponder];
7605 [self reloadData];
7606 }
7607
7608 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7609 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7610 [self reloadData];
7611 }
7612
7613 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7614 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7615 search_ = [[[UISearchBar alloc] init] autorelease];
7616 [search_ setDelegate:self];
7617
7618 if (query != nil)
7619 [search_ setText:query];
7620 } return self;
7621 }
7622
7623 - (void) viewDidAppear:(BOOL)animated {
7624 [super viewDidAppear:animated];
7625
7626 if (!searchloaded_) {
7627 searchloaded_ = YES;
7628 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7629 [search_ layoutSubviews];
7630 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7631
7632 UITextField *textField;
7633 if ([search_ respondsToSelector:@selector(searchField)])
7634 textField = [search_ searchField];
7635 else
7636 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7637
7638 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7639 [textField setEnablesReturnKeyAutomatically:NO];
7640 [[self navigationItem] setTitleView:textField];
7641 }
7642 }
7643
7644 - (void) reloadData {
7645 [self setObject:[search_ text]];
7646 [self resetCursor];
7647
7648 [super reloadData];
7649 }
7650
7651 - (void) didSelectPackage:(Package *)package {
7652 [search_ resignFirstResponder];
7653 [super didSelectPackage:package];
7654 }
7655
7656 @end
7657 /* }}} */
7658 /* Package Settings Controller {{{ */
7659 @interface PackageSettingsController : CyteViewController <
7660 UITableViewDataSource,
7661 UITableViewDelegate
7662 > {
7663 _transient Database *database_;
7664 NSString *name_;
7665 Package *package_;
7666 UITableView *table_;
7667 UISwitch *subscribedSwitch_;
7668 UISwitch *ignoredSwitch_;
7669 UITableViewCell *subscribedCell_;
7670 UITableViewCell *ignoredCell_;
7671 }
7672
7673 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7674
7675 @end
7676
7677 @implementation PackageSettingsController
7678
7679 - (void) dealloc {
7680 [self releaseSubviews];
7681 [name_ release];
7682 [package_ release];
7683
7684 [super dealloc];
7685 }
7686
7687 - (NSURL *) navigationURL {
7688 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7689 }
7690
7691 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7692 if (package_ == nil)
7693 return 0;
7694
7695 if ([package_ installed] == nil)
7696 return 1;
7697 else
7698 return 2;
7699 }
7700
7701 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7702 if (package_ == nil)
7703 return 0;
7704
7705 // both sections contain just one item right now.
7706 return 1;
7707 }
7708
7709 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7710 return nil;
7711 }
7712
7713 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7714 if (section == 0)
7715 return UCLocalize("SHOW_ALL_CHANGES_EX");
7716 else
7717 return UCLocalize("IGNORE_UPGRADES_EX");
7718 }
7719
7720 - (void) onSubscribed:(id)control {
7721 bool value([control isOn]);
7722 if (package_ == nil)
7723 return;
7724 if ([package_ setSubscribed:value])
7725 [delegate_ updateData];
7726 }
7727
7728 - (void) _updateIgnored {
7729 const char *package([name_ UTF8String]);
7730 bool on([ignoredSwitch_ isOn]);
7731
7732 pid_t pid(ExecFork());
7733 if (pid == 0) {
7734 FILE *dpkg(popen("dpkg --set-selections", "w"));
7735 fwrite(package, strlen(package), 1, dpkg);
7736
7737 if (on)
7738 fwrite(" hold\n", 6, 1, dpkg);
7739 else
7740 fwrite(" install\n", 9, 1, dpkg);
7741
7742 pclose(dpkg);
7743
7744 exit(0);
7745 _assert(false);
7746 }
7747
7748 _forever {
7749 int status;
7750 int result(waitpid(pid, &status, 0));
7751
7752 if (result != -1) {
7753 _assert(result == pid);
7754 break;
7755 }
7756 }
7757 }
7758
7759 - (void) onIgnored:(id)control {
7760 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7761 [invocation setTarget:self];
7762 [invocation setSelector:@selector(_updateIgnored)];
7763
7764 [delegate_ reloadDataWithInvocation:invocation];
7765 }
7766
7767 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7768 if (package_ == nil)
7769 return nil;
7770
7771 switch ([indexPath section]) {
7772 case 0: return subscribedCell_;
7773 case 1: return ignoredCell_;
7774
7775 _nodefault
7776 }
7777
7778 return nil;
7779 }
7780
7781 - (void) loadView {
7782 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7783
7784 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7785 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7786 [table_ setDataSource:self];
7787 [table_ setDelegate:self];
7788 [[self view] addSubview:table_];
7789
7790 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7791 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7792 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7793
7794 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7795 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7796 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7797
7798 subscribedCell_ = [[UITableViewCell alloc] init];
7799 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7800 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7801 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7802
7803 ignoredCell_ = [[UITableViewCell alloc] init];
7804 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7805 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7806 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7807 }
7808
7809 - (void) viewDidLoad {
7810 [super viewDidLoad];
7811
7812 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7813 }
7814
7815 - (void) releaseSubviews {
7816 [ignoredCell_ release];
7817 ignoredCell_ = nil;
7818
7819 [subscribedCell_ release];
7820 subscribedCell_ = nil;
7821
7822 [table_ release];
7823 table_ = nil;
7824
7825 [ignoredSwitch_ release];
7826 ignoredSwitch_ = nil;
7827
7828 [subscribedSwitch_ release];
7829 subscribedSwitch_ = nil;
7830 }
7831
7832 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7833 if ((self = [super init]) != nil) {
7834 database_ = database;
7835 name_ = [package retain];
7836 } return self;
7837 }
7838
7839 - (void) reloadData {
7840 [super reloadData];
7841
7842 if (package_ != nil)
7843 [package_ autorelease];
7844 package_ = [database_ packageWithName:name_];
7845
7846 if (package_ != nil) {
7847 package_ = [package_ retain];
7848 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7849 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7850 } // XXX: what now, G?
7851
7852 [table_ reloadData];
7853 }
7854
7855 @end
7856 /* }}} */
7857
7858 /* Installed Controller {{{ */
7859 @interface InstalledController : FilteredPackageListController {
7860 BOOL expert_;
7861 }
7862
7863 - (id) initWithDatabase:(Database *)database;
7864
7865 - (void) updateRoleButton;
7866 - (void) queueStatusDidChange;
7867
7868 @end
7869
7870 @implementation InstalledController
7871
7872 - (void) dealloc {
7873 [super dealloc];
7874 }
7875
7876 - (NSURL *) navigationURL {
7877 return [NSURL URLWithString:@"cydia://installed"];
7878 }
7879
7880 - (id) initWithDatabase:(Database *)database {
7881 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7882 [self updateRoleButton];
7883 [self queueStatusDidChange];
7884 } return self;
7885 }
7886
7887 #if !AlwaysReload
7888 - (void) queueButtonClicked {
7889 [delegate_ queue];
7890 }
7891 #endif
7892
7893 - (void) queueStatusDidChange {
7894 #if !AlwaysReload
7895 if (IsWildcat_) {
7896 if (Queuing_) {
7897 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7898 initWithTitle:UCLocalize("QUEUE")
7899 style:UIBarButtonItemStyleDone
7900 target:self
7901 action:@selector(queueButtonClicked)
7902 ] autorelease]];
7903 } else {
7904 [[self navigationItem] setLeftBarButtonItem:nil];
7905 }
7906 }
7907 #endif
7908 }
7909
7910 - (void) updateRoleButton {
7911 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7912 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7913 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7914 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7915 target:self
7916 action:@selector(roleButtonClicked)
7917 ] autorelease]];
7918 }
7919
7920 - (void) roleButtonClicked {
7921 [self setObject:[NSNumber numberWithBool:expert_]];
7922 [self reloadData];
7923 expert_ = !expert_;
7924
7925 [self updateRoleButton];
7926 }
7927
7928 @end
7929 /* }}} */
7930
7931 /* Source Cell {{{ */
7932 @interface SourceCell : CYTableViewCell <
7933 ContentDelegate
7934 > {
7935 UIImage *icon_;
7936 NSString *origin_;
7937 NSString *label_;
7938 }
7939
7940 - (void) setSource:(Source *)source;
7941
7942 @end
7943
7944 @implementation SourceCell
7945
7946 - (void) clearSource {
7947 [icon_ release];
7948 [origin_ release];
7949 [label_ release];
7950
7951 icon_ = nil;
7952 origin_ = nil;
7953 label_ = nil;
7954 }
7955
7956 - (void) setSource:(Source *)source {
7957 [self clearSource];
7958
7959 if (icon_ == nil)
7960 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7961 if (icon_ == nil)
7962 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7963 icon_ = [icon_ retain];
7964
7965 origin_ = [[source name] retain];
7966 label_ = [[source uri] retain];
7967
7968 [content_ setNeedsDisplay];
7969 }
7970
7971 - (void) dealloc {
7972 [self clearSource];
7973 [super dealloc];
7974 }
7975
7976 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7977 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7978 UIView *content([self contentView]);
7979 CGRect bounds([content bounds]);
7980
7981 content_ = [[ContentView alloc] initWithFrame:bounds];
7982 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7983 [content_ setBackgroundColor:[UIColor whiteColor]];
7984 [content addSubview:content_];
7985
7986 [content_ setDelegate:self];
7987 [content_ setOpaque:YES];
7988 } return self;
7989 }
7990
7991 - (NSString *) accessibilityLabel {
7992 return label_;
7993 }
7994
7995 - (void) drawContentRect:(CGRect)rect {
7996 bool highlighted(highlighted_);
7997 float width(rect.size.width);
7998
7999 if (icon_ != nil)
8000 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8001
8002 if (highlighted)
8003 UISetColor(White_);
8004
8005 if (!highlighted)
8006 UISetColor(Black_);
8007 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8008
8009 if (!highlighted)
8010 UISetColor(Blue_);
8011 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8012 }
8013
8014 @end
8015 /* }}} */
8016 /* Source Controller {{{ */
8017 @interface SourceController : FilteredPackageListController {
8018 _transient Source *source_;
8019 NSString *key_;
8020 }
8021
8022 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8023
8024 @end
8025
8026 @implementation SourceController
8027
8028 - (NSURL *) navigationURL {
8029 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8030 }
8031
8032 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8033 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8034 source_ = source;
8035 key_ = [[source key] retain];
8036 } return self;
8037 }
8038
8039 - (void) reloadData {
8040 source_ = [database_ sourceWithKey:key_];
8041 [key_ release];
8042 key_ = [[source_ key] retain];
8043 [self setObject:source_];
8044
8045 [[self navigationItem] setTitle:[source_ label]];
8046
8047 [super reloadData];
8048 }
8049
8050 @end
8051 /* }}} */
8052 /* Sources Controller {{{ */
8053 @interface SourcesController : CyteViewController <
8054 UITableViewDataSource,
8055 UITableViewDelegate
8056 > {
8057 _transient Database *database_;
8058 UITableView *list_;
8059 NSMutableArray *sources_;
8060 int offset_;
8061
8062 NSString *href_;
8063 UIProgressHUD *hud_;
8064 NSError *error_;
8065
8066 //NSURLConnection *installer_;
8067 NSURLConnection *trivial_;
8068 NSURLConnection *trivial_bz2_;
8069 NSURLConnection *trivial_gz_;
8070 //NSURLConnection *automatic_;
8071
8072 BOOL cydia_;
8073 }
8074
8075 - (id) initWithDatabase:(Database *)database;
8076 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8077
8078 @end
8079
8080 @implementation SourcesController
8081
8082 - (void) _releaseConnection:(NSURLConnection *)connection {
8083 if (connection != nil) {
8084 [connection cancel];
8085 //[connection setDelegate:nil];
8086 [connection release];
8087 }
8088 }
8089
8090 - (void) dealloc {
8091 [self releaseSubviews];
8092
8093 [href_ release];
8094 [hud_ release];
8095 [error_ release];
8096
8097 //[self _releaseConnection:installer_];
8098 [self _releaseConnection:trivial_];
8099 [self _releaseConnection:trivial_gz_];
8100 [self _releaseConnection:trivial_bz2_];
8101 //[self _releaseConnection:automatic_];
8102
8103 [sources_ release];
8104 [super dealloc];
8105 }
8106
8107 - (NSURL *) navigationURL {
8108 return [NSURL URLWithString:@"cydia://sources"];
8109 }
8110
8111 - (void) viewDidAppear:(BOOL)animated {
8112 [super viewDidAppear:animated];
8113 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8114 }
8115
8116 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8117 return offset_ == 0 ? 1 : 2;
8118 }
8119
8120 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8121 switch (section + (offset_ == 0 ? 1 : 0)) {
8122 case 0: return UCLocalize("ENTERED_BY_USER");
8123 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8124
8125 _nodefault
8126 }
8127 }
8128
8129 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8130 int count = [sources_ count];
8131 switch (section) {
8132 case 0: return (offset_ == 0 ? count : offset_);
8133 case 1: return count - offset_;
8134
8135 _nodefault
8136 }
8137 }
8138
8139 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8140 unsigned idx = 0;
8141 switch (indexPath.section) {
8142 case 0: idx = indexPath.row; break;
8143 case 1: idx = indexPath.row + offset_; break;
8144
8145 _nodefault
8146 }
8147 return [sources_ objectAtIndex:idx];
8148 }
8149
8150 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8151 static NSString *cellIdentifier = @"SourceCell";
8152
8153 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8154 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8155 [cell setSource:[self sourceAtIndexPath:indexPath]];
8156 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8157
8158 return cell;
8159 }
8160
8161 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8162 Source *source = [self sourceAtIndexPath:indexPath];
8163
8164 SourceController *controller = [[[SourceController alloc]
8165 initWithDatabase:database_
8166 source:source
8167 ] autorelease];
8168
8169 [controller setDelegate:delegate_];
8170
8171 [[self navigationController] pushViewController:controller animated:YES];
8172 }
8173
8174 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8175 Source *source = [self sourceAtIndexPath:indexPath];
8176 return [source record] != nil;
8177 }
8178
8179 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8180 if (editingStyle == UITableViewCellEditingStyleDelete) {
8181 Source *source = [self sourceAtIndexPath:indexPath];
8182 [Sources_ removeObjectForKey:[source key]];
8183 [delegate_ syncData];
8184 }
8185 }
8186
8187 - (void) complete {
8188 [delegate_ addTrivialSource:href_];
8189 [delegate_ syncData];
8190 }
8191
8192 - (NSString *) getWarning {
8193 NSString *href(href_);
8194 NSRange colon([href rangeOfString:@"://"]);
8195 if (colon.location != NSNotFound)
8196 href = [href substringFromIndex:(colon.location + 3)];
8197 href = [href stringByAddingPercentEscapes];
8198 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8199 href = [href stringByCachingURLWithCurrentCDN];
8200
8201 NSURL *url([NSURL URLWithString:href]);
8202
8203 NSStringEncoding encoding;
8204 NSError *error(nil);
8205
8206 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8207 return [warning length] == 0 ? nil : warning;
8208 return nil;
8209 }
8210
8211 - (void) _endConnection:(NSURLConnection *)connection {
8212 // XXX: the memory management in this method is horribly awkward
8213
8214 NSURLConnection **field = NULL;
8215 if (connection == trivial_)
8216 field = &trivial_;
8217 else if (connection == trivial_bz2_)
8218 field = &trivial_bz2_;
8219 else if (connection == trivial_gz_)
8220 field = &trivial_gz_;
8221 _assert(field != NULL);
8222 [connection release];
8223 *field = nil;
8224
8225 if (
8226 trivial_ == nil &&
8227 trivial_bz2_ == nil &&
8228 trivial_gz_ == nil
8229 ) {
8230 bool defer(false);
8231
8232 if (cydia_) {
8233 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8234 defer = true;
8235
8236 UIAlertView *alert = [[[UIAlertView alloc]
8237 initWithTitle:UCLocalize("SOURCE_WARNING")
8238 message:warning
8239 delegate:self
8240 cancelButtonTitle:UCLocalize("CANCEL")
8241 otherButtonTitles:
8242 UCLocalize("ADD_ANYWAY"),
8243 nil
8244 ] autorelease];
8245
8246 [alert setContext:@"warning"];
8247 [alert setNumberOfRows:1];
8248 [alert show];
8249 } else
8250 [self complete];
8251 } else if (error_ != nil) {
8252 UIAlertView *alert = [[[UIAlertView alloc]
8253 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8254 message:[error_ localizedDescription]
8255 delegate:self
8256 cancelButtonTitle:UCLocalize("OK")
8257 otherButtonTitles:nil
8258 ] autorelease];
8259
8260 [alert setContext:@"urlerror"];
8261 [alert show];
8262 } else {
8263 UIAlertView *alert = [[[UIAlertView alloc]
8264 initWithTitle:UCLocalize("NOT_REPOSITORY")
8265 message:UCLocalize("NOT_REPOSITORY_EX")
8266 delegate:self
8267 cancelButtonTitle:UCLocalize("OK")
8268 otherButtonTitles:nil
8269 ] autorelease];
8270
8271 [alert setContext:@"trivial"];
8272 [alert show];
8273 }
8274
8275 [delegate_ releaseNetworkActivityIndicator];
8276
8277 [delegate_ removeProgressHUD:hud_];
8278 [hud_ autorelease];
8279 hud_ = nil;
8280
8281 if (!defer) {
8282 [href_ release];
8283 href_ = nil;
8284 }
8285
8286 if (error_ != nil) {
8287 [error_ release];
8288 error_ = nil;
8289 }
8290 }
8291 }
8292
8293 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8294 switch ([response statusCode]) {
8295 case 200:
8296 cydia_ = YES;
8297 }
8298 }
8299
8300 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8301 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8302 if (error_ != nil)
8303 error_ = [error retain];
8304 [self _endConnection:connection];
8305 }
8306
8307 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8308 [self _endConnection:connection];
8309 }
8310
8311 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8312 NSMutableURLRequest *request = [NSMutableURLRequest
8313 requestWithURL:[NSURL URLWithString:href]
8314 cachePolicy:NSURLRequestUseProtocolCachePolicy
8315 timeoutInterval:120.0
8316 ];
8317
8318 [request setHTTPMethod:method];
8319
8320 if (Machine_ != NULL)
8321 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8322 if (UniqueID_ != nil)
8323 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8324
8325 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8326 }
8327
8328 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8329 NSString *context([alert context]);
8330
8331 if ([context isEqualToString:@"source"]) {
8332 switch (button) {
8333 case 1: {
8334 NSString *href = [[alert textField] text];
8335
8336 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8337
8338 if (![href hasSuffix:@"/"])
8339 href_ = [href stringByAppendingString:@"/"];
8340 else
8341 href_ = href;
8342 href_ = [href_ retain];
8343
8344 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8345 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8346 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8347 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8348
8349 cydia_ = false;
8350
8351 // XXX: this is stupid
8352 hud_ = [[delegate_ addProgressHUD] retain];
8353 [hud_ setText:UCLocalize("VERIFYING_URL")];
8354 [delegate_ retainNetworkActivityIndicator];
8355 } break;
8356
8357 case 0:
8358 break;
8359
8360 _nodefault
8361 }
8362
8363 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8364 } else if ([context isEqualToString:@"trivial"])
8365 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8366 else if ([context isEqualToString:@"urlerror"])
8367 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8368 else if ([context isEqualToString:@"warning"]) {
8369 switch (button) {
8370 case 1:
8371 [self complete];
8372 break;
8373
8374 case 0:
8375 break;
8376
8377 _nodefault
8378 }
8379
8380 [href_ release];
8381 href_ = nil;
8382
8383 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8384 }
8385 }
8386
8387 - (void) loadView {
8388 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8389
8390 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8391 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8392 [list_ setRowHeight:56];
8393 [list_ setDataSource:self];
8394 [list_ setDelegate:self];
8395 [[self view] addSubview:list_];
8396 }
8397
8398 - (void) viewDidLoad {
8399 [super viewDidLoad];
8400
8401 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8402 [self updateButtonsForEditingStatus:NO animated:NO];
8403 }
8404
8405 - (void) releaseSubviews {
8406 [list_ release];
8407 list_ = nil;
8408 }
8409
8410 - (id) initWithDatabase:(Database *)database {
8411 if ((self = [super init]) != nil) {
8412 database_ = database;
8413 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8414 } return self;
8415 }
8416
8417 - (void) reloadData {
8418 [super reloadData];
8419
8420 pkgSourceList list;
8421 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8422 return;
8423
8424 [sources_ removeAllObjects];
8425 [sources_ addObjectsFromArray:[database_ sources]];
8426 _trace();
8427 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8428 _trace();
8429
8430 int count([sources_ count]);
8431 offset_ = 0;
8432 for (int i = 0; i != count; i++) {
8433 if ([[sources_ objectAtIndex:i] record] == nil)
8434 break;
8435 offset_++;
8436 }
8437
8438 [list_ setEditing:NO];
8439 [self updateButtonsForEditingStatus:NO animated:NO];
8440 [list_ reloadData];
8441 }
8442
8443 - (void) showAddSourcePrompt {
8444 UIAlertView *alert = [[[UIAlertView alloc]
8445 initWithTitle:UCLocalize("ENTER_APT_URL")
8446 message:nil
8447 delegate:self
8448 cancelButtonTitle:UCLocalize("CANCEL")
8449 otherButtonTitles:
8450 UCLocalize("ADD_SOURCE"),
8451 nil
8452 ] autorelease];
8453
8454 [alert setContext:@"source"];
8455 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8456
8457 [alert setNumberOfRows:1];
8458 [alert addTextFieldWithValue:@"http://" label:@""];
8459
8460 UITextInputTraits *traits = [[alert textField] textInputTraits];
8461 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8462 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8463 [traits setKeyboardType:UIKeyboardTypeURL];
8464 // XXX: UIReturnKeyDone
8465 [traits setReturnKeyType:UIReturnKeyNext];
8466
8467 [alert show];
8468 }
8469
8470 - (void) addButtonClicked {
8471 [self showAddSourcePrompt];
8472 }
8473
8474 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8475 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8476 initWithTitle:UCLocalize("ADD")
8477 style:UIBarButtonItemStylePlain
8478 target:self
8479 action:@selector(addButtonClicked)
8480 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8481
8482 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8483 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8484 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8485 target:self
8486 action:@selector(editButtonClicked)
8487 ] autorelease] animated:animated];
8488
8489 if (IsWildcat_ && !editing)
8490 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8491 initWithTitle:UCLocalize("SETTINGS")
8492 style:UIBarButtonItemStylePlain
8493 target:self
8494 action:@selector(settingsButtonClicked)
8495 ] autorelease]];
8496 }
8497
8498 - (void) settingsButtonClicked {
8499 [delegate_ showSettings];
8500 }
8501
8502 - (void) editButtonClicked {
8503 [list_ setEditing:![list_ isEditing] animated:YES];
8504
8505 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8506 }
8507
8508 @end
8509 /* }}} */
8510
8511 /* Settings Controller {{{ */
8512 @interface SettingsController : CyteViewController <
8513 UITableViewDataSource,
8514 UITableViewDelegate
8515 > {
8516 _transient Database *database_;
8517 // XXX: ok, "roledelegate_"?...
8518 _transient id roledelegate_;
8519 UITableView *table_;
8520 UISegmentedControl *segment_;
8521 UIView *container_;
8522 }
8523
8524 - (void) showDoneButton;
8525 - (void) resizeSegmentedControl;
8526
8527 @end
8528
8529 @implementation SettingsController
8530
8531 - (void) dealloc {
8532 [self releaseSubviews];
8533
8534 [super dealloc];
8535 }
8536
8537 - (void) loadView {
8538 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8539
8540 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8541 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8542 [table_ setDelegate:self];
8543 [table_ setDataSource:self];
8544 [[self view] addSubview:table_];
8545
8546 NSArray *items = [NSArray arrayWithObjects:
8547 UCLocalize("USER"),
8548 UCLocalize("HACKER"),
8549 UCLocalize("DEVELOPER"),
8550 nil];
8551 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8552 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8553 [container_ addSubview:segment_];
8554 }
8555
8556 - (void) viewDidLoad {
8557 [super viewDidLoad];
8558
8559 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8560
8561 int index = -1;
8562 if ([Role_ isEqualToString:@"User"]) index = 0;
8563 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8564 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8565 if (index != -1) {
8566 [segment_ setSelectedSegmentIndex:index];
8567 [self showDoneButton];
8568 }
8569
8570 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8571 [self resizeSegmentedControl];
8572 }
8573
8574 - (void) releaseSubviews {
8575 [table_ release];
8576 table_ = nil;
8577
8578 [segment_ release];
8579 segment_ = nil;
8580
8581 [container_ release];
8582 container_ = nil;
8583 }
8584
8585 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8586 if ((self = [super init]) != nil) {
8587 database_ = database;
8588 roledelegate_ = delegate;
8589 } return self;
8590 }
8591
8592 - (void) resizeSegmentedControl {
8593 CGFloat width = [[self view] frame].size.width;
8594 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8595 }
8596
8597 - (void) viewWillAppear:(BOOL)animated {
8598 [super viewWillAppear:animated];
8599
8600 [self resizeSegmentedControl];
8601 }
8602
8603 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8604 [self resizeSegmentedControl];
8605 }
8606
8607 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8608 [self resizeSegmentedControl];
8609 }
8610
8611 - (void) save {
8612 NSString *role(nil);
8613
8614 switch ([segment_ selectedSegmentIndex]) {
8615 case 0: role = @"User"; break;
8616 case 1: role = @"Hacker"; break;
8617 case 2: role = @"Developer"; break;
8618
8619 _nodefault
8620 }
8621
8622 if (![role isEqualToString:Role_]) {
8623 bool rolling(Role_ == nil);
8624 Role_ = role;
8625
8626 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8627 Role_, @"Role",
8628 nil];
8629
8630 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8631 Changed_ = true;
8632
8633 if (rolling)
8634 [roledelegate_ loadData];
8635 else
8636 [roledelegate_ updateData];
8637 }
8638 }
8639
8640 - (void) segmentChanged:(UISegmentedControl *)control {
8641 [self showDoneButton];
8642 }
8643
8644 - (void) saveAndClose {
8645 [self save];
8646
8647 [[self navigationItem] setRightBarButtonItem:nil];
8648 [[self navigationController] dismissModalViewControllerAnimated:YES];
8649 }
8650
8651 - (void) doneButtonClicked {
8652 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8653 [spinner startAnimating];
8654 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8655 [[self navigationItem] setRightBarButtonItem:spinItem];
8656
8657 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8658 }
8659
8660 - (void) showDoneButton {
8661 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8662 initWithTitle:UCLocalize("DONE")
8663 style:UIBarButtonItemStyleDone
8664 target:self
8665 action:@selector(doneButtonClicked)
8666 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8667 }
8668
8669 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8670 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8671 return 6;
8672 }
8673
8674 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8675 return 0; // :(
8676 }
8677
8678 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8679 return nil; // This method is required by the protocol.
8680 }
8681
8682 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8683 if (section == 1)
8684 return UCLocalize("ROLE_EX");
8685 if (section == 4)
8686 return [NSString stringWithFormat:
8687 @"%@: %@\n%@: %@\n%@: %@",
8688 UCLocalize("USER"), UCLocalize("USER_EX"),
8689 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8690 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8691 ];
8692 else return nil;
8693 }
8694
8695 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8696 return section == 3 ? 44.0f : 0;
8697 }
8698
8699 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8700 return section == 3 ? container_ : nil;
8701 }
8702
8703 - (void) reloadData {
8704 [super reloadData];
8705
8706 [table_ reloadData];
8707 }
8708
8709 @end
8710 /* }}} */
8711 /* Stash Controller {{{ */
8712 @interface StashController : CyteViewController {
8713 UIActivityIndicatorView *spinner_;
8714 UILabel *status_;
8715 UILabel *caption_;
8716 }
8717
8718 @end
8719
8720 @implementation StashController
8721
8722 - (void) dealloc {
8723 [self releaseSubviews];
8724
8725 [super dealloc];
8726 }
8727
8728 - (void) loadView {
8729 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8730 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8731
8732 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8733 CGRect spinrect = [spinner_ frame];
8734 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8735 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8736 [spinner_ setFrame:spinrect];
8737 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8738 [[self view] addSubview:spinner_];
8739 [spinner_ startAnimating];
8740
8741 CGRect captrect;
8742 captrect.size.width = [[self view] frame].size.width;
8743 captrect.size.height = 40.0f;
8744 captrect.origin.x = 0;
8745 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8746 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8747 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8748 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8749 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8750 [caption_ setTextColor:[UIColor whiteColor]];
8751 [caption_ setBackgroundColor:[UIColor clearColor]];
8752 [caption_ setShadowColor:[UIColor blackColor]];
8753 [caption_ setTextAlignment:UITextAlignmentCenter];
8754 [[self view] addSubview:caption_];
8755
8756 CGRect statusrect;
8757 statusrect.size.width = [[self view] frame].size.width;
8758 statusrect.size.height = 30.0f;
8759 statusrect.origin.x = 0;
8760 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8761 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8762 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8763 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8764 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8765 [status_ setTextColor:[UIColor whiteColor]];
8766 [status_ setBackgroundColor:[UIColor clearColor]];
8767 [status_ setShadowColor:[UIColor blackColor]];
8768 [status_ setTextAlignment:UITextAlignmentCenter];
8769 [[self view] addSubview:status_];
8770 }
8771
8772 - (void) releaseSubviews {
8773 [spinner_ release];
8774 spinner_ = nil;
8775
8776 [status_ release];
8777 status_ = nil;
8778
8779 [caption_ release];
8780 caption_ = nil;
8781 }
8782
8783 @end
8784 /* }}} */
8785
8786 @interface CYURLCache : SDURLCache {
8787 }
8788
8789 @end
8790
8791 @implementation CYURLCache
8792
8793 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8794 #if !ForRelease
8795 if (false);
8796 else if ([event isEqualToString:@"no-cache"])
8797 event = @"!!!";
8798 else if ([event isEqualToString:@"store"])
8799 event = @">>>";
8800 else if ([event isEqualToString:@"invalid"])
8801 event = @"???";
8802 else if ([event isEqualToString:@"memory"])
8803 event = @"mem";
8804 else if ([event isEqualToString:@"disk"])
8805 event = @"ssd";
8806 else if ([event isEqualToString:@"miss"])
8807 event = @"---";
8808
8809 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8810 #endif
8811 }
8812
8813 @end
8814
8815 @interface Cydia : UIApplication <
8816 ConfirmationControllerDelegate,
8817 DatabaseDelegate,
8818 CydiaDelegate,
8819 UINavigationControllerDelegate,
8820 UITabBarControllerDelegate
8821 > {
8822 // XXX: evaluate all fields for _transient
8823
8824 UIWindow *window_;
8825 CYTabBarController *tabbar_;
8826 CYEmulatedLoadingController *emulated_;
8827
8828 NSMutableArray *essential_;
8829 NSMutableArray *broken_;
8830
8831 Database *database_;
8832
8833 NSURL *starturl_;
8834
8835 unsigned locked_;
8836 unsigned activity_;
8837
8838 StashController *stash_;
8839
8840 bool loaded_;
8841 }
8842
8843 - (void) loadData;
8844
8845 @end
8846
8847 @implementation Cydia
8848
8849 - (void) beginUpdate {
8850 [tabbar_ beginUpdate];
8851 }
8852
8853 - (BOOL) updating {
8854 return [tabbar_ updating];
8855 }
8856
8857 - (void) _loaded {
8858 if ([broken_ count] != 0) {
8859 int count = [broken_ count];
8860
8861 UIAlertView *alert = [[[UIAlertView alloc]
8862 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8863 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8864 delegate:self
8865 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8866 otherButtonTitles:
8867 UCLocalize("TEMPORARY_IGNORE"),
8868 nil
8869 ] autorelease];
8870
8871 [alert setContext:@"fixhalf"];
8872 [alert setNumberOfRows:2];
8873 [alert show];
8874 } else if (!Ignored_ && [essential_ count] != 0) {
8875 int count = [essential_ count];
8876
8877 UIAlertView *alert = [[[UIAlertView alloc]
8878 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8879 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8880 delegate:self
8881 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8882 otherButtonTitles:
8883 UCLocalize("UPGRADE_ESSENTIAL"),
8884 UCLocalize("COMPLETE_UPGRADE"),
8885 nil
8886 ] autorelease];
8887
8888 [alert setContext:@"upgrade"];
8889 [alert show];
8890 }
8891 }
8892
8893 - (void) _saveConfig {
8894 _trace();
8895 MetaFile_.Sync();
8896 _trace();
8897
8898 if (Changed_) {
8899 NSString *error(nil);
8900
8901 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8902 _trace();
8903 NSError *error(nil);
8904 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8905 NSLog(@"failure to save metadata data: %@", error);
8906 _trace();
8907
8908 Changed_ = false;
8909 } else {
8910 NSLog(@"failure to serialize metadata: %@", error);
8911 }
8912 }
8913 }
8914
8915 // Navigation controller for the queuing badge.
8916 - (UINavigationController *) queueNavigationController {
8917 NSArray *controllers = [tabbar_ viewControllers];
8918 return [controllers objectAtIndex:3];
8919 }
8920
8921 - (void) unloadData {
8922 [tabbar_ unloadData];
8923 }
8924
8925 - (void) _updateData {
8926 [self _saveConfig];
8927
8928 [self unloadData];
8929
8930 UINavigationController *navigation = [self queueNavigationController];
8931
8932 id queuedelegate = nil;
8933 if ([[navigation viewControllers] count] > 0)
8934 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8935
8936 [queuedelegate queueStatusDidChange];
8937 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8938 }
8939
8940 - (void) _refreshIfPossible:(NSDate *)update {
8941 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8942
8943 bool recently = false;
8944 if (update != nil) {
8945 NSTimeInterval interval([update timeIntervalSinceNow]);
8946 if (interval <= 0 && interval > -(15*60))
8947 recently = true;
8948 }
8949
8950 // Don't automatic refresh if:
8951 // - We already refreshed recently.
8952 // - We already auto-refreshed this launch.
8953 // - Auto-refresh is disabled.
8954 if (recently || loaded_ || ManualRefresh) {
8955 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8956
8957 // If we are cancelling, we need to make sure it knows it's already loaded.
8958 loaded_ = true;
8959 return;
8960 } else {
8961 // We are going to load, so remember that.
8962 loaded_ = true;
8963 }
8964
8965 SCNetworkReachabilityFlags flags; {
8966 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8967 SCNetworkReachabilityGetFlags(reachability, &flags);
8968 CFRelease(reachability);
8969 }
8970
8971 // XXX: this elaborate mess is what Apple is using to determine this? :(
8972 // XXX: do we care if the user has to intervene? maybe that's ok?
8973 bool reachable(
8974 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8975 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8976 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8977 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8978 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8979 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8980 )
8981 );
8982
8983 // If we can reach the server, auto-refresh!
8984 if (reachable)
8985 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8986
8987 [pool release];
8988 }
8989
8990 - (void) refreshIfPossible {
8991 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8992 }
8993
8994 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8995 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8996 [hud setText:UCLocalize("RELOADING_DATA")];
8997
8998 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8999
9000 if (hud != nil)
9001 [self removeProgressHUD:hud];
9002
9003 size_t changes(0);
9004
9005 [essential_ removeAllObjects];
9006 [broken_ removeAllObjects];
9007
9008 NSArray *packages([database_ packages]);
9009 for (Package *package in packages) {
9010 if ([package half])
9011 [broken_ addObject:package];
9012 if ([package upgradableAndEssential:NO]) {
9013 if ([package essential])
9014 [essential_ addObject:package];
9015 ++changes;
9016 }
9017 }
9018
9019 NSLog(@"changes:#%u", changes);
9020
9021 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9022 if (changes != 0) {
9023 _trace();
9024 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9025 [changesItem setBadgeValue:badge];
9026 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9027 [self setApplicationIconBadgeNumber:changes];
9028 } else {
9029 _trace();
9030 [changesItem setBadgeValue:nil];
9031 [changesItem setAnimatedBadge:NO];
9032 [self setApplicationIconBadgeNumber:0];
9033 }
9034
9035 [self _updateData];
9036
9037 [self refreshIfPossible];
9038 }
9039
9040 - (void) updateData {
9041 [self _updateData];
9042 }
9043
9044 - (void) update_ {
9045 [database_ update];
9046 }
9047
9048 - (void) complete {
9049 @synchronized (self) {
9050 [self _reloadDataWithInvocation:nil];
9051 }
9052 }
9053
9054 - (void) disemulate {
9055 if (emulated_ == nil)
9056 return;
9057
9058 [window_ addSubview:[tabbar_ view]];
9059 [[emulated_ view] removeFromSuperview];
9060 [emulated_ release];
9061 emulated_ = nil;
9062 [window_ setUserInteractionEnabled:YES];
9063 }
9064
9065 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9066 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9067 if (IsWildcat_)
9068 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9069
9070 UIViewController *parent;
9071 if (emulated_ == nil)
9072 parent = tabbar_;
9073 else if (!force)
9074 parent = emulated_;
9075 else {
9076 [self disemulate];
9077 parent = tabbar_;
9078 }
9079
9080 [parent presentModalViewController:navigation animated:YES];
9081 }
9082
9083 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9084 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9085
9086 if (navigation != nil)
9087 [navigation pushViewController:progress animated:YES];
9088 else
9089 [self presentModalViewController:progress force:YES];
9090
9091 [progress invoke:invocation withTitle:title];
9092 return progress;
9093 }
9094
9095 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9096 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9097 }
9098
9099 - (void) repairWithInvocation:(NSInvocation *)invocation {
9100 _trace();
9101 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9102 _trace();
9103 }
9104
9105 - (void) repairWithSelector:(SEL)selector {
9106 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9107 }
9108
9109 - (void) syncData {
9110 [self _saveConfig];
9111
9112 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9113 _assert(file != NULL);
9114
9115 for (NSString *key in [Sources_ allKeys]) {
9116 NSDictionary *source([Sources_ objectForKey:key]);
9117
9118 fprintf(file, "%s %s %s\n",
9119 [[source objectForKey:@"Type"] UTF8String],
9120 [[source objectForKey:@"URI"] UTF8String],
9121 [[source objectForKey:@"Distribution"] UTF8String]
9122 );
9123 }
9124
9125 fclose(file);
9126
9127 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9128
9129 [self complete];
9130 }
9131
9132 - (void) addTrivialSource:(NSString *)href {
9133 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9134 @"deb", @"Type",
9135 href, @"URI",
9136 @"./", @"Distribution",
9137 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9138
9139 Changed_ = true;
9140 }
9141
9142 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9143 @synchronized (self) {
9144 [self _reloadDataWithInvocation:invocation];
9145 }
9146 }
9147
9148 - (void) reloadData {
9149 [self reloadDataWithInvocation:nil];
9150 }
9151
9152 - (void) resolve {
9153 pkgProblemResolver *resolver = [database_ resolver];
9154
9155 resolver->InstallProtect();
9156 if (!resolver->Resolve(true))
9157 _error->Discard();
9158 }
9159
9160 - (bool) perform {
9161 // XXX: this is a really crappy way of doing this.
9162 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9163 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9164 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9165 if ([tabbar_ updating])
9166 [tabbar_ cancelUpdate];
9167
9168 if (![database_ prepare])
9169 return false;
9170
9171 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9172 [page setDelegate:self];
9173 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9174
9175 if (IsWildcat_)
9176 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9177 [tabbar_ presentModalViewController:confirm_ animated:YES];
9178
9179 return true;
9180 }
9181
9182 - (void) queue {
9183 @synchronized (self) {
9184 [self perform];
9185 }
9186 }
9187
9188 - (void) clearPackage:(Package *)package {
9189 @synchronized (self) {
9190 [package clear];
9191 [self resolve];
9192 [self perform];
9193 }
9194 }
9195
9196 - (void) installPackages:(NSArray *)packages {
9197 @synchronized (self) {
9198 for (Package *package in packages)
9199 [package install];
9200 [self resolve];
9201 [self perform];
9202 }
9203 }
9204
9205 - (void) installPackage:(Package *)package {
9206 @synchronized (self) {
9207 [package install];
9208 [self resolve];
9209 [self perform];
9210 }
9211 }
9212
9213 - (void) removePackage:(Package *)package {
9214 @synchronized (self) {
9215 [package remove];
9216 [self resolve];
9217 [self perform];
9218 }
9219 }
9220
9221 - (void) distUpgrade {
9222 @synchronized (self) {
9223 if (![database_ upgrade])
9224 return;
9225 [self perform];
9226 }
9227 }
9228
9229 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9230 Queuing_ = false;
9231 ++locked_;
9232 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9233 --locked_;
9234 [self complete];
9235 }
9236
9237 - (void) showSettings {
9238 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9239 }
9240
9241 - (void) retainNetworkActivityIndicator {
9242 if (activity_++ == 0)
9243 [self setNetworkActivityIndicatorVisible:YES];
9244
9245 #if TraceLogging
9246 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9247 #endif
9248 }
9249
9250 - (void) releaseNetworkActivityIndicator {
9251 if (--activity_ == 0)
9252 [self setNetworkActivityIndicatorVisible:NO];
9253
9254 #if TraceLogging
9255 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9256 #endif
9257
9258 }
9259
9260 - (void) cancelAndClear:(bool)clear {
9261 @synchronized (self) {
9262 if (clear) {
9263 [database_ clear];
9264 Queuing_ = false;
9265 } else {
9266 Queuing_ = true;
9267 }
9268
9269 [self _updateData];
9270 }
9271 }
9272
9273 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9274 NSString *context([alert context]);
9275
9276 if ([context isEqualToString:@"conffile"]) {
9277 FILE *input = [database_ input];
9278 if (button == [alert cancelButtonIndex])
9279 fprintf(input, "N\n");
9280 else if (button == [alert firstOtherButtonIndex])
9281 fprintf(input, "Y\n");
9282 fflush(input);
9283
9284 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9285 } else if ([context isEqualToString:@"fixhalf"]) {
9286 if (button == [alert cancelButtonIndex]) {
9287 @synchronized (self) {
9288 for (Package *broken in broken_) {
9289 [broken remove];
9290
9291 NSString *id = [broken id];
9292 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9293 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9294 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9295 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9296 }
9297
9298 [self resolve];
9299 [self perform];
9300 }
9301 } else if (button == [alert firstOtherButtonIndex]) {
9302 [broken_ removeAllObjects];
9303 [self _loaded];
9304 }
9305
9306 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9307 } else if ([context isEqualToString:@"upgrade"]) {
9308 if (button == [alert firstOtherButtonIndex]) {
9309 @synchronized (self) {
9310 for (Package *essential in essential_)
9311 [essential install];
9312
9313 [self resolve];
9314 [self perform];
9315 }
9316 } else if (button == [alert firstOtherButtonIndex] + 1) {
9317 [self distUpgrade];
9318 } else if (button == [alert cancelButtonIndex]) {
9319 Ignored_ = YES;
9320 }
9321
9322 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9323 }
9324 }
9325
9326 - (void) system:(NSString *)command { _pooled
9327 _trace();
9328 system([command UTF8String]);
9329 _trace();
9330 }
9331
9332 - (void) applicationWillSuspend {
9333 [database_ clean];
9334 [super applicationWillSuspend];
9335 }
9336
9337 - (BOOL) isSafeToSuspend {
9338 if (locked_ != 0) {
9339 #if !ForRelease
9340 NSLog(@"isSafeToSuspend: locked_ != 0");
9341 #endif
9342 return false;
9343 }
9344
9345 // Use external process status API internally.
9346 // This is probably a really bad idea.
9347 // XXX: what is the point of this? does this solve anything at all?
9348 uint64_t status = 0;
9349 int notify_token;
9350 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9351 notify_get_state(notify_token, &status);
9352 notify_cancel(notify_token);
9353 }
9354
9355 if (status != 0) {
9356 #if !ForRelease
9357 NSLog(@"isSafeToSuspend: status != 0");
9358 #endif
9359 return false;
9360 }
9361
9362 #if !ForRelease
9363 NSLog(@"isSafeToSuspend: -> true");
9364 #endif
9365 return true;
9366 }
9367
9368 - (void) applicationSuspend:(__GSEvent *)event {
9369 if ([self isSafeToSuspend])
9370 [super applicationSuspend:event];
9371 }
9372
9373 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9374 if ([self isSafeToSuspend])
9375 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9376 }
9377
9378 - (void) _setSuspended:(BOOL)value {
9379 if ([self isSafeToSuspend])
9380 [super _setSuspended:value];
9381 }
9382
9383 - (UIProgressHUD *) addProgressHUD {
9384 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9385 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9386
9387 [window_ setUserInteractionEnabled:NO];
9388
9389 UIViewController *target(tabbar_);
9390 if (UIViewController *modal = [target modalViewController])
9391 target = modal;
9392
9393 UIView *view([target view]);
9394 [view addSubview:hud];
9395
9396 [hud show:YES];
9397
9398 ++locked_;
9399 return hud;
9400 }
9401
9402 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9403 --locked_;
9404 [hud show:NO];
9405 [hud removeFromSuperview];
9406 [window_ setUserInteractionEnabled:YES];
9407 }
9408
9409 - (CyteViewController *) pageForPackage:(NSString *)name {
9410 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9411 }
9412
9413 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9414 NSString *scheme([[url scheme] lowercaseString]);
9415 if ([[url absoluteString] length] <= [scheme length] + 3)
9416 return nil;
9417 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9418 NSArray *components([path pathComponents]);
9419
9420 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9421 return [self pageForPackage:[components objectAtIndex:1]];
9422
9423 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9424 return nil;
9425
9426 NSString *base([components objectAtIndex:0]);
9427
9428 CyteViewController *controller = nil;
9429
9430 if ([base isEqualToString:@"url"]) {
9431 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9432 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9433 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9434 } else if (!external && [components count] == 1) {
9435 if ([base isEqualToString:@"manage"]) {
9436 controller = [[[ManageController alloc] init] autorelease];
9437 }
9438
9439 if ([base isEqualToString:@"sources"]) {
9440 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9441 }
9442
9443 if ([base isEqualToString:@"home"]) {
9444 controller = [[[HomeController alloc] init] autorelease];
9445 }
9446
9447 if ([base isEqualToString:@"sections"]) {
9448 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9449 }
9450
9451 if ([base isEqualToString:@"search"]) {
9452 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9453 }
9454
9455 if ([base isEqualToString:@"changes"]) {
9456 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9457 }
9458
9459 if ([base isEqualToString:@"installed"]) {
9460 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9461 }
9462 } else if ([components count] == 2) {
9463 NSString *argument = [components objectAtIndex:1];
9464
9465 if ([base isEqualToString:@"package"]) {
9466 controller = [self pageForPackage:argument];
9467 }
9468
9469 if (!external && [base isEqualToString:@"search"]) {
9470 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9471 }
9472
9473 if (!external && [base isEqualToString:@"sections"]) {
9474 if ([argument isEqualToString:@"all"])
9475 argument = nil;
9476 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9477 }
9478
9479 if (!external && [base isEqualToString:@"sources"]) {
9480 if ([argument isEqualToString:@"add"]) {
9481 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9482 [(SourcesController *)controller showAddSourcePrompt];
9483 } else {
9484 Source *source = [database_ sourceWithKey:argument];
9485 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9486 }
9487 }
9488
9489 if (!external && [base isEqualToString:@"launch"]) {
9490 [self launchApplicationWithIdentifier:argument suspended:NO];
9491 return nil;
9492 }
9493 } else if (!external && [components count] == 3) {
9494 NSString *arg1 = [components objectAtIndex:1];
9495 NSString *arg2 = [components objectAtIndex:2];
9496
9497 if ([base isEqualToString:@"package"]) {
9498 if ([arg2 isEqualToString:@"settings"]) {
9499 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9500 } else if ([arg2 isEqualToString:@"files"]) {
9501 if (Package *package = [database_ packageWithName:arg1]) {
9502 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9503 [(FileTable *)controller setPackage:package];
9504 }
9505 }
9506 }
9507 }
9508
9509 [controller setDelegate:self];
9510 return controller;
9511 }
9512
9513 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9514 CyteViewController *page([self pageForURL:url forExternal:external]);
9515
9516 if (page != nil) {
9517 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9518 [nav setViewControllers:[NSArray arrayWithObject:page]];
9519 [tabbar_ setUnselectedViewController:nav];
9520 }
9521
9522 return page != nil;
9523 }
9524
9525 - (void) applicationOpenURL:(NSURL *)url {
9526 [super applicationOpenURL:url];
9527
9528 if (!loaded_) starturl_ = [url retain];
9529 else [self openCydiaURL:url forExternal:YES];
9530 }
9531
9532 - (void) applicationWillResignActive:(UIApplication *)application {
9533 // Stop refreshing if you get a phone call or lock the device.
9534 if ([tabbar_ updating])
9535 [tabbar_ cancelUpdate];
9536
9537 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9538 [super applicationWillResignActive:application];
9539 }
9540
9541 - (void) applicationWillTerminate:(UIApplication *)application {
9542 Changed_ = true;
9543 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9544 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9545 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9546
9547 [self _saveConfig];
9548 }
9549
9550 - (void) setConfigurationData:(NSString *)data {
9551 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9552
9553 if (!conffile_r(data)) {
9554 lprintf("E:invalid conffile\n");
9555 return;
9556 }
9557
9558 NSString *ofile = conffile_r[1];
9559 //NSString *nfile = conffile_r[2];
9560
9561 UIAlertView *alert = [[[UIAlertView alloc]
9562 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9563 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9564 delegate:self
9565 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9566 otherButtonTitles:
9567 UCLocalize("ACCEPT_NEW_COPY"),
9568 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9569 nil
9570 ] autorelease];
9571
9572 [alert setContext:@"conffile"];
9573 [alert setNumberOfRows:2];
9574 [alert show];
9575 }
9576
9577 - (void) addStashController {
9578 ++locked_;
9579 stash_ = [[StashController alloc] init];
9580 [window_ addSubview:[stash_ view]];
9581 }
9582
9583 - (void) removeStashController {
9584 [[stash_ view] removeFromSuperview];
9585 [stash_ release];
9586 --locked_;
9587 }
9588
9589 - (void) stash {
9590 [self setIdleTimerDisabled:YES];
9591
9592 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9593 UpdateExternalStatus(1);
9594 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9595 UpdateExternalStatus(0);
9596
9597 [self removeStashController];
9598
9599 if (ExecFork() == 0) {
9600 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9601 perror("launchctl stop");
9602 }
9603 }
9604
9605 - (void) setupViewControllers {
9606 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9607
9608 NSMutableArray *items([NSMutableArray arrayWithObjects:
9609 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9610 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9611 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9612 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9613 nil]);
9614
9615 if (IsWildcat_) {
9616 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9617 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9618 } else {
9619 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9620 }
9621
9622 NSMutableArray *controllers([NSMutableArray array]);
9623 for (UITabBarItem *item in items) {
9624 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9625 [controller setTabBarItem:item];
9626 [controllers addObject:controller];
9627 }
9628 [tabbar_ setViewControllers:controllers];
9629
9630 [tabbar_ setUpdateDelegate:self];
9631 }
9632
9633 - (void) applicationDidFinishLaunching:(id)unused {
9634 _trace();
9635 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9636 [self setApplicationSupportsShakeToEdit:NO];
9637
9638 @synchronized (HostConfig_) {
9639 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9640 }
9641
9642 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9643 initWithMemoryCapacity:524288
9644 diskCapacity:10485760
9645 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9646 ] autorelease]];
9647
9648 [CydiaWebViewController _initialize];
9649
9650 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9651
9652 // this would disallow http{,s} URLs from accessing this data
9653 //[WebView registerURLSchemeAsLocal:@"cydia"];
9654
9655 Font12_ = [[UIFont systemFontOfSize:12] retain];
9656 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9657 Font14_ = [[UIFont systemFontOfSize:14] retain];
9658 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9659 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9660
9661 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9662 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9663
9664 // XXX: I really need this thing... like, seriously... I'm sorry
9665 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9666
9667 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9668 [window_ orderFront:self];
9669 [window_ makeKey:self];
9670 [window_ setHidden:NO];
9671
9672 if (
9673 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9674 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9675 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9676 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9677 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9678 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9679 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9680 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9681 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9682 false
9683 ) {
9684 [self addStashController];
9685 // XXX: this would be much cleaner as a yieldToSelector:
9686 // that way the removeStashController could happen right here inline
9687 // we also could no longer require the useless stash_ field anymore
9688 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9689 return;
9690 }
9691
9692 database_ = [Database sharedInstance];
9693 [database_ setDelegate:self];
9694
9695 [window_ setUserInteractionEnabled:NO];
9696 [self setupViewControllers];
9697
9698 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9699 [window_ addSubview:[emulated_ view]];
9700
9701 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9702 _trace();
9703 }
9704
9705 - (NSArray *) defaultStartPages {
9706 NSMutableArray *standard = [NSMutableArray array];
9707 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9708 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9709 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9710 if (!IsWildcat_) {
9711 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9712 } else {
9713 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9714 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9715 }
9716 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9717 return standard;
9718 }
9719
9720 - (void) loadData {
9721 _trace();
9722 if (Role_ == nil) {
9723 [window_ setUserInteractionEnabled:YES];
9724 [self showSettings];
9725 return;
9726 } else {
9727 if ([emulated_ modalViewController] != nil)
9728 [emulated_ dismissModalViewControllerAnimated:YES];
9729 [window_ setUserInteractionEnabled:NO];
9730 }
9731
9732 [self reloadData];
9733 PrintTimes();
9734
9735 [self disemulate];
9736
9737 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9738 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9739 int standardIndex = 0;
9740 NSArray *standard = [self defaultStartPages];
9741
9742 BOOL valid = YES;
9743
9744 if (saved == nil)
9745 valid = NO;
9746
9747 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9748 if (valid && closed != nil) {
9749 NSTimeInterval interval([closed timeIntervalSinceNow]);
9750 // XXX: Is 15 minutes the optimal time here?
9751 if (interval > 0 && interval <= -(15*60))
9752 valid = NO;
9753 }
9754
9755 if (valid && [saved count] != [standard count])
9756 valid = NO;
9757
9758 if (valid) {
9759 for (unsigned int i = 0; i < [standard count]; i++) {
9760 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9761 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9762 // but it's good enough for now.
9763 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9764 valid = NO;
9765 break;
9766 }
9767 }
9768 }
9769
9770 NSArray *items = nil;
9771 if (valid) {
9772 [tabbar_ setSelectedIndex:savedIndex];
9773 items = saved;
9774 } else {
9775 [tabbar_ setSelectedIndex:standardIndex];
9776 items = standard;
9777 }
9778
9779 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9780 NSArray *stack = [items objectAtIndex:tab];
9781 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9782 NSMutableArray *current = [NSMutableArray array];
9783
9784 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9785 NSString *addr = [stack objectAtIndex:nav];
9786 NSURL *url = [NSURL URLWithString:addr];
9787 CyteViewController *page = [self pageForURL:url forExternal:NO];
9788 if (page != nil)
9789 [current addObject:page];
9790 }
9791
9792 [navigation setViewControllers:current];
9793 }
9794
9795 // (Try to) show the startup URL.
9796 if (starturl_ != nil) {
9797 [self openCydiaURL:starturl_ forExternal:NO];
9798 [starturl_ release];
9799 starturl_ = nil;
9800 }
9801 }
9802
9803 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9804 if (item != nil && IsWildcat_) {
9805 [sheet showFromBarButtonItem:item animated:YES];
9806 } else {
9807 [sheet showInView:window_];
9808 }
9809 }
9810
9811 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9812 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9813 [progress setTitle:task];
9814 [progress addProgressEvent:event];
9815 }
9816
9817 - (void) addProgressEventForTask:(NSArray *)data {
9818 CydiaProgressEvent *event([data objectAtIndex:0]);
9819 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9820 [self addProgressEvent:event forTask:task];
9821 }
9822
9823 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9824 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9825 }
9826
9827 @end
9828
9829 /*IMP alloc_;
9830 id Alloc_(id self, SEL selector) {
9831 id object = alloc_(self, selector);
9832 lprintf("[%s]A-%p\n", self->isa->name, object);
9833 return object;
9834 }*/
9835
9836 /*IMP dealloc_;
9837 id Dealloc_(id self, SEL selector) {
9838 id object = dealloc_(self, selector);
9839 lprintf("[%s]D-%p\n", self->isa->name, object);
9840 return object;
9841 }*/
9842
9843 Class $WebDefaultUIKitDelegate;
9844
9845 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9846 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9847 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9848 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9849 }
9850
9851 static NSSet *MobilizedFiles_;
9852
9853 static NSURL *MobilizeURL(NSURL *url) {
9854 NSString *path([url path]);
9855 if ([path hasPrefix:@"/var/root/"]) {
9856 NSString *file([path substringFromIndex:10]);
9857 if ([MobilizedFiles_ containsObject:file])
9858 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9859 }
9860
9861 return url;
9862 }
9863
9864 Class $CFXPreferencesPropertyListSource;
9865 @class CFXPreferencesPropertyListSource;
9866
9867 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9868 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9869 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9870 url = MobilizeURL(url);
9871 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9872 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9873 url = old;
9874 [pool release];
9875 return value;
9876 }
9877
9878 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9879 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9880 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9881 url = MobilizeURL(url);
9882 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9883 //NSLog(@"%@ %@", [url absoluteString], value);
9884 url = old;
9885 [pool release];
9886 return value;
9887 }
9888
9889 Class $NSURLConnection;
9890
9891 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9892 NSMutableURLRequest *copy([request mutableCopy]);
9893
9894 NSURL *url([copy URL]);
9895 NSString *host([url host]);
9896 NSString *scheme([[url scheme] lowercaseString]);
9897
9898 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9899
9900 @synchronized (HostConfig_) {
9901 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9902 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9903 [copy setHTTPShouldUsePipelining:YES];
9904 }
9905
9906 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9907 } return self;
9908 }
9909
9910 int main(int argc, char *argv[]) { _pooled
9911 _trace();
9912
9913 UpdateExternalStatus(0);
9914
9915 if (Class $UIDevice = objc_getClass("UIDevice")) {
9916 UIDevice *device([$UIDevice currentDevice]);
9917 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9918 } else
9919 IsWildcat_ = false;
9920
9921 UIScreen *screen([UIScreen mainScreen]);
9922 if ([screen respondsToSelector:@selector(scale)])
9923 ScreenScale_ = [screen scale];
9924 else
9925 ScreenScale_ = 1;
9926
9927 UIDevice *device([UIDevice currentDevice]);
9928 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9929 Idiom_ = @"iphone";
9930 else {
9931 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9932 if (idiom == UIUserInterfaceIdiomPhone)
9933 Idiom_ = @"iphone";
9934 else if (idiom == UIUserInterfaceIdiomPad)
9935 Idiom_ = @"ipad";
9936 else
9937 NSLog(@"unknown UIUserInterfaceIdiom!");
9938 }
9939
9940 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
9941
9942 HostConfig_ = [[NSObject alloc] init];
9943 @synchronized (HostConfig_) {
9944 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9945 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9946 }
9947
9948 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9949
9950 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9951
9952 MobilizedFiles_ = [NSMutableSet setWithObjects:
9953 @"Library/Preferences/com.apple.Accessibility.plist",
9954 @"Library/Preferences/com.apple.preferences.sounds.plist",
9955 nil];
9956
9957 /* Library Hacks {{{ */
9958 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9959
9960 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9961
9962 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9963 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9964 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9965 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9966 }
9967
9968 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9969 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9970 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9971 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9972 }
9973
9974 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9975 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9976 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9977 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9978 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9979 }
9980
9981 $NSURLConnection = objc_getClass("NSURLConnection");
9982 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9983 if (NSURLConnection$init$ != NULL) {
9984 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9985 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9986 }
9987 /* }}} */
9988 /* Set Locale {{{ */
9989 Locale_ = CFLocaleCopyCurrent();
9990 Languages_ = [NSLocale preferredLanguages];
9991
9992 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9993 //NSLog(@"%@", [Languages_ description]);
9994
9995 const char *lang;
9996 if (Locale_ != NULL)
9997 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9998 else if (Languages_ != nil && [Languages_ count] != 0)
9999 lang = [[Languages_ objectAtIndex:0] UTF8String];
10000 else
10001 // XXX: consider just setting to C and then falling through?
10002 lang = NULL;
10003
10004 if (lang != NULL) {
10005 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10006 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10007 }
10008
10009 NSLog(@"Setting Language: %s", lang);
10010
10011 if (lang != NULL) {
10012 setenv("LANG", lang, true);
10013 std::setlocale(LC_ALL, lang);
10014 }
10015 /* }}} */
10016
10017 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10018
10019 /* Parse Arguments {{{ */
10020 bool substrate(false);
10021
10022 if (argc != 0) {
10023 char **args(argv);
10024 int arge(1);
10025
10026 for (int argi(1); argi != argc; ++argi)
10027 if (strcmp(argv[argi], "--") == 0) {
10028 arge = argi;
10029 argv[argi] = argv[0];
10030 argv += argi;
10031 argc -= argi;
10032 break;
10033 }
10034
10035 for (int argi(1); argi != arge; ++argi)
10036 if (strcmp(args[argi], "--substrate") == 0)
10037 substrate = true;
10038 else
10039 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10040 }
10041 /* }}} */
10042
10043 App_ = [[NSBundle mainBundle] bundlePath];
10044 Advanced_ = YES;
10045
10046 setuid(0);
10047 setgid(0);
10048
10049 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10050 alloc_ = alloc->method_imp;
10051 alloc->method_imp = (IMP) &Alloc_;*/
10052
10053 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10054 dealloc_ = dealloc->method_imp;
10055 dealloc->method_imp = (IMP) &Dealloc_;*/
10056
10057 /* System Information {{{ */
10058 size_t size;
10059
10060 int maxproc;
10061 size = sizeof(maxproc);
10062 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10063 perror("sysctlbyname(\"kern.maxproc\", ?)");
10064 else if (maxproc < 64) {
10065 maxproc = 64;
10066 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10067 perror("sysctlbyname(\"kern.maxproc\", #)");
10068 }
10069
10070 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10071 char *osversion = new char[size];
10072 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10073 perror("sysctlbyname(\"kern.osversion\", ?)");
10074 else
10075 System_ = [NSString stringWithUTF8String:osversion];
10076
10077 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10078 char *machine = new char[size];
10079 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10080 perror("sysctlbyname(\"hw.machine\", ?)");
10081 else
10082 Machine_ = machine;
10083
10084 SerialNumber_ = CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10085 ChipID_ = CYHex(CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true, true);
10086 BBSNum_ = CYHex(CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false, false);
10087
10088 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10089
10090 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10091 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10092 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10093
10094 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10095 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10096 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10097
10098 if (mcc != NULL && mnc != NULL)
10099 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10100
10101 if (mnc != NULL)
10102 CFRelease(mnc);
10103 if (mcc != NULL)
10104 CFRelease(mcc);
10105
10106 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10107 Build_ = [system objectForKey:@"ProductBuildVersion"];
10108 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10109 Product_ = [info objectForKey:@"SafariProductVersion"];
10110 Safari_ = [info objectForKey:@"CFBundleVersion"];
10111 }
10112 /* }}} */
10113 /* Load Database {{{ */
10114 _trace();
10115 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10116 _trace();
10117 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10118
10119 if (Metadata_ == NULL)
10120 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10121 else {
10122 Settings_ = [Metadata_ objectForKey:@"Settings"];
10123
10124 Packages_ = [Metadata_ objectForKey:@"Packages"];
10125 Sections_ = [Metadata_ objectForKey:@"Sections"];
10126 Sources_ = [Metadata_ objectForKey:@"Sources"];
10127
10128 Token_ = [Metadata_ objectForKey:@"Token"];
10129 }
10130
10131 if (Settings_ != nil)
10132 Role_ = [Settings_ objectForKey:@"Role"];
10133
10134 if (Sections_ == nil) {
10135 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10136 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10137 }
10138
10139 if (Sources_ == nil) {
10140 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10141 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10142 }
10143 /* }}} */
10144
10145 _trace();
10146 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10147 _trace();
10148
10149 if (Packages_ != nil) {
10150 bool fail(false);
10151 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10152 _trace();
10153
10154 if (!fail) {
10155 [Metadata_ removeObjectForKey:@"Packages"];
10156 Packages_ = nil;
10157 Changed_ = true;
10158 }
10159 }
10160
10161 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10162
10163 #define MobileSubstrate_(name) \
10164 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10165 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10166 if (handle == NULL) \
10167 NSLog(@"%s", dlerror()); \
10168 }
10169
10170 MobileSubstrate_(Activator)
10171 MobileSubstrate_(libstatusbar)
10172 MobileSubstrate_(SimulatedKeyEvents)
10173 MobileSubstrate_(WinterBoard)
10174
10175 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10176 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10177
10178 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10179
10180 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10181 unlink("/tmp/.cydia.fw");
10182 goto firmware;
10183 } else if (access("/User", F_OK) != 0 || version < 4) {
10184 firmware:
10185 _trace();
10186 system("/usr/libexec/cydia/firmware.sh");
10187 _trace();
10188 }
10189
10190 _assert([[NSFileManager defaultManager]
10191 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10192 withIntermediateDirectories:YES
10193 attributes:nil
10194 error:NULL
10195 ]);
10196
10197 if (access("/tmp/cydia.chk", F_OK) == 0) {
10198 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10199 _assert(errno == ENOENT);
10200 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10201 _assert(errno == ENOENT);
10202 }
10203
10204 /* APT Initialization {{{ */
10205 _assert(pkgInitConfig(*_config));
10206 _assert(pkgInitSystem(*_config, _system));
10207
10208 if (lang != NULL)
10209 _config->Set("APT::Acquire::Translation", lang);
10210
10211 // XXX: this timeout might be important :(
10212 //_config->Set("Acquire::http::Timeout", 15);
10213
10214 _config->Set("Acquire::http::MaxParallel", 3);
10215 /* }}} */
10216 /* Color Choices {{{ */
10217 space_ = CGColorSpaceCreateDeviceRGB();
10218
10219 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10220 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10221 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10222 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10223 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10224 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10225 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10226 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10227 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10228
10229 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10230 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10231 /* }}}*/
10232 /* UIKit Configuration {{{ */
10233 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10234 if ($GSFontSetUseLegacyFontMetrics != NULL)
10235 $GSFontSetUseLegacyFontMetrics(YES);
10236
10237 // XXX: I have a feeling this was important
10238 //UIKeyboardDisableAutomaticAppearance();
10239 /* }}} */
10240
10241 Colon_ = UCLocalize("COLON_DELIMITED");
10242 Elision_ = UCLocalize("ELISION");
10243 Error_ = UCLocalize("ERROR");
10244 Warning_ = UCLocalize("WARNING");
10245
10246 _trace();
10247 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10248
10249 CGColorSpaceRelease(space_);
10250 CFRelease(Locale_);
10251
10252 return value;
10253 }