]> git.saurik.com Git - cydia.git/blame - Cydia.mm
Use a static value for the width of the confirm prompt to prevent it from scrolling...
[cydia.git] / Cydia.mm
CommitLineData
36bb2ca2 1/* Cydia - iPhone UIKit Front-End for Debian APT
77801ff1 2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
36bb2ca2
JF
3*/
4
bfc87a4d 5/* Modified BSD License {{{ */
36bb2ca2
JF
6/*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37*/
bfc87a4d 38/* }}} */
36bb2ca2 39
b0ad8dee
JF
40// XXX: wtf/FastMalloc.h... wtf?
41#define USE_SYSTEM_MALLOC 1
42
dc5812ec 43/* #include Directives {{{ */
a95e0405
JF
44#import "UICaboodle/UCPlatform.h"
45#import "UICaboodle/UCLocalize.h"
807ae6d7 46
ab398adf
JF
47#include <objc/objc.h>
48#include <objc/runtime.h>
49
5f6bff8c 50#include <CoreGraphics/CoreGraphics.h>
9743c015 51#include <GraphicsServices/GraphicsServices.h>
5f6bff8c 52#include <Foundation/Foundation.h>
7d2ac47f 53
eef4ccaf
JF
54#if 0
55#define DEPLOYMENT_TARGET_MACOSX 1
56#define CF_BUILDING_CF 1
57#include <CoreFoundation/CFInternal.h>
58#endif
59
677b8415
JF
60#include <CoreFoundation/CFPriv.h>
61#include <CoreFoundation/CFUniChar.h>
62
baf80942 63#import <UIKit/UIKit.h>
a9543575 64
f79a4512
JF
65#include <WebCore/WebCoreThread.h>
66#import <WebKit/WebDefaultUIKitDelegate.h>
7e9a36b6 67
677b8415 68#include <algorithm>
808c6eb6 69#include <iomanip>
2367a917 70#include <sstream>
a0be02eb
JF
71#include <string>
72
2367a917
JF
73#include <ext/stdio_filebuf.h>
74
e59669fd
JF
75#undef ABS
76
dc5812ec
JF
77#include <apt-pkg/acquire.h>
78#include <apt-pkg/acquire-item.h>
79#include <apt-pkg/algorithms.h>
80#include <apt-pkg/cachefile.h>
77fcccaf 81#include <apt-pkg/clean.h>
dc5812ec 82#include <apt-pkg/configuration.h>
7376b55c 83#include <apt-pkg/debindexfile.h>
3178d79b 84#include <apt-pkg/debmetaindex.h>
dc5812ec
JF
85#include <apt-pkg/error.h>
86#include <apt-pkg/init.h>
dddbc481 87#include <apt-pkg/mmap.h>
dc5812ec 88#include <apt-pkg/pkgrecords.h>
dddbc481 89#include <apt-pkg/sha1.h>
dc5812ec 90#include <apt-pkg/sourcelist.h>
2367a917 91#include <apt-pkg/sptr.h>
affeffc7 92#include <apt-pkg/strutl.h>
f9f6d9e8 93#include <apt-pkg/tagfile.h>
dc5812ec 94
f79a4512
JF
95#include <apr-1/apr_pools.h>
96
87f46a96
JF
97#include <sys/types.h>
98#include <sys/stat.h>
3178d79b 99#include <sys/sysctl.h>
59c011d8
JF
100#include <sys/param.h>
101#include <sys/mount.h>
87f46a96 102
2a8d9add 103#include <notify.h>
dddbc481 104#include <dlfcn.h>
3178d79b 105
b4d89997
JF
106extern "C" {
107#include <mach-o/nlist.h>
108}
109
a0be02eb
JF
110#include <cstdio>
111#include <cstdlib>
112#include <cstring>
b4d89997 113
2367a917 114#include <errno.h>
dc5812ec 115#include <pcre.h>
a9543575 116
f79a4512
JF
117#include <ext/hash_map>
118
ef494bd8
RP
119#include <notify.h>
120
a95e0405
JF
121#import "UICaboodle/BrowserView.h"
122#import "UICaboodle/ResetView.h"
fd7853a6
JF
123
124#import "substrate.h"
9aecdc9c
GP
125
126// Apple's sample Reachability code, ASPL licensed.
127#import "Reachability.h"
dc5812ec 128/* }}} */
3178d79b 129
b5e7eebb
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
bfc87a4d 170/* Profiler {{{ */
807ae6d7
JF
171struct timeval _ltv;
172bool _itv;
173
2083b866
JF
174#define _timestamp ({ \
175 struct timeval tv; \
176 gettimeofday(&tv, NULL); \
177 tv.tv_sec * 1000000 + tv.tv_usec; \
178})
179
808c6eb6
JF
180typedef std::vector<class ProfileTime *> TimeList;
181TimeList times_;
182
183class ProfileTime {
184 private:
185 const char *name_;
186 uint64_t total_;
76933519 187 uint64_t count_;
808c6eb6
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;
76933519 199 ++count_;
808c6eb6
JF
200 }
201
202 void Print() {
203 if (total_ != 0)
76933519 204 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
808c6eb6 205 total_ = 0;
76933519 206 count_ = 0;
808c6eb6
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 }
f79a4512 238/* }}} */
affeffc7
JF
239
240#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
241
04fe1349
JF
242static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
243
bf8476c8
JF
244void NSLogPoint(const char *fix, const CGPoint &point) {
245 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
246}
247
affeffc7
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);
1e7a90f5
JF
250}
251
670a0494
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
ef494bd8
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
bfc87a4d 271/* [NSObject yieldToSelector:(withObject:)] {{{*/
d061f4ba 272@interface NSObject (Cydia)
2fc76a2d
JF
273- (id) yieldToSelector:(SEL)selector withObject:(id)object;
274- (id) yieldToSelector:(SEL)selector;
d061f4ba
JF
275@end
276
277@implementation NSObject (Cydia)
278
279- (void) doNothing {
280}
281
2fc76a2d 282- (void) _yieldToContext:(NSMutableArray *)context { _pooled
d061f4ba
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
2fc76a2d
JF
287 /* XXX: deal with exceptions */
288 id value([self performSelector:selector withObject:object]);
289
677b8415 290 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
2fc76a2d 291 [context removeAllObjects];
677b8415 292 if ([signature methodReturnLength] != 0 && value != nil)
2fc76a2d 293 [context addObject:value];
d061f4ba
JF
294
295 stopped = true;
296
297 [self
298 performSelectorOnMainThread:@selector(doNothing)
299 withObject:nil
300 waitUntilDone:NO
301 ];
302}
303
2fc76a2d 304- (id) yieldToSelector:(SEL)selector withObject:(id)object {
3e9c9e85 305 /*return [self performSelector:selector withObject:object];*/
808c6eb6 306
d061f4ba
JF
307 volatile bool stopped(false);
308
2fc76a2d 309 NSMutableArray *context([NSMutableArray arrayWithObjects:
d061f4ba
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]);
2fc76a2d
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];
d061f4ba
JF
333}
334
335@end
bfc87a4d 336/* }}} */
d061f4ba 337
38be2c4b 338@interface CYActionSheet : UIAlertView {
670a0494
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 {
38be2c4b 348 if ((self = [super init])) {
b5e7eebb
GP
349 [self setTitle:title];
350 [self setDelegate:self];
351 for (NSString *button in buttons) [self addButtonWithTitle:button];
352 [self setCancelButtonIndex:index];
670a0494
JF
353 } return self;
354}
355
31f8d96a
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
38be2c4b
GP
368- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
369 button_ = buttonIndex + 1;
670a0494
JF
370}
371
be2b3d7b 372- (void) dismiss {
b5e7eebb 373 [self dismissWithClickedButtonIndex:-1 animated:YES];
be2b3d7b
GP
374}
375
670a0494 376- (int) yieldToPopupAlertAnimated:(BOOL)animated {
a07b7e8b 377 [self setRunsModal:YES];
670a0494 378 button_ = 0;
be2b3d7b 379 [self show];
670a0494
JF
380 return button_;
381}
382
383@end
384
68f1828e 385/* NSForcedOrderingSearch doesn't work on the iPhone */
808c6eb6 386static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
677b8415
JF
387static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
388static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
1e7a90f5 389
6e201c55
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 {
bfc87a4d 410 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
6e201c55
JF
411}
412
413@end
414/* }}} */
415
c390d3ab 416#define lprintf(args...) fprintf(stderr, args)
a9543575 417
aeed65a6 418#define ForRelease 0
ab92ad73 419#define TraceLogging (1 && !ForRelease)
220fa2b0 420#define HistogramInsertionSort (0 && !ForRelease)
f9f6d9e8 421#define ProfileTimes (0 && !ForRelease)
123c5344 422#define ForSaurik (0 && !ForRelease)
670a0494 423#define LogBrowser (0 && !ForRelease)
b1ce61ec 424#define TrackResize (0 && !ForRelease)
01d93940 425#define ManualRefresh (0 && !ForRelease)
f79a4512 426#define ShowInternals (0 && !ForRelease)
b0ad8dee 427#define IgnoreInstall (0 && !ForRelease)
affeffc7 428#define RecycleWebViews 0
8cc8eb1c 429#define RecyclePackageViews (1 && ForRelease)
aeed65a6 430#define AlwaysReload (1 && !ForRelease)
795d26fc 431
ab92ad73 432#if !TraceLogging
189a73d0
JF
433#undef _trace
434#define _trace(args...)
ab92ad73
JF
435#endif
436
437#if !ProfileTimes
808c6eb6 438#undef _profile
3e9c9e85 439#define _profile(name) {
808c6eb6 440#undef _end
3e9c9e85 441#define _end }
2fc76a2d 442#define PrintTimes() do {} while (false)
189a73d0
JF
443#endif
444
807ae6d7 445/* Radix Sort {{{ */
df213583
JF
446typedef uint32_t (*SKRadixFunction)(id, void *);
447
807ae6d7 448@interface NSMutableArray (Radix)
9487f027 449- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
df213583 450- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
807ae6d7
JF
451@end
452
f79a4512
JF
453struct RadixItem_ {
454 size_t index;
455 uint32_t key;
456};
807ae6d7 457
f79a4512
JF
458static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
459 struct RadixItem_ *lhs(swap), *rhs(swap + count);
807ae6d7 460
ec3f2f53 461 static const size_t width = 32;
807ae6d7
JF
462 static const size_t bits = 11;
463 static const size_t slots = 1 << bits;
ec3f2f53 464 static const size_t passes = (width + (bits - 1)) / bits;
807ae6d7
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;
ec3f2f53 474 key &= _not(uint32_t) >> width - bits;
807ae6d7
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;
ec3f2f53 488 key &= _not(uint32_t) >> width - bits;
807ae6d7
JF
489 rhs[hist[key]++] = lhs[i];
490 }
491
f79a4512 492 RadixItem_ *tmp(lhs);
807ae6d7
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
f79a4512
JF
507@implementation NSMutableArray (Radix)
508
509- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
eef4ccaf
JF
510 size_t count([self count]);
511 if (count == 0)
512 return;
513
514#if 0
f79a4512
JF
515 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
516 [invocation setSelector:selector];
517 [invocation setArgument:&object atIndex:2];
eef4ccaf
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
f79a4512 525
f79a4512
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]);
f79a4512 533
eef4ccaf
JF
534#if 0
535 [invocation setTarget:object];
f79a4512
JF
536 [invocation invoke];
537 [invocation getReturnValue:&item.key];
eef4ccaf
JF
538#else
539 item.key = imp(object, selector, object);
540#endif
f79a4512
JF
541 }
542
543 RadixSort_(self, count, swap);
544}
545
df213583 546- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
f79a4512
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
807ae6d7 561@end
eef4ccaf
JF
562/* }}} */
563/* Insertion Sort {{{ */
564
df213583
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);
b5e7eebb 571 if (0 == cr) return (probe - (const char *)list) / elementSize;
df213583
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
eef4ccaf
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);
b5e7eebb 584 if (0 == cr) return (probe - (const char *)list) / elementSize;
eef4ccaf
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
df213583
JF
597#if HistogramInsertionSort
598 uint32_t total(0), *offsets(new uint32_t[range.length]);
599#endif
600
eef4ccaf
JF
601 for (CFIndex index(1); index != range.length; ++index) {
602 const void *value(values[index]);
df213583
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;
eef4ccaf 608 if (correct != index) {
df213583
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);
eef4ccaf
JF
617 values[correct] = value;
618 }
619 }
620
621 CFArrayReplaceValues(array, range, values, range.length);
622 delete [] values;
df213583
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
eef4ccaf
JF
631}
632
807ae6d7
JF
633/* }}} */
634
bf8476c8
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
77801ff1
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
680eb135
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
2388b078
JF
689@interface NSString (UIKit)
690- (NSString *) stringByAddingPercentEscapes;
2388b078
JF
691@end
692
bfc87a4d 693/* Cydia NSString Additions {{{ */
2388b078 694@interface NSString (Cydia)
808c6eb6 695+ (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
f79a4512 696+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
2388b078 697+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
a54b1c10 698- (NSComparisonResult) compareByPath:(NSString *)other;
2fc76a2d
JF
699- (NSString *) stringByCachingURLWithCurrentCDN;
700- (NSString *) stringByAddingPercentEscapesIncludingReserved;
2388b078
JF
701@end
702
703@implementation NSString (Cydia)
704
808c6eb6
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
f79a4512
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
2388b078 715+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
2083b866 716 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
2388b078
JF
717}
718
a54b1c10
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
2fc76a2d
JF
749- (NSString *) stringByCachingURLWithCurrentCDN {
750 return [self
65c27c56
JF
751 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
752 withString:@"://cache.cydia.saurik.com/"
2fc76a2d
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
2388b078 766@end
bfc87a4d 767/* }}} */
2388b078 768
bfc87a4d 769/* C++ NSString Wrapper Cache {{{ */
f79a4512
JF
770class CYString {
771 private:
772 char *data_;
773 size_t size_;
774 CFStringRef cache_;
775
776 _finline void clear_() {
18873623 777 if (cache_ != NULL) {
f79a4512 778 CFRelease(cache_);
18873623
JF
779 cache_ = NULL;
780 }
f79a4512
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),
18873623 804 cache_(NULL)
f79a4512
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
9fcbca29 828 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
f79a4512 829 memcpy(temp, data, size);
9fcbca29 830 temp[size] = '\0';
f79a4512
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
df213583 848 operator CFStringRef() {
f79a4512
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);
01d93940
JF
853 if (cache_ == NULL)
854 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
df213583
JF
855 } return cache_;
856 }
857
858 _finline operator id() {
859 return (NSString *) static_cast<CFStringRef>(*this);
f79a4512
JF
860 }
861};
bfc87a4d
JF
862/* }}} */
863/* C++ NSString Algorithm Adapters {{{ */
f79a4512
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};
bfc87a4d 893/* }}} */
f79a4512 894
b4d89997
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) {
c390d3ab 913 lprintf("%d:%s\n", offset, error);
b4d89997
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) {
2388b078 927 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
b4d89997
JF
928 }
929
8b29f8e6
JF
930 bool operator ()(NSString *data) {
931 // XXX: length is for characters, not for bytes
932 return operator ()([data UTF8String], [data length]);
933 }
934
b4d89997
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/* }}} */
36bb2ca2 941/* Mime Addresses {{{ */
36bb2ca2
JF
942@interface Address : NSObject {
943 NSString *name_;
6f1a15d9 944 NSString *address_;
36bb2ca2
JF
945}
946
947- (NSString *) name;
6f1a15d9 948- (NSString *) address;
36bb2ca2 949
dc63e78f
JF
950- (void) setAddress:(NSString *)address;
951
36bb2ca2
JF
952+ (Address *) addressWithString:(NSString *)string;
953- (Address *) initWithString:(NSString *)string;
954@end
955
956@implementation Address
957
958- (void) dealloc {
959 [name_ release];
6f1a15d9
JF
960 if (address_ != nil)
961 [address_ release];
36bb2ca2
JF
962 [super dealloc];
963}
964
965- (NSString *) name {
966 return name_;
967}
968
6f1a15d9
JF
969- (NSString *) address {
970 return address_;
36bb2ca2
JF
971}
972
dc63e78f
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
36bb2ca2
JF
982+ (Address *) addressWithString:(NSString *)string {
983 return [[[Address alloc] initWithString:string] autorelease];
984}
985
6f1a15d9
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
36bb2ca2
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
6f1a15d9 1003 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
7b0ce2da 1004
6f1a15d9
JF
1005 if (address_r(data, size)) {
1006 name_ = [address_r[1] retain];
1007 address_ = [address_r[2] retain];
36bb2ca2 1008 } else {
affeffc7 1009 name_ = [string retain];
6f1a15d9 1010 address_ = nil;
36bb2ca2
JF
1011 }
1012 } return self;
1013}
1014
1015@end
1016/* }}} */
5f6bff8c 1017/* CoreGraphics Primitives {{{ */
b4d89997
JF
1018class CGColor {
1019 private:
1020 CGColorRef color_;
1021
1022 public:
36bb2ca2
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_);
b4d89997
JF
1037 }
1038
1039 ~CGColor() {
36bb2ca2
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);
b4d89997
JF
1047 }
1048
1049 operator CGColorRef() {
1050 return color_;
1051 }
1052};
b4d89997
JF
1053/* }}} */
1054
36bb2ca2 1055/* Random Global Variables {{{ */
3178d79b 1056static const int PulseInterval_ = 50000;
58241d4c 1057static const int ButtonBarWidth_ = 60;
2388b078 1058static const int ButtonBarHeight_ = 48;
6d9712c4 1059static const float KeyboardTime_ = 0.3f;
affeffc7 1060
d791dce4
JF
1061static int Finish_;
1062static NSArray *Finishes_;
1063
affeffc7 1064#define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
22f8bed9 1065#define NotifyConfig_ "/etc/notify.conf"
2a8d9add 1066
dc63e78f
JF
1067static bool Queuing_;
1068
f641a0e5 1069static CGColor Blue_;
77fcccaf 1070static CGColor Blueish_;
36bb2ca2 1071static CGColor Black_;
baf80942 1072static CGColor Off_;
36bb2ca2 1073static CGColor White_;
7b0ce2da 1074static CGColor Gray_;
3bd1c2a2
JF
1075static CGColor Green_;
1076static CGColor Purple_;
1077static CGColor Purplish_;
1078
dc63e78f
JF
1079static UIColor *InstallingColor_;
1080static UIColor *RemovingColor_;
36bb2ca2 1081
7d2ac47f 1082static NSString *App_;
d73cede2 1083static NSString *Home_;
d73cede2 1084
2388b078 1085static BOOL Advanced_;
a54b1c10 1086static BOOL Ignored_;
2388b078 1087
f641a0e5
JF
1088static UIFont *Font12_;
1089static UIFont *Font12Bold_;
1090static UIFont *Font14_;
1091static UIFont *Font18Bold_;
1092static UIFont *Font22Bold_;
1093
87f46a96 1094static const char *Machine_ = NULL;
bfc87a4d 1095static const NSString *System_ = NULL;
59dbe296
JF
1096static const NSString *SerialNumber_ = nil;
1097static const NSString *ChipID_ = nil;
01d93940 1098static const NSString *Token_ = nil;
ad5d065e
JF
1099static const NSString *UniqueID_ = nil;
1100static const NSString *Build_ = nil;
3e9c9e85
JF
1101static const NSString *Product_ = nil;
1102static const NSString *Safari_ = nil;
2a8d9add 1103
d791dce4
JF
1104static CFLocaleRef Locale_;
1105static NSArray *Languages_;
1106static CGColorSpaceRef space_;
36bb2ca2 1107
46dbfd32 1108static NSDictionary *SectionMap_;
b4d89997 1109static NSMutableDictionary *Metadata_;
7b0ce2da
JF
1110static _transient NSMutableDictionary *Settings_;
1111static _transient NSString *Role_;
1112static _transient NSMutableDictionary *Packages_;
1113static _transient NSMutableDictionary *Sections_;
1114static _transient NSMutableDictionary *Sources_;
bbb879fb 1115static bool Changed_;
b4d89997 1116static NSDate *now_;
8da60fb7 1117
01d93940
JF
1118static bool IsWildcat_;
1119
affeffc7
JF
1120#if RecycleWebViews
1121static NSMutableArray *Documents_;
1122#endif
36bb2ca2 1123/* }}} */
d791dce4 1124
36bb2ca2
JF
1125/* Display Helpers {{{ */
1126inline float Interpolate(float begin, float end, float fraction) {
1127 return (end - begin) * fraction + begin;
1128}
2367a917 1129
f79a4512 1130/* XXX: localize this! */
8fe19fc1 1131NSString *SizeString(double size) {
affeffc7
JF
1132 bool negative = size < 0;
1133 if (negative)
1134 size = -size;
1135
8fe19fc1
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
86316a91 1144 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
8fe19fc1
JF
1145}
1146
0dd0c302
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
6a155117
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
843e75b8 1158CFStringRef StripVersion(const char *version) {
18876387
JF
1159 const char *colon(strchr(version, ':'));
1160 if (colon != NULL)
1161 version = colon + 1;
6a155117
JF
1162 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1163 // XXX: performance
0dd0c302 1164 return CFCString(version);
18876387
JF
1165}
1166
f79a4512 1167NSString *LocalizeSection(NSString *section) {
b1ce61ec 1168 static Pcre title_r("^(.*?) \\((.*)\\)$");
9fcbca29
JF
1169 if (title_r(section)) {
1170 NSString *parent(title_r[1]);
1171 NSString *child(title_r[2]);
1172
43f3d7f6 1173 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
9fcbca29
JF
1174 LocalizeSection(parent),
1175 LocalizeSection(child)
b1ce61ec 1176 ];
9fcbca29 1177 }
b1ce61ec
JF
1178
1179 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
f79a4512
JF
1180}
1181
4cf4165e
JF
1182NSString *Simplify(NSString *title) {
1183 const char *data = [title UTF8String];
1184 size_t size = [title length];
1185
7b0ce2da
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
b1ce61ec 1194 static Pcre title_r("^(.*?) \\((.*)\\)$");
4cf4165e 1195 if (title_r(data, size))
7b0ce2da
JF
1196 return Simplify(title_r[1]);
1197
1198 return title;
4cf4165e 1199}
36bb2ca2
JF
1200/* }}} */
1201
d791dce4
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
6d9712c4 1216bool isSectionVisible(NSString *section) {
677b8415
JF
1217 NSDictionary *metadata([Sections_ objectForKey:section]);
1218 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
6d9712c4
JF
1219 return hidden == nil || ![hidden boolValue];
1220}
1221
9cb0bff2
GP
1222@class Cydia;
1223
d36e83a3 1224/* Delegate Prototypes {{{ */
36bb2ca2
JF
1225@class Package;
1226@class Source;
1227
31f3cfff
JF
1228@interface NSObject (ProgressDelegate)
1229@end
1230
36bb2ca2 1231@protocol ProgressDelegate
670a0494 1232- (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
36bb2ca2
JF
1233- (void) setProgressTitle:(NSString *)title;
1234- (void) setProgressPercent:(float)percent;
baf80942 1235- (void) startProgress;
36bb2ca2 1236- (void) addProgressOutput:(NSString *)output;
baf80942 1237- (bool) isCancelling:(size_t)received;
36bb2ca2
JF
1238@end
1239
8b29f8e6 1240@protocol ConfigurationDelegate
5a09ae08 1241- (void) repairWithSelector:(SEL)selector;
8b29f8e6
JF
1242- (void) setConfigurationData:(NSString *)data;
1243@end
1244
adb61bda 1245@class PackageController;
f79a4512 1246
36bb2ca2 1247@protocol CydiaDelegate
adb61bda 1248- (void) setPackageController:(PackageController *)view;
dc63e78f 1249- (void) clearPackage:(Package *)package;
36bb2ca2 1250- (void) installPackage:(Package *)package;
77801ff1 1251- (void) installPackages:(NSArray *)packages;
36bb2ca2 1252- (void) removePackage:(Package *)package;
36bb2ca2 1253- (void) distUpgrade;
6d9712c4 1254- (void) updateData;
7b0ce2da 1255- (void) syncData;
21c6da4b 1256- (void) showSettings;
7b0ce2da 1257- (UIProgressHUD *) addProgressHUD;
d061f4ba 1258- (void) removeProgressHUD:(UIProgressHUD *)hud;
b5e7eebb 1259- (UIViewController *) pageForPackage:(NSString *)name;
adb61bda 1260- (PackageController *) packageController;
36bb2ca2 1261@end
d36e83a3 1262/* }}} */
b4d89997 1263
dc5812ec
JF
1264/* Status Delegation {{{ */
1265class Status :
1266 public pkgAcquireStatus
1267{
1268 private:
31f3cfff 1269 _transient NSObject<ProgressDelegate> *delegate_;
dc5812ec
JF
1270
1271 public:
1272 Status() :
1273 delegate_(nil)
1274 {
1275 }
1276
1277 void setDelegate(id delegate) {
1278 delegate_ = delegate;
1279 }
1280
670a0494
JF
1281 NSObject<ProgressDelegate> *getDelegate() const {
1282 return delegate_;
1283 }
1284
dc5812ec
JF
1285 virtual bool MediaChange(std::string media, std::string drive) {
1286 return false;
1287 }
1288
1289 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
dc5812ec
JF
1290 }
1291
1292 virtual void Fetch(pkgAcquire::ItemDesc &item) {
9487f027 1293 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
670a0494 1294 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
dc5812ec
JF
1295 }
1296
1297 virtual void Done(pkgAcquire::ItemDesc &item) {
dc5812ec
JF
1298 }
1299
1300 virtual void Fail(pkgAcquire::ItemDesc &item) {
1d80f6b9
JF
1301 if (
1302 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1303 item.Owner->Status == pkgAcquire::Item::StatDone
1304 )
1305 return;
1306
affeffc7
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
670a0494 1315 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
affeffc7
JF
1316 withObject:[NSArray arrayWithObjects:
1317 [NSString stringWithUTF8String:error.c_str()],
1318 source,
1319 nil]
31f3cfff
JF
1320 waitUntilDone:YES
1321 ];
dc5812ec
JF
1322 }
1323
1324 virtual bool Pulse(pkgAcquire *Owner) {
2367a917
JF
1325 bool value = pkgAcquireStatus::Pulse(Owner);
1326
1327 float percent(
1328 double(CurrentBytes + CurrentItems) /
1329 double(TotalBytes + TotalItems)
1330 );
1331
36bb2ca2 1332 [delegate_ setProgressPercent:percent];
baf80942 1333 return [delegate_ isCancelling:CurrentBytes] ? false : value;
dc5812ec
JF
1334 }
1335
1336 virtual void Start() {
baf80942 1337 [delegate_ startProgress];
dc5812ec
JF
1338 }
1339
1340 virtual void Stop() {
dc5812ec
JF
1341 }
1342};
1343/* }}} */
1344/* Progress Delegation {{{ */
1345class Progress :
1346 public OpProgress
1347{
1348 private:
36bb2ca2 1349 _transient id<ProgressDelegate> delegate_;
bfc87a4d 1350 float percent_;
dc5812ec
JF
1351
1352 protected:
1353 virtual void Update() {
670a0494
JF
1354 /*if (abs(Percent - percent_) > 2)
1355 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
bfc87a4d 1356 percent_ = Percent;
670a0494 1357 }*/
bfc87a4d 1358
8eed3ec6
JF
1359 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1360 [delegate_ setProgressPercent:(Percent / 100)];*/
dc5812ec
JF
1361 }
1362
1363 public:
1364 Progress() :
bfc87a4d
JF
1365 delegate_(nil),
1366 percent_(0)
dc5812ec
JF
1367 {
1368 }
1369
1370 void setDelegate(id delegate) {
1371 delegate_ = delegate;
1372 }
1373
670a0494
JF
1374 id getDelegate() const {
1375 return delegate_;
1376 }
1377
dc5812ec 1378 virtual void Done() {
670a0494 1379 //NSLog(@"DONE");
8eed3ec6 1380 //[delegate_ setProgressPercent:1];
dc5812ec
JF
1381 }
1382};
1383/* }}} */
1384
36bb2ca2 1385/* Database Interface {{{ */
68d927e2
JF
1386typedef std::map< unsigned long, _H<Source> > SourceMap;
1387
36bb2ca2 1388@interface Database : NSObject {
f79a4512
JF
1389 NSZone *zone_;
1390 apr_pool_t *pool_;
1391
a1440b10
JF
1392 unsigned era_;
1393
36bb2ca2 1394 pkgCacheFile cache_;
5a09ae08 1395 pkgDepCache::Policy *policy_;
36bb2ca2
JF
1396 pkgRecords *records_;
1397 pkgProblemResolver *resolver_;
1398 pkgAcquire *fetcher_;
1399 FileFd *lock_;
1400 SPtr<pkgPackageManager> manager_;
1401 pkgSourceList *list_;
5f6bff8c 1402
68d927e2 1403 SourceMap sources_;
9fcbca29 1404 NSMutableArray *packages_;
b4d89997 1405
31f3cfff 1406 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
36bb2ca2
JF
1407 Status status_;
1408 Progress progress_;
8b29f8e6 1409
77fcccaf 1410 int cydiafd_;
36bb2ca2 1411 int statusfd_;
8b29f8e6 1412 FILE *input_;
dc5812ec
JF
1413}
1414
770f2a8e 1415+ (Database *) sharedInstance;
a1440b10 1416- (unsigned) era;
770f2a8e 1417
77fcccaf 1418- (void) _readCydia:(NSNumber *)fd;
36bb2ca2
JF
1419- (void) _readStatus:(NSNumber *)fd;
1420- (void) _readOutput:(NSNumber *)fd;
2367a917 1421
8b29f8e6
JF
1422- (FILE *) input;
1423
36bb2ca2 1424- (Package *) packageWithName:(NSString *)name;
dc5812ec 1425
36bb2ca2 1426- (pkgCacheFile &) cache;
5a09ae08 1427- (pkgDepCache::Policy *) policy;
36bb2ca2
JF
1428- (pkgRecords *) records;
1429- (pkgProblemResolver *) resolver;
1430- (pkgAcquire &) fetcher;
a3328c28 1431- (pkgSourceList &) list;
36bb2ca2 1432- (NSArray *) packages;
7b0ce2da 1433- (NSArray *) sources;
36bb2ca2
JF
1434- (void) reloadData;
1435
5a09ae08 1436- (void) configure;
670a0494 1437- (bool) prepare;
36bb2ca2 1438- (void) perform;
670a0494 1439- (bool) upgrade;
36bb2ca2
JF
1440- (void) update;
1441
7623f855
JF
1442- (void) setVisible;
1443
670a0494 1444- (void) updateWithStatus:(Status &)status;
36bb2ca2
JF
1445
1446- (void) setDelegate:(id)delegate;
7376b55c 1447- (Source *) getSource:(pkgCache::PkgFileIterator)file;
670a0494
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!
b5e7eebb 1477 [self setProgressError:error withTitle:(package == nil ? id : [package name])];
670a0494
JF
1478}
1479
dc5812ec 1480@end
36bb2ca2 1481/* }}} */
dc5812ec 1482
36bb2ca2
JF
1483/* Source Class {{{ */
1484@interface Source : NSObject {
6204f56a 1485 CYString depiction_;
f9f6d9e8
JF
1486 CYString description_;
1487 CYString label_;
1488 CYString origin_;
1489 CYString support_;
dc5812ec 1490
f9f6d9e8
JF
1491 CYString uri_;
1492 CYString distribution_;
1493 CYString type_;
1494 CYString version_;
2367a917 1495
f9f6d9e8 1496 NSString *host_;
10bf7bbb 1497 NSString *authority_;
f9f6d9e8
JF
1498
1499 CYString defaultIcon_;
dc5812ec 1500
7b0ce2da 1501 NSDictionary *record_;
36bb2ca2 1502 BOOL trusted_;
dc5812ec
JF
1503}
1504
f9f6d9e8 1505- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
dc5812ec 1506
7b0ce2da
JF
1507- (NSComparisonResult) compareByNameAndType:(Source *)source;
1508
6204f56a 1509- (NSString *) depictionForPackage:(NSString *)package;
dc63e78f
JF
1510- (NSString *) supportForPackage:(NSString *)package;
1511
7b0ce2da 1512- (NSDictionary *) record;
36bb2ca2 1513- (BOOL) trusted;
dc5812ec 1514
36bb2ca2
JF
1515- (NSString *) uri;
1516- (NSString *) distribution;
1517- (NSString *) type;
7b0ce2da
JF
1518- (NSString *) key;
1519- (NSString *) host;
36bb2ca2 1520
7b0ce2da 1521- (NSString *) name;
36bb2ca2
JF
1522- (NSString *) description;
1523- (NSString *) label;
1524- (NSString *) origin;
1525- (NSString *) version;
dc5812ec 1526
36bb2ca2 1527- (NSString *) defaultIcon;
7b0ce2da 1528
dc5812ec 1529@end
dc5812ec 1530
36bb2ca2 1531@implementation Source
dc5812ec 1532
a3328c28 1533- (void) _clear {
f9f6d9e8
JF
1534 uri_.clear();
1535 distribution_.clear();
1536 type_.clear();
a3328c28 1537
f9f6d9e8
JF
1538 description_.clear();
1539 label_.clear();
1540 origin_.clear();
6204f56a 1541 depiction_.clear();
f9f6d9e8
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 }
7623f855
JF
1555
1556 if (authority_ != nil) {
1557 [authority_ release];
1558 authority_ = nil;
1559 }
a3328c28 1560}
dc5812ec 1561
a3328c28
JF
1562- (void) dealloc {
1563 [self _clear];
36bb2ca2 1564 [super dealloc];
dc5812ec
JF
1565}
1566
6f1a15d9
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
f9f6d9e8 1579- (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
a3328c28 1580 [self _clear];
dc5812ec 1581
a3328c28
JF
1582 trusted_ = index->IsTrusted();
1583
f9f6d9e8
JF
1584 uri_.set(pool, index->GetURI());
1585 distribution_.set(pool, index->GetDist());
1586 type_.set(pool, index->GetType());
a3328c28
JF
1587
1588 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1589 if (dindex != NULL) {
18873623
JF
1590 FileFd fd;
1591 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1592 _error->Discard();
1593 else {
1594 pkgTagFile tags(&fd);
f9f6d9e8 1595
18873623
JF
1596 pkgTagSection section;
1597 tags.Step(section);
a3328c28 1598
18873623
JF
1599 struct {
1600 const char *name_;
1601 CYString *value_;
1602 } names[] = {
1603 {"default-icon", &defaultIcon_},
6204f56a 1604 {"depiction", &depiction_},
18873623
JF
1605 {"description", &description_},
1606 {"label", &label_},
1607 {"origin", &origin_},
1608 {"support", &support_},
1609 {"version", &version_},
1610 };
f9f6d9e8 1611
18873623
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 }
f9f6d9e8 1619 }
36bb2ca2 1620 }
a3328c28 1621 }
7b0ce2da 1622
a3328c28
JF
1623 record_ = [Sources_ objectForKey:[self key]];
1624 if (record_ != nil)
1625 record_ = [record_ retain];
f9f6d9e8 1626
7623f855
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)
a6884de3 1634 authority_ = host_;
7623f855
JF
1635 else
1636 authority_ = [url path];
a6884de3
JF
1637
1638 if (authority_ != nil)
1639 authority_ = [authority_ retain];
a3328c28
JF
1640}
1641
f9f6d9e8 1642- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
a3328c28 1643 if ((self = [super init]) != nil) {
f9f6d9e8 1644 [self setMetaIndex:index inPool:pool];
36bb2ca2 1645 } return self;
2367a917 1646}
dc5812ec 1647
7b0ce2da
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
68f1828e 1668 return [lhs compare:rhs options:LaxCompareOptions_];
7b0ce2da
JF
1669}
1670
6204f56a
JF
1671- (NSString *) depictionForPackage:(NSString *)package {
1672 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1673}
1674
dc63e78f 1675- (NSString *) supportForPackage:(NSString *)package {
f9f6d9e8 1676 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
dc63e78f
JF
1677}
1678
7b0ce2da
JF
1679- (NSDictionary *) record {
1680 return record_;
1681}
1682
36bb2ca2
JF
1683- (BOOL) trusted {
1684 return trusted_;
1685}
3178d79b 1686
36bb2ca2
JF
1687- (NSString *) uri {
1688 return uri_;
1689}
ec97ef06 1690
36bb2ca2
JF
1691- (NSString *) distribution {
1692 return distribution_;
1693}
dc5812ec 1694
36bb2ca2
JF
1695- (NSString *) type {
1696 return type_;
dc5812ec
JF
1697}
1698
7b0ce2da 1699- (NSString *) key {
f9f6d9e8 1700 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
7b0ce2da
JF
1701}
1702
1703- (NSString *) host {
f9f6d9e8 1704 return host_;
7b0ce2da
JF
1705}
1706
1707- (NSString *) name {
7623f855 1708 return origin_.empty() ? authority_ : origin_;
7b0ce2da
JF
1709}
1710
36bb2ca2
JF
1711- (NSString *) description {
1712 return description_;
1713}
b4d89997 1714
36bb2ca2 1715- (NSString *) label {
7623f855 1716 return label_.empty() ? authority_ : label_;
36bb2ca2 1717}
3178d79b 1718
36bb2ca2
JF
1719- (NSString *) origin {
1720 return origin_;
1721}
3178d79b 1722
36bb2ca2
JF
1723- (NSString *) version {
1724 return version_;
1725}
2367a917 1726
36bb2ca2
JF
1727- (NSString *) defaultIcon {
1728 return defaultIcon_;
1729}
2367a917 1730
2388b078
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
dc5812ec 1766@end
b4d89997 1767/* }}} */
36bb2ca2 1768/* Package Class {{{ */
36bb2ca2 1769@interface Package : NSObject {
a1440b10 1770 unsigned era_;
68d927e2 1771 apr_pool_t *pool_;
a1440b10 1772
7376b55c 1773 pkgCache::VerIterator version_;
36bb2ca2
JF
1774 pkgCache::PkgIterator iterator_;
1775 _transient Database *database_;
36bb2ca2 1776 pkgCache::VerFileIterator file_;
bbb879fb 1777
36bb2ca2 1778 Source *source_;
bbb879fb 1779 bool cached_;
68d927e2 1780 bool parsed_;
dc5812ec 1781
f79a4512
JF
1782 CYString section_;
1783 NSString *section$_;
a1440b10 1784 bool essential_;
7623f855 1785 bool required_;
677b8415 1786 bool visible_;
01d93940 1787 bool obsolete_;
807ae6d7 1788
36bb2ca2 1789 NSString *latest_;
6a155117 1790 CYString installed_;
dc5812ec 1791
9fcbca29 1792 CYString id_;
f79a4512
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
7623f855 1805 CYString bugs_;
f79a4512 1806 CYString support_;
0dd0c302 1807 NSMutableArray *tags_;
7b0ce2da 1808 NSString *role_;
2388b078
JF
1809
1810 NSArray *relationships_;
677b8415 1811
f79a4512 1812 NSMutableDictionary *metadata_;
677b8415
JF
1813 _transient NSDate *firstSeen_;
1814 _transient NSDate *lastSeen_;
1815 bool subscribed_;
b4d89997
JF
1816}
1817
7376b55c 1818- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
f79a4512 1819+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
b4d89997 1820
2388b078 1821- (pkgCache::PkgIterator) iterator;
68d927e2 1822- (void) parse;
2388b078 1823
36bb2ca2 1824- (NSString *) section;
dec6029f
JF
1825- (NSString *) simpleSection;
1826
f79a4512
JF
1827- (NSString *) longSection;
1828- (NSString *) shortSection;
1829
a3328c28
JF
1830- (NSString *) uri;
1831
36bb2ca2
JF
1832- (Address *) maintainer;
1833- (size_t) size;
eef4ccaf
JF
1834- (NSString *) longDescription;
1835- (NSString *) shortDescription;
808c6eb6 1836- (unichar) index;
dc5812ec 1837
807ae6d7 1838- (NSMutableDictionary *) metadata;
36bb2ca2 1839- (NSDate *) seen;
807ae6d7
JF
1840- (BOOL) subscribed;
1841- (BOOL) ignored;
9e98e020 1842
36bb2ca2
JF
1843- (NSString *) latest;
1844- (NSString *) installed;
6a155117 1845- (BOOL) uninstalled;
5a09ae08
JF
1846
1847- (BOOL) valid;
31f3cfff 1848- (BOOL) upgradableAndEssential:(BOOL)essential;
36bb2ca2
JF
1849- (BOOL) essential;
1850- (BOOL) broken;
7d2ac47f 1851- (BOOL) unfiltered;
6d9712c4 1852- (BOOL) visible;
b4d89997 1853
9bedffaa
JF
1854- (BOOL) half;
1855- (BOOL) halfConfigured;
1856- (BOOL) halfInstalled;
1857- (BOOL) hasMode;
1858- (NSString *) mode;
1859
7623f855
JF
1860- (void) setVisible;
1861
36bb2ca2
JF
1862- (NSString *) id;
1863- (NSString *) name;
770f2a8e 1864- (UIImage *) icon;
6f1a15d9 1865- (NSString *) homepage;
25a2158d 1866- (NSString *) depiction;
77fcccaf 1867- (Address *) author;
b4d89997 1868
dc63e78f
JF
1869- (NSString *) support;
1870
affeffc7 1871- (NSArray *) files;
2388b078 1872- (NSArray *) relationships;
affeffc7
JF
1873- (NSArray *) warnings;
1874- (NSArray *) applications;
2388b078 1875
36bb2ca2 1876- (Source *) source;
7b0ce2da 1877- (NSString *) role;
b4d89997 1878
36bb2ca2 1879- (BOOL) matches:(NSString *)text;
b4d89997 1880
7b0ce2da 1881- (bool) hasSupportingRole;
6d9712c4 1882- (BOOL) hasTag:(NSString *)tag;
c390d3ab 1883- (NSString *) primaryPurpose;
770f2a8e 1884- (NSArray *) purposes;
3bd1c2a2 1885- (bool) isCommercial;
6d9712c4 1886
df213583
JF
1887- (CYString &) cyname;
1888
f79a4512 1889- (uint32_t) compareBySection:(NSArray *)sections;
807ae6d7
JF
1890
1891- (uint32_t) compareForChanges;
b4d89997 1892
36bb2ca2
JF
1893- (void) install;
1894- (void) remove;
06aa974d 1895
0a3b45ef 1896- (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
01d93940 1897- (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
0a3b45ef 1898- (bool) isInstalledAndVisible:(NSNumber *)number;
670a0494 1899- (bool) isVisibleInSection:(NSString *)section;
0a3b45ef 1900- (bool) isVisibleInSource:(Source *)source;
b4d89997 1901
36bb2ca2 1902@end
b4d89997 1903
f79a4512
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
df213583
JF
1931_finline static void Stifle(uint8_t &value) {
1932}
677b8415 1933
df213583
JF
1934uint32_t PackagePrefixRadix(Package *self, void *context) {
1935 size_t offset(reinterpret_cast<size_t>(context));
1936 CYString &name([self cyname]);
677b8415 1937
df213583
JF
1938 size_t size(name.size());
1939 if (size == 0)
1940 return 0;
1941 char *text(name.data());
677b8415 1942
df213583
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 }
677b8415 1953
df213583
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);
677b8415 1995
5358f56f
JF
1996 if (lhn == NULL)
1997 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1998 else if (rhn == NULL)
1999 return NSOrderedDescending;
2000
677b8415 2001 _profile(PackageNameCompare$NumbersLast)
df213583 2002 if (!lhi.empty() && !rhi.empty()) {
677b8415
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
df213583
JF
2011 CFIndex length = CFStringGetLength(lhn);
2012
677b8415
JF
2013 _profile(PackageNameCompare$Compare)
2014 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2015 _end
2016 _end
2017}
2018
eef4ccaf
JF
2019CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2020 return PackageNameCompare(*lhs, *rhs, context);
677b8415
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
36bb2ca2 2031@implementation Package
b4d89997 2032
df213583
JF
2033- (NSString *) description {
2034 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2035}
2036
36bb2ca2 2037- (void) dealloc {
bbb879fb
JF
2038 if (source_ != nil)
2039 [source_ release];
f79a4512
JF
2040 if (section$_ != nil)
2041 [section$_ release];
807ae6d7 2042
7376b55c
JF
2043 if (latest_ != nil)
2044 [latest_ release];
b4d89997 2045
f79a4512
JF
2046 if (sponsor$_ != nil)
2047 [sponsor$_ release];
2048 if (author$_ != nil)
2049 [author$_ release];
6d9712c4
JF
2050 if (tags_ != nil)
2051 [tags_ release];
7b0ce2da
JF
2052 if (role_ != nil)
2053 [role_ release];
9e98e020 2054
2388b078
JF
2055 if (relationships_ != nil)
2056 [relationships_ release];
f79a4512
JF
2057 if (metadata_ != nil)
2058 [metadata_ release];
2388b078 2059
36bb2ca2 2060 [super dealloc];
b4d89997
JF
2061}
2062
3bd1c2a2
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
6f1a15d9 2074+ (NSArray *) _attributeKeys {
eef4ccaf 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];
6f1a15d9
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
68d927e2
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},
7623f855 2111 {"bugs", &bugs_},
68d927e2
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;
0dd0c302 2131 if (parser->ShortDesc(start, end)) {
68d927e2
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)
1e9e6c94 2142 if (homepage_.empty())
68d927e2
JF
2143 homepage_ = website;
2144 if (homepage_ == depiction_)
2145 homepage_.clear();
2146 _end
2147 _end
2148}
2149
7623f855 2150- (void) setVisible {
ef055c6c 2151 visible_ = required_ && [self unfiltered];
7623f855
JF
2152}
2153
7376b55c 2154- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
a1440b10 2155 if ((self = [super init]) != nil) {
7376b55c 2156 _profile(Package$initWithVersion)
a1440b10
JF
2157 @synchronized (database) {
2158 era_ = [database era];
68d927e2 2159 pool_ = pool;
a1440b10 2160
7376b55c
JF
2161 version_ = version;
2162 iterator_ = version.ParentPkg();
36bb2ca2 2163 database_ = database;
b4d89997 2164
7376b55c 2165 _profile(Package$initWithVersion$Latest)
843e75b8 2166 latest_ = (NSString *) StripVersion(version_.VerStr());
808c6eb6 2167 _end
2083b866 2168
68d927e2
JF
2169 pkgCache::VerIterator current;
2170 _profile(Package$initWithVersion$Versions)
2171 current = iterator_.CurrentVer();
2172 if (!current.end())
6a155117 2173 installed_.set(pool_, StripVersion_(current.VerStr()));
06aa974d 2174
68d927e2
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
808c6eb6 2182
7376b55c 2183 _profile(Package$initWithVersion$Name)
68d927e2 2184 id_.set(pool_, iterator_.Name());
0dd0c302 2185 name_.set(pool, iterator_.Display());
808c6eb6
JF
2186 _end
2187
68d927e2
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;
808c6eb6 2194 _end
68d927e2
JF
2195 }
2196
7623f855 2197 required_ = true;
6204f56a 2198
7376b55c 2199 _profile(Package$initWithVersion$Tags)
0dd0c302
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)];
70d45c1e 2206 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
0dd0c302 2207 role_ = (NSString *) CFCString(name + 6);
7623f855 2208 if (required_ && strncmp(name, "require::", 9) == 0 && (
6204f56a
JF
2209 true
2210 ))
7623f855 2211 required_ = false;
0dd0c302
JF
2212 ++tag;
2213 } while (!tag.end());
2214 }
808c6eb6 2215 _end
7b0ce2da 2216
a4b0ec52 2217 bool changed(false);
86316a91
JF
2218 NSString *key([id_ lowercaseString]);
2219
7376b55c 2220 _profile(Package$initWithVersion$Metadata)
f79a4512 2221 metadata_ = [Packages_ objectForKey:key];
677b8415 2222
f79a4512 2223 if (metadata_ == nil) {
843e75b8 2224 firstSeen_ = now_;
677b8415 2225
f79a4512 2226 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
677b8415
JF
2227 firstSeen_, @"FirstSeen",
2228 latest_, @"LastVersion",
808c6eb6 2229 nil] mutableCopy];
a4b0ec52 2230
808c6eb6
JF
2231 changed = true;
2232 } else {
677b8415
JF
2233 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2234 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2235
2236 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2237 subscribed_ = [subscribed boolValue];
2238
f79a4512 2239 NSString *version([metadata_ objectForKey:@"LastVersion"]);
808c6eb6 2240
677b8415
JF
2241 if (firstSeen_ == nil) {
2242 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2243 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
a4b0ec52
JF
2244 changed = true;
2245 }
a4b0ec52 2246
7376b55c
JF
2247 if (version == nil) {
2248 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2249 changed = true;
01d93940 2250 } else if (![version isEqualToString:latest_]) {
7376b55c 2251 [metadata_ setObject:latest_ forKey:@"LastVersion"];
677b8415
JF
2252 lastSeen_ = now_;
2253 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
7376b55c 2254 changed = true;
01d93940 2255 }
808c6eb6
JF
2256 }
2257
f79a4512
JF
2258 metadata_ = [metadata_ retain];
2259
808c6eb6 2260 if (changed) {
f79a4512 2261 [Packages_ setObject:metadata_ forKey:key];
808c6eb6
JF
2262 Changed_ = true;
2263 }
2264 _end
a1440b10 2265
7376b55c 2266 _profile(Package$initWithVersion$Section)
68d927e2 2267 section_.set(pool_, iterator_.Section());
f79a4512 2268 _end
a1440b10 2269
01d93940 2270 obsolete_ = [self hasTag:@"cydia::obsolete"];
f79a4512 2271 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
7623f855 2272 [self setVisible];
a1440b10 2273 } _end } return self;
dc5812ec
JF
2274}
2275
f79a4512 2276+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
28ce8704 2277@synchronized ([Database class]) {
b1ce61ec
JF
2278 pkgCache::VerIterator version;
2279
2280 _profile(Package$packageWithIterator$GetCandidateVer)
2281 version = [database policy]->GetCandidateVer(iterator);
2282 _end
2283
7376b55c
JF
2284 if (version.end())
2285 return nil;
b1ce61ec 2286
5a09ae08 2287 return [[[Package alloc]
7376b55c 2288 initWithVersion:version
f79a4512
JF
2289 withZone:zone
2290 inPool:pool
5a09ae08
JF
2291 database:database
2292 ] autorelease];
28ce8704 2293} }
dc5812ec 2294
2388b078
JF
2295- (pkgCache::PkgIterator) iterator {
2296 return iterator_;
2297}
2298
36bb2ca2 2299- (NSString *) section {
f79a4512
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$_;
dc5812ec
JF
2316}
2317
dec6029f
JF
2318- (NSString *) simpleSection {
2319 if (NSString *section = [self section])
2320 return Simplify(section);
2321 else
2322 return nil;
a3328c28 2323}
dec6029f 2324
f79a4512 2325- (NSString *) longSection {
18873623 2326 return LocalizeSection([self section]);
f79a4512
JF
2327}
2328
2329- (NSString *) shortSection {
2330 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2331}
2332
a3328c28
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
dec6029f
JF
2344}
2345
36bb2ca2 2346- (Address *) maintainer {
5a09ae08
JF
2347 if (file_.end())
2348 return nil;
36bb2ca2 2349 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
00e2109e
JF
2350 const std::string &maintainer(parser->Maintainer());
2351 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
8fe19fc1
JF
2352}
2353
36bb2ca2 2354- (size_t) size {
5a09ae08 2355 return version_.end() ? 0 : version_->InstalledSize;
dc5812ec
JF
2356}
2357
eef4ccaf 2358- (NSString *) longDescription {
5a09ae08
JF
2359 if (file_.end())
2360 return nil;
36bb2ca2 2361 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2388b078 2362 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
8fe19fc1 2363
36bb2ca2
JF
2364 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2365 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2366 if ([lines count] < 2)
2367 return nil;
3178d79b 2368
36bb2ca2 2369 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
c4dcf2c2 2370 for (size_t i(1), e([lines count]); i != e; ++i) {
36bb2ca2
JF
2371 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2372 [trimmed addObject:trim];
2373 }
3178d79b 2374
36bb2ca2
JF
2375 return [trimmed componentsJoinedByString:@"\n"];
2376}
dc5812ec 2377
eef4ccaf
JF
2378- (NSString *) shortDescription {
2379 return tagline_;
2380}
2381
808c6eb6
JF
2382- (unichar) index {
2383 _profile(Package$index)
677b8415
JF
2384 CFStringRef name((CFStringRef) [self name]);
2385 if (CFStringGetLength(name) == 0)
808c6eb6 2386 return '#';
677b8415
JF
2387 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2388 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
808c6eb6 2389 return '#';
447db19d 2390 return toupper(character);
808c6eb6 2391 _end
36bb2ca2 2392}
3178d79b 2393
807ae6d7 2394- (NSMutableDictionary *) metadata {
f79a4512 2395 return metadata_;
807ae6d7
JF
2396}
2397
36bb2ca2 2398- (NSDate *) seen {
677b8415
JF
2399 if (subscribed_ && lastSeen_ != nil)
2400 return lastSeen_;
2401 return firstSeen_;
3178d79b
JF
2402}
2403
807ae6d7 2404- (BOOL) subscribed {
677b8415 2405 return subscribed_;
807ae6d7
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
36bb2ca2
JF
2416- (NSString *) latest {
2417 return latest_;
8fe19fc1
JF
2418}
2419
36bb2ca2
JF
2420- (NSString *) installed {
2421 return installed_;
3178d79b
JF
2422}
2423
6a155117
JF
2424- (BOOL) uninstalled {
2425 return installed_.empty();
2426}
2427
5a09ae08
JF
2428- (BOOL) valid {
2429 return !version_.end();
2430}
2431
31f3cfff 2432- (BOOL) upgradableAndEssential:(BOOL)essential {
677b8415
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
36bb2ca2 2440}
3178d79b 2441
36bb2ca2 2442- (BOOL) essential {
a1440b10 2443 return essential_;
3178d79b
JF
2444}
2445
36bb2ca2 2446- (BOOL) broken {
9bedffaa
JF
2447 return [database_ cache][iterator_].InstBroken();
2448}
2449
7d2ac47f 2450- (BOOL) unfiltered {
677b8415 2451 NSString *section([self section]);
ef055c6c 2452 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
7d2ac47f
JF
2453}
2454
2455- (BOOL) visible {
677b8415 2456 return visible_;
6d9712c4
JF
2457}
2458
9bedffaa 2459- (BOOL) half {
677b8415 2460 unsigned char current(iterator_->CurrentState);
9bedffaa
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)
f79a4512 2483 return @"PURGE";
9bedffaa 2484 else
f79a4512 2485 return @"REMOVE";
9bedffaa 2486 case pkgDepCache::ModeKeep:
dc63e78f 2487 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
f79a4512 2488 return @"REINSTALL";
dc63e78f
JF
2489 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2490 return nil;*/
9bedffaa
JF
2491 else
2492 return nil;
9bedffaa 2493 case pkgDepCache::ModeInstall:
dc63e78f 2494 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
f79a4512 2495 return @"REINSTALL";
dc63e78f 2496 else*/ switch (state.Status) {
9bedffaa 2497 case -1:
f79a4512 2498 return @"DOWNGRADE";
9bedffaa 2499 case 0:
f79a4512 2500 return @"INSTALL";
9bedffaa 2501 case 1:
f79a4512 2502 return @"UPGRADE";
9bedffaa 2503 case 2:
f79a4512 2504 return @"NEW_INSTALL";
670a0494 2505 _nodefault
9bedffaa 2506 }
670a0494 2507 _nodefault
9bedffaa 2508 }
8fe19fc1
JF
2509}
2510
36bb2ca2
JF
2511- (NSString *) id {
2512 return id_;
8fe19fc1
JF
2513}
2514
36bb2ca2 2515- (NSString *) name {
9fcbca29 2516 return name_.empty() ? id_ : name_;
36bb2ca2 2517}
8fe19fc1 2518
770f2a8e 2519- (UIImage *) icon {
dec6029f 2520 NSString *section = [self simpleSection];
770f2a8e
JF
2521
2522 UIImage *icon(nil);
df213583 2523 if (!icon_.empty())
189a73d0
JF
2524 if ([icon_ hasPrefix:@"file:///"])
2525 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
770f2a8e
JF
2526 if (icon == nil) if (section != nil)
2527 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
189a73d0
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]];
770f2a8e
JF
2531 if (icon == nil)
2532 icon = [UIImage applicationImageNamed:@"unknown.png"];
2533 return icon;
36bb2ca2 2534}
8fe19fc1 2535
6f1a15d9 2536- (NSString *) homepage {
3a49daf0 2537 return homepage_;
8fe19fc1
JF
2538}
2539
25a2158d 2540- (NSString *) depiction {
6204f56a 2541 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
25a2158d
JF
2542}
2543
795d26fc 2544- (Address *) sponsor {
f79a4512
JF
2545 if (sponsor$_ == nil) {
2546 if (sponsor_.empty())
2547 return nil;
2548 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2549 } return sponsor$_;
795d26fc
JF
2550}
2551
77fcccaf 2552- (Address *) author {
f79a4512
JF
2553 if (author$_ == nil) {
2554 if (author_.empty())
2555 return nil;
2556 author$_ = [[Address addressWithString:author_] retain];
2557 } return author$_;
77fcccaf
JF
2558}
2559
dc63e78f 2560- (NSString *) support {
7623f855 2561 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
dc63e78f
JF
2562}
2563
affeffc7 2564- (NSArray *) files {
9fcbca29 2565 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
affeffc7
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
2388b078
JF
2580- (NSArray *) relationships {
2581 return relationships_;
2582}
2583
affeffc7
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:
43f3d7f6 2590 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
affeffc7
JF
2591 else for (size_t i(0); i != length; ++i)
2592 if (
9dd60d81
JF
2593 /* XXX: technically this is not allowed */
2594 (name[i] < 'A' || name[i] > 'Z') &&
affeffc7
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;
7623f855 2602 bool user = false;
9dd60d81 2603 bool _private = false;
affeffc7
JF
2604 bool stash = false;
2605
9dd60d81
JF
2606 bool repository = [[self section] isEqualToString:@"Repositories"];
2607
affeffc7
JF
2608 if (NSArray *files = [self files])
2609 for (NSString *file in files)
2610 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2611 cydia = true;
7623f855
JF
2612 else if (!user && [file isEqualToString:@"/User"])
2613 user = true;
9dd60d81
JF
2614 else if (!_private && [file isEqualToString:@"/private"])
2615 _private = true;
affeffc7
JF
2616 else if (!stash && [file isEqualToString:@"/var/stash"])
2617 stash = true;
2618
9dd60d81
JF
2619 /* XXX: this is not sensitive enough. only some folders are valid. */
2620 if (cydia && !repository)
43f3d7f6 2621 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
7623f855
JF
2622 if (user)
2623 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
9dd60d81 2624 if (_private)
43f3d7f6 2625 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
affeffc7 2626 if (stash)
43f3d7f6 2627 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
affeffc7
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
36bb2ca2 2668- (Source *) source {
bbb879fb 2669 if (!cached_) {
a1440b10
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 }
bbb879fb
JF
2681 }
2682
36bb2ca2 2683 return source_;
8fe19fc1
JF
2684}
2685
7b0ce2da
JF
2686- (NSString *) role {
2687 return role_;
2688}
2689
36bb2ca2
JF
2690- (BOOL) matches:(NSString *)text {
2691 if (text == nil)
2692 return NO;
8fe19fc1 2693
36bb2ca2 2694 NSRange range;
8fe19fc1 2695
808c6eb6 2696 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2
JF
2697 if (range.location != NSNotFound)
2698 return YES;
8fe19fc1 2699
808c6eb6 2700 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2
JF
2701 if (range.location != NSNotFound)
2702 return YES;
8fe19fc1 2703
01d93940 2704 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2 2705 if (range.location != NSNotFound)
01d93940 2706 return YES;
8fe19fc1 2707
36bb2ca2
JF
2708 return NO;
2709}
8fe19fc1 2710
7b0ce2da
JF
2711- (bool) hasSupportingRole {
2712 if (role_ == nil)
6d9712c4 2713 return true;
7b0ce2da
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);
6d9712c4
JF
2727}
2728
2729- (BOOL) hasTag:(NSString *)tag {
2730 return tags_ == nil ? NO : [tags_ containsObject:tag];
2731}
2732
c390d3ab
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
770f2a8e
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
3bd1c2a2
JF
2748- (bool) isCommercial {
2749 return [self hasTag:@"cydia::commercial"];
2750}
2751
df213583
JF
2752- (CYString &) cyname {
2753 return name_.empty() ? id_ : name_;
f79a4512
JF
2754}
2755
f79a4512
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;
36bb2ca2 2761 }
3178d79b 2762
f79a4512 2763 return _not(uint32_t);
36bb2ca2 2764}
3178d79b 2765
807ae6d7
JF
2766- (uint32_t) compareForChanges {
2767 union {
2768 uint32_t key;
3178d79b 2769
807ae6d7
JF
2770 struct {
2771 uint32_t timestamp : 30;
2772 uint32_t ignored : 1;
2773 uint32_t upgradable : 1;
2774 } bits;
2775 } value;
3178d79b 2776
73ee6567
JF
2777 bool upgradable([self upgradableAndEssential:YES]);
2778 value.bits.upgradable = upgradable ? 1 : 0;
8fe19fc1 2779
73ee6567 2780 if (upgradable) {
807ae6d7
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;
36bb2ca2 2788 }
8fe19fc1 2789
807ae6d7 2790 return _not(uint32_t) - value.key;
36bb2ca2 2791}
8fe19fc1 2792
dc63e78f
JF
2793- (void) clear {
2794 pkgProblemResolver *resolver = [database_ resolver];
2795 resolver->Clear(iterator_);
2796 resolver->Protect(iterator_);
2797}
2798
36bb2ca2
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}
68a238ec 2809
36bb2ca2
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}
8fe19fc1 2817
0a3b45ef 2818- (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
808c6eb6
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
0a3b45ef 2830 return value;
808c6eb6 2831 _end
36bb2ca2 2832}
8fe19fc1 2833
01d93940 2834- (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
ef055c6c
JF
2835 if ([search length] == 0)
2836 return false;
2837
01d93940
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
0a3b45ef 2853- (bool) isInstalledAndVisible:(NSNumber *)number {
6a155117 2854 return (![number boolValue] || [self visible]) && ![self uninstalled];
36bb2ca2 2855}
8fe19fc1 2856
670a0494 2857- (bool) isVisibleInSection:(NSString *)name {
5a09ae08
JF
2858 NSString *section = [self section];
2859
0a3b45ef 2860 return
670a0494 2861 [self visible] && (
7b0ce2da
JF
2862 name == nil ||
2863 section == nil && [name length] == 0 ||
2864 [name isEqualToString:section]
0a3b45ef 2865 );
7b0ce2da
JF
2866}
2867
0a3b45ef
JF
2868- (bool) isVisibleInSource:(Source *)source {
2869 return [self source] == source && [self visible];
36bb2ca2 2870}
8fe19fc1 2871
36bb2ca2
JF
2872@end
2873/* }}} */
2874/* Section Class {{{ */
2875@interface Section : NSObject {
2876 NSString *name_;
808c6eb6 2877 unichar index_;
36bb2ca2
JF
2878 size_t row_;
2879 size_t count_;
f79a4512 2880 NSString *localized_;
36bb2ca2 2881}
3178d79b 2882
677b8415 2883- (NSComparisonResult) compareByLocalized:(Section *)section;
9fcbca29
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;
808c6eb6 2887- (Section *) initWithIndex:(unichar)index row:(size_t)row;
36bb2ca2 2888- (NSString *) name;
808c6eb6 2889- (unichar) index;
f79a4512 2890
36bb2ca2
JF
2891- (size_t) row;
2892- (size_t) count;
f79a4512
JF
2893
2894- (void) addToRow;
36bb2ca2 2895- (void) addToCount;
b19871dd 2896
f79a4512 2897- (void) setCount:(size_t)count;
677b8415 2898- (NSString *) localized;
f79a4512 2899
36bb2ca2 2900@end
b19871dd 2901
36bb2ca2 2902@implementation Section
b19871dd 2903
36bb2ca2
JF
2904- (void) dealloc {
2905 [name_ release];
f79a4512
JF
2906 if (localized_ != nil)
2907 [localized_ release];
36bb2ca2
JF
2908 [super dealloc];
2909}
b19871dd 2910
677b8415 2911- (NSComparisonResult) compareByLocalized:(Section *)section {
9fcbca29
JF
2912 NSString *lhs(localized_);
2913 NSString *rhs([section localized]);
6d9712c4 2914
9fcbca29 2915 /*if ([lhs length] != 0 && [rhs length] != 0) {
6d9712c4
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;
9fcbca29 2923 }*/
6d9712c4 2924
68f1828e 2925 return [lhs compare:rhs options:LaxCompareOptions_];
6d9712c4
JF
2926}
2927
9fcbca29
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];
6d9712c4
JF
2937}
2938
9fcbca29 2939- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
36bb2ca2
JF
2940 if ((self = [super init]) != nil) {
2941 name_ = [name retain];
808c6eb6
JF
2942 index_ = '\0';
2943 row_ = row;
9fcbca29
JF
2944 if (localize)
2945 localized_ = [LocalizeSection(name_) retain];
808c6eb6
JF
2946 } return self;
2947}
2948
f79a4512 2949/* XXX: localize the index thingees */
808c6eb6
JF
2950- (Section *) initWithIndex:(unichar)index row:(size_t)row {
2951 if ((self = [super init]) != nil) {
327624b6 2952 name_ = [[NSString stringWithCharacters:&index length:1] retain];
808c6eb6 2953 index_ = index;
36bb2ca2 2954 row_ = row;
b19871dd
JF
2955 } return self;
2956}
2957
36bb2ca2
JF
2958- (NSString *) name {
2959 return name_;
2960}
2961
808c6eb6
JF
2962- (unichar) index {
2963 return index_;
2964}
2965
36bb2ca2
JF
2966- (size_t) row {
2967 return row_;
2968}
2969
2970- (size_t) count {
2971 return count_;
2972}
2973
f79a4512
JF
2974- (void) addToRow {
2975 ++row_;
2976}
2977
36bb2ca2
JF
2978- (void) addToCount {
2979 ++count_;
2980}
2981
f79a4512
JF
2982- (void) setCount:(size_t)count {
2983 count_ = count;
2984}
2985
2986- (NSString *) localized {
2987 return localized_;
2988}
2989
b19871dd
JF
2990@end
2991/* }}} */
2992
670a0494
JF
2993static NSString *Colon_;
2994static NSString *Error_;
2995static NSString *Warning_;
2996
36bb2ca2
JF
2997/* Database Implementation {{{ */
2998@implementation Database
ec97ef06 2999
770f2a8e
JF
3000+ (Database *) sharedInstance {
3001 static Database *instance;
3002 if (instance == nil)
3003 instance = [[Database alloc] init];
3004 return instance;
3005}
3006
a1440b10
JF
3007- (unsigned) era {
3008 return era_;
3009}
3010
36bb2ca2
JF
3011- (void) dealloc {
3012 _assert(false);
f79a4512
JF
3013 NSRecycleZone(zone_);
3014 // XXX: malloc_destroy_zone(zone_);
3015 apr_pool_destroy(pool_);
36bb2ca2
JF
3016 [super dealloc];
3017}
ec97ef06 3018
affeffc7 3019- (void) _readCydia:(NSNumber *)fd { _pooled
77fcccaf
JF
3020 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3021 std::istream is(&ib);
3022 std::string line;
3023
bc8cd583
JF
3024 static Pcre finish_r("^finish:([^:]*)$");
3025
77fcccaf
JF
3026 while (std::getline(is, line)) {
3027 const char *data(line.c_str());
bc8cd583 3028 size_t size = line.size();
c390d3ab 3029 lprintf("C:%s\n", data);
bc8cd583
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 }
77fcccaf
JF
3037 }
3038
670a0494 3039 _assume(false);
77fcccaf
JF
3040}
3041
affeffc7 3042- (void) _readStatus:(NSNumber *)fd { _pooled
36bb2ca2
JF
3043 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3044 std::istream is(&ib);
3045 std::string line;
ec97ef06 3046
7b0ce2da
JF
3047 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3048 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
ec97ef06 3049
36bb2ca2
JF
3050 while (std::getline(is, line)) {
3051 const char *data(line.c_str());
670a0494 3052 size_t size(line.size());
c390d3ab 3053 lprintf("S:%s\n", data);
ec97ef06 3054
5a09ae08
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)];
36bb2ca2 3059 [delegate_ setProgressTitle:string];
5a09ae08 3060 } else if (pmstatus_r(data, size)) {
31f3cfff
JF
3061 std::string type([pmstatus_r[1] UTF8String]);
3062 NSString *id = pmstatus_r[2];
3063
5a09ae08
JF
3064 float percent([pmstatus_r[3] floatValue]);
3065 [delegate_ setProgressPercent:(percent / 100)];
3066
3067 NSString *string = pmstatus_r[4];
5a09ae08
JF
3068
3069 if (type == "pmerror")
670a0494 3070 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
31f3cfff
JF
3071 withObject:[NSArray arrayWithObjects:string, id, nil]
3072 waitUntilDone:YES
3073 ];
9487f027 3074 else if (type == "pmstatus") {
5a09ae08 3075 [delegate_ setProgressTitle:string];
9487f027 3076 } else if (type == "pmconffile")
5a09ae08 3077 [delegate_ setConfigurationData:string];
670a0494
JF
3078 else
3079 lprintf("E:unknown pmstatus\n");
3080 } else
3081 lprintf("E:unknown status\n");
36bb2ca2 3082 }
ec97ef06 3083
670a0494 3084 _assume(false);
36bb2ca2 3085}
ec97ef06 3086
affeffc7 3087- (void) _readOutput:(NSNumber *)fd { _pooled
36bb2ca2
JF
3088 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3089 std::istream is(&ib);
3090 std::string line;
3091
5a09ae08 3092 while (std::getline(is, line)) {
c390d3ab 3093 lprintf("O:%s\n", line.c_str());
2388b078 3094 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
5a09ae08 3095 }
36bb2ca2 3096
670a0494 3097 _assume(false);
ec97ef06
JF
3098}
3099
8b29f8e6
JF
3100- (FILE *) input {
3101 return input_;
3102}
3103
36bb2ca2 3104- (Package *) packageWithName:(NSString *)name {
28ce8704 3105@synchronized ([Database class]) {
5a09ae08
JF
3106 if (static_cast<pkgDepCache *>(cache_) == NULL)
3107 return nil;
36bb2ca2 3108 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
f79a4512 3109 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
28ce8704 3110} }
36bb2ca2
JF
3111
3112- (Database *) init {
ec97ef06 3113 if ((self = [super init]) != nil) {
5a09ae08 3114 policy_ = NULL;
36bb2ca2
JF
3115 records_ = NULL;
3116 resolver_ = NULL;
3117 fetcher_ = NULL;
3118 lock_ = NULL;
ec97ef06 3119
f79a4512
JF
3120 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3121 apr_pool_create(&pool_, NULL);
3122
9fcbca29 3123 packages_ = [[NSMutableArray alloc] init];
ec97ef06 3124
36bb2ca2 3125 int fds[2];
ec97ef06 3126
77fcccaf
JF
3127 _assert(pipe(fds) != -1);
3128 cydiafd_ = fds[1];
3129
3130 _config->Set("APT::Keep-Fds::", cydiafd_);
bc8cd583 3131 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
77fcccaf
JF
3132
3133 [NSThread
3134 detachNewThreadSelector:@selector(_readCydia:)
3135 toTarget:self
3136 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3137 ];
3138
36bb2ca2
JF
3139 _assert(pipe(fds) != -1);
3140 statusfd_ = fds[1];
ec97ef06 3141
36bb2ca2
JF
3142 [NSThread
3143 detachNewThreadSelector:@selector(_readStatus:)
3144 toTarget:self
3145 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3146 ];
ec97ef06 3147
8b29f8e6
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
36bb2ca2
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 ];
ec97ef06
JF
3163 } return self;
3164}
3165
36bb2ca2
JF
3166- (pkgCacheFile &) cache {
3167 return cache_;
ec97ef06
JF
3168}
3169
5a09ae08
JF
3170- (pkgDepCache::Policy *) policy {
3171 return policy_;
3172}
3173
36bb2ca2
JF
3174- (pkgRecords *) records {
3175 return records_;
ec97ef06
JF
3176}
3177
36bb2ca2
JF
3178- (pkgProblemResolver *) resolver {
3179 return resolver_;
ec97ef06
JF
3180}
3181
36bb2ca2
JF
3182- (pkgAcquire &) fetcher {
3183 return *fetcher_;
ec97ef06
JF
3184}
3185
a3328c28
JF
3186- (pkgSourceList &) list {
3187 return *list_;
3188}
3189
36bb2ca2
JF
3190- (NSArray *) packages {
3191 return packages_;
ec97ef06
JF
3192}
3193
7b0ce2da 3194- (NSArray *) sources {
68d927e2
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;
7b0ce2da
JF
3199}
3200
affeffc7
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
744f398e
JF
3234 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3235 if (Package *package = [self packageWithName:name])
3236 name = [package name];
3237 [failure addObject:name];
affeffc7
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
670a0494
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
ef348024 3289 if (fatal && !message.empty())
670a0494
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
d061f4ba 3299- (void) reloadData { _pooled
28ce8704 3300@synchronized ([Database class]) {
a1440b10
JF
3301 @synchronized (self) {
3302 ++era_;
3303 }
3304
843e75b8
JF
3305 [packages_ removeAllObjects];
3306 sources_.clear();
3307
36bb2ca2 3308 _error->Discard();
5a09ae08 3309
36bb2ca2 3310 delete list_;
5a09ae08 3311 list_ = NULL;
36bb2ca2
JF
3312 manager_ = NULL;
3313 delete lock_;
5a09ae08 3314 lock_ = NULL;
36bb2ca2 3315 delete fetcher_;
5a09ae08 3316 fetcher_ = NULL;
36bb2ca2 3317 delete resolver_;
5a09ae08 3318 resolver_ = NULL;
36bb2ca2 3319 delete records_;
5a09ae08
JF
3320 records_ = NULL;
3321 delete policy_;
3322 policy_ = NULL;
36bb2ca2 3323
843e75b8
JF
3324 if (now_ != nil) {
3325 [now_ release];
3326 now_ = nil;
3327 }
3328
5a09ae08 3329 cache_.Close();
8b29f8e6 3330
f79a4512
JF
3331 apr_pool_clear(pool_);
3332 NSRecycleZone(zone_);
3333
7376b55c
JF
3334 int chk(creat("/tmp/cydia.chk", 0644));
3335 if (chk != -1)
3336 close(chk);
3337
670a0494
JF
3338 NSString *title(UCLocalize("DATABASE"));
3339
9487f027 3340 _trace();
670a0494 3341 if (!cache_.Open(progress_, true)) { pop:
8b29f8e6 3342 std::string error;
670a0494 3343 bool warning(!_error->PopMessage(error));
c390d3ab 3344 lprintf("cache_.Open():[%s]\n", error.c_str());
5a09ae08
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)];
9ea8d159
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.")
670a0494
JF
3353 else
3354 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
5a09ae08 3355
670a0494
JF
3356 if (warning)
3357 goto pop;
3358 _error->Discard();
5a09ae08 3359 return;
36bb2ca2 3360 }
9487f027 3361 _trace();
36bb2ca2 3362
7376b55c
JF
3363 unlink("/tmp/cydia.chk");
3364
36bb2ca2
JF
3365 now_ = [[NSDate date] retain];
3366
5a09ae08 3367 policy_ = new pkgDepCache::Policy();
36bb2ca2
JF
3368 records_ = new pkgRecords(cache_);
3369 resolver_ = new pkgProblemResolver(cache_);
3370 fetcher_ = new pkgAcquire(&status_);
3371 lock_ = NULL;
3372
3373 list_ = new pkgSourceList();
670a0494
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 }
36bb2ca2 3381
670a0494
JF
3382 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3383 return;
9bedffaa
JF
3384
3385 if (cache_->BrokenCount() != 0) {
670a0494
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;
9bedffaa
JF
3396 }
3397
7376b55c 3398 _trace();
68d927e2 3399
68d927e2
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())
f9f6d9e8 3407 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
68d927e2 3408 }
36bb2ca2 3409 }
68d927e2 3410
7376b55c 3411 _trace();
36bb2ca2 3412
677b8415 3413 {
9fcbca29 3414 /*std::vector<Package *> packages;
677b8415 3415 packages.reserve(std::max(10000U, [packages_ count] + 1000));
677b8415 3416 [packages_ release];
9fcbca29
JF
3417 packages_ = nil;*/
3418
677b8415
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])
9fcbca29
JF
3423 //packages.push_back(package);
3424 [packages_ addObject:package];
677b8415
JF
3425
3426 _trace();
3427
9fcbca29 3428 /*if (packages.empty())
677b8415
JF
3429 packages_ = [[NSArray alloc] init];
3430 else
3431 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
9fcbca29
JF
3432 _trace();*/
3433
df213583
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)];
9fcbca29
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
eef4ccaf
JF
3448 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3449
df213583 3450 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
9fcbca29
JF
3451
3452 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
677b8415
JF
3453
3454 _trace();
3455 }
28ce8704 3456} }
ec97ef06 3457
5a09ae08
JF
3458- (void) configure {
3459 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3460 system([dpkg UTF8String]);
3461}
3462
670a0494
JF
3463- (bool) clean {
3464 // XXX: I don't remember this condition
77fcccaf 3465 if (lock_ != NULL)
670a0494 3466 return false;
77fcccaf
JF
3467
3468 FileFd Lock;
3469 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
670a0494
JF
3470
3471 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3472
3473 if ([self popErrorWithTitle:title])
3474 return false;
77fcccaf
JF
3475
3476 pkgAcquire fetcher;
3477 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3478
9bedffaa
JF
3479 class LogCleaner :
3480 public pkgArchiveCleaner
3481 {
77fcccaf
JF
3482 protected:
3483 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
9bedffaa 3484 unlink(File);
77fcccaf
JF
3485 }
3486 } cleaner;
3487
670a0494
JF
3488 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3489 return false;
3490
3491 return true;
77fcccaf
JF
3492}
3493
670a0494 3494- (bool) prepare {
744f398e
JF
3495 fetcher_->Shutdown();
3496
36bb2ca2
JF
3497 pkgRecords records(cache_);
3498
3499 lock_ = new FileFd();
3500 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
670a0494
JF
3501
3502 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3503
3504 if ([self popErrorWithTitle:title])
3505 return false;
36bb2ca2
JF
3506
3507 pkgSourceList list;
670a0494
JF
3508 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3509 return false;
36bb2ca2
JF
3510
3511 manager_ = (_system->CreatePM(cache_));
670a0494
JF
3512 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3513 return false;
3514
3515 return true;
ec97ef06
JF
3516}
3517
36bb2ca2 3518- (void) perform {
670a0494
JF
3519 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3520
a72074b2
JF
3521 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3522 pkgSourceList list;
670a0494
JF
3523 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3524 return;
a72074b2
JF
3525 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3526 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3527 }
a0be02eb 3528
eeb9b112
JF
3529 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3530 _trace();
36bb2ca2 3531 return;
eeb9b112
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;
6204f56a
JF
3538 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3539 continue;
eeb9b112
JF
3540
3541 std::string uri = (*item)->DescURI();
3542 std::string error = (*item)->ErrorText;
3543
c390d3ab 3544 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
eeb9b112
JF
3545 failed = true;
3546
670a0494 3547 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
a3328c28
JF
3548 withObject:[NSArray arrayWithObjects:
3549 [NSString stringWithUTF8String:error.c_str()],
3550 nil]
eeb9b112
JF
3551 waitUntilDone:YES
3552 ];
3553 }
3554
3555 if (failed) {
3556 _trace();
3557 return;
3558 }
36bb2ca2
JF
3559
3560 _system->UnLock();
3561 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3562
eeb9b112
JF
3563 if (_error->PendingError()) {
3564 _trace();
36bb2ca2 3565 return;
eeb9b112
JF
3566 }
3567
3568 if (result == pkgPackageManager::Failed) {
3569 _trace();
36bb2ca2 3570 return;
eeb9b112
JF
3571 }
3572
3573 if (result != pkgPackageManager::Completed) {
3574 _trace();
36bb2ca2 3575 return;
eeb9b112 3576 }
a0be02eb 3577
a72074b2
JF
3578 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3579 pkgSourceList list;
670a0494
JF
3580 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3581 return;
a72074b2
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];
ec97ef06
JF
3588}
3589
670a0494
JF
3590- (bool) upgrade {
3591 NSString *title(UCLocalize("UPGRADE"));
3592 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3593 return false;
3594 return true;
c7c6384e
JF
3595}
3596
36bb2ca2
JF
3597- (void) update {
3598 [self updateWithStatus:status_];
3599}
b4d89997 3600
7623f855
JF
3601- (void) setVisible {
3602 for (Package *package in packages_)
3603 [package setVisible];
3604}
3605
670a0494
JF
3606- (void) updateWithStatus:(Status &)status {
3607 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3608 NSString *title(UCLocalize("REFRESHING_DATA"));
3609
36bb2ca2 3610 pkgSourceList list;
670a0494
JF
3611 if (!list.ReadMainList())
3612 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
b4d89997 3613
36bb2ca2
JF
3614 FileFd lock;
3615 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
670a0494
JF
3616 if ([self popErrorWithTitle:title])
3617 return;
18873623 3618
670a0494 3619 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
ef348024 3620 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
36bb2ca2 3621
7623f855
JF
3622 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3623 Changed_ = true;
b4d89997
JF
3624}
3625
36bb2ca2
JF
3626- (void) setDelegate:(id)delegate {
3627 delegate_ = delegate;
3628 status_.setDelegate(delegate);
3629 progress_.setDelegate(delegate);
3630}
b4d89997 3631
7376b55c 3632- (Source *) getSource:(pkgCache::PkgFileIterator)file {
20cb1497
JF
3633 SourceMap::const_iterator i(sources_.find(file->ID));
3634 return i == sources_.end() ? nil : i->second;
b19871dd
JF
3635}
3636
36bb2ca2
JF
3637@end
3638/* }}} */
b4d89997 3639
adb61bda 3640/* Confirmation Controller {{{ */
43f3d7f6
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;
c390d3ab 3654}
b5e7eebb 3655/* }}} */
c390d3ab 3656
43f3d7f6
JF
3657/* Web Scripting {{{ */
3658@interface CydiaObject : NSObject {
3659 id indirect_;
77801ff1 3660 id delegate_;
43f3d7f6 3661}
c390d3ab 3662
43f3d7f6 3663- (id) initWithDelegate:(IndirectDelegate *)indirect;
c390d3ab
JF
3664@end
3665
43f3d7f6 3666@implementation CydiaObject
c390d3ab
JF
3667
3668- (void) dealloc {
43f3d7f6 3669 [indirect_ release];
c390d3ab
JF
3670 [super dealloc];
3671}
3672
43f3d7f6
JF
3673- (id) initWithDelegate:(IndirectDelegate *)indirect {
3674 if ((self = [super init]) != nil) {
3675 indirect_ = [indirect retain];
3676 } return self;
3677}
3678
77801ff1
JF
3679- (void) setDelegate:(id)delegate {
3680 delegate_ = delegate;
3681}
3682
43f3d7f6
JF
3683+ (NSArray *) _attributeKeys {
3684 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3685}
3686
3687- (NSArray *) attributeKeys {
3688 return [[self class] _attributeKeys];
c390d3ab
JF
3689}
3690
43f3d7f6
JF
3691+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3692 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
c390d3ab 3693}
43f3d7f6
JF
3694
3695- (NSString *) device {
3696 return [[UIDevice currentDevice] uniqueIdentifier];
c390d3ab
JF
3697}
3698
43f3d7f6
JF
3699#if 0 // XXX: implement!
3700- (NSString *) mac {
3701 if (![indirect_ promptForSensitive:@"Mac Address"])
3702 return nil;
affeffc7
JF
3703}
3704
43f3d7f6
JF
3705- (NSString *) serial {
3706 if (![indirect_ promptForSensitive:@"Serial #"])
3707 return nil;
3708}
86316a91 3709
43f3d7f6
JF
3710- (NSString *) firewire {
3711 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3712 return nil;
affeffc7
JF
3713}
3714
43f3d7f6
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";
8cc8eb1c
JF
3724 else if (selector == @selector(getInstalledPackages))
3725 return @"getInstalledPackages";
43f3d7f6
JF
3726 else if (selector == @selector(getPackageById:))
3727 return @"getPackageById";
77801ff1
JF
3728 else if (selector == @selector(installPackages:))
3729 return @"installPackages";
43f3d7f6
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";
ef055c6c
JF
3742 else if (selector == @selector(setToken:))
3743 return @"setToken";
43f3d7f6
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";
c390d3ab 3756 else
43f3d7f6
JF
3757 return nil;
3758}
3759
3760+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3761 return [self webScriptNameForSelector:selector] == nil;
c390d3ab
JF
3762}
3763
43f3d7f6
JF
3764- (BOOL) supports:(NSString *)feature {
3765 return [feature isEqualToString:@"window.open"];
3766}
c390d3ab 3767
8cc8eb1c
JF
3768- (NSArray *) getInstalledPackages {
3769 NSArray *packages([[Database sharedInstance] packages]);
3770 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
77801ff1 3771 for (Package *package in packages)
8cc8eb1c
JF
3772 if ([package installed] != nil)
3773 [installed addObject:package];
3774 return installed;
3775}
3776
43f3d7f6 3777- (Package *) getPackageById:(NSString *)id {
043e6a2e
JF
3778 Package *package([[Database sharedInstance] packageWithName:id]);
3779 [package parse];
3780 return package;
43f3d7f6
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
77801ff1
JF
3844- (void) installPackages:(NSArray *)packages {
3845 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3846}
3847
43f3d7f6
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
ef055c6c
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
43f3d7f6
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 {
a95e0405
JF
3895 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3896 value = nil;
43f3d7f6
JF
3897 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3898 table = nil;
3899 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
c390d3ab
JF
3900}
3901
3902@end
3903/* }}} */
f79a4512 3904
b5e7eebb
GP
3905/* Cydia View Controller {{{ */
3906@interface CYViewController : UCViewController { }
3907@end
3908
3909@implementation CYViewController
3910@end
3911/* }}} */
3912
40bfa2e6 3913@interface CYBrowserController : BrowserController {
43f3d7f6
JF
3914 CydiaObject *cydia_;
3915}
a9a0661e 3916
43f3d7f6
JF
3917@end
3918
b5e7eebb 3919@implementation CYBrowserController
43f3d7f6
JF
3920
3921- (void) dealloc {
3922 [cydia_ release];
3923 [super dealloc];
3924}
3925
01d93940
JF
3926- (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3927}
3928
43f3d7f6
JF
3929- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3930 [super webView:sender didClearWindowObject:window forFrame:frame];
01d93940
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
77801ff1
JF
3947 if (
3948 [host isEqualToString:@"cydia.saurik.com"] ||
3949 [host hasSuffix:@".cydia.saurik.com"] ||
3950 [scheme isEqualToString:@"file"]
3951 )
ef055c6c 3952 [window setValue:cydia_ forKey:@"cydia"];
43f3d7f6
JF
3953}
3954
bfc87a4d
JF
3955- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3956 if (System_ != NULL)
3957 [request setValue:System_ forHTTPHeaderField:@"X-System"];
43f3d7f6 3958 if (Machine_ != NULL)
bfc87a4d 3959 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
01d93940
JF
3960 if (Token_ != nil)
3961 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
43f3d7f6 3962 if (Role_ != nil)
bfc87a4d
JF
3963 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3964}
43f3d7f6 3965
bfc87a4d
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];
43f3d7f6 3969 return copy;
a9a0661e
JF
3970}
3971
77801ff1
JF
3972- (void) setDelegate:(id)delegate {
3973 [super setDelegate:delegate];
3974 [cydia_ setDelegate:delegate];
3975}
3976
b5e7eebb
GP
3977- (id) init {
3978 if ((self = [super initWithWidth:[[self view] bounds].size.width ofClass:[CYBrowserController class]]) != nil) {
43f3d7f6
JF
3979 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3980
aeed65a6 3981 WebView *webview([document_ webView]);
43f3d7f6
JF
3982
3983 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
35bf217f 3984
43f3d7f6
JF
3985 NSString *application = package == nil ? @"Cydia" : [NSString
3986 stringWithFormat:@"Cydia/%@",
3987 [package installed]
3988 ];
3989
43f3d7f6 3990 if (Safari_ != nil)
9ef18597 3991 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
35bf217f 3992 if (Build_ != nil)
9ef18597 3993 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
35bf217f 3994 if (Product_ != nil)
9ef18597 3995 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
43f3d7f6
JF
3996
3997 [webview setApplicationNameForUserAgent:application];
3998 } return self;
3999}
4000
4001@end
4002
adb61bda 4003@protocol ConfirmationControllerDelegate
674dce72 4004- (void) cancelAndClear:(bool)clear;
b5e7eebb 4005- (void) confirmWithNavigationController:(UINavigationController *)navigation;
dc63e78f 4006- (void) queue;
36bb2ca2 4007@end
2367a917 4008
adb61bda 4009@interface ConfirmationController : CYBrowserController {
770f2a8e 4010 _transient Database *database_;
3272e699 4011 UIAlertView *essential_;
affeffc7
JF
4012 NSArray *changes_;
4013 NSArray *issues_;
4014 NSArray *sizes_;
a9a0661e 4015 BOOL substrate_;
36bb2ca2 4016}
dc5812ec 4017
b5e7eebb 4018- (id) initWithDatabase:(Database *)database;
b4d89997 4019
dc5812ec
JF
4020@end
4021
adb61bda 4022@implementation ConfirmationController
dc5812ec 4023
2367a917 4024- (void) dealloc {
affeffc7
JF
4025 [changes_ release];
4026 if (issues_ != nil)
4027 [issues_ release];
4028 [sizes_ release];
36bb2ca2
JF
4029 if (essential_ != nil)
4030 [essential_ release];
2367a917
JF
4031 [super dealloc];
4032}
4033
b5e7eebb 4034- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3272e699 4035 NSString *context([alert context]);
9bedffaa 4036
1cedb821 4037 if ([context isEqualToString:@"remove"]) {
b5e7eebb
GP
4038 if (button == [alert cancelButtonIndex]) {
4039 [self dismissModalViewControllerAnimated:YES];
3272e699 4040 } else if (button == [alert firstOtherButtonIndex]) {
b5e7eebb
GP
4041 if (substrate_)
4042 Finish_ = 2;
4043 [delegate_ confirmWithNavigationController:[self navigationController]];
9bedffaa 4044 }
9bedffaa 4045
3272e699 4046 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 4047 } else if ([context isEqualToString:@"unable"]) {
b5e7eebb 4048 [self dismissModalViewControllerAnimated:YES];
3272e699
GP
4049 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4050 } else {
b5e7eebb
GP
4051 [super alertView:alert clickedButtonAtIndex:button];
4052 }
36bb2ca2
JF
4053}
4054
21ea11a4
GP
4055- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4056 [self dismissModalViewControllerAnimated:YES];
4057 [delegate_ cancelAndClear:NO];
4058
4059 return nil;
4060}
4061
affeffc7 4062- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
f79a4512 4063 [super webView:sender didClearWindowObject:window forFrame:frame];
affeffc7
JF
4064 [window setValue:changes_ forKey:@"changes"];
4065 [window setValue:issues_ forKey:@"issues"];
4066 [window setValue:sizes_ forKey:@"sizes"];
21ea11a4 4067 [window setValue:self forKey:@"queue"];
36bb2ca2
JF
4068}
4069
b5e7eebb
GP
4070- (id) initWithDatabase:(Database *)database {
4071 if ((self = [super init]) != nil) {
770f2a8e
JF
4072 database_ = database;
4073
b5e7eebb
GP
4074 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4075
36bb2ca2
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];
dc5812ec 4081
36bb2ca2 4082 bool remove(false);
dc5812ec 4083
a9a0661e
JF
4084 pkgDepCache::Policy *policy([database_ policy]);
4085
36bb2ca2 4086 pkgCacheFile &cache([database_ cache]);
2388b078 4087 NSArray *packages = [database_ packages];
c4dcf2c2 4088 for (Package *package in packages) {
2388b078 4089 pkgCache::PkgIterator iterator = [package iterator];
36bb2ca2 4090 pkgDepCache::StateCache &state(cache[iterator]);
dc5812ec 4091
2388b078
JF
4092 NSString *name([package name]);
4093
36bb2ca2
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()) {
2388b078 4103 if ([package essential])
36bb2ca2
JF
4104 remove = true;
4105 [removing addObject:name];
a9a0661e
JF
4106 } else continue;
4107
4108 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4109 substrate_ |= DepSubstrate(iterator.CurrentVer());
36bb2ca2 4110 }
ec97ef06 4111
36bb2ca2
JF
4112 if (!remove)
4113 essential_ = nil;
d791dce4 4114 else if (Advanced_) {
43f3d7f6 4115 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
f79a4512 4116
3272e699 4117 essential_ = [[UIAlertView alloc]
43f3d7f6 4118 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
b5e7eebb
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 ];
04fe1349 4124
3272e699 4125 [essential_ setContext:@"remove"];
9bedffaa 4126 } else {
3272e699 4127 essential_ = [[UIAlertView alloc]
43f3d7f6 4128 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
b5e7eebb
GP
4129 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4130 delegate:self
4131 cancelButtonTitle:UCLocalize("OKAY")
4132 otherButtonTitles:nil
36bb2ca2 4133 ];
ec97ef06 4134
b5e7eebb 4135 [essential_ setContext:@"unable"];
36bb2ca2 4136 }
ec97ef06 4137
affeffc7
JF
4138 changes_ = [[NSArray alloc] initWithObjects:
4139 installing,
4140 reinstalling,
4141 upgrading,
4142 downgrading,
4143 removing,
4144 nil];
dc5812ec 4145
affeffc7
JF
4146 issues_ = [database_ issues];
4147 if (issues_ != nil)
4148 issues_ = [issues_ retain];
dc5812ec 4149
affeffc7
JF
4150 sizes_ = [[NSArray alloc] initWithObjects:
4151 SizeString([database_ fetcher].FetchNeeded()),
4152 SizeString([database_ fetcher].PartialPresent()),
affeffc7 4153 nil];
dc5812ec 4154
affeffc7 4155 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
04fe1349 4156
b5e7eebb 4157 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
21c6da4b
GP
4158 initWithTitle:UCLocalize("CANCEL")
4159 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
b5e7eebb
GP
4160 style:UIBarButtonItemStylePlain
4161 target:self
4162 action:@selector(cancelButtonClicked)
4163 ];
4164 [[self navigationItem] setLeftBarButtonItem:leftItem];
4165 [leftItem release];
36bb2ca2 4166 } return self;
b4d89997 4167}
8da60fb7 4168
40bfa2e6 4169- (void) applyRightButton {
b5e7eebb
GP
4170 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4171 initWithTitle:UCLocalize("CONFIRM")
4172 style:UIBarButtonItemStylePlain
4173 target:self
4174 action:@selector(confirmButtonClicked)
4175 ];
4176#if !AlwaysReload && !IgnoreInstall
40bfa2e6
GP
4177 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4178 else [super applyRightButton];
4179#else
4180 [[self navigationItem] setRightBarButtonItem:nil];
b5e7eebb
GP
4181#endif
4182 [rightItem release];
affeffc7
JF
4183}
4184
b5e7eebb 4185- (void) cancelButtonClicked {
21ea11a4
GP
4186 [self dismissModalViewControllerAnimated:YES];
4187 [delegate_ cancelAndClear:YES];
affeffc7
JF
4188}
4189
9487f027 4190#if !AlwaysReload
b5e7eebb 4191- (void) confirmButtonClicked {
b0ad8dee 4192#if IgnoreInstall
b5e7eebb 4193 return;
b0ad8dee 4194#endif
affeffc7 4195 if (essential_ != nil)
b5e7eebb 4196 [essential_ show];
affeffc7
JF
4197 else {
4198 if (substrate_)
4199 Finish_ = 2;
b5e7eebb 4200 [delegate_ confirmWithNavigationController:[self navigationController]];
affeffc7
JF
4201 }
4202}
9487f027 4203#endif
affeffc7 4204
36bb2ca2
JF
4205@end
4206/* }}} */
8da60fb7 4207
36bb2ca2
JF
4208/* Progress Data {{{ */
4209@interface ProgressData : NSObject {
4210 SEL selector_;
4211 id target_;
4212 id object_;
dc5812ec
JF
4213}
4214
36bb2ca2 4215- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
b4d89997 4216
36bb2ca2
JF
4217- (SEL) selector;
4218- (id) target;
4219- (id) object;
4220@end
b4d89997 4221
36bb2ca2 4222@implementation ProgressData
b4d89997 4223
36bb2ca2
JF
4224- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4225 if ((self = [super init]) != nil) {
4226 selector_ = selector;
4227 target_ = target;
4228 object_ = object;
4229 } return self;
4230}
b4d89997 4231
36bb2ca2
JF
4232- (SEL) selector {
4233 return selector_;
4234}
b4d89997 4235
36bb2ca2
JF
4236- (id) target {
4237 return target_;
8da60fb7
JF
4238}
4239
36bb2ca2
JF
4240- (id) object {
4241 return object_;
dc5812ec
JF
4242}
4243
2367a917
JF
4244@end
4245/* }}} */
adb61bda
GP
4246/* Progress Controller {{{ */
4247@interface ProgressController : CYViewController <
8b29f8e6 4248 ConfigurationDelegate,
36bb2ca2
JF
4249 ProgressDelegate
4250> {
8b29f8e6 4251 _transient Database *database_;
36bb2ca2
JF
4252 UIProgressBar *progress_;
4253 UITextView *output_;
4254 UITextLabel *status_;
31f3cfff 4255 UIPushButton *close_;
bd150f54 4256 BOOL running_;
dddbc481 4257 SHA1SumValue springlist_;
22f8bed9 4258 SHA1SumValue notifyconf_;
670a0494 4259 NSString *title_;
2367a917
JF
4260}
4261
b5e7eebb 4262- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
2367a917 4263
36bb2ca2
JF
4264- (void) _retachThread;
4265- (void) _detachNewThreadData:(ProgressData *)data;
4266- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
2367a917 4267
bd150f54
JF
4268- (BOOL) isRunning;
4269
2367a917
JF
4270@end
4271
adb61bda
GP
4272@protocol ProgressControllerDelegate
4273- (void) progressControllerIsComplete:(ProgressController *)sender;
36bb2ca2
JF
4274@end
4275
adb61bda 4276@implementation ProgressController
2367a917
JF
4277
4278- (void) dealloc {
b5e7eebb 4279 [database_ setDelegate:nil];
36bb2ca2
JF
4280 [progress_ release];
4281 [output_ release];
4282 [status_ release];
31f3cfff 4283 [close_ release];
670a0494
JF
4284 if (title_ != nil)
4285 [title_ release];
2367a917
JF
4286 [super dealloc];
4287}
4288
b5e7eebb
GP
4289- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4290 if ((self = [super init]) != nil) {
8b29f8e6 4291 database_ = database;
b5e7eebb 4292 [database_ setDelegate:self];
36bb2ca2 4293 delegate_ = delegate;
ec97ef06 4294
b5e7eebb 4295 [[self view] setBackgroundColor:(CGColor *)[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
2367a917 4296
b5e7eebb 4297 progress_ = [[UIProgressBar alloc] init];
04fe1349 4298 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
31f3cfff 4299 [progress_ setStyle:0];
ec97ef06 4300
b5e7eebb 4301 status_ = [[UITextLabel alloc] init];
04fe1349 4302 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
baf80942
JF
4303 [status_ setColor:[UIColor whiteColor]];
4304 [status_ setBackgroundColor:[UIColor clearColor]];
36bb2ca2
JF
4305 [status_ setCentersHorizontally:YES];
4306 //[status_ setFont:font];
ec97ef06 4307
b5e7eebb 4308 output_ = [[UITextView alloc] init];
1d80f6b9 4309
04fe1349 4310 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
36bb2ca2 4311 //[output_ setTextFont:@"Courier New"];
d791dce4 4312 [output_ setFont:[[output_ font] fontWithSize:12]];
baf80942
JF
4313 [output_ setTextColor:[UIColor whiteColor]];
4314 [output_ setBackgroundColor:[UIColor clearColor]];
36bb2ca2
JF
4315 [output_ setMarginTop:0];
4316 [output_ setAllowsRubberBanding:YES];
795d26fc 4317 [output_ setEditable:NO];
b5e7eebb 4318 [[self view] addSubview:output_];
b4d89997 4319
b5e7eebb 4320 close_ = [[UIPushButton alloc] init];
04fe1349 4321 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
31f3cfff
JF
4322 [close_ setAutosizesToFit:NO];
4323 [close_ setDrawsShadow:YES];
4324 [close_ setStretchBackground:YES];
31f3cfff 4325 [close_ setEnabled:YES];
b5e7eebb 4326 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
bfc87a4d 4327 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
31f3cfff
JF
4328 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4329 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
36bb2ca2 4330 } return self;
2367a917
JF
4331}
4332
b5e7eebb
GP
4333- (void) positionViews {
4334 CGRect bounds = [[self view] bounds];
4335 CGSize prgsize = [UIProgressBar defaultSize];
4336
4337 CGRect prgrect = {{
4338 (bounds.size.width - prgsize.width) / 2,
4339 bounds.size.height - prgsize.height - 64
4340 }, prgsize};
4341
4342 float closewidth = bounds.size.width - 20;
4343 if (closewidth > 300) closewidth = 300;
4344
4345 [progress_ setFrame:prgrect];
4346 [status_ setFrame:CGRectMake(
4347 10,
4348 bounds.size.height - prgsize.height - 94,
4349 bounds.size.width - 20,
4350 24
4351 )];
4352 [output_ setFrame:CGRectMake(
4353 10,
4354 20,
4355 bounds.size.width - 20,
4356 bounds.size.height - 106
4357 )];
4358 [close_ setFrame:CGRectMake(
4359 (bounds.size.width - closewidth) / 2,
4360 bounds.size.height - prgsize.height - 94,
4361 closewidth,
4362 32 + prgsize.height
4363 )];
4364}
4365
4366- (void) viewWillAppear:(BOOL)animated {
4367 [super viewDidAppear:animated];
4368 [[self navigationItem] setHidesBackButton:YES];
4369 [[[self navigationController] navigationBar] setBarStyle:1];
4370
4371 [self positionViews];
2367a917
JF
4372}
4373
b5e7eebb
GP
4374- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4375 [self positionViews];
2367a917
JF
4376}
4377
b5e7eebb 4378- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
969eaf2f 4379 NSString *context([alert context]);
bc8cd583 4380
670a0494 4381 if ([context isEqualToString:@"conffile"]) {
b5e7eebb 4382 FILE *input = [database_ input];
969eaf2f
GP
4383 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4384 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
b5e7eebb 4385 fflush(input);
670a0494
JF
4386 }
4387}
4388
4389- (void) closeButtonPushed {
4390 running_ = NO;
4391
ef494bd8
RP
4392 UpdateExternalStatus(0);
4393
670a0494
JF
4394 switch (Finish_) {
4395 case 0:
b5e7eebb 4396 [self dismissModalViewControllerAnimated:YES];
670a0494
JF
4397 break;
4398
4399 case 1:
c4899376
JF
4400 [delegate_ terminateWithSuccess];
4401 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4402 [delegate_ suspendWithAnimation:YES];
4403 else
4404 [delegate_ suspend];*/
670a0494
JF
4405 break;
4406
4407 case 2:
4408 system("launchctl stop com.apple.SpringBoard");
4409 break;
4410
4411 case 3:
4412 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4413 break;
4414
4415 case 4:
4416 system("reboot");
4417 break;
bc8cd583 4418 }
670a0494 4419}
bd150f54 4420
670a0494 4421- (void) _retachThread {
b5e7eebb 4422 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
670a0494 4423
b5e7eebb 4424 [[self view] addSubview:close_];
670a0494
JF
4425 [progress_ removeFromSuperview];
4426 [status_ removeFromSuperview];
4427
4428 [database_ popErrorWithTitle:title_];
adb61bda 4429 [delegate_ progressControllerIsComplete:self];
c390d3ab 4430
22f8bed9 4431 if (Finish_ < 4) {
70d45c1e
JF
4432 FileFd file;
4433 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4434 _error->Discard();
4435 else {
4436 MMap mmap(file, MMap::ReadOnly);
4437 SHA1Summation sha1;
4438 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4439 if (!(notifyconf_ == sha1.Result()))
4440 Finish_ = 4;
4441 }
22f8bed9
JF
4442 }
4443
affeffc7 4444 if (Finish_ < 3) {
70d45c1e
JF
4445 FileFd file;
4446 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4447 _error->Discard();
4448 else {
4449 MMap mmap(file, MMap::ReadOnly);
4450 SHA1Summation sha1;
4451 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4452 if (!(springlist_ == sha1.Result()))
4453 Finish_ = 3;
4454 }
dddbc481
JF
4455 }
4456
bc8cd583 4457 switch (Finish_) {
b5e7eebb 4458 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
43f3d7f6
JF
4459 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4460 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4461 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4462 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
bc8cd583
JF
4463 }
4464
58241d4c 4465 system("su -c /usr/bin/uicache mobile");
c4ce98df 4466
ef494bd8
RP
4467 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4468
bd150f54 4469 [delegate_ setStatusBarShowsProgress:NO];
31f3cfff
JF
4470}
4471
affeffc7 4472- (void) _detachNewThreadData:(ProgressData *)data { _pooled
36bb2ca2
JF
4473 [[data target] performSelector:[data selector] withObject:[data object]];
4474 [data release];
b19871dd 4475
36bb2ca2 4476 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
b19871dd
JF
4477}
4478
36bb2ca2 4479- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
ef494bd8
RP
4480 UpdateExternalStatus(1);
4481
670a0494
JF
4482 if (title_ != nil)
4483 [title_ release];
4484 if (title == nil)
4485 title_ = nil;
4486 else
4487 title_ = [title retain];
4488
b5e7eebb 4489 [[self navigationItem] setTitle:title_];
b4d89997 4490
36bb2ca2
JF
4491 [status_ setText:nil];
4492 [output_ setText:@""];
4493 [progress_ setProgress:0];
b19871dd 4494
31f3cfff 4495 [close_ removeFromSuperview];
b5e7eebb
GP
4496 [[self view] addSubview:progress_];
4497 [[self view] addSubview:status_];
31f3cfff 4498
bd150f54
JF
4499 [delegate_ setStatusBarShowsProgress:YES];
4500 running_ = YES;
4501
22f8bed9 4502 {
70d45c1e
JF
4503 FileFd file;
4504 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4505 _error->Discard();
4506 else {
4507 MMap mmap(file, MMap::ReadOnly);
4508 SHA1Summation sha1;
4509 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4510 notifyconf_ = sha1.Result();
4511 }
22f8bed9
JF
4512 }
4513
affeffc7 4514 {
70d45c1e
JF
4515 FileFd file;
4516 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4517 _error->Discard();
4518 else {
4519 MMap mmap(file, MMap::ReadOnly);
4520 SHA1Summation sha1;
4521 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4522 springlist_ = sha1.Result();
4523 }
dddbc481
JF
4524 }
4525
36bb2ca2
JF
4526 [NSThread
4527 detachNewThreadSelector:@selector(_detachNewThreadData:)
4528 toTarget:self
4529 withObject:[[ProgressData alloc]
4530 initWithSelector:selector
4531 target:target
4532 object:object
4533 ]
4534 ];
b19871dd
JF
4535}
4536
5a09ae08
JF
4537- (void) repairWithSelector:(SEL)selector {
4538 [self
4539 detachNewThreadSelector:selector
4540 toTarget:database_
4541 withObject:nil
43f3d7f6 4542 title:UCLocalize("REPAIRING")
5a09ae08
JF
4543 ];
4544}
4545
8b29f8e6
JF
4546- (void) setConfigurationData:(NSString *)data {
4547 [self
4548 performSelectorOnMainThread:@selector(_setConfigurationData:)
4549 withObject:data
4550 waitUntilDone:YES
4551 ];
4552}
4553
670a0494
JF
4554- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4555 CYActionSheet *sheet([[[CYActionSheet alloc]
4556 initWithTitle:title
43f3d7f6 4557 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
31f3cfff 4558 defaultButtonIndex:0
670a0494 4559 ] autorelease]);
31f3cfff 4560
be2b3d7b 4561 [sheet setMessage:error];
670a0494
JF
4562 [sheet yieldToPopupAlertAnimated:YES];
4563 [sheet dismiss];
b19871dd
JF
4564}
4565
36bb2ca2
JF
4566- (void) setProgressTitle:(NSString *)title {
4567 [self
4568 performSelectorOnMainThread:@selector(_setProgressTitle:)
4569 withObject:title
4570 waitUntilDone:YES
4571 ];
b19871dd
JF
4572}
4573
36bb2ca2
JF
4574- (void) setProgressPercent:(float)percent {
4575 [self
4576 performSelectorOnMainThread:@selector(_setProgressPercent:)
4577 withObject:[NSNumber numberWithFloat:percent]
4578 waitUntilDone:YES
4579 ];
b19871dd
JF
4580}
4581
baf80942 4582- (void) startProgress {
baf80942
JF
4583}
4584
36bb2ca2
JF
4585- (void) addProgressOutput:(NSString *)output {
4586 [self
4587 performSelectorOnMainThread:@selector(_addProgressOutput:)
4588 withObject:output
4589 waitUntilDone:YES
4590 ];
b19871dd
JF
4591}
4592
baf80942 4593- (bool) isCancelling:(size_t)received {
baf80942
JF
4594 return false;
4595}
4596
8b29f8e6 4597- (void) _setConfigurationData:(NSString *)data {
7b0ce2da
JF
4598 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4599
670a0494
JF
4600 if (!conffile_r(data)) {
4601 lprintf("E:invalid conffile\n");
4602 return;
4603 }
8b29f8e6
JF
4604
4605 NSString *ofile = conffile_r[1];
4606 //NSString *nfile = conffile_r[2];
4607
969eaf2f 4608 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 4609 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
b5e7eebb
GP
4610 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4611 delegate:self
4612 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4613 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
969eaf2f 4614 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
b5e7eebb
GP
4615 nil
4616 ] autorelease];
969eaf2f 4617
b5e7eebb 4618 [alert setContext:@"conffile"];
969eaf2f 4619 [alert show];
8b29f8e6
JF
4620}
4621
36bb2ca2 4622- (void) _setProgressTitle:(NSString *)title {
9487f027
JF
4623 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4624 for (size_t i(0), e([words count]); i != e; ++i) {
4625 NSString *word([words objectAtIndex:i]);
4626 if (Package *package = [database_ packageWithName:word])
4627 [words replaceObjectAtIndex:i withObject:[package name]];
4628 }
4629
4630 [status_ setText:[words componentsJoinedByString:@" "]];
b4d89997 4631}
b19871dd 4632
36bb2ca2
JF
4633- (void) _setProgressPercent:(NSNumber *)percent {
4634 [progress_ setProgress:[percent floatValue]];
49048579
JF
4635}
4636
36bb2ca2
JF
4637- (void) _addProgressOutput:(NSString *)output {
4638 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4639 CGSize size = [output_ contentSize];
4640 CGRect rect = {{0, size.height}, {size.width, 0}};
4641 [output_ scrollRectToVisible:rect animated:YES];
4642}
dc088e63 4643
bd150f54 4644- (BOOL) isRunning {
c4ce98df 4645 return running_;
bd150f54
JF
4646}
4647
36bb2ca2
JF
4648@end
4649/* }}} */
dc088e63 4650
46aa9775 4651/* Cell Content View {{{ */
327624b6
JF
4652@interface ContentView : UIView {
4653 _transient id delegate_;
4654}
4655
4656@end
4657
46aa9775
GP
4658@implementation ContentView
4659- (id) initWithFrame:(CGRect)frame {
4660 if ((self = [super initWithFrame:frame]) != nil) {
4661 /* Fix landscape stretching. */
4662 [self setNeedsDisplayOnBoundsChange:YES];
4663 } return self;
4664}
4665
4666- (void) setDelegate:(id)delegate {
4667 delegate_ = delegate;
4668}
4669
4670- (void) drawRect:(CGRect)rect {
4671 [super drawRect:rect];
4672 [delegate_ drawContentRect:rect];
4673}
4674@end
4675/* }}} */
4676/* Package Cell {{{ */
327624b6 4677@interface PackageCell : UITableViewCell {
f641a0e5
JF
4678 UIImage *icon_;
4679 NSString *name_;
4680 NSString *description_;
3bd1c2a2 4681 bool commercial_;
f641a0e5 4682 NSString *source_;
c390d3ab 4683 UIImage *badge_;
dc63e78f 4684 Package *package_;
327624b6
JF
4685 UIColor *color_;
4686 ContentView *content_;
4687 BOOL faded_;
4688 float fade_;
670a0494 4689 UIImage *placard_;
36bb2ca2 4690}
723a0072 4691
36bb2ca2
JF
4692- (PackageCell *) init;
4693- (void) setPackage:(Package *)package;
ec97ef06 4694
9bedffaa 4695+ (int) heightForPackage:(Package *)package;
327624b6
JF
4696- (void) drawContentRect:(CGRect)rect;
4697
4698@end
4699
36bb2ca2
JF
4700@implementation PackageCell
4701
f641a0e5
JF
4702- (void) clearPackage {
4703 if (icon_ != nil) {
4704 [icon_ release];
4705 icon_ = nil;
4706 }
4707
4708 if (name_ != nil) {
4709 [name_ release];
4710 name_ = nil;
4711 }
4712
4713 if (description_ != nil) {
4714 [description_ release];
4715 description_ = nil;
4716 }
4717
4718 if (source_ != nil) {
4719 [source_ release];
4720 source_ = nil;
4721 }
c390d3ab
JF
4722
4723 if (badge_ != nil) {
4724 [badge_ release];
4725 badge_ = nil;
4726 }
dc63e78f 4727
670a0494
JF
4728 if (placard_ != nil) {
4729 [placard_ release];
4730 placard_ = nil;
4731 }
4732
dc63e78f
JF
4733 [package_ release];
4734 package_ = nil;
f641a0e5
JF
4735}
4736
36bb2ca2 4737- (void) dealloc {
f641a0e5 4738 [self clearPackage];
327624b6
JF
4739 [content_ release];
4740 [color_ release];
36bb2ca2 4741 [super dealloc];
b4d89997 4742}
b19871dd 4743
327624b6
JF
4744- (float) fade {
4745 return faded_ ? [self selectionPercent] : fade_;
4746}
4747
36bb2ca2 4748- (PackageCell *) init {
327624b6
JF
4749 CGRect frame(CGRectMake(0, 0, 320, 74));
4750 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4751 UIView *content([self contentView]);
4752 CGRect bounds([content bounds]);
04fe1349 4753
327624b6 4754 content_ = [[ContentView alloc] initWithFrame:bounds];
04fe1349
JF
4755 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4756 [content addSubview:content_];
4757
327624b6 4758 [content_ setDelegate:self];
327624b6 4759 [content_ setOpaque:YES];
327624b6
JF
4760 if ([self respondsToSelector:@selector(selectionPercent)])
4761 faded_ = YES;
36bb2ca2 4762 } return self;
b4d89997 4763}
b19871dd 4764
327624b6
JF
4765- (void) _setBackgroundColor {
4766 UIColor *color;
4767 if (NSString *mode = [package_ mode]) {
4768 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4769 color = remove ? RemovingColor_ : InstallingColor_;
4770 } else
4771 color = [UIColor whiteColor];
4772
4773 [content_ setBackgroundColor:color];
4774 [self setNeedsDisplay];
4775}
4776
36bb2ca2 4777- (void) setPackage:(Package *)package {
46dbfd32 4778 [self clearPackage];
68d927e2 4779 [package parse];
31f3cfff 4780
36bb2ca2 4781 Source *source = [package source];
b19871dd 4782
770f2a8e 4783 icon_ = [[package icon] retain];
f641a0e5 4784 name_ = [[package name] retain];
ef055c6c
JF
4785
4786 if (IsWildcat_)
4787 description_ = [package longDescription];
4788 if (description_ == nil)
4789 description_ = [package shortDescription];
4790 if (description_ != nil)
4791 description_ = [description_ retain];
4792
3bd1c2a2 4793 commercial_ = [package isCommercial];
36bb2ca2 4794
dc63e78f
JF
4795 package_ = [package retain];
4796
a54b1c10
JF
4797 NSString *label = nil;
4798 bool trusted = false;
b19871dd 4799
36bb2ca2
JF
4800 if (source != nil) {
4801 label = [source label];
4802 trusted = [source trusted];
a54b1c10 4803 } else if ([[package id] isEqualToString:@"firmware"])
43f3d7f6 4804 label = UCLocalize("APPLE");
7b0ce2da 4805 else
43f3d7f6 4806 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
b19871dd 4807
f79a4512 4808 NSString *from(label);
a54b1c10 4809
f79a4512
JF
4810 NSString *section = [package simpleSection];
4811 if (section != nil && ![section isEqualToString:label]) {
4812 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
43f3d7f6 4813 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
f79a4512 4814 }
a54b1c10 4815
43f3d7f6 4816 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
f641a0e5 4817 source_ = [from retain];
36bb2ca2 4818
c390d3ab
JF
4819 if (NSString *purpose = [package primaryPurpose])
4820 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4821 badge_ = [badge_ retain];
4822
670a0494
JF
4823 if ([package installed] != nil)
4824 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4825 placard_ = [placard_ retain];
4826
327624b6
JF
4827 [self _setBackgroundColor];
4828 [content_ setNeedsDisplay];
3bd1c2a2
JF
4829}
4830
327624b6
JF
4831- (void) drawContentRect:(CGRect)rect {
4832 bool selected([self isSelected]);
ef055c6c 4833 float width([self bounds].size.width);
dc63e78f 4834
327624b6
JF
4835#if 0
4836 CGContextRef context(UIGraphicsGetCurrentContext());
4837 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4838 CGContextFillRect(context, rect);
4839#endif
b19871dd 4840
baf80942
JF
4841 if (icon_ != nil) {
4842 CGRect rect;
4843 rect.size = [icon_ size];
4844
4845 rect.size.width /= 2;
4846 rect.size.height /= 2;
4847
4848 rect.origin.x = 25 - rect.size.width / 2;
4849 rect.origin.y = 25 - rect.size.height / 2;
4850
4851 [icon_ drawInRect:rect];
4852 }
b19871dd 4853
c390d3ab
JF
4854 if (badge_ != nil) {
4855 CGSize size = [badge_ size];
4856
4857 [badge_ drawAtPoint:CGPointMake(
4858 36 - size.width / 2,
4859 36 - size.height / 2
4860 )];
4861 }
4862
f641a0e5
JF
4863 if (selected)
4864 UISetColor(White_);
b19871dd 4865
f641a0e5 4866 if (!selected)
3bd1c2a2 4867 UISetColor(commercial_ ? Purple_ : Black_);
01d93940
JF
4868 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ ellipsis:2];
4869 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
b19871dd 4870
f641a0e5 4871 if (!selected)
3bd1c2a2 4872 UISetColor(commercial_ ? Purplish_ : Gray_);
01d93940 4873 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
670a0494
JF
4874
4875 if (placard_ != nil)
01d93940 4876 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
ec97ef06
JF
4877}
4878
327624b6
JF
4879- (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4880 //[self _setBackgroundColor];
4881 [super setSelected:selected animated:fade];
4882 [content_ setNeedsDisplay];
dc63e78f
JF
4883}
4884
9bedffaa 4885+ (int) heightForPackage:(Package *)package {
68d927e2 4886 return 73;
9bedffaa
JF
4887}
4888
8da60fb7
JF
4889@end
4890/* }}} */
36bb2ca2 4891/* Section Cell {{{ */
46aa9775 4892@interface SectionCell : UITableViewCell {
0010fa77 4893 NSString *basic_;
6d9712c4 4894 NSString *section_;
f641a0e5
JF
4895 NSString *name_;
4896 NSString *count_;
4897 UIImage *icon_;
46aa9775
GP
4898 ContentView *content_;
4899 id switch_;
6d9712c4 4900 BOOL editing_;
b4d89997 4901}
b19871dd 4902
36bb2ca2 4903- (id) init;
6d9712c4 4904- (void) setSection:(Section *)section editing:(BOOL)editing;
36bb2ca2 4905
8da60fb7
JF
4906@end
4907
36bb2ca2 4908@implementation SectionCell
8da60fb7 4909
f641a0e5 4910- (void) clearSection {
0010fa77 4911 if (basic_ != nil) {
e59669fd 4912 [basic_ release];
0010fa77
JF
4913 basic_ = nil;
4914 }
4915
f641a0e5 4916 if (section_ != nil) {
6d9712c4 4917 [section_ release];
f641a0e5
JF
4918 section_ = nil;
4919 }
7b0ce2da 4920
f641a0e5
JF
4921 if (name_ != nil) {
4922 [name_ release];
4923 name_ = nil;
4924 }
7b0ce2da 4925
f641a0e5
JF
4926 if (count_ != nil) {
4927 [count_ release];
4928 count_ = nil;
4929 }
7b0ce2da
JF
4930}
4931
f641a0e5
JF
4932- (void) dealloc {
4933 [self clearSection];
4934 [icon_ release];
4935 [switch_ release];
46aa9775
GP
4936 [content_ release];
4937
f641a0e5 4938 [super dealloc];
7b0ce2da
JF
4939}
4940
46aa9775
GP
4941- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4942 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
f641a0e5 4943 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
46aa9775
GP
4944 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4945 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4946
4947 UIView *content([self contentView]);
4948 CGRect bounds([content bounds]);
4949
4950 content_ = [[ContentView alloc] initWithFrame:bounds];
4951 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4952 [content addSubview:content_];
4953 [content_ setBackgroundColor:[UIColor whiteColor]];
4954
4955 [content_ setDelegate:self];
b4d89997 4956 } return self;
b19871dd
JF
4957}
4958
6d9712c4 4959- (void) onSwitch:(id)sender {
0010fa77 4960 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
6d9712c4
JF
4961 if (metadata == nil) {
4962 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
0010fa77 4963 [Sections_ setObject:metadata forKey:basic_];
6d9712c4
JF
4964 }
4965
4966 Changed_ = true;
46aa9775 4967 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6d9712c4
JF
4968}
4969
4970- (void) setSection:(Section *)section editing:(BOOL)editing {
4971 if (editing != editing_) {
4972 if (editing_)
4973 [switch_ removeFromSuperview];
4974 else
4975 [self addSubview:switch_];
4976 editing_ = editing;
4977 }
4978
f641a0e5 4979 [self clearSection];
6d9712c4 4980
36bb2ca2 4981 if (section == nil) {
43f3d7f6 4982 name_ = [UCLocalize("ALL_PACKAGES") retain];
f641a0e5 4983 count_ = nil;
36bb2ca2 4984 } else {
e59669fd 4985 basic_ = [section name];
0010fa77
JF
4986 if (basic_ != nil)
4987 basic_ = [basic_ retain];
4988
677b8415 4989 section_ = [section localized];
6d9712c4
JF
4990 if (section_ != nil)
4991 section_ = [section_ retain];
0010fa77 4992
43f3d7f6 4993 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
f641a0e5 4994 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
6d9712c4
JF
4995
4996 if (editing_)
46aa9775 4997 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
36bb2ca2 4998 }
46aa9775 4999
86c5b8f5 5000 [self setAccessoryType:editing ? 0 : 1 /*UITableViewCellAccessoryDisclosureIndicator*/];
46aa9775 5001 [content_ setNeedsDisplay];
f641a0e5
JF
5002}
5003
77801ff1
JF
5004- (void) setFrame:(CGRect)frame {
5005 [super setFrame:frame];
46aa9775 5006
77801ff1
JF
5007 CGRect rect([switch_ frame]);
5008 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5009}
5010
46aa9775
GP
5011- (void) drawContentRect:(CGRect)rect {
5012 BOOL selected = [self isSelected];
5013
f641a0e5
JF
5014 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5015
5016 if (selected)
5017 UISetColor(White_);
5018
5019 if (!selected)
5020 UISetColor(Black_);
58241d4c 5021
46aa9775 5022 float width(rect.size.width);
58241d4c 5023 if (editing_)
46aa9775 5024 width -= 87;
58241d4c 5025
01d93940 5026 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
6d9712c4 5027
f641a0e5
JF
5028 CGSize size = [count_ sizeWithFont:Font14_];
5029
5030 UISetColor(White_);
5031 if (count_ != nil)
c390d3ab 5032 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
b19871dd
JF
5033}
5034
36bb2ca2
JF
5035@end
5036/* }}} */
b19871dd 5037
ab398adf 5038/* File Table {{{ */
b5e7eebb 5039@interface FileTable : CYViewController {
36bb2ca2 5040 _transient Database *database_;
ab398adf
JF
5041 Package *package_;
5042 NSString *name_;
5043 NSMutableArray *files_;
46aa9775 5044 UITableView *list_;
ab398adf 5045}
b19871dd 5046
b5e7eebb 5047- (id) initWithDatabase:(Database *)database;
ab398adf
JF
5048- (void) setPackage:(Package *)package;
5049
5050@end
5051
5052@implementation FileTable
5053
5054- (void) dealloc {
5055 if (package_ != nil)
5056 [package_ release];
5057 if (name_ != nil)
5058 [name_ release];
5059 [files_ release];
5060 [list_ release];
5061 [super dealloc];
5062}
5063
46aa9775 5064- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
ab398adf
JF
5065 return files_ == nil ? 0 : [files_ count];
5066}
5067
21ea11a4
GP
5068/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5069 return 24.0f;
5070}*/
ab398adf 5071
46aa9775 5072- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
GP
5073 static NSString *reuseIdentifier = @"Cell";
5074
46aa9775
GP
5075 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5076 if (cell == nil) {
5077 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5078 [cell setFont:[UIFont systemFontOfSize:16]];
ab398adf 5079 }
46aa9775
GP
5080 [cell setText:[files_ objectAtIndex:indexPath.row]];
5081 [cell setSelectionStyle:0 /*UITableViewCellSelectionStyleNone*/];
b5e7eebb 5082
46aa9775 5083 return cell;
ab398adf 5084}
b19871dd 5085
b5e7eebb
GP
5086- (id) initWithDatabase:(Database *)database {
5087 if ((self = [super init]) != nil) {
ab398adf 5088 database_ = database;
b19871dd 5089
b5e7eebb
GP
5090 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5091
ab398adf 5092 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
8da60fb7 5093
46aa9775 5094 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
21ea11a4
GP
5095 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5096 [list_ setRowHeight:24.0f];
b5e7eebb 5097 [[self view] addSubview:list_];
ab398adf 5098
ab398adf 5099 [list_ setDataSource:self];
ab398adf 5100 [list_ setDelegate:self];
ab398adf
JF
5101 } return self;
5102}
5103
5104- (void) setPackage:(Package *)package {
5105 if (package_ != nil) {
5106 [package_ autorelease];
5107 package_ = nil;
5108 }
5109
5110 if (name_ != nil) {
5111 [name_ release];
5112 name_ = nil;
5113 }
5114
5115 [files_ removeAllObjects];
5116
5117 if (package != nil) {
5118 package_ = [package retain];
5119 name_ = [[package id] retain];
5120
affeffc7
JF
5121 if (NSArray *files = [package files])
5122 [files_ addObjectsFromArray:files];
ab398adf 5123
9ea8d159
JF
5124 if ([files_ count] != 0) {
5125 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5126 [files_ removeObjectAtIndex:0];
a54b1c10 5127 [files_ sortUsingSelector:@selector(compareByPath:)];
2388b078
JF
5128
5129 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5130 [stack addObject:@"/"];
5131
5132 for (int i(0), e([files_ count]); i != e; ++i) {
5133 NSString *file = [files_ objectAtIndex:i];
5134 while (![file hasPrefix:[stack lastObject]])
5135 [stack removeLastObject];
5136 NSString *directory = [stack lastObject];
5137 [stack addObject:[file stringByAppendingString:@"/"]];
5138 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
a54b1c10 5139 ([stack count] - 2) * 3, "",
2388b078
JF
5140 [file substringFromIndex:[directory length]]
5141 ]];
5142 }
ab398adf
JF
5143 }
5144 }
5145
5146 [list_ reloadData];
5147}
5148
ab398adf
JF
5149- (void) reloadData {
5150 [self setPackage:[database_ packageWithName:name_]];
ab398adf 5151}
b4d89997 5152
b4d89997 5153@end
36bb2ca2 5154/* }}} */
adb61bda
GP
5155/* Package Controller {{{ */
5156@interface PackageController : CYBrowserController {
770f2a8e 5157 _transient Database *database_;
36bb2ca2
JF
5158 Package *package_;
5159 NSString *name_;
3bd1c2a2 5160 bool commercial_;
5a09ae08 5161 NSMutableArray *buttons_;
b31b87cc
JF
5162}
5163
b5e7eebb 5164- (id) initWithDatabase:(Database *)database;
36bb2ca2 5165- (void) setPackage:(Package *)package;
b4d89997 5166
36bb2ca2 5167@end
b4d89997 5168
adb61bda 5169@implementation PackageController
b4d89997 5170
36bb2ca2 5171- (void) dealloc {
36bb2ca2
JF
5172 if (package_ != nil)
5173 [package_ release];
5174 if (name_ != nil)
5175 [name_ release];
5a09ae08 5176 [buttons_ release];
36bb2ca2
JF
5177 [super dealloc];
5178}
8da60fb7 5179
92d4a16a 5180- (void) release {
f79a4512 5181 if ([self retainCount] == 1)
adb61bda 5182 [delegate_ setPackageController:self];
f79a4512 5183 [super release];
92d4a16a 5184}
f79a4512
JF
5185
5186/* XXX: this is not safe at all... localization of /fail/ */
5a09ae08 5187- (void) _clickButtonWithName:(NSString *)name {
43f3d7f6 5188 if ([name isEqualToString:UCLocalize("CLEAR")])
dc63e78f 5189 [delegate_ clearPackage:package_];
43f3d7f6 5190 else if ([name isEqualToString:UCLocalize("INSTALL")])
5a09ae08 5191 [delegate_ installPackage:package_];
43f3d7f6 5192 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5a09ae08 5193 [delegate_ installPackage:package_];
43f3d7f6 5194 else if ([name isEqualToString:UCLocalize("REMOVE")])
5a09ae08 5195 [delegate_ removePackage:package_];
43f3d7f6 5196 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5a09ae08
JF
5197 [delegate_ installPackage:package_];
5198 else _assert(false);
5199}
5200
674dce72 5201- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
1cedb821 5202 NSString *context([sheet context]);
5a09ae08 5203
1cedb821 5204 if ([context isEqualToString:@"modify"]) {
674dce72
GP
5205 if (button != [sheet cancelButtonIndex]) {
5206 NSString *buttonName = [buttons_ objectAtIndex:button];
5207 [self _clickButtonWithName:buttonName];
5208 }
b5e7eebb 5209
674dce72
GP
5210 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5211 } else {
5212 [super alertSheet:sheet clickedButtonAtIndex:button];
5213 }
b4d89997 5214}
2367a917 5215
7d2ac47f 5216- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
7d2ac47f
JF
5217 return [super webView:sender didFinishLoadForFrame:frame];
5218}
5219
6f1a15d9 5220- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
c390d3ab 5221 [super webView:sender didClearWindowObject:window forFrame:frame];
f79a4512 5222 [window setValue:package_ forKey:@"package"];
6f1a15d9
JF
5223}
5224
3e9c9e85 5225- (bool) _allowJavaScriptPanel {
3bd1c2a2 5226 return commercial_;
3e9c9e85
JF
5227}
5228
9487f027 5229#if !AlwaysReload
b5e7eebb 5230- (void) _actionButtonClicked {
670a0494
JF
5231 int count([buttons_ count]);
5232 if (count == 0)
5233 return;
2367a917 5234
5a09ae08
JF
5235 if (count == 1)
5236 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5237 else {
674dce72 5238 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5a09ae08 5239 [buttons addObjectsFromArray:buttons_];
36bb2ca2 5240
674dce72 5241 UIActionSheet *sheet = [[[UIActionSheet alloc]
9ea8d159 5242 initWithTitle:nil
36bb2ca2 5243 delegate:self
674dce72
GP
5244 cancelButtonTitle:nil
5245 destructiveButtonTitle:nil
5246 otherButtonTitles:nil
5247 ] autorelease];
5248
5249 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5250 if (!IsWildcat_) {
5251 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5252 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5253 }
5254 [sheet setContext:@"modify"];
b5e7eebb
GP
5255
5256 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
36bb2ca2 5257 }
b4d89997 5258}
12b59862 5259
b5e7eebb 5260- (void) actionButtonClicked {
2e6c1426 5261 // Wait until it's done loading.
40bfa2e6 5262 if (![self isLoading])
b5e7eebb 5263 [self _actionButtonClicked];
12b59862 5264}
2e6c1426
GP
5265
5266- (void) reloadButtonClicked {
2fad210a
GP
5267 // Don't reload a package view by clicking the button.
5268}
5269
5270- (void) applyLoadingTitle {
5271 // Don't show "Loading" as the title. Ever.
2e6c1426 5272}
9487f027 5273#endif
2367a917 5274
b5e7eebb
GP
5275- (id) initWithDatabase:(Database *)database {
5276 if ((self = [super init]) != nil) {
36bb2ca2 5277 database_ = database;
5a09ae08 5278 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
f79a4512 5279 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
36bb2ca2 5280 } return self;
dc5812ec
JF
5281}
5282
36bb2ca2
JF
5283- (void) setPackage:(Package *)package {
5284 if (package_ != nil) {
5285 [package_ autorelease];
5286 package_ = nil;
5287 }
5288
5289 if (name_ != nil) {
5290 [name_ release];
5291 name_ = nil;
5292 }
5293
5a09ae08
JF
5294 [buttons_ removeAllObjects];
5295
36bb2ca2 5296 if (package != nil) {
68d927e2
JF
5297 [package parse];
5298
36bb2ca2
JF
5299 package_ = [package retain];
5300 name_ = [[package id] retain];
3bd1c2a2 5301 commercial_ = [package isCommercial];
36bb2ca2 5302
dc63e78f 5303 if ([package_ mode] != nil)
43f3d7f6 5304 [buttons_ addObject:UCLocalize("CLEAR")];
5a09ae08 5305 if ([package_ source] == nil);
31f3cfff 5306 else if ([package_ upgradableAndEssential:NO])
43f3d7f6 5307 [buttons_ addObject:UCLocalize("UPGRADE")];
6a155117 5308 else if ([package_ uninstalled])
43f3d7f6 5309 [buttons_ addObject:UCLocalize("INSTALL")];
5a09ae08 5310 else
43f3d7f6 5311 [buttons_ addObject:UCLocalize("REINSTALL")];
6a155117 5312 if (![package_ uninstalled])
43f3d7f6 5313 [buttons_ addObject:UCLocalize("REMOVE")];
f79a4512
JF
5314
5315 if (special_ != NULL) {
aeed65a6 5316 CGRect frame([document_ frame]);
f79a4512 5317 frame.size.height = 0;
aeed65a6 5318 [document_ setFrame:frame];
f79a4512 5319
58241d4c
JF
5320 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5321 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5322 else
5323 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
f79a4512
JF
5324
5325 WebThreadLock();
aeed65a6 5326 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
f79a4512
JF
5327
5328 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5329
5330 [self setFinishHook:nil];
5331 [self setPopupHook:nil];
5332 WebThreadUnlock();
5333
b1ce61ec 5334 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
f79a4512
JF
5335 [super callFunction:special_];
5336 }
36bb2ca2 5337 }
b5e7eebb 5338}
f79a4512 5339
40bfa2e6 5340- (void) applyRightButton {
b5e7eebb
GP
5341 int count = [buttons_ count];
5342 UIBarButtonItem *actionItem = [[UIBarButtonItem alloc]
5343 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5344 style:UIBarButtonItemStylePlain
5345 target:self
5346 action:@selector(actionButtonClicked)
5347 ];
40bfa2e6
GP
5348 if (![self isLoading]) [[self navigationItem] setRightBarButtonItem:actionItem];
5349 else [super applyRightButton];
b5e7eebb 5350 [actionItem release];
dc5812ec
JF
5351}
5352
3bd1c2a2
JF
5353- (bool) isLoading {
5354 return commercial_ ? [super isLoading] : false;
9fe5e5f8
JF
5355}
5356
36bb2ca2
JF
5357- (void) reloadData {
5358 [self setPackage:[database_ packageWithName:name_]];
8fe19fc1
JF
5359}
5360
b4d89997
JF
5361@end
5362/* }}} */
b4d89997 5363/* Package Table {{{ */
b5e7eebb 5364@interface PackageTable : UIView {
36bb2ca2 5365 _transient Database *database_;
36bb2ca2 5366 NSMutableArray *packages_;
b4d89997 5367 NSMutableArray *sections_;
327624b6
JF
5368 UITableView *list_;
5369 NSMutableArray *index_;
5370 NSMutableDictionary *indices_;
b5e7eebb
GP
5371 id target_;
5372 SEL action_;
5373 id delegate_;
dc5812ec
JF
5374}
5375
b5e7eebb 5376- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
b4d89997
JF
5377
5378- (void) setDelegate:(id)delegate;
a0be02eb 5379
36bb2ca2 5380- (void) reloadData;
a0be02eb 5381- (void) resetCursor;
b4d89997 5382
327624b6 5383- (UITableView *) list;
2388b078 5384
ab398adf
JF
5385- (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5386
b5e7eebb
GP
5387- (void) deselectWithAnimation:(BOOL)animated;
5388
b4d89997
JF
5389@end
5390
5391@implementation PackageTable
5392
5393- (void) dealloc {
36bb2ca2 5394 [packages_ release];
b4d89997 5395 [sections_ release];
36bb2ca2 5396 [list_ release];
327624b6
JF
5397 [index_ release];
5398 [indices_ release];
b5e7eebb 5399
b4d89997 5400 [super dealloc];
8fe19fc1
JF
5401}
5402
327624b6
JF
5403- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5404 NSInteger count([sections_ count]);
5405 return count == 0 ? 1 : count;
b4d89997 5406}
2367a917 5407
327624b6
JF
5408- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5409 if ([sections_ count] == 0)
5410 return nil;
b4d89997
JF
5411 return [[sections_ objectAtIndex:section] name];
5412}
dc5812ec 5413
327624b6
JF
5414- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5415 if ([sections_ count] == 0)
5416 return 0;
5417 return [[sections_ objectAtIndex:section] count];
b4d89997 5418}
dc5812ec 5419
327624b6
JF
5420- (Package *) packageAtIndexPath:(NSIndexPath *)path {
5421 Section *section([sections_ objectAtIndex:[path section]]);
5422 NSInteger row([path row]);
5423 Package *package([packages_ objectAtIndex:([section row] + row)]);
5424 return package;
b4d89997 5425}
dc5812ec 5426
327624b6
JF
5427- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5428 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5429 if (cell == nil)
5430 cell = [[[PackageCell alloc] init] autorelease];
5431 [cell setPackage:[self packageAtIndexPath:path]];
5432 return cell;
b4d89997 5433}
dc5812ec 5434
b5e7eebb
GP
5435- (void) deselectWithAnimation:(BOOL)animated {
5436 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5437}
5438
21ea11a4 5439/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
327624b6 5440 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
21ea11a4 5441}*/
dc5812ec 5442
327624b6
JF
5443- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5444 Package *package([self packageAtIndexPath:path]);
59c6ae22 5445 package = [database_ packageWithName:[package id]];
b5e7eebb 5446 [target_ performSelector:action_ withObject:package];
327624b6
JF
5447 return path;
5448}
5449
5450- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5451 return [packages_ count] > 20 ? index_ : nil;
5452}
5453
5454- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5455 return index;
dc5812ec
JF
5456}
5457
b5e7eebb
GP
5458- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5459 if ((self = [super initWithFrame:frame]) != nil) {
36bb2ca2 5460 database_ = database;
b5e7eebb
GP
5461
5462 target_ = target;
5463 action_ = action;
36bb2ca2 5464
327624b6
JF
5465 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5466 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5467
36bb2ca2 5468 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
b4d89997 5469 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 5470
327624b6 5471 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
04fe1349 5472 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 5473 [list_ setRowHeight:73.0f];
04fe1349
JF
5474 [self addSubview:list_];
5475
b4d89997 5476 [list_ setDataSource:self];
327624b6 5477 [list_ setDelegate:self];
b4d89997 5478 } return self;
dc5812ec
JF
5479}
5480
5481- (void) setDelegate:(id)delegate {
2367a917 5482 delegate_ = delegate;
b4d89997
JF
5483}
5484
a3328c28
JF
5485- (bool) hasPackage:(Package *)package {
5486 return true;
a0be02eb
JF
5487}
5488
36bb2ca2
JF
5489- (void) reloadData {
5490 NSArray *packages = [database_ packages];
b4d89997 5491
36bb2ca2 5492 [packages_ removeAllObjects];
b4d89997
JF
5493 [sections_ removeAllObjects];
5494
808c6eb6 5495 _profile(PackageTable$reloadData$Filter)
c4dcf2c2 5496 for (Package *package in packages)
808c6eb6
JF
5497 if ([self hasPackage:package])
5498 [packages_ addObject:package];
808c6eb6 5499 _end
36bb2ca2 5500
327624b6
JF
5501 [index_ removeAllObjects];
5502 [indices_ removeAllObjects];
5503
b4d89997
JF
5504 Section *section = nil;
5505
808c6eb6 5506 _profile(PackageTable$reloadData$Section)
c4dcf2c2
JF
5507 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5508 Package *package;
5509 unichar index;
5510
5511 _profile(PackageTable$reloadData$Section$Package)
5512 package = [packages_ objectAtIndex:offset];
5513 index = [package index];
5514 _end
b4d89997 5515
808c6eb6
JF
5516 if (section == nil || [section index] != index) {
5517 _profile(PackageTable$reloadData$Section$Allocate)
5518 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5519 _end
b4d89997 5520
327624b6
JF
5521 [index_ addObject:[section name]];
5522 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5523
c4dcf2c2
JF
5524 _profile(PackageTable$reloadData$Section$Add)
5525 [sections_ addObject:section];
5526 _end
808c6eb6
JF
5527 }
5528
5529 [section addToCount];
5530 }
5531 _end
b4d89997 5532
c4dcf2c2
JF
5533 _profile(PackageTable$reloadData$List)
5534 [list_ reloadData];
5535 _end
b4d89997
JF
5536}
5537
a0be02eb 5538- (void) resetCursor {
327624b6 5539 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
a0be02eb
JF
5540}
5541
327624b6 5542- (UITableView *) list {
2388b078
JF
5543 return list_;
5544}
5545
ab398adf 5546- (void) setShouldHideHeaderInShortLists:(BOOL)hide {
327624b6 5547 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
ab398adf
JF
5548}
5549
a3328c28
JF
5550@end
5551/* }}} */
5552/* Filtered Package Table {{{ */
5553@interface FilteredPackageTable : PackageTable {
5554 SEL filter_;
76933519 5555 IMP imp_;
a3328c28
JF
5556 id object_;
5557}
5558
5559- (void) setObject:(id)object;
01d93940 5560- (void) setObject:(id)object forFilter:(SEL)filter;
a3328c28 5561
b5e7eebb 5562- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
a3328c28
JF
5563
5564@end
5565
5566@implementation FilteredPackageTable
5567
5568- (void) dealloc {
5569 if (object_ != nil)
5570 [object_ release];
5571 [super dealloc];
5572}
5573
01d93940
JF
5574- (void) setFilter:(SEL)filter {
5575 filter_ = filter;
5576
5577 /* XXX: this is an unsafe optimization of doomy hell */
5578 Method method(class_getInstanceMethod([Package class], filter));
5579 _assert(method != NULL);
5580 imp_ = method_getImplementation(method);
5581 _assert(imp_ != NULL);
5582}
5583
a3328c28
JF
5584- (void) setObject:(id)object {
5585 if (object_ != nil)
5586 [object_ release];
5587 if (object == nil)
5588 object_ = nil;
5589 else
5590 object_ = [object retain];
5591}
5592
01d93940
JF
5593- (void) setObject:(id)object forFilter:(SEL)filter {
5594 [self setFilter:filter];
5595 [self setObject:object];
01d93940
JF
5596}
5597
a3328c28 5598- (bool) hasPackage:(Package *)package {
76933519
JF
5599 _profile(FilteredPackageTable$hasPackage)
5600 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5601 _end
a3328c28
JF
5602}
5603
b5e7eebb
GP
5604- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5605 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
01d93940 5606 [self setFilter:filter];
b5e7eebb 5607 object_ = [object retain];
189a73d0 5608 [self reloadData];
a3328c28
JF
5609 } return self;
5610}
5611
dc5812ec 5612@end
b4d89997 5613/* }}} */
dc5812ec 5614
adb61bda
GP
5615/* Filtered Package Controller {{{ */
5616@interface FilteredPackageController : CYViewController {
b5e7eebb
GP
5617 _transient Database *database_;
5618 FilteredPackageTable *packages_;
5619 NSString *title_;
5620}
5621
5622- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5623
5624@end
5625
adb61bda 5626@implementation FilteredPackageController
b5e7eebb
GP
5627
5628- (void) dealloc {
5629 [packages_ release];
5630 [title_ release];
5631
5632 [super dealloc];
5633}
5634
5635- (void) viewDidAppear:(BOOL)animated {
5636 [super viewDidAppear:animated];
5637 [packages_ deselectWithAnimation:animated];
5638}
5639
5640- (void) didSelectPackage:(Package *)package {
adb61bda 5641 PackageController *view([delegate_ packageController]);
b5e7eebb
GP
5642 [view setPackage:package];
5643 [view setDelegate:delegate_];
5644 [[self navigationController] pushViewController:view animated:YES];
5645}
5646
5647- (id) title { return title_; }
5648
5649- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5650 if ((self = [super init]) != nil) {
5651 database_ = database;
5652 title_ = [title copy];
5653 [[self navigationItem] setTitle:title_];
5654
5655 packages_ = [[FilteredPackageTable alloc]
5656 initWithFrame:[[self view] bounds]
5657 database:database
5658 target:self
5659 action:@selector(didSelectPackage:)
5660 filter:filter
5661 with:object
5662 ];
5663
5664 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5665 [[self view] addSubview:packages_];
5666 } return self;
5667}
5668
5669- (void) reloadData {
5670 [packages_ reloadData];
5671}
5672
5673- (void) setDelegate:(id)delegate {
5674 [super setDelegate:delegate];
5675 [packages_ setDelegate:delegate];
5676}
5677
5678@end
5679
5680/* }}} */
5681
adb61bda
GP
5682/* Add Source Controller {{{ */
5683@interface AddSourceController : CYViewController {
7b0ce2da 5684 _transient Database *database_;
dc5812ec
JF
5685}
5686
b5e7eebb 5687- (id) initWithDatabase:(Database *)database;
b4d89997 5688
7b0ce2da 5689@end
dc5812ec 5690
adb61bda 5691@implementation AddSourceController
dc5812ec 5692
b5e7eebb
GP
5693- (id) initWithDatabase:(Database *)database {
5694 if ((self = [super init]) != nil) {
7b0ce2da
JF
5695 database_ = database;
5696 } return self;
36bb2ca2 5697}
dc5812ec 5698
7b0ce2da
JF
5699@end
5700/* }}} */
5701/* Source Cell {{{ */
46aa9775 5702@interface SourceCell : UITableViewCell {
f641a0e5
JF
5703 UIImage *icon_;
5704 NSString *origin_;
5705 NSString *description_;
5706 NSString *label_;
46aa9775 5707 ContentView *content_;
b4d89997
JF
5708}
5709
46aa9775 5710- (void) setSource:(Source *)source;
b4d89997 5711
7b0ce2da 5712@end
b4d89997 5713
7b0ce2da 5714@implementation SourceCell
b4d89997 5715
46aa9775 5716- (void) clearSource {
f641a0e5 5717 [icon_ release];
7b0ce2da
JF
5718 [origin_ release];
5719 [description_ release];
5720 [label_ release];
46aa9775
GP
5721
5722 icon_ = nil;
5723 origin_ = nil;
5724 description_ = nil;
5725 label_ = nil;
5726}
5727
5728- (void) setSource:(Source *)source {
5729 [self clearSource];
5730
5731 if (icon_ == nil)
5732 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5733 if (icon_ == nil)
5734 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5735 icon_ = [icon_ retain];
5736
5737 origin_ = [[source name] retain];
5738 label_ = [[source uri] retain];
5739 description_ = [[source description] retain];
5740
5741 [content_ setNeedsDisplay];
5742}
5743
5744- (void) dealloc {
5745 [self clearSource];
5746 [content_ release];
7b0ce2da 5747 [super dealloc];
36bb2ca2 5748}
b4d89997 5749
46aa9775
GP
5750- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5751 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5752 UIView *content([self contentView]);
5753 CGRect bounds([content bounds]);
5754
5755 content_ = [[ContentView alloc] initWithFrame:bounds];
5756 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5757 [content_ setBackgroundColor:[UIColor whiteColor]];
5758 [content addSubview:content_];
5759
5760 [content_ setDelegate:self];
5761 [content_ setOpaque:YES];
7b0ce2da 5762 } return self;
a0376fc1
JF
5763}
5764
46aa9775
GP
5765- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5766 [super setSelected:selected animated:animated];
5767 [content_ setNeedsDisplay];
5768}
5769
5770- (void) drawContentRect:(CGRect)rect {
5771 bool selected([self isSelected]);
01d93940
JF
5772 float width(rect.size.width);
5773
f641a0e5
JF
5774 if (icon_ != nil)
5775 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7b0ce2da 5776
f641a0e5
JF
5777 if (selected)
5778 UISetColor(White_);
7b0ce2da 5779
f641a0e5
JF
5780 if (!selected)
5781 UISetColor(Black_);
01d93940 5782 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
7b0ce2da 5783
f641a0e5
JF
5784 if (!selected)
5785 UISetColor(Blue_);
01d93940 5786 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
7b0ce2da 5787
f641a0e5
JF
5788 if (!selected)
5789 UISetColor(Gray_);
01d93940 5790 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
7b0ce2da
JF
5791}
5792
5793@end
5794/* }}} */
5795/* Source Table {{{ */
b5e7eebb 5796@interface SourceTable : CYViewController {
7b0ce2da 5797 _transient Database *database_;
46aa9775 5798 UITableView *list_;
7b0ce2da 5799 NSMutableArray *sources_;
7b0ce2da
JF
5800 int offset_;
5801
5802 NSString *href_;
5803 UIProgressHUD *hud_;
5804 NSError *error_;
5805
5806 //NSURLConnection *installer_;
42543928 5807 NSURLConnection *trivial_;
7b0ce2da
JF
5808 NSURLConnection *trivial_bz2_;
5809 NSURLConnection *trivial_gz_;
5810 //NSURLConnection *automatic_;
5811
42543928 5812 BOOL cydia_;
7b0ce2da
JF
5813}
5814
b5e7eebb 5815- (id) initWithDatabase:(Database *)database;
7b0ce2da
JF
5816
5817@end
5818
5819@implementation SourceTable
5820
5821- (void) _deallocConnection:(NSURLConnection *)connection {
5822 if (connection != nil) {
5823 [connection cancel];
5824 //[connection setDelegate:nil];
5825 [connection release];
5826 }
5827}
5828
5829- (void) dealloc {
7b0ce2da
JF
5830 if (href_ != nil)
5831 [href_ release];
5832 if (hud_ != nil)
5833 [hud_ release];
5834 if (error_ != nil)
5835 [error_ release];
5836
5837 //[self _deallocConnection:installer_];
42543928 5838 [self _deallocConnection:trivial_];
7b0ce2da
JF
5839 [self _deallocConnection:trivial_gz_];
5840 [self _deallocConnection:trivial_bz2_];
5841 //[self _deallocConnection:automatic_];
5842
5843 [sources_ release];
5844 [list_ release];
5845 [super dealloc];
5846}
5847
b5e7eebb
GP
5848- (void) viewDidAppear:(BOOL)animated {
5849 [super viewDidAppear:animated];
5850 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5851}
5852
46aa9775 5853- (int) numberOfSectionsInTableView:(UITableView *)tableView {
7b0ce2da
JF
5854 return offset_ == 0 ? 1 : 2;
5855}
5856
46aa9775 5857- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
7b0ce2da 5858 switch (section + (offset_ == 0 ? 1 : 0)) {
43f3d7f6
JF
5859 case 0: return UCLocalize("ENTERED_BY_USER");
5860 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7b0ce2da 5861
670a0494 5862 _nodefault
7b0ce2da
JF
5863 }
5864}
5865
46aa9775
GP
5866- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5867 int count = [sources_ count];
5868 switch (section) {
5869 case 0: return (offset_ == 0 ? count : offset_);
5870 case 1: return count - offset_;
7b0ce2da 5871
b5e7eebb 5872 _nodefault
7b0ce2da
JF
5873 }
5874}
5875
46aa9775
GP
5876- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5877 unsigned idx = 0;
5878 switch (indexPath.section) {
5879 case 0: idx = indexPath.row; break;
5880 case 1: idx = indexPath.row + offset_; break;
5881
b5e7eebb 5882 _nodefault
46aa9775
GP
5883 }
5884 return [sources_ objectAtIndex:idx];
7b0ce2da
JF
5885}
5886
46aa9775
GP
5887- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5888 Source *source = [self sourceAtIndexPath:indexPath];
f641a0e5 5889 return [source description] == nil ? 56 : 73;
7b0ce2da
JF
5890}
5891
46aa9775 5892- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb 5893 static NSString *cellIdentifier = @"SourceCell";
7b0ce2da 5894
46aa9775 5895 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
b5e7eebb
GP
5896 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5897 [cell setSource:[self sourceAtIndexPath:indexPath]];
5898
46aa9775 5899 return cell;
7b0ce2da
JF
5900}
5901
46aa9775
GP
5902- (int) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5903 return 1; //UITableViewCellAccessoryDisclosureIndicator?
7b0ce2da
JF
5904}
5905
46aa9775
GP
5906- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5907 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da 5908
adb61bda 5909 FilteredPackageController *packages = [[[FilteredPackageController alloc]
b5e7eebb 5910 initWithDatabase:database_
7b0ce2da
JF
5911 title:[source label]
5912 filter:@selector(isVisibleInSource:)
5913 with:source
5914 ] autorelease];
5915
5916 [packages setDelegate:delegate_];
5917
b5e7eebb 5918 [[self navigationController] pushViewController:packages animated:YES];
7b0ce2da
JF
5919}
5920
46aa9775
GP
5921- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5922 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da
JF
5923 return [source record] != nil;
5924}
5925
46aa9775
GP
5926- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5927 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da
JF
5928 [Sources_ removeObjectForKey:[source key]];
5929 [delegate_ syncData];
5930}
5931
2fc76a2d
JF
5932- (void) complete {
5933 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5934 @"deb", @"Type",
5935 href_, @"URI",
5936 @"./", @"Distribution",
5937 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5938
5939 [delegate_ syncData];
5940}
5941
5942- (NSString *) getWarning {
3e9c9e85
JF
5943 NSString *href(href_);
5944 NSRange colon([href rangeOfString:@"://"]);
5945 if (colon.location != NSNotFound)
5946 href = [href substringFromIndex:(colon.location + 3)];
5947 href = [href stringByAddingPercentEscapes];
670a0494 5948 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
2fc76a2d
JF
5949 href = [href stringByCachingURLWithCurrentCDN];
5950
5951 NSURL *url([NSURL URLWithString:href]);
5952
5953 NSStringEncoding encoding;
5954 NSError *error(nil);
5955
5956 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5957 return [warning length] == 0 ? nil : warning;
5958 return nil;
5959}
5960
7b0ce2da
JF
5961- (void) _endConnection:(NSURLConnection *)connection {
5962 NSURLConnection **field = NULL;
42543928
JF
5963 if (connection == trivial_)
5964 field = &trivial_;
5965 else if (connection == trivial_bz2_)
7b0ce2da
JF
5966 field = &trivial_bz2_;
5967 else if (connection == trivial_gz_)
5968 field = &trivial_gz_;
5969 _assert(field != NULL);
5970 [connection release];
5971 *field = nil;
5972
5973 if (
42543928 5974 trivial_ == nil &&
7b0ce2da
JF
5975 trivial_bz2_ == nil &&
5976 trivial_gz_ == nil
5977 ) {
3e9c9e85 5978 bool defer(false);
7b0ce2da 5979
42543928 5980 if (cydia_) {
2fc76a2d 5981 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
3e9c9e85
JF
5982 defer = true;
5983
0fe9a7e8 5984 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 5985 initWithTitle:UCLocalize("SOURCE_WARNING")
b5e7eebb
GP
5986 message:warning
5987 delegate:self
5988 cancelButtonTitle:UCLocalize("CANCEL")
0fe9a7e8 5989 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
2fc76a2d
JF
5990 ] autorelease];
5991
b5e7eebb 5992 [alert setContext:@"warning"];
0fe9a7e8
GP
5993 [alert setNumberOfRows:1];
5994 [alert show];
2fc76a2d
JF
5995 } else
5996 [self complete];
7b0ce2da 5997 } else if (error_ != nil) {
0fe9a7e8 5998 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 5999 initWithTitle:UCLocalize("VERIFICATION_ERROR")
b5e7eebb
GP
6000 message:[error_ localizedDescription]
6001 delegate:self
6002 cancelButtonTitle:UCLocalize("OK")
0fe9a7e8 6003 otherButtonTitles:nil
7b0ce2da
JF
6004 ] autorelease];
6005
b5e7eebb 6006 [alert setContext:@"urlerror"];
0fe9a7e8 6007 [alert show];
7b0ce2da 6008 } else {
0fe9a7e8 6009 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 6010 initWithTitle:UCLocalize("NOT_REPOSITORY")
b5e7eebb
GP
6011 message:UCLocalize("NOT_REPOSITORY_EX")
6012 delegate:self
6013 cancelButtonTitle:UCLocalize("OK")
0fe9a7e8 6014 otherButtonTitles:nil
7b0ce2da
JF
6015 ] autorelease];
6016
b5e7eebb 6017 [alert setContext:@"trivial"];
0fe9a7e8 6018 [alert show];
7b0ce2da
JF
6019 }
6020
3e9c9e85
JF
6021 [delegate_ setStatusBarShowsProgress:NO];
6022 [delegate_ removeProgressHUD:hud_];
6023
6024 [hud_ autorelease];
6025 hud_ = nil;
6026
6027 if (!defer) {
6028 [href_ release];
6029 href_ = nil;
6030 }
7b0ce2da
JF
6031
6032 if (error_ != nil) {
6033 [error_ release];
6034 error_ = nil;
6035 }
6036 }
6037}
6038
6039- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6040 switch ([response statusCode]) {
6041 case 200:
42543928 6042 cydia_ = YES;
7b0ce2da
JF
6043 }
6044}
6045
6046- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
c390d3ab 6047 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7b0ce2da
JF
6048 if (error_ != nil)
6049 error_ = [error retain];
6050 [self _endConnection:connection];
6051}
6052
6053- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6054 [self _endConnection:connection];
6055}
6056
b5e7eebb
GP
6057- (id)title { return UCLocalize("SOURCES"); }
6058
7b0ce2da
JF
6059- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6060 NSMutableURLRequest *request = [NSMutableURLRequest
6061 requestWithURL:[NSURL URLWithString:href]
6062 cachePolicy:NSURLRequestUseProtocolCachePolicy
77801ff1 6063 timeoutInterval:120.0
7b0ce2da
JF
6064 ];
6065
6066 [request setHTTPMethod:method];
6067
f79a4512
JF
6068 if (Machine_ != NULL)
6069 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
77801ff1
JF
6070 if (UniqueID_ != nil)
6071 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
f79a4512
JF
6072 if (Role_ != nil)
6073 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6074
7b0ce2da
JF
6075 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6076}
6077
0fe9a7e8
GP
6078- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6079 NSString *context([alert context]);
1cedb821
JF
6080
6081 if ([context isEqualToString:@"source"]) {
7b0ce2da
JF
6082 switch (button) {
6083 case 1: {
0fe9a7e8 6084 NSString *href = [[alert textField] text];
7b0ce2da
JF
6085
6086 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6087
6088 if (![href hasSuffix:@"/"])
6089 href_ = [href stringByAppendingString:@"/"];
6090 else
6091 href_ = href;
6092 href_ = [href_ retain];
6093
42543928 6094 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7b0ce2da
JF
6095 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6096 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6097 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6098
42543928 6099 cydia_ = false;
7b0ce2da 6100
d061f4ba 6101 hud_ = [[delegate_ addProgressHUD] retain];
43f3d7f6 6102 [hud_ setText:UCLocalize("VERIFYING_URL")];
7b0ce2da
JF
6103 } break;
6104
0fe9a7e8 6105 case 0:
7b0ce2da
JF
6106 break;
6107
670a0494 6108 _nodefault
7b0ce2da
JF
6109 }
6110
0fe9a7e8 6111 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b49f4c92 6112 } else if ([context isEqualToString:@"trivial"])
0fe9a7e8 6113 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b49f4c92 6114 else if ([context isEqualToString:@"urlerror"])
0fe9a7e8 6115 [alert dismissWithClickedButtonIndex:-1 animated:YES];
2fc76a2d
JF
6116 else if ([context isEqualToString:@"warning"]) {
6117 switch (button) {
6118 case 1:
6119 [self complete];
6120 break;
6121
0fe9a7e8 6122 case 0:
2fc76a2d
JF
6123 break;
6124
670a0494 6125 _nodefault
2fc76a2d
JF
6126 }
6127
3e9c9e85
JF
6128 [href_ release];
6129 href_ = nil;
6130
0fe9a7e8 6131 [alert dismissWithClickedButtonIndex:-1 animated:YES];
2fc76a2d 6132 }
7b0ce2da
JF
6133}
6134
b5e7eebb
GP
6135- (id) initWithDatabase:(Database *)database {
6136 if ((self = [super init]) != nil) {
6137 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6138 [self updateButtonsForEditingStatus:NO animated:NO];
6139
7b0ce2da
JF
6140 database_ = database;
6141 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6142
b5e7eebb 6143 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 6144 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b5e7eebb 6145 [[self view] addSubview:list_];
04fe1349 6146
7b0ce2da 6147 [list_ setDataSource:self];
46aa9775 6148 [list_ setDelegate:self];
7b0ce2da
JF
6149
6150 [self reloadData];
6151 } return self;
6152}
6153
6154- (void) reloadData {
6155 pkgSourceList list;
670a0494
JF
6156 if (!list.ReadMainList())
6157 return;
7b0ce2da
JF
6158
6159 [sources_ removeAllObjects];
6160 [sources_ addObjectsFromArray:[database_ sources]];
807ae6d7 6161 _trace();
7b0ce2da 6162 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
807ae6d7 6163 _trace();
7b0ce2da 6164
b5e7eebb 6165 int count([sources_ count]);
46aa9775
GP
6166 offset_ = 0;
6167 for (int i = 0; i != count; i++) {
b5e7eebb
GP
6168 if ([[sources_ objectAtIndex:i] record] == nil) break;
6169 else offset_++;
7b0ce2da
JF
6170 }
6171
46aa9775 6172 [list_ setEditing:NO];
b5e7eebb 6173 [self updateButtonsForEditingStatus:NO animated:NO];
7b0ce2da
JF
6174 [list_ reloadData];
6175}
6176
b5e7eebb 6177- (void) addButtonClicked {
adb61bda 6178 /*[book_ pushPage:[[[AddSourceController alloc]
7b0ce2da
JF
6179 initWithBook:book_
6180 database:database_
6181 ] autorelease]];*/
6182
0fe9a7e8 6183 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 6184 initWithTitle:UCLocalize("ENTER_APT_URL")
b5e7eebb
GP
6185 message:nil
6186 delegate:self
6187 cancelButtonTitle:UCLocalize("CANCEL")
6188 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7b0ce2da
JF
6189 ] autorelease];
6190
b5e7eebb
GP
6191 [alert setContext:@"source"];
6192 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
1cedb821 6193
0fe9a7e8
GP
6194 [alert setNumberOfRows:1];
6195 [alert addTextFieldWithValue:@"http://" label:@""];
7b0ce2da 6196
0fe9a7e8 6197 UITextInputTraits *traits = [[alert textField] textInputTraits];
b49f4c92
JF
6198 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6199 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
1cedb821 6200 [traits setKeyboardType:UIKeyboardTypeURL];
b49f4c92
JF
6201 // XXX: UIReturnKeyDone
6202 [traits setReturnKeyType:UIReturnKeyNext];
7b0ce2da 6203
0fe9a7e8 6204 [alert show];
7b0ce2da
JF
6205}
6206
b5e7eebb
GP
6207- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6208 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6209 initWithTitle:UCLocalize("ADD")
6210 style:UIBarButtonItemStylePlain
6211 target:self
6212 action:@selector(addButtonClicked)
6213 ];
6214 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6215 [leftItem release];
6216
6217 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6218 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6219 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6220 target:self
6221 action:@selector(editButtonClicked)
6222 ];
6223 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6224 [rightItem release];
2bdd73bd
GP
6225
6226 if (IsWildcat_ && !editing) {
6227 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6228 initWithTitle:UCLocalize("SETTINGS")
6229 style:UIBarButtonItemStylePlain
6230 target:self
6231 action:@selector(settingsButtonClicked)
6232 ];
6233 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6234 [settingsItem release];
6235 }
6236}
6237
6238- (void) settingsButtonClicked {
6239 [delegate_ showSettings];
7b0ce2da
JF
6240}
6241
b5e7eebb
GP
6242- (void) editButtonClicked {
6243 [list_ setEditing:![list_ isEditing] animated:YES];
6244
6245 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
7b0ce2da
JF
6246}
6247
6248@end
6249/* }}} */
6250
adb61bda
GP
6251/* Installed Controller {{{ */
6252@interface InstalledController : FilteredPackageController {
f641a0e5 6253 BOOL expert_;
7b0ce2da
JF
6254}
6255
b5e7eebb 6256- (id) initWithDatabase:(Database *)database;
7b0ce2da
JF
6257
6258@end
6259
adb61bda 6260@implementation InstalledController
7b0ce2da
JF
6261
6262- (void) dealloc {
7b0ce2da
JF
6263 [super dealloc];
6264}
6265
b5e7eebb 6266- (id) title { return UCLocalize("INSTALLED"); }
baf80942 6267
b5e7eebb
GP
6268- (id) initWithDatabase:(Database *)database {
6269 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6270 [self updateRoleButton];
6271 [self queueStatusDidChange];
7b0ce2da
JF
6272 } return self;
6273}
6274
b5e7eebb
GP
6275#if !AlwaysReload
6276- (void) queueButtonClicked {
6277 [delegate_ queue];
7b0ce2da 6278}
b5e7eebb 6279#endif
7b0ce2da 6280
b5e7eebb
GP
6281- (void) queueStatusDidChange {
6282#if !AlwaysReload
6283 if (IsWildcat_) {
6284 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6285 initWithTitle:UCLocalize("QUEUE")
6286 style:UIBarButtonItemStyleDone
6287 target:self
6288 action:@selector(queueButtonClicked)
6289 ];
6290 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6291 else [[self navigationItem] setLeftBarButtonItem:nil];
6292 [queueItem release];
6293 }
6294#endif
f641a0e5
JF
6295}
6296
b5e7eebb
GP
6297- (void) reloadData {
6298 [packages_ reloadData];
7b0ce2da
JF
6299}
6300
b5e7eebb
GP
6301- (void) updateRoleButton {
6302 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6303 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6304 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6305 target:self
6306 action:@selector(roleButtonClicked)
6307 ];
6308 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6309 [rightItem release];
7b0ce2da
JF
6310}
6311
b5e7eebb
GP
6312- (void) roleButtonClicked {
6313 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6314 [packages_ reloadData];
6315 expert_ = !expert_;
f641a0e5 6316
b5e7eebb 6317 [self updateRoleButton];
f641a0e5
JF
6318}
6319
7b0ce2da
JF
6320- (void) setDelegate:(id)delegate {
6321 [super setDelegate:delegate];
6322 [packages_ setDelegate:delegate];
6323}
6324
6325@end
6326/* }}} */
6327
adb61bda
GP
6328/* Home Controller {{{ */
6329@interface HomeController : CYBrowserController {
7b0ce2da
JF
6330}
6331
6332@end
6333
adb61bda 6334@implementation HomeController
7b0ce2da 6335
bfc87a4d
JF
6336- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6337 [super _setMoreHeaders:request];
6338 if (ChipID_ != nil)
6339 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
01d93940
JF
6340 if (UniqueID_ != nil)
6341 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
bfc87a4d
JF
6342}
6343
b5e7eebb 6344- (void) aboutButtonClicked {
65c27c56
JF
6345 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6346 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6347 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6348 [alert setCancelButtonIndex:0];
7b0ce2da 6349
65c27c56 6350 [alert setMessage:
77801ff1 6351 @"Copyright (C) 2008-2010\n"
7b0ce2da
JF
6352 "Jay Freeman (saurik)\n"
6353 "saurik@saurik.com\n"
42fc47f8 6354 "http://www.saurik.com/"
7b0ce2da
JF
6355 ];
6356
65c27c56 6357 [alert show];
7b0ce2da
JF
6358}
6359
b5e7eebb
GP
6360- (void) viewWillAppear:(BOOL)animated {
6361 [super viewWillAppear:animated];
6362 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6363}
6364
6365- (void) viewWillDisappear:(BOOL)animated {
6366 [super viewWillDisappear:animated];
6367 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6368}
6369
6370- (id) init {
6371 if ((self = [super init]) != nil) {
6372 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6373 initWithTitle:UCLocalize("ABOUT")
6374 style:UIBarButtonItemStylePlain
6375 target:self
6376 action:@selector(aboutButtonClicked)
6377 ];
6378 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6379 [aboutItem release];
6380 } return self;
7b0ce2da
JF
6381}
6382
6383@end
98228790 6384/* }}} */
adb61bda
GP
6385/* Manage Controller {{{ */
6386@interface ManageController : CYBrowserController {
7b0ce2da
JF
6387}
6388
6389@end
6390
adb61bda 6391@implementation ManageController
7b0ce2da 6392
b5e7eebb
GP
6393- (id) init {
6394 if ((self = [super init]) != nil) {
6395 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6396
6397 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6398 initWithTitle:UCLocalize("SETTINGS")
6399 style:UIBarButtonItemStylePlain
6400 target:self
6401 action:@selector(settingsButtonClicked)
6402 ];
6403 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6404 [settingsItem release];
6405
6406 [self queueStatusDidChange];
6407 } return self;
7b0ce2da
JF
6408}
6409
b5e7eebb 6410- (void) settingsButtonClicked {
21c6da4b 6411 [delegate_ showSettings];
7b0ce2da
JF
6412}
6413
bf8476c8 6414#if !AlwaysReload
b5e7eebb
GP
6415- (void) queueButtonClicked {
6416 [delegate_ queue];
dc63e78f
JF
6417}
6418
eb97a3a8
GP
6419- (void) applyLoadingTitle {
6420 // No "Loading" title.
6421}
6422
6423- (void) applyRightButton {
6424 // No right button.
dc63e78f 6425}
eb97a3a8 6426#endif
dc63e78f 6427
b5e7eebb
GP
6428- (void) queueStatusDidChange {
6429#if !AlwaysReload
6430 if (!IsWildcat_ && Queuing_) {
6431 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6432 initWithTitle:UCLocalize("QUEUE")
6433 style:UIBarButtonItemStyleDone
6434 target:self
6435 action:@selector(queueButtonClicked)
6436 ];
6437 [[self navigationItem] setRightBarButtonItem:queueItem];
6438
6439 [queueItem release];
6440 } else {
6441 [[self navigationItem] setRightBarButtonItem:nil];
6442 }
bf8476c8 6443#endif
b5e7eebb 6444}
7b0ce2da 6445
3bd1c2a2 6446- (bool) isLoading {
9fe5e5f8
JF
6447 return false;
6448}
6449
7b0ce2da 6450@end
98228790 6451/* }}} */
7b0ce2da 6452
b5e7eebb
GP
6453/* Refresh Bar {{{ */
6454@interface RefreshBar : UINavigationBar {
7b0ce2da
JF
6455 UIProgressIndicator *indicator_;
6456 UITextLabel *prompt_;
6457 UIProgressBar *progress_;
baf80942 6458 UINavigationButton *cancel_;
aa5e5990
JF
6459}
6460
aa5e5990 6461@end
aa5e5990 6462
b5e7eebb 6463@implementation RefreshBar
01d93940 6464
39cda3a8
GP
6465- (void) positionViews {
6466 CGRect frame = [cancel_ frame];
6467 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6468 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6469 [cancel_ setFrame:frame];
6470
6471 CGSize prgsize = {75, 100};
6472 CGRect prgrect = {{
6473 [self frame].size.width - prgsize.width - 10,
6474 ([self frame].size.height - prgsize.height) / 2
6475 } , prgsize};
6476 [progress_ setFrame:prgrect];
6477
6478 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6479 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6480 CGRect indrect = {{indoffset, indoffset}, indsize};
6481 [indicator_ setFrame:indrect];
6482
6483 CGSize prmsize = {215, indsize.height + 4};
6484 CGRect prmrect = {{
6485 indoffset * 2 + indsize.width,
6486 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6487 }, prmsize};
6488 [prompt_ setFrame:prmrect];
6489}
6490
6491- (void)setFrame:(CGRect)frame {
6492 [super setFrame:frame];
6493
6494 [self positionViews];
6495}
6496
b5e7eebb
GP
6497- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6498 if ((self = [super initWithFrame:frame])) {
6499 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
01d93940 6500
b5e7eebb
GP
6501 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6502 [self setBarStyle:1];
01d93940 6503
b5e7eebb 6504 int barstyle([self _barStyle:NO]);
670a0494 6505 bool ugly(barstyle == 0);
807ae6d7
JF
6506
6507 UIProgressIndicatorStyle style = ugly ?
6508 UIProgressIndicatorStyleMediumBrown :
6509 UIProgressIndicatorStyleMediumWhite;
6510
39cda3a8 6511 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
807ae6d7 6512 [indicator_ setStyle:style];
39cda3a8 6513 [indicator_ startAnimation];
b5e7eebb 6514 [self addSubview:indicator_];
807ae6d7 6515
39cda3a8 6516 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
807ae6d7
JF
6517 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6518 [prompt_ setBackgroundColor:[UIColor clearColor]];
39cda3a8 6519 [prompt_ setFont:[UIFont systemFontOfSize:15]];
b5e7eebb 6520 [self addSubview:prompt_];
807ae6d7 6521
39cda3a8
GP
6522 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6523 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
04fe1349 6524 [progress_ setStyle:0];
39cda3a8
GP
6525 [self addSubview:progress_];
6526
43f3d7f6 6527 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
8c02abc8 6528 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
b5e7eebb 6529 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
39cda3a8
GP
6530 [cancel_ setBarStyle:barstyle];
6531
6532 [self positionViews];
807ae6d7
JF
6533 } return self;
6534}
6535
b5e7eebb 6536- (void) cancel {
807ae6d7
JF
6537 [cancel_ removeFromSuperview];
6538}
6539
b5e7eebb
GP
6540- (void) start {
6541 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6542 [progress_ setProgress:0];
6543 [self addSubview:cancel_];
6544}
6545
6546- (void) stop {
6547 [cancel_ removeFromSuperview];
6548}
6549
6550- (void) setPrompt:(NSString *)prompt {
6551 [prompt_ setText:prompt];
6552}
6553
6554- (void) setProgress:(float)progress {
6555 [progress_ setProgress:progress];
6556}
6557
6558@end
6559/* }}} */
6560
6561/* Cydia Tab Bar Controller {{{ */
8c02abc8
GP
6562@interface CYTabBarController : UITabBarController {
6563 Database *database_;
b5e7eebb
GP
6564}
6565
b5e7eebb
GP
6566@end
6567
6568@implementation CYTabBarController
6569
8c02abc8
GP
6570/* XXX: some logic should probably go here related to
6571freeing the view controllers on tab change */
807ae6d7 6572
b5e7eebb
GP
6573- (void) reloadData {
6574 size_t count([[self viewControllers] count]);
6575 for (size_t i(0); i != count; ++i) {
6576 UIViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6577 [page reloadData];
6578 }
6579}
6580
b5e7eebb
GP
6581- (id) initWithDatabase: (Database *)database {
6582 if ((self = [super init]) != nil) {
6583 database_ = database;
b5e7eebb
GP
6584 } return self;
6585}
6586
6587@end
6588/* }}} */
6589
6590/* Cydia Navigation Controller {{{ */
6591@interface CYNavigationController : UINavigationController <
6592 ProgressDelegate
6593> {
6594 _transient Database *database_;
6595 id delegate_;
6596}
6597
6598- (id) initWithDatabase:(Database *)database;
6599- (void) reloadData;
6600
6601@end
6602
6603
6604@implementation CYNavigationController
6605
9cb0bff2
GP
6606- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6607 // Inherit autorotation settings for modal parents.
6608 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6609 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6610 } else {
6611 return [super shouldAutorotateToInterfaceOrientation:orientation];
6612 }
6613}
6614
b5e7eebb
GP
6615- (void) dealloc {
6616 [super dealloc];
6617}
6618
6619- (void) reloadData {
6620 size_t count([[self viewControllers] count]);
6621 for (size_t i(0); i != count; ++i) {
6622 UIViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6623 [page reloadData];
6624 }
6625}
6626
6627- (void) setDelegate:(id)delegate {
6628 delegate_ = delegate;
6629}
6630
6631- (id) initWithDatabase:(Database *)database {
6632 if ((self = [super init]) != nil) {
6633 database_ = database;
6634 } return self;
6635}
6636
807ae6d7
JF
6637@end
6638/* }}} */
6639/* Cydia:// Protocol {{{ */
6640@interface CydiaURLProtocol : NSURLProtocol {
6641}
6642
6643@end
6644
6645@implementation CydiaURLProtocol
6646
6647+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
6648 NSURL *url([request URL]);
6649 if (url == nil)
6650 return NO;
6651 NSString *scheme([[url scheme] lowercaseString]);
6652 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6653 return NO;
6654 return YES;
6655}
6656
6657+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6658 return request;
6659}
6660
9fe5e5f8
JF
6661- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6662 id<NSURLProtocolClient> client([self client]);
189a73d0
JF
6663 if (icon == nil)
6664 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6665 else {
6666 NSData *data(UIImagePNGRepresentation(icon));
9fe5e5f8 6667
189a73d0
JF
6668 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6669 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6670 [client URLProtocol:self didLoadData:data];
6671 [client URLProtocolDidFinishLoading:self];
6672 }
9fe5e5f8
JF
6673}
6674
807ae6d7
JF
6675- (void) startLoading {
6676 id<NSURLProtocolClient> client([self client]);
6677 NSURLRequest *request([self request]);
6678
6679 NSURL *url([request URL]);
6680 NSString *href([url absoluteString]);
6681
6682 NSString *path([href substringFromIndex:8]);
6683 NSRange slash([path rangeOfString:@"/"]);
6684
6685 NSString *command;
6686 if (slash.location == NSNotFound) {
6687 command = path;
6688 path = nil;
6689 } else {
6690 command = [path substringToIndex:slash.location];
6691 path = [path substringFromIndex:(slash.location + 1)];
6692 }
6693
6694 Database *database([Database sharedInstance]);
6695
6696 if ([command isEqualToString:@"package-icon"]) {
6697 if (path == nil)
6698 goto fail;
dec6029f 6699 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
807ae6d7
JF
6700 Package *package([database packageWithName:path]);
6701 if (package == nil)
6702 goto fail;
dec6029f 6703 UIImage *icon([package icon]);
9fe5e5f8 6704 [self _returnPNGWithImage:icon forRequest:request];
16f2786b
JF
6705 } else if ([command isEqualToString:@"source-icon"]) {
6706 if (path == nil)
6707 goto fail;
6708 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6709 NSString *source(Simplify(path));
16f2786b
JF
6710 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6711 if (icon == nil)
6712 icon = [UIImage applicationImageNamed:@"unknown.png"];
9fe5e5f8
JF
6713 [self _returnPNGWithImage:icon forRequest:request];
6714 } else if ([command isEqualToString:@"uikit-image"]) {
6715 if (path == nil)
6716 goto fail;
6717 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6718 UIImage *icon(_UIImageWithName(path));
6719 [self _returnPNGWithImage:icon forRequest:request];
dec6029f
JF
6720 } else if ([command isEqualToString:@"section-icon"]) {
6721 if (path == nil)
6722 goto fail;
6723 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6724 NSString *section(Simplify(path));
dec6029f
JF
6725 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6726 if (icon == nil)
6727 icon = [UIImage applicationImageNamed:@"unknown.png"];
9fe5e5f8 6728 [self _returnPNGWithImage:icon forRequest:request];
807ae6d7
JF
6729 } else fail: {
6730 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6731 }
6732}
6733
6734- (void) stopLoading {
6735}
6736
6737@end
6738/* }}} */
6739
adb61bda
GP
6740/* Sections Controller {{{ */
6741@interface SectionsController : CYViewController {
807ae6d7
JF
6742 _transient Database *database_;
6743 NSMutableArray *sections_;
6744 NSMutableArray *filtered_;
46aa9775 6745 UITableView *list_;
807ae6d7
JF
6746 UIView *accessory_;
6747 BOOL editing_;
6748}
6749
b5e7eebb 6750- (id) initWithDatabase:(Database *)database;
807ae6d7
JF
6751- (void) reloadData;
6752- (void) resetView;
6753
6754@end
6755
adb61bda 6756@implementation SectionsController
807ae6d7
JF
6757
6758- (void) dealloc {
6759 [list_ setDataSource:nil];
6760 [list_ setDelegate:nil];
6761
6762 [sections_ release];
6763 [filtered_ release];
807ae6d7
JF
6764 [list_ release];
6765 [accessory_ release];
6766 [super dealloc];
6767}
6768
b5e7eebb
GP
6769- (void) viewDidAppear:(BOOL)animated {
6770 [super viewDidAppear:animated];
6771 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6772}
6773
46aa9775
GP
6774- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6775 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6776 return section;
807ae6d7
JF
6777}
6778
46aa9775
GP
6779- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6780 return editing_ ? [sections_ count] : [filtered_ count] + 1;
807ae6d7
JF
6781}
6782
21ea11a4
GP
6783/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6784 return 45.0f;
6785}*/
807ae6d7 6786
46aa9775 6787- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
GP
6788 static NSString *reuseIdentifier = @"SectionCell";
6789
6790 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6791 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
46aa9775 6792 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
807ae6d7 6793
46aa9775 6794 return cell;
807ae6d7
JF
6795}
6796
46aa9775
GP
6797- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6798 Section *section = [self sectionAtIndexPath:indexPath];
6799 NSString *name = [section name];
807ae6d7
JF
6800 NSString *title;
6801
46aa9775 6802 if ([indexPath row] == 0) {
807ae6d7
JF
6803 section = nil;
6804 name = nil;
43f3d7f6 6805 title = UCLocalize("ALL_PACKAGES");
807ae6d7 6806 } else {
28ce8704
JF
6807 if (name != nil) {
6808 name = [NSString stringWithString:name];
f79a4512 6809 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
28ce8704 6810 } else {
807ae6d7 6811 name = @"";
43f3d7f6 6812 title = UCLocalize("NO_SECTION");
807ae6d7
JF
6813 }
6814 }
6815
adb61bda 6816 FilteredPackageController *table = [[[FilteredPackageController alloc]
b5e7eebb 6817 initWithDatabase:database_
807ae6d7 6818 title:title
670a0494 6819 filter:@selector(isVisibleInSection:)
807ae6d7
JF
6820 with:name
6821 ] autorelease];
6822
6823 [table setDelegate:delegate_];
6824
b5e7eebb 6825 [[self navigationController] pushViewController:table animated:YES];
807ae6d7
JF
6826}
6827
b5e7eebb
GP
6828- (id) title { return UCLocalize("SECTIONS"); }
6829
6830- (id) initWithDatabase:(Database *)database {
6831 if ((self = [super init]) != nil) {
807ae6d7
JF
6832 database_ = database;
6833
b5e7eebb
GP
6834 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6835
807ae6d7
JF
6836 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6837 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6838
b5e7eebb 6839 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
04fe1349 6840 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 6841 [list_ setRowHeight:45.0f];
b5e7eebb 6842 [[self view] addSubview:list_];
807ae6d7 6843
46aa9775 6844 [list_ setDataSource:self];
b5e7eebb 6845 [list_ setDelegate:self];
807ae6d7
JF
6846
6847 [self reloadData];
807ae6d7
JF
6848 } return self;
6849}
6850
6851- (void) reloadData {
6852 NSArray *packages = [database_ packages];
6853
6854 [sections_ removeAllObjects];
6855 [filtered_ removeAllObjects];
6856
f79a4512
JF
6857#if 0
6858 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6859 SectionMap sections;
6860 sections.resize(64);
6861#else
6862 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6863#endif
807ae6d7
JF
6864
6865 _trace();
c4dcf2c2 6866 for (Package *package in packages) {
807ae6d7 6867 NSString *name([package section]);
f79a4512 6868 NSString *key(name == nil ? @"" : name);
807ae6d7 6869
f79a4512
JF
6870#if 0
6871 Section **section;
6872
6873 _profile(SectionsView$reloadData$Section)
6874 section = &sections[key];
6875 if (*section == nil) {
6876 _profile(SectionsView$reloadData$Section$Allocate)
9fcbca29 6877 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
f79a4512
JF
6878 _end
6879 }
6880 _end
6881
6882 [*section addToCount];
6883
6884 _profile(SectionsView$reloadData$Filter)
670a0494 6885 if (![package valid] || ![package visible])
f79a4512
JF
6886 continue;
6887 _end
6888
6889 [*section addToRow];
6890#else
6891 Section *section;
6892
6893 _profile(SectionsView$reloadData$Section)
6894 section = [sections objectForKey:key];
807ae6d7 6895 if (section == nil) {
f79a4512 6896 _profile(SectionsView$reloadData$Section$Allocate)
9fcbca29 6897 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
f79a4512
JF
6898 [sections setObject:section forKey:key];
6899 _end
807ae6d7 6900 }
f79a4512
JF
6901 _end
6902
6903 [section addToCount];
6d9712c4 6904
f79a4512 6905 _profile(SectionsView$reloadData$Filter)
670a0494 6906 if (![package valid] || ![package visible])
f79a4512
JF
6907 continue;
6908 _end
6909
6910 [section addToRow];
6911#endif
b4d89997 6912 }
807ae6d7 6913 _trace();
dc5812ec 6914
f79a4512
JF
6915#if 0
6916 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6917 [sections_ addObject:i->second];
6918#else
6d9712c4 6919 [sections_ addObjectsFromArray:[sections allValues]];
f79a4512 6920#endif
6d9712c4 6921
677b8415 6922 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
dc5812ec 6923
f79a4512
JF
6924 for (Section *section in sections_) {
6925 size_t count([section row]);
677b8415 6926 if (count == 0)
f79a4512 6927 continue;
dc5812ec 6928
9fcbca29 6929 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
f79a4512
JF
6930 [section setCount:count];
6931 [filtered_ addObject:section];
b4d89997 6932 }
2367a917 6933
b5e7eebb
GP
6934 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6935 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6936 style:UIBarButtonItemStylePlain
6937 target:self
6938 action:@selector(editButtonClicked)
6939 ];
8779218a 6940 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
b5e7eebb
GP
6941 [rightItem release];
6942
b4d89997 6943 [list_ reloadData];
807ae6d7 6944 _trace();
36bb2ca2 6945}
2367a917 6946
6d9712c4
JF
6947- (void) resetView {
6948 if (editing_)
b5e7eebb 6949 [self editButtonClicked];
36bb2ca2 6950}
2367a917 6951
b5e7eebb 6952- (void) editButtonClicked {
6d9712c4
JF
6953 if ((editing_ = !editing_))
6954 [list_ reloadData];
807ae6d7 6955 else
6d9712c4 6956 [delegate_ updateData];
b5e7eebb
GP
6957
6958 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6959 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6960 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
baf80942
JF
6961}
6962
a54b1c10
JF
6963- (UIView *) accessoryView {
6964 return accessory_;
6965}
6966
dc5812ec 6967@end
2367a917 6968/* }}} */
adb61bda
GP
6969/* Changes Controller {{{ */
6970@interface ChangesController : CYViewController {
36bb2ca2 6971 _transient Database *database_;
dc5812ec
JF
6972 NSMutableArray *packages_;
6973 NSMutableArray *sections_;
327624b6 6974 UITableView *list_;
36bb2ca2 6975 unsigned upgrades_;
904e4273 6976 BOOL hasSentFirstLoad_;
dc5812ec
JF
6977}
6978
b5e7eebb 6979- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
36bb2ca2 6980- (void) reloadData;
dc5812ec 6981
dc5812ec
JF
6982@end
6983
adb61bda 6984@implementation ChangesController
b4d89997
JF
6985
6986- (void) dealloc {
327624b6 6987 [list_ setDelegate:nil];
36bb2ca2
JF
6988 [list_ setDataSource:nil];
6989
b4d89997
JF
6990 [packages_ release];
6991 [sections_ release];
36bb2ca2 6992 [list_ release];
b4d89997
JF
6993 [super dealloc];
6994}
dc5812ec 6995
b5e7eebb
GP
6996- (void) viewDidAppear:(BOOL)animated {
6997 [super viewDidAppear:animated];
904e4273
RP
6998 if (!hasSentFirstLoad_) {
6999 hasSentFirstLoad_ = YES;
7000 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7001 } else {
7002 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7003 }
b5e7eebb
GP
7004}
7005
327624b6
JF
7006- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7007 NSInteger count([sections_ count]);
7008 return count == 0 ? 1 : count;
dc5812ec
JF
7009}
7010
327624b6
JF
7011- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7012 if ([sections_ count] == 0)
7013 return nil;
dc5812ec
JF
7014 return [[sections_ objectAtIndex:section] name];
7015}
7016
327624b6
JF
7017- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7018 if ([sections_ count] == 0)
7019 return 0;
7020 return [[sections_ objectAtIndex:section] count];
dc5812ec
JF
7021}
7022
327624b6
JF
7023- (Package *) packageAtIndexPath:(NSIndexPath *)path {
7024 Section *section([sections_ objectAtIndex:[path section]]);
7025 NSInteger row([path row]);
7026 return [packages_ objectAtIndex:([section row] + row)];
dc5812ec
JF
7027}
7028
327624b6
JF
7029- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7030 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
7031 if (cell == nil)
7032 cell = [[[PackageCell alloc] init] autorelease];
7033 [cell setPackage:[self packageAtIndexPath:path]];
7034 return cell;
dc5812ec
JF
7035}
7036
21ea11a4 7037/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
327624b6 7038 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
21ea11a4 7039}*/
dc5812ec 7040
327624b6
JF
7041- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7042 Package *package([self packageAtIndexPath:path]);
adb61bda 7043 PackageController *view([delegate_ packageController]);
36bb2ca2
JF
7044 [view setDelegate:delegate_];
7045 [view setPackage:package];
b5e7eebb 7046 [[self navigationController] pushViewController:view animated:YES];
327624b6 7047 return path;
dc5812ec
JF
7048}
7049
b5e7eebb
GP
7050- (void) refreshButtonClicked {
7051 [[UIApplication sharedApplication] beginUpdate];
7052 [[self navigationItem] setLeftBarButtonItem:nil];
9a7b04c5
JF
7053}
7054
b5e7eebb 7055- (void) upgradeButtonClicked {
36bb2ca2 7056 [delegate_ distUpgrade];
dc5812ec
JF
7057}
7058
b5e7eebb
GP
7059- (id) title { return UCLocalize("CHANGES"); }
7060
7061- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7062 if ((self = [super init]) != nil) {
36bb2ca2 7063 database_ = database;
b5e7eebb 7064 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
dc5812ec 7065
b4d89997
JF
7066 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7067 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 7068
b5e7eebb 7069 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 7070 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 7071 [list_ setRowHeight:73.0f];
b5e7eebb 7072 [[self view] addSubview:list_];
36bb2ca2 7073
b4d89997 7074 [list_ setDataSource:self];
327624b6 7075 [list_ setDelegate:self];
dc5812ec 7076
77801ff1 7077 delegate_ = delegate;
dc5812ec
JF
7078 } return self;
7079}
7080
77801ff1 7081- (void) _reloadPackages:(NSArray *)packages {
807ae6d7 7082 _trace();
c4dcf2c2 7083 for (Package *package in packages)
6d9712c4 7084 if (
6a155117 7085 [package uninstalled] && [package valid] && [package visible] ||
189a73d0 7086 [package upgradableAndEssential:YES]
6d9712c4 7087 )
b4d89997 7088 [packages_ addObject:package];
2367a917 7089
807ae6d7 7090 _trace();
df213583 7091 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
807ae6d7 7092 _trace();
77801ff1
JF
7093}
7094
7095- (void) reloadData {
7096 NSArray *packages = [database_ packages];
7097
7098 [packages_ removeAllObjects];
7099 [sections_ removeAllObjects];
7100
7101 UIProgressHUD *hud([delegate_ addProgressHUD]);
7102 // XXX: localize
7103 [hud setText:@"Loading Changes"];
7104 NSLog(@"HUD:%@::%@", delegate_, hud);
7105 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7106 [delegate_ removeProgressHUD:hud];
dc5812ec 7107
43f3d7f6
JF
7108 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7109 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
dc5812ec 7110 Section *section = nil;
807ae6d7 7111 NSDate *last = nil;
b4d89997 7112
36bb2ca2
JF
7113 upgrades_ = 0;
7114 bool unseens = false;
7115
677b8415 7116 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
36bb2ca2 7117
dc5812ec
JF
7118 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7119 Package *package = [packages_ objectAtIndex:offset];
dc5812ec 7120
677b8415 7121 BOOL uae = [package upgradableAndEssential:YES];
f79a4512
JF
7122
7123 if (!uae) {
36bb2ca2 7124 unseens = true;
f79a4512 7125 NSDate *seen;
dc5812ec 7126
adb61bda 7127 _profile(ChangesController$reloadData$Remember)
f79a4512
JF
7128 seen = [package seen];
7129 _end
7130
677b8415 7131 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
807ae6d7 7132 last = seen;
723a0072 7133
dc63e78f
JF
7134 NSString *name;
7135 if (seen == nil)
43f3d7f6 7136 name = UCLocalize("UNKNOWN");
dc63e78f 7137 else {
677b8415 7138 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
dc63e78f
JF
7139 [name autorelease];
7140 }
7141
adb61bda 7142 _profile(ChangesController$reloadData$Allocate)
43f3d7f6 7143 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
9fcbca29 7144 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
f79a4512
JF
7145 [sections_ addObject:section];
7146 _end
b4d89997
JF
7147 }
7148
36bb2ca2 7149 [section addToCount];
807ae6d7
JF
7150 } else if ([package ignored])
7151 [ignored addToCount];
7152 else {
7153 ++upgrades_;
7154 [upgradable addToCount];
b4d89997 7155 }
dc5812ec 7156 }
807ae6d7 7157 _trace();
dc5812ec 7158
36bb2ca2 7159 CFRelease(formatter);
b4d89997 7160
36bb2ca2
JF
7161 if (unseens) {
7162 Section *last = [sections_ lastObject];
7163 size_t count = [last count];
7164 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7165 [sections_ removeLastObject];
7166 }
dc5812ec 7167
807ae6d7
JF
7168 if ([ignored count] != 0)
7169 [sections_ insertObject:ignored atIndex:0];
36bb2ca2
JF
7170 if (upgrades_ != 0)
7171 [sections_ insertObject:upgradable atIndex:0];
c25a610d 7172
36bb2ca2 7173 [list_ reloadData];
3178d79b 7174
b5e7eebb
GP
7175 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7176 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7177 style:UIBarButtonItemStylePlain
7178 target:self
7179 action:@selector(upgradeButtonClicked)
7180 ];
7181 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7182 [rightItem release];
7183
7184 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7185 initWithTitle:UCLocalize("REFRESH")
7186 style:UIBarButtonItemStylePlain
7187 target:self
7188 action:@selector(refreshButtonClicked)
7189 ];
7190 if (![[UIApplication sharedApplication] updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7191 [leftItem release];
8fe19fc1
JF
7192}
7193
3178d79b
JF
7194@end
7195/* }}} */
adb61bda
GP
7196/* Search Controller {{{ */
7197@interface SearchController : FilteredPackageController {
b5e7eebb 7198 id search_;
36bb2ca2 7199}
b4d89997 7200
b5e7eebb 7201- (id) initWithDatabase:(Database *)database;
36bb2ca2 7202- (void) reloadData;
b4d89997 7203
3178d79b
JF
7204@end
7205
adb61bda 7206@implementation SearchController
3178d79b 7207
b4d89997 7208- (void) dealloc {
b5e7eebb 7209 [search_ release];
36bb2ca2 7210 [super dealloc];
b4d89997
JF
7211}
7212
b5e7eebb
GP
7213- (void) searchBarSearchButtonClicked:(id)searchBar {
7214 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7215 [search_ resignFirstResponder];
01d93940 7216 [self reloadData];
36bb2ca2 7217}
b4d89997 7218
b5e7eebb
GP
7219- (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7220 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
01d93940 7221 [self reloadData];
36bb2ca2 7222}
b4d89997 7223
b5e7eebb 7224- (id) title { return nil; }
ab398adf 7225
b5e7eebb 7226- (id) initWithDatabase:(Database *)database {
dcb47737
RP
7227 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7228}
7229
7230- (void)viewDidAppear:(BOOL)animated {
7231 [super viewDidAppear:animated];
7232 if (!search_) {
7233 search_ = [[objc_getClass("UISearchBar") alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7234 [search_ layoutSubviews];
b5e7eebb 7235 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
dcb47737
RP
7236 UITextField *textField = [search_ searchField];
7237 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
b5e7eebb 7238 [search_ setDelegate:self];
dcb47737
RP
7239 [textField setEnablesReturnKeyAutomatically:NO];
7240 [[self navigationItem] setTitleView:textField];
7241 }
3178d79b
JF
7242}
7243
807ae6d7
JF
7244- (void) _reloadData {
7245}
b4d89997 7246
807ae6d7 7247- (void) reloadData {
adb61bda 7248 _profile(SearchController$reloadData)
b5e7eebb 7249 [packages_ reloadData];
808c6eb6
JF
7250 _end
7251 PrintTimes();
b5e7eebb 7252 [packages_ resetCursor];
807ae6d7 7253}
8fe19fc1 7254
8e05f686
RP
7255- (void) didSelectPackage:(Package *)package {
7256 [search_ resignFirstResponder];
7257 [super didSelectPackage:package];
7258}
7259
807ae6d7
JF
7260@end
7261/* }}} */
adb61bda
GP
7262/* Settings Controller {{{ */
7263@interface SettingsController : CYViewController {
807ae6d7
JF
7264 _transient Database *database_;
7265 NSString *name_;
7266 Package *package_;
7267 UIPreferencesTable *table_;
7268 _UISwitchSlider *subscribedSwitch_;
7269 _UISwitchSlider *ignoredSwitch_;
7270 UIPreferencesControlTableCell *subscribedCell_;
7271 UIPreferencesControlTableCell *ignoredCell_;
7272}
b4d89997 7273
b5e7eebb 7274- (id) initWithDatabase:(Database *)database package:(NSString *)package;
b4d89997 7275
807ae6d7 7276@end
b4d89997 7277
adb61bda 7278@implementation SettingsController
b4d89997 7279
807ae6d7
JF
7280- (void) dealloc {
7281 [table_ setDataSource:nil];
b4d89997 7282
807ae6d7
JF
7283 [name_ release];
7284 if (package_ != nil)
7285 [package_ release];
7286 [table_ release];
7287 [subscribedSwitch_ release];
7288 [ignoredSwitch_ release];
7289 [subscribedCell_ release];
7290 [ignoredCell_ release];
7291 [super dealloc];
7292}
b4d89997 7293
807ae6d7
JF
7294- (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7295 if (package_ == nil)
7296 return 0;
b4d89997 7297
807ae6d7
JF
7298 return 2;
7299}
36bb2ca2 7300
807ae6d7
JF
7301- (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7302 if (package_ == nil)
7303 return nil;
baf80942 7304
807ae6d7
JF
7305 switch (group) {
7306 case 0: return nil;
7307 case 1: return nil;
baf80942 7308
670a0494 7309 _nodefault
807ae6d7 7310 }
baf80942 7311
807ae6d7 7312 return nil;
3178d79b
JF
7313}
7314
807ae6d7
JF
7315- (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7316 if (package_ == nil)
7317 return NO;
baf80942 7318
807ae6d7
JF
7319 switch (group) {
7320 case 0: return NO;
7321 case 1: return YES;
b4d89997 7322
670a0494 7323 _nodefault
807ae6d7 7324 }
3178d79b 7325
807ae6d7 7326 return NO;
dc5812ec
JF
7327}
7328
807ae6d7
JF
7329- (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7330 if (package_ == nil)
7331 return 0;
dc5812ec 7332
807ae6d7
JF
7333 switch (group) {
7334 case 0: return 1;
7335 case 1: return 1;
3178d79b 7336
670a0494 7337 _nodefault
807ae6d7 7338 }
baf80942 7339
807ae6d7 7340 return 0;
36bb2ca2 7341}
b4d89997 7342
807ae6d7
JF
7343- (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7344 if (package_ == nil)
7345 return;
b4d89997 7346
807ae6d7 7347 _UISwitchSlider *slider([cell control]);
807ae6d7
JF
7348 BOOL value([slider value] != 0);
7349 NSMutableDictionary *metadata([package_ metadata]);
baf80942 7350
807ae6d7
JF
7351 BOOL before;
7352 if (NSNumber *number = [metadata objectForKey:key])
7353 before = [number boolValue];
7354 else
7355 before = NO;
36bb2ca2 7356
807ae6d7
JF
7357 if (value != before) {
7358 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7359 Changed_ = true;
807ae6d7
JF
7360 [delegate_ updateData];
7361 }
baf80942
JF
7362}
7363
807ae6d7
JF
7364- (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7365 [self onSomething:cell withKey:@"IsSubscribed"];
36bb2ca2 7366}
b4d89997 7367
807ae6d7
JF
7368- (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7369 [self onSomething:cell withKey:@"IsIgnored"];
8fe19fc1
JF
7370}
7371
807ae6d7
JF
7372- (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7373 if (package_ == nil)
7374 return nil;
770f2a8e 7375
807ae6d7
JF
7376 switch (group) {
7377 case 0: switch (row) {
7378 case 0:
7379 return subscribedCell_;
7380 case 1:
7381 return ignoredCell_;
670a0494 7382 _nodefault
807ae6d7
JF
7383 } break;
7384
7385 case 1: switch (row) {
7386 case 0: {
7387 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
9487f027 7388 [cell setShowSelection:NO];
43f3d7f6 7389 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
807ae6d7
JF
7390 return cell;
7391 }
770f2a8e 7392
670a0494 7393 _nodefault
807ae6d7 7394 } break;
770f2a8e 7395
670a0494 7396 _nodefault
807ae6d7 7397 }
770f2a8e 7398
807ae6d7 7399 return nil;
770f2a8e
JF
7400}
7401
b5e7eebb
GP
7402- (id) title { return UCLocalize("SETTINGS"); }
7403
7404- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7405 if ((self = [super init])) {
807ae6d7
JF
7406 database_ = database;
7407 name_ = [package retain];
770f2a8e 7408
b5e7eebb
GP
7409 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7410
7411 table_ = [[UIPreferencesTable alloc] initWithFrame:[[self view] bounds]];
7412 [[self view] addSubview:table_];
770f2a8e 7413
807ae6d7 7414 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
bfc87a4d 7415 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
770f2a8e 7416
807ae6d7 7417 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
bfc87a4d 7418 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
770f2a8e 7419
807ae6d7 7420 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
9487f027 7421 [subscribedCell_ setShowSelection:NO];
43f3d7f6 7422 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
807ae6d7 7423 [subscribedCell_ setControl:subscribedSwitch_];
770f2a8e 7424
807ae6d7 7425 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
9487f027 7426 [ignoredCell_ setShowSelection:NO];
43f3d7f6 7427 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
807ae6d7 7428 [ignoredCell_ setControl:ignoredSwitch_];
770f2a8e 7429
807ae6d7
JF
7430 [table_ setDataSource:self];
7431 [self reloadData];
7432 } return self;
7433}
770f2a8e 7434
807ae6d7
JF
7435- (void) reloadData {
7436 if (package_ != nil)
7437 [package_ autorelease];
7438 package_ = [database_ packageWithName:name_];
7439 if (package_ != nil) {
7440 [package_ retain];
7441 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7442 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
770f2a8e 7443 }
807ae6d7
JF
7444
7445 [table_ reloadData];
770f2a8e
JF
7446}
7447
770f2a8e 7448@end
bfc87a4d 7449/* }}} */
770f2a8e 7450
adb61bda
GP
7451/* Signature Controller {{{ */
7452@interface SignatureController : CYBrowserController {
770f2a8e
JF
7453 _transient Database *database_;
7454 NSString *package_;
7455}
7456
b5e7eebb 7457- (id) initWithDatabase:(Database *)database package:(NSString *)package;
770f2a8e
JF
7458
7459@end
7460
adb61bda 7461@implementation SignatureController
770f2a8e
JF
7462
7463- (void) dealloc {
7464 [package_ release];
7465 [super dealloc];
7466}
7467
7468- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7469 // XXX: dude!
7470 [super webView:sender didClearWindowObject:window forFrame:frame];
7471}
7472
b5e7eebb
GP
7473- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7474 if ((self = [super init]) != nil) {
770f2a8e
JF
7475 database_ = database;
7476 package_ = [package retain];
7477 [self reloadData];
7478 } return self;
7479}
7480
7481- (void) reloadData {
7482 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7483}
7484
21c6da4b
GP
7485@end
7486/* }}} */
7487/* Role Controller {{{ */
7488@interface RoleController : CYViewController {
7489 _transient Database *database_;
7490 id roledelegate_;
7491 UITableView *table_;
7492 UISegmentedControl *segment_;
7493 UIView *container_;
7494}
7495@end
7496
7497@implementation RoleController
7498- (void) dealloc {
7499 [table_ release];
7500 [segment_ release];
7501 [container_ release];
7502
7503 [super dealloc];
7504}
7505
7506- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7507 if ((self = [super init])) {
7508 database_ = database;
7509 roledelegate_ = delegate;
7510
7511 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7512
7513 NSArray *items = [NSArray arrayWithObjects:
7514 UCLocalize("USER"),
7515 UCLocalize("HACKER"),
7516 UCLocalize("DEVELOPER"),
7517 nil];
7518 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7519 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7520 [container_ addSubview:segment_];
21c6da4b
GP
7521
7522 int index = -1;
7523 if ([Role_ isEqualToString:@"User"]) index = 0;
7524 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7525 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7526 if (index != -1) {
7527 [segment_ setSelectedSegmentIndex:index];
7528 [self showDoneButton];
7529 }
7530
7531 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
e62f29c6 7532 [self resizeSegmentedControl];
21c6da4b
GP
7533
7534 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7535 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7536 [table_ setDelegate:self];
7537 [table_ setDataSource:self];
7538 [[self view] addSubview:table_];
7539 [table_ reloadData];
7540 } return self;
7541}
7542
e62f29c6
GP
7543- (void) resizeSegmentedControl {
7544 CGFloat width = [[self view] frame].size.width;
7545 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7546}
7547
2bdd73bd
GP
7548- (void) viewWillAppear:(BOOL)animated {
7549 [super viewWillAppear:animated];
7550
e62f29c6
GP
7551 [self resizeSegmentedControl];
7552}
7553
7554- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7555 [self resizeSegmentedControl];
7556}
7557
7558- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7559 [self resizeSegmentedControl];
2bdd73bd
GP
7560}
7561
21c6da4b 7562- (void) save {
124c6201
GP
7563 NSString *role = nil;
7564
21c6da4b 7565 switch ([segment_ selectedSegmentIndex]) {
124c6201
GP
7566 case 0: role = @"User"; break;
7567 case 1: role = @"Hacker"; break;
7568 case 2: role = @"Developer"; break;
21c6da4b
GP
7569
7570 _nodefault
7571 }
7572
124c6201
GP
7573 if (![role isEqualToString:Role_]) {
7574 Role_ = role;
7575
7576 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7577 Role_, @"Role",
7578 nil];
21c6da4b 7579
124c6201 7580 [Metadata_ setObject:Settings_ forKey:@"Settings"];
21c6da4b 7581
124c6201 7582 Changed_ = true;
21c6da4b 7583
124c6201
GP
7584 [roledelegate_ updateData];
7585 }
21c6da4b
GP
7586}
7587
7588- (void) segmentChanged:(UISegmentedControl *)control {
7589 [self showDoneButton];
7590}
7591
7592- (void) doneButtonClicked {
7593 [self save];
7594 [[self navigationController] dismissModalViewControllerAnimated:YES];
7595}
7596
7597- (void) showDoneButton {
7598 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7599 initWithTitle:UCLocalize("DONE")
7600 style:UIBarButtonItemStyleDone
7601 target:self
7602 action:@selector(doneButtonClicked)
7603 ];
7604 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7605 [rightItem release];
7606}
7607
7608- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
e62f29c6
GP
7609 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7610 return 6;
21c6da4b
GP
7611}
7612
7613- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7614 return 0; // :(
7615}
7616
7617- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7618 return nil; // This method is required by the protocol.
7619}
7620
7621- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7622 if (section == 1)
7623 return UCLocalize("ROLE_EX");
7624 if (section == 4)
7625 return [NSString stringWithFormat:
7626 @"%@: %@\n%@: %@\n%@: %@",
7627 UCLocalize("USER"), UCLocalize("USER_EX"),
7628 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7629 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7630 ];
7631 else return nil;
7632}
7633
7634- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7635 if (section == 3) return 44.0f;
7636 else return 0;
7637}
7638
7639- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7640 if (section == 3) return container_;
7641 else return nil;
7642}
7643
770f2a8e 7644@end
807ae6d7 7645/* }}} */
770f2a8e 7646
8c02abc8
GP
7647/* Cydia Container {{{ */
7648@interface CYContainer : UIViewController <ProgressDelegate> {
7649 _transient Database *database_;
7650 RefreshBar *refreshbar_;
7651
7652 bool dropped_;
7653 bool updating_;
7654 id updatedelegate_;
9cb0bff2 7655 UIViewController *root_;
8c02abc8
GP
7656}
7657
7658@end
7659
7660@implementation CYContainer
7661
9cb0bff2
GP
7662// NOTE: UIWindow only sends the top controller these messages,
7663// So we have to forward them on.
7664
7665- (void) viewDidAppear:(BOOL)animated {
7666 [super viewDidAppear:animated];
7667 [root_ viewDidAppear:animated];
7668}
7669
7670- (void) viewWillAppear:(BOOL)animated {
7671 [super viewWillAppear:animated];
7672 [root_ viewWillAppear:animated];
7673}
7674
7675- (void) viewDidDisappear:(BOOL)animated {
7676 [super viewDidDisappear:animated];
7677 [root_ viewDidDisappear:animated];
7678}
7679
7680- (void) viewWillDisappear:(BOOL)animated {
7681 [super viewWillDisappear:animated];
7682 [root_ viewWillDisappear:animated];
7683}
7684
8c02abc8
GP
7685- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7686 return YES; /* XXX: return YES; */
7687}
7688
7689- (void) setRootController:(UIViewController *)controller {
7690 root_ = controller;
7691 [[self view] addSubview:[root_ view]];
7692}
7693
7694- (void) setUpdate:(NSDate *)date {
7695 [self beginUpdate];
7696}
7697
7698- (void) beginUpdate {
7699 [self dropBar:YES];
7700 [refreshbar_ start];
7701
7702 updating_ = true;
7703
7704 [NSThread
7705 detachNewThreadSelector:@selector(performUpdate)
7706 toTarget:self
7707 withObject:nil
7708 ];
7709}
7710
7711- (void) performUpdate { _pooled
7712 Status status;
7713 status.setDelegate(self);
7714 [database_ updateWithStatus:status];
7715
7716 [self
7717 performSelectorOnMainThread:@selector(completeUpdate)
7718 withObject:nil
7719 waitUntilDone:NO
7720 ];
7721}
7722
7723- (void) completeUpdate {
7724 updating_ = false;
7725
7726 [self raiseBar:YES];
7727 [refreshbar_ stop];
7728 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7729}
7730
7731- (void) cancelUpdate {
7732 [refreshbar_ cancel];
7733 [self completeUpdate];
7734}
7735
7736- (void) cancelPressed {
7737 [self cancelUpdate];
7738}
7739
7740- (BOOL) updating {
7741 return updating_;
7742}
7743
7744- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7745 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7746}
7747
7748- (void) startProgress {
7749}
7750
7751- (void) setProgressTitle:(NSString *)title {
7752 [self
7753 performSelectorOnMainThread:@selector(_setProgressTitle:)
7754 withObject:title
7755 waitUntilDone:YES
7756 ];
7757}
7758
7759- (bool) isCancelling:(size_t)received {
7760 return !updating_;
7761}
7762
7763- (void) setProgressPercent:(float)percent {
7764 [self
7765 performSelectorOnMainThread:@selector(_setProgressPercent:)
7766 withObject:[NSNumber numberWithFloat:percent]
7767 waitUntilDone:YES
7768 ];
7769}
7770
7771- (void) addProgressOutput:(NSString *)output {
7772 [self
7773 performSelectorOnMainThread:@selector(_addProgressOutput:)
7774 withObject:output
7775 waitUntilDone:YES
7776 ];
7777}
7778
7779- (void) _setProgressTitle:(NSString *)title {
7780 [refreshbar_ setPrompt:title];
7781}
7782
7783- (void) _setProgressPercent:(NSNumber *)percent {
7784 [refreshbar_ setProgress:[percent floatValue]];
7785}
7786
7787- (void) _addProgressOutput:(NSString *)output {
7788}
7789
7790- (void) setUpdateDelegate:(id)delegate {
7791 updatedelegate_ = delegate;
7792}
7793
7794- (void) dropBar:(BOOL)animated {
7795 if (dropped_) return;
7796 dropped_ = true;
7797
7798 [[self view] addSubview:refreshbar_];
7799
7800 if (animated) [UIView beginAnimations:nil context:NULL];
7801 CGRect barframe = [refreshbar_ frame];
7802 CGRect viewframe = [[root_ view] frame];
39cda3a8
GP
7803 viewframe.origin.y += barframe.size.height + 20.0f;
7804 viewframe.size.height -= barframe.size.height + 20.0f;
8c02abc8
GP
7805 [[root_ view] setFrame:viewframe];
7806 if (animated) [UIView commitAnimations];
7807
9cb0bff2
GP
7808 // Ensure bar has the proper width for our view, it might have changed
7809 barframe.size.width = viewframe.size.width;
7810 [refreshbar_ setFrame:barframe];
7811
8c02abc8
GP
7812 // XXX: fix Apple's layout bug
7813 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7814}
7815
7816- (void) raiseBar:(BOOL)animated {
7817 if (!dropped_) return;
7818 dropped_ = false;
7819
7820 [refreshbar_ removeFromSuperview];
7821
7822 if (animated) [UIView beginAnimations:nil context:NULL];
7823 CGRect barframe = [refreshbar_ frame];
7824 CGRect viewframe = [[root_ view] frame];
39cda3a8
GP
7825 viewframe.origin.y -= barframe.size.height + 20.0f;
7826 viewframe.size.height += barframe.size.height + 20.0f;
8c02abc8
GP
7827 [[root_ view] setFrame:viewframe];
7828 if (animated) [UIView commitAnimations];
7829
7830 // XXX: fix Apple's layout bug
7831 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7832}
7833
e62f29c6 7834- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6b727a05
RP
7835 // XXX: fix Apple's layout bug
7836 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7837}
7838
9cb0bff2 7839- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8c02abc8
GP
7840 if (dropped_) {
7841 [self raiseBar:NO];
7842 [self dropBar:NO];
7843 }
7844
8c02abc8
GP
7845 // XXX: fix Apple's layout bug
7846 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7847}
7848
7849- (void) dealloc {
7850 [refreshbar_ release];
7851 [super dealloc];
7852}
7853
7854- (id) initWithDatabase: (Database *)database {
7855 if ((self = [super init]) != nil) {
7856 database_ = database;
7857
9cb0bff2
GP
7858 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7859
7860 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
8c02abc8
GP
7861 } return self;
7862}
7863
7864@end
7865/* }}} */
7866
b5e7eebb
GP
7867typedef enum {
7868 kCydiaTag = 0,
7869 kSectionsTag = 1,
7870 kChangesTag = 2,
7871 kManageTag = 3,
7872 kInstalledTag = 4,
7873 kSourcesTag = 5,
7874 kSearchTag = 6
7875} CYTabTag;
04fe1349 7876
2367a917 7877@interface Cydia : UIApplication <
adb61bda
GP
7878 ConfirmationControllerDelegate,
7879 ProgressControllerDelegate,
5f6bff8c 7880 CydiaDelegate
2367a917 7881> {
dc5812ec 7882 UIWindow *window_;
8c02abc8 7883 CYContainer *container_;
36bb2ca2 7884
b5e7eebb 7885 id tabbar_;
9bedffaa 7886
a54b1c10 7887 NSMutableArray *essential_;
9bedffaa 7888 NSMutableArray *broken_;
dc5812ec
JF
7889
7890 Database *database_;
dc5812ec 7891
aeed65a6 7892 int tag_;
b4d89997
JF
7893
7894 UIKeyboard *keyboard_;
bd150f54 7895 UIProgressHUD *hud_;
9b619239 7896
adb61bda
GP
7897 SectionsController *sections_;
7898 ChangesController *changes_;
7899 ManageController *manage_;
7900 SearchController *search_;
b5e7eebb 7901 SourceTable *sources_;
adb61bda 7902 InstalledController *installed_;
b5e7eebb 7903 id queueDelegate_;
f79a4512 7904
ea173384 7905#if RecyclePackageViews
7592e053 7906 NSMutableArray *details_;
ea173384 7907#endif
9aecdc9c 7908
8c02abc8 7909 bool loaded_;
dc5812ec
JF
7910}
7911
b5e7eebb
GP
7912- (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7913- (void) setPage:(UIViewController *)page;
670a0494 7914
dc5812ec
JF
7915@end
7916
670a0494 7917static _finline void _setHomePage(Cydia *self) {
adb61bda 7918 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
670a0494
JF
7919}
7920
dc5812ec
JF
7921@implementation Cydia
7922
b5e7eebb 7923- (void) beginUpdate {
8c02abc8 7924 [container_ beginUpdate];
b5e7eebb
GP
7925}
7926
7927- (BOOL) updating {
8c02abc8 7928 return [container_ updating];
b5e7eebb
GP
7929}
7930
01d93940
JF
7931- (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7932 return window_;
7933}
7934
9bedffaa
JF
7935- (void) _loaded {
7936 if ([broken_ count] != 0) {
7937 int count = [broken_ count];
7938
37d2b2a9 7939 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 7940 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
b5e7eebb
GP
7941 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7942 delegate:self
7943 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7944 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
9bedffaa
JF
7945 ] autorelease];
7946
37d2b2a9
GP
7947 [alert setContext:@"fixhalf"];
7948 [alert show];
9bedffaa
JF
7949 } else if (!Ignored_ && [essential_ count] != 0) {
7950 int count = [essential_ count];
7951
37d2b2a9 7952 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 7953 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
b5e7eebb
GP
7954 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7955 delegate:self
7956 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
37d2b2a9 7957 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
9bedffaa
JF
7958 ] autorelease];
7959
37d2b2a9
GP
7960 [alert setContext:@"upgrade"];
7961 [alert show];
9bedffaa
JF
7962 }
7963}
7964
7623f855
JF
7965- (void) _saveConfig {
7966 if (Changed_) {
7967 _trace();
7968 NSString *error(nil);
7969 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7970 _trace();
7971 NSError *error(nil);
7972 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7973 NSLog(@"failure to save metadata data: %@", error);
7974 _trace();
7975 } else {
7976 NSLog(@"failure to serialize metadata: %@", error);
7977 return;
7978 }
7979
7980 Changed_ = false;
7981 }
7982}
7983
7984- (void) _updateData {
7985 [self _saveConfig];
7986
7987 /* XXX: this is just stupid */
aeed65a6 7988 if (tag_ != 1 && sections_ != nil)
7623f855 7989 [sections_ reloadData];
aeed65a6 7990 if (tag_ != 2 && changes_ != nil)
7623f855 7991 [changes_ reloadData];
aeed65a6 7992 if (tag_ != 4 && search_ != nil)
7623f855
JF
7993 [search_ reloadData];
7994
b5e7eebb
GP
7995 [[tabbar_ selectedViewController] reloadData];
7996}
7997
7998- (int)indexOfTabWithTag:(int)tag {
7999 int i = 0;
8000 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8001 if ([[controller tabBarItem] tag] == tag) return i;
8002 i += 1;
8003 }
8004
8005 return -1;
7623f855
JF
8006}
8007
9aecdc9c 8008- (void) _refreshIfPossible {
8c02abc8
GP
8009 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8010
8011 Reachability* reachability = [Reachability reachabilityWithHostName:@"cydia.saurik.com"];
8012 NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
8013
8014 if (loaded_ || ManualRefresh || remoteHostStatus == NotReachable) loaded:
9aecdc9c
GP
8015 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8016 else {
8017 loaded_ = true;
8018
8019 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8020
8021 if (update != nil) {
8022 NSTimeInterval interval([update timeIntervalSinceNow]);
8023 if (interval <= 0 && interval > -(15*60))
8024 goto loaded;
8025 }
8026
8c02abc8 8027 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9aecdc9c
GP
8028 }
8029
8c02abc8 8030 [pool release];
9aecdc9c
GP
8031}
8032
8033- (void) refreshIfPossible {
8c02abc8 8034 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9aecdc9c
GP
8035}
8036
36bb2ca2 8037- (void) _reloadData {
d061f4ba
JF
8038 UIView *block();
8039
8040 UIProgressHUD *hud([self addProgressHUD]);
9aecdc9c 8041 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
dc5812ec 8042
d061f4ba
JF
8043 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8044 _trace();
8045
8046 [self removeProgressHUD:hud];
c25a610d 8047
36bb2ca2 8048 size_t changes(0);
9bedffaa 8049
a54b1c10 8050 [essential_ removeAllObjects];
9bedffaa 8051 [broken_ removeAllObjects];
b4d89997 8052
670a0494 8053 NSArray *packages([database_ packages]);
affeffc7 8054 for (Package *package in packages) {
9bedffaa
JF
8055 if ([package half])
8056 [broken_ addObject:package];
31f3cfff 8057 if ([package upgradableAndEssential:NO]) {
a54b1c10
JF
8058 if ([package essential])
8059 [essential_ addObject:package];
36bb2ca2 8060 ++changes;
a54b1c10 8061 }
36bb2ca2 8062 }
b4d89997 8063
36bb2ca2
JF
8064 if (changes != 0) {
8065 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
b5e7eebb
GP
8066 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8067 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
8068
f79a4512
JF
8069 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8070 [self setApplicationBadge:badge];
8071 else
8072 [self setApplicationBadgeString:badge];
c25a610d 8073 } else {
b5e7eebb
GP
8074 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8075 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
8076
f79a4512
JF
8077 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8078 [self removeApplicationBadge];
8079 else // XXX: maybe use setApplicationBadgeString also?
8080 [self setApplicationIconBadgeNumber:0];
c25a610d 8081 }
b4d89997 8082
7623f855 8083 [self _updateData];
6d9712c4 8084
8c02abc8 8085 [self refreshIfPossible];
6d9712c4
JF
8086}
8087
7b0ce2da 8088- (void) updateData {
7623f855
JF
8089 [database_ setVisible];
8090 [self _updateData];
b4d89997
JF
8091}
8092
7b0ce2da
JF
8093- (void) update_ {
8094 [database_ update];
8095}
8096
8097- (void) syncData {
670a0494 8098 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7b0ce2da
JF
8099 _assert(file != NULL);
8100
670a0494
JF
8101 for (NSString *key in [Sources_ allKeys]) {
8102 NSDictionary *source([Sources_ objectForKey:key]);
7b0ce2da
JF
8103
8104 fprintf(file, "%s %s %s\n",
8105 [[source objectForKey:@"Type"] UTF8String],
8106 [[source objectForKey:@"URI"] UTF8String],
8107 [[source objectForKey:@"Distribution"] UTF8String]
8108 );
8109 }
8110
8111 fclose(file);
8112
8113 [self _saveConfig];
8114
adb61bda 8115 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9cb0bff2 8116 UINavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
b5e7eebb 8117 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8c02abc8 8118 [container_ presentModalViewController:navigation animated:YES];
b5e7eebb
GP
8119
8120 [progress
7b0ce2da
JF
8121 detachNewThreadSelector:@selector(update_)
8122 toTarget:self
8123 withObject:nil
43f3d7f6 8124 title:UCLocalize("UPDATING_SOURCES")
7b0ce2da
JF
8125 ];
8126}
8127
36bb2ca2
JF
8128- (void) reloadData {
8129 @synchronized (self) {
b5e7eebb 8130 [self _reloadData];
36bb2ca2 8131 }
b4d89997
JF
8132}
8133
8134- (void) resolve {
8135 pkgProblemResolver *resolver = [database_ resolver];
8136
8137 resolver->InstallProtect();
8138 if (!resolver->Resolve(true))
8139 _error->Discard();
2367a917
JF
8140}
8141
aa5d0de7 8142- (CGRect) popUpBounds {
b5e7eebb 8143 return [[tabbar_ view] bounds];
aa5d0de7
JF
8144}
8145
670a0494
JF
8146- (bool) perform {
8147 if (![database_ prepare])
8148 return false;
49048579 8149
adb61bda 8150 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
affeffc7 8151 [page setDelegate:self];
9cb0bff2 8152 id confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
b5e7eebb 8153 [confirm_ setDelegate:self];
49048579 8154
b5e7eebb 8155 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8c02abc8 8156 [container_ presentModalViewController:confirm_ animated:YES];
670a0494
JF
8157
8158 return true;
3178d79b
JF
8159}
8160
dc63e78f
JF
8161- (void) queue {
8162 @synchronized (self) {
8163 [self perform];
8164 }
8165}
8166
8167- (void) clearPackage:(Package *)package {
8168 @synchronized (self) {
8169 [package clear];
8170 [self resolve];
8171 [self perform];
8172 }
8173}
8174
77801ff1
JF
8175- (void) installPackages:(NSArray *)packages {
8176 @synchronized (self) {
8177 for (Package *package in packages)
8178 [package install];
8179 [self resolve];
8180 [self perform];
8181 }
8182}
8183
36bb2ca2
JF
8184- (void) installPackage:(Package *)package {
8185 @synchronized (self) {
8186 [package install];
8187 [self resolve];
8188 [self perform];
8189 }
8190}
8191
8192- (void) removePackage:(Package *)package {
8193 @synchronized (self) {
8194 [package remove];
8195 [self resolve];
8196 [self perform];
8197 }
8198}
8199
8200- (void) distUpgrade {
8201 @synchronized (self) {
670a0494
JF
8202 if (![database_ upgrade])
8203 return;
36bb2ca2
JF
8204 [self perform];
8205 }
b4d89997
JF
8206}
8207
dc63e78f 8208- (void) complete {
36bb2ca2 8209 @synchronized (self) {
36bb2ca2
JF
8210 [self _reloadData];
8211 }
3178d79b
JF
8212}
8213
b5e7eebb 8214- (void) confirmWithNavigationController:(UINavigationController *)navigation {
adb61bda 8215 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
b5e7eebb
GP
8216
8217 if (navigation != nil) {
8218 [navigation pushViewController:progress animated:YES];
8219 } else {
9cb0bff2 8220 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
b5e7eebb 8221 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8c02abc8 8222 [container_ presentModalViewController:navigation animated:YES];
b5e7eebb
GP
8223 }
8224
8225 [progress
2367a917
JF
8226 detachNewThreadSelector:@selector(perform)
8227 toTarget:database_
8228 withObject:nil
43f3d7f6 8229 title:UCLocalize("RUNNING")
2367a917
JF
8230 ];
8231}
8232
39cda3a8 8233- (void) progressControllerIsComplete:(ProgressController *)progress {
dc63e78f 8234 [self complete];
dc5812ec
JF
8235}
8236
b5e7eebb 8237- (void) setPage:(UIViewController *)page {
36bb2ca2 8238 [page setDelegate:self];
b5e7eebb
GP
8239
8240 UINavigationController *navController = [tabbar_ selectedViewController];
8241 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8242 for (UIViewController *page in [tabbar_ viewControllers]) {
8243 if (page != navController) [page setViewControllers:nil];
8244 }
dc5812ec
JF
8245}
8246
b5e7eebb
GP
8247- (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8248 CYBrowserController *browser = [[[_class alloc] init] autorelease];
7b0ce2da 8249 [browser loadURL:url];
36bb2ca2 8250 return browser;
2367a917
JF
8251}
8252
adb61bda 8253- (SectionsController *) sectionsController {
f79a4512 8254 if (sections_ == nil)
adb61bda 8255 sections_ = [[SectionsController alloc] initWithDatabase:database_];
f79a4512
JF
8256 return sections_;
8257}
8258
adb61bda 8259- (ChangesController *) changesController {
01d93940 8260 if (changes_ == nil)
adb61bda 8261 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
01d93940
JF
8262 return changes_;
8263}
8264
adb61bda 8265- (ManageController *) manageController {
b5e7eebb 8266 if (manage_ == nil) {
adb61bda 8267 manage_ = (ManageController *) [[self
01d93940 8268 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
adb61bda 8269 withClass:[ManageController class]
01d93940 8270 ] retain];
b5e7eebb
GP
8271 if (!IsWildcat_) queueDelegate_ = manage_;
8272 }
01d93940
JF
8273 return manage_;
8274}
8275
adb61bda 8276- (SearchController *) searchController {
01d93940 8277 if (search_ == nil)
adb61bda 8278 search_ = [[SearchController alloc] initWithDatabase:database_];
01d93940
JF
8279 return search_;
8280}
8281
adb61bda 8282- (SourceTable *) sourcesController {
b5e7eebb
GP
8283 if (sources_ == nil)
8284 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8285 return sources_;
8286}
8287
adb61bda 8288- (InstalledController *) installedController {
b5e7eebb 8289 if (installed_ == nil) {
adb61bda 8290 installed_ = [[InstalledController alloc] initWithDatabase:database_];
b5e7eebb
GP
8291 if (IsWildcat_) queueDelegate_ = installed_;
8292 }
8293 return installed_;
8294}
8295
8296- (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8297 int tag = [[viewController tabBarItem] tag];
559dec34 8298 if (tag == tag_) {
b5e7eebb 8299 [[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
559dec34 8300 return;
b5e7eebb 8301 } else if (tag_ == 1) {
adb61bda 8302 [[self sectionsController] resetView];
b5e7eebb 8303 }
dc5812ec 8304
06aa974d 8305 switch (tag) {
b5e7eebb 8306 case kCydiaTag: _setHomePage(self); break;
36bb2ca2 8307
adb61bda
GP
8308 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8309 case kChangesTag: [self setPage:[self changesController]]; break;
8310 case kManageTag: [self setPage:[self manageController]]; break;
8311 case kInstalledTag: [self setPage:[self installedController]]; break;
8312 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8313 case kSearchTag: [self setPage:[self searchController]]; break;
36bb2ca2 8314
670a0494 8315 _nodefault
dc5812ec
JF
8316 }
8317
06aa974d 8318 tag_ = tag;
06aa974d
JF
8319}
8320
21c6da4b
GP
8321- (void) showSettings {
8322 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
43e1f0b9 8323 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
2bdd73bd 8324 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
21c6da4b 8325 [container_ presentModalViewController:nav animated:YES];
7b0ce2da
JF
8326}
8327
adb61bda 8328- (void) setPackageController:(PackageController *)view {
7592e053
JF
8329 WebThreadLock();
8330 [view setPackage:nil];
ea173384 8331#if RecyclePackageViews
7592e053
JF
8332 if ([details_ count] < 3)
8333 [details_ addObject:view];
ea173384 8334#endif
7592e053
JF
8335 WebThreadUnlock();
8336}
8337
adb61bda
GP
8338- (PackageController *) _packageController {
8339 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
f79a4512
JF
8340}
8341
adb61bda 8342- (PackageController *) packageController {
ea173384 8343#if RecyclePackageViews
adb61bda 8344 PackageController *view;
7592e053 8345 size_t count([details_ count]);
f79a4512 8346
7592e053 8347 if (count == 0) {
adb61bda 8348 view = [self _packageController];
7592e053 8349 renew:
adb61bda 8350 [details_ addObject:[self _packageController]];
7592e053
JF
8351 } else {
8352 view = [[[details_ lastObject] retain] autorelease];
8353 [details_ removeLastObject];
8354 if (count == 1)
8355 goto renew;
f79a4512
JF
8356 }
8357
8358 return view;
ea173384 8359#else
adb61bda 8360 return [self _packageController];
ea173384 8361#endif
f79a4512
JF
8362}
8363
674dce72
GP
8364- (void) cancelAndClear:(bool)clear {
8365 @synchronized (self) {
8366 if (clear) {
b5e7eebb
GP
8367 /* XXX: clear marks instead of reloading data */
8368 /*pkgCacheFile &cache([database_ cache]);
8369 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8370 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8371 }
8372
8373 [self updateData];
8374
8375 Queuing_ = false;
8376 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8377 [queueDelegate_ queueStatusDidChange];*/
8378 [self reloadData];
674dce72 8379 } else {
b5e7eebb
GP
8380 Queuing_ = true;
8381
8382 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8383 [[tabbar_ selectedViewController] reloadData];
8384
8385 [queueDelegate_ queueStatusDidChange];
dc63e78f 8386 }
674dce72 8387 }
37d2b2a9 8388}
7b0ce2da 8389
b5e7eebb
GP
8390- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8391 NSString *context([alert context]);
8392
8393 if ([context isEqualToString:@"fixhalf"]) {
8394 if (button == [alert firstOtherButtonIndex]) {
37d2b2a9
GP
8395 @synchronized (self) {
8396 for (Package *broken in broken_) {
8397 [broken remove];
8398
8399 NSString *id = [broken id];
8400 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8401 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8402 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8403 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8404 }
7b0ce2da 8405
37d2b2a9
GP
8406 [self resolve];
8407 [self perform];
8408 }
b5e7eebb 8409 } else if (button == [alert cancelButtonIndex]) {
37d2b2a9
GP
8410 [broken_ removeAllObjects];
8411 [self _loaded];
7b0ce2da
JF
8412 }
8413
37d2b2a9 8414 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 8415 } else if ([context isEqualToString:@"upgrade"]) {
37d2b2a9
GP
8416 if (button == [alert firstOtherButtonIndex]) {
8417 @synchronized (self) {
8418 for (Package *essential in essential_)
8419 [essential install];
7b0ce2da 8420
37d2b2a9
GP
8421 [self resolve];
8422 [self perform];
8423 }
8424 } else if (button == [alert firstOtherButtonIndex] + 1) {
8425 [self distUpgrade];
8426 } else if (button == [alert cancelButtonIndex]) {
8427 Ignored_ = YES;
7b0ce2da
JF
8428 }
8429
37d2b2a9 8430 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 8431 }
7b0ce2da
JF
8432}
8433
670a0494
JF
8434- (void) system:(NSString *)command { _pooled
8435 system([command UTF8String]);
8436}
8437
8438- (void) applicationWillSuspend {
8439 [database_ clean];
8440 [super applicationWillSuspend];
bd150f54
JF
8441}
8442
8443- (void) applicationSuspend:(__GSEvent *)event {
44c6e9a8
GP
8444 // FIXME: This needs to be fixed, but we no longer have a progress_.
8445 // What's the best solution?
b5e7eebb 8446 if (hud_ == nil)// && ![progress_ isRunning])
bd150f54 8447 [super applicationSuspend:event];
bd150f54
JF
8448}
8449
6d9712c4
JF
8450- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8451 if (hud_ == nil)
8452 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8453}
8454
8455- (void) _setSuspended:(BOOL)value {
8456 if (hud_ == nil)
8457 [super _setSuspended:value];
8458}
8459
7b0ce2da 8460- (UIProgressHUD *) addProgressHUD {
d061f4ba 8461 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
04fe1349
JF
8462 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8463
d061f4ba 8464 [window_ setUserInteractionEnabled:NO];
7b0ce2da 8465 [hud show:YES];
cfa9a375 8466 [[container_ view] addSubview:hud];
7b0ce2da
JF
8467 return hud;
8468}
8469
d061f4ba
JF
8470- (void) removeProgressHUD:(UIProgressHUD *)hud {
8471 [hud show:NO];
8472 [hud removeFromSuperview];
8473 [window_ setUserInteractionEnabled:YES];
8474}
8475
b5e7eebb 8476- (UIViewController *) pageForPackage:(NSString *)name {
c390d3ab 8477 if (Package *package = [database_ packageWithName:name]) {
adb61bda 8478 PackageController *view([self packageController]);
c390d3ab
JF
8479 [view setPackage:package];
8480 return view;
8481 } else {
670a0494
JF
8482 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8483 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
b5e7eebb 8484 return [self _pageForURL:url withClass:[CYBrowserController class]];
c390d3ab
JF
8485 }
8486}
8487
b5e7eebb 8488- (UIViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
c390d3ab 8489 if (tag != NULL)
aeed65a6 8490 *tag = -1;
c390d3ab 8491
43f3d7f6
JF
8492 NSString *href([url absoluteString]);
8493 if ([href hasPrefix:@"apptapp://package/"])
8494 return [self pageForPackage:[href substringFromIndex:18]];
8495
e47c4742
JF
8496 NSString *scheme([[url scheme] lowercaseString]);
8497 if (![scheme isEqualToString:@"cydia"])
8498 return nil;
8499 NSString *path([url absoluteString]);
8500 if ([path length] < 8)
8501 return nil;
8502 path = [path substringFromIndex:8];
8503 if (![path hasPrefix:@"/"])
8504 path = [@"/" stringByAppendingString:path];
8505
8506 if ([path isEqualToString:@"/add-source"])
adb61bda 8507 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
e47c4742 8508 else if ([path isEqualToString:@"/storage"])
b5e7eebb 8509 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
e47c4742 8510 else if ([path isEqualToString:@"/sources"])
b5e7eebb 8511 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
e47c4742 8512 else if ([path isEqualToString:@"/packages"])
adb61bda 8513 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
e47c4742 8514 else if ([path hasPrefix:@"/url/"])
b5e7eebb 8515 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
e47c4742
JF
8516 else if ([path hasPrefix:@"/launch/"])
8517 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8518 else if ([path hasPrefix:@"/package-settings/"])
adb61bda 8519 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
e47c4742 8520 else if ([path hasPrefix:@"/package-signature/"])
adb61bda 8521 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
e47c4742
JF
8522 else if ([path hasPrefix:@"/package/"])
8523 return [self pageForPackage:[path substringFromIndex:9]];
8524 else if ([path hasPrefix:@"/files/"]) {
8525 NSString *name = [path substringFromIndex:7];
c390d3ab
JF
8526
8527 if (Package *package = [database_ packageWithName:name]) {
b5e7eebb 8528 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
c390d3ab
JF
8529 [files setPackage:package];
8530 return files;
8531 }
8532 }
8533
8534 return nil;
8535}
8536
8537- (void) applicationOpenURL:(NSURL *)url {
8538 [super applicationOpenURL:url];
8539 int tag;
b5e7eebb 8540 if (UIViewController *page = [self pageForURL:url hasTag:&tag]) {
c390d3ab 8541 [self setPage:page];
c390d3ab 8542 tag_ = tag;
b5e7eebb 8543 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
c390d3ab
JF
8544 }
8545}
8546
7eff7ea6
GP
8547- (void) applicationWillResignActive:(UIApplication *)application {
8548 // Stop refreshing if you get a phone call or lock the device.
8549 if ([container_ updating]) [container_ cancelUpdate];
7eff7ea6
GP
8550}
8551
bd150f54 8552- (void) applicationDidFinishLaunching:(id)unused {
b5e7eebb 8553 [CYBrowserController _initialize];
ea173384 8554
bfc87a4d
JF
8555 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8556
f641a0e5
JF
8557 Font12_ = [[UIFont systemFontOfSize:12] retain];
8558 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8559 Font14_ = [[UIFont systemFontOfSize:14] retain];
8560 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8561 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8562
aeed65a6 8563 tag_ = 0;
bd150f54
JF
8564
8565 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8566 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8567
04fe1349
JF
8568 UIScreen *screen([UIScreen mainScreen]);
8569
8570 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
f641a0e5
JF
8571 [window_ orderFront:self];
8572 [window_ makeKey:self];
c390d3ab 8573 [window_ setHidden:NO];
04fe1349 8574
770f2a8e 8575 database_ = [Database sharedInstance];
bfc87a4d 8576
6d9712c4 8577 if (
bd150f54 8578 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
bd150f54 8579 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
bfc87a4d
JF
8580 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8581 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
6d9712c4 8582 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
70d45c1e 8583 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
6d9712c4 8584 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
bfc87a4d
JF
8585 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8586 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8587 false
bd150f54 8588 ) {
5afbb4b7
JF
8589 [self setIdleTimerDisabled:YES];
8590
670a0494 8591 hud_ = [self addProgressHUD];
b5e7eebb 8592 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
bd150f54
JF
8593 [self setStatusBarShowsProgress:YES];
8594
9b73bcf8 8595 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
670a0494
JF
8596
8597 [self setStatusBarShowsProgress:NO];
8598 [self removeProgressHUD:hud_];
8599 hud_ = nil;
8600
8601 if (ExecFork() == 0) {
8602 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8603 perror("launchctl stop");
8604 }
8605
8606 return;
8607 }
8608
8609 if (Role_ == nil)
21c6da4b 8610 [self showSettings];
670a0494
JF
8611
8612 _trace();
670a0494 8613
b5e7eebb
GP
8614 NSMutableArray *controllers = [NSMutableArray array];
8615 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8616 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8617 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8618 if (IsWildcat_) [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8619 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8620 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8621
8622 NSMutableArray *items = [NSMutableArray arrayWithObjects:
8623 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8624 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8625 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8626 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8627 nil
670a0494 8628 ];
b5e7eebb
GP
8629
8630 if (IsWildcat_) {
8631 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8632 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8633 } else {
8634 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8635 }
8636
8637 for (int i = 0; i < [items count]; i++) {
8638 [[controllers objectAtIndex:i] setTabBarItem:[items objectAtIndex:i]];
8639 }
8c02abc8 8640
b5e7eebb 8641 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
b5e7eebb
GP
8642 [tabbar_ setViewControllers:controllers];
8643 [tabbar_ setDelegate:self];
8644 [tabbar_ setSelectedIndex:0];
8c02abc8
GP
8645
8646 container_ = [[CYContainer alloc] initWithDatabase:database_];
8c02abc8
GP
8647 [container_ setUpdateDelegate:self];
8648 [container_ setRootController:tabbar_];
8649 [window_ addSubview:[container_ view]];
39cda3a8 8650 [[tabbar_ view] setFrame:CGRectMake(0, -20.0f, [window_ bounds].size.width, [window_ bounds].size.height)];
670a0494
JF
8651
8652 [UIKeyboard initImplementationNow];
670a0494
JF
8653
8654 [self reloadData];
8655
670a0494
JF
8656#if RecyclePackageViews
8657 details_ = [[NSMutableArray alloc] initWithCapacity:4];
adb61bda
GP
8658 [details_ addObject:[self _packageController]];
8659 [details_ addObject:[self _packageController]];
670a0494
JF
8660#endif
8661
8662 PrintTimes();
8663
8664 _setHomePage(self);
bd150f54
JF
8665}
8666
b5e7eebb 8667- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
674dce72 8668 if (item != nil && IsWildcat_) {
b5e7eebb 8669 [sheet showFromBarButtonItem:item animated:YES];
674dce72
GP
8670 } else {
8671 [sheet showInView:window_];
8672 }
36bb2ca2
JF
8673}
8674
dc5812ec
JF
8675@end
8676
b4d89997
JF
8677/*IMP alloc_;
8678id Alloc_(id self, SEL selector) {
8679 id object = alloc_(self, selector);
c390d3ab 8680 lprintf("[%s]A-%p\n", self->isa->name, object);
b4d89997
JF
8681 return object;
8682}*/
8683
36bb2ca2
JF
8684/*IMP dealloc_;
8685id Dealloc_(id self, SEL selector) {
8686 id object = dealloc_(self, selector);
c390d3ab 8687 lprintf("[%s]D-%p\n", self->isa->name, object);
36bb2ca2
JF
8688 return object;
8689}*/
b4d89997 8690
f79a4512
JF
8691Class $WebDefaultUIKitDelegate;
8692
d791dce4 8693MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
f79a4512
JF
8694 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8695 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
d791dce4 8696 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
f79a4512
JF
8697}
8698
10d65752
RP
8699static NSNumber *shouldPlayKeyboardSounds;
8700
8701Class $UIHardware;
8702
8703MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int soundIndex) {
8704 switch (soundIndex) {
8705 case 1104: // Keyboard Button Clicked
8706 case 1105: // Keyboard Delete Repeated
8707 if (!shouldPlayKeyboardSounds) {
8708 NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"];
8709 shouldPlayKeyboardSounds = [[dict objectForKey:@"keyboard"] ?: (id)kCFBooleanTrue retain];
8710 [dict release];
8711 }
8712 if (![shouldPlayKeyboardSounds boolValue])
8713 break;
8714 default:
8715 _UIHardware$_playSystemSound$(self, _cmd, soundIndex);
8716 }
8717}
8718
affeffc7 8719int main(int argc, char *argv[]) { _pooled
d6dad1b4 8720 _trace();
f79a4512 8721
01d93940
JF
8722 if (Class $UIDevice = objc_getClass("UIDevice")) {
8723 UIDevice *device([$UIDevice currentDevice]);
8724 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8725 } else
8726 IsWildcat_ = false;
8727
df213583 8728 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
677b8415 8729
7376b55c 8730 /* Library Hacks {{{ */
77801ff1 8731 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
7376b55c
JF
8732 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8733
8734 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8735 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8736 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8737 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8738 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8739 }
10d65752
RP
8740
8741 $UIHardware = objc_getClass("UIHardware");
8742 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8743 if (UIHardware$_playSystemSound$ != NULL) {
8744 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8745 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8746 }
7376b55c
JF
8747 /* }}} */
8748 /* Set Locale {{{ */
f79a4512 8749 Locale_ = CFLocaleCopyCurrent();
b1ce61ec
JF
8750 Languages_ = [NSLocale preferredLanguages];
8751 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
18876387 8752 //NSLog(@"%@", [Languages_ description]);
78430d06 8753
b1ce61ec
JF
8754 const char *lang;
8755 if (Languages_ == nil || [Languages_ count] == 0)
78430d06 8756 // XXX: consider just setting to C and then falling through?
b1ce61ec 8757 lang = NULL;
78430d06 8758 else {
b1ce61ec 8759 lang = [[Languages_ objectAtIndex:0] UTF8String];
78430d06
JF
8760 setenv("LANG", lang, true);
8761 }
8762
b1ce61ec
JF
8763 //std::setlocale(LC_ALL, lang);
8764 NSLog(@"Setting Language: %s", lang);
7376b55c 8765 /* }}} */
f79a4512 8766
d791dce4 8767 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
f79a4512 8768
7376b55c 8769 /* Parse Arguments {{{ */
de3b1ab4
JF
8770 bool substrate(false);
8771
8772 if (argc != 0) {
8773 char **args(argv);
8774 int arge(1);
8775
8776 for (int argi(1); argi != argc; ++argi)
8777 if (strcmp(argv[argi], "--") == 0) {
8778 arge = argi;
8779 argv[argi] = argv[0];
8780 argv += argi;
8781 argc -= argi;
8782 break;
8783 }
8784
8785 for (int argi(1); argi != arge; ++argi)
d791dce4 8786 if (strcmp(args[argi], "--substrate") == 0)
de3b1ab4
JF
8787 substrate = true;
8788 else
8789 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8790 }
7376b55c 8791 /* }}} */
d73cede2 8792
7376b55c
JF
8793 App_ = [[NSBundle mainBundle] bundlePath];
8794 Home_ = NSHomeDirectory();
d791dce4 8795 Advanced_ = YES;
7376b55c 8796
b4d89997
JF
8797 setuid(0);
8798 setgid(0);
8799
8800 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8801 alloc_ = alloc->method_imp;
8802 alloc->method_imp = (IMP) &Alloc_;*/
8803
36bb2ca2
JF
8804 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8805 dealloc_ = dealloc->method_imp;
8806 dealloc->method_imp = (IMP) &Dealloc_;*/
8807
d791dce4 8808 /* System Information {{{ */
3178d79b 8809 size_t size;
c390d3ab
JF
8810
8811 int maxproc;
8812 size = sizeof(maxproc);
8813 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8814 perror("sysctlbyname(\"kern.maxproc\", ?)");
8815 else if (maxproc < 64) {
8816 maxproc = 64;
8817 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8818 perror("sysctlbyname(\"kern.maxproc\", #)");
8819 }
8820
bfc87a4d
JF
8821 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8822 char *osversion = new char[size];
8823 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8824 perror("sysctlbyname(\"kern.osversion\", ?)");
8825 else
8826 System_ = [NSString stringWithUTF8String:osversion];
8827
3178d79b
JF
8828 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8829 char *machine = new char[size];
c390d3ab
JF
8830 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8831 perror("sysctlbyname(\"hw.machine\", ?)");
8832 else
8833 Machine_ = machine;
3178d79b 8834
59dbe296
JF
8835 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8836 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8837 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
bfc87a4d 8838 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
59dbe296
JF
8839 CFRelease(serial);
8840 }
8841
8842 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8843 NSData *data((NSData *) ecid);
8844 size_t length([data length]);
8845 uint8_t bytes[length];
8846 [data getBytes:bytes];
8847 char string[length * 2 + 1];
8848 for (size_t i(0); i != length; ++i)
8849 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
bfc87a4d 8850 ChipID_ = [NSString stringWithUTF8String:string];
59dbe296
JF
8851 CFRelease(ecid);
8852 }
8853
8854 IOObjectRelease(service);
8855 }
8856 }
8857
87f46a96 8858 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
3178d79b 8859
ad5d065e
JF
8860 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8861 Build_ = [system objectForKey:@"ProductBuildVersion"];
3e9c9e85
JF
8862 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8863 Product_ = [info objectForKey:@"SafariProductVersion"];
8864 Safari_ = [info objectForKey:@"CFBundleVersion"];
8865 }
d791dce4 8866 /* }}} */
7376b55c 8867 /* Load Database {{{ */
d6dad1b4 8868 _trace();
f79a4512
JF
8869 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8870 _trace();
8871 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
d6dad1b4
JF
8872 _trace();
8873
8874 if (Metadata_ == NULL)
f79a4512 8875 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
6d9712c4 8876 else {
2bdd73bd 8877 Settings_ = [Metadata_ objectForKey:@"Settings"];
7b0ce2da 8878
b4d89997 8879 Packages_ = [Metadata_ objectForKey:@"Packages"];
6d9712c4 8880 Sections_ = [Metadata_ objectForKey:@"Sections"];
7b0ce2da 8881 Sources_ = [Metadata_ objectForKey:@"Sources"];
ef055c6c
JF
8882
8883 Token_ = [Metadata_ objectForKey:@"Token"];
7b0ce2da
JF
8884 }
8885
8886 if (Settings_ != nil)
8887 Role_ = [Settings_ objectForKey:@"Role"];
8888
8889 if (Packages_ == nil) {
8890 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8891 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8892 }
8893
8894 if (Sections_ == nil) {
8895 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8896 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8897 }
8898
8899 if (Sources_ == nil) {
8900 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8901 [Metadata_ setObject:Sources_ forKey:@"Sources"];
6d9712c4 8902 }
7376b55c 8903 /* }}} */
b4d89997 8904
affeffc7 8905#if RecycleWebViews
baf80942 8906 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
affeffc7 8907#endif
baf80942 8908
d791dce4
JF
8909 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8910
01d93940
JF
8911 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8912 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9dd60d81
JF
8913 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8914 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8915 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8916 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
dddbc481 8917
01d93940
JF
8918 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8919
3b0f10b0 8920 if (access("/tmp/.cydia.fw", F_OK) == 0) {
ea173384 8921 unlink("/tmp/.cydia.fw");
3b0f10b0 8922 goto firmware;
77801ff1 8923 } else if (access("/User", F_OK) != 0 || version < 2) {
3b0f10b0 8924 firmware:
d6dad1b4 8925 _trace();
26c2dd8c 8926 system("/usr/libexec/cydia/firmware.sh");
d6dad1b4
JF
8927 _trace();
8928 }
9e98e020 8929
87f46a96
JF
8930 _assert([[NSFileManager defaultManager]
8931 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8932 withIntermediateDirectories:YES
8933 attributes:nil
8934 error:NULL
8935 ]);
8936
7376b55c
JF
8937 if (access("/tmp/cydia.chk", F_OK) == 0) {
8938 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8939 _assert(errno == ENOENT);
8940 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8941 _assert(errno == ENOENT);
8942 }
8943
59dbe296 8944 /* APT Initialization {{{ */
b1ce61ec
JF
8945 _assert(pkgInitConfig(*_config));
8946 _assert(pkgInitSystem(*_config, _system));
8947
8948 if (lang != NULL)
8949 _config->Set("APT::Acquire::Translation", lang);
677b8415 8950 _config->Set("Acquire::http::Timeout", 15);
7623f855 8951 _config->Set("Acquire::http::MaxParallel", 3);
59dbe296 8952 /* }}} */
7376b55c 8953 /* Color Choices {{{ */
36bb2ca2
JF
8954 space_ = CGColorSpaceCreateDeviceRGB();
8955
f641a0e5 8956 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
77fcccaf 8957 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
36bb2ca2 8958 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
baf80942 8959 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
36bb2ca2 8960 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
7b0ce2da 8961 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
3bd1c2a2
JF
8962 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8963 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8964 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
59dbe296 8965
dc63e78f
JF
8966 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8967 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
7376b55c 8968 /* }}}*/
7376b55c 8969 /* UIKit Configuration {{{ */
f79a4512
JF
8970 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8971 if ($GSFontSetUseLegacyFontMetrics != NULL)
8972 $GSFontSetUseLegacyFontMetrics(YES);
7b0ce2da 8973
600d005d
JF
8974 // XXX: I have a feeling this was important
8975 //UIKeyboardDisableAutomaticAppearance();
7376b55c 8976 /* }}} */
87f46a96 8977
670a0494
JF
8978 Colon_ = UCLocalize("COLON_DELIMITED");
8979 Error_ = UCLocalize("ERROR");
8980 Warning_ = UCLocalize("WARNING");
8981
d6dad1b4 8982 _trace();
a9543575 8983 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
36bb2ca2
JF
8984
8985 CGColorSpaceRelease(space_);
199d0ba5 8986 CFRelease(Locale_);
36bb2ca2 8987
36bb2ca2 8988 return value;
b5e7eebb 8989}