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