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