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