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