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