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