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