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