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