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