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