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