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