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