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