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