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