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