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