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