]> git.saurik.com Git - cydia.git/blame - MobileCydia.mm
Use sed to build version.sh, preferring '+#.%' to '.#.%'.
[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 {
884171d6
JF
2248@synchronized (database_) {
2249 if ([database_ era] != era_ || file_.end())
5a09ae08 2250 return nil;
884171d6 2251
36bb2ca2 2252 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
00e2109e
JF
2253 const std::string &maintainer(parser->Maintainer());
2254 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
884171d6 2255} }
8fe19fc1 2256
36bb2ca2 2257- (size_t) size {
884171d6
JF
2258@synchronized (database_) {
2259 if ([database_ era] != era_ || version_.end())
2260 return 0;
2261
2262 return version_->InstalledSize;
2263} }
dc5812ec 2264
eef4ccaf 2265- (NSString *) longDescription {
3dd53516
JF
2266@synchronized (database_) {
2267 if ([database_ era] != era_ || file_.end())
5a09ae08 2268 return nil;
3dd53516 2269
36bb2ca2 2270 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2388b078 2271 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
8fe19fc1 2272
36bb2ca2
JF
2273 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2274 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2275 if ([lines count] < 2)
2276 return nil;
3178d79b 2277
36bb2ca2 2278 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
c4dcf2c2 2279 for (size_t i(1), e([lines count]); i != e; ++i) {
36bb2ca2
JF
2280 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2281 [trimmed addObject:trim];
2282 }
3178d79b 2283
36bb2ca2 2284 return [trimmed componentsJoinedByString:@"\n"];
3dd53516 2285} }
dc5812ec 2286
eef4ccaf
JF
2287- (NSString *) shortDescription {
2288 return tagline_;
2289}
2290
808c6eb6
JF
2291- (unichar) index {
2292 _profile(Package$index)
677b8415
JF
2293 CFStringRef name((CFStringRef) [self name]);
2294 if (CFStringGetLength(name) == 0)
808c6eb6 2295 return '#';
677b8415
JF
2296 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2297 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
808c6eb6 2298 return '#';
447db19d 2299 return toupper(character);
808c6eb6 2300 _end
36bb2ca2 2301}
3178d79b 2302
807ae6d7 2303- (NSMutableDictionary *) metadata {
f79a4512 2304 return metadata_;
807ae6d7
JF
2305}
2306
36bb2ca2 2307- (NSDate *) seen {
677b8415
JF
2308 if (subscribed_ && lastSeen_ != nil)
2309 return lastSeen_;
2310 return firstSeen_;
3178d79b
JF
2311}
2312
807ae6d7 2313- (BOOL) subscribed {
677b8415 2314 return subscribed_;
807ae6d7
JF
2315}
2316
2317- (BOOL) ignored {
2318 NSDictionary *metadata([self metadata]);
2319 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2320 return [ignored boolValue];
2321 else
2322 return false;
2323}
2324
36bb2ca2
JF
2325- (NSString *) latest {
2326 return latest_;
8fe19fc1
JF
2327}
2328
36bb2ca2
JF
2329- (NSString *) installed {
2330 return installed_;
3178d79b
JF
2331}
2332
6a155117
JF
2333- (BOOL) uninstalled {
2334 return installed_.empty();
2335}
2336
5a09ae08
JF
2337- (BOOL) valid {
2338 return !version_.end();
2339}
2340
31f3cfff 2341- (BOOL) upgradableAndEssential:(BOOL)essential {
677b8415
JF
2342 _profile(Package$upgradableAndEssential)
2343 pkgCache::VerIterator current(iterator_.CurrentVer());
2344 if (current.end())
e4f3d6e9 2345 return essential && essential_;
677b8415 2346 else
e4f3d6e9 2347 return !version_.end() && version_ != current;
677b8415 2348 _end
36bb2ca2 2349}
3178d79b 2350
36bb2ca2 2351- (BOOL) essential {
a1440b10 2352 return essential_;
3178d79b
JF
2353}
2354
36bb2ca2 2355- (BOOL) broken {
9bedffaa
JF
2356 return [database_ cache][iterator_].InstBroken();
2357}
2358
7d2ac47f 2359- (BOOL) unfiltered {
4fa77608
JF
2360 _profile(Package$unfiltered$obsolete)
2361 if (obsolete_)
2362 return false;
2363 _end
2364
2365 _profile(Package$unfiltered$hasSupportingRole)
2366 if (![self hasSupportingRole])
2367 return false;
2368 _end
2369
e4f3d6e9
JF
2370 return true;
2371}
4fa77608 2372
e4f3d6e9
JF
2373- (BOOL) visible {
2374 if (![self unfiltered])
2375 return false;
2376
2377 NSString *section([self section]);
4fa77608 2378
e4f3d6e9 2379 _profile(Package$visible$isSectionVisible)
4fa77608
JF
2380 if (section != nil && !isSectionVisible(section))
2381 return false;
2382 _end
2383
2384 return true;
7d2ac47f
JF
2385}
2386
9bedffaa 2387- (BOOL) half {
677b8415 2388 unsigned char current(iterator_->CurrentState);
9bedffaa
JF
2389 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2390}
2391
2392- (BOOL) halfConfigured {
2393 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2394}
2395
2396- (BOOL) halfInstalled {
2397 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2398}
2399
2400- (BOOL) hasMode {
2401 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2402 return state.Mode != pkgDepCache::ModeKeep;
2403}
2404
2405- (NSString *) mode {
2406 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2407
2408 switch (state.Mode) {
2409 case pkgDepCache::ModeDelete:
2410 if ((state.iFlags & pkgDepCache::Purge) != 0)
f79a4512 2411 return @"PURGE";
9bedffaa 2412 else
f79a4512 2413 return @"REMOVE";
9bedffaa 2414 case pkgDepCache::ModeKeep:
dc63e78f 2415 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
f79a4512 2416 return @"REINSTALL";
dc63e78f
JF
2417 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2418 return nil;*/
9bedffaa
JF
2419 else
2420 return nil;
9bedffaa 2421 case pkgDepCache::ModeInstall:
dc63e78f 2422 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
f79a4512 2423 return @"REINSTALL";
dc63e78f 2424 else*/ switch (state.Status) {
9bedffaa 2425 case -1:
f79a4512 2426 return @"DOWNGRADE";
9bedffaa 2427 case 0:
f79a4512 2428 return @"INSTALL";
9bedffaa 2429 case 1:
f79a4512 2430 return @"UPGRADE";
9bedffaa 2431 case 2:
f79a4512 2432 return @"NEW_INSTALL";
670a0494 2433 _nodefault
9bedffaa 2434 }
670a0494 2435 _nodefault
9bedffaa 2436 }
8fe19fc1
JF
2437}
2438
36bb2ca2
JF
2439- (NSString *) id {
2440 return id_;
8fe19fc1
JF
2441}
2442
36bb2ca2 2443- (NSString *) name {
9fcbca29 2444 return name_.empty() ? id_ : name_;
36bb2ca2 2445}
8fe19fc1 2446
770f2a8e 2447- (UIImage *) icon {
dec6029f 2448 NSString *section = [self simpleSection];
770f2a8e
JF
2449
2450 UIImage *icon(nil);
df213583 2451 if (!icon_.empty())
89b0ea4a 2452 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
ac308d3e 2453 // XXX: correct escaping
89b0ea4a 2454 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
770f2a8e
JF
2455 if (icon == nil) if (section != nil)
2456 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
b9956841 2457 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
189a73d0 2458 if ([dicon hasPrefix:@"file:///"])
ac308d3e 2459 // XXX: correct escaping
189a73d0 2460 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
770f2a8e
JF
2461 if (icon == nil)
2462 icon = [UIImage applicationImageNamed:@"unknown.png"];
2463 return icon;
36bb2ca2 2464}
8fe19fc1 2465
6f1a15d9 2466- (NSString *) homepage {
3a49daf0 2467 return homepage_;
8fe19fc1
JF
2468}
2469
25a2158d 2470- (NSString *) depiction {
6204f56a 2471 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
25a2158d
JF
2472}
2473
795d26fc 2474- (Address *) sponsor {
f79a4512
JF
2475 if (sponsor$_ == nil) {
2476 if (sponsor_.empty())
2477 return nil;
2478 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2479 } return sponsor$_;
795d26fc
JF
2480}
2481
77fcccaf 2482- (Address *) author {
f79a4512
JF
2483 if (author$_ == nil) {
2484 if (author_.empty())
2485 return nil;
2486 author$_ = [[Address addressWithString:author_] retain];
2487 } return author$_;
77fcccaf
JF
2488}
2489
dc63e78f 2490- (NSString *) support {
7623f855 2491 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
dc63e78f
JF
2492}
2493
affeffc7 2494- (NSArray *) files {
9fcbca29 2495 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
affeffc7
JF
2496 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2497
2498 std::ifstream fin;
2499 fin.open([path UTF8String]);
2500 if (!fin.is_open())
2501 return nil;
2502
2503 std::string line;
2504 while (std::getline(fin, line))
2505 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2506
2507 return files;
2508}
2509
affeffc7
JF
2510- (NSArray *) warnings {
2511 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2512 const char *name(iterator_.Name());
2513
2514 size_t length(strlen(name));
2515 if (length < 2) invalid:
43f3d7f6 2516 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
affeffc7
JF
2517 else for (size_t i(0); i != length; ++i)
2518 if (
9dd60d81
JF
2519 /* XXX: technically this is not allowed */
2520 (name[i] < 'A' || name[i] > 'Z') &&
affeffc7
JF
2521 (name[i] < 'a' || name[i] > 'z') &&
2522 (name[i] < '0' || name[i] > '9') &&
2523 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2524 ) goto invalid;
2525
2526 if (strcmp(name, "cydia") != 0) {
2527 bool cydia = false;
7623f855 2528 bool user = false;
9dd60d81 2529 bool _private = false;
affeffc7
JF
2530 bool stash = false;
2531
9dd60d81
JF
2532 bool repository = [[self section] isEqualToString:@"Repositories"];
2533
affeffc7
JF
2534 if (NSArray *files = [self files])
2535 for (NSString *file in files)
2536 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2537 cydia = true;
7623f855
JF
2538 else if (!user && [file isEqualToString:@"/User"])
2539 user = true;
9dd60d81
JF
2540 else if (!_private && [file isEqualToString:@"/private"])
2541 _private = true;
affeffc7
JF
2542 else if (!stash && [file isEqualToString:@"/var/stash"])
2543 stash = true;
2544
9dd60d81
JF
2545 /* XXX: this is not sensitive enough. only some folders are valid. */
2546 if (cydia && !repository)
43f3d7f6 2547 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
7623f855
JF
2548 if (user)
2549 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
9dd60d81 2550 if (_private)
43f3d7f6 2551 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
affeffc7 2552 if (stash)
43f3d7f6 2553 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
affeffc7
JF
2554 }
2555
2556 return [warnings count] == 0 ? nil : warnings;
2557}
2558
2559- (NSArray *) applications {
2560 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2561
2562 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2563
2564 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2565 if (NSArray *files = [self files])
2566 for (NSString *file in files)
2567 if (application_r(file)) {
2568 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2569 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2570 if ([id isEqualToString:me])
2571 continue;
2572
2573 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2574 if (display == nil)
2575 display = application_r[1];
2576
2577 NSString *bundle([file stringByDeletingLastPathComponent]);
2578 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2579 if (icon == nil || [icon length] == 0)
2580 icon = @"icon.png";
2581 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2582
2583 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2584 [applications addObject:application];
2585
2586 [application addObject:id];
2587 [application addObject:display];
2588 [application addObject:url];
2589 }
2590
2591 return [applications count] == 0 ? nil : applications;
2592}
2593
36bb2ca2 2594- (Source *) source {
5699667a 2595 if (source_ == nil) {
a1440b10
JF
2596 @synchronized (database_) {
2597 if ([database_ era] != era_ || file_.end())
5699667a
JF
2598 source_ = (Source *) [NSNull null];
2599 else
2600 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
a1440b10 2601 }
bbb879fb
JF
2602 }
2603
5699667a 2604 return source_ == (Source *) [NSNull null] ? nil : source_;
8fe19fc1
JF
2605}
2606
7b0ce2da
JF
2607- (NSString *) role {
2608 return role_;
2609}
2610
36bb2ca2
JF
2611- (BOOL) matches:(NSString *)text {
2612 if (text == nil)
2613 return NO;
8fe19fc1 2614
36bb2ca2 2615 NSRange range;
8fe19fc1 2616
808c6eb6 2617 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2
JF
2618 if (range.location != NSNotFound)
2619 return YES;
8fe19fc1 2620
808c6eb6 2621 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2
JF
2622 if (range.location != NSNotFound)
2623 return YES;
8fe19fc1 2624
01d93940 2625 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2 2626 if (range.location != NSNotFound)
01d93940 2627 return YES;
8fe19fc1 2628
36bb2ca2
JF
2629 return NO;
2630}
8fe19fc1 2631
7b0ce2da
JF
2632- (bool) hasSupportingRole {
2633 if (role_ == nil)
6d9712c4 2634 return true;
7b0ce2da
JF
2635 if ([role_ isEqualToString:@"enduser"])
2636 return true;
2637 if ([Role_ isEqualToString:@"User"])
2638 return false;
2639 if ([role_ isEqualToString:@"hacker"])
2640 return true;
2641 if ([Role_ isEqualToString:@"Hacker"])
2642 return false;
2643 if ([role_ isEqualToString:@"developer"])
2644 return true;
2645 if ([Role_ isEqualToString:@"Developer"])
2646 return false;
2647 _assert(false);
6d9712c4
JF
2648}
2649
2650- (BOOL) hasTag:(NSString *)tag {
2651 return tags_ == nil ? NO : [tags_ containsObject:tag];
2652}
2653
c390d3ab
JF
2654- (NSString *) primaryPurpose {
2655 for (NSString *tag in tags_)
2656 if ([tag hasPrefix:@"purpose::"])
2657 return [tag substringFromIndex:9];
2658 return nil;
2659}
2660
770f2a8e
JF
2661- (NSArray *) purposes {
2662 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2663 for (NSString *tag in tags_)
2664 if ([tag hasPrefix:@"purpose::"])
2665 [purposes addObject:[tag substringFromIndex:9]];
2666 return [purposes count] == 0 ? nil : purposes;
2667}
2668
3bd1c2a2
JF
2669- (bool) isCommercial {
2670 return [self hasTag:@"cydia::commercial"];
2671}
2672
df213583
JF
2673- (CYString &) cyname {
2674 return name_.empty() ? id_ : name_;
f79a4512
JF
2675}
2676
f79a4512
JF
2677- (uint32_t) compareBySection:(NSArray *)sections {
2678 NSString *section([self section]);
2679 for (size_t i(0), e([sections count]); i != e; ++i) {
2680 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2681 return i;
36bb2ca2 2682 }
3178d79b 2683
f79a4512 2684 return _not(uint32_t);
36bb2ca2 2685}
3178d79b 2686
dc63e78f 2687- (void) clear {
c6ca67ba 2688@synchronized (database_) {
dc63e78f
JF
2689 pkgProblemResolver *resolver = [database_ resolver];
2690 resolver->Clear(iterator_);
c6ca67ba
JF
2691
2692 pkgCacheFile &cache([database_ cache]);
2693 cache->SetReInstall(iterator_, false);
2694 cache->MarkKeep(iterator_, false);
2695} }
dc63e78f 2696
36bb2ca2 2697- (void) install {
c6ca67ba 2698@synchronized (database_) {
36bb2ca2
JF
2699 pkgProblemResolver *resolver = [database_ resolver];
2700 resolver->Clear(iterator_);
2701 resolver->Protect(iterator_);
c6ca67ba 2702
36bb2ca2 2703 pkgCacheFile &cache([database_ cache]);
c6ca67ba 2704 cache->SetReInstall(iterator_, false);
36bb2ca2 2705 cache->MarkInstall(iterator_, false);
c6ca67ba 2706
36bb2ca2
JF
2707 pkgDepCache::StateCache &state((*cache)[iterator_]);
2708 if (!state.Install())
2709 cache->SetReInstall(iterator_, true);
c6ca67ba 2710} }
68a238ec 2711
36bb2ca2 2712- (void) remove {
c6ca67ba 2713@synchronized (database_) {
36bb2ca2
JF
2714 pkgProblemResolver *resolver = [database_ resolver];
2715 resolver->Clear(iterator_);
36bb2ca2 2716 resolver->Remove(iterator_);
c6ca67ba
JF
2717 resolver->Protect(iterator_);
2718
2719 pkgCacheFile &cache([database_ cache]);
2720 cache->SetReInstall(iterator_, false);
2721 cache->MarkDelete(iterator_, true);
2722} }
8fe19fc1 2723
0a3b45ef 2724- (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
808c6eb6
JF
2725 _profile(Package$isUnfilteredAndSearchedForBy)
2726 bool value(true);
2727
2728 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2729 value &= [self unfiltered];
2730 _end
2731
2732 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2733 value &= [self matches:search];
2734 _end
2735
0a3b45ef 2736 return value;
808c6eb6 2737 _end
36bb2ca2 2738}
8fe19fc1 2739
01d93940 2740- (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
ef055c6c
JF
2741 if ([search length] == 0)
2742 return false;
2743
01d93940
JF
2744 _profile(Package$isUnfilteredAndSelectedForBy)
2745 bool value(true);
2746
2747 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2748 value &= [self unfiltered];
2749 _end
2750
2751 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2752 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2753 _end
2754
2755 return value;
2756 _end
2757}
2758
e4f3d6e9
JF
2759- (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2760 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
36bb2ca2 2761}
8fe19fc1 2762
670a0494 2763- (bool) isVisibleInSection:(NSString *)name {
e4f3d6e9 2764 NSString *section([self section]);
5a09ae08 2765
e4f3d6e9
JF
2766 return (
2767 name == nil ||
2768 section == nil && [name length] == 0 ||
2769 [name isEqualToString:section]
2770 ) && [self visible];
7b0ce2da
JF
2771}
2772
0a3b45ef
JF
2773- (bool) isVisibleInSource:(Source *)source {
2774 return [self source] == source && [self visible];
36bb2ca2 2775}
8fe19fc1 2776
36bb2ca2
JF
2777@end
2778/* }}} */
2779/* Section Class {{{ */
2780@interface Section : NSObject {
2781 NSString *name_;
808c6eb6 2782 unichar index_;
36bb2ca2
JF
2783 size_t row_;
2784 size_t count_;
f79a4512 2785 NSString *localized_;
36bb2ca2 2786}
3178d79b 2787
677b8415 2788- (NSComparisonResult) compareByLocalized:(Section *)section;
9fcbca29
JF
2789- (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2790- (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2791- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
808c6eb6 2792- (Section *) initWithIndex:(unichar)index row:(size_t)row;
36bb2ca2 2793- (NSString *) name;
808c6eb6 2794- (unichar) index;
f79a4512 2795
36bb2ca2
JF
2796- (size_t) row;
2797- (size_t) count;
f79a4512
JF
2798
2799- (void) addToRow;
36bb2ca2 2800- (void) addToCount;
b19871dd 2801
f79a4512 2802- (void) setCount:(size_t)count;
677b8415 2803- (NSString *) localized;
f79a4512 2804
36bb2ca2 2805@end
b19871dd 2806
36bb2ca2 2807@implementation Section
b19871dd 2808
36bb2ca2
JF
2809- (void) dealloc {
2810 [name_ release];
f79a4512
JF
2811 if (localized_ != nil)
2812 [localized_ release];
36bb2ca2
JF
2813 [super dealloc];
2814}
b19871dd 2815
677b8415 2816- (NSComparisonResult) compareByLocalized:(Section *)section {
9fcbca29
JF
2817 NSString *lhs(localized_);
2818 NSString *rhs([section localized]);
6d9712c4 2819
9fcbca29 2820 /*if ([lhs length] != 0 && [rhs length] != 0) {
6d9712c4
JF
2821 unichar lhc = [lhs characterAtIndex:0];
2822 unichar rhc = [rhs characterAtIndex:0];
2823
2824 if (isalpha(lhc) && !isalpha(rhc))
2825 return NSOrderedAscending;
2826 else if (!isalpha(lhc) && isalpha(rhc))
2827 return NSOrderedDescending;
9fcbca29 2828 }*/
6d9712c4 2829
68f1828e 2830 return [lhs compare:rhs options:LaxCompareOptions_];
6d9712c4
JF
2831}
2832
9fcbca29
JF
2833- (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2834 if ((self = [self initWithName:name localize:NO]) != nil) {
2835 if (localized != nil)
2836 localized_ = [localized retain];
2837 } return self;
2838}
2839
2840- (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2841 return [self initWithName:name row:0 localize:localize];
6d9712c4
JF
2842}
2843
9fcbca29 2844- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
36bb2ca2
JF
2845 if ((self = [super init]) != nil) {
2846 name_ = [name retain];
808c6eb6
JF
2847 index_ = '\0';
2848 row_ = row;
9fcbca29
JF
2849 if (localize)
2850 localized_ = [LocalizeSection(name_) retain];
808c6eb6
JF
2851 } return self;
2852}
2853
f79a4512 2854/* XXX: localize the index thingees */
808c6eb6
JF
2855- (Section *) initWithIndex:(unichar)index row:(size_t)row {
2856 if ((self = [super init]) != nil) {
327624b6 2857 name_ = [[NSString stringWithCharacters:&index length:1] retain];
808c6eb6 2858 index_ = index;
36bb2ca2 2859 row_ = row;
b19871dd
JF
2860 } return self;
2861}
2862
36bb2ca2
JF
2863- (NSString *) name {
2864 return name_;
2865}
2866
808c6eb6
JF
2867- (unichar) index {
2868 return index_;
2869}
2870
36bb2ca2
JF
2871- (size_t) row {
2872 return row_;
2873}
2874
2875- (size_t) count {
2876 return count_;
2877}
2878
f79a4512
JF
2879- (void) addToRow {
2880 ++row_;
2881}
2882
36bb2ca2
JF
2883- (void) addToCount {
2884 ++count_;
2885}
2886
f79a4512
JF
2887- (void) setCount:(size_t)count {
2888 count_ = count;
2889}
2890
2891- (NSString *) localized {
2892 return localized_;
2893}
2894
b19871dd
JF
2895@end
2896/* }}} */
2897
670a0494 2898static NSString *Colon_;
72fb3616 2899static NSString *Elision_;
670a0494
JF
2900static NSString *Error_;
2901static NSString *Warning_;
2902
36bb2ca2
JF
2903/* Database Implementation {{{ */
2904@implementation Database
ec97ef06 2905
770f2a8e
JF
2906+ (Database *) sharedInstance {
2907 static Database *instance;
2908 if (instance == nil)
2909 instance = [[Database alloc] init];
2910 return instance;
2911}
2912
a1440b10
JF
2913- (unsigned) era {
2914 return era_;
2915}
2916
0944377b
JF
2917- (void) releasePackages {
2918 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
2919 CFArrayRemoveAllValues(packages_);
2920}
2921
36bb2ca2 2922- (void) dealloc {
3931b718 2923 // XXX: actually implement this thing
36bb2ca2 2924 _assert(false);
0944377b 2925 [self releasePackages];
f79a4512 2926 apr_pool_destroy(pool_);
0944377b 2927 NSRecycleZone(zone_);
36bb2ca2
JF
2928 [super dealloc];
2929}
ec97ef06 2930
affeffc7 2931- (void) _readCydia:(NSNumber *)fd { _pooled
77fcccaf
JF
2932 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2933 std::istream is(&ib);
2934 std::string line;
2935
bc8cd583
JF
2936 static Pcre finish_r("^finish:([^:]*)$");
2937
77fcccaf
JF
2938 while (std::getline(is, line)) {
2939 const char *data(line.c_str());
bc8cd583 2940 size_t size = line.size();
c390d3ab 2941 lprintf("C:%s\n", data);
bc8cd583
JF
2942
2943 if (finish_r(data, size)) {
2944 NSString *finish = finish_r[1];
2945 int index = [Finishes_ indexOfObject:finish];
2946 if (index != INT_MAX && index > Finish_)
2947 Finish_ = index;
2948 }
77fcccaf
JF
2949 }
2950
670a0494 2951 _assume(false);
77fcccaf
JF
2952}
2953
affeffc7 2954- (void) _readStatus:(NSNumber *)fd { _pooled
36bb2ca2
JF
2955 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2956 std::istream is(&ib);
2957 std::string line;
ec97ef06 2958
7b0ce2da
JF
2959 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2960 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
ec97ef06 2961
36bb2ca2
JF
2962 while (std::getline(is, line)) {
2963 const char *data(line.c_str());
670a0494 2964 size_t size(line.size());
c390d3ab 2965 lprintf("S:%s\n", data);
ec97ef06 2966
5a09ae08
JF
2967 if (conffile_r(data, size)) {
2968 [delegate_ setConfigurationData:conffile_r[1]];
2969 } else if (strncmp(data, "status: ", 8) == 0) {
2970 NSString *string = [NSString stringWithUTF8String:(data + 8)];
36bb2ca2 2971 [delegate_ setProgressTitle:string];
5a09ae08 2972 } else if (pmstatus_r(data, size)) {
31f3cfff
JF
2973 std::string type([pmstatus_r[1] UTF8String]);
2974 NSString *id = pmstatus_r[2];
2975
5a09ae08
JF
2976 float percent([pmstatus_r[3] floatValue]);
2977 [delegate_ setProgressPercent:(percent / 100)];
2978
2979 NSString *string = pmstatus_r[4];
5a09ae08
JF
2980
2981 if (type == "pmerror")
670a0494 2982 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
31f3cfff
JF
2983 withObject:[NSArray arrayWithObjects:string, id, nil]
2984 waitUntilDone:YES
2985 ];
9487f027 2986 else if (type == "pmstatus") {
5a09ae08 2987 [delegate_ setProgressTitle:string];
9487f027 2988 } else if (type == "pmconffile")
5a09ae08 2989 [delegate_ setConfigurationData:string];
670a0494
JF
2990 else
2991 lprintf("E:unknown pmstatus\n");
2992 } else
2993 lprintf("E:unknown status\n");
36bb2ca2 2994 }
ec97ef06 2995
670a0494 2996 _assume(false);
36bb2ca2 2997}
ec97ef06 2998
affeffc7 2999- (void) _readOutput:(NSNumber *)fd { _pooled
36bb2ca2
JF
3000 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3001 std::istream is(&ib);
3002 std::string line;
3003
5a09ae08 3004 while (std::getline(is, line)) {
c390d3ab 3005 lprintf("O:%s\n", line.c_str());
2388b078 3006 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
5a09ae08 3007 }
36bb2ca2 3008
670a0494 3009 _assume(false);
ec97ef06
JF
3010}
3011
8b29f8e6
JF
3012- (FILE *) input {
3013 return input_;
3014}
3015
36bb2ca2 3016- (Package *) packageWithName:(NSString *)name {
3dd53516 3017@synchronized (self) {
5a09ae08
JF
3018 if (static_cast<pkgDepCache *>(cache_) == NULL)
3019 return nil;
36bb2ca2 3020 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
f79a4512 3021 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
28ce8704 3022} }
36bb2ca2 3023
eb30da80 3024- (id) init {
ec97ef06 3025 if ((self = [super init]) != nil) {
5a09ae08 3026 policy_ = NULL;
36bb2ca2
JF
3027 records_ = NULL;
3028 resolver_ = NULL;
3029 fetcher_ = NULL;
3030 lock_ = NULL;
ec97ef06 3031
f79a4512
JF
3032 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3033 apr_pool_create(&pool_, NULL);
3034
077e9d90 3035 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
ec97ef06 3036
36bb2ca2 3037 int fds[2];
ec97ef06 3038
77fcccaf
JF
3039 _assert(pipe(fds) != -1);
3040 cydiafd_ = fds[1];
3041
3042 _config->Set("APT::Keep-Fds::", cydiafd_);
bc8cd583 3043 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
77fcccaf
JF
3044
3045 [NSThread
3046 detachNewThreadSelector:@selector(_readCydia:)
3047 toTarget:self
3931b718 3048 withObject:[NSNumber numberWithInt:fds[0]]
77fcccaf
JF
3049 ];
3050
36bb2ca2
JF
3051 _assert(pipe(fds) != -1);
3052 statusfd_ = fds[1];
ec97ef06 3053
36bb2ca2
JF
3054 [NSThread
3055 detachNewThreadSelector:@selector(_readStatus:)
3056 toTarget:self
3931b718 3057 withObject:[NSNumber numberWithInt:fds[0]]
36bb2ca2 3058 ];
ec97ef06 3059
8b29f8e6
JF
3060 _assert(pipe(fds) != -1);
3061 _assert(dup2(fds[0], 0) != -1);
3062 _assert(close(fds[0]) != -1);
3063
3064 input_ = fdopen(fds[1], "a");
3065
36bb2ca2
JF
3066 _assert(pipe(fds) != -1);
3067 _assert(dup2(fds[1], 1) != -1);
3068 _assert(close(fds[1]) != -1);
3069
3070 [NSThread
3071 detachNewThreadSelector:@selector(_readOutput:)
3072 toTarget:self
3931b718 3073 withObject:[NSNumber numberWithInt:fds[0]]
36bb2ca2 3074 ];
ec97ef06
JF
3075 } return self;
3076}
3077
36bb2ca2
JF
3078- (pkgCacheFile &) cache {
3079 return cache_;
ec97ef06
JF
3080}
3081
5a09ae08
JF
3082- (pkgDepCache::Policy *) policy {
3083 return policy_;
3084}
3085
36bb2ca2
JF
3086- (pkgRecords *) records {
3087 return records_;
ec97ef06
JF
3088}
3089
36bb2ca2
JF
3090- (pkgProblemResolver *) resolver {
3091 return resolver_;
ec97ef06
JF
3092}
3093
36bb2ca2
JF
3094- (pkgAcquire &) fetcher {
3095 return *fetcher_;
ec97ef06
JF
3096}
3097
a3328c28
JF
3098- (pkgSourceList &) list {
3099 return *list_;
3100}
3101
36bb2ca2 3102- (NSArray *) packages {
077e9d90 3103 return (NSArray *) packages_;
ec97ef06
JF
3104}
3105
7b0ce2da 3106- (NSArray *) sources {
68d927e2
JF
3107 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3108 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3109 [sources addObject:i->second];
3110 return sources;
7b0ce2da
JF
3111}
3112
affeffc7
JF
3113- (NSArray *) issues {
3114 if (cache_->BrokenCount() == 0)
3115 return nil;
3116
3117 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3118
077e9d90 3119 for (Package *package in [self packages]) {
affeffc7
JF
3120 if (![package broken])
3121 continue;
3122 pkgCache::PkgIterator pkg([package iterator]);
3123
3124 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3125 [entry addObject:[package name]];
3126 [issues addObject:entry];
3127
3128 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3129 if (ver.end())
3130 continue;
3131
3132 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3133 pkgCache::DepIterator start;
3134 pkgCache::DepIterator end;
3135 dep.GlobOr(start, end); // ++dep
3136
3137 if (!cache_->IsImportantDep(end))
3138 continue;
3139 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3140 continue;
3141
3142 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3143 [entry addObject:failure];
3144 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3145
744f398e
JF
3146 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3147 if (Package *package = [self packageWithName:name])
3148 name = [package name];
3149 [failure addObject:name];
affeffc7
JF
3150
3151 pkgCache::PkgIterator target(start.TargetPkg());
3152 if (target->ProvidesList != 0)
3153 [failure addObject:@"?"];
3154 else {
3155 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3156 if (!ver.end())
3157 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3158 else if (!cache_[target].CandidateVerIter(cache_).end())
3159 [failure addObject:@"-"];
3160 else if (target->ProvidesList == 0)
3161 [failure addObject:@"!"];
3162 else
3163 [failure addObject:@"%"];
3164 }
3165
3166 _forever {
3167 if (start.TargetVer() != 0)
3168 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3169 if (start == end)
3170 break;
3171 ++start;
3172 }
3173 }
3174 }
3175
3176 return issues;
3177}
3178
670a0494
JF
3179- (bool) popErrorWithTitle:(NSString *)title {
3180 bool fatal(false);
3181 std::string message;
3182
3183 while (!_error->empty()) {
3184 std::string error;
3185 bool warning(!_error->PopMessage(error));
3186 if (!warning)
3187 fatal = true;
3188 for (;;) {
3189 size_t size(error.size());
3190 if (size == 0 || error[size - 1] != '\n')
3191 break;
3192 error.resize(size - 1);
3193 }
3194 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3195
3196 if (!message.empty())
3197 message += "\n\n";
3198 message += error;
3199 }
3200
ef348024 3201 if (fatal && !message.empty())
670a0494
JF
3202 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3203
3204 return fatal;
3205}
3206
3207- (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3208 return [self popErrorWithTitle:title] || !success;
3209}
3210
53bed0ff 3211- (void) reloadData { CYPoolStart() {
3dd53516
JF
3212@synchronized (self) {
3213 ++era_;
a1440b10 3214
0944377b 3215 [self releasePackages];
843e75b8
JF
3216 sources_.clear();
3217
36bb2ca2 3218 _error->Discard();
5a09ae08 3219
36bb2ca2 3220 delete list_;
5a09ae08 3221 list_ = NULL;
36bb2ca2
JF
3222 manager_ = NULL;
3223 delete lock_;
5a09ae08 3224 lock_ = NULL;
36bb2ca2 3225 delete fetcher_;
5a09ae08 3226 fetcher_ = NULL;
36bb2ca2 3227 delete resolver_;
5a09ae08 3228 resolver_ = NULL;
36bb2ca2 3229 delete records_;
5a09ae08
JF
3230 records_ = NULL;
3231 delete policy_;
3232 policy_ = NULL;
36bb2ca2 3233
843e75b8
JF
3234 if (now_ != nil) {
3235 [now_ release];
3236 now_ = nil;
3237 }
3238
5a09ae08 3239 cache_.Close();
8b29f8e6 3240
f79a4512
JF
3241 apr_pool_clear(pool_);
3242 NSRecycleZone(zone_);
3243
7376b55c
JF
3244 int chk(creat("/tmp/cydia.chk", 0644));
3245 if (chk != -1)
3246 close(chk);
3247
670a0494
JF
3248 NSString *title(UCLocalize("DATABASE"));
3249
9487f027 3250 _trace();
670a0494 3251 if (!cache_.Open(progress_, true)) { pop:
8b29f8e6 3252 std::string error;
670a0494 3253 bool warning(!_error->PopMessage(error));
c390d3ab 3254 lprintf("cache_.Open():[%s]\n", error.c_str());
5a09ae08
JF
3255
3256 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3257 [delegate_ repairWithSelector:@selector(configure)];
3258 else if (error == "The package lists or status file could not be parsed or opened.")
3259 [delegate_ repairWithSelector:@selector(update)];
9ea8d159
JF
3260 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3261 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3262 // else if (error == "The list of sources could not be read.")
670a0494
JF
3263 else
3264 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
5a09ae08 3265
670a0494
JF
3266 if (warning)
3267 goto pop;
3268 _error->Discard();
5a09ae08 3269 return;
36bb2ca2 3270 }
9487f027 3271 _trace();
36bb2ca2 3272
7376b55c
JF
3273 unlink("/tmp/cydia.chk");
3274
36bb2ca2
JF
3275 now_ = [[NSDate date] retain];
3276
5a09ae08 3277 policy_ = new pkgDepCache::Policy();
36bb2ca2
JF
3278 records_ = new pkgRecords(cache_);
3279 resolver_ = new pkgProblemResolver(cache_);
3280 fetcher_ = new pkgAcquire(&status_);
3281 lock_ = NULL;
3282
3283 list_ = new pkgSourceList();
670a0494
JF
3284 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3285 return;
3286
3287 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3288 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3289 return;
3290 }
36bb2ca2 3291
670a0494
JF
3292 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3293 return;
9bedffaa
JF
3294
3295 if (cache_->BrokenCount() != 0) {
670a0494
JF
3296 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3297 return;
3298
3299 if (cache_->BrokenCount() != 0) {
3300 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3301 return;
3302 }
3303
3304 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3305 return;
9bedffaa
JF
3306 }
3307
68d927e2
JF
3308 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3309 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3310 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3311 // XXX: this could be more intelligent
3312 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3313 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3314 if (!cached.end())
f9f6d9e8 3315 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
68d927e2 3316 }
36bb2ca2 3317 }
68d927e2 3318
677b8415 3319 {
9fcbca29 3320 /*std::vector<Package *> packages;
677b8415 3321 packages.reserve(std::max(10000U, [packages_ count] + 1000));
677b8415 3322 [packages_ release];
9fcbca29
JF
3323 packages_ = nil;*/
3324
677b8415
JF
3325 _trace();
3326
3327 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3328 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
9fcbca29 3329 //packages.push_back(package);
077e9d90 3330 CFArrayAppendValue(packages_, [package retain]);
677b8415
JF
3331
3332 _trace();
3333
9fcbca29 3334 /*if (packages.empty())
677b8415
JF
3335 packages_ = [[NSArray alloc] init];
3336 else
3337 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
9fcbca29
JF
3338 _trace();*/
3339
077e9d90
JF
3340 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3341 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3342 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
9fcbca29
JF
3343
3344 /*_trace();
3345 PrintTimes();
3346 _trace();*/
3347
3348 _trace();
3349
3350 /*if (!packages.empty())
3351 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3352 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3353
eef4ccaf
JF
3354 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3355
077e9d90 3356 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
9fcbca29
JF
3357
3358 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
677b8415
JF
3359
3360 _trace();
3361 }
c626a63f 3362} } CYPoolEnd() _trace(); }
ec97ef06 3363
c6ca67ba
JF
3364- (void) clear {
3365@synchronized (self) {
3366 delete resolver_;
3367 resolver_ = new pkgProblemResolver(cache_);
3368
3369 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3370 if (!cache_[iterator].Keep()) {
3371 cache_->MarkKeep(iterator, false);
3372 cache_->SetReInstall(iterator, false);
3373 }
3374 }
3375} }
3376
5a09ae08
JF
3377- (void) configure {
3378 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3379 system([dpkg UTF8String]);
3380}
3381
670a0494
JF
3382- (bool) clean {
3383 // XXX: I don't remember this condition
77fcccaf 3384 if (lock_ != NULL)
670a0494 3385 return false;
77fcccaf
JF
3386
3387 FileFd Lock;
3388 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
670a0494
JF
3389
3390 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3391
3392 if ([self popErrorWithTitle:title])
3393 return false;
77fcccaf
JF
3394
3395 pkgAcquire fetcher;
3396 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3397
9bedffaa
JF
3398 class LogCleaner :
3399 public pkgArchiveCleaner
3400 {
77fcccaf
JF
3401 protected:
3402 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
9bedffaa 3403 unlink(File);
77fcccaf
JF
3404 }
3405 } cleaner;
3406
670a0494
JF
3407 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3408 return false;
3409
3410 return true;
77fcccaf
JF
3411}
3412
670a0494 3413- (bool) prepare {
744f398e
JF
3414 fetcher_->Shutdown();
3415
36bb2ca2
JF
3416 pkgRecords records(cache_);
3417
3418 lock_ = new FileFd();
3419 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
670a0494
JF
3420
3421 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3422
3423 if ([self popErrorWithTitle:title])
3424 return false;
36bb2ca2
JF
3425
3426 pkgSourceList list;
670a0494
JF
3427 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3428 return false;
36bb2ca2
JF
3429
3430 manager_ = (_system->CreatePM(cache_));
670a0494
JF
3431 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3432 return false;
3433
3434 return true;
ec97ef06
JF
3435}
3436
36bb2ca2 3437- (void) perform {
670a0494
JF
3438 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3439
a72074b2
JF
3440 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3441 pkgSourceList list;
670a0494
JF
3442 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3443 return;
a72074b2
JF
3444 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3445 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3446 }
a0be02eb 3447
eeb9b112
JF
3448 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3449 _trace();
36bb2ca2 3450 return;
eeb9b112
JF
3451 }
3452
3453 bool failed = false;
3454 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3455 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3456 continue;
6204f56a
JF
3457 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3458 continue;
eeb9b112
JF
3459
3460 std::string uri = (*item)->DescURI();
3461 std::string error = (*item)->ErrorText;
3462
c390d3ab 3463 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
eeb9b112
JF
3464 failed = true;
3465
670a0494 3466 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
a3328c28
JF
3467 withObject:[NSArray arrayWithObjects:
3468 [NSString stringWithUTF8String:error.c_str()],
3469 nil]
eeb9b112
JF
3470 waitUntilDone:YES
3471 ];
3472 }
3473
3474 if (failed) {
3475 _trace();
3476 return;
3477 }
36bb2ca2
JF
3478
3479 _system->UnLock();
3480 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3481
eeb9b112
JF
3482 if (_error->PendingError()) {
3483 _trace();
36bb2ca2 3484 return;
eeb9b112
JF
3485 }
3486
3487 if (result == pkgPackageManager::Failed) {
3488 _trace();
36bb2ca2 3489 return;
eeb9b112
JF
3490 }
3491
3492 if (result != pkgPackageManager::Completed) {
3493 _trace();
36bb2ca2 3494 return;
eeb9b112 3495 }
a0be02eb 3496
a72074b2
JF
3497 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3498 pkgSourceList list;
670a0494
JF
3499 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3500 return;
a72074b2
JF
3501 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3502 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3503 }
3504
3505 if (![before isEqualToArray:after])
3506 [self update];
ec97ef06
JF
3507}
3508
670a0494
JF
3509- (bool) upgrade {
3510 NSString *title(UCLocalize("UPGRADE"));
3511 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3512 return false;
3513 return true;
c7c6384e
JF
3514}
3515
36bb2ca2
JF
3516- (void) update {
3517 [self updateWithStatus:status_];
3518}
b4d89997 3519
670a0494
JF
3520- (void) updateWithStatus:(Status &)status {
3521 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3522 NSString *title(UCLocalize("REFRESHING_DATA"));
3523
36bb2ca2 3524 pkgSourceList list;
670a0494
JF
3525 if (!list.ReadMainList())
3526 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
b4d89997 3527
36bb2ca2
JF
3528 FileFd lock;
3529 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
670a0494
JF
3530 if ([self popErrorWithTitle:title])
3531 return;
18873623 3532
670a0494 3533 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
eb30da80
GP
3534 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3535 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
36bb2ca2 3536
7623f855
JF
3537 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3538 Changed_ = true;
b4d89997
JF
3539}
3540
36bb2ca2
JF
3541- (void) setDelegate:(id)delegate {
3542 delegate_ = delegate;
3543 status_.setDelegate(delegate);
3544 progress_.setDelegate(delegate);
3545}
b4d89997 3546
7376b55c 3547- (Source *) getSource:(pkgCache::PkgFileIterator)file {
20cb1497
JF
3548 SourceMap::const_iterator i(sources_.find(file->ID));
3549 return i == sources_.end() ? nil : i->second;
b19871dd
JF
3550}
3551
36bb2ca2
JF
3552@end
3553/* }}} */
b4d89997 3554
adb61bda 3555/* Confirmation Controller {{{ */
43f3d7f6
JF
3556bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3557 if (!iterator.end())
3558 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3559 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3560 continue;
3561 pkgCache::PkgIterator package(dep.TargetPkg());
3562 if (package.end())
3563 continue;
3564 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3565 return true;
3566 }
3567
3568 return false;
c390d3ab 3569}
b5e7eebb 3570/* }}} */
c390d3ab 3571
43f3d7f6
JF
3572/* Web Scripting {{{ */
3573@interface CydiaObject : NSObject {
3574 id indirect_;
3931b718 3575 _transient id delegate_;
43f3d7f6 3576}
c390d3ab 3577
43f3d7f6 3578- (id) initWithDelegate:(IndirectDelegate *)indirect;
c390d3ab
JF
3579@end
3580
43f3d7f6 3581@implementation CydiaObject
c390d3ab
JF
3582
3583- (void) dealloc {
43f3d7f6 3584 [indirect_ release];
c390d3ab
JF
3585 [super dealloc];
3586}
3587
43f3d7f6
JF
3588- (id) initWithDelegate:(IndirectDelegate *)indirect {
3589 if ((self = [super init]) != nil) {
3590 indirect_ = [indirect retain];
3591 } return self;
3592}
3593
77801ff1
JF
3594- (void) setDelegate:(id)delegate {
3595 delegate_ = delegate;
3596}
3597
43f3d7f6
JF
3598+ (NSArray *) _attributeKeys {
3599 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3600}
3601
3602- (NSArray *) attributeKeys {
3603 return [[self class] _attributeKeys];
c390d3ab
JF
3604}
3605
43f3d7f6
JF
3606+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3607 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
c390d3ab 3608}
43f3d7f6
JF
3609
3610- (NSString *) device {
3611 return [[UIDevice currentDevice] uniqueIdentifier];
c390d3ab
JF
3612}
3613
43f3d7f6
JF
3614#if 0 // XXX: implement!
3615- (NSString *) mac {
3616 if (![indirect_ promptForSensitive:@"Mac Address"])
3617 return nil;
affeffc7
JF
3618}
3619
43f3d7f6
JF
3620- (NSString *) serial {
3621 if (![indirect_ promptForSensitive:@"Serial #"])
3622 return nil;
3623}
86316a91 3624
43f3d7f6
JF
3625- (NSString *) firewire {
3626 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3627 return nil;
affeffc7
JF
3628}
3629
43f3d7f6
JF
3630- (NSString *) imei {
3631 if (![indirect_ promptForSensitive:@"IMEI"])
3632 return nil;
3633}
3634#endif
3635
3636+ (NSString *) webScriptNameForSelector:(SEL)selector {
3637 if (selector == @selector(close))
3638 return @"close";
8cc8eb1c
JF
3639 else if (selector == @selector(getInstalledPackages))
3640 return @"getInstalledPackages";
43f3d7f6
JF
3641 else if (selector == @selector(getPackageById:))
3642 return @"getPackageById";
77801ff1
JF
3643 else if (selector == @selector(installPackages:))
3644 return @"installPackages";
43f3d7f6
JF
3645 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3646 return @"setButtonImage";
3647 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3648 return @"setButtonTitle";
43f3d7f6
JF
3649 else if (selector == @selector(setPopupHook:))
3650 return @"setPopupHook";
3651 else if (selector == @selector(setSpecial:))
3652 return @"setSpecial";
ef055c6c
JF
3653 else if (selector == @selector(setToken:))
3654 return @"setToken";
43f3d7f6
JF
3655 else if (selector == @selector(setViewportWidth:))
3656 return @"setViewportWidth";
3657 else if (selector == @selector(supports:))
3658 return @"supports";
3659 else if (selector == @selector(stringWithFormat:arguments:))
3660 return @"format";
3661 else if (selector == @selector(localizedStringForKey:value:table:))
3662 return @"localize";
3663 else if (selector == @selector(du:))
3664 return @"du";
3665 else if (selector == @selector(statfs:))
3666 return @"statfs";
c390d3ab 3667 else
43f3d7f6
JF
3668 return nil;
3669}
3670
3671+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3672 return [self webScriptNameForSelector:selector] == nil;
c390d3ab
JF
3673}
3674
43f3d7f6
JF
3675- (BOOL) supports:(NSString *)feature {
3676 return [feature isEqualToString:@"window.open"];
3677}
c390d3ab 3678
8cc8eb1c
JF
3679- (NSArray *) getInstalledPackages {
3680 NSArray *packages([[Database sharedInstance] packages]);
f4db946e 3681 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
77801ff1 3682 for (Package *package in packages)
8cc8eb1c
JF
3683 if ([package installed] != nil)
3684 [installed addObject:package];
3685 return installed;
3686}
3687
43f3d7f6 3688- (Package *) getPackageById:(NSString *)id {
043e6a2e
JF
3689 Package *package([[Database sharedInstance] packageWithName:id]);
3690 [package parse];
3691 return package;
43f3d7f6
JF
3692}
3693
3694- (NSArray *) statfs:(NSString *)path {
3695 struct statfs stat;
3696
3697 if (path == nil || statfs([path UTF8String], &stat) == -1)
3698 return nil;
3699
3700 return [NSArray arrayWithObjects:
3701 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3702 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3703 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3704 nil];
3705}
3706
3707- (NSNumber *) du:(NSString *)path {
3708 NSNumber *value(nil);
3709
3710 int fds[2];
3711 _assert(pipe(fds) != -1);
3712
3713 pid_t pid(ExecFork());
3714 if (pid == 0) {
3715 _assert(dup2(fds[1], 1) != -1);
3716 _assert(close(fds[0]) != -1);
3717 _assert(close(fds[1]) != -1);
3718 /* XXX: this should probably not use du */
3719 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3720 exit(1);
3721 _assert(false);
3722 }
3723
3724 _assert(close(fds[1]) != -1);
3725
3726 if (FILE *du = fdopen(fds[0], "r")) {
3727 char line[1024];
3728 while (fgets(line, sizeof(line), du) != NULL) {
3729 size_t length(strlen(line));
3730 while (length != 0 && line[length - 1] == '\n')
3731 line[--length] = '\0';
3732 if (char *tab = strchr(line, '\t')) {
3733 *tab = '\0';
3734 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3735 }
3736 }
3737
3738 fclose(du);
3739 } else _assert(close(fds[0]));
3740
3741 int status;
3742 wait:
3743 if (waitpid(pid, &status, 0) == -1)
3744 if (errno == EINTR)
3745 goto wait;
3746 else _assert(false);
3747
3748 return value;
3749}
3750
3751- (void) close {
3752 [indirect_ close];
3753}
3754
77801ff1
JF
3755- (void) installPackages:(NSArray *)packages {
3756 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3757}
3758
43f3d7f6
JF
3759- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3760 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3761}
3762
3763- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3764 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3765}
3766
3767- (void) setSpecial:(id)function {
3768 [indirect_ setSpecial:function];
3769}
3770
ef055c6c
JF
3771- (void) setToken:(NSString *)token {
3772 if (Token_ != nil)
3773 [Token_ release];
3774 Token_ = [token retain];
3775
3776 [Metadata_ setObject:Token_ forKey:@"Token"];
3777 Changed_ = true;
3778}
3779
43f3d7f6
JF
3780- (void) setPopupHook:(id)function {
3781 [indirect_ setPopupHook:function];
3782}
3783
3784- (void) setViewportWidth:(float)width {
3785 [indirect_ setViewportWidth:width];
3786}
3787
3788- (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3789 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3790 unsigned count([arguments count]);
3791 id values[count];
3792 for (unsigned i(0); i != count; ++i)
3793 values[i] = [arguments objectAtIndex:i];
eb30da80 3794 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
43f3d7f6
JF
3795}
3796
3797- (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
a95e0405
JF
3798 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3799 value = nil;
43f3d7f6
JF
3800 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3801 table = nil;
3802 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
c390d3ab
JF
3803}
3804
3805@end
3806/* }}} */
f79a4512 3807
80319240 3808/* Cydia Browser Controller {{{ */
40bfa2e6 3809@interface CYBrowserController : BrowserController {
43f3d7f6
JF
3810 CydiaObject *cydia_;
3811}
a9a0661e 3812
43f3d7f6
JF
3813@end
3814
b5e7eebb 3815@implementation CYBrowserController
43f3d7f6
JF
3816
3817- (void) dealloc {
3818 [cydia_ release];
3819 [super dealloc];
3820}
3821
01d93940
JF
3822- (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3823}
3824
2634b249
JF
3825- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3826 [super webView:view didClearWindowObject:window forFrame:frame];
01d93940
JF
3827
3828 WebDataSource *source([frame dataSource]);
3829 NSURLResponse *response([source response]);
3830 NSURL *url([response URL]);
3831 NSString *scheme([url scheme]);
3832
3833 NSHTTPURLResponse *http;
3834 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3835 http = (NSHTTPURLResponse *) response;
3836 else
3837 http = nil;
3838
3839 NSDictionary *headers([http allHeaderFields]);
3840 NSString *host([url host]);
3841 [self setHeaders:headers forHost:host];
3842
77801ff1
JF
3843 if (
3844 [host isEqualToString:@"cydia.saurik.com"] ||
3845 [host hasSuffix:@".cydia.saurik.com"] ||
3846 [scheme isEqualToString:@"file"]
3847 )
ef055c6c 3848 [window setValue:cydia_ forKey:@"cydia"];
43f3d7f6
JF
3849}
3850
bfc87a4d
JF
3851- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3852 if (System_ != NULL)
3853 [request setValue:System_ forHTTPHeaderField:@"X-System"];
43f3d7f6 3854 if (Machine_ != NULL)
bfc87a4d 3855 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
01d93940
JF
3856 if (Token_ != nil)
3857 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
43f3d7f6 3858 if (Role_ != nil)
bfc87a4d
JF
3859 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3860}
43f3d7f6 3861
2634b249
JF
3862- (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3863 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
bfc87a4d 3864 [self _setMoreHeaders:copy];
43f3d7f6 3865 return copy;
a9a0661e
JF
3866}
3867
77801ff1
JF
3868- (void) setDelegate:(id)delegate {
3869 [super setDelegate:delegate];
3870 [cydia_ setDelegate:delegate];
3871}
3872
b5e7eebb 3873- (id) init {
6d166849 3874 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
43f3d7f6
JF
3875 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3876
2634b249 3877 WebView *webview([[webview_ _documentView] webView]);
43f3d7f6
JF
3878
3879 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
35bf217f 3880
43f3d7f6
JF
3881 NSString *application = package == nil ? @"Cydia" : [NSString
3882 stringWithFormat:@"Cydia/%@",
3883 [package installed]
3884 ];
3885
43f3d7f6 3886 if (Safari_ != nil)
9ef18597 3887 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
35bf217f 3888 if (Build_ != nil)
9ef18597 3889 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
35bf217f 3890 if (Product_ != nil)
9ef18597 3891 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
43f3d7f6
JF
3892
3893 [webview setApplicationNameForUserAgent:application];
3894 } return self;
3895}
3896
3897@end
80319240 3898/* }}} */
43f3d7f6 3899
80319240 3900/* Confirmation {{{ */
adb61bda 3901@protocol ConfirmationControllerDelegate
674dce72 3902- (void) cancelAndClear:(bool)clear;
b5e7eebb 3903- (void) confirmWithNavigationController:(UINavigationController *)navigation;
dc63e78f 3904- (void) queue;
36bb2ca2 3905@end
2367a917 3906
adb61bda 3907@interface ConfirmationController : CYBrowserController {
770f2a8e 3908 _transient Database *database_;
3272e699 3909 UIAlertView *essential_;
affeffc7
JF
3910 NSArray *changes_;
3911 NSArray *issues_;
3912 NSArray *sizes_;
a9a0661e 3913 BOOL substrate_;
36bb2ca2 3914}
dc5812ec 3915
b5e7eebb 3916- (id) initWithDatabase:(Database *)database;
b4d89997 3917
dc5812ec
JF
3918@end
3919
adb61bda 3920@implementation ConfirmationController
dc5812ec 3921
2367a917 3922- (void) dealloc {
affeffc7
JF
3923 [changes_ release];
3924 if (issues_ != nil)
3925 [issues_ release];
3926 [sizes_ release];
36bb2ca2
JF
3927 if (essential_ != nil)
3928 [essential_ release];
2367a917
JF
3929 [super dealloc];
3930}
3931
b5e7eebb 3932- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3272e699 3933 NSString *context([alert context]);
9bedffaa 3934
1cedb821 3935 if ([context isEqualToString:@"remove"]) {
b5e7eebb
GP
3936 if (button == [alert cancelButtonIndex]) {
3937 [self dismissModalViewControllerAnimated:YES];
3272e699 3938 } else if (button == [alert firstOtherButtonIndex]) {
b5e7eebb
GP
3939 if (substrate_)
3940 Finish_ = 2;
3941 [delegate_ confirmWithNavigationController:[self navigationController]];
9bedffaa 3942 }
9bedffaa 3943
3272e699 3944 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 3945 } else if ([context isEqualToString:@"unable"]) {
b5e7eebb 3946 [self dismissModalViewControllerAnimated:YES];
3272e699
GP
3947 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3948 } else {
b5e7eebb
GP
3949 [super alertView:alert clickedButtonAtIndex:button];
3950 }
36bb2ca2
JF
3951}
3952
46c46f4f 3953- (void) _doContinue {
21ea11a4
GP
3954 [self dismissModalViewControllerAnimated:YES];
3955 [delegate_ cancelAndClear:NO];
46c46f4f 3956}
bc11cf5b 3957
46c46f4f
JF
3958- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3959 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
21ea11a4
GP
3960 return nil;
3961}
3962
2634b249
JF
3963- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3964 [super webView:view didClearWindowObject:window forFrame:frame];
affeffc7
JF
3965 [window setValue:changes_ forKey:@"changes"];
3966 [window setValue:issues_ forKey:@"issues"];
3967 [window setValue:sizes_ forKey:@"sizes"];
21ea11a4 3968 [window setValue:self forKey:@"queue"];
36bb2ca2
JF
3969}
3970
b5e7eebb
GP
3971- (id) initWithDatabase:(Database *)database {
3972 if ((self = [super init]) != nil) {
770f2a8e
JF
3973 database_ = database;
3974
b5e7eebb
GP
3975 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
3976
36bb2ca2
JF
3977 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3978 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3979 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3980 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3981 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
dc5812ec 3982
36bb2ca2 3983 bool remove(false);
dc5812ec 3984
a9a0661e
JF
3985 pkgDepCache::Policy *policy([database_ policy]);
3986
36bb2ca2 3987 pkgCacheFile &cache([database_ cache]);
2388b078 3988 NSArray *packages = [database_ packages];
c4dcf2c2 3989 for (Package *package in packages) {
2388b078 3990 pkgCache::PkgIterator iterator = [package iterator];
36bb2ca2 3991 pkgDepCache::StateCache &state(cache[iterator]);
dc5812ec 3992
2388b078
JF
3993 NSString *name([package name]);
3994
36bb2ca2
JF
3995 if (state.NewInstall())
3996 [installing addObject:name];
3997 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3998 [reinstalling addObject:name];
3999 else if (state.Upgrade())
4000 [upgrading addObject:name];
4001 else if (state.Downgrade())
4002 [downgrading addObject:name];
4003 else if (state.Delete()) {
2388b078 4004 if ([package essential])
36bb2ca2
JF
4005 remove = true;
4006 [removing addObject:name];
a9a0661e
JF
4007 } else continue;
4008
4009 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4010 substrate_ |= DepSubstrate(iterator.CurrentVer());
36bb2ca2 4011 }
ec97ef06 4012
36bb2ca2
JF
4013 if (!remove)
4014 essential_ = nil;
d791dce4 4015 else if (Advanced_) {
43f3d7f6 4016 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
f79a4512 4017
3272e699 4018 essential_ = [[UIAlertView alloc]
43f3d7f6 4019 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
b5e7eebb
GP
4020 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4021 delegate:self
4022 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4023 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4024 ];
04fe1349 4025
3272e699 4026 [essential_ setContext:@"remove"];
9bedffaa 4027 } else {
3272e699 4028 essential_ = [[UIAlertView alloc]
43f3d7f6 4029 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
b5e7eebb
GP
4030 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4031 delegate:self
4032 cancelButtonTitle:UCLocalize("OKAY")
4033 otherButtonTitles:nil
36bb2ca2 4034 ];
ec97ef06 4035
b5e7eebb 4036 [essential_ setContext:@"unable"];
36bb2ca2 4037 }
ec97ef06 4038
affeffc7
JF
4039 changes_ = [[NSArray alloc] initWithObjects:
4040 installing,
4041 reinstalling,
4042 upgrading,
4043 downgrading,
4044 removing,
4045 nil];
dc5812ec 4046
affeffc7
JF
4047 issues_ = [database_ issues];
4048 if (issues_ != nil)
4049 issues_ = [issues_ retain];
dc5812ec 4050
affeffc7
JF
4051 sizes_ = [[NSArray alloc] initWithObjects:
4052 SizeString([database_ fetcher].FetchNeeded()),
4053 SizeString([database_ fetcher].PartialPresent()),
affeffc7 4054 nil];
dc5812ec 4055
affeffc7 4056 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
04fe1349 4057
dd9de556 4058 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
21c6da4b
GP
4059 initWithTitle:UCLocalize("CANCEL")
4060 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
b5e7eebb
GP
4061 style:UIBarButtonItemStylePlain
4062 target:self
4063 action:@selector(cancelButtonClicked)
dd9de556 4064 ] autorelease]];
36bb2ca2 4065 } return self;
b4d89997 4066}
8da60fb7 4067
40bfa2e6 4068- (void) applyRightButton {
b5e7eebb 4069#if !AlwaysReload && !IgnoreInstall
dd9de556
JF
4070 if (issues_ == nil && ![self isLoading])
4071 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4072 initWithTitle:UCLocalize("CONFIRM")
4073 style:UIBarButtonItemStylePlain
4074 target:self
4075 action:@selector(confirmButtonClicked)
4076 ] autorelease]];
4077 else
4078 [super applyRightButton];
40bfa2e6 4079#else
bc11cf5b 4080 [[self navigationItem] setRightBarButtonItem:nil];
b5e7eebb 4081#endif
affeffc7
JF
4082}
4083
b5e7eebb 4084- (void) cancelButtonClicked {
21ea11a4
GP
4085 [self dismissModalViewControllerAnimated:YES];
4086 [delegate_ cancelAndClear:YES];
affeffc7
JF
4087}
4088
9487f027 4089#if !AlwaysReload
b5e7eebb 4090- (void) confirmButtonClicked {
b0ad8dee 4091#if IgnoreInstall
b5e7eebb 4092 return;
b0ad8dee 4093#endif
affeffc7 4094 if (essential_ != nil)
b5e7eebb 4095 [essential_ show];
affeffc7
JF
4096 else {
4097 if (substrate_)
4098 Finish_ = 2;
b5e7eebb 4099 [delegate_ confirmWithNavigationController:[self navigationController]];
affeffc7
JF
4100 }
4101}
9487f027 4102#endif
affeffc7 4103
36bb2ca2
JF
4104@end
4105/* }}} */
8da60fb7 4106
36bb2ca2
JF
4107/* Progress Data {{{ */
4108@interface ProgressData : NSObject {
4109 SEL selector_;
3931b718
JF
4110 // XXX: should these really both be _transient?
4111 _transient id target_;
4112 _transient id object_;
dc5812ec
JF
4113}
4114
36bb2ca2 4115- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
b4d89997 4116
36bb2ca2
JF
4117- (SEL) selector;
4118- (id) target;
4119- (id) object;
4120@end
b4d89997 4121
36bb2ca2 4122@implementation ProgressData
b4d89997 4123
36bb2ca2
JF
4124- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4125 if ((self = [super init]) != nil) {
4126 selector_ = selector;
4127 target_ = target;
4128 object_ = object;
4129 } return self;
4130}
b4d89997 4131
36bb2ca2
JF
4132- (SEL) selector {
4133 return selector_;
4134}
b4d89997 4135
36bb2ca2
JF
4136- (id) target {
4137 return target_;
8da60fb7
JF
4138}
4139
36bb2ca2
JF
4140- (id) object {
4141 return object_;
dc5812ec
JF
4142}
4143
2367a917
JF
4144@end
4145/* }}} */
adb61bda
GP
4146/* Progress Controller {{{ */
4147@interface ProgressController : CYViewController <
8b29f8e6 4148 ConfigurationDelegate,
36bb2ca2
JF
4149 ProgressDelegate
4150> {
8b29f8e6 4151 _transient Database *database_;
36bb2ca2
JF
4152 UIProgressBar *progress_;
4153 UITextView *output_;
4154 UITextLabel *status_;
31f3cfff 4155 UIPushButton *close_;
bd150f54 4156 BOOL running_;
dddbc481 4157 SHA1SumValue springlist_;
22f8bed9 4158 SHA1SumValue notifyconf_;
670a0494 4159 NSString *title_;
2367a917
JF
4160}
4161
b5e7eebb 4162- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
2367a917 4163
36bb2ca2
JF
4164- (void) _retachThread;
4165- (void) _detachNewThreadData:(ProgressData *)data;
4166- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
2367a917 4167
bd150f54
JF
4168- (BOOL) isRunning;
4169
2367a917
JF
4170@end
4171
adb61bda
GP
4172@protocol ProgressControllerDelegate
4173- (void) progressControllerIsComplete:(ProgressController *)sender;
36bb2ca2
JF
4174@end
4175
adb61bda 4176@implementation ProgressController
2367a917
JF
4177
4178- (void) dealloc {
b5e7eebb 4179 [database_ setDelegate:nil];
36bb2ca2
JF
4180 [progress_ release];
4181 [output_ release];
4182 [status_ release];
31f3cfff 4183 [close_ release];
670a0494
JF
4184 if (title_ != nil)
4185 [title_ release];
2367a917
JF
4186 [super dealloc];
4187}
4188
b5e7eebb
GP
4189- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4190 if ((self = [super init]) != nil) {
8b29f8e6 4191 database_ = database;
b5e7eebb 4192 [database_ setDelegate:self];
36bb2ca2 4193 delegate_ = delegate;
ec97ef06 4194
c21004b9 4195 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
2367a917 4196
b5e7eebb 4197 progress_ = [[UIProgressBar alloc] init];
04fe1349 4198 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
31f3cfff 4199 [progress_ setStyle:0];
ec97ef06 4200
b5e7eebb 4201 status_ = [[UITextLabel alloc] init];
04fe1349 4202 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
baf80942
JF
4203 [status_ setColor:[UIColor whiteColor]];
4204 [status_ setBackgroundColor:[UIColor clearColor]];
36bb2ca2
JF
4205 [status_ setCentersHorizontally:YES];
4206 //[status_ setFont:font];
ec97ef06 4207
b5e7eebb 4208 output_ = [[UITextView alloc] init];
1d80f6b9 4209
04fe1349 4210 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
36bb2ca2 4211 //[output_ setTextFont:@"Courier New"];
d791dce4 4212 [output_ setFont:[[output_ font] fontWithSize:12]];
baf80942
JF
4213 [output_ setTextColor:[UIColor whiteColor]];
4214 [output_ setBackgroundColor:[UIColor clearColor]];
36bb2ca2
JF
4215 [output_ setMarginTop:0];
4216 [output_ setAllowsRubberBanding:YES];
795d26fc 4217 [output_ setEditable:NO];
b5e7eebb 4218 [[self view] addSubview:output_];
b4d89997 4219
b5e7eebb 4220 close_ = [[UIPushButton alloc] init];
04fe1349 4221 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
31f3cfff
JF
4222 [close_ setAutosizesToFit:NO];
4223 [close_ setDrawsShadow:YES];
4224 [close_ setStretchBackground:YES];
31f3cfff 4225 [close_ setEnabled:YES];
b5e7eebb 4226 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
bfc87a4d 4227 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
31f3cfff
JF
4228 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4229 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
36bb2ca2 4230 } return self;
2367a917
JF
4231}
4232
b5e7eebb
GP
4233- (void) positionViews {
4234 CGRect bounds = [[self view] bounds];
4235 CGSize prgsize = [UIProgressBar defaultSize];
4236
4237 CGRect prgrect = {{
4238 (bounds.size.width - prgsize.width) / 2,
534e31fc 4239 bounds.size.height - prgsize.height - 20
b5e7eebb 4240 }, prgsize};
bc11cf5b 4241
36fbb2aa 4242 float closewidth = std::min(bounds.size.width - 20, 300.0f);
b5e7eebb
GP
4243
4244 [progress_ setFrame:prgrect];
4245 [status_ setFrame:CGRectMake(
4246 10,
534e31fc 4247 bounds.size.height - prgsize.height - 50,
b5e7eebb
GP
4248 bounds.size.width - 20,
4249 24
4250 )];
4251 [output_ setFrame:CGRectMake(
4252 10,
4253 20,
4254 bounds.size.width - 20,
534e31fc 4255 bounds.size.height - 62
b5e7eebb
GP
4256 )];
4257 [close_ setFrame:CGRectMake(
4258 (bounds.size.width - closewidth) / 2,
534e31fc 4259 bounds.size.height - prgsize.height - 50,
b5e7eebb
GP
4260 closewidth,
4261 32 + prgsize.height
4262 )];
4263}
4264
4265- (void) viewWillAppear:(BOOL)animated {
4266 [super viewDidAppear:animated];
4267 [[self navigationItem] setHidesBackButton:YES];
c21004b9 4268 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
bc11cf5b 4269
b5e7eebb 4270 [self positionViews];
2367a917
JF
4271}
4272
b5e7eebb
GP
4273- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4274 [self positionViews];
2367a917
JF
4275}
4276
b5e7eebb 4277- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
969eaf2f 4278 NSString *context([alert context]);
bc8cd583 4279
670a0494 4280 if ([context isEqualToString:@"conffile"]) {
b5e7eebb 4281 FILE *input = [database_ input];
36fbb2aa
JF
4282 if (button == [alert cancelButtonIndex])
4283 fprintf(input, "N\n");
4284 else if (button == [alert firstOtherButtonIndex])
4285 fprintf(input, "Y\n");
b5e7eebb 4286 fflush(input);
670a0494
JF
4287 }
4288}
4289
4290- (void) closeButtonPushed {
4291 running_ = NO;
4292
ef494bd8
RP
4293 UpdateExternalStatus(0);
4294
670a0494
JF
4295 switch (Finish_) {
4296 case 0:
b5e7eebb 4297 [self dismissModalViewControllerAnimated:YES];
670a0494
JF
4298 break;
4299
4300 case 1:
c4899376
JF
4301 [delegate_ terminateWithSuccess];
4302 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4303 [delegate_ suspendWithAnimation:YES];
4304 else
4305 [delegate_ suspend];*/
670a0494
JF
4306 break;
4307
4308 case 2:
4309 system("launchctl stop com.apple.SpringBoard");
4310 break;
4311
4312 case 3:
4313 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4314 break;
4315
4316 case 4:
4317 system("reboot");
4318 break;
bc8cd583 4319 }
670a0494 4320}
bd150f54 4321
670a0494 4322- (void) _retachThread {
b5e7eebb 4323 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
670a0494 4324
b5e7eebb 4325 [[self view] addSubview:close_];
670a0494
JF
4326 [progress_ removeFromSuperview];
4327 [status_ removeFromSuperview];
4328
4329 [database_ popErrorWithTitle:title_];
adb61bda 4330 [delegate_ progressControllerIsComplete:self];
c390d3ab 4331
22f8bed9 4332 if (Finish_ < 4) {
70d45c1e
JF
4333 FileFd file;
4334 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4335 _error->Discard();
4336 else {
4337 MMap mmap(file, MMap::ReadOnly);
4338 SHA1Summation sha1;
4339 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4340 if (!(notifyconf_ == sha1.Result()))
4341 Finish_ = 4;
4342 }
22f8bed9
JF
4343 }
4344
affeffc7 4345 if (Finish_ < 3) {
70d45c1e
JF
4346 FileFd file;
4347 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4348 _error->Discard();
4349 else {
4350 MMap mmap(file, MMap::ReadOnly);
4351 SHA1Summation sha1;
4352 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4353 if (!(springlist_ == sha1.Result()))
4354 Finish_ = 3;
4355 }
dddbc481
JF
4356 }
4357
bc8cd583 4358 switch (Finish_) {
b5e7eebb 4359 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
43f3d7f6
JF
4360 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4361 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4362 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4363 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
bc8cd583
JF
4364 }
4365
58241d4c 4366 system("su -c /usr/bin/uicache mobile");
c4ce98df 4367
ef494bd8
RP
4368 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4369
bd150f54 4370 [delegate_ setStatusBarShowsProgress:NO];
31f3cfff
JF
4371}
4372
affeffc7 4373- (void) _detachNewThreadData:(ProgressData *)data { _pooled
36bb2ca2 4374 [[data target] performSelector:[data selector] withObject:[data object]];
36bb2ca2 4375 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
b19871dd
JF
4376}
4377
36bb2ca2 4378- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
ef494bd8
RP
4379 UpdateExternalStatus(1);
4380
670a0494
JF
4381 if (title_ != nil)
4382 [title_ release];
4383 if (title == nil)
4384 title_ = nil;
4385 else
4386 title_ = [title retain];
4387
b5e7eebb 4388 [[self navigationItem] setTitle:title_];
b4d89997 4389
36bb2ca2
JF
4390 [status_ setText:nil];
4391 [output_ setText:@""];
4392 [progress_ setProgress:0];
b19871dd 4393
31f3cfff 4394 [close_ removeFromSuperview];
b5e7eebb
GP
4395 [[self view] addSubview:progress_];
4396 [[self view] addSubview:status_];
31f3cfff 4397
bd150f54
JF
4398 [delegate_ setStatusBarShowsProgress:YES];
4399 running_ = YES;
4400
22f8bed9 4401 {
70d45c1e
JF
4402 FileFd file;
4403 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4404 _error->Discard();
4405 else {
4406 MMap mmap(file, MMap::ReadOnly);
4407 SHA1Summation sha1;
4408 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4409 notifyconf_ = sha1.Result();
4410 }
22f8bed9
JF
4411 }
4412
affeffc7 4413 {
70d45c1e
JF
4414 FileFd file;
4415 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4416 _error->Discard();
4417 else {
4418 MMap mmap(file, MMap::ReadOnly);
4419 SHA1Summation sha1;
4420 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4421 springlist_ = sha1.Result();
4422 }
dddbc481
JF
4423 }
4424
36bb2ca2
JF
4425 [NSThread
4426 detachNewThreadSelector:@selector(_detachNewThreadData:)
4427 toTarget:self
3931b718 4428 withObject:[[[ProgressData alloc]
36bb2ca2
JF
4429 initWithSelector:selector
4430 target:target
4431 object:object
3931b718 4432 ] autorelease]
36bb2ca2 4433 ];
b19871dd
JF
4434}
4435
5a09ae08
JF
4436- (void) repairWithSelector:(SEL)selector {
4437 [self
4438 detachNewThreadSelector:selector
4439 toTarget:database_
4440 withObject:nil
43f3d7f6 4441 title:UCLocalize("REPAIRING")
5a09ae08
JF
4442 ];
4443}
4444
8b29f8e6
JF
4445- (void) setConfigurationData:(NSString *)data {
4446 [self
4447 performSelectorOnMainThread:@selector(_setConfigurationData:)
4448 withObject:data
4449 waitUntilDone:YES
4450 ];
4451}
4452
670a0494
JF
4453- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4454 CYActionSheet *sheet([[[CYActionSheet alloc]
4455 initWithTitle:title
43f3d7f6 4456 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
31f3cfff 4457 defaultButtonIndex:0
670a0494 4458 ] autorelease]);
31f3cfff 4459
be2b3d7b 4460 [sheet setMessage:error];
670a0494
JF
4461 [sheet yieldToPopupAlertAnimated:YES];
4462 [sheet dismiss];
b19871dd
JF
4463}
4464
36bb2ca2
JF
4465- (void) setProgressTitle:(NSString *)title {
4466 [self
4467 performSelectorOnMainThread:@selector(_setProgressTitle:)
4468 withObject:title
4469 waitUntilDone:YES
4470 ];
b19871dd
JF
4471}
4472
36bb2ca2
JF
4473- (void) setProgressPercent:(float)percent {
4474 [self
4475 performSelectorOnMainThread:@selector(_setProgressPercent:)
4476 withObject:[NSNumber numberWithFloat:percent]
4477 waitUntilDone:YES
4478 ];
b19871dd
JF
4479}
4480
baf80942 4481- (void) startProgress {
baf80942
JF
4482}
4483
36bb2ca2
JF
4484- (void) addProgressOutput:(NSString *)output {
4485 [self
4486 performSelectorOnMainThread:@selector(_addProgressOutput:)
4487 withObject:output
4488 waitUntilDone:YES
4489 ];
b19871dd
JF
4490}
4491
baf80942 4492- (bool) isCancelling:(size_t)received {
baf80942
JF
4493 return false;
4494}
4495
8b29f8e6 4496- (void) _setConfigurationData:(NSString *)data {
7b0ce2da
JF
4497 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4498
670a0494
JF
4499 if (!conffile_r(data)) {
4500 lprintf("E:invalid conffile\n");
4501 return;
4502 }
8b29f8e6
JF
4503
4504 NSString *ofile = conffile_r[1];
4505 //NSString *nfile = conffile_r[2];
4506
969eaf2f 4507 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 4508 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
b5e7eebb
GP
4509 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4510 delegate:self
4511 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4512 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
969eaf2f 4513 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
b5e7eebb
GP
4514 nil
4515 ] autorelease];
969eaf2f 4516
b5e7eebb 4517 [alert setContext:@"conffile"];
969eaf2f 4518 [alert show];
8b29f8e6
JF
4519}
4520
36bb2ca2 4521- (void) _setProgressTitle:(NSString *)title {
9487f027
JF
4522 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4523 for (size_t i(0), e([words count]); i != e; ++i) {
4524 NSString *word([words objectAtIndex:i]);
4525 if (Package *package = [database_ packageWithName:word])
4526 [words replaceObjectAtIndex:i withObject:[package name]];
4527 }
4528
4529 [status_ setText:[words componentsJoinedByString:@" "]];
b4d89997 4530}
b19871dd 4531
36bb2ca2
JF
4532- (void) _setProgressPercent:(NSNumber *)percent {
4533 [progress_ setProgress:[percent floatValue]];
49048579
JF
4534}
4535
36bb2ca2
JF
4536- (void) _addProgressOutput:(NSString *)output {
4537 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4538 CGSize size = [output_ contentSize];
4539 CGRect rect = {{0, size.height}, {size.width, 0}};
4540 [output_ scrollRectToVisible:rect animated:YES];
4541}
dc088e63 4542
bd150f54 4543- (BOOL) isRunning {
c4ce98df 4544 return running_;
bd150f54
JF
4545}
4546
36bb2ca2
JF
4547@end
4548/* }}} */
dc088e63 4549
46aa9775 4550/* Cell Content View {{{ */
c21004b9
JF
4551@protocol ContentDelegate
4552- (void) drawContentRect:(CGRect)rect;
4553@end
4554
327624b6 4555@interface ContentView : UIView {
c21004b9 4556 _transient id<ContentDelegate> delegate_;
327624b6
JF
4557}
4558
4559@end
4560
46aa9775 4561@implementation ContentView
555aaf71 4562
46aa9775
GP
4563- (id) initWithFrame:(CGRect)frame {
4564 if ((self = [super initWithFrame:frame]) != nil) {
46aa9775
GP
4565 [self setNeedsDisplayOnBoundsChange:YES];
4566 } return self;
4567}
4568
c21004b9 4569- (void) setDelegate:(id<ContentDelegate>)delegate {
46aa9775
GP
4570 delegate_ = delegate;
4571}
4572
4573- (void) drawRect:(CGRect)rect {
4574 [super drawRect:rect];
4575 [delegate_ drawContentRect:rect];
4576}
555aaf71
JF
4577
4578@end
4579/* }}} */
4580/* Cydia TableView Cell {{{ */
4581@interface CYTableViewCell : UITableViewCell {
4582 ContentView *content_;
4583 bool highlighted_;
4584}
4585
4586@end
4587
4588@implementation CYTableViewCell
4589
4590- (void) dealloc {
4591 [content_ release];
4592 [super dealloc];
4593}
4594
4595- (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4596 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4597
4598 if (view == content_) {
4599 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4600 highlighted_ = highlighted;
4601 }
4602
4603 [super _updateHighlightColorsForView:view highlighted:highlighted];
4604}
4605
4606- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4607 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4608 highlighted_ = selected;
4609
4610 [super setSelected:selected animated:animated];
4611 [content_ setNeedsDisplay];
4612}
4613
46aa9775
GP
4614@end
4615/* }}} */
4616/* Package Cell {{{ */
555aaf71 4617@interface PackageCell : CYTableViewCell <
c21004b9
JF
4618 ContentDelegate
4619> {
f641a0e5
JF
4620 UIImage *icon_;
4621 NSString *name_;
4622 NSString *description_;
3bd1c2a2 4623 bool commercial_;
f641a0e5 4624 NSString *source_;
c390d3ab 4625 UIImage *badge_;
dc63e78f 4626 Package *package_;
670a0494 4627 UIImage *placard_;
36bb2ca2 4628}
723a0072 4629
36bb2ca2
JF
4630- (PackageCell *) init;
4631- (void) setPackage:(Package *)package;
ec97ef06 4632
9bedffaa 4633+ (int) heightForPackage:(Package *)package;
327624b6
JF
4634- (void) drawContentRect:(CGRect)rect;
4635
4636@end
4637
36bb2ca2
JF
4638@implementation PackageCell
4639
f641a0e5
JF
4640- (void) clearPackage {
4641 if (icon_ != nil) {
4642 [icon_ release];
4643 icon_ = nil;
4644 }
4645
4646 if (name_ != nil) {
4647 [name_ release];
4648 name_ = nil;
4649 }
4650
4651 if (description_ != nil) {
4652 [description_ release];
4653 description_ = nil;
4654 }
4655
4656 if (source_ != nil) {
4657 [source_ release];
4658 source_ = nil;
4659 }
c390d3ab
JF
4660
4661 if (badge_ != nil) {
4662 [badge_ release];
4663 badge_ = nil;
4664 }
dc63e78f 4665
670a0494
JF
4666 if (placard_ != nil) {
4667 [placard_ release];
4668 placard_ = nil;
4669 }
4670
dc63e78f
JF
4671 [package_ release];
4672 package_ = nil;
f641a0e5
JF
4673}
4674
36bb2ca2 4675- (void) dealloc {
f641a0e5 4676 [self clearPackage];
36bb2ca2 4677 [super dealloc];
b4d89997 4678}
b19871dd 4679
36bb2ca2 4680- (PackageCell *) init {
327624b6
JF
4681 CGRect frame(CGRectMake(0, 0, 320, 74));
4682 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4683 UIView *content([self contentView]);
4684 CGRect bounds([content bounds]);
04fe1349 4685
327624b6 4686 content_ = [[ContentView alloc] initWithFrame:bounds];
04fe1349
JF
4687 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4688 [content addSubview:content_];
4689
327624b6 4690 [content_ setDelegate:self];
327624b6 4691 [content_ setOpaque:YES];
36bb2ca2 4692 } return self;
b4d89997 4693}
b19871dd 4694
327624b6
JF
4695- (void) _setBackgroundColor {
4696 UIColor *color;
4697 if (NSString *mode = [package_ mode]) {
4698 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4699 color = remove ? RemovingColor_ : InstallingColor_;
4700 } else
4701 color = [UIColor whiteColor];
4702
4703 [content_ setBackgroundColor:color];
4704 [self setNeedsDisplay];
4705}
4706
36bb2ca2 4707- (void) setPackage:(Package *)package {
46dbfd32 4708 [self clearPackage];
68d927e2 4709 [package parse];
31f3cfff 4710
36bb2ca2 4711 Source *source = [package source];
b19871dd 4712
770f2a8e 4713 icon_ = [[package icon] retain];
f641a0e5 4714 name_ = [[package name] retain];
ef055c6c
JF
4715
4716 if (IsWildcat_)
4717 description_ = [package longDescription];
4718 if (description_ == nil)
4719 description_ = [package shortDescription];
4720 if (description_ != nil)
4721 description_ = [description_ retain];
4722
3bd1c2a2 4723 commercial_ = [package isCommercial];
36bb2ca2 4724
dc63e78f
JF
4725 package_ = [package retain];
4726
a54b1c10
JF
4727 NSString *label = nil;
4728 bool trusted = false;
b19871dd 4729
36bb2ca2
JF
4730 if (source != nil) {
4731 label = [source label];
4732 trusted = [source trusted];
a54b1c10 4733 } else if ([[package id] isEqualToString:@"firmware"])
43f3d7f6 4734 label = UCLocalize("APPLE");
7b0ce2da 4735 else
43f3d7f6 4736 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
b19871dd 4737
f79a4512 4738 NSString *from(label);
a54b1c10 4739
f79a4512
JF
4740 NSString *section = [package simpleSection];
4741 if (section != nil && ![section isEqualToString:label]) {
4742 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
43f3d7f6 4743 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
f79a4512 4744 }
a54b1c10 4745
43f3d7f6 4746 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
f641a0e5 4747 source_ = [from retain];
36bb2ca2 4748
c390d3ab
JF
4749 if (NSString *purpose = [package primaryPurpose])
4750 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4751 badge_ = [badge_ retain];
4752
670a0494
JF
4753 if ([package installed] != nil)
4754 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4755 placard_ = [placard_ retain];
4756
327624b6
JF
4757 [self _setBackgroundColor];
4758 [content_ setNeedsDisplay];
3bd1c2a2
JF
4759}
4760
327624b6 4761- (void) drawContentRect:(CGRect)rect {
555aaf71 4762 bool highlighted(highlighted_);
ef055c6c 4763 float width([self bounds].size.width);
dc63e78f 4764
327624b6
JF
4765#if 0
4766 CGContextRef context(UIGraphicsGetCurrentContext());
4767 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4768 CGContextFillRect(context, rect);
4769#endif
b19871dd 4770
baf80942
JF
4771 if (icon_ != nil) {
4772 CGRect rect;
4773 rect.size = [icon_ size];
4774
4775 rect.size.width /= 2;
4776 rect.size.height /= 2;
4777
4778 rect.origin.x = 25 - rect.size.width / 2;
4779 rect.origin.y = 25 - rect.size.height / 2;
4780
4781 [icon_ drawInRect:rect];
4782 }
b19871dd 4783
c390d3ab
JF
4784 if (badge_ != nil) {
4785 CGSize size = [badge_ size];
4786
4787 [badge_ drawAtPoint:CGPointMake(
4788 36 - size.width / 2,
4789 36 - size.height / 2
4790 )];
4791 }
4792
555aaf71 4793 if (highlighted)
f641a0e5 4794 UISetColor(White_);
b19871dd 4795
555aaf71 4796 if (!highlighted)
3bd1c2a2 4797 UISetColor(commercial_ ? Purple_ : Black_);
54b844a0
DH
4798 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4799 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
b19871dd 4800
555aaf71 4801 if (!highlighted)
3bd1c2a2 4802 UISetColor(commercial_ ? Purplish_ : Gray_);
54b844a0 4803 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
670a0494
JF
4804
4805 if (placard_ != nil)
01d93940 4806 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
ec97ef06
JF
4807}
4808
9bedffaa 4809+ (int) heightForPackage:(Package *)package {
68d927e2 4810 return 73;
9bedffaa
JF
4811}
4812
8da60fb7
JF
4813@end
4814/* }}} */
36bb2ca2 4815/* Section Cell {{{ */
555aaf71 4816@interface SectionCell : CYTableViewCell <
c21004b9
JF
4817 ContentDelegate
4818> {
0010fa77 4819 NSString *basic_;
6d9712c4 4820 NSString *section_;
f641a0e5
JF
4821 NSString *name_;
4822 NSString *count_;
4823 UIImage *icon_;
68046ccc 4824 UISwitch *switch_;
6d9712c4 4825 BOOL editing_;
b4d89997 4826}
b19871dd 4827
6d9712c4 4828- (void) setSection:(Section *)section editing:(BOOL)editing;
36bb2ca2 4829
8da60fb7
JF
4830@end
4831
36bb2ca2 4832@implementation SectionCell
8da60fb7 4833
f641a0e5 4834- (void) clearSection {
0010fa77 4835 if (basic_ != nil) {
e59669fd 4836 [basic_ release];
0010fa77
JF
4837 basic_ = nil;
4838 }
4839
f641a0e5 4840 if (section_ != nil) {
6d9712c4 4841 [section_ release];
f641a0e5
JF
4842 section_ = nil;
4843 }
7b0ce2da 4844
f641a0e5
JF
4845 if (name_ != nil) {
4846 [name_ release];
4847 name_ = nil;
4848 }
7b0ce2da 4849
f641a0e5
JF
4850 if (count_ != nil) {
4851 [count_ release];
4852 count_ = nil;
4853 }
7b0ce2da
JF
4854}
4855
f641a0e5
JF
4856- (void) dealloc {
4857 [self clearSection];
4858 [icon_ release];
4859 [switch_ release];
4860 [super dealloc];
7b0ce2da
JF
4861}
4862
46aa9775
GP
4863- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4864 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
f641a0e5 4865 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
68046ccc 4866 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
46aa9775
GP
4867 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4868
4869 UIView *content([self contentView]);
4870 CGRect bounds([content bounds]);
4871
4872 content_ = [[ContentView alloc] initWithFrame:bounds];
4873 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4874 [content addSubview:content_];
4875 [content_ setBackgroundColor:[UIColor whiteColor]];
4876
4877 [content_ setDelegate:self];
b4d89997 4878 } return self;
b19871dd
JF
4879}
4880
6d9712c4 4881- (void) onSwitch:(id)sender {
0010fa77 4882 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
6d9712c4
JF
4883 if (metadata == nil) {
4884 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
0010fa77 4885 [Sections_ setObject:metadata forKey:basic_];
6d9712c4
JF
4886 }
4887
4888 Changed_ = true;
46aa9775 4889 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6d9712c4
JF
4890}
4891
4892- (void) setSection:(Section *)section editing:(BOOL)editing {
4893 if (editing != editing_) {
4894 if (editing_)
4895 [switch_ removeFromSuperview];
4896 else
4897 [self addSubview:switch_];
4898 editing_ = editing;
4899 }
4900
f641a0e5 4901 [self clearSection];
6d9712c4 4902
36bb2ca2 4903 if (section == nil) {
43f3d7f6 4904 name_ = [UCLocalize("ALL_PACKAGES") retain];
f641a0e5 4905 count_ = nil;
36bb2ca2 4906 } else {
e59669fd 4907 basic_ = [section name];
0010fa77
JF
4908 if (basic_ != nil)
4909 basic_ = [basic_ retain];
4910
677b8415 4911 section_ = [section localized];
6d9712c4
JF
4912 if (section_ != nil)
4913 section_ = [section_ retain];
0010fa77 4914
43f3d7f6 4915 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
f641a0e5 4916 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
6d9712c4
JF
4917
4918 if (editing_)
46aa9775 4919 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
36bb2ca2 4920 }
46aa9775 4921
c21004b9 4922 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
0abb648c
JF
4923 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4924
46aa9775 4925 [content_ setNeedsDisplay];
f641a0e5
JF
4926}
4927
77801ff1
JF
4928- (void) setFrame:(CGRect)frame {
4929 [super setFrame:frame];
46aa9775 4930
77801ff1
JF
4931 CGRect rect([switch_ frame]);
4932 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4933}
4934
46aa9775 4935- (void) drawContentRect:(CGRect)rect {
555aaf71 4936 bool highlighted(highlighted_);
bc11cf5b 4937
f641a0e5
JF
4938 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4939
555aaf71 4940 if (highlighted)
f641a0e5
JF
4941 UISetColor(White_);
4942
46aa9775 4943 float width(rect.size.width);
58241d4c 4944 if (editing_)
46aa9775 4945 width -= 87;
58241d4c 4946
555aaf71
JF
4947 if (!highlighted)
4948 UISetColor(Black_);
54b844a0 4949 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
6d9712c4 4950
f641a0e5
JF
4951 CGSize size = [count_ sizeWithFont:Font14_];
4952
4953 UISetColor(White_);
4954 if (count_ != nil)
c390d3ab 4955 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
b19871dd
JF
4956}
4957
36bb2ca2
JF
4958@end
4959/* }}} */
b19871dd 4960
ab398adf 4961/* File Table {{{ */
c21004b9
JF
4962@interface FileTable : CYViewController <
4963 UITableViewDataSource,
4964 UITableViewDelegate
4965> {
36bb2ca2 4966 _transient Database *database_;
ab398adf
JF
4967 Package *package_;
4968 NSString *name_;
4969 NSMutableArray *files_;
46aa9775 4970 UITableView *list_;
ab398adf 4971}
b19871dd 4972
b5e7eebb 4973- (id) initWithDatabase:(Database *)database;
ab398adf
JF
4974- (void) setPackage:(Package *)package;
4975
4976@end
4977
4978@implementation FileTable
4979
4980- (void) dealloc {
4981 if (package_ != nil)
4982 [package_ release];
4983 if (name_ != nil)
4984 [name_ release];
4985 [files_ release];
4986 [list_ release];
4987 [super dealloc];
4988}
4989
eb30da80 4990- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
ab398adf
JF
4991 return files_ == nil ? 0 : [files_ count];
4992}
4993
21ea11a4
GP
4994/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
4995 return 24.0f;
4996}*/
ab398adf 4997
46aa9775 4998- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
GP
4999 static NSString *reuseIdentifier = @"Cell";
5000
46aa9775
GP
5001 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5002 if (cell == nil) {
5003 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5004 [cell setFont:[UIFont systemFontOfSize:16]];
ab398adf 5005 }
46aa9775 5006 [cell setText:[files_ objectAtIndex:indexPath.row]];
c21004b9 5007 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
b5e7eebb 5008
46aa9775 5009 return cell;
ab398adf 5010}
b19871dd 5011
b5e7eebb
GP
5012- (id) initWithDatabase:(Database *)database {
5013 if ((self = [super init]) != nil) {
ab398adf 5014 database_ = database;
b19871dd 5015
b5e7eebb
GP
5016 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5017
ab398adf 5018 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
8da60fb7 5019
46aa9775 5020 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
21ea11a4
GP
5021 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5022 [list_ setRowHeight:24.0f];
b5e7eebb 5023 [[self view] addSubview:list_];
ab398adf 5024
ab398adf 5025 [list_ setDataSource:self];
ab398adf 5026 [list_ setDelegate:self];
ab398adf
JF
5027 } return self;
5028}
5029
5030- (void) setPackage:(Package *)package {
5031 if (package_ != nil) {
5032 [package_ autorelease];
5033 package_ = nil;
5034 }
5035
5036 if (name_ != nil) {
5037 [name_ release];
5038 name_ = nil;
5039 }
5040
5041 [files_ removeAllObjects];
5042
5043 if (package != nil) {
5044 package_ = [package retain];
5045 name_ = [[package id] retain];
5046
affeffc7
JF
5047 if (NSArray *files = [package files])
5048 [files_ addObjectsFromArray:files];
ab398adf 5049
9ea8d159
JF
5050 if ([files_ count] != 0) {
5051 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5052 [files_ removeObjectAtIndex:0];
a54b1c10 5053 [files_ sortUsingSelector:@selector(compareByPath:)];
2388b078
JF
5054
5055 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5056 [stack addObject:@"/"];
5057
5058 for (int i(0), e([files_ count]); i != e; ++i) {
5059 NSString *file = [files_ objectAtIndex:i];
5060 while (![file hasPrefix:[stack lastObject]])
5061 [stack removeLastObject];
5062 NSString *directory = [stack lastObject];
5063 [stack addObject:[file stringByAppendingString:@"/"]];
5064 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
a54b1c10 5065 ([stack count] - 2) * 3, "",
2388b078
JF
5066 [file substringFromIndex:[directory length]]
5067 ]];
5068 }
ab398adf
JF
5069 }
5070 }
5071
5072 [list_ reloadData];
5073}
5074
ab398adf
JF
5075- (void) reloadData {
5076 [self setPackage:[database_ packageWithName:name_]];
ab398adf 5077}
b4d89997 5078
b4d89997 5079@end
36bb2ca2 5080/* }}} */
adb61bda 5081/* Package Controller {{{ */
9daa7f25
DH
5082@interface PackageController : CYBrowserController <
5083 UIActionSheetDelegate
5084> {
770f2a8e 5085 _transient Database *database_;
36bb2ca2
JF
5086 Package *package_;
5087 NSString *name_;
3bd1c2a2 5088 bool commercial_;
5a09ae08 5089 NSMutableArray *buttons_;
2634b249 5090 UIBarButtonItem *button_;
b31b87cc
JF
5091}
5092
b5e7eebb 5093- (id) initWithDatabase:(Database *)database;
36bb2ca2 5094- (void) setPackage:(Package *)package;
b4d89997 5095
36bb2ca2 5096@end
b4d89997 5097
adb61bda 5098@implementation PackageController
b4d89997 5099
36bb2ca2 5100- (void) dealloc {
36bb2ca2
JF
5101 if (package_ != nil)
5102 [package_ release];
5103 if (name_ != nil)
5104 [name_ release];
2634b249 5105
5a09ae08 5106 [buttons_ release];
2634b249
JF
5107
5108 if (button_ != nil)
5109 [button_ release];
5110
36bb2ca2
JF
5111 [super dealloc];
5112}
8da60fb7 5113
92d4a16a 5114- (void) release {
f79a4512 5115 if ([self retainCount] == 1)
adb61bda 5116 [delegate_ setPackageController:self];
f79a4512 5117 [super release];
92d4a16a 5118}
f79a4512
JF
5119
5120/* XXX: this is not safe at all... localization of /fail/ */
5a09ae08 5121- (void) _clickButtonWithName:(NSString *)name {
43f3d7f6 5122 if ([name isEqualToString:UCLocalize("CLEAR")])
dc63e78f 5123 [delegate_ clearPackage:package_];
43f3d7f6 5124 else if ([name isEqualToString:UCLocalize("INSTALL")])
5a09ae08 5125 [delegate_ installPackage:package_];
43f3d7f6 5126 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5a09ae08 5127 [delegate_ installPackage:package_];
43f3d7f6 5128 else if ([name isEqualToString:UCLocalize("REMOVE")])
5a09ae08 5129 [delegate_ removePackage:package_];
43f3d7f6 5130 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5a09ae08
JF
5131 [delegate_ installPackage:package_];
5132 else _assert(false);
5133}
5134
674dce72 5135- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
1cedb821 5136 NSString *context([sheet context]);
5a09ae08 5137
1cedb821 5138 if ([context isEqualToString:@"modify"]) {
674dce72
GP
5139 if (button != [sheet cancelButtonIndex]) {
5140 NSString *buttonName = [buttons_ objectAtIndex:button];
5141 [self _clickButtonWithName:buttonName];
5142 }
bc11cf5b 5143
674dce72 5144 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
674dce72 5145 }
b4d89997 5146}
2367a917 5147
2634b249
JF
5148- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5149 [super webView:view didClearWindowObject:window forFrame:frame];
f79a4512 5150 [window setValue:package_ forKey:@"package"];
6f1a15d9
JF
5151}
5152
3e9c9e85 5153- (bool) _allowJavaScriptPanel {
3bd1c2a2 5154 return commercial_;
3e9c9e85
JF
5155}
5156
9487f027 5157#if !AlwaysReload
9daa7f25 5158- (void) _customButtonClicked {
670a0494
JF
5159 int count([buttons_ count]);
5160 if (count == 0)
5161 return;
2367a917 5162
5a09ae08
JF
5163 if (count == 1)
5164 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5165 else {
674dce72 5166 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5a09ae08 5167 [buttons addObjectsFromArray:buttons_];
36bb2ca2 5168
674dce72 5169 UIActionSheet *sheet = [[[UIActionSheet alloc]
9ea8d159 5170 initWithTitle:nil
36bb2ca2 5171 delegate:self
674dce72
GP
5172 cancelButtonTitle:nil
5173 destructiveButtonTitle:nil
5174 otherButtonTitles:nil
5175 ] autorelease];
5176
5177 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5178 if (!IsWildcat_) {
5179 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5180 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5181 }
5182 [sheet setContext:@"modify"];
bc11cf5b 5183
b5e7eebb 5184 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
36bb2ca2 5185 }
b4d89997 5186}
12b59862 5187
a5938ea5
DH
5188// We don't want to allow non-commercial packages to do custom things to the install button,
5189// so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
9daa7f25 5190- (void) customButtonClicked {
a5938ea5
DH
5191 if (commercial_)
5192 [super customButtonClicked];
5193 else
9daa7f25 5194 [self _customButtonClicked];
12b59862 5195}
2e6c1426
GP
5196
5197- (void) reloadButtonClicked {
2fad210a
GP
5198 // Don't reload a package view by clicking the button.
5199}
5200
5201- (void) applyLoadingTitle {
5202 // Don't show "Loading" as the title. Ever.
2e6c1426 5203}
a5938ea5
DH
5204
5205- (UIBarButtonItem *) rightButton {
2634b249 5206 return button_;
a5938ea5 5207}
9487f027 5208#endif
2367a917 5209
b5e7eebb
GP
5210- (id) initWithDatabase:(Database *)database {
5211 if ((self = [super init]) != nil) {
36bb2ca2 5212 database_ = database;
5a09ae08 5213 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
f79a4512 5214 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
36bb2ca2 5215 } return self;
dc5812ec
JF
5216}
5217
36bb2ca2
JF
5218- (void) setPackage:(Package *)package {
5219 if (package_ != nil) {
5220 [package_ autorelease];
5221 package_ = nil;
5222 }
5223
5224 if (name_ != nil) {
5225 [name_ release];
5226 name_ = nil;
5227 }
5228
5a09ae08
JF
5229 [buttons_ removeAllObjects];
5230
36bb2ca2 5231 if (package != nil) {
68d927e2
JF
5232 [package parse];
5233
36bb2ca2
JF
5234 package_ = [package retain];
5235 name_ = [[package id] retain];
3bd1c2a2 5236 commercial_ = [package isCommercial];
36bb2ca2 5237
dc63e78f 5238 if ([package_ mode] != nil)
43f3d7f6 5239 [buttons_ addObject:UCLocalize("CLEAR")];
5a09ae08 5240 if ([package_ source] == nil);
31f3cfff 5241 else if ([package_ upgradableAndEssential:NO])
43f3d7f6 5242 [buttons_ addObject:UCLocalize("UPGRADE")];
6a155117 5243 else if ([package_ uninstalled])
43f3d7f6 5244 [buttons_ addObject:UCLocalize("INSTALL")];
5a09ae08 5245 else
43f3d7f6 5246 [buttons_ addObject:UCLocalize("REINSTALL")];
6a155117 5247 if (![package_ uninstalled])
43f3d7f6 5248 [buttons_ addObject:UCLocalize("REMOVE")];
2634b249 5249 }
f79a4512 5250
2634b249
JF
5251 if (button_ != nil)
5252 [button_ release];
f79a4512 5253
2634b249
JF
5254 NSString *title;
5255 switch ([buttons_ count]) {
5256 case 0: title = nil; break;
5257 case 1: title = [buttons_ objectAtIndex:0]; break;
5258 default: title = UCLocalize("MODIFY"); break;
36bb2ca2 5259 }
2634b249
JF
5260
5261 button_ = [[UIBarButtonItem alloc]
5262 initWithTitle:title
5263 style:UIBarButtonItemStylePlain
5264 target:self
5265 action:@selector(customButtonClicked)
5266 ];
56e88a25
JF
5267
5268 [self reloadURL];
b5e7eebb 5269}
f79a4512 5270
3bd1c2a2
JF
5271- (bool) isLoading {
5272 return commercial_ ? [super isLoading] : false;
9fe5e5f8
JF
5273}
5274
36bb2ca2
JF
5275- (void) reloadData {
5276 [self setPackage:[database_ packageWithName:name_]];
8fe19fc1
JF
5277}
5278
b4d89997
JF
5279@end
5280/* }}} */
b4d89997 5281/* Package Table {{{ */
c21004b9
JF
5282@interface PackageTable : UIView <
5283 UITableViewDataSource,
5284 UITableViewDelegate
5285> {
36bb2ca2 5286 _transient Database *database_;
36bb2ca2 5287 NSMutableArray *packages_;
b4d89997 5288 NSMutableArray *sections_;
327624b6
JF
5289 UITableView *list_;
5290 NSMutableArray *index_;
5291 NSMutableDictionary *indices_;
3931b718
JF
5292 // XXX: this target_ seems to be delegate_. :(
5293 _transient id target_;
b5e7eebb 5294 SEL action_;
3931b718
JF
5295 // XXX: why do we even have this delegate_?
5296 _transient id delegate_;
dc5812ec
JF
5297}
5298
b5e7eebb 5299- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
b4d89997
JF
5300
5301- (void) setDelegate:(id)delegate;
a0be02eb 5302
36bb2ca2 5303- (void) reloadData;
a0be02eb 5304- (void) resetCursor;
b4d89997 5305
327624b6 5306- (UITableView *) list;
2388b078 5307
ab398adf
JF
5308- (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5309
b5e7eebb
GP
5310- (void) deselectWithAnimation:(BOOL)animated;
5311
b4d89997
JF
5312@end
5313
5314@implementation PackageTable
5315
5316- (void) dealloc {
36bb2ca2 5317 [packages_ release];
b4d89997 5318 [sections_ release];
36bb2ca2 5319 [list_ release];
327624b6
JF
5320 [index_ release];
5321 [indices_ release];
b5e7eebb 5322
b4d89997 5323 [super dealloc];
8fe19fc1
JF
5324}
5325
327624b6
JF
5326- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5327 NSInteger count([sections_ count]);
5328 return count == 0 ? 1 : count;
b4d89997 5329}
2367a917 5330
327624b6
JF
5331- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5332 if ([sections_ count] == 0)
5333 return nil;
b4d89997
JF
5334 return [[sections_ objectAtIndex:section] name];
5335}
dc5812ec 5336
327624b6
JF
5337- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5338 if ([sections_ count] == 0)
5339 return 0;
5340 return [[sections_ objectAtIndex:section] count];
b4d89997 5341}
dc5812ec 5342
327624b6
JF
5343- (Package *) packageAtIndexPath:(NSIndexPath *)path {
5344 Section *section([sections_ objectAtIndex:[path section]]);
5345 NSInteger row([path row]);
5346 Package *package([packages_ objectAtIndex:([section row] + row)]);
5347 return package;
b4d89997 5348}
dc5812ec 5349
327624b6 5350- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
c21004b9 5351 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
327624b6
JF
5352 if (cell == nil)
5353 cell = [[[PackageCell alloc] init] autorelease];
5354 [cell setPackage:[self packageAtIndexPath:path]];
5355 return cell;
b4d89997 5356}
dc5812ec 5357
b5e7eebb
GP
5358- (void) deselectWithAnimation:(BOOL)animated {
5359 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5360}
5361
21ea11a4 5362/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
327624b6 5363 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
21ea11a4 5364}*/
dc5812ec 5365
327624b6
JF
5366- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5367 Package *package([self packageAtIndexPath:path]);
59c6ae22 5368 package = [database_ packageWithName:[package id]];
b5e7eebb 5369 [target_ performSelector:action_ withObject:package];
327624b6
JF
5370 return path;
5371}
5372
5373- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5374 return [packages_ count] > 20 ? index_ : nil;
5375}
5376
5377- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5378 return index;
dc5812ec
JF
5379}
5380
b5e7eebb
GP
5381- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5382 if ((self = [super initWithFrame:frame]) != nil) {
36bb2ca2 5383 database_ = database;
b5e7eebb
GP
5384
5385 target_ = target;
5386 action_ = action;
36bb2ca2 5387
327624b6
JF
5388 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5389 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5390
36bb2ca2 5391 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
b4d89997 5392 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 5393
327624b6 5394 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
04fe1349 5395 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 5396 [list_ setRowHeight:73.0f];
04fe1349
JF
5397 [self addSubview:list_];
5398
b4d89997 5399 [list_ setDataSource:self];
327624b6 5400 [list_ setDelegate:self];
b4d89997 5401 } return self;
dc5812ec
JF
5402}
5403
5404- (void) setDelegate:(id)delegate {
2367a917 5405 delegate_ = delegate;
b4d89997
JF
5406}
5407
a3328c28
JF
5408- (bool) hasPackage:(Package *)package {
5409 return true;
a0be02eb
JF
5410}
5411
36bb2ca2
JF
5412- (void) reloadData {
5413 NSArray *packages = [database_ packages];
b4d89997 5414
36bb2ca2 5415 [packages_ removeAllObjects];
b4d89997
JF
5416 [sections_ removeAllObjects];
5417
808c6eb6 5418 _profile(PackageTable$reloadData$Filter)
c4dcf2c2 5419 for (Package *package in packages)
808c6eb6
JF
5420 if ([self hasPackage:package])
5421 [packages_ addObject:package];
808c6eb6 5422 _end
36bb2ca2 5423
327624b6
JF
5424 [index_ removeAllObjects];
5425 [indices_ removeAllObjects];
5426
b4d89997
JF
5427 Section *section = nil;
5428
808c6eb6 5429 _profile(PackageTable$reloadData$Section)
c4dcf2c2
JF
5430 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5431 Package *package;
5432 unichar index;
5433
5434 _profile(PackageTable$reloadData$Section$Package)
5435 package = [packages_ objectAtIndex:offset];
5436 index = [package index];
5437 _end
b4d89997 5438
808c6eb6
JF
5439 if (section == nil || [section index] != index) {
5440 _profile(PackageTable$reloadData$Section$Allocate)
5441 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5442 _end
b4d89997 5443
327624b6
JF
5444 [index_ addObject:[section name]];
5445 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5446
c4dcf2c2
JF
5447 _profile(PackageTable$reloadData$Section$Add)
5448 [sections_ addObject:section];
5449 _end
808c6eb6
JF
5450 }
5451
5452 [section addToCount];
5453 }
5454 _end
b4d89997 5455
c4dcf2c2
JF
5456 _profile(PackageTable$reloadData$List)
5457 [list_ reloadData];
5458 _end
b4d89997
JF
5459}
5460
a0be02eb 5461- (void) resetCursor {
327624b6 5462 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
a0be02eb
JF
5463}
5464
327624b6 5465- (UITableView *) list {
2388b078
JF
5466 return list_;
5467}
5468
ab398adf 5469- (void) setShouldHideHeaderInShortLists:(BOOL)hide {
327624b6 5470 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
ab398adf
JF
5471}
5472
a3328c28
JF
5473@end
5474/* }}} */
5475/* Filtered Package Table {{{ */
5476@interface FilteredPackageTable : PackageTable {
5477 SEL filter_;
76933519 5478 IMP imp_;
a3328c28
JF
5479 id object_;
5480}
5481
5482- (void) setObject:(id)object;
01d93940 5483- (void) setObject:(id)object forFilter:(SEL)filter;
a3328c28 5484
b5e7eebb 5485- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
a3328c28
JF
5486
5487@end
5488
5489@implementation FilteredPackageTable
5490
5491- (void) dealloc {
5492 if (object_ != nil)
5493 [object_ release];
5494 [super dealloc];
5495}
5496
01d93940
JF
5497- (void) setFilter:(SEL)filter {
5498 filter_ = filter;
5499
5500 /* XXX: this is an unsafe optimization of doomy hell */
5501 Method method(class_getInstanceMethod([Package class], filter));
5502 _assert(method != NULL);
5503 imp_ = method_getImplementation(method);
5504 _assert(imp_ != NULL);
5505}
5506
a3328c28
JF
5507- (void) setObject:(id)object {
5508 if (object_ != nil)
5509 [object_ release];
5510 if (object == nil)
5511 object_ = nil;
5512 else
5513 object_ = [object retain];
5514}
5515
01d93940
JF
5516- (void) setObject:(id)object forFilter:(SEL)filter {
5517 [self setFilter:filter];
5518 [self setObject:object];
01d93940
JF
5519}
5520
a3328c28 5521- (bool) hasPackage:(Package *)package {
76933519
JF
5522 _profile(FilteredPackageTable$hasPackage)
5523 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5524 _end
a3328c28
JF
5525}
5526
b5e7eebb
GP
5527- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5528 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
01d93940 5529 [self setFilter:filter];
b5e7eebb 5530 object_ = [object retain];
189a73d0 5531 [self reloadData];
a3328c28
JF
5532 } return self;
5533}
5534
dc5812ec 5535@end
b4d89997 5536/* }}} */
dc5812ec 5537
adb61bda
GP
5538/* Filtered Package Controller {{{ */
5539@interface FilteredPackageController : CYViewController {
b5e7eebb
GP
5540 _transient Database *database_;
5541 FilteredPackageTable *packages_;
5542 NSString *title_;
5543}
5544
5545- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5546
5547@end
bc11cf5b 5548
adb61bda 5549@implementation FilteredPackageController
b5e7eebb
GP
5550
5551- (void) dealloc {
5552 [packages_ release];
5553 [title_ release];
bc11cf5b 5554
b5e7eebb
GP
5555 [super dealloc];
5556}
5557
5558- (void) viewDidAppear:(BOOL)animated {
5559 [super viewDidAppear:animated];
5560 [packages_ deselectWithAnimation:animated];
5561}
5562
5563- (void) didSelectPackage:(Package *)package {
adb61bda 5564 PackageController *view([delegate_ packageController]);
b5e7eebb
GP
5565 [view setPackage:package];
5566 [view setDelegate:delegate_];
5567 [[self navigationController] pushViewController:view animated:YES];
5568}
5569
eb30da80 5570- (NSString *) title { return title_; }
b5e7eebb
GP
5571
5572- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5573 if ((self = [super init]) != nil) {
5574 database_ = database;
5575 title_ = [title copy];
5576 [[self navigationItem] setTitle:title_];
5577
5578 packages_ = [[FilteredPackageTable alloc]
5579 initWithFrame:[[self view] bounds]
5580 database:database
5581 target:self
5582 action:@selector(didSelectPackage:)
5583 filter:filter
5584 with:object
5585 ];
5586
5587 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5588 [[self view] addSubview:packages_];
5589 } return self;
5590}
5591
5592- (void) reloadData {
5593 [packages_ reloadData];
5594}
5595
5596- (void) setDelegate:(id)delegate {
5597 [super setDelegate:delegate];
5598 [packages_ setDelegate:delegate];
5599}
5600
5601@end
bc11cf5b 5602
b5e7eebb
GP
5603/* }}} */
5604
adb61bda
GP
5605/* Add Source Controller {{{ */
5606@interface AddSourceController : CYViewController {
7b0ce2da 5607 _transient Database *database_;
dc5812ec
JF
5608}
5609
b5e7eebb 5610- (id) initWithDatabase:(Database *)database;
b4d89997 5611
7b0ce2da 5612@end
dc5812ec 5613
adb61bda 5614@implementation AddSourceController
dc5812ec 5615
b5e7eebb
GP
5616- (id) initWithDatabase:(Database *)database {
5617 if ((self = [super init]) != nil) {
7b0ce2da
JF
5618 database_ = database;
5619 } return self;
36bb2ca2 5620}
dc5812ec 5621
7b0ce2da
JF
5622@end
5623/* }}} */
5624/* Source Cell {{{ */
555aaf71 5625@interface SourceCell : CYTableViewCell <
c21004b9
JF
5626 ContentDelegate
5627> {
f641a0e5
JF
5628 UIImage *icon_;
5629 NSString *origin_;
5630 NSString *description_;
5631 NSString *label_;
b4d89997
JF
5632}
5633
46aa9775 5634- (void) setSource:(Source *)source;
b4d89997 5635
7b0ce2da 5636@end
b4d89997 5637
7b0ce2da 5638@implementation SourceCell
b4d89997 5639
46aa9775 5640- (void) clearSource {
f641a0e5 5641 [icon_ release];
7b0ce2da
JF
5642 [origin_ release];
5643 [description_ release];
5644 [label_ release];
46aa9775
GP
5645
5646 icon_ = nil;
5647 origin_ = nil;
5648 description_ = nil;
5649 label_ = nil;
5650}
5651
5652- (void) setSource:(Source *)source {
5653 [self clearSource];
bc11cf5b 5654
46aa9775
GP
5655 if (icon_ == nil)
5656 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5657 if (icon_ == nil)
5658 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5659 icon_ = [icon_ retain];
5660
5661 origin_ = [[source name] retain];
5662 label_ = [[source uri] retain];
5663 description_ = [[source description] retain];
5664
5665 [content_ setNeedsDisplay];
5666}
5667
5668- (void) dealloc {
5669 [self clearSource];
7b0ce2da 5670 [super dealloc];
36bb2ca2 5671}
b4d89997 5672
46aa9775
GP
5673- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5674 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5675 UIView *content([self contentView]);
5676 CGRect bounds([content bounds]);
5677
5678 content_ = [[ContentView alloc] initWithFrame:bounds];
5679 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5680 [content_ setBackgroundColor:[UIColor whiteColor]];
5681 [content addSubview:content_];
5682
5683 [content_ setDelegate:self];
5684 [content_ setOpaque:YES];
7b0ce2da 5685 } return self;
a0376fc1
JF
5686}
5687
46aa9775 5688- (void) drawContentRect:(CGRect)rect {
555aaf71 5689 bool highlighted(highlighted_);
01d93940
JF
5690 float width(rect.size.width);
5691
f641a0e5
JF
5692 if (icon_ != nil)
5693 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7b0ce2da 5694
555aaf71 5695 if (highlighted)
f641a0e5 5696 UISetColor(White_);
7b0ce2da 5697
555aaf71 5698 if (!highlighted)
f641a0e5 5699 UISetColor(Black_);
54b844a0 5700 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7b0ce2da 5701
555aaf71 5702 if (!highlighted)
f641a0e5 5703 UISetColor(Blue_);
54b844a0 5704 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7b0ce2da 5705
555aaf71 5706 if (!highlighted)
f641a0e5 5707 UISetColor(Gray_);
54b844a0 5708 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
7b0ce2da
JF
5709}
5710
5711@end
5712/* }}} */
5713/* Source Table {{{ */
c21004b9
JF
5714@interface SourceTable : CYViewController <
5715 UITableViewDataSource,
5716 UITableViewDelegate
5717> {
7b0ce2da 5718 _transient Database *database_;
46aa9775 5719 UITableView *list_;
7b0ce2da 5720 NSMutableArray *sources_;
7b0ce2da
JF
5721 int offset_;
5722
5723 NSString *href_;
5724 UIProgressHUD *hud_;
5725 NSError *error_;
5726
5727 //NSURLConnection *installer_;
42543928 5728 NSURLConnection *trivial_;
7b0ce2da
JF
5729 NSURLConnection *trivial_bz2_;
5730 NSURLConnection *trivial_gz_;
5731 //NSURLConnection *automatic_;
5732
42543928 5733 BOOL cydia_;
7b0ce2da
JF
5734}
5735
b5e7eebb 5736- (id) initWithDatabase:(Database *)database;
7b0ce2da 5737
c21004b9
JF
5738- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5739
7b0ce2da
JF
5740@end
5741
5742@implementation SourceTable
5743
3931b718 5744- (void) _releaseConnection:(NSURLConnection *)connection {
7b0ce2da
JF
5745 if (connection != nil) {
5746 [connection cancel];
5747 //[connection setDelegate:nil];
5748 [connection release];
5749 }
5750}
5751
5752- (void) dealloc {
7b0ce2da
JF
5753 if (href_ != nil)
5754 [href_ release];
5755 if (hud_ != nil)
5756 [hud_ release];
5757 if (error_ != nil)
5758 [error_ release];
5759
3931b718
JF
5760 //[self _releaseConnection:installer_];
5761 [self _releaseConnection:trivial_];
5762 [self _releaseConnection:trivial_gz_];
5763 [self _releaseConnection:trivial_bz2_];
5764 //[self _releaseConnection:automatic_];
7b0ce2da
JF
5765
5766 [sources_ release];
5767 [list_ release];
5768 [super dealloc];
5769}
5770
b5e7eebb
GP
5771- (void) viewDidAppear:(BOOL)animated {
5772 [super viewDidAppear:animated];
5773 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5774}
5775
eb30da80 5776- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7b0ce2da
JF
5777 return offset_ == 0 ? 1 : 2;
5778}
5779
eb30da80 5780- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7b0ce2da 5781 switch (section + (offset_ == 0 ? 1 : 0)) {
43f3d7f6
JF
5782 case 0: return UCLocalize("ENTERED_BY_USER");
5783 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7b0ce2da 5784
670a0494 5785 _nodefault
7b0ce2da
JF
5786 }
5787}
5788
eb30da80 5789- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
46aa9775
GP
5790 int count = [sources_ count];
5791 switch (section) {
5792 case 0: return (offset_ == 0 ? count : offset_);
5793 case 1: return count - offset_;
7b0ce2da 5794
b5e7eebb 5795 _nodefault
7b0ce2da
JF
5796 }
5797}
5798
46aa9775
GP
5799- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5800 unsigned idx = 0;
5801 switch (indexPath.section) {
5802 case 0: idx = indexPath.row; break;
5803 case 1: idx = indexPath.row + offset_; break;
5804
b5e7eebb 5805 _nodefault
46aa9775
GP
5806 }
5807 return [sources_ objectAtIndex:idx];
7b0ce2da
JF
5808}
5809
46aa9775
GP
5810- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5811 Source *source = [self sourceAtIndexPath:indexPath];
f641a0e5 5812 return [source description] == nil ? 56 : 73;
7b0ce2da
JF
5813}
5814
46aa9775 5815- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb 5816 static NSString *cellIdentifier = @"SourceCell";
7b0ce2da 5817
46aa9775 5818 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
b5e7eebb
GP
5819 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5820 [cell setSource:[self sourceAtIndexPath:indexPath]];
bc11cf5b 5821
46aa9775 5822 return cell;
7b0ce2da
JF
5823}
5824
c21004b9
JF
5825- (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5826 return UITableViewCellAccessoryDisclosureIndicator;
7b0ce2da
JF
5827}
5828
46aa9775
GP
5829- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5830 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da 5831
adb61bda 5832 FilteredPackageController *packages = [[[FilteredPackageController alloc]
b5e7eebb 5833 initWithDatabase:database_
7b0ce2da
JF
5834 title:[source label]
5835 filter:@selector(isVisibleInSource:)
5836 with:source
5837 ] autorelease];
5838
5839 [packages setDelegate:delegate_];
5840
b5e7eebb 5841 [[self navigationController] pushViewController:packages animated:YES];
7b0ce2da
JF
5842}
5843
46aa9775
GP
5844- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5845 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da
JF
5846 return [source record] != nil;
5847}
5848
46aa9775
GP
5849- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5850 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da
JF
5851 [Sources_ removeObjectForKey:[source key]];
5852 [delegate_ syncData];
5853}
5854
2fc76a2d
JF
5855- (void) complete {
5856 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5857 @"deb", @"Type",
5858 href_, @"URI",
5859 @"./", @"Distribution",
5860 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5861
5862 [delegate_ syncData];
5863}
5864
5865- (NSString *) getWarning {
3e9c9e85
JF
5866 NSString *href(href_);
5867 NSRange colon([href rangeOfString:@"://"]);
5868 if (colon.location != NSNotFound)
5869 href = [href substringFromIndex:(colon.location + 3)];
5870 href = [href stringByAddingPercentEscapes];
670a0494 5871 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
2fc76a2d
JF
5872 href = [href stringByCachingURLWithCurrentCDN];
5873
5874 NSURL *url([NSURL URLWithString:href]);
5875
5876 NSStringEncoding encoding;
5877 NSError *error(nil);
5878
5879 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5880 return [warning length] == 0 ? nil : warning;
5881 return nil;
5882}
5883
7b0ce2da 5884- (void) _endConnection:(NSURLConnection *)connection {
3931b718
JF
5885 // XXX: the memory management in this method is horribly awkward
5886
7b0ce2da 5887 NSURLConnection **field = NULL;
42543928
JF
5888 if (connection == trivial_)
5889 field = &trivial_;
5890 else if (connection == trivial_bz2_)
7b0ce2da
JF
5891 field = &trivial_bz2_;
5892 else if (connection == trivial_gz_)
5893 field = &trivial_gz_;
5894 _assert(field != NULL);
5895 [connection release];
5896 *field = nil;
5897
5898 if (
42543928 5899 trivial_ == nil &&
7b0ce2da
JF
5900 trivial_bz2_ == nil &&
5901 trivial_gz_ == nil
5902 ) {
3e9c9e85 5903 bool defer(false);
7b0ce2da 5904
42543928 5905 if (cydia_) {
2fc76a2d 5906 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
3e9c9e85
JF
5907 defer = true;
5908
0fe9a7e8 5909 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 5910 initWithTitle:UCLocalize("SOURCE_WARNING")
b5e7eebb
GP
5911 message:warning
5912 delegate:self
5913 cancelButtonTitle:UCLocalize("CANCEL")
0fe9a7e8 5914 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
2fc76a2d
JF
5915 ] autorelease];
5916
b5e7eebb 5917 [alert setContext:@"warning"];
0fe9a7e8
GP
5918 [alert setNumberOfRows:1];
5919 [alert show];
2fc76a2d
JF
5920 } else
5921 [self complete];
7b0ce2da 5922 } else if (error_ != nil) {
0fe9a7e8 5923 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 5924 initWithTitle:UCLocalize("VERIFICATION_ERROR")
b5e7eebb
GP
5925 message:[error_ localizedDescription]
5926 delegate:self
5927 cancelButtonTitle:UCLocalize("OK")
0fe9a7e8 5928 otherButtonTitles:nil
7b0ce2da
JF
5929 ] autorelease];
5930
b5e7eebb 5931 [alert setContext:@"urlerror"];
0fe9a7e8 5932 [alert show];
7b0ce2da 5933 } else {
0fe9a7e8 5934 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 5935 initWithTitle:UCLocalize("NOT_REPOSITORY")
b5e7eebb
GP
5936 message:UCLocalize("NOT_REPOSITORY_EX")
5937 delegate:self
5938 cancelButtonTitle:UCLocalize("OK")
0fe9a7e8 5939 otherButtonTitles:nil
7b0ce2da
JF
5940 ] autorelease];
5941
b5e7eebb 5942 [alert setContext:@"trivial"];
0fe9a7e8 5943 [alert show];
7b0ce2da
JF
5944 }
5945
3e9c9e85
JF
5946 [delegate_ setStatusBarShowsProgress:NO];
5947 [delegate_ removeProgressHUD:hud_];
5948
5949 [hud_ autorelease];
5950 hud_ = nil;
5951
5952 if (!defer) {
5953 [href_ release];
5954 href_ = nil;
5955 }
7b0ce2da
JF
5956
5957 if (error_ != nil) {
5958 [error_ release];
5959 error_ = nil;
5960 }
5961 }
5962}
5963
5964- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5965 switch ([response statusCode]) {
5966 case 200:
42543928 5967 cydia_ = YES;
7b0ce2da
JF
5968 }
5969}
5970
5971- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
c390d3ab 5972 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7b0ce2da
JF
5973 if (error_ != nil)
5974 error_ = [error retain];
5975 [self _endConnection:connection];
5976}
5977
5978- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5979 [self _endConnection:connection];
5980}
5981
eb30da80 5982- (NSString *) title { return UCLocalize("SOURCES"); }
b5e7eebb 5983
7b0ce2da
JF
5984- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5985 NSMutableURLRequest *request = [NSMutableURLRequest
5986 requestWithURL:[NSURL URLWithString:href]
5987 cachePolicy:NSURLRequestUseProtocolCachePolicy
77801ff1 5988 timeoutInterval:120.0
7b0ce2da
JF
5989 ];
5990
5991 [request setHTTPMethod:method];
5992
f79a4512
JF
5993 if (Machine_ != NULL)
5994 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
77801ff1
JF
5995 if (UniqueID_ != nil)
5996 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
f79a4512
JF
5997 if (Role_ != nil)
5998 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5999
7b0ce2da
JF
6000 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6001}
6002
0fe9a7e8
GP
6003- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6004 NSString *context([alert context]);
1cedb821
JF
6005
6006 if ([context isEqualToString:@"source"]) {
7b0ce2da
JF
6007 switch (button) {
6008 case 1: {
0fe9a7e8 6009 NSString *href = [[alert textField] text];
7b0ce2da
JF
6010
6011 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6012
6013 if (![href hasSuffix:@"/"])
6014 href_ = [href stringByAppendingString:@"/"];
6015 else
6016 href_ = href;
6017 href_ = [href_ retain];
6018
42543928 6019 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7b0ce2da
JF
6020 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6021 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6022 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6023
42543928 6024 cydia_ = false;
7b0ce2da 6025
3931b718 6026 // XXX: this is stupid
d061f4ba 6027 hud_ = [[delegate_ addProgressHUD] retain];
43f3d7f6 6028 [hud_ setText:UCLocalize("VERIFYING_URL")];
7b0ce2da
JF
6029 } break;
6030
0fe9a7e8 6031 case 0:
7b0ce2da
JF
6032 break;
6033
670a0494 6034 _nodefault
7b0ce2da
JF
6035 }
6036
0fe9a7e8 6037 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b49f4c92 6038 } else if ([context isEqualToString:@"trivial"])
0fe9a7e8 6039 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b49f4c92 6040 else if ([context isEqualToString:@"urlerror"])
0fe9a7e8 6041 [alert dismissWithClickedButtonIndex:-1 animated:YES];
2fc76a2d
JF
6042 else if ([context isEqualToString:@"warning"]) {
6043 switch (button) {
6044 case 1:
6045 [self complete];
6046 break;
6047
0fe9a7e8 6048 case 0:
2fc76a2d
JF
6049 break;
6050
670a0494 6051 _nodefault
2fc76a2d
JF
6052 }
6053
3e9c9e85
JF
6054 [href_ release];
6055 href_ = nil;
6056
0fe9a7e8 6057 [alert dismissWithClickedButtonIndex:-1 animated:YES];
2fc76a2d 6058 }
7b0ce2da
JF
6059}
6060
b5e7eebb
GP
6061- (id) initWithDatabase:(Database *)database {
6062 if ((self = [super init]) != nil) {
6063 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6064 [self updateButtonsForEditingStatus:NO animated:NO];
bc11cf5b 6065
7b0ce2da
JF
6066 database_ = database;
6067 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6068
b5e7eebb 6069 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 6070 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b5e7eebb 6071 [[self view] addSubview:list_];
04fe1349 6072
7b0ce2da 6073 [list_ setDataSource:self];
46aa9775 6074 [list_ setDelegate:self];
7b0ce2da
JF
6075
6076 [self reloadData];
6077 } return self;
6078}
6079
6080- (void) reloadData {
6081 pkgSourceList list;
670a0494
JF
6082 if (!list.ReadMainList())
6083 return;
7b0ce2da
JF
6084
6085 [sources_ removeAllObjects];
6086 [sources_ addObjectsFromArray:[database_ sources]];
807ae6d7 6087 _trace();
7b0ce2da 6088 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
807ae6d7 6089 _trace();
7b0ce2da 6090
36fbb2aa 6091 int count([sources_ count]);
46aa9775
GP
6092 offset_ = 0;
6093 for (int i = 0; i != count; i++) {
36fbb2aa
JF
6094 if ([[sources_ objectAtIndex:i] record] == nil)
6095 break;
6096 offset_++;
7b0ce2da
JF
6097 }
6098
46aa9775 6099 [list_ setEditing:NO];
b5e7eebb 6100 [self updateButtonsForEditingStatus:NO animated:NO];
7b0ce2da
JF
6101 [list_ reloadData];
6102}
6103
b5e7eebb 6104- (void) addButtonClicked {
adb61bda 6105 /*[book_ pushPage:[[[AddSourceController alloc]
7b0ce2da
JF
6106 initWithBook:book_
6107 database:database_
6108 ] autorelease]];*/
6109
0fe9a7e8 6110 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 6111 initWithTitle:UCLocalize("ENTER_APT_URL")
b5e7eebb
GP
6112 message:nil
6113 delegate:self
6114 cancelButtonTitle:UCLocalize("CANCEL")
6115 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7b0ce2da
JF
6116 ] autorelease];
6117
b5e7eebb
GP
6118 [alert setContext:@"source"];
6119 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
1cedb821 6120
0fe9a7e8
GP
6121 [alert setNumberOfRows:1];
6122 [alert addTextFieldWithValue:@"http://" label:@""];
7b0ce2da 6123
0fe9a7e8 6124 UITextInputTraits *traits = [[alert textField] textInputTraits];
b49f4c92
JF
6125 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6126 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
1cedb821 6127 [traits setKeyboardType:UIKeyboardTypeURL];
b49f4c92
JF
6128 // XXX: UIReturnKeyDone
6129 [traits setReturnKeyType:UIReturnKeyNext];
7b0ce2da 6130
0fe9a7e8 6131 [alert show];
7b0ce2da
JF
6132}
6133
b5e7eebb 6134- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
dd9de556 6135 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
b5e7eebb
GP
6136 initWithTitle:UCLocalize("ADD")
6137 style:UIBarButtonItemStylePlain
6138 target:self
6139 action:@selector(addButtonClicked)
dd9de556 6140 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
b5e7eebb 6141
dd9de556
JF
6142 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6143 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6144 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
b5e7eebb
GP
6145 target:self
6146 action:@selector(editButtonClicked)
dd9de556 6147 ] autorelease] animated:animated];
bc11cf5b 6148
dd9de556
JF
6149 if (IsWildcat_ && !editing)
6150 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
2bdd73bd
GP
6151 initWithTitle:UCLocalize("SETTINGS")
6152 style:UIBarButtonItemStylePlain
6153 target:self
6154 action:@selector(settingsButtonClicked)
dd9de556 6155 ] autorelease]];
2bdd73bd
GP
6156}
6157
6158- (void) settingsButtonClicked {
6159 [delegate_ showSettings];
7b0ce2da
JF
6160}
6161
b5e7eebb
GP
6162- (void) editButtonClicked {
6163 [list_ setEditing:![list_ isEditing] animated:YES];
bc11cf5b 6164
b5e7eebb 6165 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
7b0ce2da
JF
6166}
6167
6168@end
6169/* }}} */
6170
adb61bda
GP
6171/* Installed Controller {{{ */
6172@interface InstalledController : FilteredPackageController {
f641a0e5 6173 BOOL expert_;
7b0ce2da
JF
6174}
6175
b5e7eebb 6176- (id) initWithDatabase:(Database *)database;
7b0ce2da 6177
c21004b9
JF
6178- (void) updateRoleButton;
6179- (void) queueStatusDidChange;
6180
7b0ce2da
JF
6181@end
6182
adb61bda 6183@implementation InstalledController
7b0ce2da
JF
6184
6185- (void) dealloc {
7b0ce2da
JF
6186 [super dealloc];
6187}
6188
eb30da80 6189- (NSString *) title { return UCLocalize("INSTALLED"); }
baf80942 6190
b5e7eebb 6191- (id) initWithDatabase:(Database *)database {
e4f3d6e9 6192 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
b5e7eebb
GP
6193 [self updateRoleButton];
6194 [self queueStatusDidChange];
7b0ce2da
JF
6195 } return self;
6196}
6197
b5e7eebb
GP
6198#if !AlwaysReload
6199- (void) queueButtonClicked {
6200 [delegate_ queue];
7b0ce2da 6201}
b5e7eebb 6202#endif
7b0ce2da 6203
b5e7eebb
GP
6204- (void) queueStatusDidChange {
6205#if !AlwaysReload
6206 if (IsWildcat_) {
dd9de556
JF
6207 if (Queuing_) {
6208 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6209 initWithTitle:UCLocalize("QUEUE")
6210 style:UIBarButtonItemStyleDone
6211 target:self
6212 action:@selector(queueButtonClicked)
6213 ] autorelease]];
6214 } else {
6215 [[self navigationItem] setLeftBarButtonItem:nil];
6216 }
b5e7eebb
GP
6217 }
6218#endif
f641a0e5
JF
6219}
6220
b5e7eebb
GP
6221- (void) reloadData {
6222 [packages_ reloadData];
7b0ce2da
JF
6223}
6224
b5e7eebb 6225- (void) updateRoleButton {
dd9de556
JF
6226 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6227 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6228 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6229 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6230 target:self
6231 action:@selector(roleButtonClicked)
6232 ] autorelease]];
7b0ce2da
JF
6233}
6234
b5e7eebb
GP
6235- (void) roleButtonClicked {
6236 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6237 [packages_ reloadData];
6238 expert_ = !expert_;
f641a0e5 6239
b5e7eebb 6240 [self updateRoleButton];
f641a0e5
JF
6241}
6242
7b0ce2da
JF
6243- (void) setDelegate:(id)delegate {
6244 [super setDelegate:delegate];
6245 [packages_ setDelegate:delegate];
6246}
6247
6248@end
6249/* }}} */
6250
adb61bda
GP
6251/* Home Controller {{{ */
6252@interface HomeController : CYBrowserController {
7b0ce2da
JF
6253}
6254
6255@end
6256
adb61bda 6257@implementation HomeController
7b0ce2da 6258
bfc87a4d
JF
6259- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6260 [super _setMoreHeaders:request];
526ea480 6261
bfc87a4d
JF
6262 if (ChipID_ != nil)
6263 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
01d93940
JF
6264 if (UniqueID_ != nil)
6265 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
567e3972
JF
6266 if (PLMN_ != nil)
6267 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
bfc87a4d
JF
6268}
6269
b5e7eebb 6270- (void) aboutButtonClicked {
526ea480
JF
6271 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6272
65c27c56
JF
6273 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6274 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6275 [alert setCancelButtonIndex:0];
7b0ce2da 6276
65c27c56 6277 [alert setMessage:
77801ff1 6278 @"Copyright (C) 2008-2010\n"
7b0ce2da
JF
6279 "Jay Freeman (saurik)\n"
6280 "saurik@saurik.com\n"
42fc47f8 6281 "http://www.saurik.com/"
7b0ce2da
JF
6282 ];
6283
65c27c56 6284 [alert show];
7b0ce2da
JF
6285}
6286
b5e7eebb
GP
6287- (void) viewWillAppear:(BOOL)animated {
6288 [super viewWillAppear:animated];
2411bceb 6289 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
b5e7eebb
GP
6290}
6291
6292- (void) viewWillDisappear:(BOOL)animated {
6293 [super viewWillDisappear:animated];
2411bceb 6294 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
b5e7eebb
GP
6295}
6296
6297- (id) init {
6298 if ((self = [super init]) != nil) {
526ea480 6299 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
b5e7eebb
GP
6300 initWithTitle:UCLocalize("ABOUT")
6301 style:UIBarButtonItemStylePlain
6302 target:self
6303 action:@selector(aboutButtonClicked)
526ea480 6304 ] autorelease]];
b5e7eebb 6305 } return self;
7b0ce2da
JF
6306}
6307
6308@end
98228790 6309/* }}} */
adb61bda
GP
6310/* Manage Controller {{{ */
6311@interface ManageController : CYBrowserController {
7b0ce2da
JF
6312}
6313
c21004b9 6314- (void) queueStatusDidChange;
7b0ce2da
JF
6315@end
6316
adb61bda 6317@implementation ManageController
7b0ce2da 6318
b5e7eebb
GP
6319- (id) init {
6320 if ((self = [super init]) != nil) {
6321 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
bc11cf5b 6322
dd9de556 6323 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
b5e7eebb
GP
6324 initWithTitle:UCLocalize("SETTINGS")
6325 style:UIBarButtonItemStylePlain
6326 target:self
6327 action:@selector(settingsButtonClicked)
dd9de556 6328 ] autorelease]];
bc11cf5b 6329
b5e7eebb
GP
6330 [self queueStatusDidChange];
6331 } return self;
7b0ce2da
JF
6332}
6333
b5e7eebb 6334- (void) settingsButtonClicked {
21c6da4b 6335 [delegate_ showSettings];
7b0ce2da
JF
6336}
6337
bf8476c8 6338#if !AlwaysReload
b5e7eebb
GP
6339- (void) queueButtonClicked {
6340 [delegate_ queue];
dc63e78f
JF
6341}
6342
eb97a3a8
GP
6343- (void) applyLoadingTitle {
6344 // No "Loading" title.
6345}
6346
6347- (void) applyRightButton {
6348 // No right button.
dc63e78f 6349}
eb97a3a8 6350#endif
dc63e78f 6351
b5e7eebb
GP
6352- (void) queueStatusDidChange {
6353#if !AlwaysReload
6354 if (!IsWildcat_ && Queuing_) {
dd9de556 6355 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
b5e7eebb
GP
6356 initWithTitle:UCLocalize("QUEUE")
6357 style:UIBarButtonItemStyleDone
6358 target:self
6359 action:@selector(queueButtonClicked)
dd9de556 6360 ] autorelease]];
b5e7eebb
GP
6361 } else {
6362 [[self navigationItem] setRightBarButtonItem:nil];
6363 }
bf8476c8 6364#endif
b5e7eebb 6365}
7b0ce2da 6366
3bd1c2a2 6367- (bool) isLoading {
9fe5e5f8
JF
6368 return false;
6369}
6370
7b0ce2da 6371@end
98228790 6372/* }}} */
7b0ce2da 6373
b5e7eebb
GP
6374/* Refresh Bar {{{ */
6375@interface RefreshBar : UINavigationBar {
7b0ce2da
JF
6376 UIProgressIndicator *indicator_;
6377 UITextLabel *prompt_;
6378 UIProgressBar *progress_;
baf80942 6379 UINavigationButton *cancel_;
aa5e5990
JF
6380}
6381
aa5e5990 6382@end
aa5e5990 6383
b5e7eebb 6384@implementation RefreshBar
01d93940 6385
3931b718
JF
6386- (void) dealloc {
6387 [indicator_ release];
6388 [prompt_ release];
6389 [progress_ release];
6390 [cancel_ release];
6391 [super dealloc];
6392}
6393
39cda3a8
GP
6394- (void) positionViews {
6395 CGRect frame = [cancel_ frame];
6396 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6397 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6398 [cancel_ setFrame:frame];
bc11cf5b 6399
39cda3a8
GP
6400 CGSize prgsize = {75, 100};
6401 CGRect prgrect = {{
6402 [self frame].size.width - prgsize.width - 10,
6403 ([self frame].size.height - prgsize.height) / 2
6404 } , prgsize};
6405 [progress_ setFrame:prgrect];
bc11cf5b 6406
39cda3a8
GP
6407 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6408 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6409 CGRect indrect = {{indoffset, indoffset}, indsize};
6410 [indicator_ setFrame:indrect];
bc11cf5b 6411
39cda3a8
GP
6412 CGSize prmsize = {215, indsize.height + 4};
6413 CGRect prmrect = {{
6414 indoffset * 2 + indsize.width,
6415 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6416 }, prmsize};
6417 [prompt_ setFrame:prmrect];
6418}
6419
6420- (void)setFrame:(CGRect)frame {
6421 [super setFrame:frame];
bc11cf5b 6422
39cda3a8
GP
6423 [self positionViews];
6424}
6425
b5e7eebb
GP
6426- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6427 if ((self = [super initWithFrame:frame])) {
6428 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
01d93940 6429
b5e7eebb 6430 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
c21004b9 6431 [self setBarStyle:UIBarStyleBlack];
01d93940 6432
c21004b9
JF
6433 UIBarStyle barstyle([self _barStyle:NO]);
6434 bool ugly(barstyle == UIBarStyleDefault);
807ae6d7
JF
6435
6436 UIProgressIndicatorStyle style = ugly ?
6437 UIProgressIndicatorStyleMediumBrown :
6438 UIProgressIndicatorStyleMediumWhite;
6439
39cda3a8 6440 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
807ae6d7 6441 [indicator_ setStyle:style];
39cda3a8 6442 [indicator_ startAnimation];
b5e7eebb 6443 [self addSubview:indicator_];
807ae6d7 6444
39cda3a8 6445 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
807ae6d7
JF
6446 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6447 [prompt_ setBackgroundColor:[UIColor clearColor]];
39cda3a8 6448 [prompt_ setFont:[UIFont systemFontOfSize:15]];
b5e7eebb 6449 [self addSubview:prompt_];
807ae6d7 6450
39cda3a8
GP
6451 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6452 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
04fe1349 6453 [progress_ setStyle:0];
39cda3a8 6454 [self addSubview:progress_];
bc11cf5b 6455
43f3d7f6 6456 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
8c02abc8 6457 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
b5e7eebb 6458 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
39cda3a8 6459 [cancel_ setBarStyle:barstyle];
bc11cf5b 6460
39cda3a8 6461 [self positionViews];
807ae6d7
JF
6462 } return self;
6463}
6464
b5e7eebb 6465- (void) cancel {
807ae6d7
JF
6466 [cancel_ removeFromSuperview];
6467}
6468
b5e7eebb
GP
6469- (void) start {
6470 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6471 [progress_ setProgress:0];
6472 [self addSubview:cancel_];
6473}
6474
6475- (void) stop {
6476 [cancel_ removeFromSuperview];
6477}
6478
6479- (void) setPrompt:(NSString *)prompt {
6480 [prompt_ setText:prompt];
6481}
6482
6483- (void) setProgress:(float)progress {
6484 [progress_ setProgress:progress];
6485}
6486
6487@end
6488/* }}} */
6489
c21004b9
JF
6490@class CYNavigationController;
6491
b5e7eebb 6492/* Cydia Tab Bar Controller {{{ */
8c02abc8 6493@interface CYTabBarController : UITabBarController {
3931b718 6494 _transient Database *database_;
b5e7eebb
GP
6495}
6496
bc11cf5b 6497@end
b5e7eebb
GP
6498
6499@implementation CYTabBarController
6500
8c02abc8
GP
6501/* XXX: some logic should probably go here related to
6502freeing the view controllers on tab change */
807ae6d7 6503
b5e7eebb
GP
6504- (void) reloadData {
6505 size_t count([[self viewControllers] count]);
6506 for (size_t i(0); i != count; ++i) {
c21004b9 6507 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
b5e7eebb
GP
6508 [page reloadData];
6509 }
6510}
6511
14d60a3f 6512- (id) initWithDatabase:(Database *)database {
b5e7eebb
GP
6513 if ((self = [super init]) != nil) {
6514 database_ = database;
b5e7eebb
GP
6515 } return self;
6516}
6517
6518@end
6519/* }}} */
6520
6521/* Cydia Navigation Controller {{{ */
c21004b9 6522@interface CYNavigationController : UINavigationController {
b5e7eebb 6523 _transient Database *database_;
3931b718 6524 _transient id<UINavigationControllerDelegate> delegate_;
b5e7eebb
GP
6525}
6526
6527- (id) initWithDatabase:(Database *)database;
6528- (void) reloadData;
6529
6530@end
6531
6532
6533@implementation CYNavigationController
6534
9cb0bff2
GP
6535- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6536 // Inherit autorotation settings for modal parents.
6537 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6538 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6539 } else {
6540 return [super shouldAutorotateToInterfaceOrientation:orientation];
6541 }
6542}
6543
b5e7eebb
GP
6544- (void) dealloc {
6545 [super dealloc];
6546}
6547
6548- (void) reloadData {
6549 size_t count([[self viewControllers] count]);
6550 for (size_t i(0); i != count; ++i) {
c21004b9 6551 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
b5e7eebb
GP
6552 [page reloadData];
6553 }
6554}
6555
eb30da80 6556- (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
b5e7eebb
GP
6557 delegate_ = delegate;
6558}
6559
6560- (id) initWithDatabase:(Database *)database {
6561 if ((self = [super init]) != nil) {
6562 database_ = database;
6563 } return self;
6564}
6565
807ae6d7
JF
6566@end
6567/* }}} */
6568/* Cydia:// Protocol {{{ */
6569@interface CydiaURLProtocol : NSURLProtocol {
6570}
6571
6572@end
6573
6574@implementation CydiaURLProtocol
6575
6576+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
6577 NSURL *url([request URL]);
6578 if (url == nil)
6579 return NO;
6580 NSString *scheme([[url scheme] lowercaseString]);
6581 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6582 return NO;
6583 return YES;
6584}
6585
6586+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6587 return request;
6588}
6589
9fe5e5f8
JF
6590- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6591 id<NSURLProtocolClient> client([self client]);
189a73d0
JF
6592 if (icon == nil)
6593 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6594 else {
6595 NSData *data(UIImagePNGRepresentation(icon));
9fe5e5f8 6596
189a73d0
JF
6597 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6598 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6599 [client URLProtocol:self didLoadData:data];
6600 [client URLProtocolDidFinishLoading:self];
6601 }
9fe5e5f8
JF
6602}
6603
807ae6d7
JF
6604- (void) startLoading {
6605 id<NSURLProtocolClient> client([self client]);
6606 NSURLRequest *request([self request]);
6607
6608 NSURL *url([request URL]);
6609 NSString *href([url absoluteString]);
6610
6611 NSString *path([href substringFromIndex:8]);
6612 NSRange slash([path rangeOfString:@"/"]);
6613
6614 NSString *command;
6615 if (slash.location == NSNotFound) {
6616 command = path;
6617 path = nil;
6618 } else {
6619 command = [path substringToIndex:slash.location];
6620 path = [path substringFromIndex:(slash.location + 1)];
6621 }
6622
6623 Database *database([Database sharedInstance]);
6624
6625 if ([command isEqualToString:@"package-icon"]) {
6626 if (path == nil)
6627 goto fail;
dec6029f 6628 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
807ae6d7
JF
6629 Package *package([database packageWithName:path]);
6630 if (package == nil)
6631 goto fail;
dec6029f 6632 UIImage *icon([package icon]);
9fe5e5f8 6633 [self _returnPNGWithImage:icon forRequest:request];
16f2786b
JF
6634 } else if ([command isEqualToString:@"source-icon"]) {
6635 if (path == nil)
6636 goto fail;
6637 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6638 NSString *source(Simplify(path));
16f2786b
JF
6639 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6640 if (icon == nil)
6641 icon = [UIImage applicationImageNamed:@"unknown.png"];
9fe5e5f8
JF
6642 [self _returnPNGWithImage:icon forRequest:request];
6643 } else if ([command isEqualToString:@"uikit-image"]) {
6644 if (path == nil)
6645 goto fail;
6646 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6647 UIImage *icon(_UIImageWithName(path));
6648 [self _returnPNGWithImage:icon forRequest:request];
dec6029f
JF
6649 } else if ([command isEqualToString:@"section-icon"]) {
6650 if (path == nil)
6651 goto fail;
6652 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6653 NSString *section(Simplify(path));
dec6029f
JF
6654 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6655 if (icon == nil)
6656 icon = [UIImage applicationImageNamed:@"unknown.png"];
9fe5e5f8 6657 [self _returnPNGWithImage:icon forRequest:request];
807ae6d7
JF
6658 } else fail: {
6659 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6660 }
6661}
6662
6663- (void) stopLoading {
6664}
6665
6666@end
6667/* }}} */
6668
adb61bda 6669/* Sections Controller {{{ */
c21004b9
JF
6670@interface SectionsController : CYViewController <
6671 UITableViewDataSource,
6672 UITableViewDelegate
6673> {
807ae6d7
JF
6674 _transient Database *database_;
6675 NSMutableArray *sections_;
6676 NSMutableArray *filtered_;
46aa9775 6677 UITableView *list_;
807ae6d7
JF
6678 UIView *accessory_;
6679 BOOL editing_;
6680}
6681
b5e7eebb 6682- (id) initWithDatabase:(Database *)database;
807ae6d7
JF
6683- (void) reloadData;
6684- (void) resetView;
6685
c21004b9
JF
6686- (void) editButtonClicked;
6687
807ae6d7
JF
6688@end
6689
adb61bda 6690@implementation SectionsController
807ae6d7
JF
6691
6692- (void) dealloc {
6693 [list_ setDataSource:nil];
6694 [list_ setDelegate:nil];
6695
6696 [sections_ release];
6697 [filtered_ release];
807ae6d7
JF
6698 [list_ release];
6699 [accessory_ release];
6700 [super dealloc];
6701}
6702
b5e7eebb
GP
6703- (void) viewDidAppear:(BOOL)animated {
6704 [super viewDidAppear:animated];
6705 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6706}
6707
46aa9775
GP
6708- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6709 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6710 return section;
807ae6d7
JF
6711}
6712
eb30da80 6713- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
46aa9775 6714 return editing_ ? [sections_ count] : [filtered_ count] + 1;
807ae6d7
JF
6715}
6716
21ea11a4
GP
6717/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6718 return 45.0f;
6719}*/
807ae6d7 6720
46aa9775 6721- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
GP
6722 static NSString *reuseIdentifier = @"SectionCell";
6723
6724 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
36fbb2aa
JF
6725 if (cell == nil)
6726 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6727
46aa9775 6728 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
807ae6d7 6729
46aa9775 6730 return cell;
807ae6d7
JF
6731}
6732
46aa9775 6733- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
0abb648c
JF
6734 if (editing_)
6735 return;
477de105 6736
0abb648c 6737 Section *section = [self sectionAtIndexPath:indexPath];
46aa9775 6738 NSString *name = [section name];
807ae6d7
JF
6739 NSString *title;
6740
46aa9775 6741 if ([indexPath row] == 0) {
807ae6d7
JF
6742 section = nil;
6743 name = nil;
43f3d7f6 6744 title = UCLocalize("ALL_PACKAGES");
807ae6d7 6745 } else {
28ce8704
JF
6746 if (name != nil) {
6747 name = [NSString stringWithString:name];
f79a4512 6748 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
28ce8704 6749 } else {
807ae6d7 6750 name = @"";
43f3d7f6 6751 title = UCLocalize("NO_SECTION");
807ae6d7
JF
6752 }
6753 }
6754
adb61bda 6755 FilteredPackageController *table = [[[FilteredPackageController alloc]
b5e7eebb 6756 initWithDatabase:database_
807ae6d7 6757 title:title
670a0494 6758 filter:@selector(isVisibleInSection:)
807ae6d7
JF
6759 with:name
6760 ] autorelease];
6761
6762 [table setDelegate:delegate_];
6763
b5e7eebb 6764 [[self navigationController] pushViewController:table animated:YES];
807ae6d7
JF
6765}
6766
eb30da80 6767- (NSString *) title { return UCLocalize("SECTIONS"); }
b5e7eebb
GP
6768
6769- (id) initWithDatabase:(Database *)database {
6770 if ((self = [super init]) != nil) {
807ae6d7
JF
6771 database_ = database;
6772
b5e7eebb
GP
6773 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6774
807ae6d7
JF
6775 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6776 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6777
b5e7eebb 6778 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
04fe1349 6779 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 6780 [list_ setRowHeight:45.0f];
b5e7eebb 6781 [[self view] addSubview:list_];
807ae6d7 6782
46aa9775 6783 [list_ setDataSource:self];
b5e7eebb 6784 [list_ setDelegate:self];
807ae6d7
JF
6785
6786 [self reloadData];
807ae6d7
JF
6787 } return self;
6788}
6789
6790- (void) reloadData {
6791 NSArray *packages = [database_ packages];
6792
6793 [sections_ removeAllObjects];
6794 [filtered_ removeAllObjects];
6795
f79a4512 6796 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
807ae6d7
JF
6797
6798 _trace();
c4dcf2c2 6799 for (Package *package in packages) {
807ae6d7 6800 NSString *name([package section]);
f79a4512 6801 NSString *key(name == nil ? @"" : name);
807ae6d7 6802
f79a4512
JF
6803 Section *section;
6804
6805 _profile(SectionsView$reloadData$Section)
6806 section = [sections objectForKey:key];
807ae6d7 6807 if (section == nil) {
f79a4512 6808 _profile(SectionsView$reloadData$Section$Allocate)
9fcbca29 6809 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
f79a4512
JF
6810 [sections setObject:section forKey:key];
6811 _end
807ae6d7 6812 }
f79a4512
JF
6813 _end
6814
6815 [section addToCount];
6d9712c4 6816
f79a4512 6817 _profile(SectionsView$reloadData$Filter)
670a0494 6818 if (![package valid] || ![package visible])
f79a4512
JF
6819 continue;
6820 _end
6821
6822 [section addToRow];
b4d89997 6823 }
807ae6d7 6824 _trace();
dc5812ec 6825
6d9712c4 6826 [sections_ addObjectsFromArray:[sections allValues]];
6d9712c4 6827
677b8415 6828 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
dc5812ec 6829
f79a4512
JF
6830 for (Section *section in sections_) {
6831 size_t count([section row]);
677b8415 6832 if (count == 0)
f79a4512 6833 continue;
dc5812ec 6834
9fcbca29 6835 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
f79a4512
JF
6836 [section setCount:count];
6837 [filtered_ addObject:section];
b4d89997 6838 }
2367a917 6839
dd9de556
JF
6840 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6841 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
b5e7eebb
GP
6842 style:UIBarButtonItemStylePlain
6843 target:self
6844 action:@selector(editButtonClicked)
dd9de556 6845 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
b5e7eebb 6846
b4d89997 6847 [list_ reloadData];
807ae6d7 6848 _trace();
36bb2ca2 6849}
2367a917 6850
6d9712c4
JF
6851- (void) resetView {
6852 if (editing_)
b5e7eebb 6853 [self editButtonClicked];
36bb2ca2 6854}
2367a917 6855
b5e7eebb 6856- (void) editButtonClicked {
6d9712c4
JF
6857 if ((editing_ = !editing_))
6858 [list_ reloadData];
807ae6d7 6859 else
6d9712c4 6860 [delegate_ updateData];
bc11cf5b 6861
b5e7eebb
GP
6862 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6863 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6864 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
baf80942
JF
6865}
6866
a54b1c10
JF
6867- (UIView *) accessoryView {
6868 return accessory_;
6869}
6870
dc5812ec 6871@end
2367a917 6872/* }}} */
adb61bda 6873/* Changes Controller {{{ */
c21004b9
JF
6874@interface ChangesController : CYViewController <
6875 UITableViewDataSource,
6876 UITableViewDelegate
6877> {
36bb2ca2 6878 _transient Database *database_;
6da1297d 6879 CFMutableArrayRef packages_;
dc5812ec 6880 NSMutableArray *sections_;
327624b6 6881 UITableView *list_;
36bb2ca2 6882 unsigned upgrades_;
904e4273 6883 BOOL hasSentFirstLoad_;
dc5812ec
JF
6884}
6885
b5e7eebb 6886- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
36bb2ca2 6887- (void) reloadData;
dc5812ec 6888
dc5812ec
JF
6889@end
6890
adb61bda 6891@implementation ChangesController
b4d89997
JF
6892
6893- (void) dealloc {
327624b6 6894 [list_ setDelegate:nil];
36bb2ca2
JF
6895 [list_ setDataSource:nil];
6896
6da1297d
JF
6897 CFRelease(packages_);
6898
b4d89997 6899 [sections_ release];
36bb2ca2 6900 [list_ release];
b4d89997
JF
6901 [super dealloc];
6902}
dc5812ec 6903
b5e7eebb
GP
6904- (void) viewDidAppear:(BOOL)animated {
6905 [super viewDidAppear:animated];
904e4273
RP
6906 if (!hasSentFirstLoad_) {
6907 hasSentFirstLoad_ = YES;
6908 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6909 } else {
6910 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6911 }
b5e7eebb
GP
6912}
6913
327624b6
JF
6914- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6915 NSInteger count([sections_ count]);
6916 return count == 0 ? 1 : count;
dc5812ec
JF
6917}
6918
327624b6
JF
6919- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6920 if ([sections_ count] == 0)
6921 return nil;
dc5812ec
JF
6922 return [[sections_ objectAtIndex:section] name];
6923}
6924
327624b6
JF
6925- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6926 if ([sections_ count] == 0)
6927 return 0;
6928 return [[sections_ objectAtIndex:section] count];
dc5812ec
JF
6929}
6930
6da1297d
JF
6931- (Package *) packageAtIndex:(NSUInteger)index {
6932 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6933}
6934
327624b6
JF
6935- (Package *) packageAtIndexPath:(NSIndexPath *)path {
6936 Section *section([sections_ objectAtIndex:[path section]]);
6937 NSInteger row([path row]);
6da1297d 6938 return [self packageAtIndex:([section row] + row)];
dc5812ec
JF
6939}
6940
327624b6 6941- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
c21004b9 6942 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
327624b6
JF
6943 if (cell == nil)
6944 cell = [[[PackageCell alloc] init] autorelease];
6945 [cell setPackage:[self packageAtIndexPath:path]];
6946 return cell;
dc5812ec
JF
6947}
6948
21ea11a4 6949/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
327624b6 6950 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
21ea11a4 6951}*/
dc5812ec 6952
327624b6
JF
6953- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6954 Package *package([self packageAtIndexPath:path]);
adb61bda 6955 PackageController *view([delegate_ packageController]);
36bb2ca2
JF
6956 [view setDelegate:delegate_];
6957 [view setPackage:package];
b5e7eebb 6958 [[self navigationController] pushViewController:view animated:YES];
327624b6 6959 return path;
dc5812ec
JF
6960}
6961
b5e7eebb 6962- (void) refreshButtonClicked {
c21004b9 6963 [delegate_ beginUpdate];
45e21ffa 6964 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
9a7b04c5
JF
6965}
6966
b5e7eebb 6967- (void) upgradeButtonClicked {
36bb2ca2 6968 [delegate_ distUpgrade];
dc5812ec
JF
6969}
6970
eb30da80 6971- (NSString *) title { return UCLocalize("CHANGES"); }
b5e7eebb
GP
6972
6973- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
6974 if ((self = [super init]) != nil) {
36bb2ca2 6975 database_ = database;
b5e7eebb 6976 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
dc5812ec 6977
6da1297d
JF
6978 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6979
b4d89997 6980 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 6981
b5e7eebb 6982 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 6983 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 6984 [list_ setRowHeight:73.0f];
b5e7eebb 6985 [[self view] addSubview:list_];
36bb2ca2 6986
b4d89997 6987 [list_ setDataSource:self];
327624b6 6988 [list_ setDelegate:self];
dc5812ec 6989
77801ff1 6990 delegate_ = delegate;
dc5812ec
JF
6991 } return self;
6992}
6993
77801ff1 6994- (void) _reloadPackages:(NSArray *)packages {
807ae6d7 6995 _trace();
c4dcf2c2 6996 for (Package *package in packages)
e4f3d6e9 6997 if ([package upgradableAndEssential:YES] || [package visible])
6da1297d 6998 CFArrayAppendValue(packages_, package);
2367a917 6999
807ae6d7 7000 _trace();
6da1297d 7001 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
807ae6d7 7002 _trace();
77801ff1
JF
7003}
7004
7005- (void) reloadData {
7006 NSArray *packages = [database_ packages];
7007
6da1297d
JF
7008 CFArrayRemoveAllValues(packages_);
7009
77801ff1
JF
7010 [sections_ removeAllObjects];
7011
376c37e8 7012#if 1
77801ff1 7013 UIProgressHUD *hud([delegate_ addProgressHUD]);
376c37e8 7014 [hud setText:UCLocalize("LOADING")];
534e31fc 7015 //NSLog(@"HUD:%@::%@", delegate_, hud);
77801ff1
JF
7016 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7017 [delegate_ removeProgressHUD:hud];
8e4e80cb
JF
7018#else
7019 [self _reloadPackages:packages];
7020#endif
dc5812ec 7021
43f3d7f6
JF
7022 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7023 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
dc5812ec 7024 Section *section = nil;
807ae6d7 7025 NSDate *last = nil;
b4d89997 7026
36bb2ca2
JF
7027 upgrades_ = 0;
7028 bool unseens = false;
7029
677b8415 7030 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
36bb2ca2 7031
6da1297d
JF
7032 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7033 Package *package = [self packageAtIndex:offset];
dc5812ec 7034
677b8415 7035 BOOL uae = [package upgradableAndEssential:YES];
f79a4512
JF
7036
7037 if (!uae) {
36bb2ca2 7038 unseens = true;
f79a4512 7039 NSDate *seen;
dc5812ec 7040
adb61bda 7041 _profile(ChangesController$reloadData$Remember)
f79a4512
JF
7042 seen = [package seen];
7043 _end
7044
677b8415 7045 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
807ae6d7 7046 last = seen;
723a0072 7047
dc63e78f
JF
7048 NSString *name;
7049 if (seen == nil)
43f3d7f6 7050 name = UCLocalize("UNKNOWN");
dc63e78f 7051 else {
677b8415 7052 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
dc63e78f
JF
7053 [name autorelease];
7054 }
7055
adb61bda 7056 _profile(ChangesController$reloadData$Allocate)
43f3d7f6 7057 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
9fcbca29 7058 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
f79a4512
JF
7059 [sections_ addObject:section];
7060 _end
b4d89997
JF
7061 }
7062
36bb2ca2 7063 [section addToCount];
807ae6d7
JF
7064 } else if ([package ignored])
7065 [ignored addToCount];
7066 else {
7067 ++upgrades_;
7068 [upgradable addToCount];
b4d89997 7069 }
dc5812ec 7070 }
807ae6d7 7071 _trace();
dc5812ec 7072
36bb2ca2 7073 CFRelease(formatter);
b4d89997 7074
36bb2ca2
JF
7075 if (unseens) {
7076 Section *last = [sections_ lastObject];
7077 size_t count = [last count];
6da1297d 7078 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
36bb2ca2
JF
7079 [sections_ removeLastObject];
7080 }
dc5812ec 7081
807ae6d7
JF
7082 if ([ignored count] != 0)
7083 [sections_ insertObject:ignored atIndex:0];
36bb2ca2
JF
7084 if (upgrades_ != 0)
7085 [sections_ insertObject:upgradable atIndex:0];
c25a610d 7086
36bb2ca2 7087 [list_ reloadData];
3178d79b 7088
dd9de556
JF
7089 if (upgrades_ > 0)
7090 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7091 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7092 style:UIBarButtonItemStylePlain
7093 target:self
7094 action:@selector(upgradeButtonClicked)
7095 ] autorelease]];
b5e7eebb 7096
dd9de556
JF
7097 if (![delegate_ updating])
7098 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7099 initWithTitle:UCLocalize("REFRESH")
7100 style:UIBarButtonItemStylePlain
7101 target:self
7102 action:@selector(refreshButtonClicked)
7103 ] autorelease]];
8fe19fc1
JF
7104}
7105
3178d79b
JF
7106@end
7107/* }}} */
adb61bda 7108/* Search Controller {{{ */
c21004b9
JF
7109@interface SearchController : FilteredPackageController <
7110 UISearchBarDelegate
7111> {
7112 UISearchBar *search_;
36bb2ca2 7113}
b4d89997 7114
b5e7eebb 7115- (id) initWithDatabase:(Database *)database;
36bb2ca2 7116- (void) reloadData;
b4d89997 7117
3178d79b
JF
7118@end
7119
adb61bda 7120@implementation SearchController
3178d79b 7121
b4d89997 7122- (void) dealloc {
b5e7eebb 7123 [search_ release];
36bb2ca2 7124 [super dealloc];
b4d89997
JF
7125}
7126
eb30da80 7127- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
b5e7eebb
GP
7128 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7129 [search_ resignFirstResponder];
01d93940 7130 [self reloadData];
36bb2ca2 7131}
b4d89997 7132
eb30da80 7133- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
b5e7eebb 7134 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
01d93940 7135 [self reloadData];
36bb2ca2 7136}
b4d89997 7137
eb30da80 7138- (NSString *) title { return nil; }
ab398adf 7139
b5e7eebb 7140- (id) initWithDatabase:(Database *)database {
dcb47737
RP
7141 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7142}
7143
7144- (void)viewDidAppear:(BOOL)animated {
bc11cf5b
JF
7145 [super viewDidAppear:animated];
7146 if (!search_) {
c21004b9 7147 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
dcb47737 7148 [search_ layoutSubviews];
b5e7eebb 7149 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
dcb47737
RP
7150 UITextField *textField = [search_ searchField];
7151 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
b5e7eebb 7152 [search_ setDelegate:self];
dcb47737
RP
7153 [textField setEnablesReturnKeyAutomatically:NO];
7154 [[self navigationItem] setTitleView:textField];
7155 }
3178d79b
JF
7156}
7157
807ae6d7
JF
7158- (void) _reloadData {
7159}
b4d89997 7160
807ae6d7 7161- (void) reloadData {
adb61bda 7162 _profile(SearchController$reloadData)
b5e7eebb 7163 [packages_ reloadData];
808c6eb6
JF
7164 _end
7165 PrintTimes();
b5e7eebb 7166 [packages_ resetCursor];
807ae6d7 7167}
8fe19fc1 7168
8e05f686
RP
7169- (void) didSelectPackage:(Package *)package {
7170 [search_ resignFirstResponder];
7171 [super didSelectPackage:package];
7172}
7173
807ae6d7
JF
7174@end
7175/* }}} */
adb61bda 7176/* Settings Controller {{{ */
c21004b9
JF
7177@interface SettingsController : CYViewController <
7178 UITableViewDataSource,
7179 UITableViewDelegate
7180> {
807ae6d7
JF
7181 _transient Database *database_;
7182 NSString *name_;
7183 Package *package_;
3b7fcecd 7184 UITableView *table_;
68046ccc
JF
7185 UISwitch *subscribedSwitch_;
7186 UISwitch *ignoredSwitch_;
3b7fcecd
GP
7187 UITableViewCell *subscribedCell_;
7188 UITableViewCell *ignoredCell_;
807ae6d7 7189}
b4d89997 7190
b5e7eebb 7191- (id) initWithDatabase:(Database *)database package:(NSString *)package;
b4d89997 7192
807ae6d7 7193@end
b4d89997 7194
adb61bda 7195@implementation SettingsController
b4d89997 7196
807ae6d7 7197- (void) dealloc {
807ae6d7
JF
7198 [name_ release];
7199 if (package_ != nil)
7200 [package_ release];
7201 [table_ release];
7202 [subscribedSwitch_ release];
7203 [ignoredSwitch_ release];
7204 [subscribedCell_ release];
7205 [ignoredCell_ release];
bc11cf5b 7206
807ae6d7
JF
7207 [super dealloc];
7208}
b4d89997 7209
3b7fcecd 7210- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
807ae6d7
JF
7211 if (package_ == nil)
7212 return 0;
b4d89997 7213
3b7fcecd 7214 return 1;
3178d79b
JF
7215}
7216
3b7fcecd 7217- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
807ae6d7
JF
7218 if (package_ == nil)
7219 return 0;
dc5812ec 7220
3b7fcecd
GP
7221 return 1;
7222}
baf80942 7223
3b7fcecd
GP
7224- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7225 return UCLocalize("SHOW_ALL_CHANGES_EX");
36bb2ca2 7226}
b4d89997 7227
3b7fcecd 7228- (void) onSomething:(BOOL)value withKey:(NSString *)key {
807ae6d7
JF
7229 if (package_ == nil)
7230 return;
b4d89997 7231
807ae6d7 7232 NSMutableDictionary *metadata([package_ metadata]);
baf80942 7233
807ae6d7
JF
7234 BOOL before;
7235 if (NSNumber *number = [metadata objectForKey:key])
7236 before = [number boolValue];
7237 else
7238 before = NO;
36bb2ca2 7239
807ae6d7
JF
7240 if (value != before) {
7241 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7242 Changed_ = true;
807ae6d7
JF
7243 [delegate_ updateData];
7244 }
baf80942
JF
7245}
7246
3b7fcecd
GP
7247- (void) onSubscribed:(id)control {
7248 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
36bb2ca2 7249}
b4d89997 7250
3b7fcecd
GP
7251- (void) onIgnored:(id)control {
7252 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
8fe19fc1
JF
7253}
7254
3b7fcecd 7255- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
807ae6d7
JF
7256 if (package_ == nil)
7257 return nil;
770f2a8e 7258
3b7fcecd
GP
7259 switch ([indexPath row]) {
7260 case 0: return subscribedCell_;
7261 case 1: return ignoredCell_;
bc11cf5b 7262
670a0494 7263 _nodefault
807ae6d7 7264 }
770f2a8e 7265
807ae6d7 7266 return nil;
770f2a8e
JF
7267}
7268
eb30da80 7269- (NSString *) title { return UCLocalize("SETTINGS"); }
b5e7eebb
GP
7270
7271- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7272 if ((self = [super init])) {
807ae6d7
JF
7273 database_ = database;
7274 name_ = [package retain];
770f2a8e 7275
b5e7eebb
GP
7276 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7277
3b7fcecd
GP
7278 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7279 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b5e7eebb 7280 [[self view] addSubview:table_];
770f2a8e 7281
68046ccc 7282 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
3b7fcecd
GP
7283 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7284 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
770f2a8e 7285
68046ccc 7286 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
3b7fcecd
GP
7287 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7288 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
770f2a8e 7289
3b7fcecd
GP
7290 subscribedCell_ = [[UITableViewCell alloc] init];
7291 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7292 [subscribedCell_ setAccessoryView:subscribedSwitch_];
33a97e4f 7293 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
770f2a8e 7294
3b7fcecd
GP
7295 ignoredCell_ = [[UITableViewCell alloc] init];
7296 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7297 [ignoredCell_ setAccessoryView:ignoredSwitch_];
33a97e4f 7298 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
770f2a8e 7299
807ae6d7 7300 [table_ setDataSource:self];
3b7fcecd 7301 [table_ setDelegate:self];
807ae6d7
JF
7302 [self reloadData];
7303 } return self;
7304}
770f2a8e 7305
807ae6d7
JF
7306- (void) reloadData {
7307 if (package_ != nil)
7308 [package_ autorelease];
7309 package_ = [database_ packageWithName:name_];
7310 if (package_ != nil) {
7311 [package_ retain];
3b7fcecd
GP
7312 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7313 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
770f2a8e 7314 }
807ae6d7
JF
7315
7316 [table_ reloadData];
770f2a8e
JF
7317}
7318
770f2a8e 7319@end
bfc87a4d 7320/* }}} */
adb61bda
GP
7321/* Signature Controller {{{ */
7322@interface SignatureController : CYBrowserController {
770f2a8e
JF
7323 _transient Database *database_;
7324 NSString *package_;
7325}
7326
b5e7eebb 7327- (id) initWithDatabase:(Database *)database package:(NSString *)package;
770f2a8e
JF
7328
7329@end
7330
adb61bda 7331@implementation SignatureController
770f2a8e
JF
7332
7333- (void) dealloc {
7334 [package_ release];
7335 [super dealloc];
7336}
7337
2634b249 7338- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
770f2a8e 7339 // XXX: dude!
2634b249 7340 [super webView:view didClearWindowObject:window forFrame:frame];
770f2a8e
JF
7341}
7342
b5e7eebb
GP
7343- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7344 if ((self = [super init]) != nil) {
770f2a8e
JF
7345 database_ = database;
7346 package_ = [package retain];
7347 [self reloadData];
7348 } return self;
7349}
7350
7351- (void) reloadData {
7352 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7353}
7354
21c6da4b
GP
7355@end
7356/* }}} */
f3e11d24 7357
21c6da4b 7358/* Role Controller {{{ */
c21004b9
JF
7359@interface RoleController : CYViewController <
7360 UITableViewDataSource,
7361 UITableViewDelegate
7362> {
21c6da4b 7363 _transient Database *database_;
3931b718
JF
7364 // XXX: ok, "roledelegate_"?...
7365 _transient id roledelegate_;
21c6da4b
GP
7366 UITableView *table_;
7367 UISegmentedControl *segment_;
7368 UIView *container_;
7369}
c21004b9
JF
7370
7371- (void) showDoneButton;
7372- (void) resizeSegmentedControl;
7373
21c6da4b
GP
7374@end
7375
7376@implementation RoleController
7377- (void) dealloc {
7378 [table_ release];
7379 [segment_ release];
7380 [container_ release];
bc11cf5b 7381
21c6da4b
GP
7382 [super dealloc];
7383}
7384
7385- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7386 if ((self = [super init])) {
7387 database_ = database;
7388 roledelegate_ = delegate;
bc11cf5b 7389
21c6da4b 7390 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
bc11cf5b 7391
21c6da4b 7392 NSArray *items = [NSArray arrayWithObjects:
bc11cf5b 7393 UCLocalize("USER"),
21c6da4b
GP
7394 UCLocalize("HACKER"),
7395 UCLocalize("DEVELOPER"),
7396 nil];
7397 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7398 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7399 [container_ addSubview:segment_];
bc11cf5b 7400
21c6da4b
GP
7401 int index = -1;
7402 if ([Role_ isEqualToString:@"User"]) index = 0;
7403 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7404 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7405 if (index != -1) {
7406 [segment_ setSelectedSegmentIndex:index];
7407 [self showDoneButton];
7408 }
bc11cf5b 7409
21c6da4b 7410 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
e62f29c6 7411 [self resizeSegmentedControl];
bc11cf5b 7412
21c6da4b
GP
7413 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7414 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7415 [table_ setDelegate:self];
7416 [table_ setDataSource:self];
7417 [[self view] addSubview:table_];
7418 [table_ reloadData];
7419 } return self;
7420}
7421
e62f29c6
GP
7422- (void) resizeSegmentedControl {
7423 CGFloat width = [[self view] frame].size.width;
7424 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7425}
7426
2bdd73bd
GP
7427- (void) viewWillAppear:(BOOL)animated {
7428 [super viewWillAppear:animated];
bc11cf5b 7429
e62f29c6
GP
7430 [self resizeSegmentedControl];
7431}
7432
7433- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7434 [self resizeSegmentedControl];
7435}
7436
7437- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7438 [self resizeSegmentedControl];
2bdd73bd
GP
7439}
7440
21c6da4b 7441- (void) save {
fed0d010 7442 NSString *role(nil);
bc11cf5b 7443
21c6da4b 7444 switch ([segment_ selectedSegmentIndex]) {
124c6201
GP
7445 case 0: role = @"User"; break;
7446 case 1: role = @"Hacker"; break;
7447 case 2: role = @"Developer"; break;
21c6da4b
GP
7448
7449 _nodefault
7450 }
7451
124c6201 7452 if (![role isEqualToString:Role_]) {
fed0d010 7453 bool rolling(Role_ == nil);
124c6201 7454 Role_ = role;
bc11cf5b 7455
124c6201
GP
7456 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7457 Role_, @"Role",
7458 nil];
21c6da4b 7459
124c6201 7460 [Metadata_ setObject:Settings_ forKey:@"Settings"];
21c6da4b 7461
124c6201 7462 Changed_ = true;
bc11cf5b 7463
fed0d010
JF
7464 if (rolling)
7465 [roledelegate_ loadData];
7466 else
7467 [roledelegate_ updateData];
124c6201 7468 }
21c6da4b
GP
7469}
7470
7471- (void) segmentChanged:(UISegmentedControl *)control {
7472 [self showDoneButton];
7473}
7474
8576ab50 7475- (void) saveAndClose {
21c6da4b 7476 [self save];
8576ab50
GP
7477
7478 [[self navigationItem] setRightBarButtonItem:nil];
21c6da4b
GP
7479 [[self navigationController] dismissModalViewControllerAnimated:YES];
7480}
7481
8576ab50
GP
7482- (void) doneButtonClicked {
7483 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7484 [spinner startAnimating];
7485 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7486 [[self navigationItem] setRightBarButtonItem:spinItem];
7487
7488 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7489}
7490
21c6da4b 7491- (void) showDoneButton {
dd9de556 7492 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
21c6da4b
GP
7493 initWithTitle:UCLocalize("DONE")
7494 style:UIBarButtonItemStyleDone
7495 target:self
7496 action:@selector(doneButtonClicked)
dd9de556 7497 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
21c6da4b
GP
7498}
7499
7500- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
e62f29c6
GP
7501 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7502 return 6;
21c6da4b
GP
7503}
7504
7505- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7506 return 0; // :(
7507}
7508
7509- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7510 return nil; // This method is required by the protocol.
7511}
7512
7513- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
bc11cf5b 7514 if (section == 1)
21c6da4b 7515 return UCLocalize("ROLE_EX");
bc11cf5b 7516 if (section == 4)
21c6da4b
GP
7517 return [NSString stringWithFormat:
7518 @"%@: %@\n%@: %@\n%@: %@",
bc11cf5b
JF
7519 UCLocalize("USER"), UCLocalize("USER_EX"),
7520 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
21c6da4b
GP
7521 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7522 ];
7523 else return nil;
7524}
7525
7526- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
36fbb2aa 7527 return section == 3 ? 44.0f : 0;
21c6da4b
GP
7528}
7529
7530- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
36fbb2aa 7531 return section == 3 ? container_ : nil;
21c6da4b
GP
7532}
7533
f3e11d24
GP
7534@end
7535/* }}} */
7536/* Stash Controller {{{ */
7537@interface CYStashController : CYViewController {
3931b718
JF
7538 // XXX: just delete these things
7539 _transient UIActivityIndicatorView *spinner_;
7540 _transient UILabel *status_;
7541 _transient UILabel *caption_;
f3e11d24
GP
7542}
7543@end
7544
7545@implementation CYStashController
7546- (id) init {
7547 if ((self = [super init])) {
e61a973c 7548 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
f3e11d24 7549
dd9de556 7550 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
e61a973c 7551 CGRect spinrect = [spinner_ frame];
f3e11d24
GP
7552 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7553 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7554 [spinner_ setFrame:spinrect];
7555 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
e61a973c 7556 [[self view] addSubview:spinner_];
e61a973c 7557 [spinner_ startAnimating];
f3e11d24
GP
7558
7559 CGRect captrect;
7560 captrect.size.width = [[self view] frame].size.width;
7561 captrect.size.height = 40.0f;
7562 captrect.origin.x = 0;
7563 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
dd9de556 7564 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
f3e11d24 7565 [caption_ setText:@"Initializing Filesystem"];
851f4a99 7566 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
f3e11d24
GP
7567 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7568 [caption_ setTextColor:[UIColor whiteColor]];
7569 [caption_ setBackgroundColor:[UIColor clearColor]];
7570 [caption_ setShadowColor:[UIColor blackColor]];
7571 [caption_ setTextAlignment:UITextAlignmentCenter];
7572 [[self view] addSubview:caption_];
f3e11d24
GP
7573
7574 CGRect statusrect;
7575 statusrect.size.width = [[self view] frame].size.width;
7576 statusrect.size.height = 30.0f;
7577 statusrect.origin.x = 0;
7578 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
dd9de556 7579 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
851f4a99 7580 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
f3e11d24
GP
7581 [status_ setText:@"(Cydia will exit when complete.)"];
7582 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7583 [status_ setTextColor:[UIColor whiteColor]];
7584 [status_ setBackgroundColor:[UIColor clearColor]];
7585 [status_ setShadowColor:[UIColor blackColor]];
7586 [status_ setTextAlignment:UITextAlignmentCenter];
7587 [[self view] addSubview:status_];
f3e11d24
GP
7588 } return self;
7589}
7590
7591- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7592 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7593}
770f2a8e 7594@end
807ae6d7 7595/* }}} */
770f2a8e 7596
8c02abc8
GP
7597/* Cydia Container {{{ */
7598@interface CYContainer : UIViewController <ProgressDelegate> {
7599 _transient Database *database_;
7600 RefreshBar *refreshbar_;
7601
7602 bool dropped_;
7603 bool updating_;
3931b718
JF
7604 // XXX: ok, "updatedelegate_"?...
7605 _transient NSObject<CydiaDelegate> *updatedelegate_;
7606 // XXX: can't we query for this variable when we need it?
7607 _transient UITabBarController *root_;
8c02abc8
GP
7608}
7609
c21004b9
JF
7610- (void) setTabBarController:(UITabBarController *)controller;
7611
7612- (void) dropBar:(BOOL)animated;
7613- (void) beginUpdate;
7614- (void) raiseBar:(BOOL)animated;
632f629b 7615- (BOOL) updating;
c21004b9 7616
8c02abc8
GP
7617@end
7618
7619@implementation CYContainer
7620
632f629b
GP
7621- (BOOL) _reallyWantsFullScreenLayout {
7622 return YES;
7623}
7624
9cb0bff2
GP
7625// NOTE: UIWindow only sends the top controller these messages,
7626// So we have to forward them on.
7627
7628- (void) viewDidAppear:(BOOL)animated {
7629 [super viewDidAppear:animated];
7630 [root_ viewDidAppear:animated];
7631}
7632
7633- (void) viewWillAppear:(BOOL)animated {
7634 [super viewWillAppear:animated];
7635 [root_ viewWillAppear:animated];
7636}
7637
7638- (void) viewDidDisappear:(BOOL)animated {
7639 [super viewDidDisappear:animated];
7640 [root_ viewDidDisappear:animated];
7641}
7642
7643- (void) viewWillDisappear:(BOOL)animated {
7644 [super viewWillDisappear:animated];
7645 [root_ viewWillDisappear:animated];
7646}
7647
8c02abc8 7648- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
fc53bb07 7649 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
8c02abc8
GP
7650}
7651
c21004b9 7652- (void) setTabBarController:(UITabBarController *)controller {
8c02abc8
GP
7653 root_ = controller;
7654 [[self view] addSubview:[root_ view]];
7655}
7656
7657- (void) setUpdate:(NSDate *)date {
7658 [self beginUpdate];
7659}
7660
7661- (void) beginUpdate {
7662 [self dropBar:YES];
7663 [refreshbar_ start];
bc11cf5b 7664
8c02abc8 7665 updating_ = true;
bc11cf5b 7666
8c02abc8
GP
7667 [NSThread
7668 detachNewThreadSelector:@selector(performUpdate)
7669 toTarget:self
7670 withObject:nil
7671 ];
7672}
7673
7674- (void) performUpdate { _pooled
7675 Status status;
7676 status.setDelegate(self);
7677 [database_ updateWithStatus:status];
7678
7679 [self
7680 performSelectorOnMainThread:@selector(completeUpdate)
7681 withObject:nil
7682 waitUntilDone:NO
7683 ];
7684}
7685
7686- (void) completeUpdate {
36fbb2aa
JF
7687 if (!updating_)
7688 return;
8c02abc8 7689 updating_ = false;
bc11cf5b 7690
8c02abc8
GP
7691 [self raiseBar:YES];
7692 [refreshbar_ stop];
7693 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7694}
7695
7696- (void) cancelUpdate {
45e21ffa
GP
7697 updating_ = false;
7698 [self raiseBar:YES];
7699 [refreshbar_ stop];
7700 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
8c02abc8
GP
7701}
7702
7703- (void) cancelPressed {
7704 [self cancelUpdate];
7705}
7706
7707- (BOOL) updating {
7708 return updating_;
7709}
7710
7711- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7712 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7713}
7714
7715- (void) startProgress {
7716}
7717
7718- (void) setProgressTitle:(NSString *)title {
7719 [self
7720 performSelectorOnMainThread:@selector(_setProgressTitle:)
7721 withObject:title
7722 waitUntilDone:YES
7723 ];
7724}
7725
7726- (bool) isCancelling:(size_t)received {
7727 return !updating_;
7728}
7729
7730- (void) setProgressPercent:(float)percent {
7731 [self
7732 performSelectorOnMainThread:@selector(_setProgressPercent:)
7733 withObject:[NSNumber numberWithFloat:percent]
7734 waitUntilDone:YES
7735 ];
7736}
7737
7738- (void) addProgressOutput:(NSString *)output {
7739 [self
7740 performSelectorOnMainThread:@selector(_addProgressOutput:)
7741 withObject:output
7742 waitUntilDone:YES
7743 ];
7744}
7745
7746- (void) _setProgressTitle:(NSString *)title {
7747 [refreshbar_ setPrompt:title];
7748}
7749
7750- (void) _setProgressPercent:(NSNumber *)percent {
7751 [refreshbar_ setProgress:[percent floatValue]];
7752}
7753
7754- (void) _addProgressOutput:(NSString *)output {
7755}
7756
7757- (void) setUpdateDelegate:(id)delegate {
7758 updatedelegate_ = delegate;
7759}
7760
e454f9c3
GP
7761- (CGFloat) statusBarHeight {
7762 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7763 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7764 } else {
7765 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7766 }
7767}
7768
8c02abc8 7769- (void) dropBar:(BOOL)animated {
36fbb2aa
JF
7770 if (dropped_)
7771 return;
8c02abc8
GP
7772 dropped_ = true;
7773
7774 [[self view] addSubview:refreshbar_];
7775
e454f9c3 7776 CGFloat sboffset = [self statusBarHeight];
632f629b 7777
6067f1b8 7778 CGRect barframe = [refreshbar_ frame];
632f629b
GP
7779 barframe.origin.y = sboffset;
7780 [refreshbar_ setFrame:barframe];
7781
36fbb2aa
JF
7782 if (animated)
7783 [UIView beginAnimations:nil context:NULL];
8c02abc8 7784 CGRect viewframe = [[root_ view] frame];
632f629b
GP
7785 viewframe.origin.y += barframe.size.height + sboffset;
7786 viewframe.size.height -= barframe.size.height + sboffset;
8c02abc8 7787 [[root_ view] setFrame:viewframe];
36fbb2aa
JF
7788 if (animated)
7789 [UIView commitAnimations];
8c02abc8 7790
9cb0bff2
GP
7791 // Ensure bar has the proper width for our view, it might have changed
7792 barframe.size.width = viewframe.size.width;
7793 [refreshbar_ setFrame:barframe];
7794
8c02abc8
GP
7795 // XXX: fix Apple's layout bug
7796 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7797}
7798
7799- (void) raiseBar:(BOOL)animated {
36fbb2aa
JF
7800 if (!dropped_)
7801 return;
8c02abc8
GP
7802 dropped_ = false;
7803
7804 [refreshbar_ removeFromSuperview];
7805
6067f1b8 7806 CGFloat sboffset = [self statusBarHeight];
632f629b 7807
36fbb2aa
JF
7808 if (animated)
7809 [UIView beginAnimations:nil context:NULL];
8c02abc8
GP
7810 CGRect barframe = [refreshbar_ frame];
7811 CGRect viewframe = [[root_ view] frame];
632f629b
GP
7812 viewframe.origin.y -= barframe.size.height + sboffset;
7813 viewframe.size.height += barframe.size.height + sboffset;
8c02abc8 7814 [[root_ view] setFrame:viewframe];
36fbb2aa
JF
7815 if (animated)
7816 [UIView commitAnimations];
8c02abc8
GP
7817
7818 // XXX: fix Apple's layout bug
7819 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7820}
7821
e62f29c6 7822- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6b727a05
RP
7823 // XXX: fix Apple's layout bug
7824 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7825}
7826
9cb0bff2 7827- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8c02abc8
GP
7828 if (dropped_) {
7829 [self raiseBar:NO];
7830 [self dropBar:NO];
7831 }
bc11cf5b 7832
8c02abc8
GP
7833 // XXX: fix Apple's layout bug
7834 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7835}
7836
632f629b
GP
7837- (void) statusBarFrameChanged:(NSNotification *)notification {
7838 if (dropped_) {
7839 [self raiseBar:NO];
7840 [self dropBar:NO];
7841 }
7842}
7843
8c02abc8
GP
7844- (void) dealloc {
7845 [refreshbar_ release];
632f629b 7846 [[NSNotificationCenter defaultCenter] removeObserver:self];
8c02abc8
GP
7847 [super dealloc];
7848}
7849
6f6d34ec 7850- (id) initWithDatabase:(Database *)database {
8c02abc8
GP
7851 if ((self = [super init]) != nil) {
7852 database_ = database;
7853
9cb0bff2 7854 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
632f629b 7855 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
9cb0bff2
GP
7856
7857 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
8c02abc8
GP
7858 } return self;
7859}
7860
7861@end
7862/* }}} */
7863
b5e7eebb
GP
7864typedef enum {
7865 kCydiaTag = 0,
7866 kSectionsTag = 1,
7867 kChangesTag = 2,
7868 kManageTag = 3,
7869 kInstalledTag = 4,
7870 kSourcesTag = 5,
7871 kSearchTag = 6
7872} CYTabTag;
04fe1349 7873
2367a917 7874@interface Cydia : UIApplication <
adb61bda
GP
7875 ConfirmationControllerDelegate,
7876 ProgressControllerDelegate,
eb30da80 7877 CydiaDelegate,
68046ccc
JF
7878 UINavigationControllerDelegate,
7879 UITabBarControllerDelegate
2367a917 7880> {
3931b718
JF
7881 // XXX: evaluate all fields for _transient
7882
dc5812ec 7883 UIWindow *window_;
8c02abc8 7884 CYContainer *container_;
68046ccc 7885 CYTabBarController *tabbar_;
9bedffaa 7886
a54b1c10 7887 NSMutableArray *essential_;
9bedffaa 7888 NSMutableArray *broken_;
dc5812ec
JF
7889
7890 Database *database_;
dc5812ec 7891
aeed65a6 7892 int tag_;
b4d89997
JF
7893
7894 UIKeyboard *keyboard_;
fc53bb07 7895 int huds_;
9b619239 7896
adb61bda
GP
7897 SectionsController *sections_;
7898 ChangesController *changes_;
7899 ManageController *manage_;
7900 SearchController *search_;
b5e7eebb 7901 SourceTable *sources_;
adb61bda 7902 InstalledController *installed_;
b5e7eebb 7903 id queueDelegate_;
f79a4512 7904
f3e11d24
GP
7905 CYStashController *stash_;
7906
8c02abc8 7907 bool loaded_;
dc5812ec
JF
7908}
7909
9b623dac
JF
7910- (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7911- (void) setPage:(CYViewController *)page;
fed0d010 7912- (void) loadData;
670a0494 7913
dc5812ec
JF
7914@end
7915
670a0494 7916static _finline void _setHomePage(Cydia *self) {
adb61bda 7917 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
670a0494
JF
7918}
7919
dc5812ec
JF
7920@implementation Cydia
7921
b5e7eebb 7922- (void) beginUpdate {
8c02abc8 7923 [container_ beginUpdate];
b5e7eebb
GP
7924}
7925
7926- (BOOL) updating {
8c02abc8 7927 return [container_ updating];
b5e7eebb
GP
7928}
7929
01d93940
JF
7930- (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7931 return window_;
7932}
7933
9bedffaa
JF
7934- (void) _loaded {
7935 if ([broken_ count] != 0) {
7936 int count = [broken_ count];
7937
37d2b2a9 7938 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 7939 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
b5e7eebb
GP
7940 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7941 delegate:self
7942 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7943 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
9bedffaa
JF
7944 ] autorelease];
7945
37d2b2a9
GP
7946 [alert setContext:@"fixhalf"];
7947 [alert show];
9bedffaa
JF
7948 } else if (!Ignored_ && [essential_ count] != 0) {
7949 int count = [essential_ count];
7950
37d2b2a9 7951 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 7952 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
b5e7eebb
GP
7953 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7954 delegate:self
7955 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
37d2b2a9 7956 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
9bedffaa
JF
7957 ] autorelease];
7958
37d2b2a9
GP
7959 [alert setContext:@"upgrade"];
7960 [alert show];
9bedffaa
JF
7961 }
7962}
7963
7623f855
JF
7964- (void) _saveConfig {
7965 if (Changed_) {
7966 _trace();
7967 NSString *error(nil);
7968 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7969 _trace();
7970 NSError *error(nil);
7971 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7972 NSLog(@"failure to save metadata data: %@", error);
7973 _trace();
7974 } else {
7975 NSLog(@"failure to serialize metadata: %@", error);
7976 return;
7977 }
7978
7979 Changed_ = false;
7980 }
7981}
7982
7983- (void) _updateData {
7984 [self _saveConfig];
7985
7986 /* XXX: this is just stupid */
aeed65a6 7987 if (tag_ != 1 && sections_ != nil)
7623f855 7988 [sections_ reloadData];
aeed65a6 7989 if (tag_ != 2 && changes_ != nil)
7623f855 7990 [changes_ reloadData];
aeed65a6 7991 if (tag_ != 4 && search_ != nil)
7623f855
JF
7992 [search_ reloadData];
7993
c21004b9 7994 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
b5e7eebb
GP
7995}
7996
7997- (int)indexOfTabWithTag:(int)tag {
7998 int i = 0;
7999 for (UINavigationController *controller in [tabbar_ viewControllers]) {
36fbb2aa
JF
8000 if ([[controller tabBarItem] tag] == tag)
8001 return i;
b5e7eebb
GP
8002 i += 1;
8003 }
bc11cf5b 8004
b5e7eebb 8005 return -1;
7623f855
JF
8006}
8007
9aecdc9c 8008- (void) _refreshIfPossible {
8c02abc8 8009 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
bc11cf5b 8010
45e21ffa
GP
8011 bool recently = false;
8012 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8013 if (update != nil) {
8014 NSTimeInterval interval([update timeIntervalSinceNow]);
8015 if (interval <= 0 && interval > -(15*60))
8016 recently = true;
8017 }
8018
8019 // Don't automatic refresh if:
8020 // - We already refreshed recently.
8021 // - We already auto-refreshed this launch.
8022 // - Auto-refresh is disabled.
8023 if (recently || loaded_ || ManualRefresh) {
8024 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8025
8026 // If we are cancelling due to ManualRefresh or a recent refresh
8027 // we need to make sure it knows it's already loaded.
8028 loaded_ = true;
8029 return;
8030 } else {
8031 // We are going to load, so remember that.
8032 loaded_ = true;
8033 }
8034
afb5333a
JF
8035 SCNetworkReachabilityFlags flags; {
8036 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8037 SCNetworkReachabilityGetFlags(reachability, &flags);
8038 CFRelease(reachability);
8039 }
8040
8041 // XXX: this elaborate mess is what Apple is using to determine this? :(
8042 // XXX: do we care if the user has to intervene? maybe that's ok?
8043 bool reachable(
8044 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8045 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8046 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8047 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8048 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8049 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8050 )
8051 );
bc11cf5b 8052
45e21ffa
GP
8053 // If we can reach the server, auto-refresh!
8054 if (reachable)
8c02abc8 8055 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9aecdc9c 8056
8c02abc8 8057 [pool release];
9aecdc9c
GP
8058}
8059
8060- (void) refreshIfPossible {
8c02abc8 8061 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9aecdc9c
GP
8062}
8063
36bb2ca2 8064- (void) _reloadData {
851f4a99
GP
8065 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8066 [hud setText:UCLocalize("RELOADING_DATA")];
dc5812ec 8067
d061f4ba 8068 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
d061f4ba 8069
36fbb2aa
JF
8070 if (hud != nil)
8071 [self removeProgressHUD:hud];
c25a610d 8072
36bb2ca2 8073 size_t changes(0);
9bedffaa 8074
a54b1c10 8075 [essential_ removeAllObjects];
9bedffaa 8076 [broken_ removeAllObjects];
b4d89997 8077
670a0494 8078 NSArray *packages([database_ packages]);
affeffc7 8079 for (Package *package in packages) {
9bedffaa
JF
8080 if ([package half])
8081 [broken_ addObject:package];
31f3cfff 8082 if ([package upgradableAndEssential:NO]) {
a54b1c10
JF
8083 if ([package essential])
8084 [essential_ addObject:package];
36bb2ca2 8085 ++changes;
a54b1c10 8086 }
36bb2ca2 8087 }
b4d89997 8088
45e21ffa 8089 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
36bb2ca2
JF
8090 if (changes != 0) {
8091 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
45e21ffa 8092 [changesItem setBadgeValue:badge];
65a03a7a 8093 [changesItem setAnimatedBadge:([essential_ count] > 0)];
bc11cf5b 8094
f79a4512
JF
8095 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8096 [self setApplicationBadge:badge];
8097 else
8098 [self setApplicationBadgeString:badge];
c25a610d 8099 } else {
45e21ffa
GP
8100 [changesItem setBadgeValue:nil];
8101 [changesItem setAnimatedBadge:NO];
bc11cf5b 8102
f79a4512
JF
8103 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8104 [self removeApplicationBadge];
8105 else // XXX: maybe use setApplicationBadgeString also?
8106 [self setApplicationIconBadgeNumber:0];
c25a610d 8107 }
b4d89997 8108
7623f855 8109 [self _updateData];
6d9712c4 8110
8c02abc8 8111 [self refreshIfPossible];
6d9712c4
JF
8112}
8113
7b0ce2da 8114- (void) updateData {
7623f855 8115 [self _updateData];
b4d89997
JF
8116}
8117
7b0ce2da
JF
8118- (void) update_ {
8119 [database_ update];
8120}
8121
8122- (void) syncData {
670a0494 8123 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7b0ce2da
JF
8124 _assert(file != NULL);
8125
670a0494
JF
8126 for (NSString *key in [Sources_ allKeys]) {
8127 NSDictionary *source([Sources_ objectForKey:key]);
7b0ce2da
JF
8128
8129 fprintf(file, "%s %s %s\n",
8130 [[source objectForKey:@"Type"] UTF8String],
8131 [[source objectForKey:@"URI"] UTF8String],
8132 [[source objectForKey:@"Distribution"] UTF8String]
8133 );
8134 }
8135
8136 fclose(file);
8137
8138 [self _saveConfig];
8139
adb61bda 8140 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
eb30da80 8141 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
36fbb2aa
JF
8142 if (IsWildcat_)
8143 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8c02abc8 8144 [container_ presentModalViewController:navigation animated:YES];
b5e7eebb
GP
8145
8146 [progress
7b0ce2da
JF
8147 detachNewThreadSelector:@selector(update_)
8148 toTarget:self
8149 withObject:nil
43f3d7f6 8150 title:UCLocalize("UPDATING_SOURCES")
7b0ce2da
JF
8151 ];
8152}
8153
36bb2ca2
JF
8154- (void) reloadData {
8155 @synchronized (self) {
b5e7eebb 8156 [self _reloadData];
36bb2ca2 8157 }
b4d89997
JF
8158}
8159
8160- (void) resolve {
8161 pkgProblemResolver *resolver = [database_ resolver];
8162
8163 resolver->InstallProtect();
8164 if (!resolver->Resolve(true))
8165 _error->Discard();
2367a917
JF
8166}
8167
aa5d0de7 8168- (CGRect) popUpBounds {
b5e7eebb 8169 return [[tabbar_ view] bounds];
aa5d0de7
JF
8170}
8171
670a0494
JF
8172- (bool) perform {
8173 if (![database_ prepare])
8174 return false;
49048579 8175
adb61bda 8176 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
affeffc7 8177 [page setDelegate:self];
3931b718 8178 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
b5e7eebb 8179 [confirm_ setDelegate:self];
49048579 8180
36fbb2aa
JF
8181 if (IsWildcat_)
8182 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8c02abc8 8183 [container_ presentModalViewController:confirm_ animated:YES];
670a0494
JF
8184
8185 return true;
3178d79b
JF
8186}
8187
dc63e78f
JF
8188- (void) queue {
8189 @synchronized (self) {
8190 [self perform];
8191 }
8192}
8193
8194- (void) clearPackage:(Package *)package {
8195 @synchronized (self) {
8196 [package clear];
8197 [self resolve];
8198 [self perform];
8199 }
8200}
8201
77801ff1
JF
8202- (void) installPackages:(NSArray *)packages {
8203 @synchronized (self) {
8204 for (Package *package in packages)
8205 [package install];
8206 [self resolve];
8207 [self perform];
8208 }
8209}
8210
36bb2ca2
JF
8211- (void) installPackage:(Package *)package {
8212 @synchronized (self) {
8213 [package install];
8214 [self resolve];
8215 [self perform];
8216 }
8217}
8218
8219- (void) removePackage:(Package *)package {
8220 @synchronized (self) {
8221 [package remove];
8222 [self resolve];
8223 [self perform];
8224 }
8225}
8226
8227- (void) distUpgrade {
8228 @synchronized (self) {
670a0494
JF
8229 if (![database_ upgrade])
8230 return;
36bb2ca2
JF
8231 [self perform];
8232 }
b4d89997
JF
8233}
8234
dc63e78f 8235- (void) complete {
36bb2ca2 8236 @synchronized (self) {
36bb2ca2
JF
8237 [self _reloadData];
8238 }
3178d79b
JF
8239}
8240
b5e7eebb 8241- (void) confirmWithNavigationController:(UINavigationController *)navigation {
adb61bda 8242 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
bc11cf5b 8243
b5e7eebb
GP
8244 if (navigation != nil) {
8245 [navigation pushViewController:progress animated:YES];
8246 } else {
9cb0bff2 8247 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
36fbb2aa
JF
8248 if (IsWildcat_)
8249 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8c02abc8 8250 [container_ presentModalViewController:navigation animated:YES];
b5e7eebb 8251 }
bc11cf5b 8252
b5e7eebb 8253 [progress
2367a917
JF
8254 detachNewThreadSelector:@selector(perform)
8255 toTarget:database_
8256 withObject:nil
43f3d7f6 8257 title:UCLocalize("RUNNING")
2367a917
JF
8258 ];
8259}
8260
39cda3a8 8261- (void) progressControllerIsComplete:(ProgressController *)progress {
dc63e78f 8262 [self complete];
dc5812ec
JF
8263}
8264
9b623dac 8265- (void) setPage:(CYViewController *)page {
36bb2ca2 8266 [page setDelegate:self];
b5e7eebb 8267
c21004b9 8268 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
a59e2ee6 8269 [navController setViewControllers:[NSArray arrayWithObject:page]];
36fbb2aa
JF
8270 for (CYNavigationController *page in [tabbar_ viewControllers])
8271 if (page != navController)
8272 [page setViewControllers:nil];
dc5812ec
JF
8273}
8274
9b623dac 8275- (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
b5e7eebb 8276 CYBrowserController *browser = [[[_class alloc] init] autorelease];
7b0ce2da 8277 [browser loadURL:url];
36bb2ca2 8278 return browser;
2367a917
JF
8279}
8280
adb61bda 8281- (SectionsController *) sectionsController {
f79a4512 8282 if (sections_ == nil)
adb61bda 8283 sections_ = [[SectionsController alloc] initWithDatabase:database_];
f79a4512
JF
8284 return sections_;
8285}
8286
adb61bda 8287- (ChangesController *) changesController {
01d93940 8288 if (changes_ == nil)
adb61bda 8289 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
01d93940
JF
8290 return changes_;
8291}
8292
adb61bda 8293- (ManageController *) manageController {
b5e7eebb 8294 if (manage_ == nil) {
adb61bda 8295 manage_ = (ManageController *) [[self
01d93940 8296 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
adb61bda 8297 withClass:[ManageController class]
01d93940 8298 ] retain];
36fbb2aa
JF
8299 if (!IsWildcat_)
8300 queueDelegate_ = manage_;
b5e7eebb 8301 }
01d93940
JF
8302 return manage_;
8303}
8304
adb61bda 8305- (SearchController *) searchController {
01d93940 8306 if (search_ == nil)
adb61bda 8307 search_ = [[SearchController alloc] initWithDatabase:database_];
01d93940
JF
8308 return search_;
8309}
8310
adb61bda 8311- (SourceTable *) sourcesController {
b5e7eebb
GP
8312 if (sources_ == nil)
8313 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8314 return sources_;
8315}
8316
adb61bda 8317- (InstalledController *) installedController {
b5e7eebb 8318 if (installed_ == nil) {
adb61bda 8319 installed_ = [[InstalledController alloc] initWithDatabase:database_];
36fbb2aa
JF
8320 if (IsWildcat_)
8321 queueDelegate_ = installed_;
b5e7eebb
GP
8322 }
8323 return installed_;
8324}
8325
68046ccc 8326- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
b5e7eebb 8327 int tag = [[viewController tabBarItem] tag];
559dec34 8328 if (tag == tag_) {
c21004b9 8329 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
559dec34 8330 return;
b5e7eebb 8331 } else if (tag_ == 1) {
adb61bda 8332 [[self sectionsController] resetView];
b5e7eebb 8333 }
dc5812ec 8334
06aa974d 8335 switch (tag) {
b5e7eebb 8336 case kCydiaTag: _setHomePage(self); break;
36bb2ca2 8337
adb61bda
GP
8338 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8339 case kChangesTag: [self setPage:[self changesController]]; break;
8340 case kManageTag: [self setPage:[self manageController]]; break;
8341 case kInstalledTag: [self setPage:[self installedController]]; break;
8342 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8343 case kSearchTag: [self setPage:[self searchController]]; break;
36bb2ca2 8344
670a0494 8345 _nodefault
dc5812ec
JF
8346 }
8347
06aa974d 8348 tag_ = tag;
06aa974d
JF
8349}
8350
21c6da4b 8351- (void) showSettings {
3931b718
JF
8352 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8353 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
36fbb2aa
JF
8354 if (IsWildcat_)
8355 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
21c6da4b 8356 [container_ presentModalViewController:nav animated:YES];
7b0ce2da
JF
8357}
8358
adb61bda 8359- (void) setPackageController:(PackageController *)view {
7592e053
JF
8360 WebThreadLock();
8361 [view setPackage:nil];
7592e053
JF
8362 WebThreadUnlock();
8363}
8364
adb61bda
GP
8365- (PackageController *) _packageController {
8366 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
f79a4512
JF
8367}
8368
adb61bda 8369- (PackageController *) packageController {
adb61bda 8370 return [self _packageController];
f79a4512
JF
8371}
8372
09c01bb0
GP
8373// Returns the navigation controller for the queuing badge.
8374- (id) queueBadgeController {
8375 int index = [self indexOfTabWithTag:kManageTag];
36fbb2aa
JF
8376 if (index == -1)
8377 index = [self indexOfTabWithTag:kInstalledTag];
6067f1b8 8378
09c01bb0
GP
8379 return [[tabbar_ viewControllers] objectAtIndex:index];
8380}
8381
674dce72
GP
8382- (void) cancelAndClear:(bool)clear {
8383 @synchronized (self) {
8384 if (clear) {
c6ca67ba 8385 [database_ clear];
b5e7eebb 8386
6067f1b8 8387 // Stop queuing.
b5e7eebb 8388 Queuing_ = false;
09c01bb0 8389 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
674dce72 8390 } else {
6067f1b8 8391 // Start queuing.
b5e7eebb 8392 Queuing_ = true;
09c01bb0 8393 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
6067f1b8
JF
8394 }
8395
a4217bbb 8396 [self _updateData];
09c01bb0 8397 [queueDelegate_ queueStatusDidChange];
674dce72 8398 }
37d2b2a9 8399}
7b0ce2da 8400
b5e7eebb
GP
8401- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8402 NSString *context([alert context]);
bc11cf5b 8403
b5e7eebb
GP
8404 if ([context isEqualToString:@"fixhalf"]) {
8405 if (button == [alert firstOtherButtonIndex]) {
37d2b2a9
GP
8406 @synchronized (self) {
8407 for (Package *broken in broken_) {
8408 [broken remove];
8409
8410 NSString *id = [broken id];
8411 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8412 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8413 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8414 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8415 }
7b0ce2da 8416
37d2b2a9
GP
8417 [self resolve];
8418 [self perform];
8419 }
b5e7eebb 8420 } else if (button == [alert cancelButtonIndex]) {
37d2b2a9
GP
8421 [broken_ removeAllObjects];
8422 [self _loaded];
7b0ce2da
JF
8423 }
8424
37d2b2a9 8425 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 8426 } else if ([context isEqualToString:@"upgrade"]) {
37d2b2a9
GP
8427 if (button == [alert firstOtherButtonIndex]) {
8428 @synchronized (self) {
8429 for (Package *essential in essential_)
8430 [essential install];
7b0ce2da 8431
37d2b2a9
GP
8432 [self resolve];
8433 [self perform];
8434 }
8435 } else if (button == [alert firstOtherButtonIndex] + 1) {
8436 [self distUpgrade];
8437 } else if (button == [alert cancelButtonIndex]) {
8438 Ignored_ = YES;
7b0ce2da
JF
8439 }
8440
37d2b2a9 8441 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 8442 }
7b0ce2da
JF
8443}
8444
670a0494
JF
8445- (void) system:(NSString *)command { _pooled
8446 system([command UTF8String]);
8447}
8448
8449- (void) applicationWillSuspend {
8450 [database_ clean];
8451 [super applicationWillSuspend];
bd150f54
JF
8452}
8453
fc53bb07
GP
8454- (BOOL) hudIsShowing {
8455 return (huds_ > 0);
8456}
8457
bd150f54 8458- (void) applicationSuspend:(__GSEvent *)event {
262afe11
GP
8459 // Use external process status API internally.
8460 // This is probably a really bad idea.
8461 uint64_t status = 0;
8462 int notify_token;
8463 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
8464 notify_get_state(notify_token, &status);
8465 notify_cancel(notify_token);
8466 }
8467
fc53bb07 8468 if (![self hudIsShowing] && status == 0)
bd150f54 8469 [super applicationSuspend:event];
bd150f54
JF
8470}
8471
6d9712c4 8472- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
fc53bb07 8473 if (![self hudIsShowing])
6d9712c4
JF
8474 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8475}
8476
8477- (void) _setSuspended:(BOOL)value {
fc53bb07 8478 if (![self hudIsShowing])
6d9712c4
JF
8479 [super _setSuspended:value];
8480}
8481
7b0ce2da 8482- (UIProgressHUD *) addProgressHUD {
d061f4ba 8483 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
04fe1349
JF
8484 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8485
d061f4ba 8486 [window_ setUserInteractionEnabled:NO];
7b0ce2da 8487 [hud show:YES];
534e31fc
GP
8488
8489 UIViewController *target = container_;
8490 while ([target modalViewController] != nil) target = [target modalViewController];
8491 [[target view] addSubview:hud];
8492
fc53bb07 8493 huds_++;
7b0ce2da
JF
8494 return hud;
8495}
8496
d061f4ba
JF
8497- (void) removeProgressHUD:(UIProgressHUD *)hud {
8498 [hud show:NO];
8499 [hud removeFromSuperview];
8500 [window_ setUserInteractionEnabled:YES];
fc53bb07 8501 huds_--;
d061f4ba
JF
8502}
8503
9b623dac 8504- (CYViewController *) pageForPackage:(NSString *)name {
c390d3ab 8505 if (Package *package = [database_ packageWithName:name]) {
adb61bda 8506 PackageController *view([self packageController]);
c390d3ab
JF
8507 [view setPackage:package];
8508 return view;
8509 } else {
670a0494
JF
8510 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8511 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
b5e7eebb 8512 return [self _pageForURL:url withClass:[CYBrowserController class]];
c390d3ab
JF
8513 }
8514}
8515
9b623dac 8516- (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
c390d3ab 8517 if (tag != NULL)
aeed65a6 8518 *tag = -1;
c390d3ab 8519
43f3d7f6
JF
8520 NSString *href([url absoluteString]);
8521 if ([href hasPrefix:@"apptapp://package/"])
8522 return [self pageForPackage:[href substringFromIndex:18]];
8523
e47c4742
JF
8524 NSString *scheme([[url scheme] lowercaseString]);
8525 if (![scheme isEqualToString:@"cydia"])
8526 return nil;
8527 NSString *path([url absoluteString]);
8528 if ([path length] < 8)
8529 return nil;
8530 path = [path substringFromIndex:8];
8531 if (![path hasPrefix:@"/"])
8532 path = [@"/" stringByAppendingString:path];
8533
8534 if ([path isEqualToString:@"/add-source"])
adb61bda 8535 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
e47c4742 8536 else if ([path isEqualToString:@"/storage"])
b5e7eebb 8537 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
e47c4742 8538 else if ([path isEqualToString:@"/sources"])
b5e7eebb 8539 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
e47c4742 8540 else if ([path isEqualToString:@"/packages"])
adb61bda 8541 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
e47c4742 8542 else if ([path hasPrefix:@"/url/"])
b5e7eebb 8543 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
e47c4742
JF
8544 else if ([path hasPrefix:@"/launch/"])
8545 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8546 else if ([path hasPrefix:@"/package-settings/"])
adb61bda 8547 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
e47c4742 8548 else if ([path hasPrefix:@"/package-signature/"])
adb61bda 8549 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
e47c4742
JF
8550 else if ([path hasPrefix:@"/package/"])
8551 return [self pageForPackage:[path substringFromIndex:9]];
8552 else if ([path hasPrefix:@"/files/"]) {
8553 NSString *name = [path substringFromIndex:7];
c390d3ab
JF
8554
8555 if (Package *package = [database_ packageWithName:name]) {
b5e7eebb 8556 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
c390d3ab
JF
8557 [files setPackage:package];
8558 return files;
8559 }
8560 }
8561
8562 return nil;
8563}
8564
8565- (void) applicationOpenURL:(NSURL *)url {
8566 [super applicationOpenURL:url];
8567 int tag;
9b623dac 8568 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
c390d3ab 8569 [self setPage:page];
c390d3ab 8570 tag_ = tag;
b5e7eebb 8571 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
c390d3ab
JF
8572 }
8573}
8574
bc11cf5b 8575- (void) applicationWillResignActive:(UIApplication *)application {
7eff7ea6 8576 // Stop refreshing if you get a phone call or lock the device.
36fbb2aa
JF
8577 if ([container_ updating])
8578 [container_ cancelUpdate];
bc11cf5b 8579
ca584c15
GP
8580 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8581 [super applicationWillResignActive:application];
7eff7ea6
GP
8582}
8583
f3e11d24
GP
8584- (void) addStashController {
8585 stash_ = [[CYStashController alloc] init];
8586 [window_ addSubview:[stash_ view]];
8587}
8588
8589- (void) removeStashController {
8590 [[stash_ view] removeFromSuperview];
8591 [stash_ release];
8592}
8593
8594- (void) stash {
8595 [self setIdleTimerDisabled:YES];
8596
9e1f1e91 8597 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
f3e11d24
GP
8598 [self setStatusBarShowsProgress:YES];
8599 UpdateExternalStatus(1);
8600
8601 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8602
8603 UpdateExternalStatus(0);
8604 [self setStatusBarShowsProgress:NO];
8605
8606 [self removeStashController];
8607
8608 if (ExecFork() == 0) {
8609 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8610 perror("launchctl stop");
8611 }
8612}
8613
851f4a99
GP
8614- (void) setupTabBarController {
8615 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8616 [tabbar_ setDelegate:self];
8617
8618 NSMutableArray *items([NSMutableArray arrayWithObjects:
8619 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8620 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8621 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8622 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8623 nil]);
8624
8625 if (IsWildcat_) {
8626 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8627 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8628 } else {
8629 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8630 }
8631
8632 NSMutableArray *controllers([NSMutableArray array]);
8633
8634 for (UITabBarItem *item in items) {
8635 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8636 [controller setTabBarItem:item];
8637 [controllers addObject:controller];
8638 }
8639
8640 [tabbar_ setViewControllers:controllers];
851f4a99
GP
8641}
8642
bd150f54 8643- (void) applicationDidFinishLaunching:(id)unused {
b5e7eebb 8644 [CYBrowserController _initialize];
ea173384 8645
bfc87a4d
JF
8646 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8647
f641a0e5
JF
8648 Font12_ = [[UIFont systemFontOfSize:12] retain];
8649 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8650 Font14_ = [[UIFont systemFontOfSize:14] retain];
8651 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8652 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8653
aeed65a6 8654 tag_ = 0;
bd150f54
JF
8655
8656 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8657 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8658
04fe1349
JF
8659 UIScreen *screen([UIScreen mainScreen]);
8660
8661 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
f641a0e5
JF
8662 [window_ orderFront:self];
8663 [window_ makeKey:self];
c390d3ab 8664 [window_ setHidden:NO];
04fe1349 8665
f3e11d24
GP
8666 if (
8667 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8668 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8669 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8670 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8671 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8672 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8673 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8674 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8675 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8676 false
8677 ) {
8678 [self addStashController];
3931b718
JF
8679 // XXX: this would be much cleaner as a yieldToSelector:
8680 // that way the removeStashController could happen right here inline
8681 // we also could no longer require the useless stash_ field anymore
f3e11d24
GP
8682 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8683 return;
8684 }
8685
770f2a8e 8686 database_ = [Database sharedInstance];
bfc87a4d 8687
851f4a99 8688 [self setupTabBarController];
8c02abc8
GP
8689
8690 container_ = [[CYContainer alloc] initWithDatabase:database_];
8c02abc8 8691 [container_ setUpdateDelegate:self];
c21004b9 8692 [container_ setTabBarController:tabbar_];
8c02abc8 8693 [window_ addSubview:[container_ view]];
670a0494 8694
5ccb47d8 8695 // Show pinstripes while loading data.
4985045e 8696 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
5ccb47d8 8697
fed0d010 8698 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
c626a63f 8699_trace();
fed0d010
JF
8700}
8701
8702- (void) loadData {
c626a63f 8703_trace();
fed0d010
JF
8704 if (Role_ == nil) {
8705 [self showSettings];
8706 return;
8707 }
8708
851f4a99 8709 [window_ setUserInteractionEnabled:NO];
670a0494 8710
dd9de556 8711 UIView *container = [[[UIView alloc] init] autorelease];
851f4a99
GP
8712 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8713
dd9de556 8714 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
851f4a99
GP
8715 [spinner startAnimating];
8716 [container addSubview:spinner];
851f4a99 8717
dd9de556 8718 UILabel *label = [[[UILabel alloc] init] autorelease];
851f4a99
GP
8719 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8720 [label setBackgroundColor:[UIColor clearColor]];
8721 [label setTextColor:[UIColor blackColor]];
8722 [label setShadowColor:[UIColor whiteColor]];
8723 [label setShadowOffset:CGSizeMake(0, 1)];
72fb3616 8724 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
851f4a99 8725 [container addSubview:label];
851f4a99
GP
8726
8727 CGSize viewsize = [[tabbar_ view] frame].size;
8728 CGSize spinnersize = [spinner bounds].size;
8729 CGSize textsize = [[label text] sizeWithFont:[label font]];
8730 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8731
8732 CGRect containrect = {
8733 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8734 CGSizeMake(bothwidth, spinnersize.height)
8735 };
8736 CGRect textrect = {
8737 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8738 textsize
8739 };
8740 CGRect spinrect = {
8741 CGPointZero,
8742 spinnersize
8743 };
8744
8745 [container setFrame:containrect];
8746 [spinner setFrame:spinrect];
8747 [label setFrame:textrect];
8748 [[container_ view] addSubview:container];
851f4a99
GP
8749
8750 [self reloadData];
670a0494
JF
8751 PrintTimes();
8752
851f4a99 8753 // Show the home page
176c4a5f 8754 [tabbar_ setSelectedIndex:0];
670a0494 8755 _setHomePage(self);
851f4a99 8756 [window_ setUserInteractionEnabled:YES];
5ccb47d8
GP
8757
8758 // XXX: does this actually slow anything down?
8759 [[container_ view] setBackgroundColor:[UIColor clearColor]];
851f4a99 8760 [container removeFromSuperview];
bd150f54
JF
8761}
8762
b5e7eebb 8763- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
674dce72 8764 if (item != nil && IsWildcat_) {
b5e7eebb 8765 [sheet showFromBarButtonItem:item animated:YES];
674dce72
GP
8766 } else {
8767 [sheet showInView:window_];
8768 }
36bb2ca2
JF
8769}
8770
dc5812ec
JF
8771@end
8772
b4d89997
JF
8773/*IMP alloc_;
8774id Alloc_(id self, SEL selector) {
8775 id object = alloc_(self, selector);
c390d3ab 8776 lprintf("[%s]A-%p\n", self->isa->name, object);
b4d89997
JF
8777 return object;
8778}*/
8779
36bb2ca2
JF
8780/*IMP dealloc_;
8781id Dealloc_(id self, SEL selector) {
8782 id object = dealloc_(self, selector);
c390d3ab 8783 lprintf("[%s]D-%p\n", self->isa->name, object);
36bb2ca2
JF
8784 return object;
8785}*/
b4d89997 8786
f79a4512
JF
8787Class $WebDefaultUIKitDelegate;
8788
d791dce4 8789MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
f79a4512
JF
8790 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8791 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
d791dce4 8792 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
f79a4512
JF
8793}
8794
10d65752
RP
8795static NSNumber *shouldPlayKeyboardSounds;
8796
8797Class $UIHardware;
8798
b72246b0
JF
8799MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8800 switch (sound) {
10d65752
RP
8801 case 1104: // Keyboard Button Clicked
8802 case 1105: // Keyboard Delete Repeated
b72246b0
JF
8803 if (shouldPlayKeyboardSounds == nil) {
8804 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8805 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
10d65752 8806 }
b72246b0 8807
10d65752
RP
8808 if (![shouldPlayKeyboardSounds boolValue])
8809 break;
b72246b0 8810
10d65752 8811 default:
b72246b0 8812 _UIHardware$_playSystemSound$(self, _cmd, sound);
10d65752
RP
8813 }
8814}
8815
affeffc7 8816int main(int argc, char *argv[]) { _pooled
d6dad1b4 8817 _trace();
f79a4512 8818
01d93940
JF
8819 if (Class $UIDevice = objc_getClass("UIDevice")) {
8820 UIDevice *device([$UIDevice currentDevice]);
8821 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8822 } else
8823 IsWildcat_ = false;
8824
df213583 8825 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
677b8415 8826
7376b55c
JF
8827 /* Library Hacks {{{ */
8828 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8829
8830 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8831 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8832 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8833 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8834 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8835 }
10d65752
RP
8836
8837 $UIHardware = objc_getClass("UIHardware");
8838 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8839 if (UIHardware$_playSystemSound$ != NULL) {
8840 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8841 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8842 }
7376b55c
JF
8843 /* }}} */
8844 /* Set Locale {{{ */
f79a4512 8845 Locale_ = CFLocaleCopyCurrent();
b1ce61ec
JF
8846 Languages_ = [NSLocale preferredLanguages];
8847 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
18876387 8848 //NSLog(@"%@", [Languages_ description]);
78430d06 8849
b1ce61ec
JF
8850 const char *lang;
8851 if (Languages_ == nil || [Languages_ count] == 0)
78430d06 8852 // XXX: consider just setting to C and then falling through?
b1ce61ec 8853 lang = NULL;
78430d06 8854 else {
b1ce61ec 8855 lang = [[Languages_ objectAtIndex:0] UTF8String];
78430d06
JF
8856 setenv("LANG", lang, true);
8857 }
8858
b1ce61ec
JF
8859 //std::setlocale(LC_ALL, lang);
8860 NSLog(@"Setting Language: %s", lang);
7376b55c 8861 /* }}} */
f79a4512 8862
d791dce4 8863 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
f79a4512 8864
7376b55c 8865 /* Parse Arguments {{{ */
de3b1ab4
JF
8866 bool substrate(false);
8867
8868 if (argc != 0) {
8869 char **args(argv);
8870 int arge(1);
8871
8872 for (int argi(1); argi != argc; ++argi)
8873 if (strcmp(argv[argi], "--") == 0) {
8874 arge = argi;
8875 argv[argi] = argv[0];
8876 argv += argi;
8877 argc -= argi;
8878 break;
8879 }
8880
8881 for (int argi(1); argi != arge; ++argi)
d791dce4 8882 if (strcmp(args[argi], "--substrate") == 0)
de3b1ab4
JF
8883 substrate = true;
8884 else
8885 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8886 }
7376b55c 8887 /* }}} */
d73cede2 8888
7376b55c
JF
8889 App_ = [[NSBundle mainBundle] bundlePath];
8890 Home_ = NSHomeDirectory();
d791dce4 8891 Advanced_ = YES;
7376b55c 8892
b4d89997
JF
8893 setuid(0);
8894 setgid(0);
8895
8896 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8897 alloc_ = alloc->method_imp;
8898 alloc->method_imp = (IMP) &Alloc_;*/
8899
36bb2ca2
JF
8900 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8901 dealloc_ = dealloc->method_imp;
8902 dealloc->method_imp = (IMP) &Dealloc_;*/
8903
d791dce4 8904 /* System Information {{{ */
3178d79b 8905 size_t size;
c390d3ab
JF
8906
8907 int maxproc;
8908 size = sizeof(maxproc);
8909 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8910 perror("sysctlbyname(\"kern.maxproc\", ?)");
8911 else if (maxproc < 64) {
8912 maxproc = 64;
8913 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8914 perror("sysctlbyname(\"kern.maxproc\", #)");
8915 }
8916
bfc87a4d
JF
8917 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8918 char *osversion = new char[size];
8919 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8920 perror("sysctlbyname(\"kern.osversion\", ?)");
8921 else
8922 System_ = [NSString stringWithUTF8String:osversion];
8923
3178d79b
JF
8924 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8925 char *machine = new char[size];
c390d3ab
JF
8926 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8927 perror("sysctlbyname(\"hw.machine\", ?)");
8928 else
8929 Machine_ = machine;
3178d79b 8930
59dbe296
JF
8931 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8932 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8933 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
bfc87a4d 8934 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
59dbe296
JF
8935 CFRelease(serial);
8936 }
8937
8938 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8939 NSData *data((NSData *) ecid);
8940 size_t length([data length]);
8941 uint8_t bytes[length];
8942 [data getBytes:bytes];
8943 char string[length * 2 + 1];
8944 for (size_t i(0); i != length; ++i)
8945 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
bfc87a4d 8946 ChipID_ = [NSString stringWithUTF8String:string];
59dbe296
JF
8947 CFRelease(ecid);
8948 }
8949
8950 IOObjectRelease(service);
8951 }
8952 }
8953
87f46a96 8954 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
3178d79b 8955
567e3972
JF
8956 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8957 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8958 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8959
8960 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8961 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8962 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8963
8964 if (mcc != NULL && mnc != NULL)
8965 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
8966
8967 if (mnc != NULL)
8968 CFRelease(mnc);
8969 if (mcc != NULL)
8970 CFRelease(mcc);
8971
ad5d065e
JF
8972 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8973 Build_ = [system objectForKey:@"ProductBuildVersion"];
3e9c9e85
JF
8974 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8975 Product_ = [info objectForKey:@"SafariProductVersion"];
8976 Safari_ = [info objectForKey:@"CFBundleVersion"];
8977 }
d791dce4 8978 /* }}} */
7376b55c 8979 /* Load Database {{{ */
d6dad1b4 8980 _trace();
f79a4512
JF
8981 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8982 _trace();
8983 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
d6dad1b4
JF
8984
8985 if (Metadata_ == NULL)
f79a4512 8986 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
6d9712c4 8987 else {
2bdd73bd 8988 Settings_ = [Metadata_ objectForKey:@"Settings"];
7b0ce2da 8989
b4d89997 8990 Packages_ = [Metadata_ objectForKey:@"Packages"];
6d9712c4 8991 Sections_ = [Metadata_ objectForKey:@"Sections"];
7b0ce2da 8992 Sources_ = [Metadata_ objectForKey:@"Sources"];
ef055c6c
JF
8993
8994 Token_ = [Metadata_ objectForKey:@"Token"];
7b0ce2da
JF
8995 }
8996
8997 if (Settings_ != nil)
8998 Role_ = [Settings_ objectForKey:@"Role"];
8999
9000 if (Packages_ == nil) {
9001 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9002 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9003 }
9004
9005 if (Sections_ == nil) {
9006 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9007 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9008 }
9009
9010 if (Sources_ == nil) {
9011 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9012 [Metadata_ setObject:Sources_ forKey:@"Sources"];
6d9712c4 9013 }
7376b55c 9014 /* }}} */
b4d89997 9015
d791dce4
JF
9016 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9017
01d93940
JF
9018 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9019 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9dd60d81
JF
9020 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9021 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9022 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9023 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
dddbc481 9024
01d93940
JF
9025 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9026
3b0f10b0 9027 if (access("/tmp/.cydia.fw", F_OK) == 0) {
ea173384 9028 unlink("/tmp/.cydia.fw");
3b0f10b0 9029 goto firmware;
77801ff1 9030 } else if (access("/User", F_OK) != 0 || version < 2) {
3b0f10b0 9031 firmware:
d6dad1b4 9032 _trace();
26c2dd8c 9033 system("/usr/libexec/cydia/firmware.sh");
d6dad1b4
JF
9034 _trace();
9035 }
9e98e020 9036
87f46a96
JF
9037 _assert([[NSFileManager defaultManager]
9038 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9039 withIntermediateDirectories:YES
9040 attributes:nil
9041 error:NULL
9042 ]);
9043
7376b55c
JF
9044 if (access("/tmp/cydia.chk", F_OK) == 0) {
9045 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9046 _assert(errno == ENOENT);
9047 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9048 _assert(errno == ENOENT);
9049 }
9050
59dbe296 9051 /* APT Initialization {{{ */
b1ce61ec
JF
9052 _assert(pkgInitConfig(*_config));
9053 _assert(pkgInitSystem(*_config, _system));
9054
9055 if (lang != NULL)
9056 _config->Set("APT::Acquire::Translation", lang);
cb94ff21
JF
9057
9058 // XXX: this timeout might be important :(
9059 //_config->Set("Acquire::http::Timeout", 15);
9060
7623f855 9061 _config->Set("Acquire::http::MaxParallel", 3);
59dbe296 9062 /* }}} */
7376b55c 9063 /* Color Choices {{{ */
36bb2ca2
JF
9064 space_ = CGColorSpaceCreateDeviceRGB();
9065
f641a0e5 9066 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
77fcccaf 9067 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
36bb2ca2 9068 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
baf80942 9069 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
36bb2ca2 9070 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
7b0ce2da 9071 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
3bd1c2a2
JF
9072 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9073 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9074 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
59dbe296 9075
dc63e78f
JF
9076 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9077 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
7376b55c 9078 /* }}}*/
7376b55c 9079 /* UIKit Configuration {{{ */
f79a4512
JF
9080 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9081 if ($GSFontSetUseLegacyFontMetrics != NULL)
9082 $GSFontSetUseLegacyFontMetrics(YES);
7b0ce2da 9083
600d005d
JF
9084 // XXX: I have a feeling this was important
9085 //UIKeyboardDisableAutomaticAppearance();
7376b55c 9086 /* }}} */
87f46a96 9087
670a0494 9088 Colon_ = UCLocalize("COLON_DELIMITED");
72fb3616 9089 Elision_ = UCLocalize("ELISION");
670a0494
JF
9090 Error_ = UCLocalize("ERROR");
9091 Warning_ = UCLocalize("WARNING");
9092
d6dad1b4 9093 _trace();
77df4f82 9094 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
36bb2ca2
JF
9095
9096 CGColorSpaceRelease(space_);
199d0ba5 9097 CFRelease(Locale_);
36bb2ca2 9098
36bb2ca2 9099 return value;
6d166849 9100}