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