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