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