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