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