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