]> git.saurik.com Git - cydia.git/blame - Cydia.mm
Commit (chpwn): reachability.patch
[cydia.git] / Cydia.mm
CommitLineData
36bb2ca2 1/* Cydia - iPhone UIKit Front-End for Debian APT
77801ff1 2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
36bb2ca2
JF
3*/
4
bfc87a4d 5/* Modified BSD License {{{ */
36bb2ca2
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*/
bfc87a4d 38/* }}} */
36bb2ca2 39
b0ad8dee
JF
40// XXX: wtf/FastMalloc.h... wtf?
41#define USE_SYSTEM_MALLOC 1
42
dc5812ec 43/* #include Directives {{{ */
a95e0405
JF
44#import "UICaboodle/UCPlatform.h"
45#import "UICaboodle/UCLocalize.h"
807ae6d7 46
ab398adf
JF
47#include <objc/objc.h>
48#include <objc/runtime.h>
49
5f6bff8c 50#include <CoreGraphics/CoreGraphics.h>
9743c015 51#include <GraphicsServices/GraphicsServices.h>
5f6bff8c 52#include <Foundation/Foundation.h>
7d2ac47f 53
eef4ccaf
JF
54#if 0
55#define DEPLOYMENT_TARGET_MACOSX 1
56#define CF_BUILDING_CF 1
57#include <CoreFoundation/CFInternal.h>
58#endif
59
677b8415
JF
60#include <CoreFoundation/CFPriv.h>
61#include <CoreFoundation/CFUniChar.h>
62
baf80942 63#import <UIKit/UIKit.h>
a9543575 64
f79a4512
JF
65#include <WebCore/WebCoreThread.h>
66#import <WebKit/WebDefaultUIKitDelegate.h>
7e9a36b6 67
677b8415 68#include <algorithm>
808c6eb6 69#include <iomanip>
2367a917 70#include <sstream>
a0be02eb
JF
71#include <string>
72
2367a917
JF
73#include <ext/stdio_filebuf.h>
74
e59669fd
JF
75#undef ABS
76
dc5812ec
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>
77fcccaf 81#include <apt-pkg/clean.h>
dc5812ec 82#include <apt-pkg/configuration.h>
7376b55c 83#include <apt-pkg/debindexfile.h>
3178d79b 84#include <apt-pkg/debmetaindex.h>
dc5812ec
JF
85#include <apt-pkg/error.h>
86#include <apt-pkg/init.h>
dddbc481 87#include <apt-pkg/mmap.h>
dc5812ec 88#include <apt-pkg/pkgrecords.h>
dddbc481 89#include <apt-pkg/sha1.h>
dc5812ec 90#include <apt-pkg/sourcelist.h>
2367a917 91#include <apt-pkg/sptr.h>
affeffc7 92#include <apt-pkg/strutl.h>
f9f6d9e8 93#include <apt-pkg/tagfile.h>
dc5812ec 94
f79a4512
JF
95#include <apr-1/apr_pools.h>
96
87f46a96
JF
97#include <sys/types.h>
98#include <sys/stat.h>
3178d79b 99#include <sys/sysctl.h>
59c011d8
JF
100#include <sys/param.h>
101#include <sys/mount.h>
87f46a96 102
2a8d9add 103#include <notify.h>
dddbc481 104#include <dlfcn.h>
3178d79b 105
b4d89997
JF
106extern "C" {
107#include <mach-o/nlist.h>
108}
109
a0be02eb
JF
110#include <cstdio>
111#include <cstdlib>
112#include <cstring>
b4d89997 113
2367a917 114#include <errno.h>
dc5812ec 115#include <pcre.h>
a9543575 116
f79a4512
JF
117#include <ext/hash_map>
118
a95e0405
JF
119#import "UICaboodle/BrowserView.h"
120#import "UICaboodle/ResetView.h"
fd7853a6
JF
121
122#import "substrate.h"
9aecdc9c
GP
123
124// Apple's sample Reachability code, ASPL licensed.
125#import "Reachability.h"
dc5812ec 126/* }}} */
3178d79b 127
b5e7eebb
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
bfc87a4d 168/* Profiler {{{ */
807ae6d7
JF
169struct timeval _ltv;
170bool _itv;
171
2083b866
JF
172#define _timestamp ({ \
173 struct timeval tv; \
174 gettimeofday(&tv, NULL); \
175 tv.tv_sec * 1000000 + tv.tv_usec; \
176})
177
808c6eb6
JF
178typedef std::vector<class ProfileTime *> TimeList;
179TimeList times_;
180
181class ProfileTime {
182 private:
183 const char *name_;
184 uint64_t total_;
76933519 185 uint64_t count_;
808c6eb6
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;
76933519 197 ++count_;
808c6eb6
JF
198 }
199
200 void Print() {
201 if (total_ != 0)
76933519 202 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
808c6eb6 203 total_ = 0;
76933519 204 count_ = 0;
808c6eb6
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 }
f79a4512 236/* }}} */
affeffc7
JF
237
238#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
239
04fe1349
JF
240static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
241
bf8476c8
JF
242void NSLogPoint(const char *fix, const CGPoint &point) {
243 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
244}
245
affeffc7
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);
1e7a90f5
JF
248}
249
670a0494
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
bfc87a4d 260/* [NSObject yieldToSelector:(withObject:)] {{{*/
d061f4ba 261@interface NSObject (Cydia)
2fc76a2d
JF
262- (id) yieldToSelector:(SEL)selector withObject:(id)object;
263- (id) yieldToSelector:(SEL)selector;
d061f4ba
JF
264@end
265
266@implementation NSObject (Cydia)
267
268- (void) doNothing {
269}
270
2fc76a2d 271- (void) _yieldToContext:(NSMutableArray *)context { _pooled
d061f4ba
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
2fc76a2d
JF
276 /* XXX: deal with exceptions */
277 id value([self performSelector:selector withObject:object]);
278
677b8415 279 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
2fc76a2d 280 [context removeAllObjects];
677b8415 281 if ([signature methodReturnLength] != 0 && value != nil)
2fc76a2d 282 [context addObject:value];
d061f4ba
JF
283
284 stopped = true;
285
286 [self
287 performSelectorOnMainThread:@selector(doNothing)
288 withObject:nil
289 waitUntilDone:NO
290 ];
291}
292
2fc76a2d 293- (id) yieldToSelector:(SEL)selector withObject:(id)object {
3e9c9e85 294 /*return [self performSelector:selector withObject:object];*/
808c6eb6 295
d061f4ba
JF
296 volatile bool stopped(false);
297
2fc76a2d 298 NSMutableArray *context([NSMutableArray arrayWithObjects:
d061f4ba
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]);
2fc76a2d
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];
d061f4ba
JF
322}
323
324@end
bfc87a4d 325/* }}} */
d061f4ba 326
38be2c4b 327@interface CYActionSheet : UIAlertView {
670a0494
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 {
38be2c4b 337 if ((self = [super init])) {
b5e7eebb
GP
338 [self setTitle:title];
339 [self setDelegate:self];
340 for (NSString *button in buttons) [self addButtonWithTitle:button];
341 [self setCancelButtonIndex:index];
670a0494
JF
342 } return self;
343}
344
38be2c4b
GP
345- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
346 button_ = buttonIndex + 1;
670a0494
JF
347}
348
be2b3d7b 349- (void) dismiss {
b5e7eebb 350 [self dismissWithClickedButtonIndex:-1 animated:YES];
be2b3d7b
GP
351}
352
670a0494
JF
353- (int) yieldToPopupAlertAnimated:(BOOL)animated {
354 button_ = 0;
be2b3d7b 355 [self show];
670a0494
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
68f1828e 364/* NSForcedOrderingSearch doesn't work on the iPhone */
808c6eb6 365static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
677b8415
JF
366static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
367static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
1e7a90f5 368
6e201c55
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 {
bfc87a4d 389 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
6e201c55
JF
390}
391
392@end
393/* }}} */
394
c390d3ab 395#define lprintf(args...) fprintf(stderr, args)
a9543575 396
aeed65a6 397#define ForRelease 0
ab92ad73 398#define TraceLogging (1 && !ForRelease)
220fa2b0 399#define HistogramInsertionSort (0 && !ForRelease)
f9f6d9e8 400#define ProfileTimes (0 && !ForRelease)
123c5344 401#define ForSaurik (0 && !ForRelease)
670a0494 402#define LogBrowser (0 && !ForRelease)
b1ce61ec 403#define TrackResize (0 && !ForRelease)
01d93940 404#define ManualRefresh (0 && !ForRelease)
f79a4512 405#define ShowInternals (0 && !ForRelease)
b0ad8dee 406#define IgnoreInstall (0 && !ForRelease)
affeffc7 407#define RecycleWebViews 0
8cc8eb1c 408#define RecyclePackageViews (1 && ForRelease)
aeed65a6 409#define AlwaysReload (1 && !ForRelease)
795d26fc 410
ab92ad73 411#if !TraceLogging
189a73d0
JF
412#undef _trace
413#define _trace(args...)
ab92ad73
JF
414#endif
415
416#if !ProfileTimes
808c6eb6 417#undef _profile
3e9c9e85 418#define _profile(name) {
808c6eb6 419#undef _end
3e9c9e85 420#define _end }
2fc76a2d 421#define PrintTimes() do {} while (false)
189a73d0
JF
422#endif
423
807ae6d7 424/* Radix Sort {{{ */
df213583
JF
425typedef uint32_t (*SKRadixFunction)(id, void *);
426
807ae6d7 427@interface NSMutableArray (Radix)
9487f027 428- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
df213583 429- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
807ae6d7
JF
430@end
431
f79a4512
JF
432struct RadixItem_ {
433 size_t index;
434 uint32_t key;
435};
807ae6d7 436
f79a4512
JF
437static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
438 struct RadixItem_ *lhs(swap), *rhs(swap + count);
807ae6d7 439
ec3f2f53 440 static const size_t width = 32;
807ae6d7
JF
441 static const size_t bits = 11;
442 static const size_t slots = 1 << bits;
ec3f2f53 443 static const size_t passes = (width + (bits - 1)) / bits;
807ae6d7
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;
ec3f2f53 453 key &= _not(uint32_t) >> width - bits;
807ae6d7
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;
ec3f2f53 467 key &= _not(uint32_t) >> width - bits;
807ae6d7
JF
468 rhs[hist[key]++] = lhs[i];
469 }
470
f79a4512 471 RadixItem_ *tmp(lhs);
807ae6d7
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
f79a4512
JF
486@implementation NSMutableArray (Radix)
487
488- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
eef4ccaf
JF
489 size_t count([self count]);
490 if (count == 0)
491 return;
492
493#if 0
f79a4512
JF
494 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
495 [invocation setSelector:selector];
496 [invocation setArgument:&object atIndex:2];
eef4ccaf
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
f79a4512 504
f79a4512
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]);
f79a4512 512
eef4ccaf
JF
513#if 0
514 [invocation setTarget:object];
f79a4512
JF
515 [invocation invoke];
516 [invocation getReturnValue:&item.key];
eef4ccaf
JF
517#else
518 item.key = imp(object, selector, object);
519#endif
f79a4512
JF
520 }
521
522 RadixSort_(self, count, swap);
523}
524
df213583 525- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
f79a4512
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
807ae6d7 540@end
eef4ccaf
JF
541/* }}} */
542/* Insertion Sort {{{ */
543
df213583
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);
b5e7eebb 550 if (0 == cr) return (probe - (const char *)list) / elementSize;
df213583
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
eef4ccaf
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);
b5e7eebb 563 if (0 == cr) return (probe - (const char *)list) / elementSize;
eef4ccaf
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
df213583
JF
576#if HistogramInsertionSort
577 uint32_t total(0), *offsets(new uint32_t[range.length]);
578#endif
579
eef4ccaf
JF
580 for (CFIndex index(1); index != range.length; ++index) {
581 const void *value(values[index]);
df213583
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;
eef4ccaf 587 if (correct != index) {
df213583
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);
eef4ccaf
JF
596 values[correct] = value;
597 }
598 }
599
600 CFArrayReplaceValues(array, range, values, range.length);
601 delete [] values;
df213583
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
eef4ccaf
JF
610}
611
807ae6d7
JF
612/* }}} */
613
bf8476c8
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
77801ff1
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
680eb135
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
2388b078
JF
668@interface NSString (UIKit)
669- (NSString *) stringByAddingPercentEscapes;
2388b078
JF
670@end
671
bfc87a4d 672/* Cydia NSString Additions {{{ */
2388b078 673@interface NSString (Cydia)
808c6eb6 674+ (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
f79a4512 675+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
2388b078 676+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
a54b1c10 677- (NSComparisonResult) compareByPath:(NSString *)other;
2fc76a2d
JF
678- (NSString *) stringByCachingURLWithCurrentCDN;
679- (NSString *) stringByAddingPercentEscapesIncludingReserved;
2388b078
JF
680@end
681
682@implementation NSString (Cydia)
683
808c6eb6
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
f79a4512
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
2388b078 694+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
2083b866 695 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
2388b078
JF
696}
697
a54b1c10
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
2fc76a2d
JF
728- (NSString *) stringByCachingURLWithCurrentCDN {
729 return [self
65c27c56
JF
730 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
731 withString:@"://cache.cydia.saurik.com/"
2fc76a2d
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
2388b078 745@end
bfc87a4d 746/* }}} */
2388b078 747
bfc87a4d 748/* C++ NSString Wrapper Cache {{{ */
f79a4512
JF
749class CYString {
750 private:
751 char *data_;
752 size_t size_;
753 CFStringRef cache_;
754
755 _finline void clear_() {
18873623 756 if (cache_ != NULL) {
f79a4512 757 CFRelease(cache_);
18873623
JF
758 cache_ = NULL;
759 }
f79a4512
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),
18873623 783 cache_(NULL)
f79a4512
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
9fcbca29 807 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
f79a4512 808 memcpy(temp, data, size);
9fcbca29 809 temp[size] = '\0';
f79a4512
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
df213583 827 operator CFStringRef() {
f79a4512
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);
01d93940
JF
832 if (cache_ == NULL)
833 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
df213583
JF
834 } return cache_;
835 }
836
837 _finline operator id() {
838 return (NSString *) static_cast<CFStringRef>(*this);
f79a4512
JF
839 }
840};
bfc87a4d
JF
841/* }}} */
842/* C++ NSString Algorithm Adapters {{{ */
f79a4512
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};
bfc87a4d 872/* }}} */
f79a4512 873
b4d89997
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) {
c390d3ab 892 lprintf("%d:%s\n", offset, error);
b4d89997
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) {
2388b078 906 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
b4d89997
JF
907 }
908
8b29f8e6
JF
909 bool operator ()(NSString *data) {
910 // XXX: length is for characters, not for bytes
911 return operator ()([data UTF8String], [data length]);
912 }
913
b4d89997
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/* }}} */
36bb2ca2 920/* Mime Addresses {{{ */
36bb2ca2
JF
921@interface Address : NSObject {
922 NSString *name_;
6f1a15d9 923 NSString *address_;
36bb2ca2
JF
924}
925
926- (NSString *) name;
6f1a15d9 927- (NSString *) address;
36bb2ca2 928
dc63e78f
JF
929- (void) setAddress:(NSString *)address;
930
36bb2ca2
JF
931+ (Address *) addressWithString:(NSString *)string;
932- (Address *) initWithString:(NSString *)string;
933@end
934
935@implementation Address
936
937- (void) dealloc {
938 [name_ release];
6f1a15d9
JF
939 if (address_ != nil)
940 [address_ release];
36bb2ca2
JF
941 [super dealloc];
942}
943
944- (NSString *) name {
945 return name_;
946}
947
6f1a15d9
JF
948- (NSString *) address {
949 return address_;
36bb2ca2
JF
950}
951
dc63e78f
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
36bb2ca2
JF
961+ (Address *) addressWithString:(NSString *)string {
962 return [[[Address alloc] initWithString:string] autorelease];
963}
964
6f1a15d9
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
36bb2ca2
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
6f1a15d9 982 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
7b0ce2da 983
6f1a15d9
JF
984 if (address_r(data, size)) {
985 name_ = [address_r[1] retain];
986 address_ = [address_r[2] retain];
36bb2ca2 987 } else {
affeffc7 988 name_ = [string retain];
6f1a15d9 989 address_ = nil;
36bb2ca2
JF
990 }
991 } return self;
992}
993
994@end
995/* }}} */
5f6bff8c 996/* CoreGraphics Primitives {{{ */
b4d89997
JF
997class CGColor {
998 private:
999 CGColorRef color_;
1000
1001 public:
36bb2ca2
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_);
b4d89997
JF
1016 }
1017
1018 ~CGColor() {
36bb2ca2
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);
b4d89997
JF
1026 }
1027
1028 operator CGColorRef() {
1029 return color_;
1030 }
1031};
b4d89997
JF
1032/* }}} */
1033
36bb2ca2 1034/* Random Global Variables {{{ */
3178d79b 1035static const int PulseInterval_ = 50000;
58241d4c 1036static const int ButtonBarWidth_ = 60;
2388b078 1037static const int ButtonBarHeight_ = 48;
6d9712c4 1038static const float KeyboardTime_ = 0.3f;
affeffc7 1039
d791dce4
JF
1040static int Finish_;
1041static NSArray *Finishes_;
1042
affeffc7 1043#define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
22f8bed9 1044#define NotifyConfig_ "/etc/notify.conf"
2a8d9add 1045
dc63e78f
JF
1046static bool Queuing_;
1047
f641a0e5 1048static CGColor Blue_;
77fcccaf 1049static CGColor Blueish_;
36bb2ca2 1050static CGColor Black_;
baf80942 1051static CGColor Off_;
36bb2ca2 1052static CGColor White_;
7b0ce2da 1053static CGColor Gray_;
3bd1c2a2
JF
1054static CGColor Green_;
1055static CGColor Purple_;
1056static CGColor Purplish_;
1057
dc63e78f
JF
1058static UIColor *InstallingColor_;
1059static UIColor *RemovingColor_;
36bb2ca2 1060
7d2ac47f 1061static NSString *App_;
d73cede2 1062static NSString *Home_;
d73cede2 1063
2388b078 1064static BOOL Advanced_;
a54b1c10 1065static BOOL Ignored_;
2388b078 1066
f641a0e5
JF
1067static UIFont *Font12_;
1068static UIFont *Font12Bold_;
1069static UIFont *Font14_;
1070static UIFont *Font18Bold_;
1071static UIFont *Font22Bold_;
1072
87f46a96 1073static const char *Machine_ = NULL;
bfc87a4d 1074static const NSString *System_ = NULL;
59dbe296
JF
1075static const NSString *SerialNumber_ = nil;
1076static const NSString *ChipID_ = nil;
01d93940 1077static const NSString *Token_ = nil;
ad5d065e
JF
1078static const NSString *UniqueID_ = nil;
1079static const NSString *Build_ = nil;
3e9c9e85
JF
1080static const NSString *Product_ = nil;
1081static const NSString *Safari_ = nil;
2a8d9add 1082
d791dce4
JF
1083static CFLocaleRef Locale_;
1084static NSArray *Languages_;
1085static CGColorSpaceRef space_;
36bb2ca2 1086
46dbfd32 1087static NSDictionary *SectionMap_;
b4d89997 1088static NSMutableDictionary *Metadata_;
7b0ce2da
JF
1089static _transient NSMutableDictionary *Settings_;
1090static _transient NSString *Role_;
1091static _transient NSMutableDictionary *Packages_;
1092static _transient NSMutableDictionary *Sections_;
1093static _transient NSMutableDictionary *Sources_;
bbb879fb 1094static bool Changed_;
b4d89997 1095static NSDate *now_;
8da60fb7 1096
01d93940
JF
1097static bool IsWildcat_;
1098
affeffc7
JF
1099#if RecycleWebViews
1100static NSMutableArray *Documents_;
1101#endif
36bb2ca2 1102/* }}} */
d791dce4 1103
36bb2ca2
JF
1104/* Display Helpers {{{ */
1105inline float Interpolate(float begin, float end, float fraction) {
1106 return (end - begin) * fraction + begin;
1107}
2367a917 1108
f79a4512 1109/* XXX: localize this! */
8fe19fc1 1110NSString *SizeString(double size) {
affeffc7
JF
1111 bool negative = size < 0;
1112 if (negative)
1113 size = -size;
1114
8fe19fc1
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
86316a91 1123 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
8fe19fc1
JF
1124}
1125
0dd0c302
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
6a155117
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
843e75b8 1137CFStringRef StripVersion(const char *version) {
18876387
JF
1138 const char *colon(strchr(version, ':'));
1139 if (colon != NULL)
1140 version = colon + 1;
6a155117
JF
1141 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1142 // XXX: performance
0dd0c302 1143 return CFCString(version);
18876387
JF
1144}
1145
f79a4512 1146NSString *LocalizeSection(NSString *section) {
b1ce61ec 1147 static Pcre title_r("^(.*?) \\((.*)\\)$");
9fcbca29
JF
1148 if (title_r(section)) {
1149 NSString *parent(title_r[1]);
1150 NSString *child(title_r[2]);
1151
43f3d7f6 1152 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
9fcbca29
JF
1153 LocalizeSection(parent),
1154 LocalizeSection(child)
b1ce61ec 1155 ];
9fcbca29 1156 }
b1ce61ec
JF
1157
1158 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
f79a4512
JF
1159}
1160
4cf4165e
JF
1161NSString *Simplify(NSString *title) {
1162 const char *data = [title UTF8String];
1163 size_t size = [title length];
1164
7b0ce2da
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
b1ce61ec 1173 static Pcre title_r("^(.*?) \\((.*)\\)$");
4cf4165e 1174 if (title_r(data, size))
7b0ce2da
JF
1175 return Simplify(title_r[1]);
1176
1177 return title;
4cf4165e 1178}
36bb2ca2
JF
1179/* }}} */
1180
d791dce4
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
6d9712c4 1195bool isSectionVisible(NSString *section) {
677b8415
JF
1196 NSDictionary *metadata([Sections_ objectForKey:section]);
1197 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
6d9712c4
JF
1198 return hidden == nil || ![hidden boolValue];
1199}
1200
d36e83a3 1201/* Delegate Prototypes {{{ */
36bb2ca2
JF
1202@class Package;
1203@class Source;
1204
31f3cfff
JF
1205@interface NSObject (ProgressDelegate)
1206@end
1207
36bb2ca2 1208@protocol ProgressDelegate
670a0494 1209- (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
36bb2ca2
JF
1210- (void) setProgressTitle:(NSString *)title;
1211- (void) setProgressPercent:(float)percent;
baf80942 1212- (void) startProgress;
36bb2ca2 1213- (void) addProgressOutput:(NSString *)output;
baf80942 1214- (bool) isCancelling:(size_t)received;
36bb2ca2
JF
1215@end
1216
8b29f8e6 1217@protocol ConfigurationDelegate
5a09ae08 1218- (void) repairWithSelector:(SEL)selector;
8b29f8e6
JF
1219- (void) setConfigurationData:(NSString *)data;
1220@end
1221
f79a4512
JF
1222@class PackageView;
1223
36bb2ca2 1224@protocol CydiaDelegate
f79a4512 1225- (void) setPackageView:(PackageView *)view;
dc63e78f 1226- (void) clearPackage:(Package *)package;
36bb2ca2 1227- (void) installPackage:(Package *)package;
77801ff1 1228- (void) installPackages:(NSArray *)packages;
36bb2ca2 1229- (void) removePackage:(Package *)package;
36bb2ca2 1230- (void) distUpgrade;
6d9712c4 1231- (void) updateData;
7b0ce2da
JF
1232- (void) syncData;
1233- (void) askForSettings;
1234- (UIProgressHUD *) addProgressHUD;
d061f4ba 1235- (void) removeProgressHUD:(UIProgressHUD *)hud;
b5e7eebb 1236- (UIViewController *) pageForPackage:(NSString *)name;
f79a4512 1237- (PackageView *) packageView;
36bb2ca2 1238@end
d36e83a3 1239/* }}} */
b4d89997 1240
dc5812ec
JF
1241/* Status Delegation {{{ */
1242class Status :
1243 public pkgAcquireStatus
1244{
1245 private:
31f3cfff 1246 _transient NSObject<ProgressDelegate> *delegate_;
dc5812ec
JF
1247
1248 public:
1249 Status() :
1250 delegate_(nil)
1251 {
1252 }
1253
1254 void setDelegate(id delegate) {
1255 delegate_ = delegate;
1256 }
1257
670a0494
JF
1258 NSObject<ProgressDelegate> *getDelegate() const {
1259 return delegate_;
1260 }
1261
dc5812ec
JF
1262 virtual bool MediaChange(std::string media, std::string drive) {
1263 return false;
1264 }
1265
1266 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
dc5812ec
JF
1267 }
1268
1269 virtual void Fetch(pkgAcquire::ItemDesc &item) {
9487f027 1270 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
670a0494 1271 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
dc5812ec
JF
1272 }
1273
1274 virtual void Done(pkgAcquire::ItemDesc &item) {
dc5812ec
JF
1275 }
1276
1277 virtual void Fail(pkgAcquire::ItemDesc &item) {
1d80f6b9
JF
1278 if (
1279 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1280 item.Owner->Status == pkgAcquire::Item::StatDone
1281 )
1282 return;
1283
affeffc7
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
670a0494 1292 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
affeffc7
JF
1293 withObject:[NSArray arrayWithObjects:
1294 [NSString stringWithUTF8String:error.c_str()],
1295 source,
1296 nil]
31f3cfff
JF
1297 waitUntilDone:YES
1298 ];
dc5812ec
JF
1299 }
1300
1301 virtual bool Pulse(pkgAcquire *Owner) {
2367a917
JF
1302 bool value = pkgAcquireStatus::Pulse(Owner);
1303
1304 float percent(
1305 double(CurrentBytes + CurrentItems) /
1306 double(TotalBytes + TotalItems)
1307 );
1308
36bb2ca2 1309 [delegate_ setProgressPercent:percent];
baf80942 1310 return [delegate_ isCancelling:CurrentBytes] ? false : value;
dc5812ec
JF
1311 }
1312
1313 virtual void Start() {
baf80942 1314 [delegate_ startProgress];
dc5812ec
JF
1315 }
1316
1317 virtual void Stop() {
dc5812ec
JF
1318 }
1319};
1320/* }}} */
1321/* Progress Delegation {{{ */
1322class Progress :
1323 public OpProgress
1324{
1325 private:
36bb2ca2 1326 _transient id<ProgressDelegate> delegate_;
bfc87a4d 1327 float percent_;
dc5812ec
JF
1328
1329 protected:
1330 virtual void Update() {
670a0494
JF
1331 /*if (abs(Percent - percent_) > 2)
1332 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
bfc87a4d 1333 percent_ = Percent;
670a0494 1334 }*/
bfc87a4d 1335
8eed3ec6
JF
1336 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1337 [delegate_ setProgressPercent:(Percent / 100)];*/
dc5812ec
JF
1338 }
1339
1340 public:
1341 Progress() :
bfc87a4d
JF
1342 delegate_(nil),
1343 percent_(0)
dc5812ec
JF
1344 {
1345 }
1346
1347 void setDelegate(id delegate) {
1348 delegate_ = delegate;
1349 }
1350
670a0494
JF
1351 id getDelegate() const {
1352 return delegate_;
1353 }
1354
dc5812ec 1355 virtual void Done() {
670a0494 1356 //NSLog(@"DONE");
8eed3ec6 1357 //[delegate_ setProgressPercent:1];
dc5812ec
JF
1358 }
1359};
1360/* }}} */
1361
36bb2ca2 1362/* Database Interface {{{ */
68d927e2
JF
1363typedef std::map< unsigned long, _H<Source> > SourceMap;
1364
36bb2ca2 1365@interface Database : NSObject {
f79a4512
JF
1366 NSZone *zone_;
1367 apr_pool_t *pool_;
1368
a1440b10
JF
1369 unsigned era_;
1370
36bb2ca2 1371 pkgCacheFile cache_;
5a09ae08 1372 pkgDepCache::Policy *policy_;
36bb2ca2
JF
1373 pkgRecords *records_;
1374 pkgProblemResolver *resolver_;
1375 pkgAcquire *fetcher_;
1376 FileFd *lock_;
1377 SPtr<pkgPackageManager> manager_;
1378 pkgSourceList *list_;
5f6bff8c 1379
68d927e2 1380 SourceMap sources_;
9fcbca29 1381 NSMutableArray *packages_;
b4d89997 1382
31f3cfff 1383 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
36bb2ca2
JF
1384 Status status_;
1385 Progress progress_;
8b29f8e6 1386
77fcccaf 1387 int cydiafd_;
36bb2ca2 1388 int statusfd_;
8b29f8e6 1389 FILE *input_;
dc5812ec
JF
1390}
1391
770f2a8e 1392+ (Database *) sharedInstance;
a1440b10 1393- (unsigned) era;
770f2a8e 1394
77fcccaf 1395- (void) _readCydia:(NSNumber *)fd;
36bb2ca2
JF
1396- (void) _readStatus:(NSNumber *)fd;
1397- (void) _readOutput:(NSNumber *)fd;
2367a917 1398
8b29f8e6
JF
1399- (FILE *) input;
1400
36bb2ca2 1401- (Package *) packageWithName:(NSString *)name;
dc5812ec 1402
36bb2ca2 1403- (pkgCacheFile &) cache;
5a09ae08 1404- (pkgDepCache::Policy *) policy;
36bb2ca2
JF
1405- (pkgRecords *) records;
1406- (pkgProblemResolver *) resolver;
1407- (pkgAcquire &) fetcher;
a3328c28 1408- (pkgSourceList &) list;
36bb2ca2 1409- (NSArray *) packages;
7b0ce2da 1410- (NSArray *) sources;
36bb2ca2
JF
1411- (void) reloadData;
1412
5a09ae08 1413- (void) configure;
670a0494 1414- (bool) prepare;
36bb2ca2 1415- (void) perform;
670a0494 1416- (bool) upgrade;
36bb2ca2
JF
1417- (void) update;
1418
7623f855
JF
1419- (void) setVisible;
1420
670a0494 1421- (void) updateWithStatus:(Status &)status;
36bb2ca2
JF
1422
1423- (void) setDelegate:(id)delegate;
7376b55c 1424- (Source *) getSource:(pkgCache::PkgFileIterator)file;
670a0494
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!
b5e7eebb 1454 [self setProgressError:error withTitle:(package == nil ? id : [package name])];
670a0494
JF
1455}
1456
dc5812ec 1457@end
36bb2ca2 1458/* }}} */
dc5812ec 1459
36bb2ca2
JF
1460/* Source Class {{{ */
1461@interface Source : NSObject {
6204f56a 1462 CYString depiction_;
f9f6d9e8
JF
1463 CYString description_;
1464 CYString label_;
1465 CYString origin_;
1466 CYString support_;
dc5812ec 1467
f9f6d9e8
JF
1468 CYString uri_;
1469 CYString distribution_;
1470 CYString type_;
1471 CYString version_;
2367a917 1472
f9f6d9e8 1473 NSString *host_;
10bf7bbb 1474 NSString *authority_;
f9f6d9e8
JF
1475
1476 CYString defaultIcon_;
dc5812ec 1477
7b0ce2da 1478 NSDictionary *record_;
36bb2ca2 1479 BOOL trusted_;
dc5812ec
JF
1480}
1481
f9f6d9e8 1482- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
dc5812ec 1483
7b0ce2da
JF
1484- (NSComparisonResult) compareByNameAndType:(Source *)source;
1485
6204f56a 1486- (NSString *) depictionForPackage:(NSString *)package;
dc63e78f
JF
1487- (NSString *) supportForPackage:(NSString *)package;
1488
7b0ce2da 1489- (NSDictionary *) record;
36bb2ca2 1490- (BOOL) trusted;
dc5812ec 1491
36bb2ca2
JF
1492- (NSString *) uri;
1493- (NSString *) distribution;
1494- (NSString *) type;
7b0ce2da
JF
1495- (NSString *) key;
1496- (NSString *) host;
36bb2ca2 1497
7b0ce2da 1498- (NSString *) name;
36bb2ca2
JF
1499- (NSString *) description;
1500- (NSString *) label;
1501- (NSString *) origin;
1502- (NSString *) version;
dc5812ec 1503
36bb2ca2 1504- (NSString *) defaultIcon;
7b0ce2da 1505
dc5812ec 1506@end
dc5812ec 1507
36bb2ca2 1508@implementation Source
dc5812ec 1509
a3328c28 1510- (void) _clear {
f9f6d9e8
JF
1511 uri_.clear();
1512 distribution_.clear();
1513 type_.clear();
a3328c28 1514
f9f6d9e8
JF
1515 description_.clear();
1516 label_.clear();
1517 origin_.clear();
6204f56a 1518 depiction_.clear();
f9f6d9e8
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 }
7623f855
JF
1532
1533 if (authority_ != nil) {
1534 [authority_ release];
1535 authority_ = nil;
1536 }
a3328c28 1537}
dc5812ec 1538
a3328c28
JF
1539- (void) dealloc {
1540 [self _clear];
36bb2ca2 1541 [super dealloc];
dc5812ec
JF
1542}
1543
6f1a15d9
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
f9f6d9e8 1556- (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
a3328c28 1557 [self _clear];
dc5812ec 1558
a3328c28
JF
1559 trusted_ = index->IsTrusted();
1560
f9f6d9e8
JF
1561 uri_.set(pool, index->GetURI());
1562 distribution_.set(pool, index->GetDist());
1563 type_.set(pool, index->GetType());
a3328c28
JF
1564
1565 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1566 if (dindex != NULL) {
18873623
JF
1567 FileFd fd;
1568 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1569 _error->Discard();
1570 else {
1571 pkgTagFile tags(&fd);
f9f6d9e8 1572
18873623
JF
1573 pkgTagSection section;
1574 tags.Step(section);
a3328c28 1575
18873623
JF
1576 struct {
1577 const char *name_;
1578 CYString *value_;
1579 } names[] = {
1580 {"default-icon", &defaultIcon_},
6204f56a 1581 {"depiction", &depiction_},
18873623
JF
1582 {"description", &description_},
1583 {"label", &label_},
1584 {"origin", &origin_},
1585 {"support", &support_},
1586 {"version", &version_},
1587 };
f9f6d9e8 1588
18873623
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 }
f9f6d9e8 1596 }
36bb2ca2 1597 }
a3328c28 1598 }
7b0ce2da 1599
a3328c28
JF
1600 record_ = [Sources_ objectForKey:[self key]];
1601 if (record_ != nil)
1602 record_ = [record_ retain];
f9f6d9e8 1603
7623f855
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)
a6884de3 1611 authority_ = host_;
7623f855
JF
1612 else
1613 authority_ = [url path];
a6884de3
JF
1614
1615 if (authority_ != nil)
1616 authority_ = [authority_ retain];
a3328c28
JF
1617}
1618
f9f6d9e8 1619- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
a3328c28 1620 if ((self = [super init]) != nil) {
f9f6d9e8 1621 [self setMetaIndex:index inPool:pool];
36bb2ca2 1622 } return self;
2367a917 1623}
dc5812ec 1624
7b0ce2da
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
68f1828e 1645 return [lhs compare:rhs options:LaxCompareOptions_];
7b0ce2da
JF
1646}
1647
6204f56a
JF
1648- (NSString *) depictionForPackage:(NSString *)package {
1649 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1650}
1651
dc63e78f 1652- (NSString *) supportForPackage:(NSString *)package {
f9f6d9e8 1653 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
dc63e78f
JF
1654}
1655
7b0ce2da
JF
1656- (NSDictionary *) record {
1657 return record_;
1658}
1659
36bb2ca2
JF
1660- (BOOL) trusted {
1661 return trusted_;
1662}
3178d79b 1663
36bb2ca2
JF
1664- (NSString *) uri {
1665 return uri_;
1666}
ec97ef06 1667
36bb2ca2
JF
1668- (NSString *) distribution {
1669 return distribution_;
1670}
dc5812ec 1671
36bb2ca2
JF
1672- (NSString *) type {
1673 return type_;
dc5812ec
JF
1674}
1675
7b0ce2da 1676- (NSString *) key {
f9f6d9e8 1677 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
7b0ce2da
JF
1678}
1679
1680- (NSString *) host {
f9f6d9e8 1681 return host_;
7b0ce2da
JF
1682}
1683
1684- (NSString *) name {
7623f855 1685 return origin_.empty() ? authority_ : origin_;
7b0ce2da
JF
1686}
1687
36bb2ca2
JF
1688- (NSString *) description {
1689 return description_;
1690}
b4d89997 1691
36bb2ca2 1692- (NSString *) label {
7623f855 1693 return label_.empty() ? authority_ : label_;
36bb2ca2 1694}
3178d79b 1695
36bb2ca2
JF
1696- (NSString *) origin {
1697 return origin_;
1698}
3178d79b 1699
36bb2ca2
JF
1700- (NSString *) version {
1701 return version_;
1702}
2367a917 1703
36bb2ca2
JF
1704- (NSString *) defaultIcon {
1705 return defaultIcon_;
1706}
2367a917 1707
2388b078
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
dc5812ec 1743@end
b4d89997 1744/* }}} */
36bb2ca2 1745/* Package Class {{{ */
36bb2ca2 1746@interface Package : NSObject {
a1440b10 1747 unsigned era_;
68d927e2 1748 apr_pool_t *pool_;
a1440b10 1749
7376b55c 1750 pkgCache::VerIterator version_;
36bb2ca2
JF
1751 pkgCache::PkgIterator iterator_;
1752 _transient Database *database_;
36bb2ca2 1753 pkgCache::VerFileIterator file_;
bbb879fb 1754
36bb2ca2 1755 Source *source_;
bbb879fb 1756 bool cached_;
68d927e2 1757 bool parsed_;
dc5812ec 1758
f79a4512
JF
1759 CYString section_;
1760 NSString *section$_;
a1440b10 1761 bool essential_;
7623f855 1762 bool required_;
677b8415 1763 bool visible_;
01d93940 1764 bool obsolete_;
807ae6d7 1765
36bb2ca2 1766 NSString *latest_;
6a155117 1767 CYString installed_;
dc5812ec 1768
9fcbca29 1769 CYString id_;
f79a4512
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
7623f855 1782 CYString bugs_;
f79a4512 1783 CYString support_;
0dd0c302 1784 NSMutableArray *tags_;
7b0ce2da 1785 NSString *role_;
2388b078
JF
1786
1787 NSArray *relationships_;
677b8415 1788
f79a4512 1789 NSMutableDictionary *metadata_;
677b8415
JF
1790 _transient NSDate *firstSeen_;
1791 _transient NSDate *lastSeen_;
1792 bool subscribed_;
b4d89997
JF
1793}
1794
7376b55c 1795- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
f79a4512 1796+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
b4d89997 1797
2388b078 1798- (pkgCache::PkgIterator) iterator;
68d927e2 1799- (void) parse;
2388b078 1800
36bb2ca2 1801- (NSString *) section;
dec6029f
JF
1802- (NSString *) simpleSection;
1803
f79a4512
JF
1804- (NSString *) longSection;
1805- (NSString *) shortSection;
1806
a3328c28
JF
1807- (NSString *) uri;
1808
36bb2ca2
JF
1809- (Address *) maintainer;
1810- (size_t) size;
eef4ccaf
JF
1811- (NSString *) longDescription;
1812- (NSString *) shortDescription;
808c6eb6 1813- (unichar) index;
dc5812ec 1814
807ae6d7 1815- (NSMutableDictionary *) metadata;
36bb2ca2 1816- (NSDate *) seen;
807ae6d7
JF
1817- (BOOL) subscribed;
1818- (BOOL) ignored;
9e98e020 1819
36bb2ca2
JF
1820- (NSString *) latest;
1821- (NSString *) installed;
6a155117 1822- (BOOL) uninstalled;
5a09ae08
JF
1823
1824- (BOOL) valid;
31f3cfff 1825- (BOOL) upgradableAndEssential:(BOOL)essential;
36bb2ca2
JF
1826- (BOOL) essential;
1827- (BOOL) broken;
7d2ac47f 1828- (BOOL) unfiltered;
6d9712c4 1829- (BOOL) visible;
b4d89997 1830
9bedffaa
JF
1831- (BOOL) half;
1832- (BOOL) halfConfigured;
1833- (BOOL) halfInstalled;
1834- (BOOL) hasMode;
1835- (NSString *) mode;
1836
7623f855
JF
1837- (void) setVisible;
1838
36bb2ca2
JF
1839- (NSString *) id;
1840- (NSString *) name;
770f2a8e 1841- (UIImage *) icon;
6f1a15d9 1842- (NSString *) homepage;
25a2158d 1843- (NSString *) depiction;
77fcccaf 1844- (Address *) author;
b4d89997 1845
dc63e78f
JF
1846- (NSString *) support;
1847
affeffc7 1848- (NSArray *) files;
2388b078 1849- (NSArray *) relationships;
affeffc7
JF
1850- (NSArray *) warnings;
1851- (NSArray *) applications;
2388b078 1852
36bb2ca2 1853- (Source *) source;
7b0ce2da 1854- (NSString *) role;
b4d89997 1855
36bb2ca2 1856- (BOOL) matches:(NSString *)text;
b4d89997 1857
7b0ce2da 1858- (bool) hasSupportingRole;
6d9712c4 1859- (BOOL) hasTag:(NSString *)tag;
c390d3ab 1860- (NSString *) primaryPurpose;
770f2a8e 1861- (NSArray *) purposes;
3bd1c2a2 1862- (bool) isCommercial;
6d9712c4 1863
df213583
JF
1864- (CYString &) cyname;
1865
f79a4512 1866- (uint32_t) compareBySection:(NSArray *)sections;
807ae6d7
JF
1867
1868- (uint32_t) compareForChanges;
b4d89997 1869
36bb2ca2
JF
1870- (void) install;
1871- (void) remove;
06aa974d 1872
0a3b45ef 1873- (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
01d93940 1874- (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
0a3b45ef 1875- (bool) isInstalledAndVisible:(NSNumber *)number;
670a0494 1876- (bool) isVisibleInSection:(NSString *)section;
0a3b45ef 1877- (bool) isVisibleInSource:(Source *)source;
b4d89997 1878
36bb2ca2 1879@end
b4d89997 1880
f79a4512
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
df213583
JF
1908_finline static void Stifle(uint8_t &value) {
1909}
677b8415 1910
df213583
JF
1911uint32_t PackagePrefixRadix(Package *self, void *context) {
1912 size_t offset(reinterpret_cast<size_t>(context));
1913 CYString &name([self cyname]);
677b8415 1914
df213583
JF
1915 size_t size(name.size());
1916 if (size == 0)
1917 return 0;
1918 char *text(name.data());
677b8415 1919
df213583
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 }
677b8415 1930
df213583
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);
677b8415 1972
5358f56f
JF
1973 if (lhn == NULL)
1974 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1975 else if (rhn == NULL)
1976 return NSOrderedDescending;
1977
677b8415 1978 _profile(PackageNameCompare$NumbersLast)
df213583 1979 if (!lhi.empty() && !rhi.empty()) {
677b8415
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
df213583
JF
1988 CFIndex length = CFStringGetLength(lhn);
1989
677b8415
JF
1990 _profile(PackageNameCompare$Compare)
1991 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1992 _end
1993 _end
1994}
1995
eef4ccaf
JF
1996CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1997 return PackageNameCompare(*lhs, *rhs, context);
677b8415
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
36bb2ca2 2008@implementation Package
b4d89997 2009
df213583
JF
2010- (NSString *) description {
2011 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2012}
2013
36bb2ca2 2014- (void) dealloc {
bbb879fb
JF
2015 if (source_ != nil)
2016 [source_ release];
f79a4512
JF
2017 if (section$_ != nil)
2018 [section$_ release];
807ae6d7 2019
7376b55c
JF
2020 if (latest_ != nil)
2021 [latest_ release];
b4d89997 2022
f79a4512
JF
2023 if (sponsor$_ != nil)
2024 [sponsor$_ release];
2025 if (author$_ != nil)
2026 [author$_ release];
6d9712c4
JF
2027 if (tags_ != nil)
2028 [tags_ release];
7b0ce2da
JF
2029 if (role_ != nil)
2030 [role_ release];
9e98e020 2031
2388b078
JF
2032 if (relationships_ != nil)
2033 [relationships_ release];
f79a4512
JF
2034 if (metadata_ != nil)
2035 [metadata_ release];
2388b078 2036
36bb2ca2 2037 [super dealloc];
b4d89997
JF
2038}
2039
3bd1c2a2
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
6f1a15d9 2051+ (NSArray *) _attributeKeys {
eef4ccaf 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];
6f1a15d9
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
68d927e2
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},
7623f855 2088 {"bugs", &bugs_},
68d927e2
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;
0dd0c302 2108 if (parser->ShortDesc(start, end)) {
68d927e2
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)
1e9e6c94 2119 if (homepage_.empty())
68d927e2
JF
2120 homepage_ = website;
2121 if (homepage_ == depiction_)
2122 homepage_.clear();
2123 _end
2124 _end
2125}
2126
7623f855 2127- (void) setVisible {
ef055c6c 2128 visible_ = required_ && [self unfiltered];
7623f855
JF
2129}
2130
7376b55c 2131- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
a1440b10 2132 if ((self = [super init]) != nil) {
7376b55c 2133 _profile(Package$initWithVersion)
a1440b10
JF
2134 @synchronized (database) {
2135 era_ = [database era];
68d927e2 2136 pool_ = pool;
a1440b10 2137
7376b55c
JF
2138 version_ = version;
2139 iterator_ = version.ParentPkg();
36bb2ca2 2140 database_ = database;
b4d89997 2141
7376b55c 2142 _profile(Package$initWithVersion$Latest)
843e75b8 2143 latest_ = (NSString *) StripVersion(version_.VerStr());
808c6eb6 2144 _end
2083b866 2145
68d927e2
JF
2146 pkgCache::VerIterator current;
2147 _profile(Package$initWithVersion$Versions)
2148 current = iterator_.CurrentVer();
2149 if (!current.end())
6a155117 2150 installed_.set(pool_, StripVersion_(current.VerStr()));
06aa974d 2151
68d927e2
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
808c6eb6 2159
7376b55c 2160 _profile(Package$initWithVersion$Name)
68d927e2 2161 id_.set(pool_, iterator_.Name());
0dd0c302 2162 name_.set(pool, iterator_.Display());
808c6eb6
JF
2163 _end
2164
68d927e2
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;
808c6eb6 2171 _end
68d927e2
JF
2172 }
2173
7623f855 2174 required_ = true;
6204f56a 2175
7376b55c 2176 _profile(Package$initWithVersion$Tags)
0dd0c302
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)];
70d45c1e 2183 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
0dd0c302 2184 role_ = (NSString *) CFCString(name + 6);
7623f855 2185 if (required_ && strncmp(name, "require::", 9) == 0 && (
6204f56a
JF
2186 true
2187 ))
7623f855 2188 required_ = false;
0dd0c302
JF
2189 ++tag;
2190 } while (!tag.end());
2191 }
808c6eb6 2192 _end
7b0ce2da 2193
a4b0ec52 2194 bool changed(false);
86316a91
JF
2195 NSString *key([id_ lowercaseString]);
2196
7376b55c 2197 _profile(Package$initWithVersion$Metadata)
f79a4512 2198 metadata_ = [Packages_ objectForKey:key];
677b8415 2199
f79a4512 2200 if (metadata_ == nil) {
843e75b8 2201 firstSeen_ = now_;
677b8415 2202
f79a4512 2203 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
677b8415
JF
2204 firstSeen_, @"FirstSeen",
2205 latest_, @"LastVersion",
808c6eb6 2206 nil] mutableCopy];
a4b0ec52 2207
808c6eb6
JF
2208 changed = true;
2209 } else {
677b8415
JF
2210 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2211 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2212
2213 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2214 subscribed_ = [subscribed boolValue];
2215
f79a4512 2216 NSString *version([metadata_ objectForKey:@"LastVersion"]);
808c6eb6 2217
677b8415
JF
2218 if (firstSeen_ == nil) {
2219 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2220 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
a4b0ec52
JF
2221 changed = true;
2222 }
a4b0ec52 2223
7376b55c
JF
2224 if (version == nil) {
2225 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2226 changed = true;
01d93940 2227 } else if (![version isEqualToString:latest_]) {
7376b55c 2228 [metadata_ setObject:latest_ forKey:@"LastVersion"];
677b8415
JF
2229 lastSeen_ = now_;
2230 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
7376b55c 2231 changed = true;
01d93940 2232 }
808c6eb6
JF
2233 }
2234
f79a4512
JF
2235 metadata_ = [metadata_ retain];
2236
808c6eb6 2237 if (changed) {
f79a4512 2238 [Packages_ setObject:metadata_ forKey:key];
808c6eb6
JF
2239 Changed_ = true;
2240 }
2241 _end
a1440b10 2242
7376b55c 2243 _profile(Package$initWithVersion$Section)
68d927e2 2244 section_.set(pool_, iterator_.Section());
f79a4512 2245 _end
a1440b10 2246
01d93940 2247 obsolete_ = [self hasTag:@"cydia::obsolete"];
f79a4512 2248 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
7623f855 2249 [self setVisible];
a1440b10 2250 } _end } return self;
dc5812ec
JF
2251}
2252
f79a4512 2253+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
28ce8704 2254@synchronized ([Database class]) {
b1ce61ec
JF
2255 pkgCache::VerIterator version;
2256
2257 _profile(Package$packageWithIterator$GetCandidateVer)
2258 version = [database policy]->GetCandidateVer(iterator);
2259 _end
2260
7376b55c
JF
2261 if (version.end())
2262 return nil;
b1ce61ec 2263
5a09ae08 2264 return [[[Package alloc]
7376b55c 2265 initWithVersion:version
f79a4512
JF
2266 withZone:zone
2267 inPool:pool
5a09ae08
JF
2268 database:database
2269 ] autorelease];
28ce8704 2270} }
dc5812ec 2271
2388b078
JF
2272- (pkgCache::PkgIterator) iterator {
2273 return iterator_;
2274}
2275
36bb2ca2 2276- (NSString *) section {
f79a4512
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$_;
dc5812ec
JF
2293}
2294
dec6029f
JF
2295- (NSString *) simpleSection {
2296 if (NSString *section = [self section])
2297 return Simplify(section);
2298 else
2299 return nil;
a3328c28 2300}
dec6029f 2301
f79a4512 2302- (NSString *) longSection {
18873623 2303 return LocalizeSection([self section]);
f79a4512
JF
2304}
2305
2306- (NSString *) shortSection {
2307 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2308}
2309
a3328c28
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
dec6029f
JF
2321}
2322
36bb2ca2 2323- (Address *) maintainer {
5a09ae08
JF
2324 if (file_.end())
2325 return nil;
36bb2ca2 2326 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
00e2109e
JF
2327 const std::string &maintainer(parser->Maintainer());
2328 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
8fe19fc1
JF
2329}
2330
36bb2ca2 2331- (size_t) size {
5a09ae08 2332 return version_.end() ? 0 : version_->InstalledSize;
dc5812ec
JF
2333}
2334
eef4ccaf 2335- (NSString *) longDescription {
5a09ae08
JF
2336 if (file_.end())
2337 return nil;
36bb2ca2 2338 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2388b078 2339 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
8fe19fc1 2340
36bb2ca2
JF
2341 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2342 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2343 if ([lines count] < 2)
2344 return nil;
3178d79b 2345
36bb2ca2 2346 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
c4dcf2c2 2347 for (size_t i(1), e([lines count]); i != e; ++i) {
36bb2ca2
JF
2348 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2349 [trimmed addObject:trim];
2350 }
3178d79b 2351
36bb2ca2
JF
2352 return [trimmed componentsJoinedByString:@"\n"];
2353}
dc5812ec 2354
eef4ccaf
JF
2355- (NSString *) shortDescription {
2356 return tagline_;
2357}
2358
808c6eb6
JF
2359- (unichar) index {
2360 _profile(Package$index)
677b8415
JF
2361 CFStringRef name((CFStringRef) [self name]);
2362 if (CFStringGetLength(name) == 0)
808c6eb6 2363 return '#';
677b8415
JF
2364 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2365 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
808c6eb6 2366 return '#';
447db19d 2367 return toupper(character);
808c6eb6 2368 _end
36bb2ca2 2369}
3178d79b 2370
807ae6d7 2371- (NSMutableDictionary *) metadata {
f79a4512 2372 return metadata_;
807ae6d7
JF
2373}
2374
36bb2ca2 2375- (NSDate *) seen {
677b8415
JF
2376 if (subscribed_ && lastSeen_ != nil)
2377 return lastSeen_;
2378 return firstSeen_;
3178d79b
JF
2379}
2380
807ae6d7 2381- (BOOL) subscribed {
677b8415 2382 return subscribed_;
807ae6d7
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
36bb2ca2
JF
2393- (NSString *) latest {
2394 return latest_;
8fe19fc1
JF
2395}
2396
36bb2ca2
JF
2397- (NSString *) installed {
2398 return installed_;
3178d79b
JF
2399}
2400
6a155117
JF
2401- (BOOL) uninstalled {
2402 return installed_.empty();
2403}
2404
5a09ae08
JF
2405- (BOOL) valid {
2406 return !version_.end();
2407}
2408
31f3cfff 2409- (BOOL) upgradableAndEssential:(BOOL)essential {
677b8415
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
36bb2ca2 2417}
3178d79b 2418
36bb2ca2 2419- (BOOL) essential {
a1440b10 2420 return essential_;
3178d79b
JF
2421}
2422
36bb2ca2 2423- (BOOL) broken {
9bedffaa
JF
2424 return [database_ cache][iterator_].InstBroken();
2425}
2426
7d2ac47f 2427- (BOOL) unfiltered {
677b8415 2428 NSString *section([self section]);
ef055c6c 2429 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
7d2ac47f
JF
2430}
2431
2432- (BOOL) visible {
677b8415 2433 return visible_;
6d9712c4
JF
2434}
2435
9bedffaa 2436- (BOOL) half {
677b8415 2437 unsigned char current(iterator_->CurrentState);
9bedffaa
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)
f79a4512 2460 return @"PURGE";
9bedffaa 2461 else
f79a4512 2462 return @"REMOVE";
9bedffaa 2463 case pkgDepCache::ModeKeep:
dc63e78f 2464 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
f79a4512 2465 return @"REINSTALL";
dc63e78f
JF
2466 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2467 return nil;*/
9bedffaa
JF
2468 else
2469 return nil;
9bedffaa 2470 case pkgDepCache::ModeInstall:
dc63e78f 2471 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
f79a4512 2472 return @"REINSTALL";
dc63e78f 2473 else*/ switch (state.Status) {
9bedffaa 2474 case -1:
f79a4512 2475 return @"DOWNGRADE";
9bedffaa 2476 case 0:
f79a4512 2477 return @"INSTALL";
9bedffaa 2478 case 1:
f79a4512 2479 return @"UPGRADE";
9bedffaa 2480 case 2:
f79a4512 2481 return @"NEW_INSTALL";
670a0494 2482 _nodefault
9bedffaa 2483 }
670a0494 2484 _nodefault
9bedffaa 2485 }
8fe19fc1
JF
2486}
2487
36bb2ca2
JF
2488- (NSString *) id {
2489 return id_;
8fe19fc1
JF
2490}
2491
36bb2ca2 2492- (NSString *) name {
9fcbca29 2493 return name_.empty() ? id_ : name_;
36bb2ca2 2494}
8fe19fc1 2495
770f2a8e 2496- (UIImage *) icon {
dec6029f 2497 NSString *section = [self simpleSection];
770f2a8e
JF
2498
2499 UIImage *icon(nil);
df213583 2500 if (!icon_.empty())
189a73d0
JF
2501 if ([icon_ hasPrefix:@"file:///"])
2502 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
770f2a8e
JF
2503 if (icon == nil) if (section != nil)
2504 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
189a73d0
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]];
770f2a8e
JF
2508 if (icon == nil)
2509 icon = [UIImage applicationImageNamed:@"unknown.png"];
2510 return icon;
36bb2ca2 2511}
8fe19fc1 2512
6f1a15d9 2513- (NSString *) homepage {
3a49daf0 2514 return homepage_;
8fe19fc1
JF
2515}
2516
25a2158d 2517- (NSString *) depiction {
6204f56a 2518 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
25a2158d
JF
2519}
2520
795d26fc 2521- (Address *) sponsor {
f79a4512
JF
2522 if (sponsor$_ == nil) {
2523 if (sponsor_.empty())
2524 return nil;
2525 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2526 } return sponsor$_;
795d26fc
JF
2527}
2528
77fcccaf 2529- (Address *) author {
f79a4512
JF
2530 if (author$_ == nil) {
2531 if (author_.empty())
2532 return nil;
2533 author$_ = [[Address addressWithString:author_] retain];
2534 } return author$_;
77fcccaf
JF
2535}
2536
dc63e78f 2537- (NSString *) support {
7623f855 2538 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
dc63e78f
JF
2539}
2540
affeffc7 2541- (NSArray *) files {
9fcbca29 2542 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
affeffc7
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
2388b078
JF
2557- (NSArray *) relationships {
2558 return relationships_;
2559}
2560
affeffc7
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:
43f3d7f6 2567 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
affeffc7
JF
2568 else for (size_t i(0); i != length; ++i)
2569 if (
9dd60d81
JF
2570 /* XXX: technically this is not allowed */
2571 (name[i] < 'A' || name[i] > 'Z') &&
affeffc7
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;
7623f855 2579 bool user = false;
9dd60d81 2580 bool _private = false;
affeffc7
JF
2581 bool stash = false;
2582
9dd60d81
JF
2583 bool repository = [[self section] isEqualToString:@"Repositories"];
2584
affeffc7
JF
2585 if (NSArray *files = [self files])
2586 for (NSString *file in files)
2587 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2588 cydia = true;
7623f855
JF
2589 else if (!user && [file isEqualToString:@"/User"])
2590 user = true;
9dd60d81
JF
2591 else if (!_private && [file isEqualToString:@"/private"])
2592 _private = true;
affeffc7
JF
2593 else if (!stash && [file isEqualToString:@"/var/stash"])
2594 stash = true;
2595
9dd60d81
JF
2596 /* XXX: this is not sensitive enough. only some folders are valid. */
2597 if (cydia && !repository)
43f3d7f6 2598 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
7623f855
JF
2599 if (user)
2600 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
9dd60d81 2601 if (_private)
43f3d7f6 2602 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
affeffc7 2603 if (stash)
43f3d7f6 2604 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
affeffc7
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
36bb2ca2 2645- (Source *) source {
bbb879fb 2646 if (!cached_) {
a1440b10
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 }
bbb879fb
JF
2658 }
2659
36bb2ca2 2660 return source_;
8fe19fc1
JF
2661}
2662
7b0ce2da
JF
2663- (NSString *) role {
2664 return role_;
2665}
2666
36bb2ca2
JF
2667- (BOOL) matches:(NSString *)text {
2668 if (text == nil)
2669 return NO;
8fe19fc1 2670
36bb2ca2 2671 NSRange range;
8fe19fc1 2672
808c6eb6 2673 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2
JF
2674 if (range.location != NSNotFound)
2675 return YES;
8fe19fc1 2676
808c6eb6 2677 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2
JF
2678 if (range.location != NSNotFound)
2679 return YES;
8fe19fc1 2680
01d93940 2681 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2 2682 if (range.location != NSNotFound)
01d93940 2683 return YES;
8fe19fc1 2684
36bb2ca2
JF
2685 return NO;
2686}
8fe19fc1 2687
7b0ce2da
JF
2688- (bool) hasSupportingRole {
2689 if (role_ == nil)
6d9712c4 2690 return true;
7b0ce2da
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);
6d9712c4
JF
2704}
2705
2706- (BOOL) hasTag:(NSString *)tag {
2707 return tags_ == nil ? NO : [tags_ containsObject:tag];
2708}
2709
c390d3ab
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
770f2a8e
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
3bd1c2a2
JF
2725- (bool) isCommercial {
2726 return [self hasTag:@"cydia::commercial"];
2727}
2728
df213583
JF
2729- (CYString &) cyname {
2730 return name_.empty() ? id_ : name_;
f79a4512
JF
2731}
2732
f79a4512
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;
36bb2ca2 2738 }
3178d79b 2739
f79a4512 2740 return _not(uint32_t);
36bb2ca2 2741}
3178d79b 2742
807ae6d7
JF
2743- (uint32_t) compareForChanges {
2744 union {
2745 uint32_t key;
3178d79b 2746
807ae6d7
JF
2747 struct {
2748 uint32_t timestamp : 30;
2749 uint32_t ignored : 1;
2750 uint32_t upgradable : 1;
2751 } bits;
2752 } value;
3178d79b 2753
73ee6567
JF
2754 bool upgradable([self upgradableAndEssential:YES]);
2755 value.bits.upgradable = upgradable ? 1 : 0;
8fe19fc1 2756
73ee6567 2757 if (upgradable) {
807ae6d7
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;
36bb2ca2 2765 }
8fe19fc1 2766
807ae6d7 2767 return _not(uint32_t) - value.key;
36bb2ca2 2768}
8fe19fc1 2769
dc63e78f
JF
2770- (void) clear {
2771 pkgProblemResolver *resolver = [database_ resolver];
2772 resolver->Clear(iterator_);
2773 resolver->Protect(iterator_);
2774}
2775
36bb2ca2
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}
68a238ec 2786
36bb2ca2
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}
8fe19fc1 2794
0a3b45ef 2795- (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
808c6eb6
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
0a3b45ef 2807 return value;
808c6eb6 2808 _end
36bb2ca2 2809}
8fe19fc1 2810
01d93940 2811- (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
ef055c6c
JF
2812 if ([search length] == 0)
2813 return false;
2814
01d93940
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
0a3b45ef 2830- (bool) isInstalledAndVisible:(NSNumber *)number {
6a155117 2831 return (![number boolValue] || [self visible]) && ![self uninstalled];
36bb2ca2 2832}
8fe19fc1 2833
670a0494 2834- (bool) isVisibleInSection:(NSString *)name {
5a09ae08
JF
2835 NSString *section = [self section];
2836
0a3b45ef 2837 return
670a0494 2838 [self visible] && (
7b0ce2da
JF
2839 name == nil ||
2840 section == nil && [name length] == 0 ||
2841 [name isEqualToString:section]
0a3b45ef 2842 );
7b0ce2da
JF
2843}
2844
0a3b45ef
JF
2845- (bool) isVisibleInSource:(Source *)source {
2846 return [self source] == source && [self visible];
36bb2ca2 2847}
8fe19fc1 2848
36bb2ca2
JF
2849@end
2850/* }}} */
2851/* Section Class {{{ */
2852@interface Section : NSObject {
2853 NSString *name_;
808c6eb6 2854 unichar index_;
36bb2ca2
JF
2855 size_t row_;
2856 size_t count_;
f79a4512 2857 NSString *localized_;
36bb2ca2 2858}
3178d79b 2859
677b8415 2860- (NSComparisonResult) compareByLocalized:(Section *)section;
9fcbca29
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;
808c6eb6 2864- (Section *) initWithIndex:(unichar)index row:(size_t)row;
36bb2ca2 2865- (NSString *) name;
808c6eb6 2866- (unichar) index;
f79a4512 2867
36bb2ca2
JF
2868- (size_t) row;
2869- (size_t) count;
f79a4512
JF
2870
2871- (void) addToRow;
36bb2ca2 2872- (void) addToCount;
b19871dd 2873
f79a4512 2874- (void) setCount:(size_t)count;
677b8415 2875- (NSString *) localized;
f79a4512 2876
36bb2ca2 2877@end
b19871dd 2878
36bb2ca2 2879@implementation Section
b19871dd 2880
36bb2ca2
JF
2881- (void) dealloc {
2882 [name_ release];
f79a4512
JF
2883 if (localized_ != nil)
2884 [localized_ release];
36bb2ca2
JF
2885 [super dealloc];
2886}
b19871dd 2887
677b8415 2888- (NSComparisonResult) compareByLocalized:(Section *)section {
9fcbca29
JF
2889 NSString *lhs(localized_);
2890 NSString *rhs([section localized]);
6d9712c4 2891
9fcbca29 2892 /*if ([lhs length] != 0 && [rhs length] != 0) {
6d9712c4
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;
9fcbca29 2900 }*/
6d9712c4 2901
68f1828e 2902 return [lhs compare:rhs options:LaxCompareOptions_];
6d9712c4
JF
2903}
2904
9fcbca29
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];
6d9712c4
JF
2914}
2915
9fcbca29 2916- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
36bb2ca2
JF
2917 if ((self = [super init]) != nil) {
2918 name_ = [name retain];
808c6eb6
JF
2919 index_ = '\0';
2920 row_ = row;
9fcbca29
JF
2921 if (localize)
2922 localized_ = [LocalizeSection(name_) retain];
808c6eb6
JF
2923 } return self;
2924}
2925
f79a4512 2926/* XXX: localize the index thingees */
808c6eb6
JF
2927- (Section *) initWithIndex:(unichar)index row:(size_t)row {
2928 if ((self = [super init]) != nil) {
327624b6 2929 name_ = [[NSString stringWithCharacters:&index length:1] retain];
808c6eb6 2930 index_ = index;
36bb2ca2 2931 row_ = row;
b19871dd
JF
2932 } return self;
2933}
2934
36bb2ca2
JF
2935- (NSString *) name {
2936 return name_;
2937}
2938
808c6eb6
JF
2939- (unichar) index {
2940 return index_;
2941}
2942
36bb2ca2
JF
2943- (size_t) row {
2944 return row_;
2945}
2946
2947- (size_t) count {
2948 return count_;
2949}
2950
f79a4512
JF
2951- (void) addToRow {
2952 ++row_;
2953}
2954
36bb2ca2
JF
2955- (void) addToCount {
2956 ++count_;
2957}
2958
f79a4512
JF
2959- (void) setCount:(size_t)count {
2960 count_ = count;
2961}
2962
2963- (NSString *) localized {
2964 return localized_;
2965}
2966
b19871dd
JF
2967@end
2968/* }}} */
2969
670a0494
JF
2970static NSString *Colon_;
2971static NSString *Error_;
2972static NSString *Warning_;
2973
36bb2ca2
JF
2974/* Database Implementation {{{ */
2975@implementation Database
ec97ef06 2976
770f2a8e
JF
2977+ (Database *) sharedInstance {
2978 static Database *instance;
2979 if (instance == nil)
2980 instance = [[Database alloc] init];
2981 return instance;
2982}
2983
a1440b10
JF
2984- (unsigned) era {
2985 return era_;
2986}
2987
36bb2ca2
JF
2988- (void) dealloc {
2989 _assert(false);
f79a4512
JF
2990 NSRecycleZone(zone_);
2991 // XXX: malloc_destroy_zone(zone_);
2992 apr_pool_destroy(pool_);
36bb2ca2
JF
2993 [super dealloc];
2994}
ec97ef06 2995
affeffc7 2996- (void) _readCydia:(NSNumber *)fd { _pooled
77fcccaf
JF
2997 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2998 std::istream is(&ib);
2999 std::string line;
3000
bc8cd583
JF
3001 static Pcre finish_r("^finish:([^:]*)$");
3002
77fcccaf
JF
3003 while (std::getline(is, line)) {
3004 const char *data(line.c_str());
bc8cd583 3005 size_t size = line.size();
c390d3ab 3006 lprintf("C:%s\n", data);
bc8cd583
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 }
77fcccaf
JF
3014 }
3015
670a0494 3016 _assume(false);
77fcccaf
JF
3017}
3018
affeffc7 3019- (void) _readStatus:(NSNumber *)fd { _pooled
36bb2ca2
JF
3020 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3021 std::istream is(&ib);
3022 std::string line;
ec97ef06 3023
7b0ce2da
JF
3024 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3025 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
ec97ef06 3026
36bb2ca2
JF
3027 while (std::getline(is, line)) {
3028 const char *data(line.c_str());
670a0494 3029 size_t size(line.size());
c390d3ab 3030 lprintf("S:%s\n", data);
ec97ef06 3031
5a09ae08
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)];
36bb2ca2 3036 [delegate_ setProgressTitle:string];
5a09ae08 3037 } else if (pmstatus_r(data, size)) {
31f3cfff
JF
3038 std::string type([pmstatus_r[1] UTF8String]);
3039 NSString *id = pmstatus_r[2];
3040
5a09ae08
JF
3041 float percent([pmstatus_r[3] floatValue]);
3042 [delegate_ setProgressPercent:(percent / 100)];
3043
3044 NSString *string = pmstatus_r[4];
5a09ae08
JF
3045
3046 if (type == "pmerror")
670a0494 3047 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
31f3cfff
JF
3048 withObject:[NSArray arrayWithObjects:string, id, nil]
3049 waitUntilDone:YES
3050 ];
9487f027 3051 else if (type == "pmstatus") {
5a09ae08 3052 [delegate_ setProgressTitle:string];
9487f027 3053 } else if (type == "pmconffile")
5a09ae08 3054 [delegate_ setConfigurationData:string];
670a0494
JF
3055 else
3056 lprintf("E:unknown pmstatus\n");
3057 } else
3058 lprintf("E:unknown status\n");
36bb2ca2 3059 }
ec97ef06 3060
670a0494 3061 _assume(false);
36bb2ca2 3062}
ec97ef06 3063
affeffc7 3064- (void) _readOutput:(NSNumber *)fd { _pooled
36bb2ca2
JF
3065 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3066 std::istream is(&ib);
3067 std::string line;
3068
5a09ae08 3069 while (std::getline(is, line)) {
c390d3ab 3070 lprintf("O:%s\n", line.c_str());
2388b078 3071 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
5a09ae08 3072 }
36bb2ca2 3073
670a0494 3074 _assume(false);
ec97ef06
JF
3075}
3076
8b29f8e6
JF
3077- (FILE *) input {
3078 return input_;
3079}
3080
36bb2ca2 3081- (Package *) packageWithName:(NSString *)name {
28ce8704 3082@synchronized ([Database class]) {
5a09ae08
JF
3083 if (static_cast<pkgDepCache *>(cache_) == NULL)
3084 return nil;
36bb2ca2 3085 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
f79a4512 3086 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
28ce8704 3087} }
36bb2ca2
JF
3088
3089- (Database *) init {
ec97ef06 3090 if ((self = [super init]) != nil) {
5a09ae08 3091 policy_ = NULL;
36bb2ca2
JF
3092 records_ = NULL;
3093 resolver_ = NULL;
3094 fetcher_ = NULL;
3095 lock_ = NULL;
ec97ef06 3096
f79a4512
JF
3097 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3098 apr_pool_create(&pool_, NULL);
3099
9fcbca29 3100 packages_ = [[NSMutableArray alloc] init];
ec97ef06 3101
36bb2ca2 3102 int fds[2];
ec97ef06 3103
77fcccaf
JF
3104 _assert(pipe(fds) != -1);
3105 cydiafd_ = fds[1];
3106
3107 _config->Set("APT::Keep-Fds::", cydiafd_);
bc8cd583 3108 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
77fcccaf
JF
3109
3110 [NSThread
3111 detachNewThreadSelector:@selector(_readCydia:)
3112 toTarget:self
3113 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3114 ];
3115
36bb2ca2
JF
3116 _assert(pipe(fds) != -1);
3117 statusfd_ = fds[1];
ec97ef06 3118
36bb2ca2
JF
3119 [NSThread
3120 detachNewThreadSelector:@selector(_readStatus:)
3121 toTarget:self
3122 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3123 ];
ec97ef06 3124
8b29f8e6
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
36bb2ca2
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 ];
ec97ef06
JF
3140 } return self;
3141}
3142
36bb2ca2
JF
3143- (pkgCacheFile &) cache {
3144 return cache_;
ec97ef06
JF
3145}
3146
5a09ae08
JF
3147- (pkgDepCache::Policy *) policy {
3148 return policy_;
3149}
3150
36bb2ca2
JF
3151- (pkgRecords *) records {
3152 return records_;
ec97ef06
JF
3153}
3154
36bb2ca2
JF
3155- (pkgProblemResolver *) resolver {
3156 return resolver_;
ec97ef06
JF
3157}
3158
36bb2ca2
JF
3159- (pkgAcquire &) fetcher {
3160 return *fetcher_;
ec97ef06
JF
3161}
3162
a3328c28
JF
3163- (pkgSourceList &) list {
3164 return *list_;
3165}
3166
36bb2ca2
JF
3167- (NSArray *) packages {
3168 return packages_;
ec97ef06
JF
3169}
3170
7b0ce2da 3171- (NSArray *) sources {
68d927e2
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;
7b0ce2da
JF
3176}
3177
affeffc7
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
744f398e
JF
3211 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3212 if (Package *package = [self packageWithName:name])
3213 name = [package name];
3214 [failure addObject:name];
affeffc7
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
670a0494
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
ef348024 3266 if (fatal && !message.empty())
670a0494
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
d061f4ba 3276- (void) reloadData { _pooled
28ce8704 3277@synchronized ([Database class]) {
a1440b10
JF
3278 @synchronized (self) {
3279 ++era_;
3280 }
3281
843e75b8
JF
3282 [packages_ removeAllObjects];
3283 sources_.clear();
3284
36bb2ca2 3285 _error->Discard();
5a09ae08 3286
36bb2ca2 3287 delete list_;
5a09ae08 3288 list_ = NULL;
36bb2ca2
JF
3289 manager_ = NULL;
3290 delete lock_;
5a09ae08 3291 lock_ = NULL;
36bb2ca2 3292 delete fetcher_;
5a09ae08 3293 fetcher_ = NULL;
36bb2ca2 3294 delete resolver_;
5a09ae08 3295 resolver_ = NULL;
36bb2ca2 3296 delete records_;
5a09ae08
JF
3297 records_ = NULL;
3298 delete policy_;
3299 policy_ = NULL;
36bb2ca2 3300
843e75b8
JF
3301 if (now_ != nil) {
3302 [now_ release];
3303 now_ = nil;
3304 }
3305
5a09ae08 3306 cache_.Close();
8b29f8e6 3307
f79a4512
JF
3308 apr_pool_clear(pool_);
3309 NSRecycleZone(zone_);
3310
7376b55c
JF
3311 int chk(creat("/tmp/cydia.chk", 0644));
3312 if (chk != -1)
3313 close(chk);
3314
670a0494
JF
3315 NSString *title(UCLocalize("DATABASE"));
3316
9487f027 3317 _trace();
670a0494 3318 if (!cache_.Open(progress_, true)) { pop:
8b29f8e6 3319 std::string error;
670a0494 3320 bool warning(!_error->PopMessage(error));
c390d3ab 3321 lprintf("cache_.Open():[%s]\n", error.c_str());
5a09ae08
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)];
9ea8d159
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.")
670a0494
JF
3330 else
3331 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
5a09ae08 3332
670a0494
JF
3333 if (warning)
3334 goto pop;
3335 _error->Discard();
5a09ae08 3336 return;
36bb2ca2 3337 }
9487f027 3338 _trace();
36bb2ca2 3339
7376b55c
JF
3340 unlink("/tmp/cydia.chk");
3341
36bb2ca2
JF
3342 now_ = [[NSDate date] retain];
3343
5a09ae08 3344 policy_ = new pkgDepCache::Policy();
36bb2ca2
JF
3345 records_ = new pkgRecords(cache_);
3346 resolver_ = new pkgProblemResolver(cache_);
3347 fetcher_ = new pkgAcquire(&status_);
3348 lock_ = NULL;
3349
3350 list_ = new pkgSourceList();
670a0494
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 }
36bb2ca2 3358
670a0494
JF
3359 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3360 return;
9bedffaa
JF
3361
3362 if (cache_->BrokenCount() != 0) {
670a0494
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;
9bedffaa
JF
3373 }
3374
7376b55c 3375 _trace();
68d927e2 3376
68d927e2
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())
f9f6d9e8 3384 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
68d927e2 3385 }
36bb2ca2 3386 }
68d927e2 3387
7376b55c 3388 _trace();
36bb2ca2 3389
677b8415 3390 {
9fcbca29 3391 /*std::vector<Package *> packages;
677b8415 3392 packages.reserve(std::max(10000U, [packages_ count] + 1000));
677b8415 3393 [packages_ release];
9fcbca29
JF
3394 packages_ = nil;*/
3395
677b8415
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])
9fcbca29
JF
3400 //packages.push_back(package);
3401 [packages_ addObject:package];
677b8415
JF
3402
3403 _trace();
3404
9fcbca29 3405 /*if (packages.empty())
677b8415
JF
3406 packages_ = [[NSArray alloc] init];
3407 else
3408 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
9fcbca29
JF
3409 _trace();*/
3410
df213583
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)];
9fcbca29
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
eef4ccaf
JF
3425 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3426
df213583 3427 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
9fcbca29
JF
3428
3429 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
677b8415
JF
3430
3431 _trace();
3432 }
28ce8704 3433} }
ec97ef06 3434
5a09ae08
JF
3435- (void) configure {
3436 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3437 system([dpkg UTF8String]);
3438}
3439
670a0494
JF
3440- (bool) clean {
3441 // XXX: I don't remember this condition
77fcccaf 3442 if (lock_ != NULL)
670a0494 3443 return false;
77fcccaf
JF
3444
3445 FileFd Lock;
3446 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
670a0494
JF
3447
3448 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3449
3450 if ([self popErrorWithTitle:title])
3451 return false;
77fcccaf
JF
3452
3453 pkgAcquire fetcher;
3454 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3455
9bedffaa
JF
3456 class LogCleaner :
3457 public pkgArchiveCleaner
3458 {
77fcccaf
JF
3459 protected:
3460 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
9bedffaa 3461 unlink(File);
77fcccaf
JF
3462 }
3463 } cleaner;
3464
670a0494
JF
3465 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3466 return false;
3467
3468 return true;
77fcccaf
JF
3469}
3470
670a0494 3471- (bool) prepare {
744f398e
JF
3472 fetcher_->Shutdown();
3473
36bb2ca2
JF
3474 pkgRecords records(cache_);
3475
3476 lock_ = new FileFd();
3477 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
670a0494
JF
3478
3479 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3480
3481 if ([self popErrorWithTitle:title])
3482 return false;
36bb2ca2
JF
3483
3484 pkgSourceList list;
670a0494
JF
3485 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3486 return false;
36bb2ca2
JF
3487
3488 manager_ = (_system->CreatePM(cache_));
670a0494
JF
3489 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3490 return false;
3491
3492 return true;
ec97ef06
JF
3493}
3494
36bb2ca2 3495- (void) perform {
670a0494
JF
3496 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3497
a72074b2
JF
3498 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3499 pkgSourceList list;
670a0494
JF
3500 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3501 return;
a72074b2
JF
3502 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3503 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3504 }
a0be02eb 3505
eeb9b112
JF
3506 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3507 _trace();
36bb2ca2 3508 return;
eeb9b112
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;
6204f56a
JF
3515 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3516 continue;
eeb9b112
JF
3517
3518 std::string uri = (*item)->DescURI();
3519 std::string error = (*item)->ErrorText;
3520
c390d3ab 3521 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
eeb9b112
JF
3522 failed = true;
3523
670a0494 3524 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
a3328c28
JF
3525 withObject:[NSArray arrayWithObjects:
3526 [NSString stringWithUTF8String:error.c_str()],
3527 nil]
eeb9b112
JF
3528 waitUntilDone:YES
3529 ];
3530 }
3531
3532 if (failed) {
3533 _trace();
3534 return;
3535 }
36bb2ca2
JF
3536
3537 _system->UnLock();
3538 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3539
eeb9b112
JF
3540 if (_error->PendingError()) {
3541 _trace();
36bb2ca2 3542 return;
eeb9b112
JF
3543 }
3544
3545 if (result == pkgPackageManager::Failed) {
3546 _trace();
36bb2ca2 3547 return;
eeb9b112
JF
3548 }
3549
3550 if (result != pkgPackageManager::Completed) {
3551 _trace();
36bb2ca2 3552 return;
eeb9b112 3553 }
a0be02eb 3554
a72074b2
JF
3555 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3556 pkgSourceList list;
670a0494
JF
3557 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3558 return;
a72074b2
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];
ec97ef06
JF
3565}
3566
670a0494
JF
3567- (bool) upgrade {
3568 NSString *title(UCLocalize("UPGRADE"));
3569 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3570 return false;
3571 return true;
c7c6384e
JF
3572}
3573
36bb2ca2
JF
3574- (void) update {
3575 [self updateWithStatus:status_];
3576}
b4d89997 3577
7623f855
JF
3578- (void) setVisible {
3579 for (Package *package in packages_)
3580 [package setVisible];
3581}
3582
670a0494
JF
3583- (void) updateWithStatus:(Status &)status {
3584 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3585 NSString *title(UCLocalize("REFRESHING_DATA"));
3586
36bb2ca2 3587 pkgSourceList list;
670a0494
JF
3588 if (!list.ReadMainList())
3589 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
b4d89997 3590
36bb2ca2
JF
3591 FileFd lock;
3592 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
670a0494
JF
3593 if ([self popErrorWithTitle:title])
3594 return;
18873623 3595
670a0494 3596 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
ef348024 3597 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
36bb2ca2 3598
7623f855
JF
3599 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3600 Changed_ = true;
b4d89997
JF
3601}
3602
36bb2ca2
JF
3603- (void) setDelegate:(id)delegate {
3604 delegate_ = delegate;
3605 status_.setDelegate(delegate);
3606 progress_.setDelegate(delegate);
3607}
b4d89997 3608
7376b55c 3609- (Source *) getSource:(pkgCache::PkgFileIterator)file {
20cb1497
JF
3610 SourceMap::const_iterator i(sources_.find(file->ID));
3611 return i == sources_.end() ? nil : i->second;
b19871dd
JF
3612}
3613
36bb2ca2
JF
3614@end
3615/* }}} */
b4d89997 3616
43f3d7f6
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;
c390d3ab 3631}
b5e7eebb 3632/* }}} */
c390d3ab 3633
43f3d7f6
JF
3634/* Web Scripting {{{ */
3635@interface CydiaObject : NSObject {
3636 id indirect_;
77801ff1 3637 id delegate_;
43f3d7f6 3638}
c390d3ab 3639
43f3d7f6 3640- (id) initWithDelegate:(IndirectDelegate *)indirect;
c390d3ab
JF
3641@end
3642
43f3d7f6 3643@implementation CydiaObject
c390d3ab
JF
3644
3645- (void) dealloc {
43f3d7f6 3646 [indirect_ release];
c390d3ab
JF
3647 [super dealloc];
3648}
3649
43f3d7f6
JF
3650- (id) initWithDelegate:(IndirectDelegate *)indirect {
3651 if ((self = [super init]) != nil) {
3652 indirect_ = [indirect retain];
3653 } return self;
3654}
3655
77801ff1
JF
3656- (void) setDelegate:(id)delegate {
3657 delegate_ = delegate;
3658}
3659
43f3d7f6
JF
3660+ (NSArray *) _attributeKeys {
3661 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3662}
3663
3664- (NSArray *) attributeKeys {
3665 return [[self class] _attributeKeys];
c390d3ab
JF
3666}
3667
43f3d7f6
JF
3668+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3669 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
c390d3ab 3670}
43f3d7f6
JF
3671
3672- (NSString *) device {
3673 return [[UIDevice currentDevice] uniqueIdentifier];
c390d3ab
JF
3674}
3675
43f3d7f6
JF
3676#if 0 // XXX: implement!
3677- (NSString *) mac {
3678 if (![indirect_ promptForSensitive:@"Mac Address"])
3679 return nil;
affeffc7
JF
3680}
3681
43f3d7f6
JF
3682- (NSString *) serial {
3683 if (![indirect_ promptForSensitive:@"Serial #"])
3684 return nil;
3685}
86316a91 3686
43f3d7f6
JF
3687- (NSString *) firewire {
3688 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3689 return nil;
affeffc7
JF
3690}
3691
43f3d7f6
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";
8cc8eb1c
JF
3701 else if (selector == @selector(getInstalledPackages))
3702 return @"getInstalledPackages";
43f3d7f6
JF
3703 else if (selector == @selector(getPackageById:))
3704 return @"getPackageById";
77801ff1
JF
3705 else if (selector == @selector(installPackages:))
3706 return @"installPackages";
43f3d7f6
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";
ef055c6c
JF
3719 else if (selector == @selector(setToken:))
3720 return @"setToken";
43f3d7f6
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";
c390d3ab 3733 else
43f3d7f6
JF
3734 return nil;
3735}
3736
3737+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3738 return [self webScriptNameForSelector:selector] == nil;
c390d3ab
JF
3739}
3740
43f3d7f6
JF
3741- (BOOL) supports:(NSString *)feature {
3742 return [feature isEqualToString:@"window.open"];
3743}
c390d3ab 3744
8cc8eb1c
JF
3745- (NSArray *) getInstalledPackages {
3746 NSArray *packages([[Database sharedInstance] packages]);
3747 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
77801ff1 3748 for (Package *package in packages)
8cc8eb1c
JF
3749 if ([package installed] != nil)
3750 [installed addObject:package];
3751 return installed;
3752}
3753
43f3d7f6 3754- (Package *) getPackageById:(NSString *)id {
043e6a2e
JF
3755 Package *package([[Database sharedInstance] packageWithName:id]);
3756 [package parse];
3757 return package;
43f3d7f6
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
77801ff1
JF
3821- (void) installPackages:(NSArray *)packages {
3822 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3823}
3824
43f3d7f6
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
ef055c6c
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
43f3d7f6
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 {
a95e0405
JF
3872 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3873 value = nil;
43f3d7f6
JF
3874 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3875 table = nil;
3876 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
c390d3ab
JF
3877}
3878
3879@end
3880/* }}} */
f79a4512 3881
b5e7eebb
GP
3882/* Cydia View Controller {{{ */
3883@interface CYViewController : UCViewController { }
3884@end
3885
3886@implementation CYViewController
3887@end
3888/* }}} */
3889
3890@interface CYBrowserController : BrowserView {
43f3d7f6
JF
3891 CydiaObject *cydia_;
3892}
a9a0661e 3893
43f3d7f6
JF
3894@end
3895
b5e7eebb 3896@implementation CYBrowserController
43f3d7f6
JF
3897
3898- (void) dealloc {
3899 [cydia_ release];
3900 [super dealloc];
3901}
3902
01d93940
JF
3903- (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3904}
3905
43f3d7f6
JF
3906- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3907 [super webView:sender didClearWindowObject:window forFrame:frame];
01d93940
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
77801ff1
JF
3924 if (
3925 [host isEqualToString:@"cydia.saurik.com"] ||
3926 [host hasSuffix:@".cydia.saurik.com"] ||
3927 [scheme isEqualToString:@"file"]
3928 )
ef055c6c 3929 [window setValue:cydia_ forKey:@"cydia"];
43f3d7f6
JF
3930}
3931
bfc87a4d
JF
3932- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3933 if (System_ != NULL)
3934 [request setValue:System_ forHTTPHeaderField:@"X-System"];
43f3d7f6 3935 if (Machine_ != NULL)
bfc87a4d 3936 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
01d93940
JF
3937 if (Token_ != nil)
3938 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
43f3d7f6 3939 if (Role_ != nil)
bfc87a4d
JF
3940 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3941}
43f3d7f6 3942
bfc87a4d
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];
43f3d7f6 3946 return copy;
a9a0661e
JF
3947}
3948
77801ff1
JF
3949- (void) setDelegate:(id)delegate {
3950 [super setDelegate:delegate];
3951 [cydia_ setDelegate:delegate];
3952}
3953
b5e7eebb
GP
3954- (id) init {
3955 if ((self = [super initWithWidth:[[self view] bounds].size.width ofClass:[CYBrowserController class]]) != nil) {
43f3d7f6
JF
3956 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3957
aeed65a6 3958 WebView *webview([document_ webView]);
43f3d7f6
JF
3959
3960 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
35bf217f 3961
43f3d7f6
JF
3962 NSString *application = package == nil ? @"Cydia" : [NSString
3963 stringWithFormat:@"Cydia/%@",
3964 [package installed]
3965 ];
3966
43f3d7f6 3967 if (Safari_ != nil)
9ef18597 3968 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
35bf217f 3969 if (Build_ != nil)
9ef18597 3970 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
35bf217f 3971 if (Product_ != nil)
9ef18597 3972 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
43f3d7f6
JF
3973
3974 [webview setApplicationNameForUserAgent:application];
3975 } return self;
3976}
3977
3978@end
3979
36bb2ca2 3980@protocol ConfirmationViewDelegate
674dce72 3981- (void) cancelAndClear:(bool)clear;
b5e7eebb 3982- (void) confirmWithNavigationController:(UINavigationController *)navigation;
dc63e78f 3983- (void) queue;
36bb2ca2 3984@end
2367a917 3985
b5e7eebb 3986@interface ConfirmationView : CYBrowserController {
770f2a8e 3987 _transient Database *database_;
3272e699 3988 UIAlertView *essential_;
affeffc7
JF
3989 NSArray *changes_;
3990 NSArray *issues_;
3991 NSArray *sizes_;
a9a0661e 3992 BOOL substrate_;
36bb2ca2 3993}
dc5812ec 3994
b5e7eebb 3995- (id) initWithDatabase:(Database *)database;
b4d89997 3996
dc5812ec
JF
3997@end
3998
36bb2ca2 3999@implementation ConfirmationView
dc5812ec 4000
2367a917 4001- (void) dealloc {
affeffc7
JF
4002 [changes_ release];
4003 if (issues_ != nil)
4004 [issues_ release];
4005 [sizes_ release];
36bb2ca2
JF
4006 if (essential_ != nil)
4007 [essential_ release];
2367a917
JF
4008 [super dealloc];
4009}
4010
674dce72
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;
b5e7eebb 4020
674dce72 4021 [sheet dismissWithClickedButtonIndex:0xDEADBEEF animated:YES];
b5e7eebb 4022 [self dismissModalViewControllerAnimated:YES];
674dce72
GP
4023 [delegate_ cancelAndClear:clear];
4024 }
4025}
4026
b5e7eebb 4027- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3272e699 4028 NSString *context([alert context]);
9bedffaa 4029
1cedb821 4030 if ([context isEqualToString:@"remove"]) {
b5e7eebb
GP
4031 if (button == [alert cancelButtonIndex]) {
4032 [self dismissModalViewControllerAnimated:YES];
3272e699 4033 } else if (button == [alert firstOtherButtonIndex]) {
b5e7eebb
GP
4034 if (substrate_)
4035 Finish_ = 2;
4036 [delegate_ confirmWithNavigationController:[self navigationController]];
9bedffaa 4037 }
9bedffaa 4038
3272e699 4039 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 4040 } else if ([context isEqualToString:@"unable"]) {
b5e7eebb 4041 [self dismissModalViewControllerAnimated:YES];
3272e699
GP
4042 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4043 } else {
b5e7eebb
GP
4044 [super alertView:alert clickedButtonAtIndex:button];
4045 }
36bb2ca2
JF
4046}
4047
affeffc7 4048- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
f79a4512 4049 [super webView:sender didClearWindowObject:window forFrame:frame];
affeffc7
JF
4050 [window setValue:changes_ forKey:@"changes"];
4051 [window setValue:issues_ forKey:@"issues"];
4052 [window setValue:sizes_ forKey:@"sizes"];
36bb2ca2
JF
4053}
4054
b5e7eebb
GP
4055- (id) initWithDatabase:(Database *)database {
4056 if ((self = [super init]) != nil) {
770f2a8e
JF
4057 database_ = database;
4058
b5e7eebb
GP
4059 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4060
36bb2ca2
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];
dc5812ec 4066
36bb2ca2 4067 bool remove(false);
dc5812ec 4068
a9a0661e
JF
4069 pkgDepCache::Policy *policy([database_ policy]);
4070
36bb2ca2 4071 pkgCacheFile &cache([database_ cache]);
2388b078 4072 NSArray *packages = [database_ packages];
c4dcf2c2 4073 for (Package *package in packages) {
2388b078 4074 pkgCache::PkgIterator iterator = [package iterator];
36bb2ca2 4075 pkgDepCache::StateCache &state(cache[iterator]);
dc5812ec 4076
2388b078
JF
4077 NSString *name([package name]);
4078
36bb2ca2
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()) {
2388b078 4088 if ([package essential])
36bb2ca2
JF
4089 remove = true;
4090 [removing addObject:name];
a9a0661e
JF
4091 } else continue;
4092
4093 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4094 substrate_ |= DepSubstrate(iterator.CurrentVer());
36bb2ca2 4095 }
ec97ef06 4096
36bb2ca2
JF
4097 if (!remove)
4098 essential_ = nil;
d791dce4 4099 else if (Advanced_) {
43f3d7f6 4100 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
f79a4512 4101
3272e699 4102 essential_ = [[UIAlertView alloc]
43f3d7f6 4103 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
b5e7eebb
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 ];
04fe1349 4109
3272e699 4110 [essential_ setContext:@"remove"];
9bedffaa 4111 } else {
3272e699 4112 essential_ = [[UIAlertView alloc]
43f3d7f6 4113 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
b5e7eebb
GP
4114 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4115 delegate:self
4116 cancelButtonTitle:UCLocalize("OKAY")
4117 otherButtonTitles:nil
36bb2ca2 4118 ];
ec97ef06 4119
b5e7eebb 4120 [essential_ setContext:@"unable"];
36bb2ca2 4121 }
ec97ef06 4122
affeffc7
JF
4123 changes_ = [[NSArray alloc] initWithObjects:
4124 installing,
4125 reinstalling,
4126 upgrading,
4127 downgrading,
4128 removing,
4129 nil];
dc5812ec 4130
affeffc7
JF
4131 issues_ = [database_ issues];
4132 if (issues_ != nil)
4133 issues_ = [issues_ retain];
dc5812ec 4134
affeffc7
JF
4135 sizes_ = [[NSArray alloc] initWithObjects:
4136 SizeString([database_ fetcher].FetchNeeded()),
4137 SizeString([database_ fetcher].PartialPresent()),
affeffc7 4138 nil];
dc5812ec 4139
affeffc7 4140 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
04fe1349 4141
b5e7eebb
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];
36bb2ca2 4150 } return self;
b4d89997 4151}
8da60fb7 4152
b5e7eebb
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];
affeffc7
JF
4165}
4166
b5e7eebb
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 ];
bd0a4099 4175
b5e7eebb
GP
4176 [sheet addButtonWithTitle:UCLocalize("CANCEL_CLEAR")];
4177 [sheet setDestructiveButtonIndex:[sheet numberOfButtons] - 1];
4178 [sheet addButtonWithTitle:UCLocalize("CONTINUE_QUEUING")];
4179 [sheet setContext:@"cancel"];
affeffc7 4180
b5e7eebb 4181 [delegate_ showActionSheet:[sheet autorelease] fromItem:[[self navigationItem] leftBarButtonItem]];
affeffc7
JF
4182}
4183
9487f027 4184#if !AlwaysReload
b5e7eebb 4185- (void) confirmButtonClicked {
b0ad8dee 4186#if IgnoreInstall
b5e7eebb 4187 return;
b0ad8dee 4188#endif
affeffc7 4189 if (essential_ != nil)
b5e7eebb 4190 [essential_ show];
affeffc7
JF
4191 else {
4192 if (substrate_)
4193 Finish_ = 2;
b5e7eebb 4194 [delegate_ confirmWithNavigationController:[self navigationController]];
affeffc7
JF
4195 }
4196}
9487f027 4197#endif
affeffc7 4198
36bb2ca2
JF
4199@end
4200/* }}} */
8da60fb7 4201
36bb2ca2
JF
4202/* Progress Data {{{ */
4203@interface ProgressData : NSObject {
4204 SEL selector_;
4205 id target_;
4206 id object_;
dc5812ec
JF
4207}
4208
36bb2ca2 4209- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
b4d89997 4210
36bb2ca2
JF
4211- (SEL) selector;
4212- (id) target;
4213- (id) object;
4214@end
b4d89997 4215
36bb2ca2 4216@implementation ProgressData
b4d89997 4217
36bb2ca2
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}
b4d89997 4225
36bb2ca2
JF
4226- (SEL) selector {
4227 return selector_;
4228}
b4d89997 4229
36bb2ca2
JF
4230- (id) target {
4231 return target_;
8da60fb7
JF
4232}
4233
36bb2ca2
JF
4234- (id) object {
4235 return object_;
dc5812ec
JF
4236}
4237
2367a917
JF
4238@end
4239/* }}} */
36bb2ca2 4240/* Progress View {{{ */
b5e7eebb 4241@interface ProgressView : CYViewController <
8b29f8e6 4242 ConfigurationDelegate,
36bb2ca2
JF
4243 ProgressDelegate
4244> {
8b29f8e6 4245 _transient Database *database_;
36bb2ca2
JF
4246 UIProgressBar *progress_;
4247 UITextView *output_;
4248 UITextLabel *status_;
31f3cfff 4249 UIPushButton *close_;
bd150f54 4250 BOOL running_;
dddbc481 4251 SHA1SumValue springlist_;
22f8bed9 4252 SHA1SumValue notifyconf_;
670a0494 4253 NSString *title_;
2367a917
JF
4254}
4255
b5e7eebb 4256- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
2367a917 4257
36bb2ca2
JF
4258- (void) _retachThread;
4259- (void) _detachNewThreadData:(ProgressData *)data;
4260- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
2367a917 4261
bd150f54
JF
4262- (BOOL) isRunning;
4263
2367a917
JF
4264@end
4265
36bb2ca2
JF
4266@protocol ProgressViewDelegate
4267- (void) progressViewIsComplete:(ProgressView *)sender;
4268@end
4269
4270@implementation ProgressView
2367a917
JF
4271
4272- (void) dealloc {
b5e7eebb 4273 [database_ setDelegate:nil];
36bb2ca2
JF
4274 [progress_ release];
4275 [output_ release];
4276 [status_ release];
31f3cfff 4277 [close_ release];
670a0494
JF
4278 if (title_ != nil)
4279 [title_ release];
2367a917
JF
4280 [super dealloc];
4281}
4282
b5e7eebb
GP
4283- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4284 if ((self = [super init]) != nil) {
8b29f8e6 4285 database_ = database;
b5e7eebb 4286 [database_ setDelegate:self];
36bb2ca2 4287 delegate_ = delegate;
ec97ef06 4288
b5e7eebb 4289 [[self view] setBackgroundColor:(CGColor *)[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
2367a917 4290
b5e7eebb 4291 progress_ = [[UIProgressBar alloc] init];
04fe1349 4292 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
31f3cfff 4293 [progress_ setStyle:0];
ec97ef06 4294
b5e7eebb 4295 status_ = [[UITextLabel alloc] init];
04fe1349 4296 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
baf80942
JF
4297 [status_ setColor:[UIColor whiteColor]];
4298 [status_ setBackgroundColor:[UIColor clearColor]];
36bb2ca2
JF
4299 [status_ setCentersHorizontally:YES];
4300 //[status_ setFont:font];
ec97ef06 4301
b5e7eebb 4302 output_ = [[UITextView alloc] init];
1d80f6b9 4303
04fe1349 4304 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
36bb2ca2 4305 //[output_ setTextFont:@"Courier New"];
d791dce4 4306 [output_ setFont:[[output_ font] fontWithSize:12]];
baf80942
JF
4307 [output_ setTextColor:[UIColor whiteColor]];
4308 [output_ setBackgroundColor:[UIColor clearColor]];
36bb2ca2
JF
4309 [output_ setMarginTop:0];
4310 [output_ setAllowsRubberBanding:YES];
795d26fc 4311 [output_ setEditable:NO];
b5e7eebb 4312 [[self view] addSubview:output_];
b4d89997 4313
b5e7eebb 4314 close_ = [[UIPushButton alloc] init];
04fe1349 4315 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
31f3cfff
JF
4316 [close_ setAutosizesToFit:NO];
4317 [close_ setDrawsShadow:YES];
4318 [close_ setStretchBackground:YES];
31f3cfff 4319 [close_ setEnabled:YES];
b5e7eebb 4320 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
bfc87a4d 4321 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
31f3cfff
JF
4322 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4323 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
36bb2ca2 4324 } return self;
2367a917
JF
4325}
4326
b5e7eebb
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];
2367a917
JF
4366}
4367
b5e7eebb
GP
4368- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4369 [self positionViews];
2367a917
JF
4370}
4371
b5e7eebb 4372- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
969eaf2f 4373 NSString *context([alert context]);
bc8cd583 4374
670a0494 4375 if ([context isEqualToString:@"conffile"]) {
b5e7eebb 4376 FILE *input = [database_ input];
969eaf2f
GP
4377 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4378 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
b5e7eebb 4379 fflush(input);
670a0494
JF
4380 }
4381}
4382
4383- (void) closeButtonPushed {
4384 running_ = NO;
4385
4386 switch (Finish_) {
4387 case 0:
b5e7eebb 4388 [self dismissModalViewControllerAnimated:YES];
670a0494
JF
4389 break;
4390
4391 case 1:
c4899376
JF
4392 [delegate_ terminateWithSuccess];
4393 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4394 [delegate_ suspendWithAnimation:YES];
4395 else
4396 [delegate_ suspend];*/
670a0494
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;
bc8cd583 4410 }
670a0494 4411}
bd150f54 4412
670a0494 4413- (void) _retachThread {
b5e7eebb 4414 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
670a0494 4415
b5e7eebb 4416 [[self view] addSubview:close_];
670a0494
JF
4417 [progress_ removeFromSuperview];
4418 [status_ removeFromSuperview];
4419
4420 [database_ popErrorWithTitle:title_];
c390d3ab
JF
4421 [delegate_ progressViewIsComplete:self];
4422
22f8bed9 4423 if (Finish_ < 4) {
70d45c1e
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 }
22f8bed9
JF
4434 }
4435
affeffc7 4436 if (Finish_ < 3) {
70d45c1e
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 }
dddbc481
JF
4447 }
4448
bc8cd583 4449 switch (Finish_) {
b5e7eebb 4450 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
43f3d7f6
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;
bc8cd583
JF
4455 }
4456
58241d4c 4457 system("su -c /usr/bin/uicache mobile");
c4ce98df 4458
bd150f54 4459 [delegate_ setStatusBarShowsProgress:NO];
31f3cfff
JF
4460}
4461
affeffc7 4462- (void) _detachNewThreadData:(ProgressData *)data { _pooled
36bb2ca2
JF
4463 [[data target] performSelector:[data selector] withObject:[data object]];
4464 [data release];
b19871dd 4465
36bb2ca2 4466 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
b19871dd
JF
4467}
4468
36bb2ca2 4469- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
670a0494
JF
4470 if (title_ != nil)
4471 [title_ release];
4472 if (title == nil)
4473 title_ = nil;
4474 else
4475 title_ = [title retain];
4476
b5e7eebb 4477 [[self navigationItem] setTitle:title_];
b4d89997 4478
36bb2ca2
JF
4479 [status_ setText:nil];
4480 [output_ setText:@""];
4481 [progress_ setProgress:0];
b19871dd 4482
31f3cfff 4483 [close_ removeFromSuperview];
b5e7eebb
GP
4484 [[self view] addSubview:progress_];
4485 [[self view] addSubview:status_];
31f3cfff 4486
bd150f54
JF
4487 [delegate_ setStatusBarShowsProgress:YES];
4488 running_ = YES;
4489
22f8bed9 4490 {
70d45c1e
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 }
22f8bed9
JF
4500 }
4501
affeffc7 4502 {
70d45c1e
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 }
dddbc481
JF
4512 }
4513
36bb2ca2
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 ];
b19871dd
JF
4523}
4524
5a09ae08
JF
4525- (void) repairWithSelector:(SEL)selector {
4526 [self
4527 detachNewThreadSelector:selector
4528 toTarget:database_
4529 withObject:nil
43f3d7f6 4530 title:UCLocalize("REPAIRING")
5a09ae08
JF
4531 ];
4532}
4533
8b29f8e6
JF
4534- (void) setConfigurationData:(NSString *)data {
4535 [self
4536 performSelectorOnMainThread:@selector(_setConfigurationData:)
4537 withObject:data
4538 waitUntilDone:YES
4539 ];
4540}
4541
670a0494
JF
4542- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4543 CYActionSheet *sheet([[[CYActionSheet alloc]
4544 initWithTitle:title
43f3d7f6 4545 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
31f3cfff 4546 defaultButtonIndex:0
670a0494 4547 ] autorelease]);
31f3cfff 4548
be2b3d7b 4549 [sheet setMessage:error];
670a0494
JF
4550 [sheet yieldToPopupAlertAnimated:YES];
4551 [sheet dismiss];
b19871dd
JF
4552}
4553
36bb2ca2
JF
4554- (void) setProgressTitle:(NSString *)title {
4555 [self
4556 performSelectorOnMainThread:@selector(_setProgressTitle:)
4557 withObject:title
4558 waitUntilDone:YES
4559 ];
b19871dd
JF
4560}
4561
36bb2ca2
JF
4562- (void) setProgressPercent:(float)percent {
4563 [self
4564 performSelectorOnMainThread:@selector(_setProgressPercent:)
4565 withObject:[NSNumber numberWithFloat:percent]
4566 waitUntilDone:YES
4567 ];
b19871dd
JF
4568}
4569
baf80942 4570- (void) startProgress {
baf80942
JF
4571}
4572
36bb2ca2
JF
4573- (void) addProgressOutput:(NSString *)output {
4574 [self
4575 performSelectorOnMainThread:@selector(_addProgressOutput:)
4576 withObject:output
4577 waitUntilDone:YES
4578 ];
b19871dd
JF
4579}
4580
baf80942 4581- (bool) isCancelling:(size_t)received {
baf80942
JF
4582 return false;
4583}
4584
8b29f8e6 4585- (void) _setConfigurationData:(NSString *)data {
7b0ce2da
JF
4586 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4587
670a0494
JF
4588 if (!conffile_r(data)) {
4589 lprintf("E:invalid conffile\n");
4590 return;
4591 }
8b29f8e6
JF
4592
4593 NSString *ofile = conffile_r[1];
4594 //NSString *nfile = conffile_r[2];
4595
969eaf2f 4596 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 4597 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
b5e7eebb
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"),
969eaf2f 4602 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
b5e7eebb
GP
4603 nil
4604 ] autorelease];
969eaf2f 4605
b5e7eebb 4606 [alert setContext:@"conffile"];
969eaf2f 4607 [alert show];
8b29f8e6
JF
4608}
4609
36bb2ca2 4610- (void) _setProgressTitle:(NSString *)title {
9487f027
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:@" "]];
b4d89997 4619}
b19871dd 4620
36bb2ca2
JF
4621- (void) _setProgressPercent:(NSNumber *)percent {
4622 [progress_ setProgress:[percent floatValue]];
49048579
JF
4623}
4624
36bb2ca2
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}
dc088e63 4631
bd150f54 4632- (BOOL) isRunning {
c4ce98df 4633 return running_;
bd150f54
JF
4634}
4635
36bb2ca2
JF
4636@end
4637/* }}} */
dc088e63 4638
46aa9775 4639/* Cell Content View {{{ */
327624b6
JF
4640@interface ContentView : UIView {
4641 _transient id delegate_;
4642}
4643
4644@end
4645
46aa9775
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 {{{ */
327624b6 4665@interface PackageCell : UITableViewCell {
f641a0e5
JF
4666 UIImage *icon_;
4667 NSString *name_;
4668 NSString *description_;
3bd1c2a2 4669 bool commercial_;
f641a0e5 4670 NSString *source_;
c390d3ab 4671 UIImage *badge_;
dc63e78f 4672 Package *package_;
327624b6
JF
4673 UIColor *color_;
4674 ContentView *content_;
4675 BOOL faded_;
4676 float fade_;
670a0494 4677 UIImage *placard_;
36bb2ca2 4678}
723a0072 4679
36bb2ca2
JF
4680- (PackageCell *) init;
4681- (void) setPackage:(Package *)package;
ec97ef06 4682
9bedffaa 4683+ (int) heightForPackage:(Package *)package;
327624b6
JF
4684- (void) drawContentRect:(CGRect)rect;
4685
4686@end
4687
36bb2ca2
JF
4688@implementation PackageCell
4689
f641a0e5
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 }
c390d3ab
JF
4710
4711 if (badge_ != nil) {
4712 [badge_ release];
4713 badge_ = nil;
4714 }
dc63e78f 4715
670a0494
JF
4716 if (placard_ != nil) {
4717 [placard_ release];
4718 placard_ = nil;
4719 }
4720
dc63e78f
JF
4721 [package_ release];
4722 package_ = nil;
f641a0e5
JF
4723}
4724
36bb2ca2 4725- (void) dealloc {
f641a0e5 4726 [self clearPackage];
327624b6
JF
4727 [content_ release];
4728 [color_ release];
36bb2ca2 4729 [super dealloc];
b4d89997 4730}
b19871dd 4731
327624b6
JF
4732- (float) fade {
4733 return faded_ ? [self selectionPercent] : fade_;
4734}
4735
36bb2ca2 4736- (PackageCell *) init {
327624b6
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]);
04fe1349 4741
327624b6 4742 content_ = [[ContentView alloc] initWithFrame:bounds];
04fe1349
JF
4743 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4744 [content addSubview:content_];
4745
327624b6 4746 [content_ setDelegate:self];
327624b6 4747 [content_ setOpaque:YES];
327624b6
JF
4748 if ([self respondsToSelector:@selector(selectionPercent)])
4749 faded_ = YES;
36bb2ca2 4750 } return self;
b4d89997 4751}
b19871dd 4752
327624b6
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
36bb2ca2 4765- (void) setPackage:(Package *)package {
46dbfd32 4766 [self clearPackage];
68d927e2 4767 [package parse];
31f3cfff 4768
36bb2ca2 4769 Source *source = [package source];
b19871dd 4770
770f2a8e 4771 icon_ = [[package icon] retain];
f641a0e5 4772 name_ = [[package name] retain];
ef055c6c
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
3bd1c2a2 4781 commercial_ = [package isCommercial];
36bb2ca2 4782
dc63e78f
JF
4783 package_ = [package retain];
4784
a54b1c10
JF
4785 NSString *label = nil;
4786 bool trusted = false;
b19871dd 4787
36bb2ca2
JF
4788 if (source != nil) {
4789 label = [source label];
4790 trusted = [source trusted];
a54b1c10 4791 } else if ([[package id] isEqualToString:@"firmware"])
43f3d7f6 4792 label = UCLocalize("APPLE");
7b0ce2da 4793 else
43f3d7f6 4794 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
b19871dd 4795
f79a4512 4796 NSString *from(label);
a54b1c10 4797
f79a4512
JF
4798 NSString *section = [package simpleSection];
4799 if (section != nil && ![section isEqualToString:label]) {
4800 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
43f3d7f6 4801 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
f79a4512 4802 }
a54b1c10 4803
43f3d7f6 4804 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
f641a0e5 4805 source_ = [from retain];
36bb2ca2 4806
c390d3ab
JF
4807 if (NSString *purpose = [package primaryPurpose])
4808 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4809 badge_ = [badge_ retain];
4810
670a0494
JF
4811 if ([package installed] != nil)
4812 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4813 placard_ = [placard_ retain];
4814
327624b6
JF
4815 [self _setBackgroundColor];
4816 [content_ setNeedsDisplay];
3bd1c2a2
JF
4817}
4818
327624b6
JF
4819- (void) drawContentRect:(CGRect)rect {
4820 bool selected([self isSelected]);
ef055c6c 4821 float width([self bounds].size.width);
dc63e78f 4822
327624b6
JF
4823#if 0
4824 CGContextRef context(UIGraphicsGetCurrentContext());
4825 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4826 CGContextFillRect(context, rect);
4827#endif
b19871dd 4828
baf80942
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 }
b19871dd 4841
c390d3ab
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
f641a0e5
JF
4851 if (selected)
4852 UISetColor(White_);
b19871dd 4853
f641a0e5 4854 if (!selected)
3bd1c2a2 4855 UISetColor(commercial_ ? Purple_ : Black_);
01d93940
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];
b19871dd 4858
f641a0e5 4859 if (!selected)
3bd1c2a2 4860 UISetColor(commercial_ ? Purplish_ : Gray_);
01d93940 4861 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
670a0494
JF
4862
4863 if (placard_ != nil)
01d93940 4864 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
ec97ef06
JF
4865}
4866
327624b6
JF
4867- (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4868 //[self _setBackgroundColor];
4869 [super setSelected:selected animated:fade];
4870 [content_ setNeedsDisplay];
dc63e78f
JF
4871}
4872
9bedffaa 4873+ (int) heightForPackage:(Package *)package {
68d927e2 4874 return 73;
9bedffaa
JF
4875}
4876
8da60fb7
JF
4877@end
4878/* }}} */
36bb2ca2 4879/* Section Cell {{{ */
46aa9775 4880@interface SectionCell : UITableViewCell {
0010fa77 4881 NSString *basic_;
6d9712c4 4882 NSString *section_;
f641a0e5
JF
4883 NSString *name_;
4884 NSString *count_;
4885 UIImage *icon_;
46aa9775
GP
4886 ContentView *content_;
4887 id switch_;
6d9712c4 4888 BOOL editing_;
b4d89997 4889}
b19871dd 4890
36bb2ca2 4891- (id) init;
6d9712c4 4892- (void) setSection:(Section *)section editing:(BOOL)editing;
36bb2ca2 4893
8da60fb7
JF
4894@end
4895
36bb2ca2 4896@implementation SectionCell
8da60fb7 4897
f641a0e5 4898- (void) clearSection {
0010fa77 4899 if (basic_ != nil) {
e59669fd 4900 [basic_ release];
0010fa77
JF
4901 basic_ = nil;
4902 }
4903
f641a0e5 4904 if (section_ != nil) {
6d9712c4 4905 [section_ release];
f641a0e5
JF
4906 section_ = nil;
4907 }
7b0ce2da 4908
f641a0e5
JF
4909 if (name_ != nil) {
4910 [name_ release];
4911 name_ = nil;
4912 }
7b0ce2da 4913
f641a0e5
JF
4914 if (count_ != nil) {
4915 [count_ release];
4916 count_ = nil;
4917 }
7b0ce2da
JF
4918}
4919
f641a0e5
JF
4920- (void) dealloc {
4921 [self clearSection];
4922 [icon_ release];
4923 [switch_ release];
46aa9775
GP
4924 [content_ release];
4925
f641a0e5 4926 [super dealloc];
7b0ce2da
JF
4927}
4928
46aa9775
GP
4929- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4930 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
f641a0e5 4931 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
46aa9775
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];
b4d89997 4944 } return self;
b19871dd
JF
4945}
4946
6d9712c4 4947- (void) onSwitch:(id)sender {
0010fa77 4948 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
6d9712c4
JF
4949 if (metadata == nil) {
4950 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
0010fa77 4951 [Sections_ setObject:metadata forKey:basic_];
6d9712c4
JF
4952 }
4953
4954 Changed_ = true;
46aa9775 4955 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6d9712c4
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
f641a0e5 4967 [self clearSection];
6d9712c4 4968
36bb2ca2 4969 if (section == nil) {
43f3d7f6 4970 name_ = [UCLocalize("ALL_PACKAGES") retain];
f641a0e5 4971 count_ = nil;
36bb2ca2 4972 } else {
e59669fd 4973 basic_ = [section name];
0010fa77
JF
4974 if (basic_ != nil)
4975 basic_ = [basic_ retain];
4976
677b8415 4977 section_ = [section localized];
6d9712c4
JF
4978 if (section_ != nil)
4979 section_ = [section_ retain];
0010fa77 4980
43f3d7f6 4981 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
f641a0e5 4982 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
6d9712c4
JF
4983
4984 if (editing_)
46aa9775 4985 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
36bb2ca2 4986 }
46aa9775 4987
86c5b8f5 4988 [self setAccessoryType:editing ? 0 : 1 /*UITableViewCellAccessoryDisclosureIndicator*/];
46aa9775 4989 [content_ setNeedsDisplay];
f641a0e5
JF
4990}
4991
77801ff1
JF
4992- (void) setFrame:(CGRect)frame {
4993 [super setFrame:frame];
46aa9775 4994
77801ff1
JF
4995 CGRect rect([switch_ frame]);
4996 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4997}
4998
46aa9775
GP
4999- (void) drawContentRect:(CGRect)rect {
5000 BOOL selected = [self isSelected];
5001
f641a0e5
JF
5002 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5003
5004 if (selected)
5005 UISetColor(White_);
5006
5007 if (!selected)
5008 UISetColor(Black_);
58241d4c 5009
46aa9775 5010 float width(rect.size.width);
58241d4c 5011 if (editing_)
46aa9775 5012 width -= 87;
58241d4c 5013
01d93940 5014 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
6d9712c4 5015
f641a0e5
JF
5016 CGSize size = [count_ sizeWithFont:Font14_];
5017
5018 UISetColor(White_);
5019 if (count_ != nil)
c390d3ab 5020 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
b19871dd
JF
5021}
5022
36bb2ca2
JF
5023@end
5024/* }}} */
b19871dd 5025
ab398adf 5026/* File Table {{{ */
b5e7eebb 5027@interface FileTable : CYViewController {
36bb2ca2 5028 _transient Database *database_;
ab398adf
JF
5029 Package *package_;
5030 NSString *name_;
5031 NSMutableArray *files_;
46aa9775 5032 UITableView *list_;
ab398adf 5033}
b19871dd 5034
b5e7eebb 5035- (id) initWithDatabase:(Database *)database;
ab398adf
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
46aa9775 5052- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
ab398adf
JF
5053 return files_ == nil ? 0 : [files_ count];
5054}
5055
46aa9775 5056- (float) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
ab398adf
JF
5057 return 24;
5058}
5059
46aa9775 5060- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
GP
5061 static NSString *reuseIdentifier = @"Cell";
5062
46aa9775
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]];
ab398adf 5067 }
46aa9775
GP
5068 [cell setText:[files_ objectAtIndex:indexPath.row]];
5069 [cell setSelectionStyle:0 /*UITableViewCellSelectionStyleNone*/];
b5e7eebb 5070
46aa9775 5071 return cell;
ab398adf 5072}
b19871dd 5073
b5e7eebb
GP
5074- (id) initWithDatabase:(Database *)database {
5075 if ((self = [super init]) != nil) {
ab398adf 5076 database_ = database;
b19871dd 5077
b5e7eebb
GP
5078 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5079
ab398adf 5080 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
8da60fb7 5081
46aa9775 5082 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
b5e7eebb 5083 [[self view] addSubview:list_];
ab398adf 5084
ab398adf 5085 [list_ setDataSource:self];
ab398adf 5086 [list_ setDelegate:self];
ab398adf
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
affeffc7
JF
5107 if (NSArray *files = [package files])
5108 [files_ addObjectsFromArray:files];
ab398adf 5109
9ea8d159
JF
5110 if ([files_ count] != 0) {
5111 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5112 [files_ removeObjectAtIndex:0];
a54b1c10 5113 [files_ sortUsingSelector:@selector(compareByPath:)];
2388b078
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%@",
a54b1c10 5125 ([stack count] - 2) * 3, "",
2388b078
JF
5126 [file substringFromIndex:[directory length]]
5127 ]];
5128 }
ab398adf
JF
5129 }
5130 }
5131
5132 [list_ reloadData];
5133}
5134
ab398adf
JF
5135- (void) reloadData {
5136 [self setPackage:[database_ packageWithName:name_]];
ab398adf 5137}
b4d89997 5138
b4d89997 5139@end
36bb2ca2 5140/* }}} */
36bb2ca2 5141/* Package View {{{ */
b5e7eebb 5142@interface PackageView : CYBrowserController {
770f2a8e 5143 _transient Database *database_;
36bb2ca2
JF
5144 Package *package_;
5145 NSString *name_;
3bd1c2a2 5146 bool commercial_;
5a09ae08 5147 NSMutableArray *buttons_;
b31b87cc
JF
5148}
5149
b5e7eebb 5150- (id) initWithDatabase:(Database *)database;
36bb2ca2 5151- (void) setPackage:(Package *)package;
b4d89997 5152
36bb2ca2 5153@end
b4d89997 5154
36bb2ca2 5155@implementation PackageView
b4d89997 5156
36bb2ca2 5157- (void) dealloc {
36bb2ca2
JF
5158 if (package_ != nil)
5159 [package_ release];
5160 if (name_ != nil)
5161 [name_ release];
5a09ae08 5162 [buttons_ release];
36bb2ca2
JF
5163 [super dealloc];
5164}
8da60fb7 5165
92d4a16a 5166- (void) release {
f79a4512
JF
5167 if ([self retainCount] == 1)
5168 [delegate_ setPackageView:self];
5169 [super release];
92d4a16a 5170}
f79a4512
JF
5171
5172/* XXX: this is not safe at all... localization of /fail/ */
5a09ae08 5173- (void) _clickButtonWithName:(NSString *)name {
43f3d7f6 5174 if ([name isEqualToString:UCLocalize("CLEAR")])
dc63e78f 5175 [delegate_ clearPackage:package_];
43f3d7f6 5176 else if ([name isEqualToString:UCLocalize("INSTALL")])
5a09ae08 5177 [delegate_ installPackage:package_];
43f3d7f6 5178 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5a09ae08 5179 [delegate_ installPackage:package_];
43f3d7f6 5180 else if ([name isEqualToString:UCLocalize("REMOVE")])
5a09ae08 5181 [delegate_ removePackage:package_];
43f3d7f6 5182 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5a09ae08
JF
5183 [delegate_ installPackage:package_];
5184 else _assert(false);
5185}
5186
674dce72 5187- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
1cedb821 5188 NSString *context([sheet context]);
5a09ae08 5189
1cedb821 5190 if ([context isEqualToString:@"modify"]) {
674dce72
GP
5191 if (button != [sheet cancelButtonIndex]) {
5192 NSString *buttonName = [buttons_ objectAtIndex:button];
5193 [self _clickButtonWithName:buttonName];
5194 }
b5e7eebb 5195
674dce72
GP
5196 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5197 } else {
5198 [super alertSheet:sheet clickedButtonAtIndex:button];
5199 }
b4d89997 5200}
2367a917 5201
7d2ac47f 5202- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
7d2ac47f
JF
5203 return [super webView:sender didFinishLoadForFrame:frame];
5204}
5205
6f1a15d9 5206- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
c390d3ab 5207 [super webView:sender didClearWindowObject:window forFrame:frame];
f79a4512 5208 [window setValue:package_ forKey:@"package"];
6f1a15d9
JF
5209}
5210
3e9c9e85 5211- (bool) _allowJavaScriptPanel {
3bd1c2a2 5212 return commercial_;
3e9c9e85
JF
5213}
5214
9487f027 5215#if !AlwaysReload
b5e7eebb 5216- (void) _actionButtonClicked {
670a0494
JF
5217 int count([buttons_ count]);
5218 if (count == 0)
5219 return;
2367a917 5220
5a09ae08
JF
5221 if (count == 1)
5222 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5223 else {
674dce72 5224 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5a09ae08 5225 [buttons addObjectsFromArray:buttons_];
36bb2ca2 5226
674dce72 5227 UIActionSheet *sheet = [[[UIActionSheet alloc]
9ea8d159 5228 initWithTitle:nil
36bb2ca2 5229 delegate:self
674dce72
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"];
b5e7eebb
GP
5241
5242 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
36bb2ca2 5243 }
b4d89997 5244}
12b59862 5245
b5e7eebb
GP
5246- (void) actionButtonClicked {
5247 if (commercial_ && [self isLoading])
12b59862
JF
5248 [super _rightButtonClicked];
5249 else
b5e7eebb 5250 [self _actionButtonClicked];
12b59862 5251}
9487f027 5252#endif
2367a917 5253
b5e7eebb
GP
5254- (id) initWithDatabase:(Database *)database {
5255 if ((self = [super init]) != nil) {
36bb2ca2 5256 database_ = database;
5a09ae08 5257 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
f79a4512 5258 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
36bb2ca2 5259 } return self;
dc5812ec
JF
5260}
5261
36bb2ca2
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
5a09ae08
JF
5273 [buttons_ removeAllObjects];
5274
36bb2ca2 5275 if (package != nil) {
68d927e2
JF
5276 [package parse];
5277
36bb2ca2
JF
5278 package_ = [package retain];
5279 name_ = [[package id] retain];
3bd1c2a2 5280 commercial_ = [package isCommercial];
36bb2ca2 5281
dc63e78f 5282 if ([package_ mode] != nil)
43f3d7f6 5283 [buttons_ addObject:UCLocalize("CLEAR")];
5a09ae08 5284 if ([package_ source] == nil);
31f3cfff 5285 else if ([package_ upgradableAndEssential:NO])
43f3d7f6 5286 [buttons_ addObject:UCLocalize("UPGRADE")];
6a155117 5287 else if ([package_ uninstalled])
43f3d7f6 5288 [buttons_ addObject:UCLocalize("INSTALL")];
5a09ae08 5289 else
43f3d7f6 5290 [buttons_ addObject:UCLocalize("REINSTALL")];
6a155117 5291 if (![package_ uninstalled])
43f3d7f6 5292 [buttons_ addObject:UCLocalize("REMOVE")];
f79a4512
JF
5293
5294 if (special_ != NULL) {
aeed65a6 5295 CGRect frame([document_ frame]);
f79a4512
JF
5296 frame.size.width = 320;
5297 frame.size.height = 0;
aeed65a6 5298 [document_ setFrame:frame];
f79a4512 5299
58241d4c
JF
5300 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5301 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5302 else
5303 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
f79a4512
JF
5304
5305 WebThreadLock();
aeed65a6 5306 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
f79a4512
JF
5307
5308 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5309
5310 [self setFinishHook:nil];
5311 [self setPopupHook:nil];
5312 WebThreadUnlock();
5313
b1ce61ec 5314 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
f79a4512
JF
5315 [super callFunction:special_];
5316 }
36bb2ca2 5317 }
b5e7eebb 5318}
f79a4512 5319
b5e7eebb
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];
dc5812ec
JF
5330}
5331
3bd1c2a2
JF
5332- (bool) isLoading {
5333 return commercial_ ? [super isLoading] : false;
9fe5e5f8
JF
5334}
5335
36bb2ca2
JF
5336- (void) reloadData {
5337 [self setPackage:[database_ packageWithName:name_]];
8fe19fc1
JF
5338}
5339
b4d89997
JF
5340@end
5341/* }}} */
b4d89997 5342/* Package Table {{{ */
b5e7eebb 5343@interface PackageTable : UIView {
36bb2ca2 5344 _transient Database *database_;
36bb2ca2 5345 NSMutableArray *packages_;
b4d89997 5346 NSMutableArray *sections_;
327624b6
JF
5347 UITableView *list_;
5348 NSMutableArray *index_;
5349 NSMutableDictionary *indices_;
b5e7eebb
GP
5350 id target_;
5351 SEL action_;
5352 id delegate_;
dc5812ec
JF
5353}
5354
b5e7eebb 5355- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
b4d89997
JF
5356
5357- (void) setDelegate:(id)delegate;
a0be02eb 5358
36bb2ca2 5359- (void) reloadData;
a0be02eb 5360- (void) resetCursor;
b4d89997 5361
327624b6 5362- (UITableView *) list;
2388b078 5363
ab398adf
JF
5364- (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5365
b5e7eebb
GP
5366- (void) deselectWithAnimation:(BOOL)animated;
5367
b4d89997
JF
5368@end
5369
5370@implementation PackageTable
5371
5372- (void) dealloc {
36bb2ca2 5373 [packages_ release];
b4d89997 5374 [sections_ release];
36bb2ca2 5375 [list_ release];
327624b6
JF
5376 [index_ release];
5377 [indices_ release];
b5e7eebb 5378
b4d89997 5379 [super dealloc];
8fe19fc1
JF
5380}
5381
327624b6
JF
5382- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5383 NSInteger count([sections_ count]);
5384 return count == 0 ? 1 : count;
b4d89997 5385}
2367a917 5386
327624b6
JF
5387- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5388 if ([sections_ count] == 0)
5389 return nil;
b4d89997
JF
5390 return [[sections_ objectAtIndex:section] name];
5391}
dc5812ec 5392
327624b6
JF
5393- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5394 if ([sections_ count] == 0)
5395 return 0;
5396 return [[sections_ objectAtIndex:section] count];
b4d89997 5397}
dc5812ec 5398
327624b6
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;
b4d89997 5404}
dc5812ec 5405
327624b6
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;
b4d89997 5412}
dc5812ec 5413
b5e7eebb
GP
5414- (void) deselectWithAnimation:(BOOL)animated {
5415 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5416}
5417
327624b6
JF
5418- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5419 return 73;
5420 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
b4d89997 5421}
dc5812ec 5422
327624b6
JF
5423- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5424 Package *package([self packageAtIndexPath:path]);
59c6ae22 5425 package = [database_ packageWithName:[package id]];
b5e7eebb 5426 [target_ performSelector:action_ withObject:package];
327624b6
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;
dc5812ec
JF
5436}
5437
b5e7eebb
GP
5438- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5439 if ((self = [super initWithFrame:frame]) != nil) {
36bb2ca2 5440 database_ = database;
b5e7eebb
GP
5441
5442 target_ = target;
5443 action_ = action;
36bb2ca2 5444
327624b6
JF
5445 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5446 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5447
36bb2ca2 5448 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
b4d89997 5449 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 5450
327624b6 5451 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
04fe1349
JF
5452 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5453 [self addSubview:list_];
5454
b4d89997 5455 [list_ setDataSource:self];
327624b6 5456 [list_ setDelegate:self];
b4d89997 5457 } return self;
dc5812ec
JF
5458}
5459
5460- (void) setDelegate:(id)delegate {
2367a917 5461 delegate_ = delegate;
b4d89997
JF
5462}
5463
a3328c28
JF
5464- (bool) hasPackage:(Package *)package {
5465 return true;
a0be02eb
JF
5466}
5467
36bb2ca2
JF
5468- (void) reloadData {
5469 NSArray *packages = [database_ packages];
b4d89997 5470
36bb2ca2 5471 [packages_ removeAllObjects];
b4d89997
JF
5472 [sections_ removeAllObjects];
5473
808c6eb6 5474 _profile(PackageTable$reloadData$Filter)
c4dcf2c2 5475 for (Package *package in packages)
808c6eb6
JF
5476 if ([self hasPackage:package])
5477 [packages_ addObject:package];
808c6eb6 5478 _end
36bb2ca2 5479
327624b6
JF
5480 [index_ removeAllObjects];
5481 [indices_ removeAllObjects];
5482
b4d89997
JF
5483 Section *section = nil;
5484
808c6eb6 5485 _profile(PackageTable$reloadData$Section)
c4dcf2c2
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
b4d89997 5494
808c6eb6
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
b4d89997 5499
327624b6
JF
5500 [index_ addObject:[section name]];
5501 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5502
c4dcf2c2
JF
5503 _profile(PackageTable$reloadData$Section$Add)
5504 [sections_ addObject:section];
5505 _end
808c6eb6
JF
5506 }
5507
5508 [section addToCount];
5509 }
5510 _end
b4d89997 5511
c4dcf2c2
JF
5512 _profile(PackageTable$reloadData$List)
5513 [list_ reloadData];
5514 _end
b4d89997
JF
5515}
5516
a0be02eb 5517- (void) resetCursor {
327624b6 5518 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
a0be02eb
JF
5519}
5520
327624b6 5521- (UITableView *) list {
2388b078
JF
5522 return list_;
5523}
5524
ab398adf 5525- (void) setShouldHideHeaderInShortLists:(BOOL)hide {
327624b6 5526 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
ab398adf
JF
5527}
5528
a3328c28
JF
5529@end
5530/* }}} */
5531/* Filtered Package Table {{{ */
5532@interface FilteredPackageTable : PackageTable {
5533 SEL filter_;
76933519 5534 IMP imp_;
a3328c28
JF
5535 id object_;
5536}
5537
5538- (void) setObject:(id)object;
01d93940 5539- (void) setObject:(id)object forFilter:(SEL)filter;
a3328c28 5540
b5e7eebb 5541- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
a3328c28
JF
5542
5543@end
5544
5545@implementation FilteredPackageTable
5546
5547- (void) dealloc {
5548 if (object_ != nil)
5549 [object_ release];
5550 [super dealloc];
5551}
5552
01d93940
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
a3328c28
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
01d93940
JF
5572- (void) setObject:(id)object forFilter:(SEL)filter {
5573 [self setFilter:filter];
5574 [self setObject:object];
01d93940
JF
5575}
5576
a3328c28 5577- (bool) hasPackage:(Package *)package {
76933519
JF
5578 _profile(FilteredPackageTable$hasPackage)
5579 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5580 _end
a3328c28
JF
5581}
5582
b5e7eebb
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) {
01d93940 5585 [self setFilter:filter];
b5e7eebb 5586 object_ = [object retain];
189a73d0 5587 [self reloadData];
a3328c28
JF
5588 } return self;
5589}
5590
dc5812ec 5591@end
b4d89997 5592/* }}} */
dc5812ec 5593
b5e7eebb
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
7b0ce2da 5661/* Add Source View {{{ */
b5e7eebb 5662@interface AddSourceView : CYViewController {
7b0ce2da 5663 _transient Database *database_;
dc5812ec
JF
5664}
5665
b5e7eebb 5666- (id) initWithDatabase:(Database *)database;
b4d89997 5667
7b0ce2da 5668@end
dc5812ec 5669
7b0ce2da 5670@implementation AddSourceView
dc5812ec 5671
b5e7eebb
GP
5672- (id) initWithDatabase:(Database *)database {
5673 if ((self = [super init]) != nil) {
7b0ce2da
JF
5674 database_ = database;
5675 } return self;
36bb2ca2 5676}
dc5812ec 5677
7b0ce2da
JF
5678@end
5679/* }}} */
5680/* Source Cell {{{ */
46aa9775 5681@interface SourceCell : UITableViewCell {
f641a0e5
JF
5682 UIImage *icon_;
5683 NSString *origin_;
5684 NSString *description_;
5685 NSString *label_;
46aa9775 5686 ContentView *content_;
b4d89997
JF
5687}
5688
46aa9775 5689- (void) setSource:(Source *)source;
b4d89997 5690
7b0ce2da 5691@end
b4d89997 5692
7b0ce2da 5693@implementation SourceCell
b4d89997 5694
46aa9775 5695- (void) clearSource {
f641a0e5 5696 [icon_ release];
7b0ce2da
JF
5697 [origin_ release];
5698 [description_ release];
5699 [label_ release];
46aa9775
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];
7b0ce2da 5726 [super dealloc];
36bb2ca2 5727}
b4d89997 5728
46aa9775
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];
7b0ce2da 5741 } return self;
a0376fc1
JF
5742}
5743
46aa9775
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]);
01d93940
JF
5751 float width(rect.size.width);
5752
f641a0e5
JF
5753 if (icon_ != nil)
5754 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7b0ce2da 5755
f641a0e5
JF
5756 if (selected)
5757 UISetColor(White_);
7b0ce2da 5758
f641a0e5
JF
5759 if (!selected)
5760 UISetColor(Black_);
01d93940 5761 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
7b0ce2da 5762
f641a0e5
JF
5763 if (!selected)
5764 UISetColor(Blue_);
01d93940 5765 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
7b0ce2da 5766
f641a0e5
JF
5767 if (!selected)
5768 UISetColor(Gray_);
01d93940 5769 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
7b0ce2da
JF
5770}
5771
5772@end
5773/* }}} */
5774/* Source Table {{{ */
b5e7eebb 5775@interface SourceTable : CYViewController {
7b0ce2da 5776 _transient Database *database_;
46aa9775 5777 UITableView *list_;
7b0ce2da 5778 NSMutableArray *sources_;
7b0ce2da
JF
5779 int offset_;
5780
5781 NSString *href_;
5782 UIProgressHUD *hud_;
5783 NSError *error_;
5784
5785 //NSURLConnection *installer_;
42543928 5786 NSURLConnection *trivial_;
7b0ce2da
JF
5787 NSURLConnection *trivial_bz2_;
5788 NSURLConnection *trivial_gz_;
5789 //NSURLConnection *automatic_;
5790
42543928 5791 BOOL cydia_;
7b0ce2da
JF
5792}
5793
b5e7eebb 5794- (id) initWithDatabase:(Database *)database;
7b0ce2da
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 {
7b0ce2da
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_];
42543928 5817 [self _deallocConnection:trivial_];
7b0ce2da
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
b5e7eebb
GP
5827- (void) viewDidAppear:(BOOL)animated {
5828 [super viewDidAppear:animated];
5829 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5830}
5831
46aa9775 5832- (int) numberOfSectionsInTableView:(UITableView *)tableView {
7b0ce2da
JF
5833 return offset_ == 0 ? 1 : 2;
5834}
5835
46aa9775 5836- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
7b0ce2da 5837 switch (section + (offset_ == 0 ? 1 : 0)) {
43f3d7f6
JF
5838 case 0: return UCLocalize("ENTERED_BY_USER");
5839 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7b0ce2da 5840
670a0494 5841 _nodefault
7b0ce2da
JF
5842 }
5843}
5844
46aa9775
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_;
7b0ce2da 5850
b5e7eebb 5851 _nodefault
7b0ce2da
JF
5852 }
5853}
5854
46aa9775
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
b5e7eebb 5861 _nodefault
46aa9775
GP
5862 }
5863 return [sources_ objectAtIndex:idx];
7b0ce2da
JF
5864}
5865
46aa9775
GP
5866- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5867 Source *source = [self sourceAtIndexPath:indexPath];
f641a0e5 5868 return [source description] == nil ? 56 : 73;
7b0ce2da
JF
5869}
5870
46aa9775 5871- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb 5872 static NSString *cellIdentifier = @"SourceCell";
7b0ce2da 5873
46aa9775 5874 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
b5e7eebb
GP
5875 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5876 [cell setSource:[self sourceAtIndexPath:indexPath]];
5877
46aa9775 5878 return cell;
7b0ce2da
JF
5879}
5880
46aa9775
GP
5881- (int) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5882 return 1; //UITableViewCellAccessoryDisclosureIndicator?
7b0ce2da
JF
5883}
5884
46aa9775
GP
5885- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5886 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da 5887
b5e7eebb
GP
5888 FilteredPackageView *packages = [[[FilteredPackageView alloc]
5889 initWithDatabase:database_
7b0ce2da
JF
5890 title:[source label]
5891 filter:@selector(isVisibleInSource:)
5892 with:source
5893 ] autorelease];
5894
5895 [packages setDelegate:delegate_];
5896
b5e7eebb 5897 [[self navigationController] pushViewController:packages animated:YES];
7b0ce2da
JF
5898}
5899
46aa9775
GP
5900- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5901 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da
JF
5902 return [source record] != nil;
5903}
5904
46aa9775
GP
5905- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5906 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da
JF
5907 [Sources_ removeObjectForKey:[source key]];
5908 [delegate_ syncData];
5909}
5910
2fc76a2d
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 {
3e9c9e85
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];
670a0494 5927 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
2fc76a2d
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
7b0ce2da
JF
5940- (void) _endConnection:(NSURLConnection *)connection {
5941 NSURLConnection **field = NULL;
42543928
JF
5942 if (connection == trivial_)
5943 field = &trivial_;
5944 else if (connection == trivial_bz2_)
7b0ce2da
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 (
42543928 5953 trivial_ == nil &&
7b0ce2da
JF
5954 trivial_bz2_ == nil &&
5955 trivial_gz_ == nil
5956 ) {
3e9c9e85 5957 bool defer(false);
7b0ce2da 5958
42543928 5959 if (cydia_) {
2fc76a2d 5960 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
3e9c9e85
JF
5961 defer = true;
5962
0fe9a7e8 5963 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 5964 initWithTitle:UCLocalize("SOURCE_WARNING")
b5e7eebb
GP
5965 message:warning
5966 delegate:self
5967 cancelButtonTitle:UCLocalize("CANCEL")
0fe9a7e8 5968 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
2fc76a2d
JF
5969 ] autorelease];
5970
b5e7eebb 5971 [alert setContext:@"warning"];
0fe9a7e8
GP
5972 [alert setNumberOfRows:1];
5973 [alert show];
2fc76a2d
JF
5974 } else
5975 [self complete];
7b0ce2da 5976 } else if (error_ != nil) {
0fe9a7e8 5977 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 5978 initWithTitle:UCLocalize("VERIFICATION_ERROR")
b5e7eebb
GP
5979 message:[error_ localizedDescription]
5980 delegate:self
5981 cancelButtonTitle:UCLocalize("OK")
0fe9a7e8 5982 otherButtonTitles:nil
7b0ce2da
JF
5983 ] autorelease];
5984
b5e7eebb 5985 [alert setContext:@"urlerror"];
0fe9a7e8 5986 [alert show];
7b0ce2da 5987 } else {
0fe9a7e8 5988 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 5989 initWithTitle:UCLocalize("NOT_REPOSITORY")
b5e7eebb
GP
5990 message:UCLocalize("NOT_REPOSITORY_EX")
5991 delegate:self
5992 cancelButtonTitle:UCLocalize("OK")
0fe9a7e8 5993 otherButtonTitles:nil
7b0ce2da
JF
5994 ] autorelease];
5995
b5e7eebb 5996 [alert setContext:@"trivial"];
0fe9a7e8 5997 [alert show];
7b0ce2da
JF
5998 }
5999
3e9c9e85
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 }
7b0ce2da
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:
42543928 6021 cydia_ = YES;
7b0ce2da
JF
6022 }
6023}
6024
6025- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
c390d3ab 6026 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7b0ce2da
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
b5e7eebb
GP
6036- (id)title { return UCLocalize("SOURCES"); }
6037
7b0ce2da
JF
6038- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6039 NSMutableURLRequest *request = [NSMutableURLRequest
6040 requestWithURL:[NSURL URLWithString:href]
6041 cachePolicy:NSURLRequestUseProtocolCachePolicy
77801ff1 6042 timeoutInterval:120.0
7b0ce2da
JF
6043 ];
6044
6045 [request setHTTPMethod:method];
6046
f79a4512
JF
6047 if (Machine_ != NULL)
6048 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
77801ff1
JF
6049 if (UniqueID_ != nil)
6050 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
f79a4512
JF
6051 if (Role_ != nil)
6052 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6053
7b0ce2da
JF
6054 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6055}
6056
0fe9a7e8
GP
6057- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6058 NSString *context([alert context]);
1cedb821
JF
6059
6060 if ([context isEqualToString:@"source"]) {
7b0ce2da
JF
6061 switch (button) {
6062 case 1: {
0fe9a7e8 6063 NSString *href = [[alert textField] text];
7b0ce2da
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
42543928 6073 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7b0ce2da
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
42543928 6078 cydia_ = false;
7b0ce2da 6079
d061f4ba 6080 hud_ = [[delegate_ addProgressHUD] retain];
43f3d7f6 6081 [hud_ setText:UCLocalize("VERIFYING_URL")];
7b0ce2da
JF
6082 } break;
6083
0fe9a7e8 6084 case 0:
7b0ce2da
JF
6085 break;
6086
670a0494 6087 _nodefault
7b0ce2da
JF
6088 }
6089
0fe9a7e8 6090 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b49f4c92 6091 } else if ([context isEqualToString:@"trivial"])
0fe9a7e8 6092 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b49f4c92 6093 else if ([context isEqualToString:@"urlerror"])
0fe9a7e8 6094 [alert dismissWithClickedButtonIndex:-1 animated:YES];
2fc76a2d
JF
6095 else if ([context isEqualToString:@"warning"]) {
6096 switch (button) {
6097 case 1:
6098 [self complete];
6099 break;
6100
0fe9a7e8 6101 case 0:
2fc76a2d
JF
6102 break;
6103
670a0494 6104 _nodefault
2fc76a2d
JF
6105 }
6106
3e9c9e85
JF
6107 [href_ release];
6108 href_ = nil;
6109
0fe9a7e8 6110 [alert dismissWithClickedButtonIndex:-1 animated:YES];
2fc76a2d 6111 }
7b0ce2da
JF
6112}
6113
b5e7eebb
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
7b0ce2da
JF
6119 database_ = database;
6120 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6121
b5e7eebb 6122 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 6123 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b5e7eebb 6124 [[self view] addSubview:list_];
04fe1349 6125
7b0ce2da 6126 [list_ setDataSource:self];
46aa9775 6127 [list_ setDelegate:self];
7b0ce2da
JF
6128
6129 [self reloadData];
6130 } return self;
6131}
6132
6133- (void) reloadData {
6134 pkgSourceList list;
670a0494
JF
6135 if (!list.ReadMainList())
6136 return;
7b0ce2da
JF
6137
6138 [sources_ removeAllObjects];
6139 [sources_ addObjectsFromArray:[database_ sources]];
807ae6d7 6140 _trace();
7b0ce2da 6141 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
807ae6d7 6142 _trace();
7b0ce2da 6143
b5e7eebb 6144 int count([sources_ count]);
46aa9775
GP
6145 offset_ = 0;
6146 for (int i = 0; i != count; i++) {
b5e7eebb
GP
6147 if ([[sources_ objectAtIndex:i] record] == nil) break;
6148 else offset_++;
7b0ce2da
JF
6149 }
6150
46aa9775 6151 [list_ setEditing:NO];
b5e7eebb 6152 [self updateButtonsForEditingStatus:NO animated:NO];
7b0ce2da
JF
6153 [list_ reloadData];
6154}
6155
b5e7eebb 6156- (void) addButtonClicked {
7b0ce2da
JF
6157 /*[book_ pushPage:[[[AddSourceView alloc]
6158 initWithBook:book_
6159 database:database_
6160 ] autorelease]];*/
6161
0fe9a7e8 6162 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 6163 initWithTitle:UCLocalize("ENTER_APT_URL")
b5e7eebb
GP
6164 message:nil
6165 delegate:self
6166 cancelButtonTitle:UCLocalize("CANCEL")
6167 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7b0ce2da
JF
6168 ] autorelease];
6169
b5e7eebb
GP
6170 [alert setContext:@"source"];
6171 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
1cedb821 6172
0fe9a7e8
GP
6173 [alert setNumberOfRows:1];
6174 [alert addTextFieldWithValue:@"http://" label:@""];
7b0ce2da 6175
0fe9a7e8 6176 UITextInputTraits *traits = [[alert textField] textInputTraits];
b49f4c92
JF
6177 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6178 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
1cedb821 6179 [traits setKeyboardType:UIKeyboardTypeURL];
b49f4c92
JF
6180 // XXX: UIReturnKeyDone
6181 [traits setReturnKeyType:UIReturnKeyNext];
7b0ce2da 6182
0fe9a7e8 6183 [alert show];
7b0ce2da
JF
6184}
6185
b5e7eebb
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];
7b0ce2da
JF
6204}
6205
b5e7eebb
GP
6206- (void) editButtonClicked {
6207 [list_ setEditing:![list_ isEditing] animated:YES];
6208
6209 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
7b0ce2da
JF
6210}
6211
6212@end
6213/* }}} */
6214
6215/* Installed View {{{ */
b5e7eebb 6216@interface InstalledView : FilteredPackageView {
f641a0e5 6217 BOOL expert_;
7b0ce2da
JF
6218}
6219
b5e7eebb 6220- (id) initWithDatabase:(Database *)database;
7b0ce2da
JF
6221
6222@end
6223
6224@implementation InstalledView
6225
6226- (void) dealloc {
7b0ce2da
JF
6227 [super dealloc];
6228}
6229
b5e7eebb 6230- (id) title { return UCLocalize("INSTALLED"); }
baf80942 6231
b5e7eebb
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];
7b0ce2da
JF
6236 } return self;
6237}
6238
b5e7eebb
GP
6239#if !AlwaysReload
6240- (void) queueButtonClicked {
6241 [delegate_ queue];
7b0ce2da 6242}
b5e7eebb 6243#endif
7b0ce2da 6244
b5e7eebb
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
f641a0e5
JF
6259}
6260
b5e7eebb
GP
6261- (void) reloadData {
6262 [packages_ reloadData];
7b0ce2da
JF
6263}
6264
b5e7eebb
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];
7b0ce2da
JF
6274}
6275
b5e7eebb
GP
6276- (void) roleButtonClicked {
6277 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6278 [packages_ reloadData];
6279 expert_ = !expert_;
f641a0e5 6280
b5e7eebb 6281 [self updateRoleButton];
f641a0e5
JF
6282}
6283
7b0ce2da
JF
6284- (void) setDelegate:(id)delegate {
6285 [super setDelegate:delegate];
6286 [packages_ setDelegate:delegate];
6287}
6288
6289@end
6290/* }}} */
6291
98228790 6292/* Home View {{{ */
b5e7eebb 6293@interface HomeView : CYBrowserController {
7b0ce2da
JF
6294}
6295
6296@end
6297
6298@implementation HomeView
6299
bfc87a4d
JF
6300- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6301 [super _setMoreHeaders:request];
6302 if (ChipID_ != nil)
6303 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
01d93940
JF
6304 if (UniqueID_ != nil)
6305 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
bfc87a4d
JF
6306}
6307
b5e7eebb 6308- (void) aboutButtonClicked {
65c27c56
JF
6309 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6310 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6311 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6312 [alert setCancelButtonIndex:0];
7b0ce2da 6313
65c27c56 6314 [alert setMessage:
77801ff1 6315 @"Copyright (C) 2008-2010\n"
7b0ce2da
JF
6316 "Jay Freeman (saurik)\n"
6317 "saurik@saurik.com\n"
42fc47f8 6318 "http://www.saurik.com/"
7b0ce2da
JF
6319 ];
6320
65c27c56 6321 [alert show];
7b0ce2da
JF
6322}
6323
b5e7eebb
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;
7b0ce2da
JF
6345}
6346
6347@end
98228790
JF
6348/* }}} */
6349/* Manage View {{{ */
b5e7eebb 6350@interface ManageView : CYBrowserController {
7b0ce2da
JF
6351}
6352
6353@end
6354
6355@implementation ManageView
6356
b5e7eebb
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;
7b0ce2da
JF
6372}
6373
b5e7eebb 6374- (void) settingsButtonClicked {
7b0ce2da 6375 [delegate_ askForSettings];
670a0494 6376 [delegate_ updateData];
7b0ce2da
JF
6377}
6378
bf8476c8 6379#if !AlwaysReload
b5e7eebb
GP
6380- (void) queueButtonClicked {
6381 [delegate_ queue];
dc63e78f 6382}
b5e7eebb 6383#endif
dc63e78f 6384
b5e7eebb
GP
6385- (void) didFinishLoading {
6386 [self queueStatusDidChange];
dc63e78f
JF
6387}
6388
b5e7eebb
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 }
bf8476c8 6404#endif
b5e7eebb 6405}
7b0ce2da 6406
3bd1c2a2 6407- (bool) isLoading {
9fe5e5f8
JF
6408 return false;
6409}
6410
7b0ce2da 6411@end
98228790 6412/* }}} */
7b0ce2da 6413
b5e7eebb
GP
6414/* Refresh Bar {{{ */
6415@interface RefreshBar : UINavigationBar {
7b0ce2da
JF
6416 UIProgressIndicator *indicator_;
6417 UITextLabel *prompt_;
6418 UIProgressBar *progress_;
baf80942 6419 UINavigationButton *cancel_;
aa5e5990
JF
6420}
6421
aa5e5990 6422@end
aa5e5990 6423
b5e7eebb 6424@implementation RefreshBar
01d93940 6425
b5e7eebb
GP
6426- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6427 if ((self = [super initWithFrame:frame])) {
6428 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
01d93940 6429
b5e7eebb
GP
6430 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6431 [self setBarStyle:1];
01d93940 6432
b5e7eebb 6433 int barstyle([self _barStyle:NO]);
670a0494 6434 bool ugly(barstyle == 0);
807ae6d7
JF
6435
6436 UIProgressIndicatorStyle style = ugly ?
6437 UIProgressIndicatorStyleMediumBrown :
6438 UIProgressIndicatorStyleMediumWhite;
6439
670a0494 6440 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
b5e7eebb 6441 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
807ae6d7
JF
6442 CGRect indrect = {{indoffset, indoffset}, indsize};
6443
6444 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6445 [indicator_ setStyle:style];
b5e7eebb 6446 [self addSubview:indicator_];
807ae6d7
JF
6447
6448 CGSize prmsize = {215, indsize.height + 4};
6449
6450 CGRect prmrect = {{
6451 indoffset * 2 + indsize.width,
b5e7eebb 6452 unsigned([self frame].size.height - prmsize.height) / 2 - 1
807ae6d7
JF
6453 }, prmsize};
6454
670a0494 6455 UIFont *font([UIFont systemFontOfSize:15]);
807ae6d7
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
b5e7eebb 6463 [self addSubview:prompt_];
807ae6d7
JF
6464
6465 CGSize prgsize = {75, 100};
6466
6467 CGRect prgrect = {{
b5e7eebb
GP
6468 [self frame].size.width - prgsize.width - 10,
6469 ([self frame].size.height - prgsize.height) / 2
807ae6d7
JF
6470 } , prgsize};
6471
6472 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
04fe1349 6473 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
b5e7eebb 6474 [self addSubview:progress_];
807ae6d7 6475
04fe1349
JF
6476 [progress_ setStyle:0];
6477
43f3d7f6 6478 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
04fe1349 6479 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
b5e7eebb 6480 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
807ae6d7
JF
6481
6482 CGRect frame = [cancel_ frame];
b5e7eebb
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;
807ae6d7
JF
6485 [cancel_ setFrame:frame];
6486
b5e7eebb
GP
6487 [cancel_ setBarStyle:barstyle];
6488
6489 [indicator_ startAnimation];
807ae6d7
JF
6490 } return self;
6491}
6492
b5e7eebb 6493- (void) cancel {
807ae6d7
JF
6494 [cancel_ removeFromSuperview];
6495}
6496
b5e7eebb
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
807ae6d7
JF
6567 Status status;
6568 status.setDelegate(self);
670a0494 6569 [database_ updateWithStatus:status];
807ae6d7
JF
6570
6571 [self
b5e7eebb 6572 performSelectorOnMainThread:@selector(completeUpdate)
670a0494 6573 withObject:nil
807ae6d7
JF
6574 waitUntilDone:NO
6575 ];
6576}
6577
b5e7eebb
GP
6578- (void) completeUpdate {
6579 updating_ = false;
6580
6581 [self raiseBar:YES];
6582 [refreshbar_ stop];
6583 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
807ae6d7
JF
6584}
6585
b5e7eebb
GP
6586- (void) cancelUpdate {
6587 [refreshbar_ cancel];
6588 [self completeUpdate];
6589}
670a0494 6590
b5e7eebb
GP
6591- (void) cancelPressed {
6592 [self cancelUpdate];
6593}
04fe1349 6594
b5e7eebb
GP
6595- (BOOL) updating {
6596 return updating_;
6597}
670a0494 6598
b5e7eebb
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}
670a0494 6605
807ae6d7
JF
6606- (void) setProgressTitle:(NSString *)title {
6607 [self
6608 performSelectorOnMainThread:@selector(_setProgressTitle:)
6609 withObject:title
6610 waitUntilDone:YES
6611 ];
6612}
6613
b5e7eebb
GP
6614- (bool) isCancelling:(size_t)received {
6615 return !updating_;
6616}
6617
807ae6d7
JF
6618- (void) setProgressPercent:(float)percent {
6619 [self
6620 performSelectorOnMainThread:@selector(_setProgressPercent:)
6621 withObject:[NSNumber numberWithFloat:percent]
6622 waitUntilDone:YES
6623 ];
6624}
6625
807ae6d7
JF
6626- (void) addProgressOutput:(NSString *)output {
6627 [self
6628 performSelectorOnMainThread:@selector(_addProgressOutput:)
6629 withObject:output
6630 waitUntilDone:YES
6631 ];
6632}
6633
807ae6d7 6634- (void) _setProgressTitle:(NSString *)title {
b5e7eebb 6635 [refreshbar_ setPrompt:title];
807ae6d7
JF
6636}
6637
6638- (void) _setProgressPercent:(NSNumber *)percent {
b5e7eebb 6639 [refreshbar_ setProgress:[percent floatValue]];
807ae6d7
JF
6640}
6641
6642- (void) _addProgressOutput:(NSString *)output {
6643}
6644
b5e7eebb
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
807ae6d7
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
9fe5e5f8
JF
6773- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6774 id<NSURLProtocolClient> client([self client]);
189a73d0
JF
6775 if (icon == nil)
6776 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6777 else {
6778 NSData *data(UIImagePNGRepresentation(icon));
9fe5e5f8 6779
189a73d0
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 }
9fe5e5f8
JF
6785}
6786
807ae6d7
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;
dec6029f 6811 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
807ae6d7
JF
6812 Package *package([database packageWithName:path]);
6813 if (package == nil)
6814 goto fail;
dec6029f 6815 UIImage *icon([package icon]);
9fe5e5f8 6816 [self _returnPNGWithImage:icon forRequest:request];
16f2786b
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));
16f2786b
JF
6822 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6823 if (icon == nil)
6824 icon = [UIImage applicationImageNamed:@"unknown.png"];
9fe5e5f8
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];
dec6029f
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));
dec6029f
JF
6837 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6838 if (icon == nil)
6839 icon = [UIImage applicationImageNamed:@"unknown.png"];
9fe5e5f8 6840 [self _returnPNGWithImage:icon forRequest:request];
807ae6d7
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
a3328c28 6852/* Sections View {{{ */
b5e7eebb 6853@interface SectionsView : CYViewController {
807ae6d7
JF
6854 _transient Database *database_;
6855 NSMutableArray *sections_;
6856 NSMutableArray *filtered_;
46aa9775 6857 UITableView *list_;
807ae6d7
JF
6858 UIView *accessory_;
6859 BOOL editing_;
6860}
6861
b5e7eebb 6862- (id) initWithDatabase:(Database *)database;
807ae6d7
JF
6863- (void) reloadData;
6864- (void) resetView;
6865
6866@end
6867
a3328c28 6868@implementation SectionsView
807ae6d7
JF
6869
6870- (void) dealloc {
6871 [list_ setDataSource:nil];
6872 [list_ setDelegate:nil];
6873
6874 [sections_ release];
6875 [filtered_ release];
807ae6d7
JF
6876 [list_ release];
6877 [accessory_ release];
6878 [super dealloc];
6879}
6880
b5e7eebb
GP
6881- (void) viewDidAppear:(BOOL)animated {
6882 [super viewDidAppear:animated];
6883 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6884}
6885
46aa9775
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;
807ae6d7
JF
6889}
6890
46aa9775
GP
6891- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6892 return editing_ ? [sections_ count] : [filtered_ count] + 1;
807ae6d7
JF
6893}
6894
46aa9775
GP
6895- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6896 return 45;
807ae6d7
JF
6897}
6898
46aa9775 6899- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
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];
46aa9775 6904 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
807ae6d7 6905
46aa9775 6906 return cell;
807ae6d7
JF
6907}
6908
46aa9775
GP
6909- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6910 Section *section = [self sectionAtIndexPath:indexPath];
6911 NSString *name = [section name];
807ae6d7
JF
6912 NSString *title;
6913
46aa9775 6914 if ([indexPath row] == 0) {
807ae6d7
JF
6915 section = nil;
6916 name = nil;
43f3d7f6 6917 title = UCLocalize("ALL_PACKAGES");
807ae6d7 6918 } else {
28ce8704
JF
6919 if (name != nil) {
6920 name = [NSString stringWithString:name];
f79a4512 6921 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
28ce8704 6922 } else {
807ae6d7 6923 name = @"";
43f3d7f6 6924 title = UCLocalize("NO_SECTION");
807ae6d7
JF
6925 }
6926 }
6927
b5e7eebb
GP
6928 FilteredPackageView *table = [[[FilteredPackageView alloc]
6929 initWithDatabase:database_
807ae6d7 6930 title:title
670a0494 6931 filter:@selector(isVisibleInSection:)
807ae6d7
JF
6932 with:name
6933 ] autorelease];
6934
6935 [table setDelegate:delegate_];
6936
b5e7eebb 6937 [[self navigationController] pushViewController:table animated:YES];
807ae6d7
JF
6938}
6939
b5e7eebb
GP
6940- (id) title { return UCLocalize("SECTIONS"); }
6941
6942- (id) initWithDatabase:(Database *)database {
6943 if ((self = [super init]) != nil) {
807ae6d7
JF
6944 database_ = database;
6945
b5e7eebb
GP
6946 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6947
807ae6d7
JF
6948 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6949 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6950
b5e7eebb 6951 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
04fe1349 6952 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b5e7eebb 6953 [[self view] addSubview:list_];
807ae6d7 6954
46aa9775 6955 [list_ setDataSource:self];
b5e7eebb 6956 [list_ setDelegate:self];
807ae6d7
JF
6957
6958 [self reloadData];
807ae6d7
JF
6959 } return self;
6960}
6961
6962- (void) reloadData {
6963 NSArray *packages = [database_ packages];
6964
6965 [sections_ removeAllObjects];
6966 [filtered_ removeAllObjects];
6967
f79a4512
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
807ae6d7
JF
6975
6976 _trace();
c4dcf2c2 6977 for (Package *package in packages) {
807ae6d7 6978 NSString *name([package section]);
f79a4512 6979 NSString *key(name == nil ? @"" : name);
807ae6d7 6980
f79a4512
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)
9fcbca29 6988 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
f79a4512
JF
6989 _end
6990 }
6991 _end
6992
6993 [*section addToCount];
6994
6995 _profile(SectionsView$reloadData$Filter)
670a0494 6996 if (![package valid] || ![package visible])
f79a4512
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];
807ae6d7 7006 if (section == nil) {
f79a4512 7007 _profile(SectionsView$reloadData$Section$Allocate)
9fcbca29 7008 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
f79a4512
JF
7009 [sections setObject:section forKey:key];
7010 _end
807ae6d7 7011 }
f79a4512
JF
7012 _end
7013
7014 [section addToCount];
6d9712c4 7015
f79a4512 7016 _profile(SectionsView$reloadData$Filter)
670a0494 7017 if (![package valid] || ![package visible])
f79a4512
JF
7018 continue;
7019 _end
7020
7021 [section addToRow];
7022#endif
b4d89997 7023 }
807ae6d7 7024 _trace();
dc5812ec 7025
f79a4512
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
6d9712c4 7030 [sections_ addObjectsFromArray:[sections allValues]];
f79a4512 7031#endif
6d9712c4 7032
677b8415 7033 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
dc5812ec 7034
f79a4512
JF
7035 for (Section *section in sections_) {
7036 size_t count([section row]);
677b8415 7037 if (count == 0)
f79a4512 7038 continue;
dc5812ec 7039
9fcbca29 7040 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
f79a4512
JF
7041 [section setCount:count];
7042 [filtered_ addObject:section];
b4d89997 7043 }
2367a917 7044
b5e7eebb
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
b4d89997 7054 [list_ reloadData];
807ae6d7 7055 _trace();
36bb2ca2 7056}
2367a917 7057
6d9712c4
JF
7058- (void) resetView {
7059 if (editing_)
b5e7eebb 7060 [self editButtonClicked];
36bb2ca2 7061}
2367a917 7062
b5e7eebb 7063- (void) editButtonClicked {
6d9712c4
JF
7064 if ((editing_ = !editing_))
7065 [list_ reloadData];
807ae6d7 7066 else
6d9712c4 7067 [delegate_ updateData];
b5e7eebb
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];
baf80942
JF
7072}
7073
a54b1c10
JF
7074- (UIView *) accessoryView {
7075 return accessory_;
7076}
7077
dc5812ec 7078@end
2367a917 7079/* }}} */
b4d89997 7080/* Changes View {{{ */
b5e7eebb 7081@interface ChangesView : CYViewController {
36bb2ca2 7082 _transient Database *database_;
dc5812ec
JF
7083 NSMutableArray *packages_;
7084 NSMutableArray *sections_;
327624b6 7085 UITableView *list_;
36bb2ca2 7086 unsigned upgrades_;
dc5812ec
JF
7087}
7088
b5e7eebb 7089- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
36bb2ca2 7090- (void) reloadData;
dc5812ec 7091
dc5812ec
JF
7092@end
7093
b4d89997
JF
7094@implementation ChangesView
7095
7096- (void) dealloc {
327624b6 7097 [list_ setDelegate:nil];
36bb2ca2
JF
7098 [list_ setDataSource:nil];
7099
b4d89997
JF
7100 [packages_ release];
7101 [sections_ release];
36bb2ca2 7102 [list_ release];
b4d89997
JF
7103 [super dealloc];
7104}
dc5812ec 7105
b5e7eebb
GP
7106- (void) viewDidAppear:(BOOL)animated {
7107 [super viewDidAppear:animated];
7108 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7109}
7110
327624b6
JF
7111- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7112 NSInteger count([sections_ count]);
7113 return count == 0 ? 1 : count;
dc5812ec
JF
7114}
7115
327624b6
JF
7116- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7117 if ([sections_ count] == 0)
7118 return nil;
dc5812ec
JF
7119 return [[sections_ objectAtIndex:section] name];
7120}
7121
327624b6
JF
7122- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7123 if ([sections_ count] == 0)
7124 return 0;
7125 return [[sections_ objectAtIndex:section] count];
dc5812ec
JF
7126}
7127
327624b6
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)];
dc5812ec
JF
7132}
7133
327624b6
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;
dc5812ec
JF
7140}
7141
327624b6
JF
7142- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7143 return 73;
7144 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
dc5812ec
JF
7145}
7146
327624b6
JF
7147- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7148 Package *package([self packageAtIndexPath:path]);
f79a4512 7149 PackageView *view([delegate_ packageView]);
36bb2ca2
JF
7150 [view setDelegate:delegate_];
7151 [view setPackage:package];
b5e7eebb 7152 [[self navigationController] pushViewController:view animated:YES];
327624b6 7153 return path;
dc5812ec
JF
7154}
7155
b5e7eebb
GP
7156- (void) refreshButtonClicked {
7157 [[UIApplication sharedApplication] beginUpdate];
7158 [[self navigationItem] setLeftBarButtonItem:nil];
9a7b04c5
JF
7159}
7160
b5e7eebb 7161- (void) upgradeButtonClicked {
36bb2ca2 7162 [delegate_ distUpgrade];
dc5812ec
JF
7163}
7164
b5e7eebb
GP
7165- (id) title { return UCLocalize("CHANGES"); }
7166
7167- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7168 if ((self = [super init]) != nil) {
36bb2ca2 7169 database_ = database;
b5e7eebb 7170 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
dc5812ec 7171
b4d89997
JF
7172 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7173 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 7174
b5e7eebb 7175 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 7176 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b5e7eebb 7177 [[self view] addSubview:list_];
36bb2ca2 7178
b4d89997 7179 [list_ setDataSource:self];
327624b6 7180 [list_ setDelegate:self];
dc5812ec 7181
77801ff1 7182 delegate_ = delegate;
36bb2ca2 7183 [self reloadData];
dc5812ec
JF
7184 } return self;
7185}
7186
77801ff1 7187- (void) _reloadPackages:(NSArray *)packages {
807ae6d7 7188 _trace();
c4dcf2c2 7189 for (Package *package in packages)
6d9712c4 7190 if (
6a155117 7191 [package uninstalled] && [package valid] && [package visible] ||
189a73d0 7192 [package upgradableAndEssential:YES]
6d9712c4 7193 )
b4d89997 7194 [packages_ addObject:package];
2367a917 7195
807ae6d7 7196 _trace();
df213583 7197 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
807ae6d7 7198 _trace();
77801ff1
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];
dc5812ec 7213
43f3d7f6
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];
dc5812ec 7216 Section *section = nil;
807ae6d7 7217 NSDate *last = nil;
b4d89997 7218
36bb2ca2
JF
7219 upgrades_ = 0;
7220 bool unseens = false;
7221
677b8415 7222 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
36bb2ca2 7223
dc5812ec
JF
7224 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7225 Package *package = [packages_ objectAtIndex:offset];
dc5812ec 7226
677b8415 7227 BOOL uae = [package upgradableAndEssential:YES];
f79a4512
JF
7228
7229 if (!uae) {
36bb2ca2 7230 unseens = true;
f79a4512 7231 NSDate *seen;
dc5812ec 7232
f79a4512
JF
7233 _profile(ChangesView$reloadData$Remember)
7234 seen = [package seen];
7235 _end
7236
677b8415 7237 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
807ae6d7 7238 last = seen;
723a0072 7239
dc63e78f
JF
7240 NSString *name;
7241 if (seen == nil)
43f3d7f6 7242 name = UCLocalize("UNKNOWN");
dc63e78f 7243 else {
677b8415 7244 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
dc63e78f
JF
7245 [name autorelease];
7246 }
7247
f79a4512 7248 _profile(ChangesView$reloadData$Allocate)
43f3d7f6 7249 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
9fcbca29 7250 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
f79a4512
JF
7251 [sections_ addObject:section];
7252 _end
b4d89997
JF
7253 }
7254
36bb2ca2 7255 [section addToCount];
807ae6d7
JF
7256 } else if ([package ignored])
7257 [ignored addToCount];
7258 else {
7259 ++upgrades_;
7260 [upgradable addToCount];
b4d89997 7261 }
dc5812ec 7262 }
807ae6d7 7263 _trace();
dc5812ec 7264
36bb2ca2 7265 CFRelease(formatter);
b4d89997 7266
36bb2ca2
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 }
dc5812ec 7273
807ae6d7
JF
7274 if ([ignored count] != 0)
7275 [sections_ insertObject:ignored atIndex:0];
36bb2ca2
JF
7276 if (upgrades_ != 0)
7277 [sections_ insertObject:upgradable atIndex:0];
c25a610d 7278
36bb2ca2 7279 [list_ reloadData];
3178d79b 7280
b5e7eebb
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];
8fe19fc1
JF
7298}
7299
3178d79b
JF
7300@end
7301/* }}} */
36bb2ca2 7302/* Search View {{{ */
b5e7eebb
GP
7303@interface SearchView : FilteredPackageView {
7304 id search_;
36bb2ca2 7305}
b4d89997 7306
b5e7eebb 7307- (id) initWithDatabase:(Database *)database;
36bb2ca2 7308- (void) reloadData;
b4d89997 7309
3178d79b
JF
7310@end
7311
36bb2ca2 7312@implementation SearchView
3178d79b 7313
b4d89997 7314- (void) dealloc {
b5e7eebb 7315 [search_ release];
36bb2ca2 7316 [super dealloc];
b4d89997
JF
7317}
7318
b5e7eebb
GP
7319- (void) searchBarSearchButtonClicked:(id)searchBar {
7320 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7321 [search_ resignFirstResponder];
01d93940 7322 [self reloadData];
36bb2ca2 7323}
b4d89997 7324
b5e7eebb
GP
7325- (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7326 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
01d93940 7327 [self reloadData];
36bb2ca2 7328}
b4d89997 7329
b5e7eebb 7330- (id) title { return nil; }
ab398adf 7331
b5e7eebb
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_];
36bb2ca2 7340 } return self;
3178d79b
JF
7341}
7342
807ae6d7
JF
7343- (void) _reloadData {
7344}
b4d89997 7345
807ae6d7 7346- (void) reloadData {
808c6eb6 7347 _profile(SearchView$reloadData)
b5e7eebb 7348 [packages_ reloadData];
808c6eb6
JF
7349 _end
7350 PrintTimes();
b5e7eebb 7351 [packages_ resetCursor];
807ae6d7 7352}
8fe19fc1 7353
807ae6d7
JF
7354@end
7355/* }}} */
bfc87a4d 7356/* Settings View {{{ */
b5e7eebb 7357@interface SettingsView : CYViewController {
807ae6d7
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}
b4d89997 7367
b5e7eebb 7368- (id) initWithDatabase:(Database *)database package:(NSString *)package;
b4d89997 7369
807ae6d7 7370@end
b4d89997 7371
807ae6d7 7372@implementation SettingsView
b4d89997 7373
807ae6d7
JF
7374- (void) dealloc {
7375 [table_ setDataSource:nil];
b4d89997 7376
807ae6d7
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}
b4d89997 7387
807ae6d7
JF
7388- (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7389 if (package_ == nil)
7390 return 0;
b4d89997 7391
807ae6d7
JF
7392 return 2;
7393}
36bb2ca2 7394
807ae6d7
JF
7395- (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7396 if (package_ == nil)
7397 return nil;
baf80942 7398
807ae6d7
JF
7399 switch (group) {
7400 case 0: return nil;
7401 case 1: return nil;
baf80942 7402
670a0494 7403 _nodefault
807ae6d7 7404 }
baf80942 7405
807ae6d7 7406 return nil;
3178d79b
JF
7407}
7408
807ae6d7
JF
7409- (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7410 if (package_ == nil)
7411 return NO;
baf80942 7412
807ae6d7
JF
7413 switch (group) {
7414 case 0: return NO;
7415 case 1: return YES;
b4d89997 7416
670a0494 7417 _nodefault
807ae6d7 7418 }
3178d79b 7419
807ae6d7 7420 return NO;
dc5812ec
JF
7421}
7422
807ae6d7
JF
7423- (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7424 if (package_ == nil)
7425 return 0;
dc5812ec 7426
807ae6d7
JF
7427 switch (group) {
7428 case 0: return 1;
7429 case 1: return 1;
3178d79b 7430
670a0494 7431 _nodefault
807ae6d7 7432 }
baf80942 7433
807ae6d7 7434 return 0;
36bb2ca2 7435}
b4d89997 7436
807ae6d7
JF
7437- (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7438 if (package_ == nil)
7439 return;
b4d89997 7440
807ae6d7 7441 _UISwitchSlider *slider([cell control]);
807ae6d7
JF
7442 BOOL value([slider value] != 0);
7443 NSMutableDictionary *metadata([package_ metadata]);
baf80942 7444
807ae6d7
JF
7445 BOOL before;
7446 if (NSNumber *number = [metadata objectForKey:key])
7447 before = [number boolValue];
7448 else
7449 before = NO;
36bb2ca2 7450
807ae6d7
JF
7451 if (value != before) {
7452 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7453 Changed_ = true;
807ae6d7
JF
7454 [delegate_ updateData];
7455 }
baf80942
JF
7456}
7457
807ae6d7
JF
7458- (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7459 [self onSomething:cell withKey:@"IsSubscribed"];
36bb2ca2 7460}
b4d89997 7461
807ae6d7
JF
7462- (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7463 [self onSomething:cell withKey:@"IsIgnored"];
8fe19fc1
JF
7464}
7465
807ae6d7
JF
7466- (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7467 if (package_ == nil)
7468 return nil;
770f2a8e 7469
807ae6d7
JF
7470 switch (group) {
7471 case 0: switch (row) {
7472 case 0:
7473 return subscribedCell_;
7474 case 1:
7475 return ignoredCell_;
670a0494 7476 _nodefault
807ae6d7
JF
7477 } break;
7478
7479 case 1: switch (row) {
7480 case 0: {
7481 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
9487f027 7482 [cell setShowSelection:NO];
43f3d7f6 7483 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
807ae6d7
JF
7484 return cell;
7485 }
770f2a8e 7486
670a0494 7487 _nodefault
807ae6d7 7488 } break;
770f2a8e 7489
670a0494 7490 _nodefault
807ae6d7 7491 }
770f2a8e 7492
807ae6d7 7493 return nil;
770f2a8e
JF
7494}
7495
b5e7eebb
GP
7496- (id) title { return UCLocalize("SETTINGS"); }
7497
7498- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7499 if ((self = [super init])) {
807ae6d7
JF
7500 database_ = database;
7501 name_ = [package retain];
770f2a8e 7502
b5e7eebb
GP
7503 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7504
7505 table_ = [[UIPreferencesTable alloc] initWithFrame:[[self view] bounds]];
7506 [[self view] addSubview:table_];
770f2a8e 7507
807ae6d7 7508 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
bfc87a4d 7509 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
770f2a8e 7510
807ae6d7 7511 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
bfc87a4d 7512 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
770f2a8e 7513
807ae6d7 7514 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
9487f027 7515 [subscribedCell_ setShowSelection:NO];
43f3d7f6 7516 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
807ae6d7 7517 [subscribedCell_ setControl:subscribedSwitch_];
770f2a8e 7518
807ae6d7 7519 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
9487f027 7520 [ignoredCell_ setShowSelection:NO];
43f3d7f6 7521 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
807ae6d7 7522 [ignoredCell_ setControl:ignoredSwitch_];
770f2a8e 7523
807ae6d7
JF
7524 [table_ setDataSource:self];
7525 [self reloadData];
7526 } return self;
7527}
770f2a8e 7528
807ae6d7
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];
770f2a8e 7537 }
807ae6d7
JF
7538
7539 [table_ reloadData];
770f2a8e
JF
7540}
7541
770f2a8e 7542@end
bfc87a4d 7543/* }}} */
770f2a8e 7544
807ae6d7 7545/* Signature View {{{ */
b5e7eebb 7546@interface SignatureView : CYBrowserController {
770f2a8e
JF
7547 _transient Database *database_;
7548 NSString *package_;
7549}
7550
b5e7eebb 7551- (id) initWithDatabase:(Database *)database package:(NSString *)package;
770f2a8e
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
b5e7eebb
GP
7567- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7568 if ((self = [super init]) != nil) {
770f2a8e
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
807ae6d7 7580/* }}} */
770f2a8e 7581
b5e7eebb
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;
04fe1349 7591
2367a917 7592@interface Cydia : UIApplication <
3178d79b 7593 ConfirmationViewDelegate,
b4d89997 7594 ProgressViewDelegate,
5f6bff8c 7595 CydiaDelegate
2367a917 7596> {
dc5812ec 7597 UIWindow *window_;
36bb2ca2 7598
b5e7eebb 7599 id tabbar_;
9bedffaa 7600
a54b1c10 7601 NSMutableArray *essential_;
9bedffaa 7602 NSMutableArray *broken_;
dc5812ec
JF
7603
7604 Database *database_;
dc5812ec 7605
aeed65a6 7606 int tag_;
b4d89997
JF
7607
7608 UIKeyboard *keyboard_;
bd150f54 7609 UIProgressHUD *hud_;
9b619239 7610
a3328c28 7611 SectionsView *sections_;
9b619239
JF
7612 ChangesView *changes_;
7613 ManageView *manage_;
7614 SearchView *search_;
b5e7eebb
GP
7615 SourceTable *sources_;
7616 InstalledView *installed_;
7617 id queueDelegate_;
f79a4512 7618
ea173384 7619#if RecyclePackageViews
7592e053 7620 NSMutableArray *details_;
ea173384 7621#endif
9aecdc9c
GP
7622
7623 bool loaded_;
dc5812ec
JF
7624}
7625
b5e7eebb
GP
7626- (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7627- (void) setPage:(UIViewController *)page;
670a0494 7628
dc5812ec
JF
7629@end
7630
670a0494
JF
7631static _finline void _setHomePage(Cydia *self) {
7632 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7633}
7634
dc5812ec
JF
7635@implementation Cydia
7636
b5e7eebb
GP
7637- (void) beginUpdate {
7638 [tabbar_ beginUpdate];
7639}
7640
7641- (BOOL) updating {
7642 return [tabbar_ updating];
7643}
7644
01d93940
JF
7645- (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7646 return window_;
7647}
7648
9bedffaa
JF
7649- (void) _loaded {
7650 if ([broken_ count] != 0) {
7651 int count = [broken_ count];
7652
37d2b2a9 7653 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 7654 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
b5e7eebb
GP
7655 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7656 delegate:self
7657 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7658 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
9bedffaa
JF
7659 ] autorelease];
7660
37d2b2a9
GP
7661 [alert setContext:@"fixhalf"];
7662 [alert show];
9bedffaa
JF
7663 } else if (!Ignored_ && [essential_ count] != 0) {
7664 int count = [essential_ count];
7665
37d2b2a9 7666 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 7667 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
b5e7eebb
GP
7668 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7669 delegate:self
7670 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
37d2b2a9 7671 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
9bedffaa
JF
7672 ] autorelease];
7673
37d2b2a9
GP
7674 [alert setContext:@"upgrade"];
7675 [alert show];
9bedffaa
JF
7676 }
7677}
7678
7623f855
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 */
aeed65a6 7702 if (tag_ != 1 && sections_ != nil)
7623f855 7703 [sections_ reloadData];
aeed65a6 7704 if (tag_ != 2 && changes_ != nil)
7623f855 7705 [changes_ reloadData];
aeed65a6 7706 if (tag_ != 4 && search_ != nil)
7623f855
JF
7707 [search_ reloadData];
7708
b5e7eebb
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;
7623f855
JF
7720}
7721
9aecdc9c
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
36bb2ca2 7751- (void) _reloadData {
d061f4ba
JF
7752 UIView *block();
7753
7754 UIProgressHUD *hud([self addProgressHUD]);
9aecdc9c 7755 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
dc5812ec 7756
d061f4ba
JF
7757 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7758 _trace();
7759
7760 [self removeProgressHUD:hud];
c25a610d 7761
36bb2ca2 7762 size_t changes(0);
9bedffaa 7763
a54b1c10 7764 [essential_ removeAllObjects];
9bedffaa 7765 [broken_ removeAllObjects];
b4d89997 7766
670a0494 7767 NSArray *packages([database_ packages]);
affeffc7 7768 for (Package *package in packages) {
9bedffaa
JF
7769 if ([package half])
7770 [broken_ addObject:package];
31f3cfff 7771 if ([package upgradableAndEssential:NO]) {
a54b1c10
JF
7772 if ([package essential])
7773 [essential_ addObject:package];
36bb2ca2 7774 ++changes;
a54b1c10 7775 }
36bb2ca2 7776 }
b4d89997 7777
36bb2ca2
JF
7778 if (changes != 0) {
7779 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
b5e7eebb
GP
7780 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
7781 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
7782
f79a4512
JF
7783 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7784 [self setApplicationBadge:badge];
7785 else
7786 [self setApplicationBadgeString:badge];
c25a610d 7787 } else {
b5e7eebb
GP
7788 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
7789 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
7790
f79a4512
JF
7791 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7792 [self removeApplicationBadge];
7793 else // XXX: maybe use setApplicationBadgeString also?
7794 [self setApplicationIconBadgeNumber:0];
c25a610d 7795 }
b4d89997 7796
7623f855 7797 [self _updateData];
6d9712c4 7798
9aecdc9c 7799 [self refreshIfPossible];
6d9712c4
JF
7800}
7801
7b0ce2da 7802- (void) updateData {
7623f855
JF
7803 [database_ setVisible];
7804 [self _updateData];
b4d89997
JF
7805}
7806
7b0ce2da
JF
7807- (void) update_ {
7808 [database_ update];
7809}
7810
7811- (void) syncData {
670a0494 7812 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7b0ce2da
JF
7813 _assert(file != NULL);
7814
670a0494
JF
7815 for (NSString *key in [Sources_ allKeys]) {
7816 NSDictionary *source([Sources_ objectForKey:key]);
7b0ce2da
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
b5e7eebb
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
7b0ce2da
JF
7835 detachNewThreadSelector:@selector(update_)
7836 toTarget:self
7837 withObject:nil
43f3d7f6 7838 title:UCLocalize("UPDATING_SOURCES")
7b0ce2da
JF
7839 ];
7840}
7841
36bb2ca2
JF
7842- (void) reloadData {
7843 @synchronized (self) {
b5e7eebb 7844 [self _reloadData];
36bb2ca2 7845 }
b4d89997
JF
7846}
7847
7848- (void) resolve {
7849 pkgProblemResolver *resolver = [database_ resolver];
7850
7851 resolver->InstallProtect();
7852 if (!resolver->Resolve(true))
7853 _error->Discard();
2367a917
JF
7854}
7855
aa5d0de7 7856- (CGRect) popUpBounds {
b5e7eebb 7857 return [[tabbar_ view] bounds];
aa5d0de7
JF
7858}
7859
670a0494
JF
7860- (bool) perform {
7861 if (![database_ prepare])
7862 return false;
49048579 7863
b5e7eebb 7864 ConfirmationView *page([[[ConfirmationView alloc] initWithDatabase:database_] autorelease]);
affeffc7 7865 [page setDelegate:self];
b5e7eebb
GP
7866 id confirm_ = [[UINavigationController alloc] initWithRootViewController:page];
7867 [confirm_ setDelegate:self];
49048579 7868
b5e7eebb
GP
7869 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
7870 [[tabbar_ selectedViewController] presentModalViewController:confirm_ animated:YES];
670a0494
JF
7871
7872 return true;
3178d79b
JF
7873}
7874
dc63e78f
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
77801ff1
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
36bb2ca2
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) {
670a0494
JF
7916 if (![database_ upgrade])
7917 return;
36bb2ca2
JF
7918 [self perform];
7919 }
b4d89997
JF
7920}
7921
dc63e78f 7922- (void) complete {
36bb2ca2 7923 @synchronized (self) {
36bb2ca2
JF
7924 [self _reloadData];
7925 }
3178d79b
JF
7926}
7927
b5e7eebb
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
2367a917
JF
7940 detachNewThreadSelector:@selector(perform)
7941 toTarget:database_
7942 withObject:nil
43f3d7f6 7943 title:UCLocalize("RUNNING")
2367a917
JF
7944 ];
7945}
7946
7947- (void) progressViewIsComplete:(ProgressView *)progress {
dc63e78f 7948 [self complete];
dc5812ec
JF
7949}
7950
b5e7eebb 7951- (void) setPage:(UIViewController *)page {
36bb2ca2 7952 [page setDelegate:self];
b5e7eebb
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 }
dc5812ec
JF
7959}
7960
b5e7eebb
GP
7961- (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7962 CYBrowserController *browser = [[[_class alloc] init] autorelease];
7b0ce2da 7963 [browser loadURL:url];
36bb2ca2 7964 return browser;
2367a917
JF
7965}
7966
f79a4512
JF
7967- (SectionsView *) sectionsView {
7968 if (sections_ == nil)
b5e7eebb 7969 sections_ = [[SectionsView alloc] initWithDatabase:database_];
f79a4512
JF
7970 return sections_;
7971}
7972
01d93940
JF
7973- (ChangesView *) changesView {
7974 if (changes_ == nil)
b5e7eebb 7975 changes_ = [[ChangesView alloc] initWithDatabase:database_ delegate:self];
01d93940
JF
7976 return changes_;
7977}
7978
7979- (ManageView *) manageView {
b5e7eebb 7980 if (manage_ == nil) {
01d93940
JF
7981 manage_ = (ManageView *) [[self
7982 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7983 withClass:[ManageView class]
7984 ] retain];
b5e7eebb
GP
7985 if (!IsWildcat_) queueDelegate_ = manage_;
7986 }
01d93940
JF
7987 return manage_;
7988}
7989
7990- (SearchView *) searchView {
7991 if (search_ == nil)
b5e7eebb 7992 search_ = [[SearchView alloc] initWithDatabase:database_];
01d93940
JF
7993 return search_;
7994}
7995
b5e7eebb
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];
559dec34 8012 if (tag == tag_) {
b5e7eebb 8013 [[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
559dec34 8014 return;
b5e7eebb 8015 } else if (tag_ == 1) {
f79a4512 8016 [[self sectionsView] resetView];
b5e7eebb 8017 }
dc5812ec 8018
06aa974d 8019 switch (tag) {
b5e7eebb 8020 case kCydiaTag: _setHomePage(self); break;
36bb2ca2 8021
b5e7eebb
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;
36bb2ca2 8028
670a0494 8029 _nodefault
dc5812ec
JF
8030 }
8031
06aa974d 8032 tag_ = tag;
06aa974d
JF
8033}
8034
7b0ce2da 8035- (void) askForSettings {
43f3d7f6 8036 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
f79a4512 8037
670a0494 8038 CYActionSheet *role([[[CYActionSheet alloc]
43f3d7f6 8039 initWithTitle:UCLocalize("WHO_ARE_YOU")
7b0ce2da 8040 buttons:[NSArray arrayWithObjects:
43f3d7f6
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")],
7b0ce2da
JF
8044 nil]
8045 defaultButtonIndex:-1
670a0494 8046 ] autorelease]);
7b0ce2da 8047
be2b3d7b 8048 [role setMessage:UCLocalize("ROLE_EX")];
670a0494
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];
7b0ce2da
JF
8069}
8070
f79a4512 8071- (void) setPackageView:(PackageView *)view {
7592e053
JF
8072 WebThreadLock();
8073 [view setPackage:nil];
ea173384 8074#if RecyclePackageViews
7592e053
JF
8075 if ([details_ count] < 3)
8076 [details_ addObject:view];
ea173384 8077#endif
7592e053
JF
8078 WebThreadUnlock();
8079}
8080
8081- (PackageView *) _packageView {
b5e7eebb 8082 return [[[PackageView alloc] initWithDatabase:database_] autorelease];
f79a4512
JF
8083}
8084
8085- (PackageView *) packageView {
ea173384 8086#if RecyclePackageViews
f79a4512 8087 PackageView *view;
7592e053 8088 size_t count([details_ count]);
f79a4512 8089
7592e053
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;
f79a4512
JF
8099 }
8100
8101 return view;
ea173384
JF
8102#else
8103 return [self _packageView];
8104#endif
f79a4512
JF
8105}
8106
674dce72
GP
8107- (void) cancelAndClear:(bool)clear {
8108 @synchronized (self) {
8109 if (clear) {
b5e7eebb
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];
674dce72 8122 } else {
b5e7eebb
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];
dc63e78f 8129 }
674dce72 8130 }
37d2b2a9 8131}
7b0ce2da 8132
b5e7eebb
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]) {
37d2b2a9
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 }
7b0ce2da 8148
37d2b2a9
GP
8149 [self resolve];
8150 [self perform];
8151 }
b5e7eebb 8152 } else if (button == [alert cancelButtonIndex]) {
37d2b2a9
GP
8153 [broken_ removeAllObjects];
8154 [self _loaded];
7b0ce2da
JF
8155 }
8156
37d2b2a9 8157 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 8158 } else if ([context isEqualToString:@"upgrade"]) {
37d2b2a9
GP
8159 if (button == [alert firstOtherButtonIndex]) {
8160 @synchronized (self) {
8161 for (Package *essential in essential_)
8162 [essential install];
7b0ce2da 8163
37d2b2a9
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;
7b0ce2da
JF
8171 }
8172
37d2b2a9 8173 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 8174 }
7b0ce2da
JF
8175}
8176
670a0494
JF
8177- (void) system:(NSString *)command { _pooled
8178 system([command UTF8String]);
8179}
8180
8181- (void) applicationWillSuspend {
8182 [database_ clean];
8183 [super applicationWillSuspend];
bd150f54
JF
8184}
8185
8186- (void) applicationSuspend:(__GSEvent *)event {
b5e7eebb 8187 if (hud_ == nil)// && ![progress_ isRunning])
bd150f54 8188 [super applicationSuspend:event];
bd150f54
JF
8189}
8190
6d9712c4
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
7b0ce2da 8201- (UIProgressHUD *) addProgressHUD {
d061f4ba 8202 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
04fe1349
JF
8203 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8204
d061f4ba 8205 [window_ setUserInteractionEnabled:NO];
7b0ce2da 8206 [hud show:YES];
b5e7eebb 8207 [window_ addSubview:hud];
7b0ce2da
JF
8208 return hud;
8209}
8210
d061f4ba
JF
8211- (void) removeProgressHUD:(UIProgressHUD *)hud {
8212 [hud show:NO];
8213 [hud removeFromSuperview];
8214 [window_ setUserInteractionEnabled:YES];
8215}
8216
b5e7eebb 8217- (UIViewController *) pageForPackage:(NSString *)name {
c390d3ab 8218 if (Package *package = [database_ packageWithName:name]) {
f79a4512 8219 PackageView *view([self packageView]);
c390d3ab
JF
8220 [view setPackage:package];
8221 return view;
8222 } else {
670a0494
JF
8223 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8224 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
b5e7eebb 8225 return [self _pageForURL:url withClass:[CYBrowserController class]];
c390d3ab
JF
8226 }
8227}
8228
b5e7eebb 8229- (UIViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
c390d3ab 8230 if (tag != NULL)
aeed65a6 8231 *tag = -1;
c390d3ab 8232
43f3d7f6
JF
8233 NSString *href([url absoluteString]);
8234 if ([href hasPrefix:@"apptapp://package/"])
8235 return [self pageForPackage:[href substringFromIndex:18]];
8236
e47c4742
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"])
b5e7eebb 8248 return [[[AddSourceView alloc] initWithDatabase:database_] autorelease];
e47c4742 8249 else if ([path isEqualToString:@"/storage"])
b5e7eebb 8250 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
e47c4742 8251 else if ([path isEqualToString:@"/sources"])
b5e7eebb 8252 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
e47c4742 8253 else if ([path isEqualToString:@"/packages"])
b5e7eebb 8254 return [[[InstalledView alloc] initWithDatabase:database_] autorelease];
e47c4742 8255 else if ([path hasPrefix:@"/url/"])
b5e7eebb 8256 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
e47c4742
JF
8257 else if ([path hasPrefix:@"/launch/"])
8258 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8259 else if ([path hasPrefix:@"/package-settings/"])
b5e7eebb 8260 return [[[SettingsView alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
e47c4742 8261 else if ([path hasPrefix:@"/package-signature/"])
b5e7eebb 8262 return [[[SignatureView alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
e47c4742
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];
c390d3ab
JF
8267
8268 if (Package *package = [database_ packageWithName:name]) {
b5e7eebb 8269 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
c390d3ab
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;
b5e7eebb 8281 if (UIViewController *page = [self pageForURL:url hasTag:&tag]) {
c390d3ab 8282 [self setPage:page];
c390d3ab 8283 tag_ = tag;
b5e7eebb 8284 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
c390d3ab
JF
8285 }
8286}
8287
bd150f54 8288- (void) applicationDidFinishLaunching:(id)unused {
b5e7eebb 8289 [CYBrowserController _initialize];
ea173384 8290
bfc87a4d
JF
8291 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8292
f641a0e5
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
aeed65a6 8299 tag_ = 0;
bd150f54
JF
8300
8301 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8302 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8303
04fe1349
JF
8304 UIScreen *screen([UIScreen mainScreen]);
8305
8306 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
f641a0e5
JF
8307 [window_ orderFront:self];
8308 [window_ makeKey:self];
c390d3ab 8309 [window_ setHidden:NO];
04fe1349 8310
770f2a8e 8311 database_ = [Database sharedInstance];
bfc87a4d 8312
6d9712c4 8313 if (
bd150f54 8314 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
bd150f54 8315 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
bfc87a4d
JF
8316 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8317 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
6d9712c4 8318 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
70d45c1e 8319 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
6d9712c4 8320 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
bfc87a4d
JF
8321 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8322 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8323 false
bd150f54 8324 ) {
5afbb4b7
JF
8325 [self setIdleTimerDisabled:YES];
8326
670a0494 8327 hud_ = [self addProgressHUD];
b5e7eebb 8328 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
bd150f54
JF
8329 [self setStatusBarShowsProgress:YES];
8330
9b73bcf8 8331 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
670a0494
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();
670a0494 8349
b5e7eebb
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
670a0494 8364 ];
b5e7eebb
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]];
670a0494
JF
8383
8384 [UIKeyboard initImplementationNow];
670a0494
JF
8385
8386 [self reloadData];
8387
670a0494
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);
bd150f54
JF
8397}
8398
b5e7eebb 8399- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
674dce72 8400 if (item != nil && IsWildcat_) {
b5e7eebb 8401 [sheet showFromBarButtonItem:item animated:YES];
674dce72
GP
8402 } else {
8403 [sheet showInView:window_];
8404 }
36bb2ca2
JF
8405}
8406
dc5812ec
JF
8407@end
8408
b4d89997
JF
8409/*IMP alloc_;
8410id Alloc_(id self, SEL selector) {
8411 id object = alloc_(self, selector);
c390d3ab 8412 lprintf("[%s]A-%p\n", self->isa->name, object);
b4d89997
JF
8413 return object;
8414}*/
8415
36bb2ca2
JF
8416/*IMP dealloc_;
8417id Dealloc_(id self, SEL selector) {
8418 id object = dealloc_(self, selector);
c390d3ab 8419 lprintf("[%s]D-%p\n", self->isa->name, object);
36bb2ca2
JF
8420 return object;
8421}*/
b4d89997 8422
f79a4512
JF
8423Class $WebDefaultUIKitDelegate;
8424
d791dce4 8425MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
f79a4512
JF
8426 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8427 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
d791dce4 8428 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
f79a4512
JF
8429}
8430
affeffc7 8431int main(int argc, char *argv[]) { _pooled
d6dad1b4 8432 _trace();
f79a4512 8433
01d93940
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
df213583 8440 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
677b8415 8441
7376b55c 8442 /* Library Hacks {{{ */
77801ff1 8443 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
7376b55c
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 {{{ */
f79a4512 8454 Locale_ = CFLocaleCopyCurrent();
b1ce61ec
JF
8455 Languages_ = [NSLocale preferredLanguages];
8456 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
18876387 8457 //NSLog(@"%@", [Languages_ description]);
78430d06 8458
b1ce61ec
JF
8459 const char *lang;
8460 if (Languages_ == nil || [Languages_ count] == 0)
78430d06 8461 // XXX: consider just setting to C and then falling through?
b1ce61ec 8462 lang = NULL;
78430d06 8463 else {
b1ce61ec 8464 lang = [[Languages_ objectAtIndex:0] UTF8String];
78430d06
JF
8465 setenv("LANG", lang, true);
8466 }
8467
b1ce61ec
JF
8468 //std::setlocale(LC_ALL, lang);
8469 NSLog(@"Setting Language: %s", lang);
7376b55c 8470 /* }}} */
f79a4512 8471
d791dce4 8472 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
f79a4512 8473
7376b55c 8474 /* Parse Arguments {{{ */
de3b1ab4
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)
d791dce4 8491 if (strcmp(args[argi], "--substrate") == 0)
de3b1ab4
JF
8492 substrate = true;
8493 else
8494 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8495 }
7376b55c 8496 /* }}} */
d73cede2 8497
7376b55c
JF
8498 App_ = [[NSBundle mainBundle] bundlePath];
8499 Home_ = NSHomeDirectory();
d791dce4 8500 Advanced_ = YES;
7376b55c 8501
b4d89997
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
36bb2ca2
JF
8509 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8510 dealloc_ = dealloc->method_imp;
8511 dealloc->method_imp = (IMP) &Dealloc_;*/
8512
d791dce4 8513 /* System Information {{{ */
3178d79b 8514 size_t size;
c390d3ab
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
bfc87a4d
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
3178d79b
JF
8533 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8534 char *machine = new char[size];
c390d3ab
JF
8535 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8536 perror("sysctlbyname(\"hw.machine\", ?)");
8537 else
8538 Machine_ = machine;
3178d79b 8539
59dbe296
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)) {
bfc87a4d 8543 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
59dbe296
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]);
bfc87a4d 8555 ChipID_ = [NSString stringWithUTF8String:string];
59dbe296
JF
8556 CFRelease(ecid);
8557 }
8558
8559 IOObjectRelease(service);
8560 }
8561 }
8562
87f46a96 8563 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
3178d79b 8564
ad5d065e
JF
8565 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8566 Build_ = [system objectForKey:@"ProductBuildVersion"];
3e9c9e85
JF
8567 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8568 Product_ = [info objectForKey:@"SafariProductVersion"];
8569 Safari_ = [info objectForKey:@"CFBundleVersion"];
8570 }
d791dce4 8571 /* }}} */
7376b55c 8572 /* Load Database {{{ */
d6dad1b4 8573 _trace();
f79a4512
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];
d6dad1b4
JF
8577 _trace();
8578
8579 if (Metadata_ == NULL)
f79a4512 8580 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
6d9712c4 8581 else {
7b0ce2da
JF
8582 Settings_ = [Metadata_ objectForKey:@"Settings"];
8583
b4d89997 8584 Packages_ = [Metadata_ objectForKey:@"Packages"];
6d9712c4 8585 Sections_ = [Metadata_ objectForKey:@"Sections"];
7b0ce2da 8586 Sources_ = [Metadata_ objectForKey:@"Sources"];
ef055c6c
JF
8587
8588 Token_ = [Metadata_ objectForKey:@"Token"];
7b0ce2da
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"];
6d9712c4 8607 }
7376b55c 8608 /* }}} */
b4d89997 8609
affeffc7 8610#if RecycleWebViews
baf80942 8611 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
affeffc7 8612#endif
baf80942 8613
d791dce4
JF
8614 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8615
01d93940
JF
8616 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8617 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9dd60d81
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);*/
dddbc481 8622
01d93940
JF
8623 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8624
3b0f10b0 8625 if (access("/tmp/.cydia.fw", F_OK) == 0) {
ea173384 8626 unlink("/tmp/.cydia.fw");
3b0f10b0 8627 goto firmware;
77801ff1 8628 } else if (access("/User", F_OK) != 0 || version < 2) {
3b0f10b0 8629 firmware:
d6dad1b4 8630 _trace();
26c2dd8c 8631 system("/usr/libexec/cydia/firmware.sh");
d6dad1b4
JF
8632 _trace();
8633 }
9e98e020 8634
87f46a96
JF
8635 _assert([[NSFileManager defaultManager]
8636 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8637 withIntermediateDirectories:YES
8638 attributes:nil
8639 error:NULL
8640 ]);
8641
7376b55c
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
59dbe296 8649 /* APT Initialization {{{ */
b1ce61ec
JF
8650 _assert(pkgInitConfig(*_config));
8651 _assert(pkgInitSystem(*_config, _system));
8652
8653 if (lang != NULL)
8654 _config->Set("APT::Acquire::Translation", lang);
677b8415 8655 _config->Set("Acquire::http::Timeout", 15);
7623f855 8656 _config->Set("Acquire::http::MaxParallel", 3);
59dbe296 8657 /* }}} */
7376b55c 8658 /* Color Choices {{{ */
36bb2ca2
JF
8659 space_ = CGColorSpaceCreateDeviceRGB();
8660
f641a0e5 8661 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
77fcccaf 8662 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
36bb2ca2 8663 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
baf80942 8664 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
36bb2ca2 8665 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
7b0ce2da 8666 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
3bd1c2a2
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);
59dbe296 8670
dc63e78f
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];
7376b55c 8673 /* }}}*/
7376b55c 8674 /* UIKit Configuration {{{ */
f79a4512
JF
8675 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8676 if ($GSFontSetUseLegacyFontMetrics != NULL)
8677 $GSFontSetUseLegacyFontMetrics(YES);
7b0ce2da 8678
600d005d
JF
8679 // XXX: I have a feeling this was important
8680 //UIKeyboardDisableAutomaticAppearance();
7376b55c 8681 /* }}} */
87f46a96 8682
670a0494
JF
8683 Colon_ = UCLocalize("COLON_DELIMITED");
8684 Error_ = UCLocalize("ERROR");
8685 Warning_ = UCLocalize("WARNING");
8686
d6dad1b4 8687 _trace();
a9543575 8688 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
36bb2ca2
JF
8689
8690 CGColorSpaceRelease(space_);
199d0ba5 8691 CFRelease(Locale_);
36bb2ca2 8692
36bb2ca2 8693 return value;
b5e7eebb 8694}