]> git.saurik.com Git - cydia.git/blob - Cydia.mm
Commit (chpwn): refresh-rotation-fixes.patch
[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 PackageView;
1225
1226 @protocol CydiaDelegate
1227 - (void) setPackageView:(PackageView *)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 - (PackageView *) packageView;
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 View {{{ */
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 ConfirmationViewDelegate
3983 - (void) cancelAndClear:(bool)clear;
3984 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3985 - (void) queue;
3986 @end
3987
3988 @interface ConfirmationView : 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 ConfirmationView
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 View {{{ */
4243 @interface ProgressView : 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 ProgressViewDelegate
4269 - (void) progressViewIsComplete:(ProgressView *)sender;
4270 @end
4271
4272 @implementation ProgressView
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_ progressViewIsComplete: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 View {{{ */
5144 @interface PackageView : 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 PackageView
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_ setPackageView: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.width = 320;
5299 frame.size.height = 0;
5300 [document_ setFrame:frame];
5301
5302 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5303 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5304 else
5305 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5306
5307 WebThreadLock();
5308 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5309
5310 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5311
5312 [self setFinishHook:nil];
5313 [self setPopupHook:nil];
5314 WebThreadUnlock();
5315
5316 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5317 [super callFunction:special_];
5318 }
5319 }
5320 }
5321
5322 - (void) didFinishLoading {
5323 int count = [buttons_ count];
5324 UIBarButtonItem *actionItem = [[UIBarButtonItem alloc]
5325 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5326 style:UIBarButtonItemStylePlain
5327 target:self
5328 action:@selector(actionButtonClicked)
5329 ];
5330 [[self navigationItem] setRightBarButtonItem:actionItem];
5331 [actionItem release];
5332 }
5333
5334 - (bool) isLoading {
5335 return commercial_ ? [super isLoading] : false;
5336 }
5337
5338 - (void) reloadData {
5339 [self setPackage:[database_ packageWithName:name_]];
5340 }
5341
5342 @end
5343 /* }}} */
5344 /* Package Table {{{ */
5345 @interface PackageTable : UIView {
5346 _transient Database *database_;
5347 NSMutableArray *packages_;
5348 NSMutableArray *sections_;
5349 UITableView *list_;
5350 NSMutableArray *index_;
5351 NSMutableDictionary *indices_;
5352 id target_;
5353 SEL action_;
5354 id delegate_;
5355 }
5356
5357 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5358
5359 - (void) setDelegate:(id)delegate;
5360
5361 - (void) reloadData;
5362 - (void) resetCursor;
5363
5364 - (UITableView *) list;
5365
5366 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5367
5368 - (void) deselectWithAnimation:(BOOL)animated;
5369
5370 @end
5371
5372 @implementation PackageTable
5373
5374 - (void) dealloc {
5375 [packages_ release];
5376 [sections_ release];
5377 [list_ release];
5378 [index_ release];
5379 [indices_ release];
5380
5381 [super dealloc];
5382 }
5383
5384 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5385 NSInteger count([sections_ count]);
5386 return count == 0 ? 1 : count;
5387 }
5388
5389 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5390 if ([sections_ count] == 0)
5391 return nil;
5392 return [[sections_ objectAtIndex:section] name];
5393 }
5394
5395 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5396 if ([sections_ count] == 0)
5397 return 0;
5398 return [[sections_ objectAtIndex:section] count];
5399 }
5400
5401 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5402 Section *section([sections_ objectAtIndex:[path section]]);
5403 NSInteger row([path row]);
5404 Package *package([packages_ objectAtIndex:([section row] + row)]);
5405 return package;
5406 }
5407
5408 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5409 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5410 if (cell == nil)
5411 cell = [[[PackageCell alloc] init] autorelease];
5412 [cell setPackage:[self packageAtIndexPath:path]];
5413 return cell;
5414 }
5415
5416 - (void) deselectWithAnimation:(BOOL)animated {
5417 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5418 }
5419
5420 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5421 return 73;
5422 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5423 }
5424
5425 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5426 Package *package([self packageAtIndexPath:path]);
5427 package = [database_ packageWithName:[package id]];
5428 [target_ performSelector:action_ withObject:package];
5429 return path;
5430 }
5431
5432 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5433 return [packages_ count] > 20 ? index_ : nil;
5434 }
5435
5436 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5437 return index;
5438 }
5439
5440 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5441 if ((self = [super initWithFrame:frame]) != nil) {
5442 database_ = database;
5443
5444 target_ = target;
5445 action_ = action;
5446
5447 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5448 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5449
5450 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5451 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5452
5453 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5454 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5455 [self addSubview:list_];
5456
5457 [list_ setDataSource:self];
5458 [list_ setDelegate:self];
5459 } return self;
5460 }
5461
5462 - (void) setDelegate:(id)delegate {
5463 delegate_ = delegate;
5464 }
5465
5466 - (bool) hasPackage:(Package *)package {
5467 return true;
5468 }
5469
5470 - (void) reloadData {
5471 NSArray *packages = [database_ packages];
5472
5473 [packages_ removeAllObjects];
5474 [sections_ removeAllObjects];
5475
5476 _profile(PackageTable$reloadData$Filter)
5477 for (Package *package in packages)
5478 if ([self hasPackage:package])
5479 [packages_ addObject:package];
5480 _end
5481
5482 [index_ removeAllObjects];
5483 [indices_ removeAllObjects];
5484
5485 Section *section = nil;
5486
5487 _profile(PackageTable$reloadData$Section)
5488 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5489 Package *package;
5490 unichar index;
5491
5492 _profile(PackageTable$reloadData$Section$Package)
5493 package = [packages_ objectAtIndex:offset];
5494 index = [package index];
5495 _end
5496
5497 if (section == nil || [section index] != index) {
5498 _profile(PackageTable$reloadData$Section$Allocate)
5499 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5500 _end
5501
5502 [index_ addObject:[section name]];
5503 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5504
5505 _profile(PackageTable$reloadData$Section$Add)
5506 [sections_ addObject:section];
5507 _end
5508 }
5509
5510 [section addToCount];
5511 }
5512 _end
5513
5514 _profile(PackageTable$reloadData$List)
5515 [list_ reloadData];
5516 _end
5517 }
5518
5519 - (void) resetCursor {
5520 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5521 }
5522
5523 - (UITableView *) list {
5524 return list_;
5525 }
5526
5527 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5528 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5529 }
5530
5531 @end
5532 /* }}} */
5533 /* Filtered Package Table {{{ */
5534 @interface FilteredPackageTable : PackageTable {
5535 SEL filter_;
5536 IMP imp_;
5537 id object_;
5538 }
5539
5540 - (void) setObject:(id)object;
5541 - (void) setObject:(id)object forFilter:(SEL)filter;
5542
5543 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5544
5545 @end
5546
5547 @implementation FilteredPackageTable
5548
5549 - (void) dealloc {
5550 if (object_ != nil)
5551 [object_ release];
5552 [super dealloc];
5553 }
5554
5555 - (void) setFilter:(SEL)filter {
5556 filter_ = filter;
5557
5558 /* XXX: this is an unsafe optimization of doomy hell */
5559 Method method(class_getInstanceMethod([Package class], filter));
5560 _assert(method != NULL);
5561 imp_ = method_getImplementation(method);
5562 _assert(imp_ != NULL);
5563 }
5564
5565 - (void) setObject:(id)object {
5566 if (object_ != nil)
5567 [object_ release];
5568 if (object == nil)
5569 object_ = nil;
5570 else
5571 object_ = [object retain];
5572 }
5573
5574 - (void) setObject:(id)object forFilter:(SEL)filter {
5575 [self setFilter:filter];
5576 [self setObject:object];
5577 }
5578
5579 - (bool) hasPackage:(Package *)package {
5580 _profile(FilteredPackageTable$hasPackage)
5581 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5582 _end
5583 }
5584
5585 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5586 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5587 [self setFilter:filter];
5588 object_ = [object retain];
5589 [self reloadData];
5590 } return self;
5591 }
5592
5593 @end
5594 /* }}} */
5595
5596 /* Filtered Package View {{{ */
5597 @interface FilteredPackageView : CYViewController {
5598 _transient Database *database_;
5599 FilteredPackageTable *packages_;
5600 NSString *title_;
5601 }
5602
5603 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5604
5605 @end
5606
5607 @implementation FilteredPackageView
5608
5609 - (void) dealloc {
5610 [packages_ release];
5611 [title_ release];
5612
5613 [super dealloc];
5614 }
5615
5616 - (void) viewDidAppear:(BOOL)animated {
5617 [super viewDidAppear:animated];
5618 [packages_ deselectWithAnimation:animated];
5619 }
5620
5621 - (void) didSelectPackage:(Package *)package {
5622 PackageView *view([delegate_ packageView]);
5623 [view setPackage:package];
5624 [view setDelegate:delegate_];
5625 [[self navigationController] pushViewController:view animated:YES];
5626 }
5627
5628 - (id) title { return title_; }
5629
5630 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5631 if ((self = [super init]) != nil) {
5632 database_ = database;
5633 title_ = [title copy];
5634 [[self navigationItem] setTitle:title_];
5635
5636 packages_ = [[FilteredPackageTable alloc]
5637 initWithFrame:[[self view] bounds]
5638 database:database
5639 target:self
5640 action:@selector(didSelectPackage:)
5641 filter:filter
5642 with:object
5643 ];
5644
5645 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5646 [[self view] addSubview:packages_];
5647 } return self;
5648 }
5649
5650 - (void) reloadData {
5651 [packages_ reloadData];
5652 }
5653
5654 - (void) setDelegate:(id)delegate {
5655 [super setDelegate:delegate];
5656 [packages_ setDelegate:delegate];
5657 }
5658
5659 @end
5660
5661 /* }}} */
5662
5663 /* Add Source View {{{ */
5664 @interface AddSourceView : CYViewController {
5665 _transient Database *database_;
5666 }
5667
5668 - (id) initWithDatabase:(Database *)database;
5669
5670 @end
5671
5672 @implementation AddSourceView
5673
5674 - (id) initWithDatabase:(Database *)database {
5675 if ((self = [super init]) != nil) {
5676 database_ = database;
5677 } return self;
5678 }
5679
5680 @end
5681 /* }}} */
5682 /* Source Cell {{{ */
5683 @interface SourceCell : UITableViewCell {
5684 UIImage *icon_;
5685 NSString *origin_;
5686 NSString *description_;
5687 NSString *label_;
5688 ContentView *content_;
5689 }
5690
5691 - (void) setSource:(Source *)source;
5692
5693 @end
5694
5695 @implementation SourceCell
5696
5697 - (void) clearSource {
5698 [icon_ release];
5699 [origin_ release];
5700 [description_ release];
5701 [label_ release];
5702
5703 icon_ = nil;
5704 origin_ = nil;
5705 description_ = nil;
5706 label_ = nil;
5707 }
5708
5709 - (void) setSource:(Source *)source {
5710 [self clearSource];
5711
5712 if (icon_ == nil)
5713 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5714 if (icon_ == nil)
5715 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5716 icon_ = [icon_ retain];
5717
5718 origin_ = [[source name] retain];
5719 label_ = [[source uri] retain];
5720 description_ = [[source description] retain];
5721
5722 [content_ setNeedsDisplay];
5723 }
5724
5725 - (void) dealloc {
5726 [self clearSource];
5727 [content_ release];
5728 [super dealloc];
5729 }
5730
5731 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5732 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5733 UIView *content([self contentView]);
5734 CGRect bounds([content bounds]);
5735
5736 content_ = [[ContentView alloc] initWithFrame:bounds];
5737 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5738 [content_ setBackgroundColor:[UIColor whiteColor]];
5739 [content addSubview:content_];
5740
5741 [content_ setDelegate:self];
5742 [content_ setOpaque:YES];
5743 } return self;
5744 }
5745
5746 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5747 [super setSelected:selected animated:animated];
5748 [content_ setNeedsDisplay];
5749 }
5750
5751 - (void) drawContentRect:(CGRect)rect {
5752 bool selected([self isSelected]);
5753 float width(rect.size.width);
5754
5755 if (icon_ != nil)
5756 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5757
5758 if (selected)
5759 UISetColor(White_);
5760
5761 if (!selected)
5762 UISetColor(Black_);
5763 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
5764
5765 if (!selected)
5766 UISetColor(Blue_);
5767 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
5768
5769 if (!selected)
5770 UISetColor(Gray_);
5771 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
5772 }
5773
5774 @end
5775 /* }}} */
5776 /* Source Table {{{ */
5777 @interface SourceTable : CYViewController {
5778 _transient Database *database_;
5779 UITableView *list_;
5780 NSMutableArray *sources_;
5781 int offset_;
5782
5783 NSString *href_;
5784 UIProgressHUD *hud_;
5785 NSError *error_;
5786
5787 //NSURLConnection *installer_;
5788 NSURLConnection *trivial_;
5789 NSURLConnection *trivial_bz2_;
5790 NSURLConnection *trivial_gz_;
5791 //NSURLConnection *automatic_;
5792
5793 BOOL cydia_;
5794 }
5795
5796 - (id) initWithDatabase:(Database *)database;
5797
5798 @end
5799
5800 @implementation SourceTable
5801
5802 - (void) _deallocConnection:(NSURLConnection *)connection {
5803 if (connection != nil) {
5804 [connection cancel];
5805 //[connection setDelegate:nil];
5806 [connection release];
5807 }
5808 }
5809
5810 - (void) dealloc {
5811 if (href_ != nil)
5812 [href_ release];
5813 if (hud_ != nil)
5814 [hud_ release];
5815 if (error_ != nil)
5816 [error_ release];
5817
5818 //[self _deallocConnection:installer_];
5819 [self _deallocConnection:trivial_];
5820 [self _deallocConnection:trivial_gz_];
5821 [self _deallocConnection:trivial_bz2_];
5822 //[self _deallocConnection:automatic_];
5823
5824 [sources_ release];
5825 [list_ release];
5826 [super dealloc];
5827 }
5828
5829 - (void) viewDidAppear:(BOOL)animated {
5830 [super viewDidAppear:animated];
5831 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5832 }
5833
5834 - (int) numberOfSectionsInTableView:(UITableView *)tableView {
5835 return offset_ == 0 ? 1 : 2;
5836 }
5837
5838 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
5839 switch (section + (offset_ == 0 ? 1 : 0)) {
5840 case 0: return UCLocalize("ENTERED_BY_USER");
5841 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5842
5843 _nodefault
5844 }
5845 }
5846
5847 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5848 int count = [sources_ count];
5849 switch (section) {
5850 case 0: return (offset_ == 0 ? count : offset_);
5851 case 1: return count - offset_;
5852
5853 _nodefault
5854 }
5855 }
5856
5857 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5858 unsigned idx = 0;
5859 switch (indexPath.section) {
5860 case 0: idx = indexPath.row; break;
5861 case 1: idx = indexPath.row + offset_; break;
5862
5863 _nodefault
5864 }
5865 return [sources_ objectAtIndex:idx];
5866 }
5867
5868 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5869 Source *source = [self sourceAtIndexPath:indexPath];
5870 return [source description] == nil ? 56 : 73;
5871 }
5872
5873 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5874 static NSString *cellIdentifier = @"SourceCell";
5875
5876 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5877 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5878 [cell setSource:[self sourceAtIndexPath:indexPath]];
5879
5880 return cell;
5881 }
5882
5883 - (int) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5884 return 1; //UITableViewCellAccessoryDisclosureIndicator?
5885 }
5886
5887 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5888 Source *source = [self sourceAtIndexPath:indexPath];
5889
5890 FilteredPackageView *packages = [[[FilteredPackageView alloc]
5891 initWithDatabase:database_
5892 title:[source label]
5893 filter:@selector(isVisibleInSource:)
5894 with:source
5895 ] autorelease];
5896
5897 [packages setDelegate:delegate_];
5898
5899 [[self navigationController] pushViewController:packages animated:YES];
5900 }
5901
5902 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5903 Source *source = [self sourceAtIndexPath:indexPath];
5904 return [source record] != nil;
5905 }
5906
5907 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5908 Source *source = [self sourceAtIndexPath:indexPath];
5909 [Sources_ removeObjectForKey:[source key]];
5910 [delegate_ syncData];
5911 }
5912
5913 - (void) complete {
5914 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5915 @"deb", @"Type",
5916 href_, @"URI",
5917 @"./", @"Distribution",
5918 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5919
5920 [delegate_ syncData];
5921 }
5922
5923 - (NSString *) getWarning {
5924 NSString *href(href_);
5925 NSRange colon([href rangeOfString:@"://"]);
5926 if (colon.location != NSNotFound)
5927 href = [href substringFromIndex:(colon.location + 3)];
5928 href = [href stringByAddingPercentEscapes];
5929 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5930 href = [href stringByCachingURLWithCurrentCDN];
5931
5932 NSURL *url([NSURL URLWithString:href]);
5933
5934 NSStringEncoding encoding;
5935 NSError *error(nil);
5936
5937 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5938 return [warning length] == 0 ? nil : warning;
5939 return nil;
5940 }
5941
5942 - (void) _endConnection:(NSURLConnection *)connection {
5943 NSURLConnection **field = NULL;
5944 if (connection == trivial_)
5945 field = &trivial_;
5946 else if (connection == trivial_bz2_)
5947 field = &trivial_bz2_;
5948 else if (connection == trivial_gz_)
5949 field = &trivial_gz_;
5950 _assert(field != NULL);
5951 [connection release];
5952 *field = nil;
5953
5954 if (
5955 trivial_ == nil &&
5956 trivial_bz2_ == nil &&
5957 trivial_gz_ == nil
5958 ) {
5959 bool defer(false);
5960
5961 if (cydia_) {
5962 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5963 defer = true;
5964
5965 UIAlertView *alert = [[[UIAlertView alloc]
5966 initWithTitle:UCLocalize("SOURCE_WARNING")
5967 message:warning
5968 delegate:self
5969 cancelButtonTitle:UCLocalize("CANCEL")
5970 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5971 ] autorelease];
5972
5973 [alert setContext:@"warning"];
5974 [alert setNumberOfRows:1];
5975 [alert show];
5976 } else
5977 [self complete];
5978 } else if (error_ != nil) {
5979 UIAlertView *alert = [[[UIAlertView alloc]
5980 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5981 message:[error_ localizedDescription]
5982 delegate:self
5983 cancelButtonTitle:UCLocalize("OK")
5984 otherButtonTitles:nil
5985 ] autorelease];
5986
5987 [alert setContext:@"urlerror"];
5988 [alert show];
5989 } else {
5990 UIAlertView *alert = [[[UIAlertView alloc]
5991 initWithTitle:UCLocalize("NOT_REPOSITORY")
5992 message:UCLocalize("NOT_REPOSITORY_EX")
5993 delegate:self
5994 cancelButtonTitle:UCLocalize("OK")
5995 otherButtonTitles:nil
5996 ] autorelease];
5997
5998 [alert setContext:@"trivial"];
5999 [alert show];
6000 }
6001
6002 [delegate_ setStatusBarShowsProgress:NO];
6003 [delegate_ removeProgressHUD:hud_];
6004
6005 [hud_ autorelease];
6006 hud_ = nil;
6007
6008 if (!defer) {
6009 [href_ release];
6010 href_ = nil;
6011 }
6012
6013 if (error_ != nil) {
6014 [error_ release];
6015 error_ = nil;
6016 }
6017 }
6018 }
6019
6020 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6021 switch ([response statusCode]) {
6022 case 200:
6023 cydia_ = YES;
6024 }
6025 }
6026
6027 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6028 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6029 if (error_ != nil)
6030 error_ = [error retain];
6031 [self _endConnection:connection];
6032 }
6033
6034 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6035 [self _endConnection:connection];
6036 }
6037
6038 - (id)title { return UCLocalize("SOURCES"); }
6039
6040 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6041 NSMutableURLRequest *request = [NSMutableURLRequest
6042 requestWithURL:[NSURL URLWithString:href]
6043 cachePolicy:NSURLRequestUseProtocolCachePolicy
6044 timeoutInterval:120.0
6045 ];
6046
6047 [request setHTTPMethod:method];
6048
6049 if (Machine_ != NULL)
6050 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6051 if (UniqueID_ != nil)
6052 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6053 if (Role_ != nil)
6054 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6055
6056 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6057 }
6058
6059 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6060 NSString *context([alert context]);
6061
6062 if ([context isEqualToString:@"source"]) {
6063 switch (button) {
6064 case 1: {
6065 NSString *href = [[alert textField] text];
6066
6067 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6068
6069 if (![href hasSuffix:@"/"])
6070 href_ = [href stringByAppendingString:@"/"];
6071 else
6072 href_ = href;
6073 href_ = [href_ retain];
6074
6075 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6076 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6077 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6078 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6079
6080 cydia_ = false;
6081
6082 hud_ = [[delegate_ addProgressHUD] retain];
6083 [hud_ setText:UCLocalize("VERIFYING_URL")];
6084 } break;
6085
6086 case 0:
6087 break;
6088
6089 _nodefault
6090 }
6091
6092 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6093 } else if ([context isEqualToString:@"trivial"])
6094 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6095 else if ([context isEqualToString:@"urlerror"])
6096 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6097 else if ([context isEqualToString:@"warning"]) {
6098 switch (button) {
6099 case 1:
6100 [self complete];
6101 break;
6102
6103 case 0:
6104 break;
6105
6106 _nodefault
6107 }
6108
6109 [href_ release];
6110 href_ = nil;
6111
6112 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6113 }
6114 }
6115
6116 - (id) initWithDatabase:(Database *)database {
6117 if ((self = [super init]) != nil) {
6118 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6119 [self updateButtonsForEditingStatus:NO animated:NO];
6120
6121 database_ = database;
6122 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6123
6124 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6125 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6126 [[self view] addSubview:list_];
6127
6128 [list_ setDataSource:self];
6129 [list_ setDelegate:self];
6130
6131 [self reloadData];
6132 } return self;
6133 }
6134
6135 - (void) reloadData {
6136 pkgSourceList list;
6137 if (!list.ReadMainList())
6138 return;
6139
6140 [sources_ removeAllObjects];
6141 [sources_ addObjectsFromArray:[database_ sources]];
6142 _trace();
6143 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6144 _trace();
6145
6146 int count([sources_ count]);
6147 offset_ = 0;
6148 for (int i = 0; i != count; i++) {
6149 if ([[sources_ objectAtIndex:i] record] == nil) break;
6150 else offset_++;
6151 }
6152
6153 [list_ setEditing:NO];
6154 [self updateButtonsForEditingStatus:NO animated:NO];
6155 [list_ reloadData];
6156 }
6157
6158 - (void) addButtonClicked {
6159 /*[book_ pushPage:[[[AddSourceView alloc]
6160 initWithBook:book_
6161 database:database_
6162 ] autorelease]];*/
6163
6164 UIAlertView *alert = [[[UIAlertView alloc]
6165 initWithTitle:UCLocalize("ENTER_APT_URL")
6166 message:nil
6167 delegate:self
6168 cancelButtonTitle:UCLocalize("CANCEL")
6169 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6170 ] autorelease];
6171
6172 [alert setContext:@"source"];
6173 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6174
6175 [alert setNumberOfRows:1];
6176 [alert addTextFieldWithValue:@"http://" label:@""];
6177
6178 UITextInputTraits *traits = [[alert textField] textInputTraits];
6179 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6180 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6181 [traits setKeyboardType:UIKeyboardTypeURL];
6182 // XXX: UIReturnKeyDone
6183 [traits setReturnKeyType:UIReturnKeyNext];
6184
6185 [alert show];
6186 }
6187
6188 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6189 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6190 initWithTitle:UCLocalize("ADD")
6191 style:UIBarButtonItemStylePlain
6192 target:self
6193 action:@selector(addButtonClicked)
6194 ];
6195 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6196 [leftItem release];
6197
6198 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6199 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6200 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6201 target:self
6202 action:@selector(editButtonClicked)
6203 ];
6204 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6205 [rightItem release];
6206 }
6207
6208 - (void) editButtonClicked {
6209 [list_ setEditing:![list_ isEditing] animated:YES];
6210
6211 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6212 }
6213
6214 @end
6215 /* }}} */
6216
6217 /* Installed View {{{ */
6218 @interface InstalledView : FilteredPackageView {
6219 BOOL expert_;
6220 }
6221
6222 - (id) initWithDatabase:(Database *)database;
6223
6224 @end
6225
6226 @implementation InstalledView
6227
6228 - (void) dealloc {
6229 [super dealloc];
6230 }
6231
6232 - (id) title { return UCLocalize("INSTALLED"); }
6233
6234 - (id) initWithDatabase:(Database *)database {
6235 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6236 [self updateRoleButton];
6237 [self queueStatusDidChange];
6238 } return self;
6239 }
6240
6241 #if !AlwaysReload
6242 - (void) queueButtonClicked {
6243 [delegate_ queue];
6244 }
6245 #endif
6246
6247 - (void) queueStatusDidChange {
6248 #if !AlwaysReload
6249 if (IsWildcat_) {
6250 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6251 initWithTitle:UCLocalize("QUEUE")
6252 style:UIBarButtonItemStyleDone
6253 target:self
6254 action:@selector(queueButtonClicked)
6255 ];
6256 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6257 else [[self navigationItem] setLeftBarButtonItem:nil];
6258 [queueItem release];
6259 }
6260 #endif
6261 }
6262
6263 - (void) reloadData {
6264 [packages_ reloadData];
6265 }
6266
6267 - (void) updateRoleButton {
6268 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6269 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6270 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6271 target:self
6272 action:@selector(roleButtonClicked)
6273 ];
6274 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6275 [rightItem release];
6276 }
6277
6278 - (void) roleButtonClicked {
6279 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6280 [packages_ reloadData];
6281 expert_ = !expert_;
6282
6283 [self updateRoleButton];
6284 }
6285
6286 - (void) setDelegate:(id)delegate {
6287 [super setDelegate:delegate];
6288 [packages_ setDelegate:delegate];
6289 }
6290
6291 @end
6292 /* }}} */
6293
6294 /* Home View {{{ */
6295 @interface HomeView : CYBrowserController {
6296 }
6297
6298 @end
6299
6300 @implementation HomeView
6301
6302 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6303 [super _setMoreHeaders:request];
6304 if (ChipID_ != nil)
6305 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6306 if (UniqueID_ != nil)
6307 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6308 }
6309
6310 - (void) aboutButtonClicked {
6311 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6312 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6313 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6314 [alert setCancelButtonIndex:0];
6315
6316 [alert setMessage:
6317 @"Copyright (C) 2008-2010\n"
6318 "Jay Freeman (saurik)\n"
6319 "saurik@saurik.com\n"
6320 "http://www.saurik.com/"
6321 ];
6322
6323 [alert show];
6324 }
6325
6326 - (void) viewWillAppear:(BOOL)animated {
6327 [super viewWillAppear:animated];
6328 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6329 }
6330
6331 - (void) viewWillDisappear:(BOOL)animated {
6332 [super viewWillDisappear:animated];
6333 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6334 }
6335
6336 - (id) init {
6337 if ((self = [super init]) != nil) {
6338 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6339 initWithTitle:UCLocalize("ABOUT")
6340 style:UIBarButtonItemStylePlain
6341 target:self
6342 action:@selector(aboutButtonClicked)
6343 ];
6344 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6345 [aboutItem release];
6346 } return self;
6347 }
6348
6349 @end
6350 /* }}} */
6351 /* Manage View {{{ */
6352 @interface ManageView : CYBrowserController {
6353 }
6354
6355 @end
6356
6357 @implementation ManageView
6358
6359 - (id) init {
6360 if ((self = [super init]) != nil) {
6361 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6362
6363 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6364 initWithTitle:UCLocalize("SETTINGS")
6365 style:UIBarButtonItemStylePlain
6366 target:self
6367 action:@selector(settingsButtonClicked)
6368 ];
6369 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6370 [settingsItem release];
6371
6372 [self queueStatusDidChange];
6373 } return self;
6374 }
6375
6376 - (void) settingsButtonClicked {
6377 [delegate_ askForSettings];
6378 [delegate_ updateData];
6379 }
6380
6381 #if !AlwaysReload
6382 - (void) queueButtonClicked {
6383 [delegate_ queue];
6384 }
6385 #endif
6386
6387 - (void) didFinishLoading {
6388 [self queueStatusDidChange];
6389 }
6390
6391 - (void) queueStatusDidChange {
6392 #if !AlwaysReload
6393 if (!IsWildcat_ && Queuing_) {
6394 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6395 initWithTitle:UCLocalize("QUEUE")
6396 style:UIBarButtonItemStyleDone
6397 target:self
6398 action:@selector(queueButtonClicked)
6399 ];
6400 [[self navigationItem] setRightBarButtonItem:queueItem];
6401
6402 [queueItem release];
6403 } else {
6404 [[self navigationItem] setRightBarButtonItem:nil];
6405 }
6406 #endif
6407 }
6408
6409 - (bool) isLoading {
6410 return false;
6411 }
6412
6413 @end
6414 /* }}} */
6415
6416 /* Refresh Bar {{{ */
6417 @interface RefreshBar : UINavigationBar {
6418 UIProgressIndicator *indicator_;
6419 UITextLabel *prompt_;
6420 UIProgressBar *progress_;
6421 UINavigationButton *cancel_;
6422 }
6423
6424 @end
6425
6426 @implementation RefreshBar
6427
6428 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6429 if ((self = [super initWithFrame:frame])) {
6430 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6431
6432 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6433 [self setBarStyle:1];
6434
6435 int barstyle([self _barStyle:NO]);
6436 bool ugly(barstyle == 0);
6437
6438 UIProgressIndicatorStyle style = ugly ?
6439 UIProgressIndicatorStyleMediumBrown :
6440 UIProgressIndicatorStyleMediumWhite;
6441
6442 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6443 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6444 CGRect indrect = {{indoffset, indoffset}, indsize};
6445
6446 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6447 [indicator_ setStyle:style];
6448 [self addSubview:indicator_];
6449
6450 CGSize prmsize = {215, indsize.height + 4};
6451
6452 CGRect prmrect = {{
6453 indoffset * 2 + indsize.width,
6454 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6455 }, prmsize};
6456
6457 UIFont *font([UIFont systemFontOfSize:15]);
6458
6459 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6460
6461 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6462 [prompt_ setBackgroundColor:[UIColor clearColor]];
6463 [prompt_ setFont:font];
6464
6465 [self addSubview:prompt_];
6466
6467 CGSize prgsize = {75, 100};
6468
6469 CGRect prgrect = {{
6470 [self frame].size.width - prgsize.width - 10,
6471 ([self frame].size.height - prgsize.height) / 2
6472 } , prgsize};
6473
6474 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6475 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6476 [self addSubview:progress_];
6477
6478 [progress_ setStyle:0];
6479
6480 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6481 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6482 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6483 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6484
6485 CGRect frame = [cancel_ frame];
6486 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6487 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6488 [cancel_ setFrame:frame];
6489
6490 [cancel_ setBarStyle:barstyle];
6491
6492 [indicator_ startAnimation];
6493 } return self;
6494 }
6495
6496 - (void) cancel {
6497 [cancel_ removeFromSuperview];
6498 }
6499
6500 - (void) start {
6501 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6502 [progress_ setProgress:0];
6503 [self addSubview:cancel_];
6504 }
6505
6506 - (void) stop {
6507 [cancel_ removeFromSuperview];
6508 }
6509
6510 - (void) setPrompt:(NSString *)prompt {
6511 [prompt_ setText:prompt];
6512 }
6513
6514 - (void) setProgress:(float)progress {
6515 [progress_ setProgress:progress];
6516 }
6517
6518 @end
6519 /* }}} */
6520
6521 /* Cydia Tab Bar Controller {{{ */
6522 @interface CYTabBarController : UITabBarController {
6523 Database *database_;
6524 }
6525
6526 @end
6527
6528 @implementation CYTabBarController
6529
6530 /* XXX: some logic should probably go here related to
6531 freeing the view controllers on tab change */
6532
6533 - (void) reloadData {
6534 size_t count([[self viewControllers] count]);
6535 for (size_t i(0); i != count; ++i) {
6536 UIViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6537 [page reloadData];
6538 }
6539 }
6540
6541 - (id) initWithDatabase: (Database *)database {
6542 if ((self = [super init]) != nil) {
6543 database_ = database;
6544 } return self;
6545 }
6546
6547 @end
6548 /* }}} */
6549
6550 /* Cydia Navigation Controller {{{ */
6551 @interface CYNavigationController : UINavigationController <
6552 ProgressDelegate
6553 > {
6554 _transient Database *database_;
6555 id delegate_;
6556 }
6557
6558 - (id) initWithDatabase:(Database *)database;
6559 - (void) reloadData;
6560
6561 @end
6562
6563
6564 @implementation CYNavigationController
6565
6566 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6567 // Inherit autorotation settings for modal parents.
6568 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6569 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6570 } else {
6571 return [super shouldAutorotateToInterfaceOrientation:orientation];
6572 }
6573 }
6574
6575 - (void) dealloc {
6576 [super dealloc];
6577 }
6578
6579 - (void) reloadData {
6580 size_t count([[self viewControllers] count]);
6581 for (size_t i(0); i != count; ++i) {
6582 UIViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6583 [page reloadData];
6584 }
6585 }
6586
6587 - (void) setDelegate:(id)delegate {
6588 delegate_ = delegate;
6589 }
6590
6591 - (id) initWithDatabase:(Database *)database {
6592 if ((self = [super init]) != nil) {
6593 database_ = database;
6594 } return self;
6595 }
6596
6597 @end
6598 /* }}} */
6599 /* Cydia:// Protocol {{{ */
6600 @interface CydiaURLProtocol : NSURLProtocol {
6601 }
6602
6603 @end
6604
6605 @implementation CydiaURLProtocol
6606
6607 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6608 NSURL *url([request URL]);
6609 if (url == nil)
6610 return NO;
6611 NSString *scheme([[url scheme] lowercaseString]);
6612 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6613 return NO;
6614 return YES;
6615 }
6616
6617 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6618 return request;
6619 }
6620
6621 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6622 id<NSURLProtocolClient> client([self client]);
6623 if (icon == nil)
6624 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6625 else {
6626 NSData *data(UIImagePNGRepresentation(icon));
6627
6628 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6629 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6630 [client URLProtocol:self didLoadData:data];
6631 [client URLProtocolDidFinishLoading:self];
6632 }
6633 }
6634
6635 - (void) startLoading {
6636 id<NSURLProtocolClient> client([self client]);
6637 NSURLRequest *request([self request]);
6638
6639 NSURL *url([request URL]);
6640 NSString *href([url absoluteString]);
6641
6642 NSString *path([href substringFromIndex:8]);
6643 NSRange slash([path rangeOfString:@"/"]);
6644
6645 NSString *command;
6646 if (slash.location == NSNotFound) {
6647 command = path;
6648 path = nil;
6649 } else {
6650 command = [path substringToIndex:slash.location];
6651 path = [path substringFromIndex:(slash.location + 1)];
6652 }
6653
6654 Database *database([Database sharedInstance]);
6655
6656 if ([command isEqualToString:@"package-icon"]) {
6657 if (path == nil)
6658 goto fail;
6659 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6660 Package *package([database packageWithName:path]);
6661 if (package == nil)
6662 goto fail;
6663 UIImage *icon([package icon]);
6664 [self _returnPNGWithImage:icon forRequest:request];
6665 } else if ([command isEqualToString:@"source-icon"]) {
6666 if (path == nil)
6667 goto fail;
6668 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6669 NSString *source(Simplify(path));
6670 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6671 if (icon == nil)
6672 icon = [UIImage applicationImageNamed:@"unknown.png"];
6673 [self _returnPNGWithImage:icon forRequest:request];
6674 } else if ([command isEqualToString:@"uikit-image"]) {
6675 if (path == nil)
6676 goto fail;
6677 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6678 UIImage *icon(_UIImageWithName(path));
6679 [self _returnPNGWithImage:icon forRequest:request];
6680 } else if ([command isEqualToString:@"section-icon"]) {
6681 if (path == nil)
6682 goto fail;
6683 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6684 NSString *section(Simplify(path));
6685 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6686 if (icon == nil)
6687 icon = [UIImage applicationImageNamed:@"unknown.png"];
6688 [self _returnPNGWithImage:icon forRequest:request];
6689 } else fail: {
6690 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6691 }
6692 }
6693
6694 - (void) stopLoading {
6695 }
6696
6697 @end
6698 /* }}} */
6699
6700 /* Sections View {{{ */
6701 @interface SectionsView : CYViewController {
6702 _transient Database *database_;
6703 NSMutableArray *sections_;
6704 NSMutableArray *filtered_;
6705 UITableView *list_;
6706 UIView *accessory_;
6707 BOOL editing_;
6708 }
6709
6710 - (id) initWithDatabase:(Database *)database;
6711 - (void) reloadData;
6712 - (void) resetView;
6713
6714 @end
6715
6716 @implementation SectionsView
6717
6718 - (void) dealloc {
6719 [list_ setDataSource:nil];
6720 [list_ setDelegate:nil];
6721
6722 [sections_ release];
6723 [filtered_ release];
6724 [list_ release];
6725 [accessory_ release];
6726 [super dealloc];
6727 }
6728
6729 - (void) viewDidAppear:(BOOL)animated {
6730 [super viewDidAppear:animated];
6731 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6732 }
6733
6734 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6735 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6736 return section;
6737 }
6738
6739 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6740 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6741 }
6742
6743 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6744 return 45;
6745 }
6746
6747 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6748 static NSString *reuseIdentifier = @"SectionCell";
6749
6750 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6751 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6752 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6753
6754 return cell;
6755 }
6756
6757 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6758 Section *section = [self sectionAtIndexPath:indexPath];
6759 NSString *name = [section name];
6760 NSString *title;
6761
6762 if ([indexPath row] == 0) {
6763 section = nil;
6764 name = nil;
6765 title = UCLocalize("ALL_PACKAGES");
6766 } else {
6767 if (name != nil) {
6768 name = [NSString stringWithString:name];
6769 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6770 } else {
6771 name = @"";
6772 title = UCLocalize("NO_SECTION");
6773 }
6774 }
6775
6776 FilteredPackageView *table = [[[FilteredPackageView alloc]
6777 initWithDatabase:database_
6778 title:title
6779 filter:@selector(isVisibleInSection:)
6780 with:name
6781 ] autorelease];
6782
6783 [table setDelegate:delegate_];
6784
6785 [[self navigationController] pushViewController:table animated:YES];
6786 }
6787
6788 - (id) title { return UCLocalize("SECTIONS"); }
6789
6790 - (id) initWithDatabase:(Database *)database {
6791 if ((self = [super init]) != nil) {
6792 database_ = database;
6793
6794 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6795
6796 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6797 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6798
6799 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6800 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6801 [[self view] addSubview:list_];
6802
6803 [list_ setDataSource:self];
6804 [list_ setDelegate:self];
6805
6806 [self reloadData];
6807 } return self;
6808 }
6809
6810 - (void) reloadData {
6811 NSArray *packages = [database_ packages];
6812
6813 [sections_ removeAllObjects];
6814 [filtered_ removeAllObjects];
6815
6816 #if 0
6817 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6818 SectionMap sections;
6819 sections.resize(64);
6820 #else
6821 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6822 #endif
6823
6824 _trace();
6825 for (Package *package in packages) {
6826 NSString *name([package section]);
6827 NSString *key(name == nil ? @"" : name);
6828
6829 #if 0
6830 Section **section;
6831
6832 _profile(SectionsView$reloadData$Section)
6833 section = &sections[key];
6834 if (*section == nil) {
6835 _profile(SectionsView$reloadData$Section$Allocate)
6836 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6837 _end
6838 }
6839 _end
6840
6841 [*section addToCount];
6842
6843 _profile(SectionsView$reloadData$Filter)
6844 if (![package valid] || ![package visible])
6845 continue;
6846 _end
6847
6848 [*section addToRow];
6849 #else
6850 Section *section;
6851
6852 _profile(SectionsView$reloadData$Section)
6853 section = [sections objectForKey:key];
6854 if (section == nil) {
6855 _profile(SectionsView$reloadData$Section$Allocate)
6856 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6857 [sections setObject:section forKey:key];
6858 _end
6859 }
6860 _end
6861
6862 [section addToCount];
6863
6864 _profile(SectionsView$reloadData$Filter)
6865 if (![package valid] || ![package visible])
6866 continue;
6867 _end
6868
6869 [section addToRow];
6870 #endif
6871 }
6872 _trace();
6873
6874 #if 0
6875 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6876 [sections_ addObject:i->second];
6877 #else
6878 [sections_ addObjectsFromArray:[sections allValues]];
6879 #endif
6880
6881 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6882
6883 for (Section *section in sections_) {
6884 size_t count([section row]);
6885 if (count == 0)
6886 continue;
6887
6888 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6889 [section setCount:count];
6890 [filtered_ addObject:section];
6891 }
6892
6893 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6894 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6895 style:UIBarButtonItemStylePlain
6896 target:self
6897 action:@selector(editButtonClicked)
6898 ];
6899 [[self navigationItem] setRightBarButtonItem:rightItem];
6900 [rightItem release];
6901
6902 [list_ reloadData];
6903 _trace();
6904 }
6905
6906 - (void) resetView {
6907 if (editing_)
6908 [self editButtonClicked];
6909 }
6910
6911 - (void) editButtonClicked {
6912 if ((editing_ = !editing_))
6913 [list_ reloadData];
6914 else
6915 [delegate_ updateData];
6916
6917 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6918 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6919 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6920 }
6921
6922 - (UIView *) accessoryView {
6923 return accessory_;
6924 }
6925
6926 @end
6927 /* }}} */
6928 /* Changes View {{{ */
6929 @interface ChangesView : CYViewController {
6930 _transient Database *database_;
6931 NSMutableArray *packages_;
6932 NSMutableArray *sections_;
6933 UITableView *list_;
6934 unsigned upgrades_;
6935 }
6936
6937 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6938 - (void) reloadData;
6939
6940 @end
6941
6942 @implementation ChangesView
6943
6944 - (void) dealloc {
6945 [list_ setDelegate:nil];
6946 [list_ setDataSource:nil];
6947
6948 [packages_ release];
6949 [sections_ release];
6950 [list_ release];
6951 [super dealloc];
6952 }
6953
6954 - (void) viewDidAppear:(BOOL)animated {
6955 [super viewDidAppear:animated];
6956 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6957 }
6958
6959 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6960 NSInteger count([sections_ count]);
6961 return count == 0 ? 1 : count;
6962 }
6963
6964 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6965 if ([sections_ count] == 0)
6966 return nil;
6967 return [[sections_ objectAtIndex:section] name];
6968 }
6969
6970 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6971 if ([sections_ count] == 0)
6972 return 0;
6973 return [[sections_ objectAtIndex:section] count];
6974 }
6975
6976 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6977 Section *section([sections_ objectAtIndex:[path section]]);
6978 NSInteger row([path row]);
6979 return [packages_ objectAtIndex:([section row] + row)];
6980 }
6981
6982 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6983 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6984 if (cell == nil)
6985 cell = [[[PackageCell alloc] init] autorelease];
6986 [cell setPackage:[self packageAtIndexPath:path]];
6987 return cell;
6988 }
6989
6990 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6991 return 73;
6992 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6993 }
6994
6995 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6996 Package *package([self packageAtIndexPath:path]);
6997 PackageView *view([delegate_ packageView]);
6998 [view setDelegate:delegate_];
6999 [view setPackage:package];
7000 [[self navigationController] pushViewController:view animated:YES];
7001 return path;
7002 }
7003
7004 - (void) refreshButtonClicked {
7005 [[UIApplication sharedApplication] beginUpdate];
7006 [[self navigationItem] setLeftBarButtonItem:nil];
7007 }
7008
7009 - (void) upgradeButtonClicked {
7010 [delegate_ distUpgrade];
7011 }
7012
7013 - (id) title { return UCLocalize("CHANGES"); }
7014
7015 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7016 if ((self = [super init]) != nil) {
7017 database_ = database;
7018 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7019
7020 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7021 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7022
7023 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7024 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7025 [[self view] addSubview:list_];
7026
7027 [list_ setDataSource:self];
7028 [list_ setDelegate:self];
7029
7030 delegate_ = delegate;
7031 [self reloadData];
7032 } return self;
7033 }
7034
7035 - (void) _reloadPackages:(NSArray *)packages {
7036 _trace();
7037 for (Package *package in packages)
7038 if (
7039 [package uninstalled] && [package valid] && [package visible] ||
7040 [package upgradableAndEssential:YES]
7041 )
7042 [packages_ addObject:package];
7043
7044 _trace();
7045 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7046 _trace();
7047 }
7048
7049 - (void) reloadData {
7050 NSArray *packages = [database_ packages];
7051
7052 [packages_ removeAllObjects];
7053 [sections_ removeAllObjects];
7054
7055 UIProgressHUD *hud([delegate_ addProgressHUD]);
7056 // XXX: localize
7057 [hud setText:@"Loading Changes"];
7058 NSLog(@"HUD:%@::%@", delegate_, hud);
7059 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7060 [delegate_ removeProgressHUD:hud];
7061
7062 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7063 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7064 Section *section = nil;
7065 NSDate *last = nil;
7066
7067 upgrades_ = 0;
7068 bool unseens = false;
7069
7070 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7071
7072 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7073 Package *package = [packages_ objectAtIndex:offset];
7074
7075 BOOL uae = [package upgradableAndEssential:YES];
7076
7077 if (!uae) {
7078 unseens = true;
7079 NSDate *seen;
7080
7081 _profile(ChangesView$reloadData$Remember)
7082 seen = [package seen];
7083 _end
7084
7085 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7086 last = seen;
7087
7088 NSString *name;
7089 if (seen == nil)
7090 name = UCLocalize("UNKNOWN");
7091 else {
7092 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7093 [name autorelease];
7094 }
7095
7096 _profile(ChangesView$reloadData$Allocate)
7097 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7098 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7099 [sections_ addObject:section];
7100 _end
7101 }
7102
7103 [section addToCount];
7104 } else if ([package ignored])
7105 [ignored addToCount];
7106 else {
7107 ++upgrades_;
7108 [upgradable addToCount];
7109 }
7110 }
7111 _trace();
7112
7113 CFRelease(formatter);
7114
7115 if (unseens) {
7116 Section *last = [sections_ lastObject];
7117 size_t count = [last count];
7118 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7119 [sections_ removeLastObject];
7120 }
7121
7122 if ([ignored count] != 0)
7123 [sections_ insertObject:ignored atIndex:0];
7124 if (upgrades_ != 0)
7125 [sections_ insertObject:upgradable atIndex:0];
7126
7127 [list_ reloadData];
7128
7129 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7130 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7131 style:UIBarButtonItemStylePlain
7132 target:self
7133 action:@selector(upgradeButtonClicked)
7134 ];
7135 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7136 [rightItem release];
7137
7138 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7139 initWithTitle:UCLocalize("REFRESH")
7140 style:UIBarButtonItemStylePlain
7141 target:self
7142 action:@selector(refreshButtonClicked)
7143 ];
7144 if (![[UIApplication sharedApplication] updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7145 [leftItem release];
7146 }
7147
7148 @end
7149 /* }}} */
7150 /* Search View {{{ */
7151 @interface SearchView : FilteredPackageView {
7152 id search_;
7153 }
7154
7155 - (id) initWithDatabase:(Database *)database;
7156 - (void) reloadData;
7157
7158 @end
7159
7160 @implementation SearchView
7161
7162 - (void) dealloc {
7163 [search_ release];
7164 [super dealloc];
7165 }
7166
7167 - (void) searchBarSearchButtonClicked:(id)searchBar {
7168 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7169 [search_ resignFirstResponder];
7170 [self reloadData];
7171 }
7172
7173 - (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7174 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7175 [self reloadData];
7176 }
7177
7178 - (id) title { return nil; }
7179
7180 - (id) initWithDatabase:(Database *)database {
7181 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil]) != nil) {
7182 search_ = [[objc_getClass("UISearchBar") alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7183 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7184 [search_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
7185 [search_ setDelegate:self];
7186 [[search_ searchField] setEnablesReturnKeyAutomatically:NO];
7187 [[self navigationItem] setTitleView:search_];
7188 } return self;
7189 }
7190
7191 - (void) _reloadData {
7192 }
7193
7194 - (void) reloadData {
7195 _profile(SearchView$reloadData)
7196 [packages_ reloadData];
7197 _end
7198 PrintTimes();
7199 [packages_ resetCursor];
7200 }
7201
7202 @end
7203 /* }}} */
7204 /* Settings View {{{ */
7205 @interface SettingsView : CYViewController {
7206 _transient Database *database_;
7207 NSString *name_;
7208 Package *package_;
7209 UIPreferencesTable *table_;
7210 _UISwitchSlider *subscribedSwitch_;
7211 _UISwitchSlider *ignoredSwitch_;
7212 UIPreferencesControlTableCell *subscribedCell_;
7213 UIPreferencesControlTableCell *ignoredCell_;
7214 }
7215
7216 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7217
7218 @end
7219
7220 @implementation SettingsView
7221
7222 - (void) dealloc {
7223 [table_ setDataSource:nil];
7224
7225 [name_ release];
7226 if (package_ != nil)
7227 [package_ release];
7228 [table_ release];
7229 [subscribedSwitch_ release];
7230 [ignoredSwitch_ release];
7231 [subscribedCell_ release];
7232 [ignoredCell_ release];
7233 [super dealloc];
7234 }
7235
7236 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7237 if (package_ == nil)
7238 return 0;
7239
7240 return 2;
7241 }
7242
7243 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7244 if (package_ == nil)
7245 return nil;
7246
7247 switch (group) {
7248 case 0: return nil;
7249 case 1: return nil;
7250
7251 _nodefault
7252 }
7253
7254 return nil;
7255 }
7256
7257 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7258 if (package_ == nil)
7259 return NO;
7260
7261 switch (group) {
7262 case 0: return NO;
7263 case 1: return YES;
7264
7265 _nodefault
7266 }
7267
7268 return NO;
7269 }
7270
7271 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7272 if (package_ == nil)
7273 return 0;
7274
7275 switch (group) {
7276 case 0: return 1;
7277 case 1: return 1;
7278
7279 _nodefault
7280 }
7281
7282 return 0;
7283 }
7284
7285 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7286 if (package_ == nil)
7287 return;
7288
7289 _UISwitchSlider *slider([cell control]);
7290 BOOL value([slider value] != 0);
7291 NSMutableDictionary *metadata([package_ metadata]);
7292
7293 BOOL before;
7294 if (NSNumber *number = [metadata objectForKey:key])
7295 before = [number boolValue];
7296 else
7297 before = NO;
7298
7299 if (value != before) {
7300 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7301 Changed_ = true;
7302 [delegate_ updateData];
7303 }
7304 }
7305
7306 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7307 [self onSomething:cell withKey:@"IsSubscribed"];
7308 }
7309
7310 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7311 [self onSomething:cell withKey:@"IsIgnored"];
7312 }
7313
7314 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7315 if (package_ == nil)
7316 return nil;
7317
7318 switch (group) {
7319 case 0: switch (row) {
7320 case 0:
7321 return subscribedCell_;
7322 case 1:
7323 return ignoredCell_;
7324 _nodefault
7325 } break;
7326
7327 case 1: switch (row) {
7328 case 0: {
7329 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7330 [cell setShowSelection:NO];
7331 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7332 return cell;
7333 }
7334
7335 _nodefault
7336 } break;
7337
7338 _nodefault
7339 }
7340
7341 return nil;
7342 }
7343
7344 - (id) title { return UCLocalize("SETTINGS"); }
7345
7346 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7347 if ((self = [super init])) {
7348 database_ = database;
7349 name_ = [package retain];
7350
7351 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7352
7353 table_ = [[UIPreferencesTable alloc] initWithFrame:[[self view] bounds]];
7354 [[self view] addSubview:table_];
7355
7356 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7357 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7358
7359 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7360 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7361
7362 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7363 [subscribedCell_ setShowSelection:NO];
7364 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7365 [subscribedCell_ setControl:subscribedSwitch_];
7366
7367 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7368 [ignoredCell_ setShowSelection:NO];
7369 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7370 [ignoredCell_ setControl:ignoredSwitch_];
7371
7372 [table_ setDataSource:self];
7373 [self reloadData];
7374 } return self;
7375 }
7376
7377 - (void) reloadData {
7378 if (package_ != nil)
7379 [package_ autorelease];
7380 package_ = [database_ packageWithName:name_];
7381 if (package_ != nil) {
7382 [package_ retain];
7383 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7384 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7385 }
7386
7387 [table_ reloadData];
7388 }
7389
7390 @end
7391 /* }}} */
7392
7393 /* Signature View {{{ */
7394 @interface SignatureView : CYBrowserController {
7395 _transient Database *database_;
7396 NSString *package_;
7397 }
7398
7399 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7400
7401 @end
7402
7403 @implementation SignatureView
7404
7405 - (void) dealloc {
7406 [package_ release];
7407 [super dealloc];
7408 }
7409
7410 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7411 // XXX: dude!
7412 [super webView:sender didClearWindowObject:window forFrame:frame];
7413 }
7414
7415 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7416 if ((self = [super init]) != nil) {
7417 database_ = database;
7418 package_ = [package retain];
7419 [self reloadData];
7420 } return self;
7421 }
7422
7423 - (void) reloadData {
7424 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7425 }
7426
7427 @end
7428 /* }}} */
7429
7430 /* Cydia Container {{{ */
7431 @interface CYContainer : UIViewController <ProgressDelegate> {
7432 _transient Database *database_;
7433 RefreshBar *refreshbar_;
7434
7435 bool dropped_;
7436 bool updating_;
7437 id updatedelegate_;
7438 UIViewController *root_;
7439 }
7440
7441 @end
7442
7443 @implementation CYContainer
7444
7445 // NOTE: UIWindow only sends the top controller these messages,
7446 // So we have to forward them on.
7447
7448 - (void) viewDidAppear:(BOOL)animated {
7449 [super viewDidAppear:animated];
7450 [root_ viewDidAppear:animated];
7451 }
7452
7453 - (void) viewWillAppear:(BOOL)animated {
7454 [super viewWillAppear:animated];
7455 [root_ viewWillAppear:animated];
7456 }
7457
7458 - (void) viewDidDisappear:(BOOL)animated {
7459 [super viewDidDisappear:animated];
7460 [root_ viewDidDisappear:animated];
7461 }
7462
7463 - (void) viewWillDisappear:(BOOL)animated {
7464 [super viewWillDisappear:animated];
7465 [root_ viewWillDisappear:animated];
7466 }
7467
7468 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7469 return YES; /* XXX: return YES; */
7470 }
7471
7472 - (void) setRootController:(UIViewController *)controller {
7473 root_ = controller;
7474 [[self view] addSubview:[root_ view]];
7475 }
7476
7477 - (void) setUpdate:(NSDate *)date {
7478 [self beginUpdate];
7479 }
7480
7481 - (void) beginUpdate {
7482 [self dropBar:YES];
7483 [refreshbar_ start];
7484
7485 updating_ = true;
7486
7487 [NSThread
7488 detachNewThreadSelector:@selector(performUpdate)
7489 toTarget:self
7490 withObject:nil
7491 ];
7492 }
7493
7494 - (void) performUpdate { _pooled
7495 Status status;
7496 status.setDelegate(self);
7497 [database_ updateWithStatus:status];
7498
7499 [self
7500 performSelectorOnMainThread:@selector(completeUpdate)
7501 withObject:nil
7502 waitUntilDone:NO
7503 ];
7504 }
7505
7506 - (void) completeUpdate {
7507 updating_ = false;
7508
7509 [self raiseBar:YES];
7510 [refreshbar_ stop];
7511 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7512 }
7513
7514 - (void) cancelUpdate {
7515 [refreshbar_ cancel];
7516 [self completeUpdate];
7517 }
7518
7519 - (void) cancelPressed {
7520 [self cancelUpdate];
7521 }
7522
7523 - (BOOL) updating {
7524 return updating_;
7525 }
7526
7527 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7528 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7529 }
7530
7531 - (void) startProgress {
7532 }
7533
7534 - (void) setProgressTitle:(NSString *)title {
7535 [self
7536 performSelectorOnMainThread:@selector(_setProgressTitle:)
7537 withObject:title
7538 waitUntilDone:YES
7539 ];
7540 }
7541
7542 - (bool) isCancelling:(size_t)received {
7543 return !updating_;
7544 }
7545
7546 - (void) setProgressPercent:(float)percent {
7547 [self
7548 performSelectorOnMainThread:@selector(_setProgressPercent:)
7549 withObject:[NSNumber numberWithFloat:percent]
7550 waitUntilDone:YES
7551 ];
7552 }
7553
7554 - (void) addProgressOutput:(NSString *)output {
7555 [self
7556 performSelectorOnMainThread:@selector(_addProgressOutput:)
7557 withObject:output
7558 waitUntilDone:YES
7559 ];
7560 }
7561
7562 - (void) _setProgressTitle:(NSString *)title {
7563 [refreshbar_ setPrompt:title];
7564 }
7565
7566 - (void) _setProgressPercent:(NSNumber *)percent {
7567 [refreshbar_ setProgress:[percent floatValue]];
7568 }
7569
7570 - (void) _addProgressOutput:(NSString *)output {
7571 }
7572
7573 - (void) setUpdateDelegate:(id)delegate {
7574 updatedelegate_ = delegate;
7575 }
7576
7577 - (void) dropBar:(BOOL)animated {
7578 if (dropped_) return;
7579 dropped_ = true;
7580
7581 [[self view] addSubview:refreshbar_];
7582
7583 if (animated) [UIView beginAnimations:nil context:NULL];
7584 CGRect barframe = [refreshbar_ frame];
7585 CGRect viewframe = [[root_ view] frame];
7586 viewframe.origin.y += barframe.size.height;
7587 viewframe.size.height -= barframe.size.height;
7588 [[root_ view] setFrame:viewframe];
7589 if (animated) [UIView commitAnimations];
7590
7591 // Ensure bar has the proper width for our view, it might have changed
7592 barframe.size.width = viewframe.size.width;
7593 [refreshbar_ setFrame:barframe];
7594
7595 // XXX: fix Apple's layout bug
7596 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7597 }
7598
7599 - (void) raiseBar:(BOOL)animated {
7600 if (!dropped_) return;
7601 dropped_ = false;
7602
7603 [refreshbar_ removeFromSuperview];
7604
7605 if (animated) [UIView beginAnimations:nil context:NULL];
7606 CGRect barframe = [refreshbar_ frame];
7607 CGRect viewframe = [[root_ view] frame];
7608 viewframe.origin.y -= barframe.size.height;
7609 viewframe.size.height += barframe.size.height;
7610 [[root_ view] setFrame:viewframe];
7611 if (animated) [UIView commitAnimations];
7612
7613 // XXX: fix Apple's layout bug
7614 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7615 }
7616
7617 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7618 if (dropped_) {
7619 [self raiseBar:NO];
7620 [self dropBar:NO];
7621 }
7622
7623 // XXX: fix Apple's layout bug
7624 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7625
7626 // Resize refresh bar to fit the new size
7627 CGRect barframe = [refreshbar_ frame];
7628 barframe.size.width = [[self view] frame].size.width;
7629 [refreshbar_ setFrame:barframe];
7630 }
7631
7632 - (void) dealloc {
7633 [refreshbar_ release];
7634 [super dealloc];
7635 }
7636
7637 - (id) initWithDatabase: (Database *)database {
7638 if ((self = [super init]) != nil) {
7639 database_ = database;
7640
7641 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7642
7643 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7644 } return self;
7645 }
7646
7647 @end
7648 /* }}} */
7649
7650 typedef enum {
7651 kCydiaTag = 0,
7652 kSectionsTag = 1,
7653 kChangesTag = 2,
7654 kManageTag = 3,
7655 kInstalledTag = 4,
7656 kSourcesTag = 5,
7657 kSearchTag = 6
7658 } CYTabTag;
7659
7660 @interface Cydia : UIApplication <
7661 ConfirmationViewDelegate,
7662 ProgressViewDelegate,
7663 CydiaDelegate
7664 > {
7665 UIWindow *window_;
7666 CYContainer *container_;
7667
7668 id tabbar_;
7669
7670 NSMutableArray *essential_;
7671 NSMutableArray *broken_;
7672
7673 Database *database_;
7674
7675 int tag_;
7676
7677 UIKeyboard *keyboard_;
7678 UIProgressHUD *hud_;
7679
7680 SectionsView *sections_;
7681 ChangesView *changes_;
7682 ManageView *manage_;
7683 SearchView *search_;
7684 SourceTable *sources_;
7685 InstalledView *installed_;
7686 id queueDelegate_;
7687
7688 #if RecyclePackageViews
7689 NSMutableArray *details_;
7690 #endif
7691
7692 bool loaded_;
7693 }
7694
7695 - (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7696 - (void) setPage:(UIViewController *)page;
7697
7698 @end
7699
7700 static _finline void _setHomePage(Cydia *self) {
7701 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7702 }
7703
7704 @implementation Cydia
7705
7706 - (void) beginUpdate {
7707 [container_ beginUpdate];
7708 }
7709
7710 - (BOOL) updating {
7711 return [container_ updating];
7712 }
7713
7714 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7715 return window_;
7716 }
7717
7718 - (void) _loaded {
7719 if ([broken_ count] != 0) {
7720 int count = [broken_ count];
7721
7722 UIAlertView *alert = [[[UIAlertView alloc]
7723 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7724 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7725 delegate:self
7726 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7727 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7728 ] autorelease];
7729
7730 [alert setContext:@"fixhalf"];
7731 [alert show];
7732 } else if (!Ignored_ && [essential_ count] != 0) {
7733 int count = [essential_ count];
7734
7735 UIAlertView *alert = [[[UIAlertView alloc]
7736 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7737 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7738 delegate:self
7739 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7740 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7741 ] autorelease];
7742
7743 [alert setContext:@"upgrade"];
7744 [alert show];
7745 }
7746 }
7747
7748 - (void) _saveConfig {
7749 if (Changed_) {
7750 _trace();
7751 NSString *error(nil);
7752 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7753 _trace();
7754 NSError *error(nil);
7755 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7756 NSLog(@"failure to save metadata data: %@", error);
7757 _trace();
7758 } else {
7759 NSLog(@"failure to serialize metadata: %@", error);
7760 return;
7761 }
7762
7763 Changed_ = false;
7764 }
7765 }
7766
7767 - (void) _updateData {
7768 [self _saveConfig];
7769
7770 /* XXX: this is just stupid */
7771 if (tag_ != 1 && sections_ != nil)
7772 [sections_ reloadData];
7773 if (tag_ != 2 && changes_ != nil)
7774 [changes_ reloadData];
7775 if (tag_ != 4 && search_ != nil)
7776 [search_ reloadData];
7777
7778 [[tabbar_ selectedViewController] reloadData];
7779 }
7780
7781 - (int)indexOfTabWithTag:(int)tag {
7782 int i = 0;
7783 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7784 if ([[controller tabBarItem] tag] == tag) return i;
7785 i += 1;
7786 }
7787
7788 return -1;
7789 }
7790
7791 - (void) _refreshIfPossible {
7792 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7793
7794 Reachability* reachability = [Reachability reachabilityWithHostName:@"cydia.saurik.com"];
7795 NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
7796
7797 if (loaded_ || ManualRefresh || remoteHostStatus == NotReachable) loaded:
7798 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
7799 else {
7800 loaded_ = true;
7801
7802 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7803
7804 if (update != nil) {
7805 NSTimeInterval interval([update timeIntervalSinceNow]);
7806 if (interval <= 0 && interval > -(15*60))
7807 goto loaded;
7808 }
7809
7810 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
7811 }
7812
7813 [pool release];
7814 }
7815
7816 - (void) refreshIfPossible {
7817 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
7818 }
7819
7820 - (void) _reloadData {
7821 UIView *block();
7822
7823 UIProgressHUD *hud([self addProgressHUD]);
7824 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7825
7826 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7827 _trace();
7828
7829 [self removeProgressHUD:hud];
7830
7831 size_t changes(0);
7832
7833 [essential_ removeAllObjects];
7834 [broken_ removeAllObjects];
7835
7836 NSArray *packages([database_ packages]);
7837 for (Package *package in packages) {
7838 if ([package half])
7839 [broken_ addObject:package];
7840 if ([package upgradableAndEssential:NO]) {
7841 if ([package essential])
7842 [essential_ addObject:package];
7843 ++changes;
7844 }
7845 }
7846
7847 if (changes != 0) {
7848 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7849 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
7850 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
7851
7852 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7853 [self setApplicationBadge:badge];
7854 else
7855 [self setApplicationBadgeString:badge];
7856 } else {
7857 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
7858 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
7859
7860 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7861 [self removeApplicationBadge];
7862 else // XXX: maybe use setApplicationBadgeString also?
7863 [self setApplicationIconBadgeNumber:0];
7864 }
7865
7866 [self _updateData];
7867
7868 [self refreshIfPossible];
7869 }
7870
7871 - (void) updateData {
7872 [database_ setVisible];
7873 [self _updateData];
7874 }
7875
7876 - (void) update_ {
7877 [database_ update];
7878 }
7879
7880 - (void) syncData {
7881 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7882 _assert(file != NULL);
7883
7884 for (NSString *key in [Sources_ allKeys]) {
7885 NSDictionary *source([Sources_ objectForKey:key]);
7886
7887 fprintf(file, "%s %s %s\n",
7888 [[source objectForKey:@"Type"] UTF8String],
7889 [[source objectForKey:@"URI"] UTF8String],
7890 [[source objectForKey:@"Distribution"] UTF8String]
7891 );
7892 }
7893
7894 fclose(file);
7895
7896 [self _saveConfig];
7897
7898 ProgressView *progress = [[[ProgressView alloc] initWithDatabase:database_ delegate:self] autorelease];
7899 UINavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
7900 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
7901 [container_ presentModalViewController:navigation animated:YES];
7902
7903 [progress
7904 detachNewThreadSelector:@selector(update_)
7905 toTarget:self
7906 withObject:nil
7907 title:UCLocalize("UPDATING_SOURCES")
7908 ];
7909 }
7910
7911 - (void) reloadData {
7912 @synchronized (self) {
7913 [self _reloadData];
7914 }
7915 }
7916
7917 - (void) resolve {
7918 pkgProblemResolver *resolver = [database_ resolver];
7919
7920 resolver->InstallProtect();
7921 if (!resolver->Resolve(true))
7922 _error->Discard();
7923 }
7924
7925 - (CGRect) popUpBounds {
7926 return [[tabbar_ view] bounds];
7927 }
7928
7929 - (bool) perform {
7930 if (![database_ prepare])
7931 return false;
7932
7933 ConfirmationView *page([[[ConfirmationView alloc] initWithDatabase:database_] autorelease]);
7934 [page setDelegate:self];
7935 id confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
7936 [confirm_ setDelegate:self];
7937
7938 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
7939 [container_ presentModalViewController:confirm_ animated:YES];
7940
7941 return true;
7942 }
7943
7944 - (void) queue {
7945 @synchronized (self) {
7946 [self perform];
7947 }
7948 }
7949
7950 - (void) clearPackage:(Package *)package {
7951 @synchronized (self) {
7952 [package clear];
7953 [self resolve];
7954 [self perform];
7955 }
7956 }
7957
7958 - (void) installPackages:(NSArray *)packages {
7959 @synchronized (self) {
7960 for (Package *package in packages)
7961 [package install];
7962 [self resolve];
7963 [self perform];
7964 }
7965 }
7966
7967 - (void) installPackage:(Package *)package {
7968 @synchronized (self) {
7969 [package install];
7970 [self resolve];
7971 [self perform];
7972 }
7973 }
7974
7975 - (void) removePackage:(Package *)package {
7976 @synchronized (self) {
7977 [package remove];
7978 [self resolve];
7979 [self perform];
7980 }
7981 }
7982
7983 - (void) distUpgrade {
7984 @synchronized (self) {
7985 if (![database_ upgrade])
7986 return;
7987 [self perform];
7988 }
7989 }
7990
7991 - (void) complete {
7992 @synchronized (self) {
7993 [self _reloadData];
7994 }
7995 }
7996
7997 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
7998 ProgressView *progress = [[[ProgressView alloc] initWithDatabase:database_ delegate:self] autorelease];
7999
8000 if (navigation != nil) {
8001 [navigation pushViewController:progress animated:YES];
8002 } else {
8003 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8004 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8005 [container_ presentModalViewController:navigation animated:YES];
8006 }
8007
8008 [progress
8009 detachNewThreadSelector:@selector(perform)
8010 toTarget:database_
8011 withObject:nil
8012 title:UCLocalize("RUNNING")
8013 ];
8014 }
8015
8016 - (void) progressViewIsComplete:(ProgressView *)progress {
8017 [self complete];
8018 }
8019
8020 - (void) setPage:(UIViewController *)page {
8021 [page setDelegate:self];
8022
8023 UINavigationController *navController = [tabbar_ selectedViewController];
8024 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8025 for (UIViewController *page in [tabbar_ viewControllers]) {
8026 if (page != navController) [page setViewControllers:nil];
8027 }
8028 }
8029
8030 - (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8031 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8032 [browser loadURL:url];
8033 return browser;
8034 }
8035
8036 - (SectionsView *) sectionsView {
8037 if (sections_ == nil)
8038 sections_ = [[SectionsView alloc] initWithDatabase:database_];
8039 return sections_;
8040 }
8041
8042 - (ChangesView *) changesView {
8043 if (changes_ == nil)
8044 changes_ = [[ChangesView alloc] initWithDatabase:database_ delegate:self];
8045 return changes_;
8046 }
8047
8048 - (ManageView *) manageView {
8049 if (manage_ == nil) {
8050 manage_ = (ManageView *) [[self
8051 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8052 withClass:[ManageView class]
8053 ] retain];
8054 if (!IsWildcat_) queueDelegate_ = manage_;
8055 }
8056 return manage_;
8057 }
8058
8059 - (SearchView *) searchView {
8060 if (search_ == nil)
8061 search_ = [[SearchView alloc] initWithDatabase:database_];
8062 return search_;
8063 }
8064
8065 - (SourceTable *) sourcesView {
8066 if (sources_ == nil)
8067 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8068 return sources_;
8069 }
8070
8071 - (InstalledView *) installedView {
8072 if (installed_ == nil) {
8073 installed_ = [[InstalledView alloc] initWithDatabase:database_];
8074 if (IsWildcat_) queueDelegate_ = installed_;
8075 }
8076 return installed_;
8077 }
8078
8079 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8080 int tag = [[viewController tabBarItem] tag];
8081 if (tag == tag_) {
8082 [[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8083 return;
8084 } else if (tag_ == 1) {
8085 [[self sectionsView] resetView];
8086 }
8087
8088 switch (tag) {
8089 case kCydiaTag: _setHomePage(self); break;
8090
8091 case kSectionsTag: [self setPage:[self sectionsView]]; break;
8092 case kChangesTag: [self setPage:[self changesView]]; break;
8093 case kManageTag: [self setPage:[self manageView]]; break;
8094 case kInstalledTag: [self setPage:[self installedView]]; break;
8095 case kSourcesTag: [self setPage:[self sourcesView]]; break;
8096 case kSearchTag: [self setPage:[self searchView]]; break;
8097
8098 _nodefault
8099 }
8100
8101 tag_ = tag;
8102 }
8103
8104 - (void) askForSettings {
8105 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
8106
8107 CYActionSheet *role([[[CYActionSheet alloc]
8108 initWithTitle:UCLocalize("WHO_ARE_YOU")
8109 buttons:[NSArray arrayWithObjects:
8110 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
8111 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
8112 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
8113 nil]
8114 defaultButtonIndex:-1
8115 ] autorelease]);
8116
8117 [role setMessage:UCLocalize("ROLE_EX")];
8118
8119 int button([role yieldToPopupAlertAnimated:YES]);
8120
8121 switch (button) {
8122 case 1: Role_ = @"User"; break;
8123 case 2: Role_ = @"Hacker"; break;
8124 case 3: Role_ = @"Developer"; break;
8125
8126 _nodefault
8127 }
8128
8129 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8130 Role_, @"Role",
8131 nil];
8132
8133 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8134
8135 Changed_ = true;
8136
8137 [role dismiss];
8138 }
8139
8140 - (void) setPackageView:(PackageView *)view {
8141 WebThreadLock();
8142 [view setPackage:nil];
8143 #if RecyclePackageViews
8144 if ([details_ count] < 3)
8145 [details_ addObject:view];
8146 #endif
8147 WebThreadUnlock();
8148 }
8149
8150 - (PackageView *) _packageView {
8151 return [[[PackageView alloc] initWithDatabase:database_] autorelease];
8152 }
8153
8154 - (PackageView *) packageView {
8155 #if RecyclePackageViews
8156 PackageView *view;
8157 size_t count([details_ count]);
8158
8159 if (count == 0) {
8160 view = [self _packageView];
8161 renew:
8162 [details_ addObject:[self _packageView]];
8163 } else {
8164 view = [[[details_ lastObject] retain] autorelease];
8165 [details_ removeLastObject];
8166 if (count == 1)
8167 goto renew;
8168 }
8169
8170 return view;
8171 #else
8172 return [self _packageView];
8173 #endif
8174 }
8175
8176 - (void) cancelAndClear:(bool)clear {
8177 @synchronized (self) {
8178 if (clear) {
8179 /* XXX: clear marks instead of reloading data */
8180 /*pkgCacheFile &cache([database_ cache]);
8181 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8182 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8183 }
8184
8185 [self updateData];
8186
8187 Queuing_ = false;
8188 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8189 [queueDelegate_ queueStatusDidChange];*/
8190 [self reloadData];
8191 } else {
8192 Queuing_ = true;
8193
8194 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8195 [[tabbar_ selectedViewController] reloadData];
8196
8197 [queueDelegate_ queueStatusDidChange];
8198 }
8199 }
8200 }
8201
8202 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8203 NSString *context([alert context]);
8204
8205 if ([context isEqualToString:@"fixhalf"]) {
8206 if (button == [alert firstOtherButtonIndex]) {
8207 @synchronized (self) {
8208 for (Package *broken in broken_) {
8209 [broken remove];
8210
8211 NSString *id = [broken id];
8212 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8213 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8214 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8215 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8216 }
8217
8218 [self resolve];
8219 [self perform];
8220 }
8221 } else if (button == [alert cancelButtonIndex]) {
8222 [broken_ removeAllObjects];
8223 [self _loaded];
8224 }
8225
8226 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8227 } else if ([context isEqualToString:@"upgrade"]) {
8228 if (button == [alert firstOtherButtonIndex]) {
8229 @synchronized (self) {
8230 for (Package *essential in essential_)
8231 [essential install];
8232
8233 [self resolve];
8234 [self perform];
8235 }
8236 } else if (button == [alert firstOtherButtonIndex] + 1) {
8237 [self distUpgrade];
8238 } else if (button == [alert cancelButtonIndex]) {
8239 Ignored_ = YES;
8240 }
8241
8242 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8243 }
8244 }
8245
8246 - (void) system:(NSString *)command { _pooled
8247 system([command UTF8String]);
8248 }
8249
8250 - (void) applicationWillSuspend {
8251 [database_ clean];
8252 [super applicationWillSuspend];
8253 }
8254
8255 - (void) applicationSuspend:(__GSEvent *)event {
8256 if (hud_ == nil)// && ![progress_ isRunning])
8257 [super applicationSuspend:event];
8258 }
8259
8260 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8261 if (hud_ == nil)
8262 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8263 }
8264
8265 - (void) _setSuspended:(BOOL)value {
8266 if (hud_ == nil)
8267 [super _setSuspended:value];
8268 }
8269
8270 - (UIProgressHUD *) addProgressHUD {
8271 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8272 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8273
8274 [window_ setUserInteractionEnabled:NO];
8275 [hud show:YES];
8276 [window_ addSubview:hud];
8277 return hud;
8278 }
8279
8280 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8281 [hud show:NO];
8282 [hud removeFromSuperview];
8283 [window_ setUserInteractionEnabled:YES];
8284 }
8285
8286 - (UIViewController *) pageForPackage:(NSString *)name {
8287 if (Package *package = [database_ packageWithName:name]) {
8288 PackageView *view([self packageView]);
8289 [view setPackage:package];
8290 return view;
8291 } else {
8292 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8293 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8294 return [self _pageForURL:url withClass:[CYBrowserController class]];
8295 }
8296 }
8297
8298 - (UIViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8299 if (tag != NULL)
8300 *tag = -1;
8301
8302 NSString *href([url absoluteString]);
8303 if ([href hasPrefix:@"apptapp://package/"])
8304 return [self pageForPackage:[href substringFromIndex:18]];
8305
8306 NSString *scheme([[url scheme] lowercaseString]);
8307 if (![scheme isEqualToString:@"cydia"])
8308 return nil;
8309 NSString *path([url absoluteString]);
8310 if ([path length] < 8)
8311 return nil;
8312 path = [path substringFromIndex:8];
8313 if (![path hasPrefix:@"/"])
8314 path = [@"/" stringByAppendingString:path];
8315
8316 if ([path isEqualToString:@"/add-source"])
8317 return [[[AddSourceView alloc] initWithDatabase:database_] autorelease];
8318 else if ([path isEqualToString:@"/storage"])
8319 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8320 else if ([path isEqualToString:@"/sources"])
8321 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8322 else if ([path isEqualToString:@"/packages"])
8323 return [[[InstalledView alloc] initWithDatabase:database_] autorelease];
8324 else if ([path hasPrefix:@"/url/"])
8325 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8326 else if ([path hasPrefix:@"/launch/"])
8327 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8328 else if ([path hasPrefix:@"/package-settings/"])
8329 return [[[SettingsView alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8330 else if ([path hasPrefix:@"/package-signature/"])
8331 return [[[SignatureView alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8332 else if ([path hasPrefix:@"/package/"])
8333 return [self pageForPackage:[path substringFromIndex:9]];
8334 else if ([path hasPrefix:@"/files/"]) {
8335 NSString *name = [path substringFromIndex:7];
8336
8337 if (Package *package = [database_ packageWithName:name]) {
8338 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8339 [files setPackage:package];
8340 return files;
8341 }
8342 }
8343
8344 return nil;
8345 }
8346
8347 - (void) applicationOpenURL:(NSURL *)url {
8348 [super applicationOpenURL:url];
8349 int tag;
8350 if (UIViewController *page = [self pageForURL:url hasTag:&tag]) {
8351 [self setPage:page];
8352 tag_ = tag;
8353 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8354 }
8355 }
8356
8357 - (void) applicationDidFinishLaunching:(id)unused {
8358 [CYBrowserController _initialize];
8359
8360 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8361
8362 Font12_ = [[UIFont systemFontOfSize:12] retain];
8363 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8364 Font14_ = [[UIFont systemFontOfSize:14] retain];
8365 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8366 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8367
8368 tag_ = 0;
8369
8370 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8371 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8372
8373 UIScreen *screen([UIScreen mainScreen]);
8374
8375 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8376 [window_ orderFront:self];
8377 [window_ makeKey:self];
8378 [window_ setHidden:NO];
8379
8380 database_ = [Database sharedInstance];
8381
8382 if (
8383 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8384 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8385 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8386 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8387 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8388 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8389 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8390 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8391 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8392 false
8393 ) {
8394 [self setIdleTimerDisabled:YES];
8395
8396 hud_ = [self addProgressHUD];
8397 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8398 [self setStatusBarShowsProgress:YES];
8399
8400 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8401
8402 [self setStatusBarShowsProgress:NO];
8403 [self removeProgressHUD:hud_];
8404 hud_ = nil;
8405
8406 if (ExecFork() == 0) {
8407 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8408 perror("launchctl stop");
8409 }
8410
8411 return;
8412 }
8413
8414 if (Role_ == nil)
8415 [self askForSettings];
8416
8417 _trace();
8418
8419 NSMutableArray *controllers = [NSMutableArray array];
8420 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8421 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8422 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8423 if (IsWildcat_) [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8424 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8425 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8426
8427 NSMutableArray *items = [NSMutableArray arrayWithObjects:
8428 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8429 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8430 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8431 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8432 nil
8433 ];
8434
8435 if (IsWildcat_) {
8436 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8437 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8438 } else {
8439 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8440 }
8441
8442 for (int i = 0; i < [items count]; i++) {
8443 [[controllers objectAtIndex:i] setTabBarItem:[items objectAtIndex:i]];
8444 }
8445
8446 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8447 [tabbar_ setViewControllers:controllers];
8448 [tabbar_ setDelegate:self];
8449 [tabbar_ setSelectedIndex:0];
8450
8451 container_ = [[CYContainer alloc] initWithDatabase:database_];
8452 [[container_ view] setFrame:[window_ bounds]];
8453 [container_ setUpdateDelegate:self];
8454 [container_ setRootController:tabbar_];
8455 [window_ addSubview:[container_ view]];
8456
8457 [UIKeyboard initImplementationNow];
8458
8459 [self reloadData];
8460
8461 #if RecyclePackageViews
8462 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8463 [details_ addObject:[self _packageView]];
8464 [details_ addObject:[self _packageView]];
8465 #endif
8466
8467 PrintTimes();
8468
8469 _setHomePage(self);
8470 }
8471
8472 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8473 if (item != nil && IsWildcat_) {
8474 [sheet showFromBarButtonItem:item animated:YES];
8475 } else {
8476 [sheet showInView:window_];
8477 }
8478 }
8479
8480 @end
8481
8482 /*IMP alloc_;
8483 id Alloc_(id self, SEL selector) {
8484 id object = alloc_(self, selector);
8485 lprintf("[%s]A-%p\n", self->isa->name, object);
8486 return object;
8487 }*/
8488
8489 /*IMP dealloc_;
8490 id Dealloc_(id self, SEL selector) {
8491 id object = dealloc_(self, selector);
8492 lprintf("[%s]D-%p\n", self->isa->name, object);
8493 return object;
8494 }*/
8495
8496 Class $WebDefaultUIKitDelegate;
8497
8498 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8499 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8500 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8501 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8502 }
8503
8504 int main(int argc, char *argv[]) { _pooled
8505 _trace();
8506
8507 if (Class $UIDevice = objc_getClass("UIDevice")) {
8508 UIDevice *device([$UIDevice currentDevice]);
8509 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8510 } else
8511 IsWildcat_ = false;
8512
8513 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8514
8515 /* Library Hacks {{{ */
8516 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8517 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8518
8519 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8520 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8521 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8522 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8523 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8524 }
8525 /* }}} */
8526 /* Set Locale {{{ */
8527 Locale_ = CFLocaleCopyCurrent();
8528 Languages_ = [NSLocale preferredLanguages];
8529 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8530 //NSLog(@"%@", [Languages_ description]);
8531
8532 const char *lang;
8533 if (Languages_ == nil || [Languages_ count] == 0)
8534 // XXX: consider just setting to C and then falling through?
8535 lang = NULL;
8536 else {
8537 lang = [[Languages_ objectAtIndex:0] UTF8String];
8538 setenv("LANG", lang, true);
8539 }
8540
8541 //std::setlocale(LC_ALL, lang);
8542 NSLog(@"Setting Language: %s", lang);
8543 /* }}} */
8544
8545 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8546
8547 /* Parse Arguments {{{ */
8548 bool substrate(false);
8549
8550 if (argc != 0) {
8551 char **args(argv);
8552 int arge(1);
8553
8554 for (int argi(1); argi != argc; ++argi)
8555 if (strcmp(argv[argi], "--") == 0) {
8556 arge = argi;
8557 argv[argi] = argv[0];
8558 argv += argi;
8559 argc -= argi;
8560 break;
8561 }
8562
8563 for (int argi(1); argi != arge; ++argi)
8564 if (strcmp(args[argi], "--substrate") == 0)
8565 substrate = true;
8566 else
8567 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8568 }
8569 /* }}} */
8570
8571 App_ = [[NSBundle mainBundle] bundlePath];
8572 Home_ = NSHomeDirectory();
8573 Advanced_ = YES;
8574
8575 setuid(0);
8576 setgid(0);
8577
8578 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8579 alloc_ = alloc->method_imp;
8580 alloc->method_imp = (IMP) &Alloc_;*/
8581
8582 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8583 dealloc_ = dealloc->method_imp;
8584 dealloc->method_imp = (IMP) &Dealloc_;*/
8585
8586 /* System Information {{{ */
8587 size_t size;
8588
8589 int maxproc;
8590 size = sizeof(maxproc);
8591 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8592 perror("sysctlbyname(\"kern.maxproc\", ?)");
8593 else if (maxproc < 64) {
8594 maxproc = 64;
8595 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8596 perror("sysctlbyname(\"kern.maxproc\", #)");
8597 }
8598
8599 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8600 char *osversion = new char[size];
8601 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8602 perror("sysctlbyname(\"kern.osversion\", ?)");
8603 else
8604 System_ = [NSString stringWithUTF8String:osversion];
8605
8606 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8607 char *machine = new char[size];
8608 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8609 perror("sysctlbyname(\"hw.machine\", ?)");
8610 else
8611 Machine_ = machine;
8612
8613 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8614 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8615 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8616 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8617 CFRelease(serial);
8618 }
8619
8620 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8621 NSData *data((NSData *) ecid);
8622 size_t length([data length]);
8623 uint8_t bytes[length];
8624 [data getBytes:bytes];
8625 char string[length * 2 + 1];
8626 for (size_t i(0); i != length; ++i)
8627 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8628 ChipID_ = [NSString stringWithUTF8String:string];
8629 CFRelease(ecid);
8630 }
8631
8632 IOObjectRelease(service);
8633 }
8634 }
8635
8636 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8637
8638 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8639 Build_ = [system objectForKey:@"ProductBuildVersion"];
8640 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8641 Product_ = [info objectForKey:@"SafariProductVersion"];
8642 Safari_ = [info objectForKey:@"CFBundleVersion"];
8643 }
8644 /* }}} */
8645 /* Load Database {{{ */
8646 _trace();
8647 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8648 _trace();
8649 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8650 _trace();
8651
8652 if (Metadata_ == NULL)
8653 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8654 else {
8655 Settings_ = [Metadata_ objectForKey:@"Settings"];
8656
8657 Packages_ = [Metadata_ objectForKey:@"Packages"];
8658 Sections_ = [Metadata_ objectForKey:@"Sections"];
8659 Sources_ = [Metadata_ objectForKey:@"Sources"];
8660
8661 Token_ = [Metadata_ objectForKey:@"Token"];
8662 }
8663
8664 if (Settings_ != nil)
8665 Role_ = [Settings_ objectForKey:@"Role"];
8666
8667 if (Packages_ == nil) {
8668 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8669 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8670 }
8671
8672 if (Sections_ == nil) {
8673 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8674 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8675 }
8676
8677 if (Sources_ == nil) {
8678 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8679 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8680 }
8681 /* }}} */
8682
8683 #if RecycleWebViews
8684 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8685 #endif
8686
8687 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8688
8689 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8690 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8691 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8692 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8693 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8694 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8695
8696 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8697
8698 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8699 unlink("/tmp/.cydia.fw");
8700 goto firmware;
8701 } else if (access("/User", F_OK) != 0 || version < 2) {
8702 firmware:
8703 _trace();
8704 system("/usr/libexec/cydia/firmware.sh");
8705 _trace();
8706 }
8707
8708 _assert([[NSFileManager defaultManager]
8709 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8710 withIntermediateDirectories:YES
8711 attributes:nil
8712 error:NULL
8713 ]);
8714
8715 if (access("/tmp/cydia.chk", F_OK) == 0) {
8716 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8717 _assert(errno == ENOENT);
8718 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8719 _assert(errno == ENOENT);
8720 }
8721
8722 /* APT Initialization {{{ */
8723 _assert(pkgInitConfig(*_config));
8724 _assert(pkgInitSystem(*_config, _system));
8725
8726 if (lang != NULL)
8727 _config->Set("APT::Acquire::Translation", lang);
8728 _config->Set("Acquire::http::Timeout", 15);
8729 _config->Set("Acquire::http::MaxParallel", 3);
8730 /* }}} */
8731 /* Color Choices {{{ */
8732 space_ = CGColorSpaceCreateDeviceRGB();
8733
8734 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8735 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8736 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8737 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8738 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8739 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8740 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8741 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8742 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8743
8744 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8745 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8746 /* }}}*/
8747 /* UIKit Configuration {{{ */
8748 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8749 if ($GSFontSetUseLegacyFontMetrics != NULL)
8750 $GSFontSetUseLegacyFontMetrics(YES);
8751
8752 // XXX: I have a feeling this was important
8753 //UIKeyboardDisableAutomaticAppearance();
8754 /* }}} */
8755
8756 Colon_ = UCLocalize("COLON_DELIMITED");
8757 Error_ = UCLocalize("ERROR");
8758 Warning_ = UCLocalize("WARNING");
8759
8760 _trace();
8761 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8762
8763 CGColorSpaceRelease(space_);
8764 CFRelease(Locale_);
8765
8766 return value;
8767 }