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