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