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