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