]> git.saurik.com Git - cydia.git/blame - MobileCydia.mm
Pinstripes while loading, removed afterwards due to (nonexistant?) performance implic...
[cydia.git] / MobileCydia.mm
CommitLineData
e057ec05 1/* Cydia - iPhone UIKit Front-End for Debian APT
daf7f6e2 2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
e057ec05
JF
3*/
4
017b2b71 5/* Modified BSD License {{{ */
e057ec05
JF
6/*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37*/
017b2b71 38/* }}} */
e057ec05 39
83105e6e
JF
40// XXX: wtf/FastMalloc.h... wtf?
41#define USE_SYSTEM_MALLOC 1
42
a75f53e7 43/* #include Directives {{{ */
1e4922b8
JF
44#include "UICaboodle/UCPlatform.h"
45#include "UICaboodle/UCLocalize.h"
f159ecd4 46
59efd93a
JF
47#include <objc/objc.h>
48#include <objc/runtime.h>
49
b0d03ade 50#include <CoreGraphics/CoreGraphics.h>
b0d03ade 51#include <Foundation/Foundation.h>
853d14d3 52
66abcbb0
JF
53#if 0
54#define DEPLOYMENT_TARGET_MACOSX 1
55#define CF_BUILDING_CF 1
56#include <CoreFoundation/CFInternal.h>
57#endif
58
43b742af
JF
59#include <CoreFoundation/CFPriv.h>
60#include <CoreFoundation/CFUniChar.h>
61
d7a235a6
JF
62#include <SystemConfiguration/SystemConfiguration.h>
63
1e4922b8
JF
64#include <UIKit/UIKit.h>
65#include "iPhonePrivate.h"
66
67#include <IOKit/IOKitLib.h>
d210b85d 68
6932575e 69#include <WebCore/WebCoreThread.h>
77f175ac 70
43b742af 71#include <algorithm>
3bddda52 72#include <iomanip>
4941f41d 73#include <sstream>
8993ad57
JF
74#include <string>
75
4941f41d
JF
76#include <ext/stdio_filebuf.h>
77
7805b429
JF
78#undef ABS
79
a75f53e7
JF
80#include <apt-pkg/acquire.h>
81#include <apt-pkg/acquire-item.h>
82#include <apt-pkg/algorithms.h>
83#include <apt-pkg/cachefile.h>
d72d91aa 84#include <apt-pkg/clean.h>
a75f53e7 85#include <apt-pkg/configuration.h>
3e3977a2 86#include <apt-pkg/debindexfile.h>
2d28b35a 87#include <apt-pkg/debmetaindex.h>
a75f53e7
JF
88#include <apt-pkg/error.h>
89#include <apt-pkg/init.h>
1eb0c554 90#include <apt-pkg/mmap.h>
a75f53e7 91#include <apt-pkg/pkgrecords.h>
1eb0c554 92#include <apt-pkg/sha1.h>
a75f53e7 93#include <apt-pkg/sourcelist.h>
4941f41d 94#include <apt-pkg/sptr.h>
f464053e 95#include <apt-pkg/strutl.h>
b8b1cfd0 96#include <apt-pkg/tagfile.h>
a75f53e7 97
6932575e
JF
98#include <apr-1/apr_pools.h>
99
2cb68ddf
JF
100#include <sys/types.h>
101#include <sys/stat.h>
2d28b35a 102#include <sys/sysctl.h>
65fe894c
JF
103#include <sys/param.h>
104#include <sys/mount.h>
2cb68ddf 105
1e4922b8 106#include <fcntl.h>
fc675b93 107#include <notify.h>
1eb0c554 108#include <dlfcn.h>
2d28b35a 109
686e302f
JF
110extern "C" {
111#include <mach-o/nlist.h>
112}
113
8993ad57
JF
114#include <cstdio>
115#include <cstdlib>
116#include <cstring>
686e302f 117
4941f41d 118#include <errno.h>
a75f53e7 119#include <pcre.h>
d210b85d 120
6932575e
JF
121#include <ext/hash_map>
122
1e4922b8 123#include "UICaboodle/BrowserView.h"
2bfeaf6f 124
1e4922b8 125#include "substrate.h"
9ae52960
GP
126/* }}} */
127
017b2b71 128/* Profiler {{{ */
f159ecd4
JF
129struct timeval _ltv;
130bool _itv;
131
e2a207dd
JF
132#define _timestamp ({ \
133 struct timeval tv; \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
136})
137
3bddda52
JF
138typedef std::vector<class ProfileTime *> TimeList;
139TimeList times_;
140
141class ProfileTime {
142 private:
143 const char *name_;
144 uint64_t total_;
142bd2db 145 uint64_t count_;
3bddda52
JF
146
147 public:
148 ProfileTime(const char *name) :
149 name_(name),
150 total_(0)
151 {
152 times_.push_back(this);
153 }
154
155 void AddTime(uint64_t time) {
156 total_ += time;
142bd2db 157 ++count_;
3bddda52
JF
158 }
159
160 void Print() {
161 if (total_ != 0)
142bd2db 162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
3bddda52 163 total_ = 0;
142bd2db 164 count_ = 0;
3bddda52
JF
165 }
166};
167
168class ProfileTimer {
169 private:
170 ProfileTime &time_;
171 uint64_t start_;
172
173 public:
174 ProfileTimer(ProfileTime &time) :
175 time_(time),
176 start_(_timestamp)
177 {
178 }
179
180 ~ProfileTimer() {
181 time_.AddTime(_timestamp - start_);
182 }
183};
184
185void PrintTimes() {
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
187 (*i)->Print();
188 std::cerr << "========" << std::endl;
189}
190
191#define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
194
195#define _end }
6932575e 196/* }}} */
f464053e
JF
197
198#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
199
d3bef7bc
JF
200static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
201
541a556a
JF
202void NSLogPoint(const char *fix, const CGPoint &point) {
203 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
204}
205
f464053e
JF
206void NSLogRect(const char *fix, const CGRect &rect) {
207 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
c045fc11
JF
208}
209
6981ccdf
JF
210static _finline NSString *CydiaURL(NSString *path) {
211 char page[25];
212 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
213 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
214 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
215 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
216 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
217 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
218}
219
864da84b
RP
220static _finline void UpdateExternalStatus(uint64_t newStatus) {
221 int notify_token;
222 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
223 notify_set_state(notify_token, newStatus);
224 notify_cancel(notify_token);
225 }
226 notify_post("com.saurik.Cydia.status");
227}
228
017b2b71 229/* [NSObject yieldToSelector:(withObject:)] {{{*/
7398a389 230@interface NSObject (Cydia)
b4dff19a
JF
231- (id) yieldToSelector:(SEL)selector withObject:(id)object;
232- (id) yieldToSelector:(SEL)selector;
7398a389
JF
233@end
234
235@implementation NSObject (Cydia)
236
237- (void) doNothing {
238}
239
b4dff19a 240- (void) _yieldToContext:(NSMutableArray *)context { _pooled
7398a389
JF
241 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
242 id object([[context objectAtIndex:1] nonretainedObjectValue]);
243 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
244
b4dff19a
JF
245 /* XXX: deal with exceptions */
246 id value([self performSelector:selector withObject:object]);
247
43b742af 248 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
b4dff19a 249 [context removeAllObjects];
43b742af 250 if ([signature methodReturnLength] != 0 && value != nil)
b4dff19a 251 [context addObject:value];
7398a389
JF
252
253 stopped = true;
254
255 [self
256 performSelectorOnMainThread:@selector(doNothing)
257 withObject:nil
258 waitUntilDone:NO
259 ];
260}
261
b4dff19a 262- (id) yieldToSelector:(SEL)selector withObject:(id)object {
7b00c562 263 /*return [self performSelector:selector withObject:object];*/
3bddda52 264
7398a389
JF
265 volatile bool stopped(false);
266
b4dff19a 267 NSMutableArray *context([NSMutableArray arrayWithObjects:
7398a389
JF
268 [NSValue valueWithPointer:selector],
269 [NSValue valueWithNonretainedObject:object],
270 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
271 nil]);
272
273 NSThread *thread([[[NSThread alloc]
274 initWithTarget:self
275 selector:@selector(_yieldToContext:)
276 object:context
277 ] autorelease]);
278
279 [thread start];
280
281 NSRunLoop *loop([NSRunLoop currentRunLoop]);
282 NSDate *future([NSDate distantFuture]);
283
284 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
b4dff19a
JF
285
286 return [context count] == 0 ? nil : [context objectAtIndex:0];
287}
288
289- (id) yieldToSelector:(SEL)selector {
290 return [self yieldToSelector:selector withObject:nil];
7398a389
JF
291}
292
293@end
017b2b71 294/* }}} */
7398a389 295
6744338a 296/* Cydia Action Sheet {{{ */
19723386 297@interface CYActionSheet : UIAlertView {
6981ccdf
JF
298 unsigned button_;
299}
300
301- (int) yieldToPopupAlertAnimated:(BOOL)animated;
302@end
303
304@implementation CYActionSheet
305
306- (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
19723386 307 if ((self = [super init])) {
9ae52960
GP
308 [self setTitle:title];
309 [self setDelegate:self];
310 for (NSString *button in buttons) [self addButtonWithTitle:button];
311 [self setCancelButtonIndex:index];
6981ccdf
JF
312 } return self;
313}
314
d5653f96 315- (void) _updateFrameForDisplay {
8b6bb0fd
RP
316 [super _updateFrameForDisplay];
317 if ([self cancelButtonIndex] == -1) {
318 NSArray *buttons = [self buttons];
319 if ([buttons count]) {
320 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
321 for (UIThreePartButton *button in buttons)
322 [button setBackground:background forState:0];
323 }
324 }
325}
326
19723386
GP
327- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
328 button_ = buttonIndex + 1;
6981ccdf
JF
329}
330
9e639c5a 331- (void) dismiss {
9ae52960 332 [self dismissWithClickedButtonIndex:-1 animated:YES];
9e639c5a
GP
333}
334
6981ccdf 335- (int) yieldToPopupAlertAnimated:(BOOL)animated {
05636a2c 336 [self setRunsModal:YES];
6981ccdf 337 button_ = 0;
9e639c5a 338 [self show];
6981ccdf
JF
339 return button_;
340}
341
342@end
6744338a 343/* }}} */
6981ccdf 344
9c4e0cbe 345/* NSForcedOrderingSearch doesn't work on the iPhone */
3bddda52 346static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
43b742af
JF
347static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
348static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
c045fc11 349
7f9c29fa
JF
350/* Information Dictionaries {{{ */
351@interface NSMutableArray (Cydia)
352- (void) addInfoDictionary:(NSDictionary *)info;
353@end
354
355@implementation NSMutableArray (Cydia)
356
357- (void) addInfoDictionary:(NSDictionary *)info {
358 [self addObject:info];
359}
360
361@end
362
363@interface NSMutableDictionary (Cydia)
364- (void) addInfoDictionary:(NSDictionary *)info;
365@end
366
367@implementation NSMutableDictionary (Cydia)
368
369- (void) addInfoDictionary:(NSDictionary *)info {
017b2b71 370 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
7f9c29fa
JF
371}
372
373@end
374/* }}} */
375
cb9c2100 376#define lprintf(args...) fprintf(stderr, args)
d210b85d 377
982de8f1 378#define ForRelease 1
1ff58dbb 379#define TraceLogging (1 && !ForRelease)
956b73c3 380#define HistogramInsertionSort (0 && !ForRelease)
b8b1cfd0 381#define ProfileTimes (0 && !ForRelease)
fa5cb337 382#define ForSaurik (0 && !ForRelease)
6981ccdf 383#define LogBrowser (0 && !ForRelease)
bb9edf8b 384#define TrackResize (0 && !ForRelease)
c2292b80 385#define ManualRefresh (1 && !ForRelease)
6932575e 386#define ShowInternals (0 && !ForRelease)
83105e6e 387#define IgnoreInstall (0 && !ForRelease)
c2292b80 388#define AlwaysReload (0 && !ForRelease)
81ab76dc 389
1ff58dbb 390#if !TraceLogging
6e673d99
JF
391#undef _trace
392#define _trace(args...)
1ff58dbb
JF
393#endif
394
395#if !ProfileTimes
3bddda52 396#undef _profile
7b00c562 397#define _profile(name) {
3bddda52 398#undef _end
7b00c562 399#define _end }
b4dff19a 400#define PrintTimes() do {} while (false)
6e673d99
JF
401#endif
402
f159ecd4 403/* Radix Sort {{{ */
dd9390c5
JF
404typedef uint32_t (*SKRadixFunction)(id, void *);
405
f159ecd4 406@interface NSMutableArray (Radix)
907a35d6 407- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
dd9390c5 408- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
f159ecd4
JF
409@end
410
6932575e
JF
411struct RadixItem_ {
412 size_t index;
413 uint32_t key;
414};
f159ecd4 415
6932575e
JF
416static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
417 struct RadixItem_ *lhs(swap), *rhs(swap + count);
f159ecd4 418
890c1d38 419 static const size_t width = 32;
f159ecd4
JF
420 static const size_t bits = 11;
421 static const size_t slots = 1 << bits;
890c1d38 422 static const size_t passes = (width + (bits - 1)) / bits;
f159ecd4
JF
423
424 size_t *hist(new size_t[slots]);
425
426 for (size_t pass(0); pass != passes; ++pass) {
427 memset(hist, 0, sizeof(size_t) * slots);
428
429 for (size_t i(0); i != count; ++i) {
430 uint32_t key(lhs[i].key);
431 key >>= pass * bits;
890c1d38 432 key &= _not(uint32_t) >> width - bits;
f159ecd4
JF
433 ++hist[key];
434 }
435
436 size_t offset(0);
437 for (size_t i(0); i != slots; ++i) {
438 size_t local(offset);
439 offset += hist[i];
440 hist[i] = local;
441 }
442
443 for (size_t i(0); i != count; ++i) {
444 uint32_t key(lhs[i].key);
445 key >>= pass * bits;
890c1d38 446 key &= _not(uint32_t) >> width - bits;
f159ecd4
JF
447 rhs[hist[key]++] = lhs[i];
448 }
449
6932575e 450 RadixItem_ *tmp(lhs);
f159ecd4
JF
451 lhs = rhs;
452 rhs = tmp;
453 }
454
455 delete [] hist;
456
457 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
458 for (size_t i(0); i != count; ++i)
459 [values addObject:[self objectAtIndex:lhs[i].index]];
460 [self setArray:values];
461
462 delete [] swap;
463}
464
6932575e
JF
465@implementation NSMutableArray (Radix)
466
467- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
66abcbb0
JF
468 size_t count([self count]);
469 if (count == 0)
470 return;
471
472#if 0
6932575e
JF
473 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
474 [invocation setSelector:selector];
475 [invocation setArgument:&object atIndex:2];
66abcbb0
JF
476#else
477 /* XXX: this is an unsafe optimization of doomy hell */
478 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
479 _assert(method != NULL);
480 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
481 _assert(imp != NULL);
482#endif
6932575e 483
6932575e
JF
484 struct RadixItem_ *swap(new RadixItem_[count * 2]);
485
486 for (size_t i(0); i != count; ++i) {
487 RadixItem_ &item(swap[i]);
488 item.index = i;
489
490 id object([self objectAtIndex:i]);
6932575e 491
66abcbb0
JF
492#if 0
493 [invocation setTarget:object];
6932575e
JF
494 [invocation invoke];
495 [invocation getReturnValue:&item.key];
66abcbb0
JF
496#else
497 item.key = imp(object, selector, object);
498#endif
6932575e
JF
499 }
500
501 RadixSort_(self, count, swap);
502}
503
dd9390c5 504- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
6932575e
JF
505 size_t count([self count]);
506 struct RadixItem_ *swap(new RadixItem_[count * 2]);
507
508 for (size_t i(0); i != count; ++i) {
509 RadixItem_ &item(swap[i]);
510 item.index = i;
511
512 id object([self objectAtIndex:i]);
513 item.key = function(object, argument);
514 }
515
516 RadixSort_(self, count, swap);
517}
518
f159ecd4 519@end
66abcbb0
JF
520/* }}} */
521/* Insertion Sort {{{ */
522
dd9390c5
JF
523CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
524 const char *ptr = (const char *)list;
525 while (0 < count) {
526 CFIndex half = count / 2;
527 const char *probe = ptr + elementSize * half;
528 CFComparisonResult cr = comparator(element, probe, context);
9ae52960 529 if (0 == cr) return (probe - (const char *)list) / elementSize;
dd9390c5
JF
530 ptr = (cr < 0) ? ptr : probe + elementSize;
531 count = (cr < 0) ? half : (half + (count & 1) - 1);
532 }
533 return (ptr - (const char *)list) / elementSize;
534}
535
66abcbb0
JF
536CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
537 const char *ptr = (const char *)list;
538 while (0 < count) {
539 CFIndex half = count / 2;
540 const char *probe = ptr + elementSize * half;
541 CFComparisonResult cr = comparator(element, probe, context);
9ae52960 542 if (0 == cr) return (probe - (const char *)list) / elementSize;
66abcbb0
JF
543 ptr = (cr < 0) ? ptr : probe + elementSize;
544 count = (cr < 0) ? half : (half + (count & 1) - 1);
545 }
546 return (ptr - (const char *)list) / elementSize;
547}
548
549void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
550 if (range.length == 0)
551 return;
552 const void **values(new const void *[range.length]);
553 CFArrayGetValues(array, range, values);
554
dd9390c5
JF
555#if HistogramInsertionSort
556 uint32_t total(0), *offsets(new uint32_t[range.length]);
557#endif
558
66abcbb0
JF
559 for (CFIndex index(1); index != range.length; ++index) {
560 const void *value(values[index]);
dd9390c5
JF
561 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
562 CFIndex correct(index);
563 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
564 if (--correct == 0)
565 break;
66abcbb0 566 if (correct != index) {
dd9390c5
JF
567 size_t offset(index - correct);
568#if HistogramInsertionSort
569 total += offset;
570 ++offsets[offset];
571 if (offset > 10)
572 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
573#endif
574 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
66abcbb0
JF
575 values[correct] = value;
576 }
577 }
578
579 CFArrayReplaceValues(array, range, values, range.length);
580 delete [] values;
dd9390c5
JF
581
582#if HistogramInsertionSort
583 for (CFIndex index(0); index != range.length; ++index)
584 if (offsets[index] != 0)
585 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
586 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
587 delete [] offsets;
588#endif
66abcbb0
JF
589}
590
f159ecd4
JF
591/* }}} */
592
541a556a
JF
593/* Apple Bug Fixes {{{ */
594@implementation UIWebDocumentView (Cydia)
595
596- (void) _setScrollerOffset:(CGPoint)offset {
597 UIScroller *scroller([self _scroller]);
598
599 CGSize size([scroller contentSize]);
600 CGSize bounds([scroller bounds].size);
601
602 CGPoint max;
603 max.x = size.width - bounds.width;
604 max.y = size.height - bounds.height;
605
606 // wtf Apple?!
607 if (max.x < 0)
608 max.x = 0;
609 if (max.y < 0)
610 max.y = 0;
611
612 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
613 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
614
615 [scroller setOffset:offset];
616}
617
618@end
619/* }}} */
620
8a4106c2
JF
621@implementation WebScriptObject (NSFastEnumeration)
622
623- (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
daf7f6e2
JF
624 size_t length([self count] - state->state);
625 if (length <= 0)
626 return 0;
627 else if (length > count)
628 length = count;
629 for (size_t i(0); i != length; ++i)
630 objects[i] = [self objectAtIndex:state->state++];
631 state->itemsPtr = objects;
632 state->mutationsPtr = (unsigned long *) self;
633 return length;
634}
635
8a4106c2
JF
636@end
637
cd8bec2f
JF
638NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
639 size_t length([self length] - state->state);
640 if (length <= 0)
641 return 0;
642 else if (length > count)
643 length = count;
644 for (size_t i(0); i != length; ++i)
645 objects[i] = [self item:state->state++];
646 state->itemsPtr = objects;
647 state->mutationsPtr = (unsigned long *) self;
648 return length;
649}
650
017b2b71 651/* Cydia NSString Additions {{{ */
2a987aa5 652@interface NSString (Cydia)
3bddda52 653+ (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
6932575e 654+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
2a987aa5 655+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
9e07091a 656- (NSComparisonResult) compareByPath:(NSString *)other;
b4dff19a
JF
657- (NSString *) stringByCachingURLWithCurrentCDN;
658- (NSString *) stringByAddingPercentEscapesIncludingReserved;
2a987aa5
JF
659@end
660
661@implementation NSString (Cydia)
662
3bddda52
JF
663+ (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
664 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
665}
666
6932575e
JF
667+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
668 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
669 memcpy(data, bytes, length);
670 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
671}
672
2a987aa5 673+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
e2a207dd 674 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
2a987aa5
JF
675}
676
9e07091a
JF
677- (NSComparisonResult) compareByPath:(NSString *)other {
678 NSString *prefix = [self commonPrefixWithString:other options:0];
679 size_t length = [prefix length];
680
681 NSRange lrange = NSMakeRange(length, [self length] - length);
682 NSRange rrange = NSMakeRange(length, [other length] - length);
683
684 lrange = [self rangeOfString:@"/" options:0 range:lrange];
685 rrange = [other rangeOfString:@"/" options:0 range:rrange];
686
687 NSComparisonResult value;
688
689 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
690 value = NSOrderedSame;
691 else if (lrange.location == NSNotFound)
692 value = NSOrderedAscending;
693 else if (rrange.location == NSNotFound)
694 value = NSOrderedDescending;
695 else
696 value = NSOrderedSame;
697
698 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
699 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
700 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
701 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
702
703 NSComparisonResult result = [lpath compare:rpath];
704 return result == NSOrderedSame ? value : result;
705}
706
b4dff19a
JF
707- (NSString *) stringByCachingURLWithCurrentCDN {
708 return [self
99dc9e91
JF
709 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
710 withString:@"://cache.cydia.saurik.com/"
b4dff19a
JF
711 ];
712}
713
714- (NSString *) stringByAddingPercentEscapesIncludingReserved {
715 return [(id)CFURLCreateStringByAddingPercentEscapes(
f99f86e2 716 kCFAllocatorDefault,
b4dff19a
JF
717 (CFStringRef) self,
718 NULL,
719 CFSTR(";/?:@&=+$,"),
720 kCFStringEncodingUTF8
721 ) autorelease];
722}
723
2a987aa5 724@end
017b2b71 725/* }}} */
2a987aa5 726
017b2b71 727/* C++ NSString Wrapper Cache {{{ */
6932575e
JF
728class CYString {
729 private:
730 char *data_;
731 size_t size_;
732 CFStringRef cache_;
733
734 _finline void clear_() {
f30eaf83 735 if (cache_ != NULL) {
6932575e 736 CFRelease(cache_);
f30eaf83
JF
737 cache_ = NULL;
738 }
6932575e
JF
739 }
740
741 public:
742 _finline bool empty() const {
743 return size_ == 0;
744 }
745
746 _finline size_t size() const {
747 return size_;
748 }
749
750 _finline char *data() const {
751 return data_;
752 }
753
754 _finline void clear() {
755 size_ = 0;
756 clear_();
757 }
758
759 _finline CYString() :
760 data_(0),
761 size_(0),
f30eaf83 762 cache_(NULL)
6932575e
JF
763 {
764 }
765
766 _finline ~CYString() {
767 clear_();
768 }
769
770 void operator =(const CYString &rhs) {
771 data_ = rhs.data_;
772 size_ = rhs.size_;
773
774 if (rhs.cache_ == nil)
775 cache_ = NULL;
776 else
777 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
778 }
779
780 void set(apr_pool_t *pool, const char *data, size_t size) {
781 if (size == 0)
782 clear();
783 else {
784 clear_();
785
9ee296df 786 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
6932575e 787 memcpy(temp, data, size);
9ee296df 788 temp[size] = '\0';
6932575e
JF
789 data_ = temp;
790 size_ = size;
791 }
792 }
793
794 _finline void set(apr_pool_t *pool, const char *data) {
795 set(pool, data, data == NULL ? 0 : strlen(data));
796 }
797
798 _finline void set(apr_pool_t *pool, const std::string &rhs) {
799 set(pool, rhs.data(), rhs.size());
800 }
801
802 bool operator ==(const CYString &rhs) const {
803 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
804 }
805
dd9390c5 806 operator CFStringRef() {
6932575e
JF
807 if (cache_ == NULL) {
808 if (size_ == 0)
809 return nil;
810 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
5ec44e34
JF
811 if (cache_ == NULL)
812 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
dd9390c5
JF
813 } return cache_;
814 }
815
816 _finline operator id() {
817 return (NSString *) static_cast<CFStringRef>(*this);
6932575e
JF
818 }
819};
017b2b71
JF
820/* }}} */
821/* C++ NSString Algorithm Adapters {{{ */
6932575e
JF
822extern "C" {
823 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
824}
825
826struct NSStringMapHash :
827 std::unary_function<NSString *, size_t>
828{
829 _finline size_t operator ()(NSString *value) const {
830 return CFStringHashNSString((CFStringRef) value);
831 }
832};
833
834struct NSStringMapLess :
835 std::binary_function<NSString *, NSString *, bool>
836{
837 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
838 return [lhs compare:rhs] == NSOrderedAscending;
839 }
840};
841
842struct NSStringMapEqual :
843 std::binary_function<NSString *, NSString *, bool>
844{
845 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
846 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
847 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
848 //[lhs isEqualToString:rhs];
849 }
850};
017b2b71 851/* }}} */
6932575e 852
686e302f
JF
853/* Perl-Compatible RegEx {{{ */
854class Pcre {
855 private:
856 pcre *code_;
857 pcre_extra *study_;
858 int capture_;
859 int *matches_;
860 const char *data_;
861
862 public:
863 Pcre(const char *regex) :
864 study_(NULL)
865 {
866 const char *error;
867 int offset;
868 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
869
870 if (code_ == NULL) {
cb9c2100 871 lprintf("%d:%s\n", offset, error);
686e302f
JF
872 _assert(false);
873 }
874
875 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
876 matches_ = new int[(capture_ + 1) * 3];
877 }
878
879 ~Pcre() {
880 pcre_free(code_);
881 delete matches_;
882 }
883
884 NSString *operator [](size_t match) {
2a987aa5 885 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
686e302f
JF
886 }
887
7600bd69
JF
888 bool operator ()(NSString *data) {
889 // XXX: length is for characters, not for bytes
890 return operator ()([data UTF8String], [data length]);
891 }
892
686e302f
JF
893 bool operator ()(const char *data, size_t size) {
894 data_ = data;
895 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
896 }
897};
898/* }}} */
e057ec05 899/* Mime Addresses {{{ */
e057ec05
JF
900@interface Address : NSObject {
901 NSString *name_;
ad554f10 902 NSString *address_;
e057ec05
JF
903}
904
905- (NSString *) name;
ad554f10 906- (NSString *) address;
e057ec05 907
3ff1504e
JF
908- (void) setAddress:(NSString *)address;
909
e057ec05
JF
910+ (Address *) addressWithString:(NSString *)string;
911- (Address *) initWithString:(NSString *)string;
912@end
913
914@implementation Address
915
916- (void) dealloc {
917 [name_ release];
ad554f10
JF
918 if (address_ != nil)
919 [address_ release];
e057ec05
JF
920 [super dealloc];
921}
922
923- (NSString *) name {
924 return name_;
925}
926
ad554f10
JF
927- (NSString *) address {
928 return address_;
e057ec05
JF
929}
930
3ff1504e
JF
931- (void) setAddress:(NSString *)address {
932 if (address_ != nil)
933 [address_ autorelease];
934 if (address == nil)
935 address_ = nil;
936 else
937 address_ = [address retain];
938}
939
e057ec05
JF
940+ (Address *) addressWithString:(NSString *)string {
941 return [[[Address alloc] initWithString:string] autorelease];
942}
943
ad554f10
JF
944+ (NSArray *) _attributeKeys {
945 return [NSArray arrayWithObjects:@"address", @"name", nil];
946}
947
948- (NSArray *) attributeKeys {
949 return [[self class] _attributeKeys];
950}
951
952+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
953 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
954}
955
e057ec05
JF
956- (Address *) initWithString:(NSString *)string {
957 if ((self = [super init]) != nil) {
958 const char *data = [string UTF8String];
959 size_t size = [string length];
960
ad554f10 961 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
faf4eb4f 962
ad554f10
JF
963 if (address_r(data, size)) {
964 name_ = [address_r[1] retain];
965 address_ = [address_r[2] retain];
e057ec05 966 } else {
f464053e 967 name_ = [string retain];
ad554f10 968 address_ = nil;
e057ec05
JF
969 }
970 } return self;
971}
972
973@end
974/* }}} */
b0d03ade 975/* CoreGraphics Primitives {{{ */
eb6d9c93 976class CYColor {
686e302f
JF
977 private:
978 CGColorRef color_;
979
980 public:
eb6d9c93 981 CYColor() :
e057ec05
JF
982 color_(NULL)
983 {
984 }
985
eb6d9c93 986 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
e057ec05
JF
987 color_(NULL)
988 {
989 Set(space, red, green, blue, alpha);
990 }
991
992 void Clear() {
993 if (color_ != NULL)
994 CGColorRelease(color_);
686e302f
JF
995 }
996
eb6d9c93 997 ~CYColor() {
e057ec05
JF
998 Clear();
999 }
1000
1001 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1002 Clear();
1003 float color[] = {red, green, blue, alpha};
9b62701b 1004 color_ = CGColorCreate(space, (CGFloat *) color);
686e302f
JF
1005 }
1006
1007 operator CGColorRef() {
1008 return color_;
1009 }
1010};
686e302f
JF
1011/* }}} */
1012
e057ec05 1013/* Random Global Variables {{{ */
2d28b35a 1014static const int PulseInterval_ = 50000;
575ffd3c 1015static const int ButtonBarWidth_ = 60;
2a987aa5 1016static const int ButtonBarHeight_ = 48;
fa7bb92f 1017static const float KeyboardTime_ = 0.3f;
f464053e 1018
c59881cd
JF
1019static int Finish_;
1020static NSArray *Finishes_;
1021
f464053e 1022#define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
bde2d79b 1023#define NotifyConfig_ "/etc/notify.conf"
fc675b93 1024
3ff1504e
JF
1025static bool Queuing_;
1026
eb6d9c93
JF
1027static CYColor Blue_;
1028static CYColor Blueish_;
1029static CYColor Black_;
1030static CYColor Off_;
1031static CYColor White_;
1032static CYColor Gray_;
1033static CYColor Green_;
1034static CYColor Purple_;
1035static CYColor Purplish_;
d8d9a65c 1036
3ff1504e
JF
1037static UIColor *InstallingColor_;
1038static UIColor *RemovingColor_;
e057ec05 1039
853d14d3 1040static NSString *App_;
0039464f 1041static NSString *Home_;
0039464f 1042
2a987aa5 1043static BOOL Advanced_;
9e07091a 1044static BOOL Ignored_;
2a987aa5 1045
5e563e79
JF
1046static UIFont *Font12_;
1047static UIFont *Font12Bold_;
1048static UIFont *Font14_;
1049static UIFont *Font18Bold_;
1050static UIFont *Font22Bold_;
1051
2cb68ddf 1052static const char *Machine_ = NULL;
78f1a54b 1053static NSString *System_ = nil;
3bdadc1e
JF
1054static NSString *SerialNumber_ = nil;
1055static NSString *ChipID_ = nil;
1056static NSString *Token_ = nil;
1057static NSString *UniqueID_ = nil;
1058static NSString *Build_ = nil;
1059static NSString *Product_ = nil;
1060static NSString *Safari_ = nil;
fc675b93 1061
c59881cd
JF
1062static CFLocaleRef Locale_;
1063static NSArray *Languages_;
1064static CGColorSpaceRef space_;
e057ec05 1065
d1494d2c 1066static NSDictionary *SectionMap_;
686e302f 1067static NSMutableDictionary *Metadata_;
faf4eb4f
JF
1068static _transient NSMutableDictionary *Settings_;
1069static _transient NSString *Role_;
1070static _transient NSMutableDictionary *Packages_;
1071static _transient NSMutableDictionary *Sections_;
1072static _transient NSMutableDictionary *Sources_;
3d37fc0d 1073static bool Changed_;
686e302f 1074static NSDate *now_;
20dd7407 1075
5ec44e34 1076static bool IsWildcat_;
e057ec05 1077/* }}} */
c59881cd 1078
e057ec05
JF
1079/* Display Helpers {{{ */
1080inline float Interpolate(float begin, float end, float fraction) {
1081 return (end - begin) * fraction + begin;
1082}
4941f41d 1083
6932575e 1084/* XXX: localize this! */
b6ffa083 1085NSString *SizeString(double size) {
f464053e
JF
1086 bool negative = size < 0;
1087 if (negative)
1088 size = -size;
1089
b6ffa083
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
56e10908 1098 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
b6ffa083
JF
1099}
1100
fbe40361
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
b4c4fac4
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
98fb9119 1112CFStringRef StripVersion(const char *version) {
f7ee98cb
JF
1113 const char *colon(strchr(version, ':'));
1114 if (colon != NULL)
1115 version = colon + 1;
b4c4fac4
JF
1116 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1117 // XXX: performance
fbe40361 1118 return CFCString(version);
f7ee98cb
JF
1119}
1120
6932575e 1121NSString *LocalizeSection(NSString *section) {
bb9edf8b 1122 static Pcre title_r("^(.*?) \\((.*)\\)$");
9ee296df
JF
1123 if (title_r(section)) {
1124 NSString *parent(title_r[1]);
1125 NSString *child(title_r[2]);
1126
61b13cae 1127 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
9ee296df
JF
1128 LocalizeSection(parent),
1129 LocalizeSection(child)
bb9edf8b 1130 ];
9ee296df 1131 }
bb9edf8b
JF
1132
1133 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
6932575e
JF
1134}
1135
49525fb2
JF
1136NSString *Simplify(NSString *title) {
1137 const char *data = [title UTF8String];
1138 size_t size = [title length];
1139
faf4eb4f
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
bb9edf8b 1148 static Pcre title_r("^(.*?) \\((.*)\\)$");
49525fb2 1149 if (title_r(data, size))
faf4eb4f
JF
1150 return Simplify(title_r[1]);
1151
1152 return title;
49525fb2 1153}
e057ec05
JF
1154/* }}} */
1155
c59881cd
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
fa7bb92f 1170bool isSectionVisible(NSString *section) {
43b742af
JF
1171 NSDictionary *metadata([Sections_ objectForKey:section]);
1172 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
fa7bb92f
JF
1173 return hidden == nil || ![hidden boolValue];
1174}
1175
15b41c77
GP
1176@class Cydia;
1177
a0e1b888 1178/* Delegate Prototypes {{{ */
e057ec05
JF
1179@class Package;
1180@class Source;
1181
238b07ce
JF
1182@interface NSObject (ProgressDelegate)
1183@end
1184
e057ec05 1185@protocol ProgressDelegate
6981ccdf 1186- (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
e057ec05
JF
1187- (void) setProgressTitle:(NSString *)title;
1188- (void) setProgressPercent:(float)percent;
87c76914 1189- (void) startProgress;
e057ec05 1190- (void) addProgressOutput:(NSString *)output;
87c76914 1191- (bool) isCancelling:(size_t)received;
e057ec05
JF
1192@end
1193
7600bd69 1194@protocol ConfigurationDelegate
965edd52 1195- (void) repairWithSelector:(SEL)selector;
7600bd69
JF
1196- (void) setConfigurationData:(NSString *)data;
1197@end
1198
f441e717 1199@class PackageController;
6932575e 1200
e057ec05 1201@protocol CydiaDelegate
f441e717 1202- (void) setPackageController:(PackageController *)view;
3ff1504e 1203- (void) clearPackage:(Package *)package;
e057ec05 1204- (void) installPackage:(Package *)package;
daf7f6e2 1205- (void) installPackages:(NSArray *)packages;
e057ec05 1206- (void) removePackage:(Package *)package;
1e4922b8
JF
1207- (void) beginUpdate;
1208- (BOOL) updating;
e057ec05 1209- (void) distUpgrade;
90e9a238 1210- (void) loadData;
fa7bb92f 1211- (void) updateData;
faf4eb4f 1212- (void) syncData;
c1edf105 1213- (void) showSettings;
faf4eb4f 1214- (UIProgressHUD *) addProgressHUD;
7398a389 1215- (void) removeProgressHUD:(UIProgressHUD *)hud;
881fe77f 1216- (CYViewController *) pageForPackage:(NSString *)name;
f441e717 1217- (PackageController *) packageController;
48861ec9 1218- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
e057ec05 1219@end
a0e1b888 1220/* }}} */
686e302f 1221
a75f53e7
JF
1222/* Status Delegation {{{ */
1223class Status :
1224 public pkgAcquireStatus
1225{
1226 private:
238b07ce 1227 _transient NSObject<ProgressDelegate> *delegate_;
a75f53e7
JF
1228
1229 public:
1230 Status() :
1231 delegate_(nil)
1232 {
1233 }
1234
1235 void setDelegate(id delegate) {
1236 delegate_ = delegate;
1237 }
1238
6981ccdf
JF
1239 NSObject<ProgressDelegate> *getDelegate() const {
1240 return delegate_;
1241 }
1242
a75f53e7
JF
1243 virtual bool MediaChange(std::string media, std::string drive) {
1244 return false;
1245 }
1246
1247 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
a75f53e7
JF
1248 }
1249
1250 virtual void Fetch(pkgAcquire::ItemDesc &item) {
907a35d6 1251 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
6981ccdf 1252 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
a75f53e7
JF
1253 }
1254
1255 virtual void Done(pkgAcquire::ItemDesc &item) {
a75f53e7
JF
1256 }
1257
1258 virtual void Fail(pkgAcquire::ItemDesc &item) {
3325a005
JF
1259 if (
1260 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1261 item.Owner->Status == pkgAcquire::Item::StatDone
1262 )
1263 return;
1264
f464053e
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
6981ccdf 1273 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
f464053e
JF
1274 withObject:[NSArray arrayWithObjects:
1275 [NSString stringWithUTF8String:error.c_str()],
1276 source,
1277 nil]
238b07ce
JF
1278 waitUntilDone:YES
1279 ];
a75f53e7
JF
1280 }
1281
1282 virtual bool Pulse(pkgAcquire *Owner) {
4941f41d
JF
1283 bool value = pkgAcquireStatus::Pulse(Owner);
1284
1285 float percent(
1286 double(CurrentBytes + CurrentItems) /
1287 double(TotalBytes + TotalItems)
1288 );
1289
e057ec05 1290 [delegate_ setProgressPercent:percent];
87c76914 1291 return [delegate_ isCancelling:CurrentBytes] ? false : value;
a75f53e7
JF
1292 }
1293
1294 virtual void Start() {
87c76914 1295 [delegate_ startProgress];
a75f53e7
JF
1296 }
1297
1298 virtual void Stop() {
a75f53e7
JF
1299 }
1300};
1301/* }}} */
1302/* Progress Delegation {{{ */
1303class Progress :
1304 public OpProgress
1305{
1306 private:
e057ec05 1307 _transient id<ProgressDelegate> delegate_;
017b2b71 1308 float percent_;
a75f53e7
JF
1309
1310 protected:
1311 virtual void Update() {
6981ccdf
JF
1312 /*if (abs(Percent - percent_) > 2)
1313 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
017b2b71 1314 percent_ = Percent;
6981ccdf 1315 }*/
017b2b71 1316
b7ad9c68
JF
1317 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1318 [delegate_ setProgressPercent:(Percent / 100)];*/
a75f53e7
JF
1319 }
1320
1321 public:
1322 Progress() :
017b2b71
JF
1323 delegate_(nil),
1324 percent_(0)
a75f53e7
JF
1325 {
1326 }
1327
1328 void setDelegate(id delegate) {
1329 delegate_ = delegate;
1330 }
1331
6981ccdf
JF
1332 id getDelegate() const {
1333 return delegate_;
1334 }
1335
a75f53e7 1336 virtual void Done() {
6981ccdf 1337 //NSLog(@"DONE");
b7ad9c68 1338 //[delegate_ setProgressPercent:1];
a75f53e7
JF
1339 }
1340};
1341/* }}} */
1342
e057ec05 1343/* Database Interface {{{ */
631a0a1e
JF
1344typedef std::map< unsigned long, _H<Source> > SourceMap;
1345
e057ec05 1346@interface Database : NSObject {
6932575e
JF
1347 NSZone *zone_;
1348 apr_pool_t *pool_;
1349
a70cf746
JF
1350 unsigned era_;
1351
e057ec05 1352 pkgCacheFile cache_;
965edd52 1353 pkgDepCache::Policy *policy_;
e057ec05
JF
1354 pkgRecords *records_;
1355 pkgProblemResolver *resolver_;
1356 pkgAcquire *fetcher_;
1357 FileFd *lock_;
1358 SPtr<pkgPackageManager> manager_;
1359 pkgSourceList *list_;
b0d03ade 1360
631a0a1e 1361 SourceMap sources_;
9ee296df 1362 NSMutableArray *packages_;
686e302f 1363
238b07ce 1364 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
e057ec05
JF
1365 Status status_;
1366 Progress progress_;
7600bd69 1367
d72d91aa 1368 int cydiafd_;
e057ec05 1369 int statusfd_;
7600bd69 1370 FILE *input_;
a75f53e7
JF
1371}
1372
dbe0f181 1373+ (Database *) sharedInstance;
a70cf746 1374- (unsigned) era;
dbe0f181 1375
d72d91aa 1376- (void) _readCydia:(NSNumber *)fd;
e057ec05
JF
1377- (void) _readStatus:(NSNumber *)fd;
1378- (void) _readOutput:(NSNumber *)fd;
4941f41d 1379
7600bd69
JF
1380- (FILE *) input;
1381
e057ec05 1382- (Package *) packageWithName:(NSString *)name;
a75f53e7 1383
e057ec05 1384- (pkgCacheFile &) cache;
965edd52 1385- (pkgDepCache::Policy *) policy;
e057ec05
JF
1386- (pkgRecords *) records;
1387- (pkgProblemResolver *) resolver;
1388- (pkgAcquire &) fetcher;
ce09fc27 1389- (pkgSourceList &) list;
e057ec05 1390- (NSArray *) packages;
faf4eb4f 1391- (NSArray *) sources;
e057ec05
JF
1392- (void) reloadData;
1393
965edd52 1394- (void) configure;
6981ccdf 1395- (bool) prepare;
e057ec05 1396- (void) perform;
6981ccdf 1397- (bool) upgrade;
e057ec05
JF
1398- (void) update;
1399
419a9efd
JF
1400- (void) setVisible;
1401
6981ccdf 1402- (void) updateWithStatus:(Status &)status;
e057ec05
JF
1403
1404- (void) setDelegate:(id)delegate;
3e3977a2 1405- (Source *) getSource:(pkgCache::PkgFileIterator)file;
6981ccdf
JF
1406@end
1407/* }}} */
1408/* Delegate Helpers {{{ */
1e4922b8 1409@implementation NSObject (ProgressDelegate)
6981ccdf
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];
283fc596 1434
9b62701b
GP
1435 [self performSelector:@selector(setProgressError:withTitle:)
1436 withObject:error
1437 withObject:(package == nil ? id : [package name])
1438 ];
6981ccdf
JF
1439}
1440
a75f53e7 1441@end
e057ec05 1442/* }}} */
a75f53e7 1443
e057ec05
JF
1444/* Source Class {{{ */
1445@interface Source : NSObject {
9050015e 1446 CYString depiction_;
b8b1cfd0
JF
1447 CYString description_;
1448 CYString label_;
1449 CYString origin_;
1450 CYString support_;
a75f53e7 1451
b8b1cfd0
JF
1452 CYString uri_;
1453 CYString distribution_;
1454 CYString type_;
1455 CYString version_;
4941f41d 1456
b8b1cfd0 1457 NSString *host_;
6b8ef53e 1458 NSString *authority_;
b8b1cfd0
JF
1459
1460 CYString defaultIcon_;
a75f53e7 1461
faf4eb4f 1462 NSDictionary *record_;
e057ec05 1463 BOOL trusted_;
a75f53e7
JF
1464}
1465
b8b1cfd0 1466- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
a75f53e7 1467
faf4eb4f
JF
1468- (NSComparisonResult) compareByNameAndType:(Source *)source;
1469
9050015e 1470- (NSString *) depictionForPackage:(NSString *)package;
3ff1504e
JF
1471- (NSString *) supportForPackage:(NSString *)package;
1472
faf4eb4f 1473- (NSDictionary *) record;
e057ec05 1474- (BOOL) trusted;
a75f53e7 1475
e057ec05
JF
1476- (NSString *) uri;
1477- (NSString *) distribution;
1478- (NSString *) type;
faf4eb4f
JF
1479- (NSString *) key;
1480- (NSString *) host;
e057ec05 1481
faf4eb4f 1482- (NSString *) name;
e057ec05
JF
1483- (NSString *) description;
1484- (NSString *) label;
1485- (NSString *) origin;
1486- (NSString *) version;
a75f53e7 1487
e057ec05 1488- (NSString *) defaultIcon;
faf4eb4f 1489
a75f53e7 1490@end
a75f53e7 1491
e057ec05 1492@implementation Source
a75f53e7 1493
ce09fc27 1494- (void) _clear {
b8b1cfd0
JF
1495 uri_.clear();
1496 distribution_.clear();
1497 type_.clear();
ce09fc27 1498
b8b1cfd0
JF
1499 description_.clear();
1500 label_.clear();
1501 origin_.clear();
9050015e 1502 depiction_.clear();
b8b1cfd0
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 }
419a9efd
JF
1516
1517 if (authority_ != nil) {
1518 [authority_ release];
1519 authority_ = nil;
1520 }
ce09fc27 1521}
a75f53e7 1522
ce09fc27
JF
1523- (void) dealloc {
1524 [self _clear];
e057ec05 1525 [super dealloc];
a75f53e7
JF
1526}
1527
ad554f10
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
b8b1cfd0 1540- (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
ce09fc27 1541 [self _clear];
a75f53e7 1542
ce09fc27
JF
1543 trusted_ = index->IsTrusted();
1544
b8b1cfd0
JF
1545 uri_.set(pool, index->GetURI());
1546 distribution_.set(pool, index->GetDist());
1547 type_.set(pool, index->GetType());
ce09fc27
JF
1548
1549 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1550 if (dindex != NULL) {
f30eaf83
JF
1551 FileFd fd;
1552 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1553 _error->Discard();
1554 else {
1555 pkgTagFile tags(&fd);
b8b1cfd0 1556
f30eaf83
JF
1557 pkgTagSection section;
1558 tags.Step(section);
ce09fc27 1559
f30eaf83
JF
1560 struct {
1561 const char *name_;
1562 CYString *value_;
1563 } names[] = {
1564 {"default-icon", &defaultIcon_},
9050015e 1565 {"depiction", &depiction_},
f30eaf83
JF
1566 {"description", &description_},
1567 {"label", &label_},
1568 {"origin", &origin_},
1569 {"support", &support_},
1570 {"version", &version_},
1571 };
b8b1cfd0 1572
f30eaf83
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 }
b8b1cfd0 1580 }
e057ec05 1581 }
ce09fc27 1582 }
faf4eb4f 1583
ce09fc27
JF
1584 record_ = [Sources_ objectForKey:[self key]];
1585 if (record_ != nil)
1586 record_ = [record_ retain];
b8b1cfd0 1587
419a9efd
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)
12b7669a 1595 authority_ = host_;
419a9efd
JF
1596 else
1597 authority_ = [url path];
12b7669a
JF
1598
1599 if (authority_ != nil)
1600 authority_ = [authority_ retain];
ce09fc27
JF
1601}
1602
b8b1cfd0 1603- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
ce09fc27 1604 if ((self = [super init]) != nil) {
b8b1cfd0 1605 [self setMetaIndex:index inPool:pool];
e057ec05 1606 } return self;
4941f41d 1607}
a75f53e7 1608
faf4eb4f
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
9c4e0cbe 1629 return [lhs compare:rhs options:LaxCompareOptions_];
faf4eb4f
JF
1630}
1631
9050015e 1632- (NSString *) depictionForPackage:(NSString *)package {
cbc40330 1633 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
9050015e
JF
1634}
1635
3ff1504e 1636- (NSString *) supportForPackage:(NSString *)package {
cbc40330 1637 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
3ff1504e
JF
1638}
1639
faf4eb4f
JF
1640- (NSDictionary *) record {
1641 return record_;
1642}
1643
e057ec05
JF
1644- (BOOL) trusted {
1645 return trusted_;
1646}
2d28b35a 1647
e057ec05
JF
1648- (NSString *) uri {
1649 return uri_;
1650}
1cb11c5f 1651
e057ec05
JF
1652- (NSString *) distribution {
1653 return distribution_;
1654}
a75f53e7 1655
e057ec05
JF
1656- (NSString *) type {
1657 return type_;
a75f53e7
JF
1658}
1659
faf4eb4f 1660- (NSString *) key {
b8b1cfd0 1661 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
faf4eb4f
JF
1662}
1663
1664- (NSString *) host {
b8b1cfd0 1665 return host_;
faf4eb4f
JF
1666}
1667
1668- (NSString *) name {
419a9efd 1669 return origin_.empty() ? authority_ : origin_;
faf4eb4f
JF
1670}
1671
e057ec05
JF
1672- (NSString *) description {
1673 return description_;
1674}
686e302f 1675
e057ec05 1676- (NSString *) label {
419a9efd 1677 return label_.empty() ? authority_ : label_;
e057ec05 1678}
2d28b35a 1679
e057ec05
JF
1680- (NSString *) origin {
1681 return origin_;
1682}
2d28b35a 1683
e057ec05
JF
1684- (NSString *) version {
1685 return version_;
1686}
4941f41d 1687
e057ec05
JF
1688- (NSString *) defaultIcon {
1689 return defaultIcon_;
1690}
4941f41d 1691
2a987aa5
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
a75f53e7 1727@end
686e302f 1728/* }}} */
e057ec05 1729/* Package Class {{{ */
e057ec05 1730@interface Package : NSObject {
a70cf746 1731 unsigned era_;
631a0a1e 1732 apr_pool_t *pool_;
a70cf746 1733
3e3977a2 1734 pkgCache::VerIterator version_;
e057ec05
JF
1735 pkgCache::PkgIterator iterator_;
1736 _transient Database *database_;
e057ec05 1737 pkgCache::VerFileIterator file_;
3d37fc0d 1738
e057ec05 1739 Source *source_;
3d37fc0d 1740 bool cached_;
631a0a1e 1741 bool parsed_;
a75f53e7 1742
6932575e
JF
1743 CYString section_;
1744 NSString *section$_;
a70cf746 1745 bool essential_;
419a9efd 1746 bool required_;
43b742af 1747 bool visible_;
5ec44e34 1748 bool obsolete_;
f159ecd4 1749
e057ec05 1750 NSString *latest_;
b4c4fac4 1751 CYString installed_;
a75f53e7 1752
9ee296df 1753 CYString id_;
6932575e
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
419a9efd 1766 CYString bugs_;
6932575e 1767 CYString support_;
fbe40361 1768 NSMutableArray *tags_;
faf4eb4f 1769 NSString *role_;
2a987aa5
JF
1770
1771 NSArray *relationships_;
43b742af 1772
6932575e 1773 NSMutableDictionary *metadata_;
43b742af
JF
1774 _transient NSDate *firstSeen_;
1775 _transient NSDate *lastSeen_;
1776 bool subscribed_;
686e302f
JF
1777}
1778
3e3977a2 1779- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
6932575e 1780+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
686e302f 1781
2a987aa5 1782- (pkgCache::PkgIterator) iterator;
631a0a1e 1783- (void) parse;
2a987aa5 1784
e057ec05 1785- (NSString *) section;
6b4b3bee
JF
1786- (NSString *) simpleSection;
1787
6932575e
JF
1788- (NSString *) longSection;
1789- (NSString *) shortSection;
1790
ce09fc27
JF
1791- (NSString *) uri;
1792
e057ec05
JF
1793- (Address *) maintainer;
1794- (size_t) size;
66abcbb0
JF
1795- (NSString *) longDescription;
1796- (NSString *) shortDescription;
3bddda52 1797- (unichar) index;
a75f53e7 1798
f159ecd4 1799- (NSMutableDictionary *) metadata;
e057ec05 1800- (NSDate *) seen;
f159ecd4
JF
1801- (BOOL) subscribed;
1802- (BOOL) ignored;
63a1e4b8 1803
e057ec05
JF
1804- (NSString *) latest;
1805- (NSString *) installed;
b4c4fac4 1806- (BOOL) uninstalled;
965edd52
JF
1807
1808- (BOOL) valid;
238b07ce 1809- (BOOL) upgradableAndEssential:(BOOL)essential;
e057ec05
JF
1810- (BOOL) essential;
1811- (BOOL) broken;
853d14d3 1812- (BOOL) unfiltered;
fa7bb92f 1813- (BOOL) visible;
686e302f 1814
3319715b
JF
1815- (BOOL) half;
1816- (BOOL) halfConfigured;
1817- (BOOL) halfInstalled;
1818- (BOOL) hasMode;
1819- (NSString *) mode;
1820
419a9efd
JF
1821- (void) setVisible;
1822
e057ec05
JF
1823- (NSString *) id;
1824- (NSString *) name;
dbe0f181 1825- (UIImage *) icon;
ad554f10 1826- (NSString *) homepage;
0235116c 1827- (NSString *) depiction;
d72d91aa 1828- (Address *) author;
686e302f 1829
3ff1504e
JF
1830- (NSString *) support;
1831
f464053e 1832- (NSArray *) files;
2a987aa5 1833- (NSArray *) relationships;
f464053e
JF
1834- (NSArray *) warnings;
1835- (NSArray *) applications;
2a987aa5 1836
e057ec05 1837- (Source *) source;
faf4eb4f 1838- (NSString *) role;
686e302f 1839
e057ec05 1840- (BOOL) matches:(NSString *)text;
686e302f 1841
faf4eb4f 1842- (bool) hasSupportingRole;
fa7bb92f 1843- (BOOL) hasTag:(NSString *)tag;
cb9c2100 1844- (NSString *) primaryPurpose;
dbe0f181 1845- (NSArray *) purposes;
d8d9a65c 1846- (bool) isCommercial;
fa7bb92f 1847
dd9390c5
JF
1848- (CYString &) cyname;
1849
6932575e 1850- (uint32_t) compareBySection:(NSArray *)sections;
f159ecd4
JF
1851
1852- (uint32_t) compareForChanges;
686e302f 1853
e057ec05
JF
1854- (void) install;
1855- (void) remove;
7e986211 1856
7cf54836 1857- (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
5ec44e34 1858- (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
7cf54836 1859- (bool) isInstalledAndVisible:(NSNumber *)number;
6981ccdf 1860- (bool) isVisibleInSection:(NSString *)section;
7cf54836 1861- (bool) isVisibleInSource:(Source *)source;
686e302f 1862
e057ec05 1863@end
686e302f 1864
6932575e
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
dd9390c5
JF
1892_finline static void Stifle(uint8_t &value) {
1893}
43b742af 1894
dd9390c5
JF
1895uint32_t PackagePrefixRadix(Package *self, void *context) {
1896 size_t offset(reinterpret_cast<size_t>(context));
1897 CYString &name([self cyname]);
43b742af 1898
dd9390c5
JF
1899 size_t size(name.size());
1900 if (size == 0)
1901 return 0;
1902 char *text(name.data());
43b742af 1903
dd9390c5
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 }
43b742af 1914
dd9390c5
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);
43b742af 1956
08383255
JF
1957 if (lhn == NULL)
1958 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1959 else if (rhn == NULL)
1960 return NSOrderedDescending;
1961
43b742af 1962 _profile(PackageNameCompare$NumbersLast)
dd9390c5 1963 if (!lhi.empty() && !rhi.empty()) {
43b742af
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
dd9390c5
JF
1972 CFIndex length = CFStringGetLength(lhn);
1973
43b742af
JF
1974 _profile(PackageNameCompare$Compare)
1975 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1976 _end
1977 _end
1978}
1979
66abcbb0
JF
1980CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1981 return PackageNameCompare(*lhs, *rhs, context);
43b742af
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
e057ec05 1992@implementation Package
686e302f 1993
dd9390c5
JF
1994- (NSString *) description {
1995 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1996}
1997
e057ec05 1998- (void) dealloc {
3d37fc0d
JF
1999 if (source_ != nil)
2000 [source_ release];
6932575e
JF
2001 if (section$_ != nil)
2002 [section$_ release];
f159ecd4 2003
3e3977a2
JF
2004 if (latest_ != nil)
2005 [latest_ release];
686e302f 2006
6932575e
JF
2007 if (sponsor$_ != nil)
2008 [sponsor$_ release];
2009 if (author$_ != nil)
2010 [author$_ release];
fa7bb92f
JF
2011 if (tags_ != nil)
2012 [tags_ release];
faf4eb4f
JF
2013 if (role_ != nil)
2014 [role_ release];
63a1e4b8 2015
2a987aa5
JF
2016 if (relationships_ != nil)
2017 [relationships_ release];
6932575e
JF
2018 if (metadata_ != nil)
2019 [metadata_ release];
2a987aa5 2020
e057ec05 2021 [super dealloc];
686e302f
JF
2022}
2023
d8d9a65c
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
ad554f10 2035+ (NSArray *) _attributeKeys {
66abcbb0 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];
ad554f10
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
631a0a1e
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},
419a9efd 2072 {"bugs", &bugs_},
631a0a1e
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;
fbe40361 2092 if (parser->ShortDesc(start, end)) {
631a0a1e
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)
7affe45b 2103 if (homepage_.empty())
631a0a1e
JF
2104 homepage_ = website;
2105 if (homepage_ == depiction_)
2106 homepage_.clear();
2107 _end
2108 _end
2109}
2110
419a9efd 2111- (void) setVisible {
37455cf8 2112 visible_ = required_ && [self unfiltered];
419a9efd
JF
2113}
2114
3e3977a2 2115- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
a70cf746 2116 if ((self = [super init]) != nil) {
3e3977a2 2117 _profile(Package$initWithVersion)
a70cf746
JF
2118 @synchronized (database) {
2119 era_ = [database era];
631a0a1e 2120 pool_ = pool;
a70cf746 2121
3e3977a2
JF
2122 version_ = version;
2123 iterator_ = version.ParentPkg();
e057ec05 2124 database_ = database;
686e302f 2125
3e3977a2 2126 _profile(Package$initWithVersion$Latest)
98fb9119 2127 latest_ = (NSString *) StripVersion(version_.VerStr());
3bddda52 2128 _end
e2a207dd 2129
631a0a1e
JF
2130 pkgCache::VerIterator current;
2131 _profile(Package$initWithVersion$Versions)
2132 current = iterator_.CurrentVer();
2133 if (!current.end())
b4c4fac4 2134 installed_.set(pool_, StripVersion_(current.VerStr()));
7e986211 2135
631a0a1e
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
3bddda52 2143
3e3977a2 2144 _profile(Package$initWithVersion$Name)
631a0a1e 2145 id_.set(pool_, iterator_.Name());
fbe40361 2146 name_.set(pool, iterator_.Display());
3bddda52
JF
2147 _end
2148
631a0a1e
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;
3bddda52 2155 _end
631a0a1e
JF
2156 }
2157
419a9efd 2158 required_ = true;
9050015e 2159
3e3977a2 2160 _profile(Package$initWithVersion$Tags)
fbe40361
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)];
bd8e54e1 2167 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
fbe40361 2168 role_ = (NSString *) CFCString(name + 6);
419a9efd 2169 if (required_ && strncmp(name, "require::", 9) == 0 && (
9050015e
JF
2170 true
2171 ))
419a9efd 2172 required_ = false;
fbe40361
JF
2173 ++tag;
2174 } while (!tag.end());
2175 }
3bddda52 2176 _end
faf4eb4f 2177
6b92acab 2178 bool changed(false);
cbc40330 2179 NSString *key([static_cast<id>(id_) lowercaseString]);
56e10908 2180
3e3977a2 2181 _profile(Package$initWithVersion$Metadata)
6932575e 2182 metadata_ = [Packages_ objectForKey:key];
43b742af 2183
6932575e 2184 if (metadata_ == nil) {
98fb9119 2185 firstSeen_ = now_;
43b742af 2186
6932575e 2187 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
43b742af
JF
2188 firstSeen_, @"FirstSeen",
2189 latest_, @"LastVersion",
3bddda52 2190 nil] mutableCopy];
6b92acab 2191
3bddda52
JF
2192 changed = true;
2193 } else {
43b742af
JF
2194 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2195 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2196
2197 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2198 subscribed_ = [subscribed boolValue];
2199
6932575e 2200 NSString *version([metadata_ objectForKey:@"LastVersion"]);
3bddda52 2201
43b742af
JF
2202 if (firstSeen_ == nil) {
2203 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2204 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
6b92acab
JF
2205 changed = true;
2206 }
6b92acab 2207
3e3977a2
JF
2208 if (version == nil) {
2209 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2210 changed = true;
5ec44e34 2211 } else if (![version isEqualToString:latest_]) {
3e3977a2 2212 [metadata_ setObject:latest_ forKey:@"LastVersion"];
43b742af
JF
2213 lastSeen_ = now_;
2214 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
3e3977a2 2215 changed = true;
5ec44e34 2216 }
3bddda52
JF
2217 }
2218
6932575e
JF
2219 metadata_ = [metadata_ retain];
2220
3bddda52 2221 if (changed) {
6932575e 2222 [Packages_ setObject:metadata_ forKey:key];
3bddda52
JF
2223 Changed_ = true;
2224 }
2225 _end
a70cf746 2226
3e3977a2 2227 _profile(Package$initWithVersion$Section)
631a0a1e 2228 section_.set(pool_, iterator_.Section());
6932575e 2229 _end
a70cf746 2230
5ec44e34 2231 obsolete_ = [self hasTag:@"cydia::obsolete"];
6932575e 2232 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
419a9efd 2233 [self setVisible];
a70cf746 2234 } _end } return self;
a75f53e7
JF
2235}
2236
6932575e 2237+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
ca06bb0e 2238@synchronized ([Database class]) {
bb9edf8b
JF
2239 pkgCache::VerIterator version;
2240
2241 _profile(Package$packageWithIterator$GetCandidateVer)
2242 version = [database policy]->GetCandidateVer(iterator);
2243 _end
2244
3e3977a2
JF
2245 if (version.end())
2246 return nil;
bb9edf8b 2247
965edd52 2248 return [[[Package alloc]
3e3977a2 2249 initWithVersion:version
6932575e
JF
2250 withZone:zone
2251 inPool:pool
965edd52
JF
2252 database:database
2253 ] autorelease];
ca06bb0e 2254} }
a75f53e7 2255
2a987aa5
JF
2256- (pkgCache::PkgIterator) iterator {
2257 return iterator_;
2258}
2259
e057ec05 2260- (NSString *) section {
6932575e
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$_;
a75f53e7
JF
2277}
2278
6b4b3bee
JF
2279- (NSString *) simpleSection {
2280 if (NSString *section = [self section])
2281 return Simplify(section);
2282 else
2283 return nil;
ce09fc27 2284}
6b4b3bee 2285
6932575e 2286- (NSString *) longSection {
f30eaf83 2287 return LocalizeSection([self section]);
6932575e
JF
2288}
2289
2290- (NSString *) shortSection {
2291 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2292}
2293
ce09fc27
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
6b4b3bee
JF
2305}
2306
e057ec05 2307- (Address *) maintainer {
965edd52
JF
2308 if (file_.end())
2309 return nil;
e057ec05 2310 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
0a7e5478
JF
2311 const std::string &maintainer(parser->Maintainer());
2312 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
b6ffa083
JF
2313}
2314
e057ec05 2315- (size_t) size {
965edd52 2316 return version_.end() ? 0 : version_->InstalledSize;
a75f53e7
JF
2317}
2318
66abcbb0 2319- (NSString *) longDescription {
965edd52
JF
2320 if (file_.end())
2321 return nil;
e057ec05 2322 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2a987aa5 2323 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
b6ffa083 2324
e057ec05
JF
2325 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2326 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2327 if ([lines count] < 2)
2328 return nil;
2d28b35a 2329
e057ec05 2330 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
9fdd37d0 2331 for (size_t i(1), e([lines count]); i != e; ++i) {
e057ec05
JF
2332 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2333 [trimmed addObject:trim];
2334 }
2d28b35a 2335
e057ec05
JF
2336 return [trimmed componentsJoinedByString:@"\n"];
2337}
a75f53e7 2338
66abcbb0
JF
2339- (NSString *) shortDescription {
2340 return tagline_;
2341}
2342
3bddda52
JF
2343- (unichar) index {
2344 _profile(Package$index)
43b742af
JF
2345 CFStringRef name((CFStringRef) [self name]);
2346 if (CFStringGetLength(name) == 0)
3bddda52 2347 return '#';
43b742af
JF
2348 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2349 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
3bddda52 2350 return '#';
c46df204 2351 return toupper(character);
3bddda52 2352 _end
e057ec05 2353}
2d28b35a 2354
f159ecd4 2355- (NSMutableDictionary *) metadata {
6932575e 2356 return metadata_;
f159ecd4
JF
2357}
2358
e057ec05 2359- (NSDate *) seen {
43b742af
JF
2360 if (subscribed_ && lastSeen_ != nil)
2361 return lastSeen_;
2362 return firstSeen_;
2d28b35a
JF
2363}
2364
f159ecd4 2365- (BOOL) subscribed {
43b742af 2366 return subscribed_;
f159ecd4
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
e057ec05
JF
2377- (NSString *) latest {
2378 return latest_;
b6ffa083
JF
2379}
2380
e057ec05
JF
2381- (NSString *) installed {
2382 return installed_;
2d28b35a
JF
2383}
2384
b4c4fac4
JF
2385- (BOOL) uninstalled {
2386 return installed_.empty();
2387}
2388
965edd52
JF
2389- (BOOL) valid {
2390 return !version_.end();
2391}
2392
238b07ce 2393- (BOOL) upgradableAndEssential:(BOOL)essential {
43b742af
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
e057ec05 2401}
2d28b35a 2402
e057ec05 2403- (BOOL) essential {
a70cf746 2404 return essential_;
2d28b35a
JF
2405}
2406
e057ec05 2407- (BOOL) broken {
3319715b
JF
2408 return [database_ cache][iterator_].InstBroken();
2409}
2410
853d14d3 2411- (BOOL) unfiltered {
43b742af 2412 NSString *section([self section]);
37455cf8 2413 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
853d14d3
JF
2414}
2415
2416- (BOOL) visible {
43b742af 2417 return visible_;
fa7bb92f
JF
2418}
2419
3319715b 2420- (BOOL) half {
43b742af 2421 unsigned char current(iterator_->CurrentState);
3319715b
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)
6932575e 2444 return @"PURGE";
3319715b 2445 else
6932575e 2446 return @"REMOVE";
3319715b 2447 case pkgDepCache::ModeKeep:
3ff1504e 2448 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
6932575e 2449 return @"REINSTALL";
3ff1504e
JF
2450 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2451 return nil;*/
3319715b
JF
2452 else
2453 return nil;
3319715b 2454 case pkgDepCache::ModeInstall:
3ff1504e 2455 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
6932575e 2456 return @"REINSTALL";
3ff1504e 2457 else*/ switch (state.Status) {
3319715b 2458 case -1:
6932575e 2459 return @"DOWNGRADE";
3319715b 2460 case 0:
6932575e 2461 return @"INSTALL";
3319715b 2462 case 1:
6932575e 2463 return @"UPGRADE";
3319715b 2464 case 2:
6932575e 2465 return @"NEW_INSTALL";
6981ccdf 2466 _nodefault
3319715b 2467 }
6981ccdf 2468 _nodefault
3319715b 2469 }
b6ffa083
JF
2470}
2471
e057ec05
JF
2472- (NSString *) id {
2473 return id_;
b6ffa083
JF
2474}
2475
e057ec05 2476- (NSString *) name {
9ee296df 2477 return name_.empty() ? id_ : name_;
e057ec05 2478}
b6ffa083 2479
dbe0f181 2480- (UIImage *) icon {
6b4b3bee 2481 NSString *section = [self simpleSection];
dbe0f181
JF
2482
2483 UIImage *icon(nil);
dd9390c5 2484 if (!icon_.empty())
cbc40330 2485 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
69a8c80e 2486 // XXX: correct escaping
cbc40330 2487 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
dbe0f181
JF
2488 if (icon == nil) if (section != nil)
2489 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
6e673d99
JF
2490 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2491 if ([dicon hasPrefix:@"file:///"])
69a8c80e 2492 // XXX: correct escaping
6e673d99 2493 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
dbe0f181
JF
2494 if (icon == nil)
2495 icon = [UIImage applicationImageNamed:@"unknown.png"];
2496 return icon;
e057ec05 2497}
b6ffa083 2498
ad554f10 2499- (NSString *) homepage {
ff47b800 2500 return homepage_;
b6ffa083
JF
2501}
2502
0235116c 2503- (NSString *) depiction {
9050015e 2504 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
0235116c
JF
2505}
2506
81ab76dc 2507- (Address *) sponsor {
6932575e
JF
2508 if (sponsor$_ == nil) {
2509 if (sponsor_.empty())
2510 return nil;
2511 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2512 } return sponsor$_;
81ab76dc
JF
2513}
2514
d72d91aa 2515- (Address *) author {
6932575e
JF
2516 if (author$_ == nil) {
2517 if (author_.empty())
2518 return nil;
2519 author$_ = [[Address addressWithString:author_] retain];
2520 } return author$_;
d72d91aa
JF
2521}
2522
3ff1504e 2523- (NSString *) support {
419a9efd 2524 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
3ff1504e
JF
2525}
2526
f464053e 2527- (NSArray *) files {
9ee296df 2528 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
f464053e
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
2a987aa5
JF
2543- (NSArray *) relationships {
2544 return relationships_;
2545}
2546
f464053e
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:
61b13cae 2553 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
f464053e
JF
2554 else for (size_t i(0); i != length; ++i)
2555 if (
8944281a
JF
2556 /* XXX: technically this is not allowed */
2557 (name[i] < 'A' || name[i] > 'Z') &&
f464053e
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;
419a9efd 2565 bool user = false;
8944281a 2566 bool _private = false;
f464053e
JF
2567 bool stash = false;
2568
8944281a
JF
2569 bool repository = [[self section] isEqualToString:@"Repositories"];
2570
f464053e
JF
2571 if (NSArray *files = [self files])
2572 for (NSString *file in files)
2573 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2574 cydia = true;
419a9efd
JF
2575 else if (!user && [file isEqualToString:@"/User"])
2576 user = true;
8944281a
JF
2577 else if (!_private && [file isEqualToString:@"/private"])
2578 _private = true;
f464053e
JF
2579 else if (!stash && [file isEqualToString:@"/var/stash"])
2580 stash = true;
2581
8944281a
JF
2582 /* XXX: this is not sensitive enough. only some folders are valid. */
2583 if (cydia && !repository)
61b13cae 2584 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
419a9efd
JF
2585 if (user)
2586 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
8944281a 2587 if (_private)
61b13cae 2588 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
f464053e 2589 if (stash)
61b13cae 2590 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
f464053e
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
e057ec05 2631- (Source *) source {
3d37fc0d 2632 if (!cached_) {
a70cf746
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 }
3d37fc0d
JF
2644 }
2645
e057ec05 2646 return source_;
b6ffa083
JF
2647}
2648
faf4eb4f
JF
2649- (NSString *) role {
2650 return role_;
2651}
2652
e057ec05
JF
2653- (BOOL) matches:(NSString *)text {
2654 if (text == nil)
2655 return NO;
b6ffa083 2656
e057ec05 2657 NSRange range;
b6ffa083 2658
3bddda52 2659 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
e057ec05
JF
2660 if (range.location != NSNotFound)
2661 return YES;
b6ffa083 2662
3bddda52 2663 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
e057ec05
JF
2664 if (range.location != NSNotFound)
2665 return YES;
b6ffa083 2666
5ec44e34 2667 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
e057ec05 2668 if (range.location != NSNotFound)
5ec44e34 2669 return YES;
b6ffa083 2670
e057ec05
JF
2671 return NO;
2672}
b6ffa083 2673
faf4eb4f
JF
2674- (bool) hasSupportingRole {
2675 if (role_ == nil)
fa7bb92f 2676 return true;
faf4eb4f
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);
fa7bb92f
JF
2690}
2691
2692- (BOOL) hasTag:(NSString *)tag {
2693 return tags_ == nil ? NO : [tags_ containsObject:tag];
2694}
2695
cb9c2100
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
dbe0f181
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
d8d9a65c
JF
2711- (bool) isCommercial {
2712 return [self hasTag:@"cydia::commercial"];
2713}
2714
dd9390c5
JF
2715- (CYString &) cyname {
2716 return name_.empty() ? id_ : name_;
6932575e
JF
2717}
2718
6932575e
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;
e057ec05 2724 }
2d28b35a 2725
6932575e 2726 return _not(uint32_t);
e057ec05 2727}
2d28b35a 2728
f159ecd4
JF
2729- (uint32_t) compareForChanges {
2730 union {
2731 uint32_t key;
2d28b35a 2732
f159ecd4
JF
2733 struct {
2734 uint32_t timestamp : 30;
2735 uint32_t ignored : 1;
2736 uint32_t upgradable : 1;
2737 } bits;
2738 } value;
2d28b35a 2739
5c87d61b
JF
2740 bool upgradable([self upgradableAndEssential:YES]);
2741 value.bits.upgradable = upgradable ? 1 : 0;
b6ffa083 2742
5c87d61b 2743 if (upgradable) {
f159ecd4
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;
e057ec05 2751 }
b6ffa083 2752
f159ecd4 2753 return _not(uint32_t) - value.key;
e057ec05 2754}
b6ffa083 2755
3ff1504e
JF
2756- (void) clear {
2757 pkgProblemResolver *resolver = [database_ resolver];
2758 resolver->Clear(iterator_);
2759 resolver->Protect(iterator_);
2760}
2761
e057ec05
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}
0f25fa58 2772
e057ec05
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}
b6ffa083 2780
7cf54836 2781- (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3bddda52
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
7cf54836 2793 return value;
3bddda52 2794 _end
e057ec05 2795}
b6ffa083 2796
5ec44e34 2797- (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
37455cf8
JF
2798 if ([search length] == 0)
2799 return false;
2800
5ec44e34
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
7cf54836 2816- (bool) isInstalledAndVisible:(NSNumber *)number {
b4c4fac4 2817 return (![number boolValue] || [self visible]) && ![self uninstalled];
e057ec05 2818}
b6ffa083 2819
6981ccdf 2820- (bool) isVisibleInSection:(NSString *)name {
965edd52
JF
2821 NSString *section = [self section];
2822
7cf54836 2823 return
6981ccdf 2824 [self visible] && (
faf4eb4f
JF
2825 name == nil ||
2826 section == nil && [name length] == 0 ||
2827 [name isEqualToString:section]
7cf54836 2828 );
faf4eb4f
JF
2829}
2830
7cf54836
JF
2831- (bool) isVisibleInSource:(Source *)source {
2832 return [self source] == source && [self visible];
e057ec05 2833}
b6ffa083 2834
e057ec05
JF
2835@end
2836/* }}} */
2837/* Section Class {{{ */
2838@interface Section : NSObject {
2839 NSString *name_;
3bddda52 2840 unichar index_;
e057ec05
JF
2841 size_t row_;
2842 size_t count_;
6932575e 2843 NSString *localized_;
e057ec05 2844}
2d28b35a 2845
43b742af 2846- (NSComparisonResult) compareByLocalized:(Section *)section;
9ee296df
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;
3bddda52 2850- (Section *) initWithIndex:(unichar)index row:(size_t)row;
e057ec05 2851- (NSString *) name;
3bddda52 2852- (unichar) index;
6932575e 2853
e057ec05
JF
2854- (size_t) row;
2855- (size_t) count;
6932575e
JF
2856
2857- (void) addToRow;
e057ec05 2858- (void) addToCount;
a933cee2 2859
6932575e 2860- (void) setCount:(size_t)count;
43b742af 2861- (NSString *) localized;
6932575e 2862
e057ec05 2863@end
a933cee2 2864
e057ec05 2865@implementation Section
a933cee2 2866
e057ec05
JF
2867- (void) dealloc {
2868 [name_ release];
6932575e
JF
2869 if (localized_ != nil)
2870 [localized_ release];
e057ec05
JF
2871 [super dealloc];
2872}
a933cee2 2873
43b742af 2874- (NSComparisonResult) compareByLocalized:(Section *)section {
9ee296df
JF
2875 NSString *lhs(localized_);
2876 NSString *rhs([section localized]);
fa7bb92f 2877
9ee296df 2878 /*if ([lhs length] != 0 && [rhs length] != 0) {
fa7bb92f
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;
9ee296df 2886 }*/
fa7bb92f 2887
9c4e0cbe 2888 return [lhs compare:rhs options:LaxCompareOptions_];
fa7bb92f
JF
2889}
2890
9ee296df
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];
fa7bb92f
JF
2900}
2901
9ee296df 2902- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
e057ec05
JF
2903 if ((self = [super init]) != nil) {
2904 name_ = [name retain];
3bddda52
JF
2905 index_ = '\0';
2906 row_ = row;
9ee296df
JF
2907 if (localize)
2908 localized_ = [LocalizeSection(name_) retain];
3bddda52
JF
2909 } return self;
2910}
2911
6932575e 2912/* XXX: localize the index thingees */
3bddda52
JF
2913- (Section *) initWithIndex:(unichar)index row:(size_t)row {
2914 if ((self = [super init]) != nil) {
5d8f1006 2915 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3bddda52 2916 index_ = index;
e057ec05 2917 row_ = row;
a933cee2
JF
2918 } return self;
2919}
2920
e057ec05
JF
2921- (NSString *) name {
2922 return name_;
2923}
2924
3bddda52
JF
2925- (unichar) index {
2926 return index_;
2927}
2928
e057ec05
JF
2929- (size_t) row {
2930 return row_;
2931}
2932
2933- (size_t) count {
2934 return count_;
2935}
2936
6932575e
JF
2937- (void) addToRow {
2938 ++row_;
2939}
2940
e057ec05
JF
2941- (void) addToCount {
2942 ++count_;
2943}
2944
6932575e
JF
2945- (void) setCount:(size_t)count {
2946 count_ = count;
2947}
2948
2949- (NSString *) localized {
2950 return localized_;
2951}
2952
a933cee2
JF
2953@end
2954/* }}} */
2955
6981ccdf
JF
2956static NSString *Colon_;
2957static NSString *Error_;
2958static NSString *Warning_;
2959
e057ec05
JF
2960/* Database Implementation {{{ */
2961@implementation Database
1cb11c5f 2962
dbe0f181
JF
2963+ (Database *) sharedInstance {
2964 static Database *instance;
2965 if (instance == nil)
2966 instance = [[Database alloc] init];
2967 return instance;
2968}
2969
a70cf746
JF
2970- (unsigned) era {
2971 return era_;
2972}
2973
e057ec05
JF
2974- (void) dealloc {
2975 _assert(false);
6932575e
JF
2976 NSRecycleZone(zone_);
2977 // XXX: malloc_destroy_zone(zone_);
2978 apr_pool_destroy(pool_);
e057ec05
JF
2979 [super dealloc];
2980}
1cb11c5f 2981
f464053e 2982- (void) _readCydia:(NSNumber *)fd { _pooled
d72d91aa
JF
2983 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2984 std::istream is(&ib);
2985 std::string line;
2986
03d01f0e
JF
2987 static Pcre finish_r("^finish:([^:]*)$");
2988
d72d91aa
JF
2989 while (std::getline(is, line)) {
2990 const char *data(line.c_str());
03d01f0e 2991 size_t size = line.size();
cb9c2100 2992 lprintf("C:%s\n", data);
03d01f0e
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 }
d72d91aa
JF
3000 }
3001
6981ccdf 3002 _assume(false);
d72d91aa
JF
3003}
3004
f464053e 3005- (void) _readStatus:(NSNumber *)fd { _pooled
e057ec05
JF
3006 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3007 std::istream is(&ib);
3008 std::string line;
1cb11c5f 3009
faf4eb4f
JF
3010 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3011 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
1cb11c5f 3012
e057ec05
JF
3013 while (std::getline(is, line)) {
3014 const char *data(line.c_str());
6981ccdf 3015 size_t size(line.size());
cb9c2100 3016 lprintf("S:%s\n", data);
1cb11c5f 3017
965edd52
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)];
e057ec05 3022 [delegate_ setProgressTitle:string];
965edd52 3023 } else if (pmstatus_r(data, size)) {
238b07ce
JF
3024 std::string type([pmstatus_r[1] UTF8String]);
3025 NSString *id = pmstatus_r[2];
3026
965edd52
JF
3027 float percent([pmstatus_r[3] floatValue]);
3028 [delegate_ setProgressPercent:(percent / 100)];
3029
3030 NSString *string = pmstatus_r[4];
965edd52
JF
3031
3032 if (type == "pmerror")
6981ccdf 3033 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
238b07ce
JF
3034 withObject:[NSArray arrayWithObjects:string, id, nil]
3035 waitUntilDone:YES
3036 ];
907a35d6 3037 else if (type == "pmstatus") {
965edd52 3038 [delegate_ setProgressTitle:string];
907a35d6 3039 } else if (type == "pmconffile")
965edd52 3040 [delegate_ setConfigurationData:string];
6981ccdf
JF
3041 else
3042 lprintf("E:unknown pmstatus\n");
3043 } else
3044 lprintf("E:unknown status\n");
e057ec05 3045 }
1cb11c5f 3046
6981ccdf 3047 _assume(false);
e057ec05 3048}
1cb11c5f 3049
f464053e 3050- (void) _readOutput:(NSNumber *)fd { _pooled
e057ec05
JF
3051 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3052 std::istream is(&ib);
3053 std::string line;
3054
965edd52 3055 while (std::getline(is, line)) {
cb9c2100 3056 lprintf("O:%s\n", line.c_str());
2a987aa5 3057 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
965edd52 3058 }
e057ec05 3059
6981ccdf 3060 _assume(false);
1cb11c5f
JF
3061}
3062
7600bd69
JF
3063- (FILE *) input {
3064 return input_;
3065}
3066
e057ec05 3067- (Package *) packageWithName:(NSString *)name {
ca06bb0e 3068@synchronized ([Database class]) {
965edd52
JF
3069 if (static_cast<pkgDepCache *>(cache_) == NULL)
3070 return nil;
e057ec05 3071 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
6932575e 3072 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
ca06bb0e 3073} }
e057ec05 3074
9b62701b 3075- (id) init {
1cb11c5f 3076 if ((self = [super init]) != nil) {
965edd52 3077 policy_ = NULL;
e057ec05
JF
3078 records_ = NULL;
3079 resolver_ = NULL;
3080 fetcher_ = NULL;
3081 lock_ = NULL;
1cb11c5f 3082
6932575e
JF
3083 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3084 apr_pool_create(&pool_, NULL);
3085
9ee296df 3086 packages_ = [[NSMutableArray alloc] init];
1cb11c5f 3087
e057ec05 3088 int fds[2];
1cb11c5f 3089
d72d91aa
JF
3090 _assert(pipe(fds) != -1);
3091 cydiafd_ = fds[1];
3092
3093 _config->Set("APT::Keep-Fds::", cydiafd_);
03d01f0e 3094 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
d72d91aa
JF
3095
3096 [NSThread
3097 detachNewThreadSelector:@selector(_readCydia:)
3098 toTarget:self
3099 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3100 ];
3101
e057ec05
JF
3102 _assert(pipe(fds) != -1);
3103 statusfd_ = fds[1];
1cb11c5f 3104
e057ec05
JF
3105 [NSThread
3106 detachNewThreadSelector:@selector(_readStatus:)
3107 toTarget:self
3108 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3109 ];
1cb11c5f 3110
7600bd69
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
e057ec05
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 ];
1cb11c5f
JF
3126 } return self;
3127}
3128
e057ec05
JF
3129- (pkgCacheFile &) cache {
3130 return cache_;
1cb11c5f
JF
3131}
3132
965edd52
JF
3133- (pkgDepCache::Policy *) policy {
3134 return policy_;
3135}
3136
e057ec05
JF
3137- (pkgRecords *) records {
3138 return records_;
1cb11c5f
JF
3139}
3140
e057ec05
JF
3141- (pkgProblemResolver *) resolver {
3142 return resolver_;
1cb11c5f
JF
3143}
3144
e057ec05
JF
3145- (pkgAcquire &) fetcher {
3146 return *fetcher_;
1cb11c5f
JF
3147}
3148
ce09fc27
JF
3149- (pkgSourceList &) list {
3150 return *list_;
3151}
3152
e057ec05
JF
3153- (NSArray *) packages {
3154 return packages_;
1cb11c5f
JF
3155}
3156
faf4eb4f 3157- (NSArray *) sources {
631a0a1e
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;
faf4eb4f
JF
3162}
3163
f464053e
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
e4765783
JF
3197 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3198 if (Package *package = [self packageWithName:name])
3199 name = [package name];
3200 [failure addObject:name];
f464053e
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
6981ccdf
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
281f523c 3252 if (fatal && !message.empty())
6981ccdf
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
7398a389 3262- (void) reloadData { _pooled
ca06bb0e 3263@synchronized ([Database class]) {
a70cf746
JF
3264 @synchronized (self) {
3265 ++era_;
3266 }
3267
98fb9119
JF
3268 [packages_ removeAllObjects];
3269 sources_.clear();
3270
e057ec05 3271 _error->Discard();
965edd52 3272
e057ec05 3273 delete list_;
965edd52 3274 list_ = NULL;
e057ec05
JF
3275 manager_ = NULL;
3276 delete lock_;
965edd52 3277 lock_ = NULL;
e057ec05 3278 delete fetcher_;
965edd52 3279 fetcher_ = NULL;
e057ec05 3280 delete resolver_;
965edd52 3281 resolver_ = NULL;
e057ec05 3282 delete records_;
965edd52
JF
3283 records_ = NULL;
3284 delete policy_;
3285 policy_ = NULL;
e057ec05 3286
98fb9119
JF
3287 if (now_ != nil) {
3288 [now_ release];
3289 now_ = nil;
3290 }
3291
965edd52 3292 cache_.Close();
7600bd69 3293
6932575e
JF
3294 apr_pool_clear(pool_);
3295 NSRecycleZone(zone_);
3296
3e3977a2
JF
3297 int chk(creat("/tmp/cydia.chk", 0644));
3298 if (chk != -1)
3299 close(chk);
3300
6981ccdf
JF
3301 NSString *title(UCLocalize("DATABASE"));
3302
907a35d6 3303 _trace();
6981ccdf 3304 if (!cache_.Open(progress_, true)) { pop:
7600bd69 3305 std::string error;
6981ccdf 3306 bool warning(!_error->PopMessage(error));
cb9c2100 3307 lprintf("cache_.Open():[%s]\n", error.c_str());
965edd52
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)];
fc19e583
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.")
6981ccdf
JF
3316 else
3317 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
965edd52 3318
6981ccdf
JF
3319 if (warning)
3320 goto pop;
3321 _error->Discard();
965edd52 3322 return;
e057ec05 3323 }
907a35d6 3324 _trace();
e057ec05 3325
3e3977a2
JF
3326 unlink("/tmp/cydia.chk");
3327
e057ec05
JF
3328 now_ = [[NSDate date] retain];
3329
965edd52 3330 policy_ = new pkgDepCache::Policy();
e057ec05
JF
3331 records_ = new pkgRecords(cache_);
3332 resolver_ = new pkgProblemResolver(cache_);
3333 fetcher_ = new pkgAcquire(&status_);
3334 lock_ = NULL;
3335
3336 list_ = new pkgSourceList();
6981ccdf
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 }
e057ec05 3344
6981ccdf
JF
3345 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3346 return;
3319715b
JF
3347
3348 if (cache_->BrokenCount() != 0) {
6981ccdf
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;
3319715b
JF
3359 }
3360
3e3977a2 3361 _trace();
631a0a1e 3362
631a0a1e
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())
b8b1cfd0 3370 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
631a0a1e 3371 }
e057ec05 3372 }
631a0a1e 3373
3e3977a2 3374 _trace();
e057ec05 3375
43b742af 3376 {
9ee296df 3377 /*std::vector<Package *> packages;
43b742af 3378 packages.reserve(std::max(10000U, [packages_ count] + 1000));
43b742af 3379 [packages_ release];
9ee296df
JF
3380 packages_ = nil;*/
3381
43b742af
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])
9ee296df
JF
3386 //packages.push_back(package);
3387 [packages_ addObject:package];
43b742af
JF
3388
3389 _trace();
3390
9ee296df 3391 /*if (packages.empty())
43b742af
JF
3392 packages_ = [[NSArray alloc] init];
3393 else
3394 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
9ee296df
JF
3395 _trace();*/
3396
dd9390c5
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)];
9ee296df
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
66abcbb0
JF
3411 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3412
dd9390c5 3413 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
9ee296df
JF
3414
3415 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
43b742af
JF
3416
3417 _trace();
3418 }
ca06bb0e 3419} }
1cb11c5f 3420
965edd52
JF
3421- (void) configure {
3422 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3423 system([dpkg UTF8String]);
3424}
3425
6981ccdf
JF
3426- (bool) clean {
3427 // XXX: I don't remember this condition
d72d91aa 3428 if (lock_ != NULL)
6981ccdf 3429 return false;
d72d91aa
JF
3430
3431 FileFd Lock;
3432 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
6981ccdf
JF
3433
3434 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3435
3436 if ([self popErrorWithTitle:title])
3437 return false;
d72d91aa
JF
3438
3439 pkgAcquire fetcher;
3440 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3441
3319715b
JF
3442 class LogCleaner :
3443 public pkgArchiveCleaner
3444 {
d72d91aa
JF
3445 protected:
3446 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3319715b 3447 unlink(File);
d72d91aa
JF
3448 }
3449 } cleaner;
3450
6981ccdf
JF
3451 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3452 return false;
3453
3454 return true;
d72d91aa
JF
3455}
3456
6981ccdf 3457- (bool) prepare {
e4765783
JF
3458 fetcher_->Shutdown();
3459
e057ec05
JF
3460 pkgRecords records(cache_);
3461
3462 lock_ = new FileFd();
3463 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
6981ccdf
JF
3464
3465 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3466
3467 if ([self popErrorWithTitle:title])
3468 return false;
e057ec05
JF
3469
3470 pkgSourceList list;
6981ccdf
JF
3471 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3472 return false;
e057ec05
JF
3473
3474 manager_ = (_system->CreatePM(cache_));
6981ccdf
JF
3475 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3476 return false;
3477
3478 return true;
1cb11c5f
JF
3479}
3480
e057ec05 3481- (void) perform {
6981ccdf
JF
3482 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3483
113c9b62
JF
3484 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3485 pkgSourceList list;
6981ccdf
JF
3486 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3487 return;
113c9b62
JF
3488 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3489 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3490 }
8993ad57 3491
2d7f7dea
JF
3492 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3493 _trace();
e057ec05 3494 return;
2d7f7dea
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;
9050015e
JF
3501 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3502 continue;
2d7f7dea
JF
3503
3504 std::string uri = (*item)->DescURI();
3505 std::string error = (*item)->ErrorText;
3506
cb9c2100 3507 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
2d7f7dea
JF
3508 failed = true;
3509
6981ccdf 3510 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
ce09fc27
JF
3511 withObject:[NSArray arrayWithObjects:
3512 [NSString stringWithUTF8String:error.c_str()],
3513 nil]
2d7f7dea
JF
3514 waitUntilDone:YES
3515 ];
3516 }
3517
3518 if (failed) {
3519 _trace();
3520 return;
3521 }
e057ec05
JF
3522
3523 _system->UnLock();
3524 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3525
2d7f7dea
JF
3526 if (_error->PendingError()) {
3527 _trace();
e057ec05 3528 return;
2d7f7dea
JF
3529 }
3530
3531 if (result == pkgPackageManager::Failed) {
3532 _trace();
e057ec05 3533 return;
2d7f7dea
JF
3534 }
3535
3536 if (result != pkgPackageManager::Completed) {
3537 _trace();
e057ec05 3538 return;
2d7f7dea 3539 }
8993ad57 3540
113c9b62
JF
3541 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3542 pkgSourceList list;
6981ccdf
JF
3543 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3544 return;
113c9b62
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];
1cb11c5f
JF
3551}
3552
6981ccdf
JF
3553- (bool) upgrade {
3554 NSString *title(UCLocalize("UPGRADE"));
3555 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3556 return false;
3557 return true;
1951a333
JF
3558}
3559
e057ec05
JF
3560- (void) update {
3561 [self updateWithStatus:status_];
3562}
686e302f 3563
419a9efd
JF
3564- (void) setVisible {
3565 for (Package *package in packages_)
3566 [package setVisible];
3567}
3568
6981ccdf
JF
3569- (void) updateWithStatus:(Status &)status {
3570 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3571 NSString *title(UCLocalize("REFRESHING_DATA"));
3572
e057ec05 3573 pkgSourceList list;
6981ccdf
JF
3574 if (!list.ReadMainList())
3575 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
686e302f 3576
e057ec05
JF
3577 FileFd lock;
3578 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
6981ccdf
JF
3579 if ([self popErrorWithTitle:title])
3580 return;
f30eaf83 3581
6981ccdf 3582 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
9b62701b
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;
e057ec05 3585
419a9efd
JF
3586 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3587 Changed_ = true;
686e302f
JF
3588}
3589
e057ec05
JF
3590- (void) setDelegate:(id)delegate {
3591 delegate_ = delegate;
3592 status_.setDelegate(delegate);
3593 progress_.setDelegate(delegate);
3594}
686e302f 3595
3e3977a2 3596- (Source *) getSource:(pkgCache::PkgFileIterator)file {
1636cf29
JF
3597 SourceMap::const_iterator i(sources_.find(file->ID));
3598 return i == sources_.end() ? nil : i->second;
a933cee2
JF
3599}
3600
e057ec05
JF
3601@end
3602/* }}} */
686e302f 3603
f441e717 3604/* Confirmation Controller {{{ */
61b13cae
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;
cb9c2100 3618}
9ae52960 3619/* }}} */
cb9c2100 3620
61b13cae
JF
3621/* Web Scripting {{{ */
3622@interface CydiaObject : NSObject {
3623 id indirect_;
daf7f6e2 3624 id delegate_;
61b13cae 3625}
cb9c2100 3626
61b13cae 3627- (id) initWithDelegate:(IndirectDelegate *)indirect;
cb9c2100
JF
3628@end
3629
61b13cae 3630@implementation CydiaObject
cb9c2100
JF
3631
3632- (void) dealloc {
61b13cae 3633 [indirect_ release];
cb9c2100
JF
3634 [super dealloc];
3635}
3636
61b13cae
JF
3637- (id) initWithDelegate:(IndirectDelegate *)indirect {
3638 if ((self = [super init]) != nil) {
3639 indirect_ = [indirect retain];
3640 } return self;
3641}
3642
daf7f6e2
JF
3643- (void) setDelegate:(id)delegate {
3644 delegate_ = delegate;
3645}
3646
61b13cae
JF
3647+ (NSArray *) _attributeKeys {
3648 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3649}
3650
3651- (NSArray *) attributeKeys {
3652 return [[self class] _attributeKeys];
cb9c2100
JF
3653}
3654
61b13cae
JF
3655+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3656 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
cb9c2100 3657}
61b13cae
JF
3658
3659- (NSString *) device {
3660 return [[UIDevice currentDevice] uniqueIdentifier];
cb9c2100
JF
3661}
3662
61b13cae
JF
3663#if 0 // XXX: implement!
3664- (NSString *) mac {
3665 if (![indirect_ promptForSensitive:@"Mac Address"])
3666 return nil;
f464053e
JF
3667}
3668
61b13cae
JF
3669- (NSString *) serial {
3670 if (![indirect_ promptForSensitive:@"Serial #"])
3671 return nil;
3672}
56e10908 3673
61b13cae
JF
3674- (NSString *) firewire {
3675 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3676 return nil;
f464053e
JF
3677}
3678
61b13cae
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";
22b21e43
JF
3688 else if (selector == @selector(getInstalledPackages))
3689 return @"getInstalledPackages";
61b13cae
JF
3690 else if (selector == @selector(getPackageById:))
3691 return @"getPackageById";
daf7f6e2
JF
3692 else if (selector == @selector(installPackages:))
3693 return @"installPackages";
61b13cae
JF
3694 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3695 return @"setButtonImage";
3696 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3697 return @"setButtonTitle";
61b13cae
JF
3698 else if (selector == @selector(setPopupHook:))
3699 return @"setPopupHook";
3700 else if (selector == @selector(setSpecial:))
3701 return @"setSpecial";
37455cf8
JF
3702 else if (selector == @selector(setToken:))
3703 return @"setToken";
61b13cae
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";
cb9c2100 3716 else
61b13cae
JF
3717 return nil;
3718}
3719
3720+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3721 return [self webScriptNameForSelector:selector] == nil;
cb9c2100
JF
3722}
3723
61b13cae
JF
3724- (BOOL) supports:(NSString *)feature {
3725 return [feature isEqualToString:@"window.open"];
3726}
cb9c2100 3727
22b21e43
JF
3728- (NSArray *) getInstalledPackages {
3729 NSArray *packages([[Database sharedInstance] packages]);
3730 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
daf7f6e2 3731 for (Package *package in packages)
22b21e43
JF
3732 if ([package installed] != nil)
3733 [installed addObject:package];
3734 return installed;
3735}
3736
61b13cae 3737- (Package *) getPackageById:(NSString *)id {
e32f0fcb
JF
3738 Package *package([[Database sharedInstance] packageWithName:id]);
3739 [package parse];
3740 return package;
61b13cae
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
daf7f6e2
JF
3804- (void) installPackages:(NSArray *)packages {
3805 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3806}
3807
61b13cae
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
37455cf8
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
61b13cae
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];
9b62701b 3843 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
61b13cae
JF
3844}
3845
3846- (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
e1316e10
JF
3847 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3848 value = nil;
61b13cae
JF
3849 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3850 table = nil;
3851 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
cb9c2100
JF
3852}
3853
3854@end
3855/* }}} */
6932575e 3856
7d6ecbef 3857/* Cydia Browser Controller {{{ */
ed349d9a 3858@interface CYBrowserController : BrowserController {
61b13cae
JF
3859 CydiaObject *cydia_;
3860}
e00439f7 3861
61b13cae
JF
3862@end
3863
9ae52960 3864@implementation CYBrowserController
61b13cae
JF
3865
3866- (void) dealloc {
3867 [cydia_ release];
3868 [super dealloc];
3869}
3870
5ec44e34
JF
3871- (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3872}
3873
c2292b80
JF
3874- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3875 [super webView:view didClearWindowObject:window forFrame:frame];
5ec44e34
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
daf7f6e2
JF
3892 if (
3893 [host isEqualToString:@"cydia.saurik.com"] ||
3894 [host hasSuffix:@".cydia.saurik.com"] ||
3895 [scheme isEqualToString:@"file"]
3896 )
37455cf8 3897 [window setValue:cydia_ forKey:@"cydia"];
61b13cae
JF
3898}
3899
017b2b71
JF
3900- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3901 if (System_ != NULL)
3902 [request setValue:System_ forHTTPHeaderField:@"X-System"];
61b13cae 3903 if (Machine_ != NULL)
017b2b71 3904 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5ec44e34
JF
3905 if (Token_ != nil)
3906 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
61b13cae 3907 if (Role_ != nil)
017b2b71
JF
3908 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3909}
61b13cae 3910
c2292b80
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]);
017b2b71 3913 [self _setMoreHeaders:copy];
61b13cae 3914 return copy;
e00439f7
JF
3915}
3916
daf7f6e2
JF
3917- (void) setDelegate:(id)delegate {
3918 [super setDelegate:delegate];
3919 [cydia_ setDelegate:delegate];
3920}
3921
9ae52960 3922- (id) init {
2938b930 3923 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
61b13cae
JF
3924 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3925
c2292b80 3926 WebView *webview([[webview_ _documentView] webView]);
61b13cae
JF
3927
3928 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
0a523b5a 3929
61b13cae
JF
3930 NSString *application = package == nil ? @"Cydia" : [NSString
3931 stringWithFormat:@"Cydia/%@",
3932 [package installed]
3933 ];
3934
61b13cae 3935 if (Safari_ != nil)
f26c1a7f 3936 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
0a523b5a 3937 if (Build_ != nil)
f26c1a7f 3938 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
0a523b5a 3939 if (Product_ != nil)
f26c1a7f 3940 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
61b13cae
JF
3941
3942 [webview setApplicationNameForUserAgent:application];
3943 } return self;
3944}
3945
3946@end
7d6ecbef 3947/* }}} */
61b13cae 3948
7d6ecbef 3949/* Confirmation {{{ */
f441e717 3950@protocol ConfirmationControllerDelegate
1ca35d78 3951- (void) cancelAndClear:(bool)clear;
9ae52960 3952- (void) confirmWithNavigationController:(UINavigationController *)navigation;
3ff1504e 3953- (void) queue;
e057ec05 3954@end
4941f41d 3955
f441e717 3956@interface ConfirmationController : CYBrowserController {
dbe0f181 3957 _transient Database *database_;
9c421310 3958 UIAlertView *essential_;
f464053e
JF
3959 NSArray *changes_;
3960 NSArray *issues_;
3961 NSArray *sizes_;
e00439f7 3962 BOOL substrate_;
e057ec05 3963}
a75f53e7 3964
9ae52960 3965- (id) initWithDatabase:(Database *)database;
686e302f 3966
a75f53e7
JF
3967@end
3968
f441e717 3969@implementation ConfirmationController
a75f53e7 3970
4941f41d 3971- (void) dealloc {
f464053e
JF
3972 [changes_ release];
3973 if (issues_ != nil)
3974 [issues_ release];
3975 [sizes_ release];
e057ec05
JF
3976 if (essential_ != nil)
3977 [essential_ release];
4941f41d
JF
3978 [super dealloc];
3979}
3980
9ae52960 3981- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9c421310 3982 NSString *context([alert context]);
3319715b 3983
a5dd312c 3984 if ([context isEqualToString:@"remove"]) {
9ae52960
GP
3985 if (button == [alert cancelButtonIndex]) {
3986 [self dismissModalViewControllerAnimated:YES];
9c421310 3987 } else if (button == [alert firstOtherButtonIndex]) {
9ae52960
GP
3988 if (substrate_)
3989 Finish_ = 2;
3990 [delegate_ confirmWithNavigationController:[self navigationController]];
3319715b 3991 }
3319715b 3992
9c421310 3993 [alert dismissWithClickedButtonIndex:-1 animated:YES];
a5dd312c 3994 } else if ([context isEqualToString:@"unable"]) {
9ae52960 3995 [self dismissModalViewControllerAnimated:YES];
9c421310
GP
3996 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3997 } else {
9ae52960
GP
3998 [super alertView:alert clickedButtonAtIndex:button];
3999 }
e057ec05
JF
4000}
4001
fa2cd4b3 4002- (void) _doContinue {
2064d251
GP
4003 [self dismissModalViewControllerAnimated:YES];
4004 [delegate_ cancelAndClear:NO];
fa2cd4b3 4005}
f99f86e2 4006
fa2cd4b3
JF
4007- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4008 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
2064d251
GP
4009 return nil;
4010}
4011
c2292b80
JF
4012- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4013 [super webView:view didClearWindowObject:window forFrame:frame];
f464053e
JF
4014 [window setValue:changes_ forKey:@"changes"];
4015 [window setValue:issues_ forKey:@"issues"];
4016 [window setValue:sizes_ forKey:@"sizes"];
2064d251 4017 [window setValue:self forKey:@"queue"];
e057ec05
JF
4018}
4019
9ae52960
GP
4020- (id) initWithDatabase:(Database *)database {
4021 if ((self = [super init]) != nil) {
dbe0f181
JF
4022 database_ = database;
4023
9ae52960
GP
4024 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4025
e057ec05
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];
a75f53e7 4031
e057ec05 4032 bool remove(false);
a75f53e7 4033
e00439f7
JF
4034 pkgDepCache::Policy *policy([database_ policy]);
4035
e057ec05 4036 pkgCacheFile &cache([database_ cache]);
2a987aa5 4037 NSArray *packages = [database_ packages];
9fdd37d0 4038 for (Package *package in packages) {
2a987aa5 4039 pkgCache::PkgIterator iterator = [package iterator];
e057ec05 4040 pkgDepCache::StateCache &state(cache[iterator]);
a75f53e7 4041
2a987aa5
JF
4042 NSString *name([package name]);
4043
e057ec05
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()) {
2a987aa5 4053 if ([package essential])
e057ec05
JF
4054 remove = true;
4055 [removing addObject:name];
e00439f7
JF
4056 } else continue;
4057
4058 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4059 substrate_ |= DepSubstrate(iterator.CurrentVer());
e057ec05 4060 }
1cb11c5f 4061
e057ec05
JF
4062 if (!remove)
4063 essential_ = nil;
c59881cd 4064 else if (Advanced_) {
61b13cae 4065 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
6932575e 4066
9c421310 4067 essential_ = [[UIAlertView alloc]
61b13cae 4068 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
9ae52960
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 ];
d3bef7bc 4074
9c421310 4075 [essential_ setContext:@"remove"];
3319715b 4076 } else {
9c421310 4077 essential_ = [[UIAlertView alloc]
61b13cae 4078 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
9ae52960
GP
4079 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4080 delegate:self
4081 cancelButtonTitle:UCLocalize("OKAY")
4082 otherButtonTitles:nil
e057ec05 4083 ];
1cb11c5f 4084
9ae52960 4085 [essential_ setContext:@"unable"];
e057ec05 4086 }
1cb11c5f 4087
f464053e
JF
4088 changes_ = [[NSArray alloc] initWithObjects:
4089 installing,
4090 reinstalling,
4091 upgrading,
4092 downgrading,
4093 removing,
4094 nil];
a75f53e7 4095
f464053e
JF
4096 issues_ = [database_ issues];
4097 if (issues_ != nil)
4098 issues_ = [issues_ retain];
a75f53e7 4099
f464053e
JF
4100 sizes_ = [[NSArray alloc] initWithObjects:
4101 SizeString([database_ fetcher].FetchNeeded()),
4102 SizeString([database_ fetcher].PartialPresent()),
f464053e 4103 nil];
a75f53e7 4104
f464053e 4105 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
d3bef7bc 4106
9ae52960 4107 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
c1edf105
GP
4108 initWithTitle:UCLocalize("CANCEL")
4109 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
9ae52960
GP
4110 style:UIBarButtonItemStylePlain
4111 target:self
4112 action:@selector(cancelButtonClicked)
4113 ];
4114 [[self navigationItem] setLeftBarButtonItem:leftItem];
4115 [leftItem release];
e057ec05 4116 } return self;
686e302f 4117}
20dd7407 4118
ed349d9a 4119- (void) applyRightButton {
9ae52960
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
ed349d9a
GP
4127 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4128 else [super applyRightButton];
4129#else
f99f86e2 4130 [[self navigationItem] setRightBarButtonItem:nil];
9ae52960
GP
4131#endif
4132 [rightItem release];
f464053e
JF
4133}
4134
9ae52960 4135- (void) cancelButtonClicked {
2064d251
GP
4136 [self dismissModalViewControllerAnimated:YES];
4137 [delegate_ cancelAndClear:YES];
f464053e
JF
4138}
4139
907a35d6 4140#if !AlwaysReload
9ae52960 4141- (void) confirmButtonClicked {
83105e6e 4142#if IgnoreInstall
9ae52960 4143 return;
83105e6e 4144#endif
f464053e 4145 if (essential_ != nil)
9ae52960 4146 [essential_ show];
f464053e
JF
4147 else {
4148 if (substrate_)
4149 Finish_ = 2;
9ae52960 4150 [delegate_ confirmWithNavigationController:[self navigationController]];
f464053e
JF
4151 }
4152}
907a35d6 4153#endif
f464053e 4154
e057ec05
JF
4155@end
4156/* }}} */
20dd7407 4157
e057ec05
JF
4158/* Progress Data {{{ */
4159@interface ProgressData : NSObject {
4160 SEL selector_;
4161 id target_;
4162 id object_;
a75f53e7
JF
4163}
4164
e057ec05 4165- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
686e302f 4166
e057ec05
JF
4167- (SEL) selector;
4168- (id) target;
4169- (id) object;
4170@end
686e302f 4171
e057ec05 4172@implementation ProgressData
686e302f 4173
e057ec05
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}
686e302f 4181
e057ec05
JF
4182- (SEL) selector {
4183 return selector_;
4184}
686e302f 4185
e057ec05
JF
4186- (id) target {
4187 return target_;
20dd7407
JF
4188}
4189
e057ec05
JF
4190- (id) object {
4191 return object_;
a75f53e7
JF
4192}
4193
4941f41d
JF
4194@end
4195/* }}} */
f441e717
GP
4196/* Progress Controller {{{ */
4197@interface ProgressController : CYViewController <
7600bd69 4198 ConfigurationDelegate,
e057ec05
JF
4199 ProgressDelegate
4200> {
7600bd69 4201 _transient Database *database_;
e057ec05
JF
4202 UIProgressBar *progress_;
4203 UITextView *output_;
4204 UITextLabel *status_;
238b07ce 4205 UIPushButton *close_;
b26eb97d 4206 BOOL running_;
1eb0c554 4207 SHA1SumValue springlist_;
bde2d79b 4208 SHA1SumValue notifyconf_;
6981ccdf 4209 NSString *title_;
4941f41d
JF
4210}
4211
9ae52960 4212- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4941f41d 4213
e057ec05
JF
4214- (void) _retachThread;
4215- (void) _detachNewThreadData:(ProgressData *)data;
4216- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4941f41d 4217
b26eb97d
JF
4218- (BOOL) isRunning;
4219
4941f41d
JF
4220@end
4221
f441e717
GP
4222@protocol ProgressControllerDelegate
4223- (void) progressControllerIsComplete:(ProgressController *)sender;
e057ec05
JF
4224@end
4225
f441e717 4226@implementation ProgressController
4941f41d
JF
4227
4228- (void) dealloc {
9ae52960 4229 [database_ setDelegate:nil];
e057ec05
JF
4230 [progress_ release];
4231 [output_ release];
4232 [status_ release];
238b07ce 4233 [close_ release];
6981ccdf
JF
4234 if (title_ != nil)
4235 [title_ release];
4941f41d
JF
4236 [super dealloc];
4237}
4238
9ae52960
GP
4239- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4240 if ((self = [super init]) != nil) {
7600bd69 4241 database_ = database;
9ae52960 4242 [database_ setDelegate:self];
e057ec05 4243 delegate_ = delegate;
1cb11c5f 4244
1e4922b8 4245 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4941f41d 4246
9ae52960 4247 progress_ = [[UIProgressBar alloc] init];
d3bef7bc 4248 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
238b07ce 4249 [progress_ setStyle:0];
1cb11c5f 4250
9ae52960 4251 status_ = [[UITextLabel alloc] init];
d3bef7bc 4252 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
87c76914
JF
4253 [status_ setColor:[UIColor whiteColor]];
4254 [status_ setBackgroundColor:[UIColor clearColor]];
e057ec05
JF
4255 [status_ setCentersHorizontally:YES];
4256 //[status_ setFont:font];
1cb11c5f 4257
9ae52960 4258 output_ = [[UITextView alloc] init];
3325a005 4259
d3bef7bc 4260 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
e057ec05 4261 //[output_ setTextFont:@"Courier New"];
c59881cd 4262 [output_ setFont:[[output_ font] fontWithSize:12]];
87c76914
JF
4263 [output_ setTextColor:[UIColor whiteColor]];
4264 [output_ setBackgroundColor:[UIColor clearColor]];
e057ec05
JF
4265 [output_ setMarginTop:0];
4266 [output_ setAllowsRubberBanding:YES];
81ab76dc 4267 [output_ setEditable:NO];
9ae52960 4268 [[self view] addSubview:output_];
686e302f 4269
9ae52960 4270 close_ = [[UIPushButton alloc] init];
d3bef7bc 4271 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
238b07ce
JF
4272 [close_ setAutosizesToFit:NO];
4273 [close_ setDrawsShadow:YES];
4274 [close_ setStretchBackground:YES];
238b07ce 4275 [close_ setEnabled:YES];
9ae52960 4276 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
017b2b71 4277 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
238b07ce
JF
4278 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4279 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
e057ec05 4280 } return self;
4941f41d
JF
4281}
4282
9ae52960
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,
4289 bounds.size.height - prgsize.height - 64
4290 }, prgsize};
f99f86e2 4291
9ae52960
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,
4298 bounds.size.height - prgsize.height - 94,
4299 bounds.size.width - 20,
4300 24
4301 )];
4302 [output_ setFrame:CGRectMake(
4303 10,
4304 20,
4305 bounds.size.width - 20,
4306 bounds.size.height - 106
4307 )];
4308 [close_ setFrame:CGRectMake(
4309 (bounds.size.width - closewidth) / 2,
4310 bounds.size.height - prgsize.height - 94,
4311 closewidth,
4312 32 + prgsize.height
4313 )];
4314}
4315
4316- (void) viewWillAppear:(BOOL)animated {
4317 [super viewDidAppear:animated];
4318 [[self navigationItem] setHidesBackButton:YES];
1e4922b8 4319 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
f99f86e2 4320
9ae52960 4321 [self positionViews];
4941f41d
JF
4322}
4323
9ae52960
GP
4324- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4325 [self positionViews];
4941f41d
JF
4326}
4327
9ae52960 4328- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3d257c70 4329 NSString *context([alert context]);
03d01f0e 4330
6981ccdf 4331 if ([context isEqualToString:@"conffile"]) {
9ae52960 4332 FILE *input = [database_ input];
3d257c70
GP
4333 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4334 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
9ae52960 4335 fflush(input);
6981ccdf
JF
4336 }
4337}
4338
4339- (void) closeButtonPushed {
4340 running_ = NO;
4341
864da84b
RP
4342 UpdateExternalStatus(0);
4343
6981ccdf
JF
4344 switch (Finish_) {
4345 case 0:
9ae52960 4346 [self dismissModalViewControllerAnimated:YES];
6981ccdf
JF
4347 break;
4348
4349 case 1:
74a834de
JF
4350 [delegate_ terminateWithSuccess];
4351 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4352 [delegate_ suspendWithAnimation:YES];
4353 else
4354 [delegate_ suspend];*/
6981ccdf
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;
03d01f0e 4368 }
6981ccdf 4369}
b26eb97d 4370
6981ccdf 4371- (void) _retachThread {
9ae52960 4372 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
6981ccdf 4373
9ae52960 4374 [[self view] addSubview:close_];
6981ccdf
JF
4375 [progress_ removeFromSuperview];
4376 [status_ removeFromSuperview];
4377
4378 [database_ popErrorWithTitle:title_];
f441e717 4379 [delegate_ progressControllerIsComplete:self];
cb9c2100 4380
bde2d79b 4381 if (Finish_ < 4) {
bd8e54e1
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 }
bde2d79b
JF
4392 }
4393
f464053e 4394 if (Finish_ < 3) {
bd8e54e1
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 }
1eb0c554
JF
4405 }
4406
03d01f0e 4407 switch (Finish_) {
9ae52960 4408 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
61b13cae
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;
03d01f0e
JF
4413 }
4414
575ffd3c 4415 system("su -c /usr/bin/uicache mobile");
5f54c108 4416
864da84b
RP
4417 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4418
b26eb97d 4419 [delegate_ setStatusBarShowsProgress:NO];
238b07ce
JF
4420}
4421
f464053e 4422- (void) _detachNewThreadData:(ProgressData *)data { _pooled
e057ec05
JF
4423 [[data target] performSelector:[data selector] withObject:[data object]];
4424 [data release];
a933cee2 4425
e057ec05 4426 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
a933cee2
JF
4427}
4428
e057ec05 4429- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
864da84b
RP
4430 UpdateExternalStatus(1);
4431
6981ccdf
JF
4432 if (title_ != nil)
4433 [title_ release];
4434 if (title == nil)
4435 title_ = nil;
4436 else
4437 title_ = [title retain];
4438
9ae52960 4439 [[self navigationItem] setTitle:title_];
686e302f 4440
e057ec05
JF
4441 [status_ setText:nil];
4442 [output_ setText:@""];
4443 [progress_ setProgress:0];
a933cee2 4444
238b07ce 4445 [close_ removeFromSuperview];
9ae52960
GP
4446 [[self view] addSubview:progress_];
4447 [[self view] addSubview:status_];
238b07ce 4448
b26eb97d
JF
4449 [delegate_ setStatusBarShowsProgress:YES];
4450 running_ = YES;
4451
bde2d79b 4452 {
bd8e54e1
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 }
bde2d79b
JF
4462 }
4463
f464053e 4464 {
bd8e54e1
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 }
1eb0c554
JF
4474 }
4475
e057ec05
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 ];
a933cee2
JF
4485}
4486
965edd52
JF
4487- (void) repairWithSelector:(SEL)selector {
4488 [self
4489 detachNewThreadSelector:selector
4490 toTarget:database_
4491 withObject:nil
61b13cae 4492 title:UCLocalize("REPAIRING")
965edd52
JF
4493 ];
4494}
4495
7600bd69
JF
4496- (void) setConfigurationData:(NSString *)data {
4497 [self
4498 performSelectorOnMainThread:@selector(_setConfigurationData:)
4499 withObject:data
4500 waitUntilDone:YES
4501 ];
4502}
4503
6981ccdf
JF
4504- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4505 CYActionSheet *sheet([[[CYActionSheet alloc]
4506 initWithTitle:title
61b13cae 4507 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
238b07ce 4508 defaultButtonIndex:0
6981ccdf 4509 ] autorelease]);
238b07ce 4510
9e639c5a 4511 [sheet setMessage:error];
6981ccdf
JF
4512 [sheet yieldToPopupAlertAnimated:YES];
4513 [sheet dismiss];
a933cee2
JF
4514}
4515
e057ec05
JF
4516- (void) setProgressTitle:(NSString *)title {
4517 [self
4518 performSelectorOnMainThread:@selector(_setProgressTitle:)
4519 withObject:title
4520 waitUntilDone:YES
4521 ];
a933cee2
JF
4522}
4523
e057ec05
JF
4524- (void) setProgressPercent:(float)percent {
4525 [self
4526 performSelectorOnMainThread:@selector(_setProgressPercent:)
4527 withObject:[NSNumber numberWithFloat:percent]
4528 waitUntilDone:YES
4529 ];
a933cee2
JF
4530}
4531
87c76914 4532- (void) startProgress {
87c76914
JF
4533}
4534
e057ec05
JF
4535- (void) addProgressOutput:(NSString *)output {
4536 [self
4537 performSelectorOnMainThread:@selector(_addProgressOutput:)
4538 withObject:output
4539 waitUntilDone:YES
4540 ];
a933cee2
JF
4541}
4542
87c76914 4543- (bool) isCancelling:(size_t)received {
87c76914
JF
4544 return false;
4545}
4546
7600bd69 4547- (void) _setConfigurationData:(NSString *)data {
faf4eb4f
JF
4548 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4549
6981ccdf
JF
4550 if (!conffile_r(data)) {
4551 lprintf("E:invalid conffile\n");
4552 return;
4553 }
7600bd69
JF
4554
4555 NSString *ofile = conffile_r[1];
4556 //NSString *nfile = conffile_r[2];
4557
3d257c70 4558 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 4559 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9ae52960
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"),
3d257c70 4564 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9ae52960
GP
4565 nil
4566 ] autorelease];
3d257c70 4567
9ae52960 4568 [alert setContext:@"conffile"];
3d257c70 4569 [alert show];
7600bd69
JF
4570}
4571
e057ec05 4572- (void) _setProgressTitle:(NSString *)title {
907a35d6
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:@" "]];
686e302f 4581}
a933cee2 4582
e057ec05
JF
4583- (void) _setProgressPercent:(NSNumber *)percent {
4584 [progress_ setProgress:[percent floatValue]];
242bcc6d
JF
4585}
4586
e057ec05
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}
3957dd75 4593
b26eb97d 4594- (BOOL) isRunning {
5f54c108 4595 return running_;
b26eb97d
JF
4596}
4597
e057ec05
JF
4598@end
4599/* }}} */
3957dd75 4600
d4a9ec10 4601/* Cell Content View {{{ */
1e4922b8
JF
4602@protocol ContentDelegate
4603- (void) drawContentRect:(CGRect)rect;
4604@end
4605
5d8f1006 4606@interface ContentView : UIView {
1e4922b8 4607 _transient id<ContentDelegate> delegate_;
5d8f1006
JF
4608}
4609
4610@end
4611
d4a9ec10
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
1e4922b8 4620- (void) setDelegate:(id<ContentDelegate>)delegate {
d4a9ec10
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 {{{ */
1e4922b8
JF
4631@interface PackageCell : UITableViewCell <
4632 ContentDelegate
4633> {
5e563e79
JF
4634 UIImage *icon_;
4635 NSString *name_;
4636 NSString *description_;
d8d9a65c 4637 bool commercial_;
5e563e79 4638 NSString *source_;
cb9c2100 4639 UIImage *badge_;
3ff1504e 4640 Package *package_;
5d8f1006
JF
4641 UIColor *color_;
4642 ContentView *content_;
4643 BOOL faded_;
4644 float fade_;
6981ccdf 4645 UIImage *placard_;
e057ec05 4646}
138ae18d 4647
e057ec05
JF
4648- (PackageCell *) init;
4649- (void) setPackage:(Package *)package;
1cb11c5f 4650
3319715b 4651+ (int) heightForPackage:(Package *)package;
5d8f1006
JF
4652- (void) drawContentRect:(CGRect)rect;
4653
4654@end
4655
e057ec05
JF
4656@implementation PackageCell
4657
5e563e79
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 }
cb9c2100
JF
4678
4679 if (badge_ != nil) {
4680 [badge_ release];
4681 badge_ = nil;
4682 }
3ff1504e 4683
6981ccdf
JF
4684 if (placard_ != nil) {
4685 [placard_ release];
4686 placard_ = nil;
4687 }
4688
3ff1504e
JF
4689 [package_ release];
4690 package_ = nil;
5e563e79
JF
4691}
4692
e057ec05 4693- (void) dealloc {
5e563e79 4694 [self clearPackage];
5d8f1006
JF
4695 [content_ release];
4696 [color_ release];
e057ec05 4697 [super dealloc];
686e302f 4698}
a933cee2 4699
5d8f1006
JF
4700- (float) fade {
4701 return faded_ ? [self selectionPercent] : fade_;
4702}
4703
e057ec05 4704- (PackageCell *) init {
5d8f1006
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]);
d3bef7bc 4709
5d8f1006 4710 content_ = [[ContentView alloc] initWithFrame:bounds];
d3bef7bc
JF
4711 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4712 [content addSubview:content_];
4713
5d8f1006 4714 [content_ setDelegate:self];
5d8f1006 4715 [content_ setOpaque:YES];
5d8f1006
JF
4716 if ([self respondsToSelector:@selector(selectionPercent)])
4717 faded_ = YES;
e057ec05 4718 } return self;
686e302f 4719}
a933cee2 4720
5d8f1006
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
e057ec05 4733- (void) setPackage:(Package *)package {
d1494d2c 4734 [self clearPackage];
631a0a1e 4735 [package parse];
238b07ce 4736
e057ec05 4737 Source *source = [package source];
a933cee2 4738
dbe0f181 4739 icon_ = [[package icon] retain];
5e563e79 4740 name_ = [[package name] retain];
37455cf8
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
d8d9a65c 4749 commercial_ = [package isCommercial];
e057ec05 4750
3ff1504e
JF
4751 package_ = [package retain];
4752
9e07091a
JF
4753 NSString *label = nil;
4754 bool trusted = false;
a933cee2 4755
e057ec05
JF
4756 if (source != nil) {
4757 label = [source label];
4758 trusted = [source trusted];
9e07091a 4759 } else if ([[package id] isEqualToString:@"firmware"])
61b13cae 4760 label = UCLocalize("APPLE");
faf4eb4f 4761 else
61b13cae 4762 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
a933cee2 4763
6932575e 4764 NSString *from(label);
9e07091a 4765
6932575e
JF
4766 NSString *section = [package simpleSection];
4767 if (section != nil && ![section isEqualToString:label]) {
4768 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
61b13cae 4769 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
6932575e 4770 }
9e07091a 4771
61b13cae 4772 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5e563e79 4773 source_ = [from retain];
e057ec05 4774
cb9c2100
JF
4775 if (NSString *purpose = [package primaryPurpose])
4776 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4777 badge_ = [badge_ retain];
4778
6981ccdf
JF
4779 if ([package installed] != nil)
4780 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4781 placard_ = [placard_ retain];
4782
5d8f1006
JF
4783 [self _setBackgroundColor];
4784 [content_ setNeedsDisplay];
d8d9a65c
JF
4785}
4786
5d8f1006
JF
4787- (void) drawContentRect:(CGRect)rect {
4788 bool selected([self isSelected]);
37455cf8 4789 float width([self bounds].size.width);
3ff1504e 4790
5d8f1006
JF
4791#if 0
4792 CGContextRef context(UIGraphicsGetCurrentContext());
4793 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4794 CGContextFillRect(context, rect);
4795#endif
a933cee2 4796
87c76914
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 }
a933cee2 4809
cb9c2100
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
5e563e79
JF
4819 if (selected)
4820 UISetColor(White_);
a933cee2 4821
5e563e79 4822 if (!selected)
d8d9a65c 4823 UISetColor(commercial_ ? Purple_ : Black_);
a6c1718e
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];
a933cee2 4826
5e563e79 4827 if (!selected)
d8d9a65c 4828 UISetColor(commercial_ ? Purplish_ : Gray_);
a6c1718e 4829 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
6981ccdf
JF
4830
4831 if (placard_ != nil)
5ec44e34 4832 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
1cb11c5f
JF
4833}
4834
5d8f1006
JF
4835- (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4836 //[self _setBackgroundColor];
4837 [super setSelected:selected animated:fade];
4838 [content_ setNeedsDisplay];
3ff1504e
JF
4839}
4840
3319715b 4841+ (int) heightForPackage:(Package *)package {
631a0a1e 4842 return 73;
3319715b
JF
4843}
4844
20dd7407
JF
4845@end
4846/* }}} */
e057ec05 4847/* Section Cell {{{ */
1e4922b8
JF
4848@interface SectionCell : UITableViewCell <
4849 ContentDelegate
4850> {
4923fbd7 4851 NSString *basic_;
fa7bb92f 4852 NSString *section_;
5e563e79
JF
4853 NSString *name_;
4854 NSString *count_;
4855 UIImage *icon_;
d4a9ec10
GP
4856 ContentView *content_;
4857 id switch_;
fa7bb92f 4858 BOOL editing_;
686e302f 4859}
a933cee2 4860
fa7bb92f 4861- (void) setSection:(Section *)section editing:(BOOL)editing;
e057ec05 4862
20dd7407
JF
4863@end
4864
e057ec05 4865@implementation SectionCell
20dd7407 4866
5e563e79 4867- (void) clearSection {
4923fbd7 4868 if (basic_ != nil) {
7805b429 4869 [basic_ release];
4923fbd7
JF
4870 basic_ = nil;
4871 }
4872
5e563e79 4873 if (section_ != nil) {
fa7bb92f 4874 [section_ release];
5e563e79
JF
4875 section_ = nil;
4876 }
faf4eb4f 4877
5e563e79
JF
4878 if (name_ != nil) {
4879 [name_ release];
4880 name_ = nil;
4881 }
faf4eb4f 4882
5e563e79
JF
4883 if (count_ != nil) {
4884 [count_ release];
4885 count_ = nil;
4886 }
faf4eb4f
JF
4887}
4888
5e563e79
JF
4889- (void) dealloc {
4890 [self clearSection];
4891 [icon_ release];
4892 [switch_ release];
d4a9ec10
GP
4893 [content_ release];
4894
5e563e79 4895 [super dealloc];
faf4eb4f
JF
4896}
4897
d4a9ec10
GP
4898- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4899 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5e563e79 4900 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
d4a9ec10
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];
686e302f 4913 } return self;
a933cee2
JF
4914}
4915
fa7bb92f 4916- (void) onSwitch:(id)sender {
4923fbd7 4917 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
fa7bb92f
JF
4918 if (metadata == nil) {
4919 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4923fbd7 4920 [Sections_ setObject:metadata forKey:basic_];
fa7bb92f
JF
4921 }
4922
4923 Changed_ = true;
d4a9ec10 4924 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
fa7bb92f
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
5e563e79 4936 [self clearSection];
fa7bb92f 4937
e057ec05 4938 if (section == nil) {
61b13cae 4939 name_ = [UCLocalize("ALL_PACKAGES") retain];
5e563e79 4940 count_ = nil;
e057ec05 4941 } else {
7805b429 4942 basic_ = [section name];
4923fbd7
JF
4943 if (basic_ != nil)
4944 basic_ = [basic_ retain];
4945
43b742af 4946 section_ = [section localized];
fa7bb92f
JF
4947 if (section_ != nil)
4948 section_ = [section_ retain];
4923fbd7 4949
61b13cae 4950 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5e563e79 4951 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
fa7bb92f
JF
4952
4953 if (editing_)
d4a9ec10 4954 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
e057ec05 4955 }
d4a9ec10 4956
1e4922b8 4957 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
864db79b
JF
4958 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4959
d4a9ec10 4960 [content_ setNeedsDisplay];
5e563e79
JF
4961}
4962
daf7f6e2
JF
4963- (void) setFrame:(CGRect)frame {
4964 [super setFrame:frame];
d4a9ec10 4965
daf7f6e2
JF
4966 CGRect rect([switch_ frame]);
4967 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4968}
4969
d4a9ec10
GP
4970- (void) drawContentRect:(CGRect)rect {
4971 BOOL selected = [self isSelected];
f99f86e2 4972
5e563e79
JF
4973 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4974
4975 if (selected)
4976 UISetColor(White_);
4977
4978 if (!selected)
4979 UISetColor(Black_);
575ffd3c 4980
d4a9ec10 4981 float width(rect.size.width);
575ffd3c 4982 if (editing_)
d4a9ec10 4983 width -= 87;
575ffd3c 4984
a6c1718e 4985 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
fa7bb92f 4986
5e563e79
JF
4987 CGSize size = [count_ sizeWithFont:Font14_];
4988
4989 UISetColor(White_);
4990 if (count_ != nil)
cb9c2100 4991 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
a933cee2
JF
4992}
4993
e057ec05
JF
4994@end
4995/* }}} */
a933cee2 4996
59efd93a 4997/* File Table {{{ */
1e4922b8
JF
4998@interface FileTable : CYViewController <
4999 UITableViewDataSource,
5000 UITableViewDelegate
5001> {
e057ec05 5002 _transient Database *database_;
59efd93a
JF
5003 Package *package_;
5004 NSString *name_;
5005 NSMutableArray *files_;
d4a9ec10 5006 UITableView *list_;
59efd93a 5007}
a933cee2 5008
9ae52960 5009- (id) initWithDatabase:(Database *)database;
59efd93a
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
9b62701b 5026- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
59efd93a
JF
5027 return files_ == nil ? 0 : [files_ count];
5028}
5029
2064d251
GP
5030/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5031 return 24.0f;
5032}*/
59efd93a 5033
d4a9ec10 5034- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9ae52960
GP
5035 static NSString *reuseIdentifier = @"Cell";
5036
d4a9ec10
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]];
59efd93a 5041 }
d4a9ec10 5042 [cell setText:[files_ objectAtIndex:indexPath.row]];
1e4922b8 5043 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
9ae52960 5044
d4a9ec10 5045 return cell;
59efd93a 5046}
a933cee2 5047
9ae52960
GP
5048- (id) initWithDatabase:(Database *)database {
5049 if ((self = [super init]) != nil) {
59efd93a 5050 database_ = database;
a933cee2 5051
9ae52960
GP
5052 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5053
59efd93a 5054 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
20dd7407 5055
d4a9ec10 5056 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
2064d251
GP
5057 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5058 [list_ setRowHeight:24.0f];
9ae52960 5059 [[self view] addSubview:list_];
59efd93a 5060
59efd93a 5061 [list_ setDataSource:self];
59efd93a 5062 [list_ setDelegate:self];
59efd93a
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
f464053e
JF
5083 if (NSArray *files = [package files])
5084 [files_ addObjectsFromArray:files];
59efd93a 5085
fc19e583
JF
5086 if ([files_ count] != 0) {
5087 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5088 [files_ removeObjectAtIndex:0];
9e07091a 5089 [files_ sortUsingSelector:@selector(compareByPath:)];
2a987aa5
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%@",
9e07091a 5101 ([stack count] - 2) * 3, "",
2a987aa5
JF
5102 [file substringFromIndex:[directory length]]
5103 ]];
5104 }
59efd93a
JF
5105 }
5106 }
5107
5108 [list_ reloadData];
5109}
5110
59efd93a
JF
5111- (void) reloadData {
5112 [self setPackage:[database_ packageWithName:name_]];
59efd93a 5113}
686e302f 5114
686e302f 5115@end
e057ec05 5116/* }}} */
f441e717 5117/* Package Controller {{{ */
48861ec9
DH
5118@interface PackageController : CYBrowserController <
5119 UIActionSheetDelegate
5120> {
dbe0f181 5121 _transient Database *database_;
e057ec05
JF
5122 Package *package_;
5123 NSString *name_;
d8d9a65c 5124 bool commercial_;
965edd52 5125 NSMutableArray *buttons_;
c2292b80 5126 UIBarButtonItem *button_;
df5a7529
JF
5127}
5128
9ae52960 5129- (id) initWithDatabase:(Database *)database;
e057ec05 5130- (void) setPackage:(Package *)package;
686e302f 5131
e057ec05 5132@end
686e302f 5133
f441e717 5134@implementation PackageController
686e302f 5135
e057ec05 5136- (void) dealloc {
e057ec05
JF
5137 if (package_ != nil)
5138 [package_ release];
5139 if (name_ != nil)
5140 [name_ release];
c2292b80 5141
965edd52 5142 [buttons_ release];
c2292b80
JF
5143
5144 if (button_ != nil)
5145 [button_ release];
5146
e057ec05
JF
5147 [super dealloc];
5148}
20dd7407 5149
d287ae9a 5150- (void) release {
6932575e 5151 if ([self retainCount] == 1)
f441e717 5152 [delegate_ setPackageController:self];
6932575e 5153 [super release];
d287ae9a 5154}
6932575e
JF
5155
5156/* XXX: this is not safe at all... localization of /fail/ */
965edd52 5157- (void) _clickButtonWithName:(NSString *)name {
61b13cae 5158 if ([name isEqualToString:UCLocalize("CLEAR")])
3ff1504e 5159 [delegate_ clearPackage:package_];
61b13cae 5160 else if ([name isEqualToString:UCLocalize("INSTALL")])
965edd52 5161 [delegate_ installPackage:package_];
61b13cae 5162 else if ([name isEqualToString:UCLocalize("REINSTALL")])
965edd52 5163 [delegate_ installPackage:package_];
61b13cae 5164 else if ([name isEqualToString:UCLocalize("REMOVE")])
965edd52 5165 [delegate_ removePackage:package_];
61b13cae 5166 else if ([name isEqualToString:UCLocalize("UPGRADE")])
965edd52
JF
5167 [delegate_ installPackage:package_];
5168 else _assert(false);
5169}
5170
1ca35d78 5171- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
a5dd312c 5172 NSString *context([sheet context]);
965edd52 5173
a5dd312c 5174 if ([context isEqualToString:@"modify"]) {
1ca35d78
GP
5175 if (button != [sheet cancelButtonIndex]) {
5176 NSString *buttonName = [buttons_ objectAtIndex:button];
5177 [self _clickButtonWithName:buttonName];
5178 }
f99f86e2 5179
1ca35d78 5180 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
1ca35d78 5181 }
686e302f 5182}
4941f41d 5183
c2292b80
JF
5184- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5185 [super webView:view didClearWindowObject:window forFrame:frame];
6932575e 5186 [window setValue:package_ forKey:@"package"];
ad554f10
JF
5187}
5188
7b00c562 5189- (bool) _allowJavaScriptPanel {
d8d9a65c 5190 return commercial_;
7b00c562
JF
5191}
5192
907a35d6 5193#if !AlwaysReload
48861ec9 5194- (void) _customButtonClicked {
6981ccdf
JF
5195 int count([buttons_ count]);
5196 if (count == 0)
5197 return;
4941f41d 5198
965edd52
JF
5199 if (count == 1)
5200 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5201 else {
1ca35d78 5202 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
965edd52 5203 [buttons addObjectsFromArray:buttons_];
e057ec05 5204
1ca35d78 5205 UIActionSheet *sheet = [[[UIActionSheet alloc]
fc19e583 5206 initWithTitle:nil
e057ec05 5207 delegate:self
1ca35d78
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"];
f99f86e2 5219
9ae52960 5220 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
e057ec05 5221 }
686e302f 5222}
1ce016d4 5223
3db9f43c
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.
48861ec9 5226- (void) customButtonClicked {
3db9f43c
DH
5227 if (commercial_)
5228 [super customButtonClicked];
5229 else
48861ec9 5230 [self _customButtonClicked];
1ce016d4 5231}
c8e3b4b3
GP
5232
5233- (void) reloadButtonClicked {
b36becfc
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.
c8e3b4b3 5239}
3db9f43c
DH
5240
5241- (UIBarButtonItem *) rightButton {
c2292b80 5242 return button_;
3db9f43c 5243}
907a35d6 5244#endif
4941f41d 5245
9ae52960
GP
5246- (id) initWithDatabase:(Database *)database {
5247 if ((self = [super init]) != nil) {
e057ec05 5248 database_ = database;
965edd52 5249 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
6932575e 5250 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
e057ec05 5251 } return self;
a75f53e7
JF
5252}
5253
e057ec05
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
965edd52
JF
5265 [buttons_ removeAllObjects];
5266
e057ec05 5267 if (package != nil) {
631a0a1e
JF
5268 [package parse];
5269
e057ec05
JF
5270 package_ = [package retain];
5271 name_ = [[package id] retain];
d8d9a65c 5272 commercial_ = [package isCommercial];
e057ec05 5273
3ff1504e 5274 if ([package_ mode] != nil)
61b13cae 5275 [buttons_ addObject:UCLocalize("CLEAR")];
965edd52 5276 if ([package_ source] == nil);
238b07ce 5277 else if ([package_ upgradableAndEssential:NO])
61b13cae 5278 [buttons_ addObject:UCLocalize("UPGRADE")];
b4c4fac4 5279 else if ([package_ uninstalled])
61b13cae 5280 [buttons_ addObject:UCLocalize("INSTALL")];
965edd52 5281 else
61b13cae 5282 [buttons_ addObject:UCLocalize("REINSTALL")];
b4c4fac4 5283 if (![package_ uninstalled])
61b13cae 5284 [buttons_ addObject:UCLocalize("REMOVE")];
c2292b80 5285 }
6932575e 5286
c2292b80
JF
5287 if (button_ != nil)
5288 [button_ release];
6932575e 5289
c2292b80
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;
e057ec05 5295 }
c2292b80
JF
5296
5297 button_ = [[UIBarButtonItem alloc]
5298 initWithTitle:title
5299 style:UIBarButtonItemStylePlain
5300 target:self
5301 action:@selector(customButtonClicked)
5302 ];
9ae52960 5303}
6932575e 5304
d8d9a65c
JF
5305- (bool) isLoading {
5306 return commercial_ ? [super isLoading] : false;
a99d2808
JF
5307}
5308
e057ec05
JF
5309- (void) reloadData {
5310 [self setPackage:[database_ packageWithName:name_]];
b6ffa083
JF
5311}
5312
686e302f
JF
5313@end
5314/* }}} */
686e302f 5315/* Package Table {{{ */
1e4922b8
JF
5316@interface PackageTable : UIView <
5317 UITableViewDataSource,
5318 UITableViewDelegate
5319> {
e057ec05 5320 _transient Database *database_;
e057ec05 5321 NSMutableArray *packages_;
686e302f 5322 NSMutableArray *sections_;
5d8f1006
JF
5323 UITableView *list_;
5324 NSMutableArray *index_;
5325 NSMutableDictionary *indices_;
9ae52960
GP
5326 id target_;
5327 SEL action_;
5328 id delegate_;
a75f53e7
JF
5329}
5330
9ae52960 5331- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
686e302f
JF
5332
5333- (void) setDelegate:(id)delegate;
8993ad57 5334
e057ec05 5335- (void) reloadData;
8993ad57 5336- (void) resetCursor;
686e302f 5337
5d8f1006 5338- (UITableView *) list;
2a987aa5 5339
59efd93a
JF
5340- (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5341
9ae52960
GP
5342- (void) deselectWithAnimation:(BOOL)animated;
5343
686e302f
JF
5344@end
5345
5346@implementation PackageTable
5347
5348- (void) dealloc {
e057ec05 5349 [packages_ release];
686e302f 5350 [sections_ release];
e057ec05 5351 [list_ release];
5d8f1006
JF
5352 [index_ release];
5353 [indices_ release];
9ae52960 5354
686e302f 5355 [super dealloc];
b6ffa083
JF
5356}
5357
5d8f1006
JF
5358- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5359 NSInteger count([sections_ count]);
5360 return count == 0 ? 1 : count;
686e302f 5361}
4941f41d 5362
5d8f1006
JF
5363- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5364 if ([sections_ count] == 0)
5365 return nil;
686e302f
JF
5366 return [[sections_ objectAtIndex:section] name];
5367}
a75f53e7 5368
5d8f1006
JF
5369- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5370 if ([sections_ count] == 0)
5371 return 0;
5372 return [[sections_ objectAtIndex:section] count];
686e302f 5373}
a75f53e7 5374
5d8f1006
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;
686e302f 5380}
a75f53e7 5381
5d8f1006 5382- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
1e4922b8 5383 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5d8f1006
JF
5384 if (cell == nil)
5385 cell = [[[PackageCell alloc] init] autorelease];
5386 [cell setPackage:[self packageAtIndexPath:path]];
5387 return cell;
686e302f 5388}
a75f53e7 5389
9ae52960
GP
5390- (void) deselectWithAnimation:(BOOL)animated {
5391 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5392}
5393
2064d251 5394/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5d8f1006 5395 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
2064d251 5396}*/
a75f53e7 5397
5d8f1006
JF
5398- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5399 Package *package([self packageAtIndexPath:path]);
c3f582af 5400 package = [database_ packageWithName:[package id]];
9ae52960 5401 [target_ performSelector:action_ withObject:package];
5d8f1006
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;
a75f53e7
JF
5411}
5412
9ae52960
GP
5413- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5414 if ((self = [super initWithFrame:frame]) != nil) {
e057ec05 5415 database_ = database;
9ae52960
GP
5416
5417 target_ = target;
5418 action_ = action;
e057ec05 5419
5d8f1006
JF
5420 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5421 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5422
e057ec05 5423 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
686e302f 5424 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
a75f53e7 5425
5d8f1006 5426 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
d3bef7bc 5427 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
2064d251 5428 [list_ setRowHeight:73.0f];
d3bef7bc
JF
5429 [self addSubview:list_];
5430
686e302f 5431 [list_ setDataSource:self];
5d8f1006 5432 [list_ setDelegate:self];
686e302f 5433 } return self;
a75f53e7
JF
5434}
5435
5436- (void) setDelegate:(id)delegate {
4941f41d 5437 delegate_ = delegate;
686e302f
JF
5438}
5439
ce09fc27
JF
5440- (bool) hasPackage:(Package *)package {
5441 return true;
8993ad57
JF
5442}
5443
e057ec05
JF
5444- (void) reloadData {
5445 NSArray *packages = [database_ packages];
686e302f 5446
e057ec05 5447 [packages_ removeAllObjects];
686e302f
JF
5448 [sections_ removeAllObjects];
5449
3bddda52 5450 _profile(PackageTable$reloadData$Filter)
9fdd37d0 5451 for (Package *package in packages)
3bddda52
JF
5452 if ([self hasPackage:package])
5453 [packages_ addObject:package];
3bddda52 5454 _end
e057ec05 5455
5d8f1006
JF
5456 [index_ removeAllObjects];
5457 [indices_ removeAllObjects];
5458
686e302f
JF
5459 Section *section = nil;
5460
3bddda52 5461 _profile(PackageTable$reloadData$Section)
9fdd37d0
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
686e302f 5470
3bddda52
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
686e302f 5475
5d8f1006
JF
5476 [index_ addObject:[section name]];
5477 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5478
9fdd37d0
JF
5479 _profile(PackageTable$reloadData$Section$Add)
5480 [sections_ addObject:section];
5481 _end
3bddda52
JF
5482 }
5483
5484 [section addToCount];
5485 }
5486 _end
686e302f 5487
9fdd37d0
JF
5488 _profile(PackageTable$reloadData$List)
5489 [list_ reloadData];
5490 _end
686e302f
JF
5491}
5492
8993ad57 5493- (void) resetCursor {
5d8f1006 5494 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
8993ad57
JF
5495}
5496
5d8f1006 5497- (UITableView *) list {
2a987aa5
JF
5498 return list_;
5499}
5500
59efd93a 5501- (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5d8f1006 5502 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
59efd93a
JF
5503}
5504
ce09fc27
JF
5505@end
5506/* }}} */
5507/* Filtered Package Table {{{ */
5508@interface FilteredPackageTable : PackageTable {
5509 SEL filter_;
142bd2db 5510 IMP imp_;
ce09fc27
JF
5511 id object_;
5512}
5513
5514- (void) setObject:(id)object;
5ec44e34 5515- (void) setObject:(id)object forFilter:(SEL)filter;
ce09fc27 5516
9ae52960 5517- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
ce09fc27
JF
5518
5519@end
5520
5521@implementation FilteredPackageTable
5522
5523- (void) dealloc {
5524 if (object_ != nil)
5525 [object_ release];
5526 [super dealloc];
5527}
5528
5ec44e34
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
ce09fc27
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
5ec44e34
JF
5548- (void) setObject:(id)object forFilter:(SEL)filter {
5549 [self setFilter:filter];
5550 [self setObject:object];
5ec44e34
JF
5551}
5552
ce09fc27 5553- (bool) hasPackage:(Package *)package {
142bd2db
JF
5554 _profile(FilteredPackageTable$hasPackage)
5555 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5556 _end
ce09fc27
JF
5557}
5558
9ae52960
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) {
5ec44e34 5561 [self setFilter:filter];
9ae52960 5562 object_ = [object retain];
6e673d99 5563 [self reloadData];
ce09fc27
JF
5564 } return self;
5565}
5566
a75f53e7 5567@end
686e302f 5568/* }}} */
a75f53e7 5569
f441e717
GP
5570/* Filtered Package Controller {{{ */
5571@interface FilteredPackageController : CYViewController {
9ae52960
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
f99f86e2 5580
f441e717 5581@implementation FilteredPackageController
9ae52960
GP
5582
5583- (void) dealloc {
5584 [packages_ release];
5585 [title_ release];
f99f86e2 5586
9ae52960
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 {
f441e717 5596 PackageController *view([delegate_ packageController]);
9ae52960
GP
5597 [view setPackage:package];
5598 [view setDelegate:delegate_];
5599 [[self navigationController] pushViewController:view animated:YES];
5600}
5601
9b62701b 5602- (NSString *) title { return title_; }
9ae52960
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
f99f86e2 5634
9ae52960
GP
5635/* }}} */
5636
f441e717
GP
5637/* Add Source Controller {{{ */
5638@interface AddSourceController : CYViewController {
faf4eb4f 5639 _transient Database *database_;
a75f53e7
JF
5640}
5641
9ae52960 5642- (id) initWithDatabase:(Database *)database;
686e302f 5643
faf4eb4f 5644@end
a75f53e7 5645
f441e717 5646@implementation AddSourceController
a75f53e7 5647
9ae52960
GP
5648- (id) initWithDatabase:(Database *)database {
5649 if ((self = [super init]) != nil) {
faf4eb4f
JF
5650 database_ = database;
5651 } return self;
e057ec05 5652}
a75f53e7 5653
faf4eb4f
JF
5654@end
5655/* }}} */
5656/* Source Cell {{{ */
1e4922b8
JF
5657@interface SourceCell : UITableViewCell <
5658 ContentDelegate
5659> {
5e563e79
JF
5660 UIImage *icon_;
5661 NSString *origin_;
5662 NSString *description_;
5663 NSString *label_;
d4a9ec10 5664 ContentView *content_;
686e302f
JF
5665}
5666
d4a9ec10 5667- (void) setSource:(Source *)source;
686e302f 5668
faf4eb4f 5669@end
686e302f 5670
faf4eb4f 5671@implementation SourceCell
686e302f 5672
d4a9ec10 5673- (void) clearSource {
5e563e79 5674 [icon_ release];
faf4eb4f
JF
5675 [origin_ release];
5676 [description_ release];
5677 [label_ release];
d4a9ec10
GP
5678
5679 icon_ = nil;
5680 origin_ = nil;
5681 description_ = nil;
5682 label_ = nil;
5683}
5684
5685- (void) setSource:(Source *)source {
5686 [self clearSource];
f99f86e2 5687
d4a9ec10
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];
faf4eb4f 5704 [super dealloc];
e057ec05 5705}
686e302f 5706
d4a9ec10
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];
faf4eb4f 5719 } return self;
48c0461e
JF
5720}
5721
d4a9ec10
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]);
5ec44e34
JF
5729 float width(rect.size.width);
5730
5e563e79
JF
5731 if (icon_ != nil)
5732 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
faf4eb4f 5733
5e563e79
JF
5734 if (selected)
5735 UISetColor(White_);
faf4eb4f 5736
5e563e79
JF
5737 if (!selected)
5738 UISetColor(Black_);
a6c1718e 5739 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
faf4eb4f 5740
5e563e79
JF
5741 if (!selected)
5742 UISetColor(Blue_);
a6c1718e 5743 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
faf4eb4f 5744
5e563e79
JF
5745 if (!selected)
5746 UISetColor(Gray_);
a6c1718e 5747 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
faf4eb4f
JF
5748}
5749
5750@end
5751/* }}} */
5752/* Source Table {{{ */
1e4922b8
JF
5753@interface SourceTable : CYViewController <
5754 UITableViewDataSource,
5755 UITableViewDelegate
5756> {
faf4eb4f 5757 _transient Database *database_;
d4a9ec10 5758 UITableView *list_;
faf4eb4f 5759 NSMutableArray *sources_;
faf4eb4f
JF
5760 int offset_;
5761
5762 NSString *href_;
5763 UIProgressHUD *hud_;
5764 NSError *error_;
5765
5766 //NSURLConnection *installer_;
3d3f4666 5767 NSURLConnection *trivial_;
faf4eb4f
JF
5768 NSURLConnection *trivial_bz2_;
5769 NSURLConnection *trivial_gz_;
5770 //NSURLConnection *automatic_;
5771
3d3f4666 5772 BOOL cydia_;
faf4eb4f
JF
5773}
5774
9ae52960 5775- (id) initWithDatabase:(Database *)database;
faf4eb4f 5776
1e4922b8
JF
5777- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5778
faf4eb4f
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 {
faf4eb4f
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_];
3d3f4666 5800 [self _deallocConnection:trivial_];
faf4eb4f
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
9ae52960
GP
5810- (void) viewDidAppear:(BOOL)animated {
5811 [super viewDidAppear:animated];
5812 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5813}
5814
9b62701b 5815- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
faf4eb4f
JF
5816 return offset_ == 0 ? 1 : 2;
5817}
5818
9b62701b 5819- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
faf4eb4f 5820 switch (section + (offset_ == 0 ? 1 : 0)) {
61b13cae
JF
5821 case 0: return UCLocalize("ENTERED_BY_USER");
5822 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
faf4eb4f 5823
6981ccdf 5824 _nodefault
faf4eb4f
JF
5825 }
5826}
5827
9b62701b 5828- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
d4a9ec10
GP
5829 int count = [sources_ count];
5830 switch (section) {
5831 case 0: return (offset_ == 0 ? count : offset_);
5832 case 1: return count - offset_;
faf4eb4f 5833
9ae52960 5834 _nodefault
faf4eb4f
JF
5835 }
5836}
5837
d4a9ec10
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
9ae52960 5844 _nodefault
d4a9ec10
GP
5845 }
5846 return [sources_ objectAtIndex:idx];
faf4eb4f
JF
5847}
5848
d4a9ec10
GP
5849- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5850 Source *source = [self sourceAtIndexPath:indexPath];
5e563e79 5851 return [source description] == nil ? 56 : 73;
faf4eb4f
JF
5852}
5853
d4a9ec10 5854- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9ae52960 5855 static NSString *cellIdentifier = @"SourceCell";
faf4eb4f 5856
d4a9ec10 5857 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
9ae52960
GP
5858 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5859 [cell setSource:[self sourceAtIndexPath:indexPath]];
f99f86e2 5860
d4a9ec10 5861 return cell;
faf4eb4f
JF
5862}
5863
1e4922b8
JF
5864- (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5865 return UITableViewCellAccessoryDisclosureIndicator;
faf4eb4f
JF
5866}
5867
d4a9ec10
GP
5868- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5869 Source *source = [self sourceAtIndexPath:indexPath];
faf4eb4f 5870
f441e717 5871 FilteredPackageController *packages = [[[FilteredPackageController alloc]
9ae52960 5872 initWithDatabase:database_
faf4eb4f
JF
5873 title:[source label]
5874 filter:@selector(isVisibleInSource:)
5875 with:source
5876 ] autorelease];
5877
5878 [packages setDelegate:delegate_];
5879
9ae52960 5880 [[self navigationController] pushViewController:packages animated:YES];
faf4eb4f
JF
5881}
5882
d4a9ec10
GP
5883- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5884 Source *source = [self sourceAtIndexPath:indexPath];
faf4eb4f
JF
5885 return [source record] != nil;
5886}
5887
d4a9ec10
GP
5888- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5889 Source *source = [self sourceAtIndexPath:indexPath];
faf4eb4f
JF
5890 [Sources_ removeObjectForKey:[source key]];
5891 [delegate_ syncData];
5892}
5893
b4dff19a
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 {
7b00c562
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];
6981ccdf 5910 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
b4dff19a
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
faf4eb4f
JF
5923- (void) _endConnection:(NSURLConnection *)connection {
5924 NSURLConnection **field = NULL;
3d3f4666
JF
5925 if (connection == trivial_)
5926 field = &trivial_;
5927 else if (connection == trivial_bz2_)
faf4eb4f
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 (
3d3f4666 5936 trivial_ == nil &&
faf4eb4f
JF
5937 trivial_bz2_ == nil &&
5938 trivial_gz_ == nil
5939 ) {
7b00c562 5940 bool defer(false);
faf4eb4f 5941
3d3f4666 5942 if (cydia_) {
b4dff19a 5943 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7b00c562
JF
5944 defer = true;
5945
1ba930a4 5946 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 5947 initWithTitle:UCLocalize("SOURCE_WARNING")
9ae52960
GP
5948 message:warning
5949 delegate:self
5950 cancelButtonTitle:UCLocalize("CANCEL")
1ba930a4 5951 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
b4dff19a
JF
5952 ] autorelease];
5953
9ae52960 5954 [alert setContext:@"warning"];
1ba930a4
GP
5955 [alert setNumberOfRows:1];
5956 [alert show];
b4dff19a
JF
5957 } else
5958 [self complete];
faf4eb4f 5959 } else if (error_ != nil) {
1ba930a4 5960 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 5961 initWithTitle:UCLocalize("VERIFICATION_ERROR")
9ae52960
GP
5962 message:[error_ localizedDescription]
5963 delegate:self
5964 cancelButtonTitle:UCLocalize("OK")
1ba930a4 5965 otherButtonTitles:nil
faf4eb4f
JF
5966 ] autorelease];
5967
9ae52960 5968 [alert setContext:@"urlerror"];
1ba930a4 5969 [alert show];
faf4eb4f 5970 } else {
1ba930a4 5971 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 5972 initWithTitle:UCLocalize("NOT_REPOSITORY")
9ae52960
GP
5973 message:UCLocalize("NOT_REPOSITORY_EX")
5974 delegate:self
5975 cancelButtonTitle:UCLocalize("OK")
1ba930a4 5976 otherButtonTitles:nil
faf4eb4f
JF
5977 ] autorelease];
5978
9ae52960 5979 [alert setContext:@"trivial"];
1ba930a4 5980 [alert show];
faf4eb4f
JF
5981 }
5982
7b00c562
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 }
faf4eb4f
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:
3d3f4666 6004 cydia_ = YES;
faf4eb4f
JF
6005 }
6006}
6007
6008- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
cb9c2100 6009 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
faf4eb4f
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
9b62701b 6019- (NSString *) title { return UCLocalize("SOURCES"); }
9ae52960 6020
faf4eb4f
JF
6021- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6022 NSMutableURLRequest *request = [NSMutableURLRequest
6023 requestWithURL:[NSURL URLWithString:href]
6024 cachePolicy:NSURLRequestUseProtocolCachePolicy
daf7f6e2 6025 timeoutInterval:120.0
faf4eb4f
JF
6026 ];
6027
6028 [request setHTTPMethod:method];
6029
6932575e
JF
6030 if (Machine_ != NULL)
6031 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
daf7f6e2
JF
6032 if (UniqueID_ != nil)
6033 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6932575e
JF
6034 if (Role_ != nil)
6035 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6036
faf4eb4f
JF
6037 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6038}
6039
1ba930a4
GP
6040- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6041 NSString *context([alert context]);
a5dd312c
JF
6042
6043 if ([context isEqualToString:@"source"]) {
faf4eb4f
JF
6044 switch (button) {
6045 case 1: {
1ba930a4 6046 NSString *href = [[alert textField] text];
faf4eb4f
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
3d3f4666 6056 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
faf4eb4f
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
3d3f4666 6061 cydia_ = false;
faf4eb4f 6062
7398a389 6063 hud_ = [[delegate_ addProgressHUD] retain];
61b13cae 6064 [hud_ setText:UCLocalize("VERIFYING_URL")];
faf4eb4f
JF
6065 } break;
6066
1ba930a4 6067 case 0:
faf4eb4f
JF
6068 break;
6069
6981ccdf 6070 _nodefault
faf4eb4f
JF
6071 }
6072
1ba930a4 6073 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b7adefda 6074 } else if ([context isEqualToString:@"trivial"])
1ba930a4 6075 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b7adefda 6076 else if ([context isEqualToString:@"urlerror"])
1ba930a4 6077 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b4dff19a
JF
6078 else if ([context isEqualToString:@"warning"]) {
6079 switch (button) {
6080 case 1:
6081 [self complete];
6082 break;
6083
1ba930a4 6084 case 0:
b4dff19a
JF
6085 break;
6086
6981ccdf 6087 _nodefault
b4dff19a
JF
6088 }
6089
7b00c562
JF
6090 [href_ release];
6091 href_ = nil;
6092
1ba930a4 6093 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b4dff19a 6094 }
faf4eb4f
JF
6095}
6096
9ae52960
GP
6097- (id) initWithDatabase:(Database *)database {
6098 if ((self = [super init]) != nil) {
6099 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6100 [self updateButtonsForEditingStatus:NO animated:NO];
f99f86e2 6101
faf4eb4f
JF
6102 database_ = database;
6103 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6104
9ae52960 6105 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
d3bef7bc 6106 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9ae52960 6107 [[self view] addSubview:list_];
d3bef7bc 6108
faf4eb4f 6109 [list_ setDataSource:self];
d4a9ec10 6110 [list_ setDelegate:self];
faf4eb4f
JF
6111
6112 [self reloadData];
6113 } return self;
6114}
6115
6116- (void) reloadData {
6117 pkgSourceList list;
6981ccdf
JF
6118 if (!list.ReadMainList())
6119 return;
faf4eb4f
JF
6120
6121 [sources_ removeAllObjects];
6122 [sources_ addObjectsFromArray:[database_ sources]];
f159ecd4 6123 _trace();
faf4eb4f 6124 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
f159ecd4 6125 _trace();
faf4eb4f 6126
9ae52960 6127 int count([sources_ count]);
d4a9ec10
GP
6128 offset_ = 0;
6129 for (int i = 0; i != count; i++) {
9ae52960
GP
6130 if ([[sources_ objectAtIndex:i] record] == nil) break;
6131 else offset_++;
faf4eb4f
JF
6132 }
6133
d4a9ec10 6134 [list_ setEditing:NO];
9ae52960 6135 [self updateButtonsForEditingStatus:NO animated:NO];
faf4eb4f
JF
6136 [list_ reloadData];
6137}
6138
9ae52960 6139- (void) addButtonClicked {
f441e717 6140 /*[book_ pushPage:[[[AddSourceController alloc]
faf4eb4f
JF
6141 initWithBook:book_
6142 database:database_
6143 ] autorelease]];*/
6144
1ba930a4 6145 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 6146 initWithTitle:UCLocalize("ENTER_APT_URL")
9ae52960
GP
6147 message:nil
6148 delegate:self
6149 cancelButtonTitle:UCLocalize("CANCEL")
6150 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
faf4eb4f
JF
6151 ] autorelease];
6152
9ae52960
GP
6153 [alert setContext:@"source"];
6154 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
a5dd312c 6155
1ba930a4
GP
6156 [alert setNumberOfRows:1];
6157 [alert addTextFieldWithValue:@"http://" label:@""];
faf4eb4f 6158
1ba930a4 6159 UITextInputTraits *traits = [[alert textField] textInputTraits];
b7adefda
JF
6160 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6161 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
a5dd312c 6162 [traits setKeyboardType:UIKeyboardTypeURL];
b7adefda
JF
6163 // XXX: UIReturnKeyDone
6164 [traits setReturnKeyType:UIReturnKeyNext];
faf4eb4f 6165
1ba930a4 6166 [alert show];
faf4eb4f
JF
6167}
6168
9ae52960
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];
f99f86e2 6187
ca45de84
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];
faf4eb4f
JF
6202}
6203
9ae52960
GP
6204- (void) editButtonClicked {
6205 [list_ setEditing:![list_ isEditing] animated:YES];
f99f86e2 6206
9ae52960 6207 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
faf4eb4f
JF
6208}
6209
6210@end
6211/* }}} */
6212
f441e717
GP
6213/* Installed Controller {{{ */
6214@interface InstalledController : FilteredPackageController {
5e563e79 6215 BOOL expert_;
faf4eb4f
JF
6216}
6217
9ae52960 6218- (id) initWithDatabase:(Database *)database;
faf4eb4f 6219
1e4922b8
JF
6220- (void) updateRoleButton;
6221- (void) queueStatusDidChange;
6222
faf4eb4f
JF
6223@end
6224
f441e717 6225@implementation InstalledController
faf4eb4f
JF
6226
6227- (void) dealloc {
faf4eb4f
JF
6228 [super dealloc];
6229}
6230
9b62701b 6231- (NSString *) title { return UCLocalize("INSTALLED"); }
87c76914 6232
9ae52960
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];
faf4eb4f
JF
6237 } return self;
6238}
6239
9ae52960
GP
6240#if !AlwaysReload
6241- (void) queueButtonClicked {
6242 [delegate_ queue];
faf4eb4f 6243}
9ae52960 6244#endif
faf4eb4f 6245
9ae52960
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
5e563e79
JF
6260}
6261
9ae52960
GP
6262- (void) reloadData {
6263 [packages_ reloadData];
faf4eb4f
JF
6264}
6265
9ae52960
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];
faf4eb4f
JF
6275}
6276
9ae52960
GP
6277- (void) roleButtonClicked {
6278 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6279 [packages_ reloadData];
6280 expert_ = !expert_;
5e563e79 6281
9ae52960 6282 [self updateRoleButton];
5e563e79
JF
6283}
6284
faf4eb4f
JF
6285- (void) setDelegate:(id)delegate {
6286 [super setDelegate:delegate];
6287 [packages_ setDelegate:delegate];
6288}
6289
6290@end
6291/* }}} */
6292
f441e717
GP
6293/* Home Controller {{{ */
6294@interface HomeController : CYBrowserController {
faf4eb4f
JF
6295}
6296
6297@end
6298
f441e717 6299@implementation HomeController
faf4eb4f 6300
017b2b71
JF
6301- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6302 [super _setMoreHeaders:request];
ba87b4de 6303
017b2b71
JF
6304 if (ChipID_ != nil)
6305 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
5ec44e34
JF
6306 if (UniqueID_ != nil)
6307 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
017b2b71
JF
6308}
6309
9ae52960 6310- (void) aboutButtonClicked {
ba87b4de
JF
6311 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6312
99dc9e91
JF
6313 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6314 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6315 [alert setCancelButtonIndex:0];
faf4eb4f 6316
99dc9e91 6317 [alert setMessage:
daf7f6e2 6318 @"Copyright (C) 2008-2010\n"
faf4eb4f
JF
6319 "Jay Freeman (saurik)\n"
6320 "saurik@saurik.com\n"
991507f3 6321 "http://www.saurik.com/"
faf4eb4f
JF
6322 ];
6323
99dc9e91 6324 [alert show];
faf4eb4f
JF
6325}
6326
9ae52960
GP
6327- (void) viewWillAppear:(BOOL)animated {
6328 [super viewWillAppear:animated];
2ecf1e7f 6329 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
9ae52960
GP
6330}
6331
6332- (void) viewWillDisappear:(BOOL)animated {
6333 [super viewWillDisappear:animated];
2ecf1e7f 6334 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
9ae52960
GP
6335}
6336
6337- (id) init {
6338 if ((self = [super init]) != nil) {
ba87b4de 6339 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
9ae52960
GP
6340 initWithTitle:UCLocalize("ABOUT")
6341 style:UIBarButtonItemStylePlain
6342 target:self
6343 action:@selector(aboutButtonClicked)
ba87b4de 6344 ] autorelease]];
9ae52960 6345 } return self;
faf4eb4f
JF
6346}
6347
6348@end
1bb0d66c 6349/* }}} */
f441e717
GP
6350/* Manage Controller {{{ */
6351@interface ManageController : CYBrowserController {
faf4eb4f
JF
6352}
6353
1e4922b8 6354- (void) queueStatusDidChange;
faf4eb4f
JF
6355@end
6356
f441e717 6357@implementation ManageController
faf4eb4f 6358
9ae52960
GP
6359- (id) init {
6360 if ((self = [super init]) != nil) {
6361 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
f99f86e2 6362
9ae52960
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];
f99f86e2 6371
9ae52960
GP
6372 [self queueStatusDidChange];
6373 } return self;
faf4eb4f
JF
6374}
6375
9ae52960 6376- (void) settingsButtonClicked {
c1edf105 6377 [delegate_ showSettings];
faf4eb4f
JF
6378}
6379
541a556a 6380#if !AlwaysReload
9ae52960
GP
6381- (void) queueButtonClicked {
6382 [delegate_ queue];
3ff1504e
JF
6383}
6384
b38613d7
GP
6385- (void) applyLoadingTitle {
6386 // No "Loading" title.
6387}
6388
6389- (void) applyRightButton {
6390 // No right button.
3ff1504e 6391}
b38613d7 6392#endif
3ff1504e 6393
9ae52960
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];
f99f86e2 6404
9ae52960
GP
6405 [queueItem release];
6406 } else {
6407 [[self navigationItem] setRightBarButtonItem:nil];
6408 }
541a556a 6409#endif
9ae52960 6410}
faf4eb4f 6411
d8d9a65c 6412- (bool) isLoading {
a99d2808
JF
6413 return false;
6414}
6415
faf4eb4f 6416@end
1bb0d66c 6417/* }}} */
faf4eb4f 6418
9ae52960
GP
6419/* Refresh Bar {{{ */
6420@interface RefreshBar : UINavigationBar {
faf4eb4f
JF
6421 UIProgressIndicator *indicator_;
6422 UITextLabel *prompt_;
6423 UIProgressBar *progress_;
87c76914 6424 UINavigationButton *cancel_;
30d83bfe
JF
6425}
6426
30d83bfe 6427@end
30d83bfe 6428
9ae52960 6429@implementation RefreshBar
5ec44e34 6430
ba6cbb36
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];
f99f86e2 6436
ba6cbb36
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];
f99f86e2 6443
ba6cbb36
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];
f99f86e2 6448
ba6cbb36
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];
f99f86e2 6459
ba6cbb36
GP
6460 [self positionViews];
6461}
6462
9ae52960
GP
6463- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6464 if ((self = [super initWithFrame:frame])) {
6465 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
5ec44e34 6466
9ae52960 6467 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
1e4922b8 6468 [self setBarStyle:UIBarStyleBlack];
5ec44e34 6469
1e4922b8
JF
6470 UIBarStyle barstyle([self _barStyle:NO]);
6471 bool ugly(barstyle == UIBarStyleDefault);
f159ecd4
JF
6472
6473 UIProgressIndicatorStyle style = ugly ?
6474 UIProgressIndicatorStyleMediumBrown :
6475 UIProgressIndicatorStyleMediumWhite;
6476
ba6cbb36 6477 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
f159ecd4 6478 [indicator_ setStyle:style];
ba6cbb36 6479 [indicator_ startAnimation];
9ae52960 6480 [self addSubview:indicator_];
f159ecd4 6481
ba6cbb36 6482 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
f159ecd4
JF
6483 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6484 [prompt_ setBackgroundColor:[UIColor clearColor]];
ba6cbb36 6485 [prompt_ setFont:[UIFont systemFontOfSize:15]];
9ae52960 6486 [self addSubview:prompt_];
f159ecd4 6487
ba6cbb36
GP
6488 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6489 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
d3bef7bc 6490 [progress_ setStyle:0];
ba6cbb36 6491 [self addSubview:progress_];
f99f86e2 6492
61b13cae 6493 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
e7a88a8c 6494 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
9ae52960 6495 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
ba6cbb36 6496 [cancel_ setBarStyle:barstyle];
f99f86e2 6497
ba6cbb36 6498 [self positionViews];
f159ecd4
JF
6499 } return self;
6500}
6501
9ae52960 6502- (void) cancel {
f159ecd4
JF
6503 [cancel_ removeFromSuperview];
6504}
6505
9ae52960
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
1e4922b8
JF
6527@class CYNavigationController;
6528
9ae52960 6529/* Cydia Tab Bar Controller {{{ */
e7a88a8c
GP
6530@interface CYTabBarController : UITabBarController {
6531 Database *database_;
9ae52960
GP
6532}
6533
f99f86e2 6534@end
9ae52960
GP
6535
6536@implementation CYTabBarController
6537
e7a88a8c
GP
6538/* XXX: some logic should probably go here related to
6539freeing the view controllers on tab change */
f159ecd4 6540
9ae52960
GP
6541- (void) reloadData {
6542 size_t count([[self viewControllers] count]);
6543 for (size_t i(0); i != count; ++i) {
1e4922b8 6544 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
9ae52960
GP
6545 [page reloadData];
6546 }
6547}
6548
982de8f1 6549- (id) initWithDatabase:(Database *)database {
9ae52960
GP
6550 if ((self = [super init]) != nil) {
6551 database_ = database;
9ae52960
GP
6552 } return self;
6553}
6554
6555@end
6556/* }}} */
6557
6558/* Cydia Navigation Controller {{{ */
1e4922b8 6559@interface CYNavigationController : UINavigationController {
9ae52960 6560 _transient Database *database_;
9b62701b 6561 id<UINavigationControllerDelegate> delegate_;
9ae52960
GP
6562}
6563
6564- (id) initWithDatabase:(Database *)database;
6565- (void) reloadData;
6566
6567@end
6568
6569
6570@implementation CYNavigationController
6571
15b41c77
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
9ae52960
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) {
1e4922b8 6588 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
9ae52960
GP
6589 [page reloadData];
6590 }
6591}
6592
9b62701b 6593- (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
9ae52960
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
f159ecd4
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
a99d2808
JF
6627- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6628 id<NSURLProtocolClient> client([self client]);
6e673d99
JF
6629 if (icon == nil)
6630 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6631 else {
6632 NSData *data(UIImagePNGRepresentation(icon));
a99d2808 6633
6e673d99
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 }
a99d2808
JF
6639}
6640
f159ecd4
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;
6b4b3bee 6665 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
f159ecd4
JF
6666 Package *package([database packageWithName:path]);
6667 if (package == nil)
6668 goto fail;
6b4b3bee 6669 UIImage *icon([package icon]);
a99d2808 6670 [self _returnPNGWithImage:icon forRequest:request];
18159e09
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));
18159e09
JF
6676 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6677 if (icon == nil)
6678 icon = [UIImage applicationImageNamed:@"unknown.png"];
a99d2808
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];
6b4b3bee
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));
6b4b3bee
JF
6691 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6692 if (icon == nil)
6693 icon = [UIImage applicationImageNamed:@"unknown.png"];
a99d2808 6694 [self _returnPNGWithImage:icon forRequest:request];
f159ecd4
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
f441e717 6706/* Sections Controller {{{ */
1e4922b8
JF
6707@interface SectionsController : CYViewController <
6708 UITableViewDataSource,
6709 UITableViewDelegate
6710> {
f159ecd4
JF
6711 _transient Database *database_;
6712 NSMutableArray *sections_;
6713 NSMutableArray *filtered_;
d4a9ec10 6714 UITableView *list_;
f159ecd4
JF
6715 UIView *accessory_;
6716 BOOL editing_;
6717}
6718
9ae52960 6719- (id) initWithDatabase:(Database *)database;
f159ecd4
JF
6720- (void) reloadData;
6721- (void) resetView;
6722
1e4922b8
JF
6723- (void) editButtonClicked;
6724
f159ecd4
JF
6725@end
6726
f441e717 6727@implementation SectionsController
f159ecd4
JF
6728
6729- (void) dealloc {
6730 [list_ setDataSource:nil];
6731 [list_ setDelegate:nil];
6732
6733 [sections_ release];
6734 [filtered_ release];
f159ecd4
JF
6735 [list_ release];
6736 [accessory_ release];
6737 [super dealloc];
6738}
6739
9ae52960
GP
6740- (void) viewDidAppear:(BOOL)animated {
6741 [super viewDidAppear:animated];
6742 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6743}
6744
d4a9ec10
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;
f159ecd4
JF
6748}
6749
9b62701b 6750- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
d4a9ec10 6751 return editing_ ? [sections_ count] : [filtered_ count] + 1;
f159ecd4
JF
6752}
6753
2064d251
GP
6754/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6755 return 45.0f;
6756}*/
f159ecd4 6757
d4a9ec10 6758- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9ae52960
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];
d4a9ec10 6763 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
f159ecd4 6764
d4a9ec10 6765 return cell;
f159ecd4
JF
6766}
6767
d4a9ec10 6768- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
864db79b
JF
6769 if (editing_)
6770 return;
d1e1aaab 6771
864db79b 6772 Section *section = [self sectionAtIndexPath:indexPath];
d4a9ec10 6773 NSString *name = [section name];
f159ecd4
JF
6774 NSString *title;
6775
d4a9ec10 6776 if ([indexPath row] == 0) {
f159ecd4
JF
6777 section = nil;
6778 name = nil;
61b13cae 6779 title = UCLocalize("ALL_PACKAGES");
f159ecd4 6780 } else {
ca06bb0e
JF
6781 if (name != nil) {
6782 name = [NSString stringWithString:name];
6932575e 6783 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
ca06bb0e 6784 } else {
f159ecd4 6785 name = @"";
61b13cae 6786 title = UCLocalize("NO_SECTION");
f159ecd4
JF
6787 }
6788 }
6789
f441e717 6790 FilteredPackageController *table = [[[FilteredPackageController alloc]
9ae52960 6791 initWithDatabase:database_
f159ecd4 6792 title:title
6981ccdf 6793 filter:@selector(isVisibleInSection:)
f159ecd4
JF
6794 with:name
6795 ] autorelease];
6796
6797 [table setDelegate:delegate_];
6798
9ae52960 6799 [[self navigationController] pushViewController:table animated:YES];
f159ecd4
JF
6800}
6801
9b62701b 6802- (NSString *) title { return UCLocalize("SECTIONS"); }
9ae52960
GP
6803
6804- (id) initWithDatabase:(Database *)database {
6805 if ((self = [super init]) != nil) {
f159ecd4
JF
6806 database_ = database;
6807
9ae52960
GP
6808 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6809
f159ecd4
JF
6810 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6811 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6812
9ae52960 6813 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
d3bef7bc 6814 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
2064d251 6815 [list_ setRowHeight:45.0f];
9ae52960 6816 [[self view] addSubview:list_];
f159ecd4 6817
d4a9ec10 6818 [list_ setDataSource:self];
9ae52960 6819 [list_ setDelegate:self];
f159ecd4
JF
6820
6821 [self reloadData];
f159ecd4
JF
6822 } return self;
6823}
6824
6825- (void) reloadData {
6826 NSArray *packages = [database_ packages];
6827
6828 [sections_ removeAllObjects];
6829 [filtered_ removeAllObjects];
6830
6932575e
JF
6831#if 0
6832 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6833 SectionMap sections;
6834 sections.resize(64);
6835#else
6836 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6837#endif
f159ecd4
JF
6838
6839 _trace();
9fdd37d0 6840 for (Package *package in packages) {
f159ecd4 6841 NSString *name([package section]);
6932575e 6842 NSString *key(name == nil ? @"" : name);
f159ecd4 6843
6932575e
JF
6844#if 0
6845 Section **section;
6846
6847 _profile(SectionsView$reloadData$Section)
6848 section = &sections[key];
6849 if (*section == nil) {
6850 _profile(SectionsView$reloadData$Section$Allocate)
9ee296df 6851 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6932575e
JF
6852 _end
6853 }
6854 _end
6855
6856 [*section addToCount];
6857
6858 _profile(SectionsView$reloadData$Filter)
6981ccdf 6859 if (![package valid] || ![package visible])
6932575e
JF
6860 continue;
6861 _end
6862
6863 [*section addToRow];
6864#else
6865 Section *section;
6866
6867 _profile(SectionsView$reloadData$Section)
6868 section = [sections objectForKey:key];
f159ecd4 6869 if (section == nil) {
6932575e 6870 _profile(SectionsView$reloadData$Section$Allocate)
9ee296df 6871 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6932575e
JF
6872 [sections setObject:section forKey:key];
6873 _end
f159ecd4 6874 }
6932575e
JF
6875 _end
6876
6877 [section addToCount];
fa7bb92f 6878
6932575e 6879 _profile(SectionsView$reloadData$Filter)
6981ccdf 6880 if (![package valid] || ![package visible])
6932575e
JF
6881 continue;
6882 _end
6883
6884 [section addToRow];
6885#endif
686e302f 6886 }
f159ecd4 6887 _trace();
a75f53e7 6888
6932575e
JF
6889#if 0
6890 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6891 [sections_ addObject:i->second];
6892#else
fa7bb92f 6893 [sections_ addObjectsFromArray:[sections allValues]];
6932575e 6894#endif
fa7bb92f 6895
43b742af 6896 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
a75f53e7 6897
6932575e
JF
6898 for (Section *section in sections_) {
6899 size_t count([section row]);
43b742af 6900 if (count == 0)
6932575e 6901 continue;
a75f53e7 6902
9ee296df 6903 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6932575e
JF
6904 [section setCount:count];
6905 [filtered_ addObject:section];
686e302f 6906 }
4941f41d 6907
9ae52960
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 ];
84aa0f36 6914 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
9ae52960
GP
6915 [rightItem release];
6916
686e302f 6917 [list_ reloadData];
f159ecd4 6918 _trace();
e057ec05 6919}
4941f41d 6920
fa7bb92f
JF
6921- (void) resetView {
6922 if (editing_)
9ae52960 6923 [self editButtonClicked];
e057ec05 6924}
4941f41d 6925
9ae52960 6926- (void) editButtonClicked {
fa7bb92f
JF
6927 if ((editing_ = !editing_))
6928 [list_ reloadData];
f159ecd4 6929 else
fa7bb92f 6930 [delegate_ updateData];
f99f86e2 6931
9ae52960
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];
87c76914
JF
6935}
6936
9e07091a
JF
6937- (UIView *) accessoryView {
6938 return accessory_;
6939}
6940
a75f53e7 6941@end
4941f41d 6942/* }}} */
f441e717 6943/* Changes Controller {{{ */
1e4922b8
JF
6944@interface ChangesController : CYViewController <
6945 UITableViewDataSource,
6946 UITableViewDelegate
6947> {
e057ec05 6948 _transient Database *database_;
a75f53e7
JF
6949 NSMutableArray *packages_;
6950 NSMutableArray *sections_;
5d8f1006 6951 UITableView *list_;
e057ec05 6952 unsigned upgrades_;
77a4e323 6953 BOOL hasSentFirstLoad_;
a75f53e7
JF
6954}
6955
9ae52960 6956- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
e057ec05 6957- (void) reloadData;
a75f53e7 6958
a75f53e7
JF
6959@end
6960
f441e717 6961@implementation ChangesController
686e302f
JF
6962
6963- (void) dealloc {
5d8f1006 6964 [list_ setDelegate:nil];
e057ec05
JF
6965 [list_ setDataSource:nil];
6966
686e302f
JF
6967 [packages_ release];
6968 [sections_ release];
e057ec05 6969 [list_ release];
686e302f
JF
6970 [super dealloc];
6971}
a75f53e7 6972
9ae52960
GP
6973- (void) viewDidAppear:(BOOL)animated {
6974 [super viewDidAppear:animated];
77a4e323
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 }
9ae52960
GP
6981}
6982
5d8f1006
JF
6983- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6984 NSInteger count([sections_ count]);
6985 return count == 0 ? 1 : count;
a75f53e7
JF
6986}
6987
5d8f1006
JF
6988- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6989 if ([sections_ count] == 0)
6990 return nil;
a75f53e7
JF
6991 return [[sections_ objectAtIndex:section] name];
6992}
6993
5d8f1006
JF
6994- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6995 if ([sections_ count] == 0)
6996 return 0;
6997 return [[sections_ objectAtIndex:section] count];
a75f53e7
JF
6998}
6999
5d8f1006
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)];
a75f53e7
JF
7004}
7005
5d8f1006 7006- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
1e4922b8 7007 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5d8f1006
JF
7008 if (cell == nil)
7009 cell = [[[PackageCell alloc] init] autorelease];
7010 [cell setPackage:[self packageAtIndexPath:path]];
7011 return cell;
a75f53e7
JF
7012}
7013
2064d251 7014/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5d8f1006 7015 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
2064d251 7016}*/
a75f53e7 7017
5d8f1006
JF
7018- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7019 Package *package([self packageAtIndexPath:path]);
f441e717 7020 PackageController *view([delegate_ packageController]);
e057ec05
JF
7021 [view setDelegate:delegate_];
7022 [view setPackage:package];
9ae52960 7023 [[self navigationController] pushViewController:view animated:YES];
5d8f1006 7024 return path;
a75f53e7
JF
7025}
7026
9ae52960 7027- (void) refreshButtonClicked {
1e4922b8 7028 [delegate_ beginUpdate];
24966c5d 7029 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
b7eb9e84
JF
7030}
7031
9ae52960 7032- (void) upgradeButtonClicked {
e057ec05 7033 [delegate_ distUpgrade];
a75f53e7
JF
7034}
7035
9b62701b 7036- (NSString *) title { return UCLocalize("CHANGES"); }
9ae52960
GP
7037
7038- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7039 if ((self = [super init]) != nil) {
e057ec05 7040 database_ = database;
9ae52960 7041 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
a75f53e7 7042
686e302f
JF
7043 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7044 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
a75f53e7 7045
9ae52960 7046 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
d3bef7bc 7047 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
2064d251 7048 [list_ setRowHeight:73.0f];
9ae52960 7049 [[self view] addSubview:list_];
e057ec05 7050
686e302f 7051 [list_ setDataSource:self];
5d8f1006 7052 [list_ setDelegate:self];
a75f53e7 7053
daf7f6e2 7054 delegate_ = delegate;
a75f53e7
JF
7055 } return self;
7056}
7057
daf7f6e2 7058- (void) _reloadPackages:(NSArray *)packages {
f159ecd4 7059 _trace();
9fdd37d0 7060 for (Package *package in packages)
fa7bb92f 7061 if (
b4c4fac4 7062 [package uninstalled] && [package valid] && [package visible] ||
6e673d99 7063 [package upgradableAndEssential:YES]
fa7bb92f 7064 )
686e302f 7065 [packages_ addObject:package];
4941f41d 7066
f159ecd4 7067 _trace();
dd9390c5 7068 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
f159ecd4 7069 _trace();
daf7f6e2
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"];
7081 NSLog(@"HUD:%@::%@", delegate_, hud);
7082 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7083 [delegate_ removeProgressHUD:hud];
a75f53e7 7084
61b13cae
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];
a75f53e7 7087 Section *section = nil;
f159ecd4 7088 NSDate *last = nil;
686e302f 7089
e057ec05
JF
7090 upgrades_ = 0;
7091 bool unseens = false;
7092
43b742af 7093 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
e057ec05 7094
a75f53e7
JF
7095 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7096 Package *package = [packages_ objectAtIndex:offset];
a75f53e7 7097
43b742af 7098 BOOL uae = [package upgradableAndEssential:YES];
6932575e
JF
7099
7100 if (!uae) {
e057ec05 7101 unseens = true;
6932575e 7102 NSDate *seen;
a75f53e7 7103
f441e717 7104 _profile(ChangesController$reloadData$Remember)
6932575e
JF
7105 seen = [package seen];
7106 _end
7107
43b742af 7108 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
f159ecd4 7109 last = seen;
138ae18d 7110
3ff1504e
JF
7111 NSString *name;
7112 if (seen == nil)
61b13cae 7113 name = UCLocalize("UNKNOWN");
3ff1504e 7114 else {
43b742af 7115 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
3ff1504e
JF
7116 [name autorelease];
7117 }
7118
f441e717 7119 _profile(ChangesController$reloadData$Allocate)
61b13cae 7120 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
9ee296df 7121 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6932575e
JF
7122 [sections_ addObject:section];
7123 _end
686e302f
JF
7124 }
7125
e057ec05 7126 [section addToCount];
f159ecd4
JF
7127 } else if ([package ignored])
7128 [ignored addToCount];
7129 else {
7130 ++upgrades_;
7131 [upgradable addToCount];
686e302f 7132 }
a75f53e7 7133 }
f159ecd4 7134 _trace();
a75f53e7 7135
e057ec05 7136 CFRelease(formatter);
686e302f 7137
e057ec05
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 }
a75f53e7 7144
f159ecd4
JF
7145 if ([ignored count] != 0)
7146 [sections_ insertObject:ignored atIndex:0];
e057ec05
JF
7147 if (upgrades_ != 0)
7148 [sections_ insertObject:upgradable atIndex:0];
d12c6e70 7149
e057ec05 7150 [list_ reloadData];
2d28b35a 7151
9ae52960
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 ];
1e4922b8 7167 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
9ae52960 7168 [leftItem release];
b6ffa083
JF
7169}
7170
2d28b35a
JF
7171@end
7172/* }}} */
f441e717 7173/* Search Controller {{{ */
1e4922b8
JF
7174@interface SearchController : FilteredPackageController <
7175 UISearchBarDelegate
7176> {
7177 UISearchBar *search_;
e057ec05 7178}
686e302f 7179
9ae52960 7180- (id) initWithDatabase:(Database *)database;
e057ec05 7181- (void) reloadData;
686e302f 7182
2d28b35a
JF
7183@end
7184
f441e717 7185@implementation SearchController
2d28b35a 7186
686e302f 7187- (void) dealloc {
9ae52960 7188 [search_ release];
e057ec05 7189 [super dealloc];
686e302f
JF
7190}
7191
9b62701b 7192- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
9ae52960
GP
7193 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7194 [search_ resignFirstResponder];
5ec44e34 7195 [self reloadData];
e057ec05 7196}
686e302f 7197
9b62701b 7198- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
9ae52960 7199 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
5ec44e34 7200 [self reloadData];
e057ec05 7201}
686e302f 7202
9b62701b 7203- (NSString *) title { return nil; }
59efd93a 7204
9ae52960 7205- (id) initWithDatabase:(Database *)database {
2c4fc6f1
RP
7206 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7207}
7208
7209- (void)viewDidAppear:(BOOL)animated {
f99f86e2
JF
7210 [super viewDidAppear:animated];
7211 if (!search_) {
1e4922b8 7212 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
2c4fc6f1 7213 [search_ layoutSubviews];
9ae52960 7214 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
2c4fc6f1
RP
7215 UITextField *textField = [search_ searchField];
7216 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9ae52960 7217 [search_ setDelegate:self];
2c4fc6f1
RP
7218 [textField setEnablesReturnKeyAutomatically:NO];
7219 [[self navigationItem] setTitleView:textField];
7220 }
2d28b35a
JF
7221}
7222
f159ecd4
JF
7223- (void) _reloadData {
7224}
686e302f 7225
f159ecd4 7226- (void) reloadData {
f441e717 7227 _profile(SearchController$reloadData)
9ae52960 7228 [packages_ reloadData];
3bddda52
JF
7229 _end
7230 PrintTimes();
9ae52960 7231 [packages_ resetCursor];
f159ecd4 7232}
b6ffa083 7233
583b5809
RP
7234- (void) didSelectPackage:(Package *)package {
7235 [search_ resignFirstResponder];
7236 [super didSelectPackage:package];
7237}
7238
f159ecd4
JF
7239@end
7240/* }}} */
f441e717 7241/* Settings Controller {{{ */
1e4922b8
JF
7242@interface SettingsController : CYViewController <
7243 UITableViewDataSource,
7244 UITableViewDelegate
7245> {
f159ecd4
JF
7246 _transient Database *database_;
7247 NSString *name_;
7248 Package *package_;
31a8e05a
GP
7249 UITableView *table_;
7250 id subscribedSwitch_;
7251 id ignoredSwitch_;
7252 UITableViewCell *subscribedCell_;
7253 UITableViewCell *ignoredCell_;
f159ecd4 7254}
686e302f 7255
9ae52960 7256- (id) initWithDatabase:(Database *)database package:(NSString *)package;
686e302f 7257
f159ecd4 7258@end
686e302f 7259
f441e717 7260@implementation SettingsController
686e302f 7261
f159ecd4 7262- (void) dealloc {
f159ecd4
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];
f99f86e2 7271
f159ecd4
JF
7272 [super dealloc];
7273}
686e302f 7274
31a8e05a 7275- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
f159ecd4
JF
7276 if (package_ == nil)
7277 return 0;
686e302f 7278
31a8e05a 7279 return 1;
2d28b35a
JF
7280}
7281
31a8e05a 7282- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
f159ecd4
JF
7283 if (package_ == nil)
7284 return 0;
a75f53e7 7285
31a8e05a
GP
7286 return 1;
7287}
87c76914 7288
31a8e05a
GP
7289- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7290 return UCLocalize("SHOW_ALL_CHANGES_EX");
e057ec05 7291}
686e302f 7292
31a8e05a 7293- (void) onSomething:(BOOL)value withKey:(NSString *)key {
f159ecd4
JF
7294 if (package_ == nil)
7295 return;
686e302f 7296
f159ecd4 7297 NSMutableDictionary *metadata([package_ metadata]);
87c76914 7298
f159ecd4
JF
7299 BOOL before;
7300 if (NSNumber *number = [metadata objectForKey:key])
7301 before = [number boolValue];
7302 else
7303 before = NO;
e057ec05 7304
f159ecd4
JF
7305 if (value != before) {
7306 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7307 Changed_ = true;
f159ecd4
JF
7308 [delegate_ updateData];
7309 }
87c76914
JF
7310}
7311
31a8e05a
GP
7312- (void) onSubscribed:(id)control {
7313 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
e057ec05 7314}
686e302f 7315
31a8e05a
GP
7316- (void) onIgnored:(id)control {
7317 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
b6ffa083
JF
7318}
7319
31a8e05a 7320- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
f159ecd4
JF
7321 if (package_ == nil)
7322 return nil;
dbe0f181 7323
31a8e05a
GP
7324 switch ([indexPath row]) {
7325 case 0: return subscribedCell_;
7326 case 1: return ignoredCell_;
f99f86e2 7327
6981ccdf 7328 _nodefault
f159ecd4 7329 }
dbe0f181 7330
f159ecd4 7331 return nil;
dbe0f181
JF
7332}
7333
9b62701b 7334- (NSString *) title { return UCLocalize("SETTINGS"); }
9ae52960
GP
7335
7336- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7337 if ((self = [super init])) {
f159ecd4
JF
7338 database_ = database;
7339 name_ = [package retain];
dbe0f181 7340
9ae52960
GP
7341 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7342
31a8e05a
GP
7343 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7344 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9ae52960 7345 [[self view] addSubview:table_];
dbe0f181 7346
31a8e05a
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];
dbe0f181 7350
31a8e05a
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];
dbe0f181 7354
31a8e05a
GP
7355 subscribedCell_ = [[UITableViewCell alloc] init];
7356 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7357 [subscribedCell_ setAccessoryView:subscribedSwitch_];
ced7fc60 7358 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
dbe0f181 7359
31a8e05a
GP
7360 ignoredCell_ = [[UITableViewCell alloc] init];
7361 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7362 [ignoredCell_ setAccessoryView:ignoredSwitch_];
ced7fc60 7363 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
dbe0f181 7364
f159ecd4 7365 [table_ setDataSource:self];
31a8e05a 7366 [table_ setDelegate:self];
f159ecd4
JF
7367 [self reloadData];
7368 } return self;
7369}
dbe0f181 7370
f159ecd4
JF
7371- (void) reloadData {
7372 if (package_ != nil)
7373 [package_ autorelease];
7374 package_ = [database_ packageWithName:name_];
7375 if (package_ != nil) {
7376 [package_ retain];
31a8e05a
GP
7377 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7378 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
dbe0f181 7379 }
f159ecd4
JF
7380
7381 [table_ reloadData];
dbe0f181
JF
7382}
7383
dbe0f181 7384@end
017b2b71 7385/* }}} */
dbe0f181 7386
f441e717
GP
7387/* Signature Controller {{{ */
7388@interface SignatureController : CYBrowserController {
dbe0f181
JF
7389 _transient Database *database_;
7390 NSString *package_;
7391}
7392
9ae52960 7393- (id) initWithDatabase:(Database *)database package:(NSString *)package;
dbe0f181
JF
7394
7395@end
7396
f441e717 7397@implementation SignatureController
dbe0f181
JF
7398
7399- (void) dealloc {
7400 [package_ release];
7401 [super dealloc];
7402}
7403
c2292b80 7404- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
dbe0f181 7405 // XXX: dude!
c2292b80 7406 [super webView:view didClearWindowObject:window forFrame:frame];
dbe0f181
JF
7407}
7408
9ae52960
GP
7409- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7410 if ((self = [super init]) != nil) {
dbe0f181
JF
7411 database_ = database;
7412 package_ = [package retain];
7413 [self reloadData];
7414 } return self;
7415}
7416
7417- (void) reloadData {
7418 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7419}
7420
c1edf105
GP
7421@end
7422/* }}} */
7423/* Role Controller {{{ */
1e4922b8
JF
7424@interface RoleController : CYViewController <
7425 UITableViewDataSource,
7426 UITableViewDelegate
7427> {
c1edf105
GP
7428 _transient Database *database_;
7429 id roledelegate_;
7430 UITableView *table_;
7431 UISegmentedControl *segment_;
7432 UIView *container_;
7433}
1e4922b8
JF
7434
7435- (void) showDoneButton;
7436- (void) resizeSegmentedControl;
7437
c1edf105
GP
7438@end
7439
7440@implementation RoleController
7441- (void) dealloc {
7442 [table_ release];
7443 [segment_ release];
7444 [container_ release];
f99f86e2 7445
c1edf105
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;
f99f86e2 7453
c1edf105 7454 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
f99f86e2 7455
c1edf105 7456 NSArray *items = [NSArray arrayWithObjects:
f99f86e2 7457 UCLocalize("USER"),
c1edf105
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_];
f99f86e2 7464
c1edf105
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 }
f99f86e2 7473
c1edf105 7474 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
62d55799 7475 [self resizeSegmentedControl];
f99f86e2 7476
c1edf105
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
62d55799
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
ca45de84
GP
7491- (void) viewWillAppear:(BOOL)animated {
7492 [super viewWillAppear:animated];
f99f86e2 7493
62d55799
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];
ca45de84
GP
7503}
7504
c1edf105 7505- (void) save {
90e9a238 7506 NSString *role(nil);
f99f86e2 7507
c1edf105 7508 switch ([segment_ selectedSegmentIndex]) {
fabc4a01
GP
7509 case 0: role = @"User"; break;
7510 case 1: role = @"Hacker"; break;
7511 case 2: role = @"Developer"; break;
c1edf105
GP
7512
7513 _nodefault
7514 }
7515
fabc4a01 7516 if (![role isEqualToString:Role_]) {
90e9a238 7517 bool rolling(Role_ == nil);
fabc4a01 7518 Role_ = role;
f99f86e2 7519
fabc4a01
GP
7520 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7521 Role_, @"Role",
7522 nil];
c1edf105 7523
fabc4a01 7524 [Metadata_ setObject:Settings_ forKey:@"Settings"];
c1edf105 7525
fabc4a01 7526 Changed_ = true;
f99f86e2 7527
90e9a238
JF
7528 if (rolling)
7529 [roledelegate_ loadData];
7530 else
7531 [roledelegate_ updateData];
fabc4a01 7532 }
c1edf105
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 {
62d55799
GP
7556 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7557 return 6;
c1edf105
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 {
f99f86e2 7569 if (section == 1)
c1edf105 7570 return UCLocalize("ROLE_EX");
f99f86e2 7571 if (section == 4)
c1edf105
GP
7572 return [NSString stringWithFormat:
7573 @"%@: %@\n%@: %@\n%@: %@",
f99f86e2
JF
7574 UCLocalize("USER"), UCLocalize("USER_EX"),
7575 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
c1edf105
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
dbe0f181 7591@end
f159ecd4 7592/* }}} */
dbe0f181 7593
e7a88a8c
GP
7594/* Cydia Container {{{ */
7595@interface CYContainer : UIViewController <ProgressDelegate> {
7596 _transient Database *database_;
7597 RefreshBar *refreshbar_;
7598
7599 bool dropped_;
7600 bool updating_;
7601 id updatedelegate_;
1e4922b8 7602 UITabBarController *root_;
e7a88a8c
GP
7603}
7604
1e4922b8
JF
7605- (void) setTabBarController:(UITabBarController *)controller;
7606
7607- (void) dropBar:(BOOL)animated;
7608- (void) beginUpdate;
7609- (void) raiseBar:(BOOL)animated;
57fde81f 7610- (BOOL) updating;
1e4922b8 7611
e7a88a8c
GP
7612@end
7613
7614@implementation CYContainer
7615
57fde81f
GP
7616- (BOOL) _reallyWantsFullScreenLayout {
7617 return YES;
7618}
7619
15b41c77
GP
7620// NOTE: UIWindow only sends the top controller these messages,
7621// So we have to forward them on.
7622
7623- (void) viewDidAppear:(BOOL)animated {
7624 [super viewDidAppear:animated];
7625 [root_ viewDidAppear:animated];
7626}
7627
7628- (void) viewWillAppear:(BOOL)animated {
7629 [super viewWillAppear:animated];
7630 [root_ viewWillAppear:animated];
7631}
7632
7633- (void) viewDidDisappear:(BOOL)animated {
7634 [super viewDidDisappear:animated];
7635 [root_ viewDidDisappear:animated];
7636}
7637
7638- (void) viewWillDisappear:(BOOL)animated {
7639 [super viewWillDisappear:animated];
7640 [root_ viewWillDisappear:animated];
7641}
7642
e7a88a8c 7643- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
3ac13a9d 7644 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
e7a88a8c
GP
7645}
7646
1e4922b8 7647- (void) setTabBarController:(UITabBarController *)controller {
e7a88a8c
GP
7648 root_ = controller;
7649 [[self view] addSubview:[root_ view]];
7650}
7651
7652- (void) setUpdate:(NSDate *)date {
7653 [self beginUpdate];
7654}
7655
7656- (void) beginUpdate {
7657 [self dropBar:YES];
7658 [refreshbar_ start];
f99f86e2 7659
e7a88a8c 7660 updating_ = true;
f99f86e2 7661
e7a88a8c
GP
7662 [NSThread
7663 detachNewThreadSelector:@selector(performUpdate)
7664 toTarget:self
7665 withObject:nil
7666 ];
7667}
7668
7669- (void) performUpdate { _pooled
7670 Status status;
7671 status.setDelegate(self);
7672 [database_ updateWithStatus:status];
7673
7674 [self
7675 performSelectorOnMainThread:@selector(completeUpdate)
7676 withObject:nil
7677 waitUntilDone:NO
7678 ];
7679}
7680
7681- (void) completeUpdate {
24966c5d 7682 if (!updating_) return;
e7a88a8c 7683 updating_ = false;
f99f86e2 7684
e7a88a8c
GP
7685 [self raiseBar:YES];
7686 [refreshbar_ stop];
7687 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7688}
7689
7690- (void) cancelUpdate {
24966c5d
GP
7691 updating_ = false;
7692 [self raiseBar:YES];
7693 [refreshbar_ stop];
7694 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
e7a88a8c
GP
7695}
7696
7697- (void) cancelPressed {
7698 [self cancelUpdate];
7699}
7700
7701- (BOOL) updating {
7702 return updating_;
7703}
7704
7705- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7706 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7707}
7708
7709- (void) startProgress {
7710}
7711
7712- (void) setProgressTitle:(NSString *)title {
7713 [self
7714 performSelectorOnMainThread:@selector(_setProgressTitle:)
7715 withObject:title
7716 waitUntilDone:YES
7717 ];
7718}
7719
7720- (bool) isCancelling:(size_t)received {
7721 return !updating_;
7722}
7723
7724- (void) setProgressPercent:(float)percent {
7725 [self
7726 performSelectorOnMainThread:@selector(_setProgressPercent:)
7727 withObject:[NSNumber numberWithFloat:percent]
7728 waitUntilDone:YES
7729 ];
7730}
7731
7732- (void) addProgressOutput:(NSString *)output {
7733 [self
7734 performSelectorOnMainThread:@selector(_addProgressOutput:)
7735 withObject:output
7736 waitUntilDone:YES
7737 ];
7738}
7739
7740- (void) _setProgressTitle:(NSString *)title {
7741 [refreshbar_ setPrompt:title];
7742}
7743
7744- (void) _setProgressPercent:(NSNumber *)percent {
7745 [refreshbar_ setProgress:[percent floatValue]];
7746}
7747
7748- (void) _addProgressOutput:(NSString *)output {
7749}
7750
7751- (void) setUpdateDelegate:(id)delegate {
7752 updatedelegate_ = delegate;
7753}
7754
149ed89e
GP
7755- (CGFloat) statusBarHeight {
7756 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7757 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7758 } else {
7759 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7760 }
7761}
7762
e7a88a8c
GP
7763- (void) dropBar:(BOOL)animated {
7764 if (dropped_) return;
7765 dropped_ = true;
7766
7767 [[self view] addSubview:refreshbar_];
7768
149ed89e 7769 CGFloat sboffset = [self statusBarHeight];
57fde81f 7770
283fc596 7771 CGRect barframe = [refreshbar_ frame];
57fde81f
GP
7772 barframe.origin.y = sboffset;
7773 [refreshbar_ setFrame:barframe];
7774
e7a88a8c 7775 if (animated) [UIView beginAnimations:nil context:NULL];
e7a88a8c 7776 CGRect viewframe = [[root_ view] frame];
57fde81f
GP
7777 viewframe.origin.y += barframe.size.height + sboffset;
7778 viewframe.size.height -= barframe.size.height + sboffset;
e7a88a8c
GP
7779 [[root_ view] setFrame:viewframe];
7780 if (animated) [UIView commitAnimations];
7781
15b41c77
GP
7782 // Ensure bar has the proper width for our view, it might have changed
7783 barframe.size.width = viewframe.size.width;
7784 [refreshbar_ setFrame:barframe];
7785
e7a88a8c
GP
7786 // XXX: fix Apple's layout bug
7787 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7788}
7789
7790- (void) raiseBar:(BOOL)animated {
7791 if (!dropped_) return;
7792 dropped_ = false;
7793
7794 [refreshbar_ removeFromSuperview];
7795
283fc596 7796 CGFloat sboffset = [self statusBarHeight];
57fde81f 7797
e7a88a8c
GP
7798 if (animated) [UIView beginAnimations:nil context:NULL];
7799 CGRect barframe = [refreshbar_ frame];
7800 CGRect viewframe = [[root_ view] frame];
57fde81f
GP
7801 viewframe.origin.y -= barframe.size.height + sboffset;
7802 viewframe.size.height += barframe.size.height + sboffset;
e7a88a8c
GP
7803 [[root_ view] setFrame:viewframe];
7804 if (animated) [UIView commitAnimations];
7805
7806 // XXX: fix Apple's layout bug
7807 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7808}
7809
62d55799 7810- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
d6011e10
RP
7811 // XXX: fix Apple's layout bug
7812 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7813}
7814
15b41c77 7815- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
e7a88a8c
GP
7816 if (dropped_) {
7817 [self raiseBar:NO];
7818 [self dropBar:NO];
7819 }
f99f86e2 7820
e7a88a8c
GP
7821 // XXX: fix Apple's layout bug
7822 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7823}
7824
57fde81f
GP
7825- (void) statusBarFrameChanged:(NSNotification *)notification {
7826 if (dropped_) {
7827 [self raiseBar:NO];
7828 [self dropBar:NO];
7829 }
7830}
7831
e7a88a8c
GP
7832- (void) dealloc {
7833 [refreshbar_ release];
57fde81f 7834 [[NSNotificationCenter defaultCenter] removeObserver:self];
e7a88a8c
GP
7835 [super dealloc];
7836}
7837
d5653f96 7838- (id) initWithDatabase:(Database *)database {
e7a88a8c
GP
7839 if ((self = [super init]) != nil) {
7840 database_ = database;
7841
15b41c77 7842 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
57fde81f 7843 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
15b41c77
GP
7844
7845 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
e7a88a8c
GP
7846 } return self;
7847}
7848
7849@end
7850/* }}} */
7851
9ae52960
GP
7852typedef enum {
7853 kCydiaTag = 0,
7854 kSectionsTag = 1,
7855 kChangesTag = 2,
7856 kManageTag = 3,
7857 kInstalledTag = 4,
7858 kSourcesTag = 5,
7859 kSearchTag = 6
7860} CYTabTag;
d3bef7bc 7861
4941f41d 7862@interface Cydia : UIApplication <
f441e717
GP
7863 ConfirmationControllerDelegate,
7864 ProgressControllerDelegate,
9b62701b
GP
7865 CydiaDelegate,
7866 UINavigationControllerDelegate
4941f41d 7867> {
a75f53e7 7868 UIWindow *window_;
e7a88a8c 7869 CYContainer *container_;
e057ec05 7870
9ae52960 7871 id tabbar_;
3319715b 7872
9e07091a 7873 NSMutableArray *essential_;
3319715b 7874 NSMutableArray *broken_;
a75f53e7
JF
7875
7876 Database *database_;
a75f53e7 7877
84848968 7878 int tag_;
686e302f
JF
7879
7880 UIKeyboard *keyboard_;
b26eb97d 7881 UIProgressHUD *hud_;
e25e221f 7882
f441e717
GP
7883 SectionsController *sections_;
7884 ChangesController *changes_;
7885 ManageController *manage_;
7886 SearchController *search_;
9ae52960 7887 SourceTable *sources_;
f441e717 7888 InstalledController *installed_;
9ae52960 7889 id queueDelegate_;
6932575e 7890
e7a88a8c 7891 bool loaded_;
a75f53e7
JF
7892}
7893
881fe77f
JF
7894- (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7895- (void) setPage:(CYViewController *)page;
90e9a238 7896- (void) loadData;
6981ccdf 7897
a75f53e7
JF
7898@end
7899
6981ccdf 7900static _finline void _setHomePage(Cydia *self) {
f441e717 7901 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
6981ccdf
JF
7902}
7903
a75f53e7
JF
7904@implementation Cydia
7905
9ae52960 7906- (void) beginUpdate {
e7a88a8c 7907 [container_ beginUpdate];
9ae52960
GP
7908}
7909
7910- (BOOL) updating {
e7a88a8c 7911 return [container_ updating];
9ae52960
GP
7912}
7913
5ec44e34
JF
7914- (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7915 return window_;
7916}
7917
3319715b
JF
7918- (void) _loaded {
7919 if ([broken_ count] != 0) {
7920 int count = [broken_ count];
7921
7d3e75f4 7922 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 7923 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9ae52960
GP
7924 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7925 delegate:self
7926 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7927 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
3319715b
JF
7928 ] autorelease];
7929
7d3e75f4
GP
7930 [alert setContext:@"fixhalf"];
7931 [alert show];
3319715b
JF
7932 } else if (!Ignored_ && [essential_ count] != 0) {
7933 int count = [essential_ count];
7934
7d3e75f4 7935 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 7936 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9ae52960
GP
7937 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7938 delegate:self
7939 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7d3e75f4 7940 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
3319715b
JF
7941 ] autorelease];
7942
7d3e75f4
GP
7943 [alert setContext:@"upgrade"];
7944 [alert show];
3319715b
JF
7945 }
7946}
7947
419a9efd
JF
7948- (void) _saveConfig {
7949 if (Changed_) {
7950 _trace();
7951 NSString *error(nil);
7952 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7953 _trace();
7954 NSError *error(nil);
7955 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7956 NSLog(@"failure to save metadata data: %@", error);
7957 _trace();
7958 } else {
7959 NSLog(@"failure to serialize metadata: %@", error);
7960 return;
7961 }
7962
7963 Changed_ = false;
7964 }
7965}
7966
7967- (void) _updateData {
7968 [self _saveConfig];
7969
7970 /* XXX: this is just stupid */
84848968 7971 if (tag_ != 1 && sections_ != nil)
419a9efd 7972 [sections_ reloadData];
84848968 7973 if (tag_ != 2 && changes_ != nil)
419a9efd 7974 [changes_ reloadData];
84848968 7975 if (tag_ != 4 && search_ != nil)
419a9efd
JF
7976 [search_ reloadData];
7977
1e4922b8 7978 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
9ae52960
GP
7979}
7980
7981- (int)indexOfTabWithTag:(int)tag {
7982 int i = 0;
7983 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7984 if ([[controller tabBarItem] tag] == tag) return i;
7985 i += 1;
7986 }
f99f86e2 7987
9ae52960 7988 return -1;
419a9efd
JF
7989}
7990
d56a0c9b 7991- (void) _refreshIfPossible {
e7a88a8c 7992 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
f99f86e2 7993
24966c5d
GP
7994 bool recently = false;
7995 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7996 if (update != nil) {
7997 NSTimeInterval interval([update timeIntervalSinceNow]);
7998 if (interval <= 0 && interval > -(15*60))
7999 recently = true;
8000 }
8001
8002 // Don't automatic refresh if:
8003 // - We already refreshed recently.
8004 // - We already auto-refreshed this launch.
8005 // - Auto-refresh is disabled.
8006 if (recently || loaded_ || ManualRefresh) {
8007 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8008
8009 // If we are cancelling due to ManualRefresh or a recent refresh
8010 // we need to make sure it knows it's already loaded.
8011 loaded_ = true;
8012 return;
8013 } else {
8014 // We are going to load, so remember that.
8015 loaded_ = true;
8016 }
8017
d7a235a6
JF
8018 SCNetworkReachabilityFlags flags; {
8019 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8020 SCNetworkReachabilityGetFlags(reachability, &flags);
8021 CFRelease(reachability);
8022 }
8023
8024 // XXX: this elaborate mess is what Apple is using to determine this? :(
8025 // XXX: do we care if the user has to intervene? maybe that's ok?
8026 bool reachable(
8027 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8028 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8029 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8030 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8031 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8032 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8033 )
8034 );
f99f86e2 8035
24966c5d
GP
8036 // If we can reach the server, auto-refresh!
8037 if (reachable)
e7a88a8c 8038 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
d56a0c9b 8039
e7a88a8c 8040 [pool release];
d56a0c9b
GP
8041}
8042
8043- (void) refreshIfPossible {
e7a88a8c 8044 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
d56a0c9b
GP
8045}
8046
e057ec05 8047- (void) _reloadData {
7398a389 8048 UIProgressHUD *hud([self addProgressHUD]);
d56a0c9b 8049 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
a75f53e7 8050
7398a389
JF
8051 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8052 _trace();
8053
8054 [self removeProgressHUD:hud];
d12c6e70 8055
e057ec05 8056 size_t changes(0);
3319715b 8057
9e07091a 8058 [essential_ removeAllObjects];
3319715b 8059 [broken_ removeAllObjects];
686e302f 8060
6981ccdf 8061 NSArray *packages([database_ packages]);
f464053e 8062 for (Package *package in packages) {
3319715b
JF
8063 if ([package half])
8064 [broken_ addObject:package];
238b07ce 8065 if ([package upgradableAndEssential:NO]) {
9e07091a
JF
8066 if ([package essential])
8067 [essential_ addObject:package];
e057ec05 8068 ++changes;
9e07091a 8069 }
e057ec05 8070 }
686e302f 8071
24966c5d 8072 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
e057ec05
JF
8073 if (changes != 0) {
8074 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
24966c5d
GP
8075 [changesItem setBadgeValue:badge];
8076 [changesItem setAnimatedBadge:YES];
f99f86e2 8077
6932575e
JF
8078 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8079 [self setApplicationBadge:badge];
8080 else
8081 [self setApplicationBadgeString:badge];
d12c6e70 8082 } else {
24966c5d
GP
8083 [changesItem setBadgeValue:nil];
8084 [changesItem setAnimatedBadge:NO];
f99f86e2 8085
6932575e
JF
8086 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8087 [self removeApplicationBadge];
8088 else // XXX: maybe use setApplicationBadgeString also?
8089 [self setApplicationIconBadgeNumber:0];
d12c6e70 8090 }
686e302f 8091
419a9efd 8092 [self _updateData];
fa7bb92f 8093
e7a88a8c 8094 [self refreshIfPossible];
fa7bb92f
JF
8095}
8096
faf4eb4f 8097- (void) updateData {
419a9efd
JF
8098 [database_ setVisible];
8099 [self _updateData];
686e302f
JF
8100}
8101
faf4eb4f
JF
8102- (void) update_ {
8103 [database_ update];
8104}
8105
8106- (void) syncData {
6981ccdf 8107 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
faf4eb4f
JF
8108 _assert(file != NULL);
8109
6981ccdf
JF
8110 for (NSString *key in [Sources_ allKeys]) {
8111 NSDictionary *source([Sources_ objectForKey:key]);
faf4eb4f
JF
8112
8113 fprintf(file, "%s %s %s\n",
8114 [[source objectForKey:@"Type"] UTF8String],
8115 [[source objectForKey:@"URI"] UTF8String],
8116 [[source objectForKey:@"Distribution"] UTF8String]
8117 );
8118 }
8119
8120 fclose(file);
8121
8122 [self _saveConfig];
8123
f441e717 8124 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9b62701b 8125 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9ae52960 8126 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
e7a88a8c 8127 [container_ presentModalViewController:navigation animated:YES];
9ae52960
GP
8128
8129 [progress
faf4eb4f
JF
8130 detachNewThreadSelector:@selector(update_)
8131 toTarget:self
8132 withObject:nil
61b13cae 8133 title:UCLocalize("UPDATING_SOURCES")
faf4eb4f
JF
8134 ];
8135}
8136
e057ec05
JF
8137- (void) reloadData {
8138 @synchronized (self) {
9ae52960 8139 [self _reloadData];
e057ec05 8140 }
686e302f
JF
8141}
8142
8143- (void) resolve {
8144 pkgProblemResolver *resolver = [database_ resolver];
8145
8146 resolver->InstallProtect();
8147 if (!resolver->Resolve(true))
8148 _error->Discard();
4941f41d
JF
8149}
8150
04700693 8151- (CGRect) popUpBounds {
9ae52960 8152 return [[tabbar_ view] bounds];
04700693
JF
8153}
8154
6981ccdf
JF
8155- (bool) perform {
8156 if (![database_ prepare])
8157 return false;
242bcc6d 8158
f441e717 8159 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
f464053e 8160 [page setDelegate:self];
9b62701b 8161 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
9ae52960 8162 [confirm_ setDelegate:self];
242bcc6d 8163
9ae52960 8164 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
e7a88a8c 8165 [container_ presentModalViewController:confirm_ animated:YES];
6981ccdf
JF
8166
8167 return true;
2d28b35a
JF
8168}
8169
3ff1504e
JF
8170- (void) queue {
8171 @synchronized (self) {
8172 [self perform];
8173 }
8174}
8175
8176- (void) clearPackage:(Package *)package {
8177 @synchronized (self) {
8178 [package clear];
8179 [self resolve];
8180 [self perform];
8181 }
8182}
8183
daf7f6e2
JF
8184- (void) installPackages:(NSArray *)packages {
8185 @synchronized (self) {
8186 for (Package *package in packages)
8187 [package install];
8188 [self resolve];
8189 [self perform];
8190 }
8191}
8192
e057ec05
JF
8193- (void) installPackage:(Package *)package {
8194 @synchronized (self) {
8195 [package install];
8196 [self resolve];
8197 [self perform];
8198 }
8199}
8200
8201- (void) removePackage:(Package *)package {
8202 @synchronized (self) {
8203 [package remove];
8204 [self resolve];
8205 [self perform];
8206 }
8207}
8208
8209- (void) distUpgrade {
8210 @synchronized (self) {
6981ccdf
JF
8211 if (![database_ upgrade])
8212 return;
e057ec05
JF
8213 [self perform];
8214 }
686e302f
JF
8215}
8216
3ff1504e 8217- (void) complete {
e057ec05 8218 @synchronized (self) {
e057ec05
JF
8219 [self _reloadData];
8220 }
2d28b35a
JF
8221}
8222
9ae52960 8223- (void) confirmWithNavigationController:(UINavigationController *)navigation {
f441e717 8224 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
f99f86e2 8225
9ae52960
GP
8226 if (navigation != nil) {
8227 [navigation pushViewController:progress animated:YES];
8228 } else {
15b41c77 8229 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9ae52960 8230 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
e7a88a8c 8231 [container_ presentModalViewController:navigation animated:YES];
9ae52960 8232 }
f99f86e2 8233
9ae52960 8234 [progress
4941f41d
JF
8235 detachNewThreadSelector:@selector(perform)
8236 toTarget:database_
8237 withObject:nil
61b13cae 8238 title:UCLocalize("RUNNING")
4941f41d
JF
8239 ];
8240}
8241
ba6cbb36 8242- (void) progressControllerIsComplete:(ProgressController *)progress {
3ff1504e 8243 [self complete];
a75f53e7
JF
8244}
8245
881fe77f 8246- (void) setPage:(CYViewController *)page {
e057ec05 8247 [page setDelegate:self];
9ae52960 8248
1e4922b8 8249 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
eceab8e6 8250 [navController setViewControllers:[NSArray arrayWithObject:page]];
1e4922b8 8251 for (CYNavigationController *page in [tabbar_ viewControllers]) {
9ae52960
GP
8252 if (page != navController) [page setViewControllers:nil];
8253 }
a75f53e7
JF
8254}
8255
881fe77f 8256- (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
9ae52960 8257 CYBrowserController *browser = [[[_class alloc] init] autorelease];
faf4eb4f 8258 [browser loadURL:url];
e057ec05 8259 return browser;
4941f41d
JF
8260}
8261
f441e717 8262- (SectionsController *) sectionsController {
6932575e 8263 if (sections_ == nil)
f441e717 8264 sections_ = [[SectionsController alloc] initWithDatabase:database_];
6932575e
JF
8265 return sections_;
8266}
8267
f441e717 8268- (ChangesController *) changesController {
5ec44e34 8269 if (changes_ == nil)
f441e717 8270 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
5ec44e34
JF
8271 return changes_;
8272}
8273
f441e717 8274- (ManageController *) manageController {
9ae52960 8275 if (manage_ == nil) {
f441e717 8276 manage_ = (ManageController *) [[self
5ec44e34 8277 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
f441e717 8278 withClass:[ManageController class]
5ec44e34 8279 ] retain];
9ae52960
GP
8280 if (!IsWildcat_) queueDelegate_ = manage_;
8281 }
5ec44e34
JF
8282 return manage_;
8283}
8284
f441e717 8285- (SearchController *) searchController {
5ec44e34 8286 if (search_ == nil)
f441e717 8287 search_ = [[SearchController alloc] initWithDatabase:database_];
5ec44e34
JF
8288 return search_;
8289}
8290
f441e717 8291- (SourceTable *) sourcesController {
9ae52960
GP
8292 if (sources_ == nil)
8293 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8294 return sources_;
8295}
8296
f441e717 8297- (InstalledController *) installedController {
9ae52960 8298 if (installed_ == nil) {
f441e717 8299 installed_ = [[InstalledController alloc] initWithDatabase:database_];
9ae52960
GP
8300 if (IsWildcat_) queueDelegate_ = installed_;
8301 }
8302 return installed_;
8303}
8304
f99f86e2 8305- (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
9ae52960 8306 int tag = [[viewController tabBarItem] tag];
97959670 8307 if (tag == tag_) {
1e4922b8 8308 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
97959670 8309 return;
9ae52960 8310 } else if (tag_ == 1) {
f441e717 8311 [[self sectionsController] resetView];
9ae52960 8312 }
a75f53e7 8313
7e986211 8314 switch (tag) {
9ae52960 8315 case kCydiaTag: _setHomePage(self); break;
e057ec05 8316
f441e717
GP
8317 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8318 case kChangesTag: [self setPage:[self changesController]]; break;
8319 case kManageTag: [self setPage:[self manageController]]; break;
8320 case kInstalledTag: [self setPage:[self installedController]]; break;
8321 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8322 case kSearchTag: [self setPage:[self searchController]]; break;
e057ec05 8323
6981ccdf 8324 _nodefault
a75f53e7
JF
8325 }
8326
7e986211 8327 tag_ = tag;
7e986211
JF
8328}
8329
c1edf105
GP
8330- (void) showSettings {
8331 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
e9a716a7 8332 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
ca45de84 8333 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
c1edf105 8334 [container_ presentModalViewController:nav animated:YES];
faf4eb4f
JF
8335}
8336
f441e717 8337- (void) setPackageController:(PackageController *)view {
b452841e
JF
8338 WebThreadLock();
8339 [view setPackage:nil];
b452841e
JF
8340 WebThreadUnlock();
8341}
8342
f441e717
GP
8343- (PackageController *) _packageController {
8344 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
6932575e
JF
8345}
8346
f441e717 8347- (PackageController *) packageController {
f441e717 8348 return [self _packageController];
6932575e
JF
8349}
8350
19044e4f
GP
8351// Returns the navigation controller for the queuing badge.
8352- (id) queueBadgeController {
8353 int index = [self indexOfTabWithTag:kManageTag];
8354 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
283fc596 8355
19044e4f
GP
8356 return [[tabbar_ viewControllers] objectAtIndex:index];
8357}
8358
1ca35d78
GP
8359- (void) cancelAndClear:(bool)clear {
8360 @synchronized (self) {
8361 if (clear) {
ccb4681d
GP
8362 // Clear all marks.
8363 pkgCacheFile &cache([database_ cache]);
9ae52960 8364 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
ccb4681d 8365 // Unmark method taken from Synaptic Package Manager.
283fc596
JF
8366 // Thanks for being sane, unlike Aptitude.
8367 if (!cache[iterator].Keep()) {
8368 cache->MarkKeep(iterator, false);
8369 cache->SetReInstall(iterator, false);
8370 }
9ae52960
GP
8371 }
8372
283fc596 8373 // Stop queuing.
9ae52960 8374 Queuing_ = false;
19044e4f 8375 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
1ca35d78 8376 } else {
283fc596 8377 // Start queuing.
9ae52960 8378 Queuing_ = true;
19044e4f 8379 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
283fc596
JF
8380 }
8381
8382 // Show the changes in the current view.
19044e4f
GP
8383 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8384 [queueDelegate_ queueStatusDidChange];
1ca35d78 8385 }
7d3e75f4 8386}
faf4eb4f 8387
9ae52960
GP
8388- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8389 NSString *context([alert context]);
f99f86e2 8390
9ae52960
GP
8391 if ([context isEqualToString:@"fixhalf"]) {
8392 if (button == [alert firstOtherButtonIndex]) {
7d3e75f4
GP
8393 @synchronized (self) {
8394 for (Package *broken in broken_) {
8395 [broken remove];
8396
8397 NSString *id = [broken id];
8398 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8399 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8400 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8401 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8402 }
faf4eb4f 8403
7d3e75f4
GP
8404 [self resolve];
8405 [self perform];
8406 }
9ae52960 8407 } else if (button == [alert cancelButtonIndex]) {
7d3e75f4
GP
8408 [broken_ removeAllObjects];
8409 [self _loaded];
faf4eb4f
JF
8410 }
8411
7d3e75f4 8412 [alert dismissWithClickedButtonIndex:-1 animated:YES];
a5dd312c 8413 } else if ([context isEqualToString:@"upgrade"]) {
7d3e75f4
GP
8414 if (button == [alert firstOtherButtonIndex]) {
8415 @synchronized (self) {
8416 for (Package *essential in essential_)
8417 [essential install];
faf4eb4f 8418
7d3e75f4
GP
8419 [self resolve];
8420 [self perform];
8421 }
8422 } else if (button == [alert firstOtherButtonIndex] + 1) {
8423 [self distUpgrade];
8424 } else if (button == [alert cancelButtonIndex]) {
8425 Ignored_ = YES;
faf4eb4f
JF
8426 }
8427
7d3e75f4 8428 [alert dismissWithClickedButtonIndex:-1 animated:YES];
a5dd312c 8429 }
faf4eb4f
JF
8430}
8431
6981ccdf
JF
8432- (void) system:(NSString *)command { _pooled
8433 system([command UTF8String]);
8434}
8435
8436- (void) applicationWillSuspend {
8437 [database_ clean];
8438 [super applicationWillSuspend];
b26eb97d
JF
8439}
8440
8441- (void) applicationSuspend:(__GSEvent *)event {
2b04cd97
GP
8442 // FIXME: This needs to be fixed, but we no longer have a progress_.
8443 // What's the best solution?
9ae52960 8444 if (hud_ == nil)// && ![progress_ isRunning])
b26eb97d 8445 [super applicationSuspend:event];
b26eb97d
JF
8446}
8447
fa7bb92f
JF
8448- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8449 if (hud_ == nil)
8450 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8451}
8452
8453- (void) _setSuspended:(BOOL)value {
8454 if (hud_ == nil)
8455 [super _setSuspended:value];
8456}
8457
faf4eb4f 8458- (UIProgressHUD *) addProgressHUD {
7398a389 8459 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
d3bef7bc
JF
8460 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8461
7398a389 8462 [window_ setUserInteractionEnabled:NO];
faf4eb4f 8463 [hud show:YES];
0efe9812 8464 [[container_ view] addSubview:hud];
faf4eb4f
JF
8465 return hud;
8466}
8467
7398a389
JF
8468- (void) removeProgressHUD:(UIProgressHUD *)hud {
8469 [hud show:NO];
8470 [hud removeFromSuperview];
8471 [window_ setUserInteractionEnabled:YES];
8472}
8473
881fe77f 8474- (CYViewController *) pageForPackage:(NSString *)name {
cb9c2100 8475 if (Package *package = [database_ packageWithName:name]) {
f441e717 8476 PackageController *view([self packageController]);
cb9c2100
JF
8477 [view setPackage:package];
8478 return view;
8479 } else {
6981ccdf
JF
8480 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8481 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
9ae52960 8482 return [self _pageForURL:url withClass:[CYBrowserController class]];
cb9c2100
JF
8483 }
8484}
8485
881fe77f 8486- (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
cb9c2100 8487 if (tag != NULL)
84848968 8488 *tag = -1;
cb9c2100 8489
61b13cae
JF
8490 NSString *href([url absoluteString]);
8491 if ([href hasPrefix:@"apptapp://package/"])
8492 return [self pageForPackage:[href substringFromIndex:18]];
8493
2dfc46f7
JF
8494 NSString *scheme([[url scheme] lowercaseString]);
8495 if (![scheme isEqualToString:@"cydia"])
8496 return nil;
8497 NSString *path([url absoluteString]);
8498 if ([path length] < 8)
8499 return nil;
8500 path = [path substringFromIndex:8];
8501 if (![path hasPrefix:@"/"])
8502 path = [@"/" stringByAppendingString:path];
8503
8504 if ([path isEqualToString:@"/add-source"])
f441e717 8505 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
2dfc46f7 8506 else if ([path isEqualToString:@"/storage"])
9ae52960 8507 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
2dfc46f7 8508 else if ([path isEqualToString:@"/sources"])
9ae52960 8509 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
2dfc46f7 8510 else if ([path isEqualToString:@"/packages"])
f441e717 8511 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
2dfc46f7 8512 else if ([path hasPrefix:@"/url/"])
9ae52960 8513 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
2dfc46f7
JF
8514 else if ([path hasPrefix:@"/launch/"])
8515 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8516 else if ([path hasPrefix:@"/package-settings/"])
f441e717 8517 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
2dfc46f7 8518 else if ([path hasPrefix:@"/package-signature/"])
f441e717 8519 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
2dfc46f7
JF
8520 else if ([path hasPrefix:@"/package/"])
8521 return [self pageForPackage:[path substringFromIndex:9]];
8522 else if ([path hasPrefix:@"/files/"]) {
8523 NSString *name = [path substringFromIndex:7];
cb9c2100
JF
8524
8525 if (Package *package = [database_ packageWithName:name]) {
9ae52960 8526 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
cb9c2100
JF
8527 [files setPackage:package];
8528 return files;
8529 }
8530 }
8531
8532 return nil;
8533}
8534
8535- (void) applicationOpenURL:(NSURL *)url {
8536 [super applicationOpenURL:url];
8537 int tag;
881fe77f 8538 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
cb9c2100 8539 [self setPage:page];
cb9c2100 8540 tag_ = tag;
9ae52960 8541 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
cb9c2100
JF
8542 }
8543}
8544
f99f86e2 8545- (void) applicationWillResignActive:(UIApplication *)application {
57e5156d
GP
8546 // Stop refreshing if you get a phone call or lock the device.
8547 if ([container_ updating]) [container_ cancelUpdate];
f99f86e2 8548
0a6531c7
GP
8549 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8550 [super applicationWillResignActive:application];
57e5156d
GP
8551}
8552
b26eb97d 8553- (void) applicationDidFinishLaunching:(id)unused {
9ae52960 8554 [CYBrowserController _initialize];
4825688a 8555
017b2b71
JF
8556 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8557
5e563e79
JF
8558 Font12_ = [[UIFont systemFontOfSize:12] retain];
8559 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8560 Font14_ = [[UIFont systemFontOfSize:14] retain];
8561 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8562 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8563
84848968 8564 tag_ = 0;
b26eb97d
JF
8565
8566 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8567 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8568
d3bef7bc
JF
8569 UIScreen *screen([UIScreen mainScreen]);
8570
8571 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
5e563e79
JF
8572 [window_ orderFront:self];
8573 [window_ makeKey:self];
cb9c2100 8574 [window_ setHidden:NO];
d3bef7bc 8575
dbe0f181 8576 database_ = [Database sharedInstance];
017b2b71 8577
b36d03d7 8578 NSMutableArray *items([NSMutableArray arrayWithObjects:
9ae52960
GP
8579 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8580 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8581 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8582 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
b36d03d7 8583 nil]);
f99f86e2 8584
9ae52960
GP
8585 if (IsWildcat_) {
8586 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8587 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8588 } else {
8589 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8590 }
f99f86e2 8591
b36d03d7
JF
8592 NSMutableArray *controllers([NSMutableArray array]);
8593
8594 for (UITabBarItem *item in items) {
8595 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8596 [controller setTabBarItem:item];
8597 [controllers addObject:controller];
8598 }
e7a88a8c 8599
9ae52960 8600 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9ae52960
GP
8601 [tabbar_ setViewControllers:controllers];
8602 [tabbar_ setDelegate:self];
8603 [tabbar_ setSelectedIndex:0];
e7a88a8c
GP
8604
8605 container_ = [[CYContainer alloc] initWithDatabase:database_];
e7a88a8c 8606 [container_ setUpdateDelegate:self];
1e4922b8 8607 [container_ setTabBarController:tabbar_];
e7a88a8c 8608 [window_ addSubview:[container_ view]];
6981ccdf 8609
ddb74789
JF
8610 if (
8611 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8612 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8613 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8614 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8615 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8616 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8617 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8618 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8619 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8620 false
8621 ) {
8622 [self setIdleTimerDisabled:YES];
8623
8624 hud_ = [self addProgressHUD];
8625 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8626 [self setStatusBarShowsProgress:YES];
8627
8628 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8629
8630 [self setStatusBarShowsProgress:NO];
8631 [self removeProgressHUD:hud_];
8632 hud_ = nil;
8633
8634 if (ExecFork() == 0) {
8635 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8636 perror("launchctl stop");
8637 }
8638
8639 return;
8640 }
8641
525bc190
GP
8642 // Show pinstripes while loading data.
8643 [[container_ view] setBackgroundColor:[UIColor performSelector:@selector(pinStripeColor)]];
8644
90e9a238
JF
8645 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8646}
8647
8648- (void) loadData {
8649 if (Role_ == nil) {
8650 [self showSettings];
8651 return;
8652 }
8653
6981ccdf 8654 [UIKeyboard initImplementationNow];
6981ccdf
JF
8655
8656 [self reloadData];
8657
6981ccdf
JF
8658 PrintTimes();
8659
8660 _setHomePage(self);
525bc190
GP
8661
8662 // XXX: does this actually slow anything down?
8663 [[container_ view] setBackgroundColor:[UIColor clearColor]];
b26eb97d
JF
8664}
8665
9ae52960 8666- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
1ca35d78 8667 if (item != nil && IsWildcat_) {
9ae52960 8668 [sheet showFromBarButtonItem:item animated:YES];
1ca35d78
GP
8669 } else {
8670 [sheet showInView:window_];
8671 }
e057ec05
JF
8672}
8673
a75f53e7
JF
8674@end
8675
686e302f
JF
8676/*IMP alloc_;
8677id Alloc_(id self, SEL selector) {
8678 id object = alloc_(self, selector);
cb9c2100 8679 lprintf("[%s]A-%p\n", self->isa->name, object);
686e302f
JF
8680 return object;
8681}*/
8682
e057ec05
JF
8683/*IMP dealloc_;
8684id Dealloc_(id self, SEL selector) {
8685 id object = dealloc_(self, selector);
cb9c2100 8686 lprintf("[%s]D-%p\n", self->isa->name, object);
e057ec05
JF
8687 return object;
8688}*/
686e302f 8689
6932575e
JF
8690Class $WebDefaultUIKitDelegate;
8691
c59881cd 8692MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
6932575e
JF
8693 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8694 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
c59881cd 8695 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
6932575e
JF
8696}
8697
aaab313d
RP
8698static NSNumber *shouldPlayKeyboardSounds;
8699
8700Class $UIHardware;
8701
d5f224e7
JF
8702MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8703 switch (sound) {
aaab313d
RP
8704 case 1104: // Keyboard Button Clicked
8705 case 1105: // Keyboard Delete Repeated
d5f224e7
JF
8706 if (shouldPlayKeyboardSounds == nil) {
8707 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8708 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
aaab313d 8709 }
d5f224e7 8710
aaab313d
RP
8711 if (![shouldPlayKeyboardSounds boolValue])
8712 break;
d5f224e7 8713
aaab313d 8714 default:
d5f224e7 8715 _UIHardware$_playSystemSound$(self, _cmd, sound);
aaab313d
RP
8716 }
8717}
8718
f464053e 8719int main(int argc, char *argv[]) { _pooled
7ec29c77 8720 _trace();
6932575e 8721
5ec44e34
JF
8722 if (Class $UIDevice = objc_getClass("UIDevice")) {
8723 UIDevice *device([$UIDevice currentDevice]);
8724 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8725 } else
8726 IsWildcat_ = false;
8727
dd9390c5 8728 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
43b742af 8729
3e3977a2
JF
8730 /* Library Hacks {{{ */
8731 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8732
8733 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8734 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8735 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8736 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8737 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8738 }
aaab313d
RP
8739
8740 $UIHardware = objc_getClass("UIHardware");
8741 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8742 if (UIHardware$_playSystemSound$ != NULL) {
8743 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8744 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8745 }
3e3977a2
JF
8746 /* }}} */
8747 /* Set Locale {{{ */
6932575e 8748 Locale_ = CFLocaleCopyCurrent();
bb9edf8b
JF
8749 Languages_ = [NSLocale preferredLanguages];
8750 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
f7ee98cb 8751 //NSLog(@"%@", [Languages_ description]);
85e0f0f0 8752
bb9edf8b
JF
8753 const char *lang;
8754 if (Languages_ == nil || [Languages_ count] == 0)
85e0f0f0 8755 // XXX: consider just setting to C and then falling through?
bb9edf8b 8756 lang = NULL;
85e0f0f0 8757 else {
bb9edf8b 8758 lang = [[Languages_ objectAtIndex:0] UTF8String];
85e0f0f0
JF
8759 setenv("LANG", lang, true);
8760 }
8761
bb9edf8b
JF
8762 //std::setlocale(LC_ALL, lang);
8763 NSLog(@"Setting Language: %s", lang);
3e3977a2 8764 /* }}} */
6932575e 8765
c59881cd 8766 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
6932575e 8767
3e3977a2 8768 /* Parse Arguments {{{ */
64da7a2f
JF
8769 bool substrate(false);
8770
8771 if (argc != 0) {
8772 char **args(argv);
8773 int arge(1);
8774
8775 for (int argi(1); argi != argc; ++argi)
8776 if (strcmp(argv[argi], "--") == 0) {
8777 arge = argi;
8778 argv[argi] = argv[0];
8779 argv += argi;
8780 argc -= argi;
8781 break;
8782 }
8783
8784 for (int argi(1); argi != arge; ++argi)
c59881cd 8785 if (strcmp(args[argi], "--substrate") == 0)
64da7a2f
JF
8786 substrate = true;
8787 else
8788 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8789 }
3e3977a2 8790 /* }}} */
0039464f 8791
3e3977a2
JF
8792 App_ = [[NSBundle mainBundle] bundlePath];
8793 Home_ = NSHomeDirectory();
c59881cd 8794 Advanced_ = YES;
3e3977a2 8795
686e302f
JF
8796 setuid(0);
8797 setgid(0);
8798
8799 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8800 alloc_ = alloc->method_imp;
8801 alloc->method_imp = (IMP) &Alloc_;*/
8802
e057ec05
JF
8803 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8804 dealloc_ = dealloc->method_imp;
8805 dealloc->method_imp = (IMP) &Dealloc_;*/
8806
c59881cd 8807 /* System Information {{{ */
2d28b35a 8808 size_t size;
cb9c2100
JF
8809
8810 int maxproc;
8811 size = sizeof(maxproc);
8812 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8813 perror("sysctlbyname(\"kern.maxproc\", ?)");
8814 else if (maxproc < 64) {
8815 maxproc = 64;
8816 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8817 perror("sysctlbyname(\"kern.maxproc\", #)");
8818 }
8819
017b2b71
JF
8820 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8821 char *osversion = new char[size];
8822 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8823 perror("sysctlbyname(\"kern.osversion\", ?)");
8824 else
8825 System_ = [NSString stringWithUTF8String:osversion];
8826
2d28b35a
JF
8827 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8828 char *machine = new char[size];
cb9c2100
JF
8829 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8830 perror("sysctlbyname(\"hw.machine\", ?)");
8831 else
8832 Machine_ = machine;
2d28b35a 8833
6188cfdd
JF
8834 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8835 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8836 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
017b2b71 8837 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
6188cfdd
JF
8838 CFRelease(serial);
8839 }
8840
8841 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8842 NSData *data((NSData *) ecid);
8843 size_t length([data length]);
8844 uint8_t bytes[length];
8845 [data getBytes:bytes];
8846 char string[length * 2 + 1];
8847 for (size_t i(0); i != length; ++i)
8848 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
017b2b71 8849 ChipID_ = [NSString stringWithUTF8String:string];
6188cfdd
JF
8850 CFRelease(ecid);
8851 }
8852
8853 IOObjectRelease(service);
8854 }
8855 }
8856
2cb68ddf 8857 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
2d28b35a 8858
68c05606
JF
8859 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8860 Build_ = [system objectForKey:@"ProductBuildVersion"];
7b00c562
JF
8861 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8862 Product_ = [info objectForKey:@"SafariProductVersion"];
8863 Safari_ = [info objectForKey:@"CFBundleVersion"];
8864 }
c59881cd 8865 /* }}} */
3e3977a2 8866 /* Load Database {{{ */
7ec29c77 8867 _trace();
6932575e
JF
8868 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8869 _trace();
8870 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
7ec29c77
JF
8871 _trace();
8872
8873 if (Metadata_ == NULL)
6932575e 8874 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
fa7bb92f 8875 else {
ca45de84 8876 Settings_ = [Metadata_ objectForKey:@"Settings"];
faf4eb4f 8877
686e302f 8878 Packages_ = [Metadata_ objectForKey:@"Packages"];
fa7bb92f 8879 Sections_ = [Metadata_ objectForKey:@"Sections"];
faf4eb4f 8880 Sources_ = [Metadata_ objectForKey:@"Sources"];
37455cf8
JF
8881
8882 Token_ = [Metadata_ objectForKey:@"Token"];
faf4eb4f
JF
8883 }
8884
8885 if (Settings_ != nil)
8886 Role_ = [Settings_ objectForKey:@"Role"];
8887
8888 if (Packages_ == nil) {
8889 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8890 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8891 }
8892
8893 if (Sections_ == nil) {
8894 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8895 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8896 }
8897
8898 if (Sources_ == nil) {
8899 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8900 [Metadata_ setObject:Sources_ forKey:@"Sources"];
fa7bb92f 8901 }
3e3977a2 8902 /* }}} */
686e302f 8903
c59881cd
JF
8904 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8905
5ec44e34
JF
8906 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8907 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8944281a
JF
8908 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8909 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8910 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8911 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
1eb0c554 8912
5ec44e34
JF
8913 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8914
17f91215 8915 if (access("/tmp/.cydia.fw", F_OK) == 0) {
4825688a 8916 unlink("/tmp/.cydia.fw");
17f91215 8917 goto firmware;
daf7f6e2 8918 } else if (access("/User", F_OK) != 0 || version < 2) {
17f91215 8919 firmware:
7ec29c77 8920 _trace();
6a0db335 8921 system("/usr/libexec/cydia/firmware.sh");
7ec29c77
JF
8922 _trace();
8923 }
63a1e4b8 8924
2cb68ddf
JF
8925 _assert([[NSFileManager defaultManager]
8926 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8927 withIntermediateDirectories:YES
8928 attributes:nil
8929 error:NULL
8930 ]);
8931
3e3977a2
JF
8932 if (access("/tmp/cydia.chk", F_OK) == 0) {
8933 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8934 _assert(errno == ENOENT);
8935 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8936 _assert(errno == ENOENT);
8937 }
8938
6188cfdd 8939 /* APT Initialization {{{ */
bb9edf8b
JF
8940 _assert(pkgInitConfig(*_config));
8941 _assert(pkgInitSystem(*_config, _system));
8942
8943 if (lang != NULL)
8944 _config->Set("APT::Acquire::Translation", lang);
43b742af 8945 _config->Set("Acquire::http::Timeout", 15);
419a9efd 8946 _config->Set("Acquire::http::MaxParallel", 3);
6188cfdd 8947 /* }}} */
3e3977a2 8948 /* Color Choices {{{ */
e057ec05
JF
8949 space_ = CGColorSpaceCreateDeviceRGB();
8950
5e563e79 8951 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
d72d91aa 8952 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
e057ec05 8953 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
87c76914 8954 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
e057ec05 8955 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
faf4eb4f 8956 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
d8d9a65c
JF
8957 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8958 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8959 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
6188cfdd 8960
3ff1504e
JF
8961 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8962 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
3e3977a2 8963 /* }}}*/
3e3977a2 8964 /* UIKit Configuration {{{ */
6932575e
JF
8965 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8966 if ($GSFontSetUseLegacyFontMetrics != NULL)
8967 $GSFontSetUseLegacyFontMetrics(YES);
faf4eb4f 8968
d4f84362
JF
8969 // XXX: I have a feeling this was important
8970 //UIKeyboardDisableAutomaticAppearance();
3e3977a2 8971 /* }}} */
2cb68ddf 8972
6981ccdf
JF
8973 Colon_ = UCLocalize("COLON_DELIMITED");
8974 Error_ = UCLocalize("ERROR");
8975 Warning_ = UCLocalize("WARNING");
8976
7ec29c77 8977 _trace();
bf50bdfa 8978 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
e057ec05
JF
8979
8980 CGColorSpaceRelease(space_);
b27f0a94 8981 CFRelease(Locale_);
e057ec05 8982
e057ec05 8983 return value;
2938b930 8984}