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