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