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