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