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