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