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