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