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