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