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