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