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