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