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