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