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