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