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