]> git.saurik.com Git - cydia.git/blame - MobileCydia.mm
Update Default-*.png for iPad with UITableView.
[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
fe8e721f
GP
4519- (void) loadView {
4520 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
65ea9562
JF
4521
4522 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4523 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4524 [[self view] addSubview:table];
fe8e721f 4525
a4a27fd0 4526 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
fe8e721f
GP
4527 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4528 [[self view] addSubview:indicator_];
4529
a4a27fd0 4530 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
fe8e721f
GP
4531 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4532 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4533 [[self view] addSubview:tabbar_];
4534
a4a27fd0 4535 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
fe8e721f
GP
4536 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4537 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4538 [[self view] addSubview:navbar_];
4539}
4540
4541- (void) releaseSubviews {
fe8e721f 4542 indicator_ = nil;
fe8e721f 4543 tabbar_ = nil;
fe8e721f 4544 navbar_ = nil;
f6e13561
GP
4545}
4546
f6e13561 4547@end
dd5f8161
GP
4548/* }}} */
4549
80319240 4550/* Cydia Browser Controller {{{ */
40bfa2e6 4551@interface CYBrowserController : BrowserController {
43f3d7f6
JF
4552 CydiaObject *cydia_;
4553}
a9a0661e 4554
43f3d7f6
JF
4555@end
4556
b5e7eebb 4557@implementation CYBrowserController
43f3d7f6
JF
4558
4559- (void) dealloc {
4560 [cydia_ release];
4561 [super dealloc];
4562}
4563
fe8e721f
GP
4564- (NSURL *) navigationURL {
4565 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4566}
4567
2634b249
JF
4568- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4569 [super webView:view didClearWindowObject:window forFrame:frame];
01d93940
JF
4570
4571 WebDataSource *source([frame dataSource]);
4572 NSURLResponse *response([source response]);
4573 NSURL *url([response URL]);
8804004f 4574
61c10d56
JF
4575 if ([[[url scheme] lowercaseString] isEqualToString:@"https"])
4576 if ([CydiaHosts_ containsObject:[url host]])
8804004f 4577 [window setValue:cydia_ forKey:@"cydia"];
43f3d7f6
JF
4578}
4579
9d1bf666
JF
4580- (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4581 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4582
bfc87a4d 4583 if (System_ != NULL)
9d1bf666 4584 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
43f3d7f6 4585 if (Machine_ != NULL)
9d1bf666 4586 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
01d93940 4587 if (Token_ != nil)
9d1bf666 4588 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
43f3d7f6
JF
4589
4590 return copy;
a9a0661e
JF
4591}
4592
77801ff1
JF
4593- (void) setDelegate:(id)delegate {
4594 [super setDelegate:delegate];
4595 [cydia_ setDelegate:delegate];
4596}
4597
b5e7eebb 4598- (id) init {
6d166849 4599 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
43f3d7f6
JF
4600 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4601
2634b249 4602 WebView *webview([[webview_ _documentView] webView]);
43f3d7f6 4603
44c1771c 4604 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
43f3d7f6 4605
43f3d7f6 4606 if (Safari_ != nil)
9ef18597 4607 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
35bf217f 4608 if (Build_ != nil)
9ef18597 4609 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
35bf217f 4610 if (Product_ != nil)
9ef18597 4611 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
43f3d7f6
JF
4612
4613 [webview setApplicationNameForUserAgent:application];
4614 } return self;
4615}
4616
4617@end
80319240 4618/* }}} */
43f3d7f6 4619
b1ca831d
JF
4620// CydiaScript {{{
4621@interface NSObject (CydiaScript)
4622- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4623@end
4624
4625@implementation NSObject (CydiaScript)
4626
4627- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4628 return self;
4629}
4630
4631@end
4632
4633@implementation NSArray (CydiaScript)
4634
4635- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4636 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4637 for (size_t i(0), e([self count]); i != e; ++i)
4638 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4639 return object;
4640}
4641
4642@end
4643
4644@implementation NSDictionary (CydiaScript)
4645
4646- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4647 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4648 for (id i in self)
4649 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4650 return object;
4651}
4652
4653@end
4654// }}}
4655
5829aea2
GP
4656/* Confirmation Controller {{{ */
4657bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4658 if (!iterator.end())
4659 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4660 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4661 continue;
4662 pkgCache::PkgIterator package(dep.TargetPkg());
4663 if (package.end())
4664 continue;
4665 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4666 return true;
4667 }
4668
4669 return false;
4670}
4671
adb61bda 4672@protocol ConfirmationControllerDelegate
674dce72 4673- (void) cancelAndClear:(bool)clear;
b5e7eebb 4674- (void) confirmWithNavigationController:(UINavigationController *)navigation;
dc63e78f 4675- (void) queue;
36bb2ca2 4676@end
2367a917 4677
adb61bda 4678@interface ConfirmationController : CYBrowserController {
770f2a8e 4679 _transient Database *database_;
6ceb0959 4680
3272e699 4681 UIAlertView *essential_;
6ceb0959
JF
4682
4683 NSDictionary *changes_;
4684 NSMutableArray *issues_;
4685 NSDictionary *sizes_;
4686
a9a0661e 4687 BOOL substrate_;
36bb2ca2 4688}
dc5812ec 4689
b5e7eebb 4690- (id) initWithDatabase:(Database *)database;
b4d89997 4691
dc5812ec
JF
4692@end
4693
adb61bda 4694@implementation ConfirmationController
dc5812ec 4695
2367a917 4696- (void) dealloc {
affeffc7 4697 [changes_ release];
6ceb0959 4698 [issues_ release];
affeffc7 4699 [sizes_ release];
6ceb0959 4700
36bb2ca2
JF
4701 if (essential_ != nil)
4702 [essential_ release];
6ceb0959 4703
2367a917
JF
4704 [super dealloc];
4705}
4706
ab2cfc1e
JF
4707- (void) complete {
4708 if (substrate_)
be860cc8 4709 RestartSubstrate_ = true;
ab2cfc1e
JF
4710 [delegate_ confirmWithNavigationController:[self navigationController]];
4711}
4712
b5e7eebb 4713- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3272e699 4714 NSString *context([alert context]);
9bedffaa 4715
1cedb821 4716 if ([context isEqualToString:@"remove"]) {
ab2cfc1e 4717 if (button == [alert cancelButtonIndex])
b5e7eebb 4718 [self dismissModalViewControllerAnimated:YES];
ab2cfc1e
JF
4719 else if (button == [alert firstOtherButtonIndex]) {
4720 [self complete];
9bedffaa 4721 }
9bedffaa 4722
3272e699 4723 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 4724 } else if ([context isEqualToString:@"unable"]) {
b5e7eebb 4725 [self dismissModalViewControllerAnimated:YES];
3272e699
GP
4726 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4727 } else {
b5e7eebb
GP
4728 [super alertView:alert clickedButtonAtIndex:button];
4729 }
36bb2ca2
JF
4730}
4731
46c46f4f 4732- (void) _doContinue {
21ea11a4
GP
4733 [self dismissModalViewControllerAnimated:YES];
4734 [delegate_ cancelAndClear:NO];
46c46f4f 4735}
bc11cf5b 4736
46c46f4f
JF
4737- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4738 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
21ea11a4
GP
4739 return nil;
4740}
4741
2634b249
JF
4742- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4743 [super webView:view didClearWindowObject:window forFrame:frame];
6ceb0959 4744
781001d7
JF
4745 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4746 changes_, @"changes",
4747 issues_, @"issues",
4748 sizes_, @"sizes",
4749 self, @"queue",
4750 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
36bb2ca2
JF
4751}
4752
b5e7eebb
GP
4753- (id) initWithDatabase:(Database *)database {
4754 if ((self = [super init]) != nil) {
770f2a8e
JF
4755 database_ = database;
4756
6ceb0959
JF
4757 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4758 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4759 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4760 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4761 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
dc5812ec 4762
36bb2ca2 4763 bool remove(false);
dc5812ec 4764
6ceb0959
JF
4765 pkgCacheFile &cache([database_ cache]);
4766 NSArray *packages([database_ packages]);
a9a0661e
JF
4767 pkgDepCache::Policy *policy([database_ policy]);
4768
6ceb0959
JF
4769 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4770
c4dcf2c2 4771 for (Package *package in packages) {
6ceb0959
JF
4772 pkgCache::PkgIterator iterator([package iterator]);
4773 NSString *name([package id]);
4774
4775 if ([package broken]) {
4776 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4777
4778 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4779 name, @"package",
4780 reasons, @"reasons",
4781 nil]];
4782
4783 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4784 if (ver.end())
4785 continue;
4786
4787 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4788 pkgCache::DepIterator start;
4789 pkgCache::DepIterator end;
4790 dep.GlobOr(start, end); // ++dep
4791
4792 if (!cache->IsImportantDep(end))
4793 continue;
4794 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4795 continue;
4796
810c9763
JF
4797 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4798
4799 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4800 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4801 clauses, @"clauses",
4802 nil]];
4803
6ceb0959
JF
4804 _forever {
4805 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4806
4807 pkgCache::PkgIterator target(start.TargetPkg());
4808 if (target->ProvidesList != 0)
4809 reason = @"missing";
4810 else {
4811 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4812 if (!ver.end()) {
4813 reason = @"installed";
4814 installed = [NSString stringWithUTF8String:ver.VerStr()];
4815 } else if (!cache[target].CandidateVerIter(cache).end())
4816 reason = @"uninstalled";
4817 else if (target->ProvidesList == 0)
4818 reason = @"uninstallable";
4819 else
4820 reason = @"virtual";
4821 }
4822
4823 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4824 [NSString stringWithUTF8String:start.CompType()], @"operator",
4825 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4826 nil]);
4827
810c9763 4828 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
6ceb0959
JF
4829 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4830 version, @"version",
4831 reason, @"reason",
4832 installed, @"installed",
4833 nil]];
4834
4835 // yes, seriously. (wtf?)
4836 if (start == end)
4837 break;
4838 ++start;
4839 }
4840 }
4841 }
4842
36bb2ca2 4843 pkgDepCache::StateCache &state(cache[iterator]);
dc5812ec 4844
6ceb0959 4845 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
2388b078 4846
36bb2ca2 4847 if (state.NewInstall())
6ceb0959 4848 [installs addObject:name];
36bb2ca2 4849 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
6ceb0959 4850 [reinstalls addObject:name];
36bb2ca2 4851 else if (state.Upgrade())
6ceb0959 4852 [upgrades addObject:name];
36bb2ca2 4853 else if (state.Downgrade())
6ceb0959
JF
4854 [downgrades addObject:name];
4855 else if (!state.Delete())
4856 continue;
1916f316
JF
4857 else if (special_r(name))
4858 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4859 [NSNull null], @"package",
4860 [NSArray arrayWithObjects:
4861 [NSDictionary dictionaryWithObjectsAndKeys:
810c9763
JF
4862 @"Conflicts", @"relationship",
4863 [NSArray arrayWithObjects:
4864 [NSDictionary dictionaryWithObjectsAndKeys:
4865 name, @"package",
4866 [NSNull null], @"version",
4867 @"installed", @"reason",
4868 nil],
4869 nil], @"clauses",
1916f316
JF
4870 nil],
4871 nil], @"reasons",
4872 nil]];
4873 else {
2388b078 4874 if ([package essential])
36bb2ca2 4875 remove = true;
6ceb0959
JF
4876 [removes addObject:name];
4877 }
a9a0661e
JF
4878
4879 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4880 substrate_ |= DepSubstrate(iterator.CurrentVer());
36bb2ca2 4881 }
ec97ef06 4882
36bb2ca2
JF
4883 if (!remove)
4884 essential_ = nil;
d791dce4 4885 else if (Advanced_) {
43f3d7f6 4886 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
f79a4512 4887
3272e699 4888 essential_ = [[UIAlertView alloc]
43f3d7f6 4889 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
b5e7eebb
GP
4890 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4891 delegate:self
4892 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
1aa29546
JF
4893 otherButtonTitles:
4894 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4895 nil
b5e7eebb 4896 ];
04fe1349 4897
3272e699 4898 [essential_ setContext:@"remove"];
9bedffaa 4899 } else {
3272e699 4900 essential_ = [[UIAlertView alloc]
43f3d7f6 4901 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
b5e7eebb
GP
4902 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4903 delegate:self
4904 cancelButtonTitle:UCLocalize("OKAY")
4905 otherButtonTitles:nil
36bb2ca2 4906 ];
ec97ef06 4907
b5e7eebb 4908 [essential_ setContext:@"unable"];
36bb2ca2 4909 }
ec97ef06 4910
6ceb0959
JF
4911 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4912 installs, @"installs",
4913 reinstalls, @"reinstalls",
4914 upgrades, @"upgrades",
4915 downgrades, @"downgrades",
4916 removes, @"removes",
affeffc7 4917 nil];
dc5812ec 4918
6ceb0959
JF
4919 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4920 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4921 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
affeffc7 4922 nil];
dc5812ec 4923
90351d93 4924 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
04fe1349 4925
dd9de556 4926 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
21c6da4b 4927 initWithTitle:UCLocalize("CANCEL")
b5e7eebb
GP
4928 style:UIBarButtonItemStylePlain
4929 target:self
4930 action:@selector(cancelButtonClicked)
dd9de556 4931 ] autorelease]];
36bb2ca2 4932 } return self;
b4d89997 4933}
8da60fb7 4934
614cd4f1 4935#if !AlwaysReload
bcde1e70 4936- (void) applyRightButton {
6ceb0959 4937 if ([issues_ count] == 0 && ![self isLoading])
dd9de556
JF
4938 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4939 initWithTitle:UCLocalize("CONFIRM")
2761d574 4940 style:UIBarButtonItemStyleDone
dd9de556
JF
4941 target:self
4942 action:@selector(confirmButtonClicked)
4943 ] autorelease]];
4944 else
bcde1e70 4945 [[self navigationItem] setRightBarButtonItem:nil];
affeffc7 4946}
bcde1e70 4947#endif
affeffc7 4948
b5e7eebb 4949- (void) cancelButtonClicked {
21ea11a4
GP
4950 [self dismissModalViewControllerAnimated:YES];
4951 [delegate_ cancelAndClear:YES];
affeffc7
JF
4952}
4953
9487f027 4954#if !AlwaysReload
b5e7eebb 4955- (void) confirmButtonClicked {
affeffc7 4956 if (essential_ != nil)
b5e7eebb 4957 [essential_ show];
ab2cfc1e
JF
4958 else
4959 [self complete];
affeffc7 4960}
9487f027 4961#endif
affeffc7 4962
36bb2ca2
JF
4963@end
4964/* }}} */
8da60fb7 4965
aaae308d
JF
4966/* Progress Data {{{ */
4967@interface CydiaProgressData : NSObject {
4968 _transient id delegate_;
4969
4970 bool running_;
b0b11d99 4971 float percent_;
aaae308d 4972
bcbac8f7
JF
4973 float current_;
4974 float total_;
4975 float speed_;
4976
aaae308d
JF
4977 _H<NSMutableArray> events_;
4978 _H<NSString> title_;
4979
4980 _H<NSString> status_;
4981 _H<NSString> finish_;
4982}
4983
4984@end
4985
4986@implementation CydiaProgressData
4987
4988+ (NSArray *) _attributeKeys {
4989 return [NSArray arrayWithObjects:
bcbac8f7 4990 @"current",
aaae308d
JF
4991 @"events",
4992 @"finish",
b0b11d99 4993 @"percent",
aaae308d 4994 @"running",
bcbac8f7 4995 @"speed",
aaae308d 4996 @"title",
bcbac8f7 4997 @"total",
aaae308d
JF
4998 nil];
4999}
5000
5001- (NSArray *) attributeKeys {
5002 return [[self class] _attributeKeys];
5003}
5004
5005+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5006 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5007}
5008
5009- (id) init {
5010 if ((self = [super init]) != nil) {
5011 events_ = [NSMutableArray arrayWithCapacity:32];
5012 } return self;
5013}
5014
5015- (void) setDelegate:(id)delegate {
5016 delegate_ = delegate;
5017}
5018
b0b11d99
JF
5019- (void) setPercent:(float)value {
5020 percent_ = value;
aaae308d
JF
5021}
5022
b0b11d99
JF
5023- (NSNumber *) percent {
5024 return [NSNumber numberWithFloat:percent_];
aaae308d
JF
5025}
5026
bcbac8f7
JF
5027- (void) setCurrent:(float)value {
5028 current_ = value;
5029}
5030
5031- (NSNumber *) current {
5032 return [NSNumber numberWithFloat:current_];
5033}
5034
5035- (void) setTotal:(float)value {
5036 total_ = value;
5037}
5038
5039- (NSNumber *) total {
5040 return [NSNumber numberWithFloat:total_];
5041}
5042
5043- (void) setSpeed:(float)value {
5044 speed_ = value;
5045}
5046
5047- (NSNumber *) speed {
5048 return [NSNumber numberWithFloat:speed_];
5049}
5050
aaae308d
JF
5051- (NSArray *) events {
5052 return events_;
5053}
5054
5055- (void) removeAllEvents {
5056 [events_ removeAllObjects];
5057}
5058
5059- (void) addEvent:(CydiaProgressEvent *)event {
5060 [events_ addObject:event];
5061}
5062
5063- (void) setTitle:(NSString *)text {
5064 title_ = text;
5065}
5066
5067- (NSString *) title {
5068 return title_;
5069}
5070
5071- (void) setFinish:(NSString *)text {
5072 finish_ = text;
5073}
5074
5075- (NSString *) finish {
5076 return (id) finish_ ?: [NSNull null];
5077}
5078
5079- (void) setRunning:(bool)running {
5080 running_ = running;
5081}
5082
5083- (NSNumber *) running {
5084 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5085}
5086
5087@end
5088/* }}} */
adb61bda 5089/* Progress Controller {{{ */
aaae308d 5090@interface ProgressController : CYBrowserController <
36bb2ca2
JF
5091 ProgressDelegate
5092> {
8b29f8e6 5093 _transient Database *database_;
aaae308d
JF
5094 _H<CydiaProgressData> progress_;
5095 unsigned cancel_;
2367a917
JF
5096}
5097
b5e7eebb 5098- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
2367a917 5099
6915b806 5100- (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
2367a917 5101
6915b806 5102- (void) setTitle:(NSString *)title;
aaae308d 5103- (void) setCancellable:(bool)cancellable;
bd150f54 5104
36bb2ca2
JF
5105@end
5106
adb61bda 5107@implementation ProgressController
2367a917
JF
5108
5109- (void) dealloc {
6915b806 5110 [database_ setProgressDelegate:nil];
aaae308d 5111 [progress_ setDelegate:nil];
2367a917
JF
5112 [super dealloc];
5113}
5114
3c62d654
JF
5115- (void) updateCancel {
5116 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5117 initWithTitle:UCLocalize("CANCEL")
5118 style:UIBarButtonItemStylePlain
5119 target:self
5120 action:@selector(cancel)
5121 ] autorelease] : nil)];
5122}
5123
b5e7eebb
GP
5124- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5125 if ((self = [super init]) != nil) {
8b29f8e6 5126 database_ = database;
36bb2ca2 5127 delegate_ = delegate;
ec97ef06 5128
6915b806
JF
5129 [database_ setProgressDelegate:self];
5130
aaae308d
JF
5131 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5132 [progress_ setDelegate:self];
3c62d654 5133
90351d93 5134 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
3c62d654
JF
5135
5136 [scroller_ setBackgroundColor:[UIColor blackColor]];
5137
5138 [[self navigationItem] setHidesBackButton:YES];
5139
5140 [self updateCancel];
36bb2ca2 5141 } return self;
2367a917
JF
5142}
5143
aaae308d
JF
5144- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5145 [super webView:view didClearWindowObject:window forFrame:frame];
5146 [window setValue:progress_ forKey:@"cydiaProgress"];
5147}
bc11cf5b 5148
aaae308d
JF
5149- (void) updateProgress {
5150 [self dispatchEvent:@"CydiaProgressUpdate"];
5151}
b5e7eebb 5152
b5e7eebb 5153- (void) viewWillAppear:(BOOL)animated {
3c62d654
JF
5154 if (![self hasLoaded])
5155 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
2367a917 5156
3c62d654 5157 [super viewWillAppear:animated];
2367a917
JF
5158}
5159
aaae308d 5160- (void) close {
ef494bd8
RP
5161 UpdateExternalStatus(0);
5162
670a0494
JF
5163 switch (Finish_) {
5164 case 0:
670a0494
JF
5165 break;
5166
5167 case 1:
c4899376
JF
5168 [delegate_ terminateWithSuccess];
5169 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5170 [delegate_ suspendWithAnimation:YES];
5171 else
5172 [delegate_ suspend];*/
670a0494
JF
5173 break;
5174
5175 case 2:
985d2dff 5176 _trace();
ef812071 5177 goto reload;
670a0494
JF
5178
5179 case 3:
985d2dff 5180 _trace();
ef812071
JF
5181 goto reload;
5182
5183 reload:
5184 system("/usr/bin/sbreload");
985d2dff 5185 _trace();
670a0494
JF
5186 break;
5187
5188 case 4:
985d2dff 5189 _trace();
0e371502
JF
5190 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5191 SBReboot(SBSSpringBoardServerPort());
5192 else
bb0fe3c9 5193 reboot2(RB_AUTOBOOT);
670a0494 5194 break;
bc8cd583 5195 }
aaae308d
JF
5196
5197 [super close];
670a0494 5198}
bd150f54 5199
6915b806 5200- (void) setTitle:(NSString *)title {
aaae308d
JF
5201 [progress_ setTitle:title];
5202 [self updateProgress];
5203}
5204
5205- (UIBarButtonItem *) rightButton {
380d0443 5206 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
aaae308d
JF
5207 initWithTitle:UCLocalize("CLOSE")
5208 style:UIBarButtonItemStylePlain
5209 target:self
5210 action:@selector(close)
5211 ] autorelease];
6915b806
JF
5212}
5213
5214- (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5215 UpdateExternalStatus(1);
5216
aaae308d 5217 [progress_ setRunning:true];
6915b806 5218 [self setTitle:title];
aaae308d 5219 // implicit updateProgress
6915b806 5220
140710ba 5221 SHA1SumValue notifyconf; {
6915b806
JF
5222 FileFd file;
5223 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5224 _error->Discard();
5225 else {
5226 MMap mmap(file, MMap::ReadOnly);
5227 SHA1Summation sha1;
5228 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
140710ba 5229 notifyconf = sha1.Result();
6915b806
JF
5230 }
5231 }
5232
140710ba 5233 SHA1SumValue springlist; {
6915b806
JF
5234 FileFd file;
5235 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5236 _error->Discard();
5237 else {
5238 MMap mmap(file, MMap::ReadOnly);
5239 SHA1Summation sha1;
5240 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
140710ba 5241 springlist = sha1.Result();
6915b806
JF
5242 }
5243 }
5244
5245 if (invocation != nil) {
5246 [invocation yieldToSelector:@selector(invoke)];
aaae308d 5247 [self setTitle:@"COMPLETE"];
6915b806 5248 }
670a0494 5249
22f8bed9 5250 if (Finish_ < 4) {
70d45c1e
JF
5251 FileFd file;
5252 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5253 _error->Discard();
5254 else {
5255 MMap mmap(file, MMap::ReadOnly);
5256 SHA1Summation sha1;
5257 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
140710ba 5258 if (!(notifyconf == sha1.Result()))
70d45c1e
JF
5259 Finish_ = 4;
5260 }
22f8bed9
JF
5261 }
5262
affeffc7 5263 if (Finish_ < 3) {
70d45c1e
JF
5264 FileFd file;
5265 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5266 _error->Discard();
5267 else {
5268 MMap mmap(file, MMap::ReadOnly);
5269 SHA1Summation sha1;
5270 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
140710ba 5271 if (!(springlist == sha1.Result()))
70d45c1e
JF
5272 Finish_ = 3;
5273 }
dddbc481
JF
5274 }
5275
be860cc8
JF
5276 if (Finish_ < 2) {
5277 if (RestartSubstrate_)
5278 Finish_ = 2;
5279 }
5280
5281 RestartSubstrate_ = false;
5282
bc8cd583 5283 switch (Finish_) {
aaae308d
JF
5284 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5285 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5286 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5287 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5288 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
bc8cd583
JF
5289 }
5290
985d2dff 5291 _trace();
58241d4c 5292 system("su -c /usr/bin/uicache mobile");
985d2dff 5293 _trace();
c4ce98df 5294
eb403f34 5295 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
ef494bd8 5296
aaae308d
JF
5297 [progress_ setRunning:false];
5298 [self updateProgress];
5299
5300 [self applyRightButton];
31f3cfff
JF
5301}
5302
6915b806 5303- (void) addProgressEvent:(CydiaProgressEvent *)event {
aaae308d
JF
5304 [progress_ addEvent:event];
5305 [self updateProgress];
baf80942
JF
5306}
5307
ff2d5dcd 5308- (bool) isProgressCancelled {
aaae308d
JF
5309 return cancel_ == 2;
5310}
5311
5312- (void) cancel {
5313 cancel_ = 2;
5314 [self updateCancel];
5315}
5316
5317- (void) setCancellable:(bool)cancellable {
5318 unsigned cancel(cancel_);
5319
5320 if (!cancellable)
5321 cancel_ = 0;
5322 else if (cancel_ == 0)
5323 cancel_ = 1;
5324
5325 if (cancel != cancel_)
5326 [self updateCancel];
5327}
5328
5329- (void) setProgressCancellable:(NSNumber *)cancellable {
5330 [self setCancellable:[cancellable boolValue]];
baf80942
JF
5331}
5332
d885343d 5333- (void) setProgressPercent:(NSNumber *)percent {
b0b11d99 5334 [progress_ setPercent:[percent floatValue]];
aaae308d 5335 [self updateProgress];
49048579
JF
5336}
5337
bcbac8f7
JF
5338- (void) setProgressStatus:(NSDictionary *)status {
5339 if (status == nil) {
5340 [progress_ setCurrent:0];
5341 [progress_ setTotal:0];
5342 [progress_ setSpeed:0];
5343 } else {
5344 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5345
5346 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5347 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5348 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5349 }
5350
5351 [self updateProgress];
5352}
5353
36bb2ca2
JF
5354@end
5355/* }}} */
dc088e63 5356
46aa9775 5357/* Cell Content View {{{ */
c21004b9
JF
5358@protocol ContentDelegate
5359- (void) drawContentRect:(CGRect)rect;
5360@end
5361
327624b6 5362@interface ContentView : UIView {
c21004b9 5363 _transient id<ContentDelegate> delegate_;
327624b6
JF
5364}
5365
5366@end
5367
46aa9775 5368@implementation ContentView
555aaf71 5369
46aa9775
GP
5370- (id) initWithFrame:(CGRect)frame {
5371 if ((self = [super initWithFrame:frame]) != nil) {
46aa9775
GP
5372 [self setNeedsDisplayOnBoundsChange:YES];
5373 } return self;
5374}
5375
c21004b9 5376- (void) setDelegate:(id<ContentDelegate>)delegate {
46aa9775
GP
5377 delegate_ = delegate;
5378}
5379
5380- (void) drawRect:(CGRect)rect {
5381 [super drawRect:rect];
5382 [delegate_ drawContentRect:rect];
5383}
555aaf71
JF
5384
5385@end
5386/* }}} */
5387/* Cydia TableView Cell {{{ */
5388@interface CYTableViewCell : UITableViewCell {
5389 ContentView *content_;
5390 bool highlighted_;
5391}
5392
5393@end
5394
5395@implementation CYTableViewCell
5396
5397- (void) dealloc {
5398 [content_ release];
5399 [super dealloc];
5400}
5401
5402- (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5403 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5404
5405 if (view == content_) {
5406 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5407 highlighted_ = highlighted;
5408 }
5409
5410 [super _updateHighlightColorsForView:view highlighted:highlighted];
5411}
5412
5413- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5414 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5415 highlighted_ = selected;
5416
5417 [super setSelected:selected animated:animated];
5418 [content_ setNeedsDisplay];
5419}
5420
46aa9775
GP
5421@end
5422/* }}} */
5829aea2 5423
46aa9775 5424/* Package Cell {{{ */
555aaf71 5425@interface PackageCell : CYTableViewCell <
c21004b9
JF
5426 ContentDelegate
5427> {
f641a0e5
JF
5428 UIImage *icon_;
5429 NSString *name_;
5430 NSString *description_;
3bd1c2a2 5431 bool commercial_;
f641a0e5 5432 NSString *source_;
c390d3ab 5433 UIImage *badge_;
dc63e78f 5434 Package *package_;
670a0494 5435 UIImage *placard_;
36bb2ca2 5436}
723a0072 5437
36bb2ca2
JF
5438- (PackageCell *) init;
5439- (void) setPackage:(Package *)package;
ec97ef06 5440
327624b6
JF
5441- (void) drawContentRect:(CGRect)rect;
5442
5443@end
5444
36bb2ca2
JF
5445@implementation PackageCell
5446
f641a0e5
JF
5447- (void) clearPackage {
5448 if (icon_ != nil) {
5449 [icon_ release];
5450 icon_ = nil;
5451 }
5452
5453 if (name_ != nil) {
5454 [name_ release];
5455 name_ = nil;
5456 }
5457
5458 if (description_ != nil) {
5459 [description_ release];
5460 description_ = nil;
5461 }
5462
5463 if (source_ != nil) {
5464 [source_ release];
5465 source_ = nil;
5466 }
c390d3ab
JF
5467
5468 if (badge_ != nil) {
5469 [badge_ release];
5470 badge_ = nil;
5471 }
dc63e78f 5472
670a0494
JF
5473 if (placard_ != nil) {
5474 [placard_ release];
5475 placard_ = nil;
5476 }
5477
dc63e78f
JF
5478 [package_ release];
5479 package_ = nil;
f641a0e5
JF
5480}
5481
36bb2ca2 5482- (void) dealloc {
f641a0e5 5483 [self clearPackage];
36bb2ca2 5484 [super dealloc];
b4d89997 5485}
b19871dd 5486
36bb2ca2 5487- (PackageCell *) init {
327624b6
JF
5488 CGRect frame(CGRectMake(0, 0, 320, 74));
5489 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5490 UIView *content([self contentView]);
5491 CGRect bounds([content bounds]);
04fe1349 5492
327624b6 5493 content_ = [[ContentView alloc] initWithFrame:bounds];
04fe1349
JF
5494 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5495 [content addSubview:content_];
5496
327624b6 5497 [content_ setDelegate:self];
327624b6 5498 [content_ setOpaque:YES];
36bb2ca2 5499 } return self;
b4d89997 5500}
b19871dd 5501
003fc610
GP
5502- (NSString *) accessibilityLabel {
5503 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5504}
5505
36bb2ca2 5506- (void) setPackage:(Package *)package {
46dbfd32 5507 [self clearPackage];
68d927e2 5508 [package parse];
31f3cfff 5509
36bb2ca2 5510 Source *source = [package source];
b19871dd 5511
770f2a8e 5512 icon_ = [[package icon] retain];
f641a0e5 5513 name_ = [[package name] retain];
ef055c6c
JF
5514
5515 if (IsWildcat_)
5516 description_ = [package longDescription];
5517 if (description_ == nil)
5518 description_ = [package shortDescription];
5519 if (description_ != nil)
5520 description_ = [description_ retain];
5521
3bd1c2a2 5522 commercial_ = [package isCommercial];
36bb2ca2 5523
dc63e78f
JF
5524 package_ = [package retain];
5525
a54b1c10
JF
5526 NSString *label = nil;
5527 bool trusted = false;
b19871dd 5528
36bb2ca2
JF
5529 if (source != nil) {
5530 label = [source label];
5531 trusted = [source trusted];
a54b1c10 5532 } else if ([[package id] isEqualToString:@"firmware"])
43f3d7f6 5533 label = UCLocalize("APPLE");
7b0ce2da 5534 else
43f3d7f6 5535 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
b19871dd 5536
f79a4512 5537 NSString *from(label);
a54b1c10 5538
f79a4512
JF
5539 NSString *section = [package simpleSection];
5540 if (section != nil && ![section isEqualToString:label]) {
5541 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
43f3d7f6 5542 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
f79a4512 5543 }
a54b1c10 5544
43f3d7f6 5545 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
f641a0e5 5546 source_ = [from retain];
36bb2ca2 5547
c390d3ab
JF
5548 if (NSString *purpose = [package primaryPurpose])
5549 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5550 badge_ = [badge_ retain];
5551
d832908d
JF
5552 UIColor *color;
5553 NSString *placard;
5554
5555 if (NSString *mode = [package_ mode]) {
5556 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5557 color = RemovingColor_;
5558 //placard = @"removing";
5559 } else {
5560 color = InstallingColor_;
5561 //placard = @"installing";
5562 }
5563
5564 // XXX: the removing/installing placards are not @2x
5565 placard = nil;
5566 } else {
5567 color = [UIColor whiteColor];
5568
5569 if ([package installed] != nil)
5570 placard = @"installed";
5571 else
5572 placard = nil;
5573 }
5574
5575 [content_ setBackgroundColor:color];
5576
5577 if (placard != nil)
5578 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
670a0494
JF
5579 placard_ = [placard_ retain];
5580
d832908d 5581 [self setNeedsDisplay];
327624b6 5582 [content_ setNeedsDisplay];
3bd1c2a2
JF
5583}
5584
327624b6 5585- (void) drawContentRect:(CGRect)rect {
555aaf71 5586 bool highlighted(highlighted_);
ef055c6c 5587 float width([self bounds].size.width);
dc63e78f 5588
327624b6
JF
5589#if 0
5590 CGContextRef context(UIGraphicsGetCurrentContext());
5591 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5592 CGContextFillRect(context, rect);
5593#endif
b19871dd 5594
baf80942
JF
5595 if (icon_ != nil) {
5596 CGRect rect;
5597 rect.size = [icon_ size];
5598
5599 rect.size.width /= 2;
5600 rect.size.height /= 2;
5601
5602 rect.origin.x = 25 - rect.size.width / 2;
5603 rect.origin.y = 25 - rect.size.height / 2;
5604
5605 [icon_ drawInRect:rect];
5606 }
b19871dd 5607
c390d3ab 5608 if (badge_ != nil) {
f79c810d
JF
5609 CGRect rect;
5610 rect.size = [badge_ size];
5611
5612 rect.size.width /= 2;
5613 rect.size.height /= 2;
5614
5615 rect.origin.x = 36 - rect.size.width / 2;
5616 rect.origin.y = 36 - rect.size.height / 2;
c390d3ab 5617
f79c810d 5618 [badge_ drawInRect:rect];
c390d3ab
JF
5619 }
5620
555aaf71 5621 if (highlighted)
f641a0e5 5622 UISetColor(White_);
b19871dd 5623
555aaf71 5624 if (!highlighted)
3bd1c2a2 5625 UISetColor(commercial_ ? Purple_ : Black_);
54b844a0
DH
5626 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5627 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
b19871dd 5628
555aaf71 5629 if (!highlighted)
3bd1c2a2 5630 UISetColor(commercial_ ? Purplish_ : Gray_);
54b844a0 5631 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
670a0494
JF
5632
5633 if (placard_ != nil)
01d93940 5634 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
ec97ef06
JF
5635}
5636
8da60fb7
JF
5637@end
5638/* }}} */
36bb2ca2 5639/* Section Cell {{{ */
555aaf71 5640@interface SectionCell : CYTableViewCell <
c21004b9
JF
5641 ContentDelegate
5642> {
0010fa77 5643 NSString *basic_;
6d9712c4 5644 NSString *section_;
f641a0e5
JF
5645 NSString *name_;
5646 NSString *count_;
5647 UIImage *icon_;
68046ccc 5648 UISwitch *switch_;
6d9712c4 5649 BOOL editing_;
b4d89997 5650}
b19871dd 5651
6d9712c4 5652- (void) setSection:(Section *)section editing:(BOOL)editing;
36bb2ca2 5653
8da60fb7
JF
5654@end
5655
36bb2ca2 5656@implementation SectionCell
8da60fb7 5657
f641a0e5 5658- (void) clearSection {
0010fa77 5659 if (basic_ != nil) {
e59669fd 5660 [basic_ release];
0010fa77
JF
5661 basic_ = nil;
5662 }
5663
f641a0e5 5664 if (section_ != nil) {
6d9712c4 5665 [section_ release];
f641a0e5
JF
5666 section_ = nil;
5667 }
7b0ce2da 5668
f641a0e5
JF
5669 if (name_ != nil) {
5670 [name_ release];
5671 name_ = nil;
5672 }
7b0ce2da 5673
f641a0e5
JF
5674 if (count_ != nil) {
5675 [count_ release];
5676 count_ = nil;
5677 }
7b0ce2da
JF
5678}
5679
f641a0e5
JF
5680- (void) dealloc {
5681 [self clearSection];
5682 [icon_ release];
5683 [switch_ release];
5684 [super dealloc];
7b0ce2da
JF
5685}
5686
46aa9775
GP
5687- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5688 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
f641a0e5 5689 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
68046ccc 5690 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
46aa9775
GP
5691 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5692
5693 UIView *content([self contentView]);
5694 CGRect bounds([content bounds]);
5695
5696 content_ = [[ContentView alloc] initWithFrame:bounds];
5697 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5698 [content addSubview:content_];
5699 [content_ setBackgroundColor:[UIColor whiteColor]];
5700
5701 [content_ setDelegate:self];
b4d89997 5702 } return self;
b19871dd
JF
5703}
5704
6d9712c4 5705- (void) onSwitch:(id)sender {
a171abd4 5706 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6d9712c4
JF
5707 if (metadata == nil) {
5708 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
0010fa77 5709 [Sections_ setObject:metadata forKey:basic_];
6d9712c4
JF
5710 }
5711
46aa9775 5712 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
a171abd4 5713 Changed_ = true;
6d9712c4
JF
5714}
5715
5716- (void) setSection:(Section *)section editing:(BOOL)editing {
5717 if (editing != editing_) {
5718 if (editing_)
5719 [switch_ removeFromSuperview];
5720 else
5721 [self addSubview:switch_];
5722 editing_ = editing;
5723 }
5724
f641a0e5 5725 [self clearSection];
6d9712c4 5726
36bb2ca2 5727 if (section == nil) {
43f3d7f6 5728 name_ = [UCLocalize("ALL_PACKAGES") retain];
f641a0e5 5729 count_ = nil;
36bb2ca2 5730 } else {
e59669fd 5731 basic_ = [section name];
0010fa77
JF
5732 if (basic_ != nil)
5733 basic_ = [basic_ retain];
5734
677b8415 5735 section_ = [section localized];
6d9712c4
JF
5736 if (section_ != nil)
5737 section_ = [section_ retain];
0010fa77 5738
43f3d7f6 5739 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
f641a0e5 5740 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
6d9712c4
JF
5741
5742 if (editing_)
46aa9775 5743 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
36bb2ca2 5744 }
46aa9775 5745
c21004b9 5746 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
0abb648c
JF
5747 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5748
46aa9775 5749 [content_ setNeedsDisplay];
f641a0e5
JF
5750}
5751
77801ff1
JF
5752- (void) setFrame:(CGRect)frame {
5753 [super setFrame:frame];
46aa9775 5754
77801ff1
JF
5755 CGRect rect([switch_ frame]);
5756 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5757}
5758
003fc610
GP
5759- (NSString *) accessibilityLabel {
5760 return name_;
5761}
5762
46aa9775 5763- (void) drawContentRect:(CGRect)rect {
8cfba088 5764 bool highlighted(highlighted_ && !editing_);
bc11cf5b 5765
f641a0e5
JF
5766 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5767
555aaf71 5768 if (highlighted)
f641a0e5
JF
5769 UISetColor(White_);
5770
46aa9775 5771 float width(rect.size.width);
58241d4c 5772 if (editing_)
46aa9775 5773 width -= 87;
58241d4c 5774
555aaf71
JF
5775 if (!highlighted)
5776 UISetColor(Black_);
54b844a0 5777 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
6d9712c4 5778
f641a0e5
JF
5779 CGSize size = [count_ sizeWithFont:Font14_];
5780
5781 UISetColor(White_);
5782 if (count_ != nil)
c390d3ab 5783 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
b19871dd
JF
5784}
5785
36bb2ca2
JF
5786@end
5787/* }}} */
b19871dd 5788
ab398adf 5789/* File Table {{{ */
c21004b9
JF
5790@interface FileTable : CYViewController <
5791 UITableViewDataSource,
5792 UITableViewDelegate
5793> {
36bb2ca2 5794 _transient Database *database_;
ab398adf
JF
5795 Package *package_;
5796 NSString *name_;
5797 NSMutableArray *files_;
46aa9775 5798 UITableView *list_;
ab398adf 5799}
b19871dd 5800
b5e7eebb 5801- (id) initWithDatabase:(Database *)database;
ab398adf
JF
5802- (void) setPackage:(Package *)package;
5803
5804@end
5805
5806@implementation FileTable
5807
5808- (void) dealloc {
fe8e721f
GP
5809 [self releaseSubviews];
5810
5811 [package_ release];
5812 [name_ release];
ab398adf 5813 [files_ release];
fe8e721f 5814
ab398adf
JF
5815 [super dealloc];
5816}
5817
eb30da80 5818- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
ab398adf
JF
5819 return files_ == nil ? 0 : [files_ count];
5820}
5821
21ea11a4
GP
5822/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5823 return 24.0f;
5824}*/
ab398adf 5825
46aa9775 5826- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
GP
5827 static NSString *reuseIdentifier = @"Cell";
5828
46aa9775
GP
5829 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5830 if (cell == nil) {
5831 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5832 [cell setFont:[UIFont systemFontOfSize:16]];
ab398adf 5833 }
46aa9775 5834 [cell setText:[files_ objectAtIndex:indexPath.row]];
c21004b9 5835 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
b5e7eebb 5836
46aa9775 5837 return cell;
ab398adf 5838}
b19871dd 5839
fe8e721f
GP
5840- (NSURL *) navigationURL {
5841 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5842}
5843
5844- (void) loadView {
5845 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5846
5847 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5848 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5849 [list_ setRowHeight:24.0f];
5850 [list_ setDataSource:self];
5851 [list_ setDelegate:self];
5852 [[self view] addSubview:list_];
5853}
5854
5855- (void) viewDidLoad {
5856 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5857}
5858
5859- (void) releaseSubviews {
5860 [list_ release];
5861 list_ = nil;
5862}
5863
b5e7eebb
GP
5864- (id) initWithDatabase:(Database *)database {
5865 if ((self = [super init]) != nil) {
ab398adf 5866 database_ = database;
b19871dd 5867
ab398adf 5868 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
ab398adf
JF
5869 } return self;
5870}
5871
5872- (void) setPackage:(Package *)package {
5873 if (package_ != nil) {
5874 [package_ autorelease];
5875 package_ = nil;
5876 }
5877
5878 if (name_ != nil) {
5879 [name_ release];
5880 name_ = nil;
5881 }
5882
5883 [files_ removeAllObjects];
5884
5885 if (package != nil) {
5886 package_ = [package retain];
5887 name_ = [[package id] retain];
5888
affeffc7
JF
5889 if (NSArray *files = [package files])
5890 [files_ addObjectsFromArray:files];
ab398adf 5891
9ea8d159
JF
5892 if ([files_ count] != 0) {
5893 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5894 [files_ removeObjectAtIndex:0];
a54b1c10 5895 [files_ sortUsingSelector:@selector(compareByPath:)];
2388b078
JF
5896
5897 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5898 [stack addObject:@"/"];
5899
5900 for (int i(0), e([files_ count]); i != e; ++i) {
5901 NSString *file = [files_ objectAtIndex:i];
5902 while (![file hasPrefix:[stack lastObject]])
5903 [stack removeLastObject];
5904 NSString *directory = [stack lastObject];
5905 [stack addObject:[file stringByAppendingString:@"/"]];
5906 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
a54b1c10 5907 ([stack count] - 2) * 3, "",
2388b078
JF
5908 [file substringFromIndex:[directory length]]
5909 ]];
5910 }
ab398adf
JF
5911 }
5912 }
5913
5914 [list_ reloadData];
5915}
5916
ab398adf 5917- (void) reloadData {
fe8e721f
GP
5918 [super reloadData];
5919
ab398adf 5920 [self setPackage:[database_ packageWithName:name_]];
ab398adf 5921}
b4d89997 5922
b4d89997 5923@end
36bb2ca2 5924/* }}} */
adb61bda 5925/* Package Controller {{{ */
f6e13561 5926@interface CYPackageController : CYBrowserController <
9daa7f25
DH
5927 UIActionSheetDelegate
5928> {
770f2a8e 5929 _transient Database *database_;
5d79f7bf
JF
5930 _H<Package> package_;
5931 _H<NSString> name_;
3bd1c2a2 5932 bool commercial_;
5d79f7bf
JF
5933 _H<NSMutableArray> buttons_;
5934 _H<UIBarButtonItem> button_;
b31b87cc
JF
5935}
5936
57e8b225 5937- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
b4d89997 5938
36bb2ca2 5939@end
b4d89997 5940
f6e13561 5941@implementation CYPackageController
b4d89997 5942
fe8e721f 5943- (NSURL *) navigationURL {
5d79f7bf 5944 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
fe8e721f
GP
5945}
5946
f79a4512 5947/* XXX: this is not safe at all... localization of /fail/ */
5a09ae08 5948- (void) _clickButtonWithName:(NSString *)name {
43f3d7f6 5949 if ([name isEqualToString:UCLocalize("CLEAR")])
dc63e78f 5950 [delegate_ clearPackage:package_];
43f3d7f6 5951 else if ([name isEqualToString:UCLocalize("INSTALL")])
5a09ae08 5952 [delegate_ installPackage:package_];
43f3d7f6 5953 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5a09ae08 5954 [delegate_ installPackage:package_];
43f3d7f6 5955 else if ([name isEqualToString:UCLocalize("REMOVE")])
5a09ae08 5956 [delegate_ removePackage:package_];
43f3d7f6 5957 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5a09ae08
JF
5958 [delegate_ installPackage:package_];
5959 else _assert(false);
5960}
5961
674dce72 5962- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
1cedb821 5963 NSString *context([sheet context]);
5a09ae08 5964
1cedb821 5965 if ([context isEqualToString:@"modify"]) {
674dce72
GP
5966 if (button != [sheet cancelButtonIndex]) {
5967 NSString *buttonName = [buttons_ objectAtIndex:button];
5968 [self _clickButtonWithName:buttonName];
5969 }
bc11cf5b 5970
674dce72 5971 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
674dce72 5972 }
b4d89997 5973}
2367a917 5974
3e9c9e85 5975- (bool) _allowJavaScriptPanel {
3bd1c2a2 5976 return commercial_;
3e9c9e85
JF
5977}
5978
9487f027 5979#if !AlwaysReload
9daa7f25 5980- (void) _customButtonClicked {
670a0494
JF
5981 int count([buttons_ count]);
5982 if (count == 0)
5983 return;
2367a917 5984
5a09ae08
JF
5985 if (count == 1)
5986 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5987 else {
674dce72 5988 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5a09ae08 5989 [buttons addObjectsFromArray:buttons_];
36bb2ca2 5990
674dce72 5991 UIActionSheet *sheet = [[[UIActionSheet alloc]
9ea8d159 5992 initWithTitle:nil
36bb2ca2 5993 delegate:self
674dce72
GP
5994 cancelButtonTitle:nil
5995 destructiveButtonTitle:nil
5996 otherButtonTitles:nil
5997 ] autorelease];
5998
5999 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6000 if (!IsWildcat_) {
6001 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6002 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6003 }
6004 [sheet setContext:@"modify"];
bc11cf5b 6005
b5e7eebb 6006 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
36bb2ca2 6007 }
b4d89997 6008}
12b59862 6009
a5938ea5
DH
6010// We don't want to allow non-commercial packages to do custom things to the install button,
6011// so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
9daa7f25 6012- (void) customButtonClicked {
a5938ea5
DH
6013 if (commercial_)
6014 [super customButtonClicked];
6015 else
9daa7f25 6016 [self _customButtonClicked];
12b59862 6017}
2e6c1426
GP
6018
6019- (void) reloadButtonClicked {
6a8591be
GP
6020 // Don't reload a commerical package by tapping the loading button,
6021 // but if it's not an Install button, we should forward it on.
6022 if (![package_ uninstalled])
6023 [self _customButtonClicked];
2fad210a
GP
6024}
6025
6026- (void) applyLoadingTitle {
6027 // Don't show "Loading" as the title. Ever.
2e6c1426 6028}
a5938ea5
DH
6029
6030- (UIBarButtonItem *) rightButton {
2634b249 6031 return button_;
a5938ea5 6032}
9487f027 6033#endif
2367a917 6034
57e8b225 6035- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
b5e7eebb 6036 if ((self = [super init]) != nil) {
36bb2ca2 6037 database_ = database;
5d79f7bf
JF
6038 buttons_ = [NSMutableArray arrayWithCapacity:4];
6039 name_ = [NSString stringWithString:name];
6040 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
36bb2ca2 6041 } return self;
dc5812ec
JF
6042}
6043
57e8b225 6044- (void) reloadData {
57e8b225 6045 package_ = [database_ packageWithName:name_];
36bb2ca2 6046
5a09ae08
JF
6047 [buttons_ removeAllObjects];
6048
57e8b225 6049 if (package_ != nil) {
5d79f7bf 6050 [(Package *) package_ parse];
68d927e2 6051
57e8b225 6052 commercial_ = [package_ isCommercial];
36bb2ca2 6053
dc63e78f 6054 if ([package_ mode] != nil)
43f3d7f6 6055 [buttons_ addObject:UCLocalize("CLEAR")];
5a09ae08 6056 if ([package_ source] == nil);
31f3cfff 6057 else if ([package_ upgradableAndEssential:NO])
43f3d7f6 6058 [buttons_ addObject:UCLocalize("UPGRADE")];
6a155117 6059 else if ([package_ uninstalled])
43f3d7f6 6060 [buttons_ addObject:UCLocalize("INSTALL")];
5a09ae08 6061 else
43f3d7f6 6062 [buttons_ addObject:UCLocalize("REINSTALL")];
6a155117 6063 if (![package_ uninstalled])
43f3d7f6 6064 [buttons_ addObject:UCLocalize("REMOVE")];
2634b249 6065 }
f79a4512 6066
2634b249
JF
6067 NSString *title;
6068 switch ([buttons_ count]) {
6069 case 0: title = nil; break;
6070 case 1: title = [buttons_ objectAtIndex:0]; break;
6071 default: title = UCLocalize("MODIFY"); break;
36bb2ca2 6072 }
2634b249 6073
5d79f7bf 6074 button_ = [[[UIBarButtonItem alloc]
2634b249
JF
6075 initWithTitle:title
6076 style:UIBarButtonItemStylePlain
6077 target:self
6078 action:@selector(customButtonClicked)
5d79f7bf 6079 ] autorelease];
56e88a25 6080
4bff3341 6081 [super reloadData];
b5e7eebb 6082}
f79a4512 6083
3bd1c2a2
JF
6084- (bool) isLoading {
6085 return commercial_ ? [super isLoading] : false;
9fe5e5f8
JF
6086}
6087
b4d89997
JF
6088@end
6089/* }}} */
5829aea2 6090
f50860ee
GP
6091/* Package List Controller {{{ */
6092@interface PackageListController : CYViewController <
c21004b9
JF
6093 UITableViewDataSource,
6094 UITableViewDelegate
6095> {
36bb2ca2 6096 _transient Database *database_;
0175295c 6097 unsigned era_;
36bb2ca2 6098 NSMutableArray *packages_;
b4d89997 6099 NSMutableArray *sections_;
327624b6
JF
6100 UITableView *list_;
6101 NSMutableArray *index_;
6102 NSMutableDictionary *indices_;
f50860ee 6103 NSString *title_;
dc5812ec
JF
6104}
6105
f50860ee 6106- (id) initWithDatabase:(Database *)database title:(NSString *)title;
b4d89997 6107- (void) setDelegate:(id)delegate;
a0be02eb 6108- (void) resetCursor;
b4d89997 6109
b4d89997
JF
6110@end
6111
f50860ee 6112@implementation PackageListController
b4d89997
JF
6113
6114- (void) dealloc {
36bb2ca2 6115 [packages_ release];
b4d89997 6116 [sections_ release];
36bb2ca2 6117 [list_ release];
327624b6
JF
6118 [index_ release];
6119 [indices_ release];
f50860ee 6120 [title_ release];
b5e7eebb 6121
b4d89997 6122 [super dealloc];
8fe19fc1
JF
6123}
6124
f50860ee
GP
6125- (void) deselectWithAnimation:(BOOL)animated {
6126 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6127}
6128
bfb45dcb
GP
6129- (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6130 CGRect base = [[self view] bounds];
6131 base.size.height -= bounds.size.height;
6132 base.origin = [list_ frame].origin;
6133
6134 [UIView beginAnimations:nil context:NULL];
6135 [UIView setAnimationBeginsFromCurrentState:YES];
6136 [UIView setAnimationCurve:curve];
6137 [UIView setAnimationDuration:duration];
6138 [list_ setFrame:base];
6139 [UIView commitAnimations];
6140}
6141
6142- (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6143 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6144}
6145
6146- (void) resizeForKeyboardBounds:(CGRect)bounds {
6147 [self resizeForKeyboardBounds:bounds duration:0];
6148}
6149
6150- (void) keyboardWillShow:(NSNotification *)notification {
6151 CGRect bounds;
6152 CGPoint center;
6153 NSTimeInterval duration;
6154 UIViewAnimationCurve curve;
6155 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6156 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6157 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6158 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6159
6160 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
6161 UIViewController *base = self;
6162 while ([base parentViewController] != nil)
6163 base = [base parentViewController];
6164 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
bfb45dcb
GP
6165 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6166
6167 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6168}
6169
6170- (void) keyboardWillHide:(NSNotification *)notification {
6171 NSTimeInterval duration;
6172 UIViewAnimationCurve curve;
6173 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6174 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6175
6176 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6177}
6178
6179- (void) viewWillAppear:(BOOL)animated {
6180 [super viewWillAppear:animated];
6181
6182 [self resizeForKeyboardBounds:CGRectZero];
6183 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6184 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6185}
6186
6187- (void) viewWillDisappear:(BOOL)animated {
6188 [super viewWillDisappear:animated];
6189
6190 [self resizeForKeyboardBounds:CGRectZero];
6191 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6192 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6193}
6194
f50860ee
GP
6195- (void) viewDidAppear:(BOOL)animated {
6196 [super viewDidAppear:animated];
6197 [self deselectWithAnimation:animated];
6198}
6199
6200- (void) didSelectPackage:(Package *)package {
57e8b225 6201 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
f50860ee
GP
6202 [view setDelegate:delegate_];
6203 [[self navigationController] pushViewController:view animated:YES];
6204}
6205
d03d7492 6206#if TryIndexedCollation
a891c345
GP
6207+ (BOOL) hasIndexedCollation {
6208 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6209}
d03d7492 6210#endif
a891c345 6211
327624b6
JF
6212- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6213 NSInteger count([sections_ count]);
6214 return count == 0 ? 1 : count;
b4d89997 6215}
2367a917 6216
327624b6 6217- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
a891c345 6218 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
327624b6 6219 return nil;
b4d89997
JF
6220 return [[sections_ objectAtIndex:section] name];
6221}
dc5812ec 6222
327624b6
JF
6223- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6224 if ([sections_ count] == 0)
6225 return 0;
6226 return [[sections_ objectAtIndex:section] count];
b4d89997 6227}
dc5812ec 6228
327624b6 6229- (Package *) packageAtIndexPath:(NSIndexPath *)path {
0175295c
JF
6230@synchronized (database_) {
6231 if ([database_ era] != era_)
6232 return nil;
6233
327624b6
JF
6234 Section *section([sections_ objectAtIndex:[path section]]);
6235 NSInteger row([path row]);
6236 Package *package([packages_ objectAtIndex:([section row] + row)]);
0175295c
JF
6237 return [[package retain] autorelease];
6238} }
dc5812ec 6239
327624b6 6240- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
c21004b9 6241 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
327624b6
JF
6242 if (cell == nil)
6243 cell = [[[PackageCell alloc] init] autorelease];
6244 [cell setPackage:[self packageAtIndexPath:path]];
6245 return cell;
b4d89997 6246}
dc5812ec 6247
f50860ee 6248- (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
327624b6 6249 Package *package([self packageAtIndexPath:path]);
59c6ae22 6250 package = [database_ packageWithName:[package id]];
f50860ee 6251 [self didSelectPackage:package];
327624b6
JF
6252}
6253
6254- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
a891c345 6255 // XXX: is 20 the most optimal number here?
327624b6
JF
6256 return [packages_ count] > 20 ? index_ : nil;
6257}
6258
a891c345 6259- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
d03d7492 6260#if TryIndexedCollation
a891c345
GP
6261 if ([[self class] hasIndexedCollation]) {
6262 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6263 }
d03d7492 6264#endif
a891c345 6265
327624b6 6266 return index;
dc5812ec
JF
6267}
6268
f50860ee
GP
6269- (id) initWithDatabase:(Database *)database title:(NSString *)title {
6270 if ((self = [super init]) != nil) {
36bb2ca2 6271 database_ = database;
f50860ee
GP
6272 title_ = [title copy];
6273 [[self navigationItem] setTitle:title_];
36bb2ca2 6274
d03d7492
JF
6275#if TryIndexedCollation
6276 if ([[self class] hasIndexedCollation])
6277 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6278 else
6279#endif
6280 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6281
327624b6
JF
6282 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6283
36bb2ca2 6284 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
b4d89997 6285 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 6286
f50860ee 6287 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 6288 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
d2741c0a 6289 [list_ setRowHeight:73];
f50860ee 6290 [[self view] addSubview:list_];
04fe1349 6291
b4d89997 6292 [list_ setDataSource:self];
327624b6 6293 [list_ setDelegate:self];
b4d89997 6294 } return self;
dc5812ec
JF
6295}
6296
6297- (void) setDelegate:(id)delegate {
2367a917 6298 delegate_ = delegate;
b4d89997
JF
6299}
6300
a3328c28
JF
6301- (bool) hasPackage:(Package *)package {
6302 return true;
a0be02eb
JF
6303}
6304
36bb2ca2 6305- (void) reloadData {
35f0a3b5
GP
6306 [super reloadData];
6307
0175295c 6308 era_ = [database_ era];
36bb2ca2 6309 NSArray *packages = [database_ packages];
b4d89997 6310
36bb2ca2 6311 [packages_ removeAllObjects];
b4d89997
JF
6312 [sections_ removeAllObjects];
6313
808c6eb6 6314 _profile(PackageTable$reloadData$Filter)
c4dcf2c2 6315 for (Package *package in packages)
808c6eb6
JF
6316 if ([self hasPackage:package])
6317 [packages_ addObject:package];
808c6eb6 6318 _end
36bb2ca2 6319
327624b6
JF
6320 [indices_ removeAllObjects];
6321
b4d89997
JF
6322 Section *section = nil;
6323
d03d7492 6324#if TryIndexedCollation
a891c345
GP
6325 if ([[self class] hasIndexedCollation]) {
6326 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6327 NSArray *titles = [collation sectionIndexTitles];
6328 int secidx = -1;
c4dcf2c2 6329
a891c345
GP
6330 _profile(PackageTable$reloadData$Section)
6331 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6332 Package *package;
6333 int index;
b4d89997 6334
a891c345
GP
6335 _profile(PackageTable$reloadData$Section$Package)
6336 package = [packages_ objectAtIndex:offset];
6337 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
808c6eb6 6338 _end
b4d89997 6339
a891c345
GP
6340 while (secidx < index) {
6341 secidx += 1;
327624b6 6342
a891c345
GP
6343 _profile(PackageTable$reloadData$Section$Allocate)
6344 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6345 _end
6346
6347 _profile(PackageTable$reloadData$Section$Add)
6348 [sections_ addObject:section];
6349 _end
6350 }
6351
6352 [section addToCount];
808c6eb6 6353 }
a891c345 6354 _end
d03d7492
JF
6355 } else
6356#endif
6357 {
a891c345 6358 [index_ removeAllObjects];
808c6eb6 6359
a891c345
GP
6360 _profile(PackageTable$reloadData$Section)
6361 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6362 Package *package;
6363 unichar index;
6364
6365 _profile(PackageTable$reloadData$Section$Package)
6366 package = [packages_ objectAtIndex:offset];
6367 index = [package index];
6368 _end
6369
6370 if (section == nil || [section index] != index) {
6371 _profile(PackageTable$reloadData$Section$Allocate)
6372 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6373 _end
6374
6375 [index_ addObject:[section name]];
6376 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6377
6378 _profile(PackageTable$reloadData$Section$Add)
6379 [sections_ addObject:section];
6380 _end
6381 }
6382
6383 [section addToCount];
6384 }
6385 _end
6386 }
b4d89997 6387
c4dcf2c2
JF
6388 _profile(PackageTable$reloadData$List)
6389 [list_ reloadData];
6390 _end
b4d89997
JF
6391}
6392
a0be02eb 6393- (void) resetCursor {
327624b6 6394 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
a0be02eb
JF
6395}
6396
a3328c28
JF
6397@end
6398/* }}} */
f50860ee
GP
6399/* Filtered Package List Controller {{{ */
6400@interface FilteredPackageListController : PackageListController {
a3328c28 6401 SEL filter_;
76933519 6402 IMP imp_;
a3328c28
JF
6403 id object_;
6404}
6405
6406- (void) setObject:(id)object;
01d93940 6407- (void) setObject:(id)object forFilter:(SEL)filter;
a3328c28 6408
f50860ee 6409- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
a3328c28
JF
6410
6411@end
6412
f50860ee 6413@implementation FilteredPackageListController
a3328c28
JF
6414
6415- (void) dealloc {
6416 if (object_ != nil)
6417 [object_ release];
6418 [super dealloc];
6419}
6420
01d93940
JF
6421- (void) setFilter:(SEL)filter {
6422 filter_ = filter;
6423
6424 /* XXX: this is an unsafe optimization of doomy hell */
6425 Method method(class_getInstanceMethod([Package class], filter));
6426 _assert(method != NULL);
6427 imp_ = method_getImplementation(method);
6428 _assert(imp_ != NULL);
6429}
6430
a3328c28
JF
6431- (void) setObject:(id)object {
6432 if (object_ != nil)
6433 [object_ release];
6434 if (object == nil)
6435 object_ = nil;
6436 else
6437 object_ = [object retain];
6438}
6439
01d93940
JF
6440- (void) setObject:(id)object forFilter:(SEL)filter {
6441 [self setFilter:filter];
6442 [self setObject:object];
01d93940
JF
6443}
6444
a3328c28 6445- (bool) hasPackage:(Package *)package {
76933519
JF
6446 _profile(FilteredPackageTable$hasPackage)
6447 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6448 _end
a3328c28
JF
6449}
6450
f50860ee
GP
6451- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6452 if ((self = [super initWithDatabase:database title:title]) != nil) {
01d93940 6453 [self setFilter:filter];
f50860ee 6454 [self setObject:object];
a3328c28
JF
6455 } return self;
6456}
6457
dc5812ec 6458@end
b5e7eebb
GP
6459/* }}} */
6460
5829aea2
GP
6461/* Home Controller {{{ */
6462@interface HomeController : CYBrowserController {
b4d89997 6463}
6840bff3 6464
7b0ce2da 6465@end
b4d89997 6466
5829aea2 6467@implementation HomeController
46aa9775 6468
3c62d654
JF
6469- (id) init {
6470 if ((self = [super init]) != nil) {
90351d93 6471 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
3c62d654
JF
6472 } return self;
6473}
6474
fe8e721f
GP
6475- (NSURL *) navigationURL {
6476 return [NSURL URLWithString:@"cydia://home"];
6477}
6478
5829aea2
GP
6479- (void) aboutButtonClicked {
6480 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
b4d89997 6481
5829aea2
GP
6482 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6483 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6484 [alert setCancelButtonIndex:0];
46aa9775 6485
5829aea2 6486 [alert setMessage:
0e74df6b 6487 @"Copyright (C) 2008-2011\n"
5829aea2
GP
6488 "Jay Freeman (saurik)\n"
6489 "saurik@saurik.com\n"
6490 "http://www.saurik.com/"
6491 ];
46aa9775 6492
5829aea2 6493 [alert show];
a0376fc1
JF
6494}
6495
35f0a3b5
GP
6496- (void) viewDidLoad {
6497 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6498 initWithTitle:UCLocalize("ABOUT")
6499 style:UIBarButtonItemStylePlain
6500 target:self
6501 action:@selector(aboutButtonClicked)
6502 ] autorelease]];
7b0ce2da
JF
6503}
6504
6505@end
6506/* }}} */
5829aea2
GP
6507/* Manage Controller {{{ */
6508@interface ManageController : CYBrowserController {
7b0ce2da
JF
6509}
6510
5829aea2 6511- (void) queueStatusDidChange;
6840bff3 6512
7b0ce2da
JF
6513@end
6514
5829aea2 6515@implementation ManageController
7b0ce2da 6516
3c62d654
JF
6517- (id) init {
6518 if ((self = [super init]) != nil) {
90351d93 6519 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
3c62d654 6520 } return self;
fe8e721f 6521}
7b0ce2da 6522
3c62d654
JF
6523- (NSURL *) navigationURL {
6524 return [NSURL URLWithString:@"cydia://manage"];
35f0a3b5 6525}
7b0ce2da 6526
35f0a3b5 6527- (void) viewDidLoad {
35f0a3b5
GP
6528 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6529 initWithTitle:UCLocalize("SETTINGS")
6530 style:UIBarButtonItemStylePlain
6531 target:self
6532 action:@selector(settingsButtonClicked)
6533 ] autorelease]];
6534
6535 [self queueStatusDidChange];
7b0ce2da
JF
6536}
6537
5829aea2
GP
6538- (void) settingsButtonClicked {
6539 [delegate_ showSettings];
b5e7eebb
GP
6540}
6541
5829aea2
GP
6542#if !AlwaysReload
6543- (void) queueButtonClicked {
6544 [delegate_ queue];
7b0ce2da
JF
6545}
6546
5829aea2 6547- (void) applyLoadingTitle {
35f0a3b5 6548 // Disable "Loading" title.
7b0ce2da
JF
6549}
6550
5829aea2 6551- (void) applyRightButton {
35f0a3b5 6552 // Disable right button.
7b0ce2da 6553}
5829aea2 6554#endif
7b0ce2da 6555
5829aea2
GP
6556- (void) queueStatusDidChange {
6557#if !AlwaysReload
6558 if (!IsWildcat_ && Queuing_) {
6559 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6560 initWithTitle:UCLocalize("QUEUE")
6561 style:UIBarButtonItemStyleDone
6562 target:self
6563 action:@selector(queueButtonClicked)
6564 ] autorelease]];
6565 } else {
6566 [[self navigationItem] setRightBarButtonItem:nil];
46aa9775 6567 }
5829aea2 6568#endif
7b0ce2da
JF
6569}
6570
5829aea2 6571- (bool) isLoading {
35f0a3b5 6572 // Never show as loading.
5829aea2 6573 return false;
7b0ce2da
JF
6574}
6575
5829aea2
GP
6576@end
6577/* }}} */
7b0ce2da 6578
5829aea2
GP
6579/* Refresh Bar {{{ */
6580@interface RefreshBar : UINavigationBar {
6581 UIProgressIndicator *indicator_;
6582 UITextLabel *prompt_;
6583 UIProgressBar *progress_;
6584 UINavigationButton *cancel_;
6585}
7b0ce2da 6586
5829aea2 6587@end
7b0ce2da 6588
5829aea2 6589@implementation RefreshBar
7b0ce2da 6590
5829aea2
GP
6591- (void) dealloc {
6592 [indicator_ release];
6593 [prompt_ release];
6594 [progress_ release];
6595 [cancel_ release];
6596 [super dealloc];
7b0ce2da
JF
6597}
6598
5829aea2
GP
6599- (void) positionViews {
6600 CGRect frame = [cancel_ frame];
6601 frame.size = [cancel_ sizeThatFits:frame.size];
6602 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6603 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6604 [cancel_ setFrame:frame];
7b0ce2da 6605
5829aea2
GP
6606 CGSize prgsize = {75, 100};
6607 CGRect prgrect = {{
6608 [self frame].size.width - prgsize.width - 10,
6609 ([self frame].size.height - prgsize.height) / 2
6610 } , prgsize};
6611 [progress_ setFrame:prgrect];
7b0ce2da 6612
5829aea2
GP
6613 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6614 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6615 CGRect indrect = {{indoffset, indoffset}, indsize};
6616 [indicator_ setFrame:indrect];
2fc76a2d 6617
5829aea2
GP
6618 CGSize prmsize = {215, indsize.height + 4};
6619 CGRect prmrect = {{
6620 indoffset * 2 + indsize.width,
6621 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6622 }, prmsize};
6623 [prompt_ setFrame:prmrect];
2fc76a2d
JF
6624}
6625
6840bff3 6626- (void) setFrame:(CGRect)frame {
5829aea2 6627 [super setFrame:frame];
5829aea2 6628 [self positionViews];
2fc76a2d
JF
6629}
6630
5829aea2 6631- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6840bff3 6632 if ((self = [super initWithFrame:frame]) != nil) {
5829aea2 6633 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7b0ce2da 6634
5829aea2 6635 [self setBarStyle:UIBarStyleBlack];
7b0ce2da 6636
5829aea2
GP
6637 UIBarStyle barstyle([self _barStyle:NO]);
6638 bool ugly(barstyle == UIBarStyleDefault);
3e9c9e85 6639
5829aea2
GP
6640 UIProgressIndicatorStyle style = ugly ?
6641 UIProgressIndicatorStyleMediumBrown :
6642 UIProgressIndicatorStyleMediumWhite;
2fc76a2d 6643
5829aea2
GP
6644 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6645 [indicator_ setStyle:style];
6646 [indicator_ startAnimation];
6647 [self addSubview:indicator_];
7b0ce2da 6648
5829aea2
GP
6649 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6650 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6651 [prompt_ setBackgroundColor:[UIColor clearColor]];
6652 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6653 [self addSubview:prompt_];
7b0ce2da 6654
5829aea2
GP
6655 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6656 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6657 [progress_ setStyle:0];
6658 [self addSubview:progress_];
7b0ce2da 6659
5829aea2
GP
6660 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6661 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6662 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6663 [cancel_ setBarStyle:barstyle];
3e9c9e85 6664
5829aea2
GP
6665 [self positionViews];
6666 } return self;
6667}
3e9c9e85 6668
aaae308d
JF
6669- (void) setCancellable:(bool)cancellable {
6670 if (cancellable)
6671 [self addSubview:cancel_];
6672 else
6673 [cancel_ removeFromSuperview];
5829aea2 6674}
7b0ce2da 6675
5829aea2
GP
6676- (void) start {
6677 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6678 [progress_ setProgress:0];
7b0ce2da
JF
6679}
6680
5829aea2 6681- (void) stop {
aaae308d 6682 [self setCancellable:NO];
7b0ce2da
JF
6683}
6684
5829aea2
GP
6685- (void) setPrompt:(NSString *)prompt {
6686 [prompt_ setText:prompt];
7b0ce2da
JF
6687}
6688
5829aea2
GP
6689- (void) setProgress:(float)progress {
6690 [progress_ setProgress:progress];
7b0ce2da
JF
6691}
6692
5829aea2
GP
6693@end
6694/* }}} */
b5e7eebb 6695
5829aea2 6696@class CYNavigationController;
7b0ce2da 6697
5829aea2
GP
6698/* Cydia Tab Bar Controller {{{ */
6699@interface CYTabBarController : UITabBarController <
9f99f3da 6700 UITabBarControllerDelegate,
5829aea2
GP
6701 ProgressDelegate
6702> {
6703 _transient Database *database_;
6704 RefreshBar *refreshbar_;
7b0ce2da 6705
5829aea2
GP
6706 bool dropped_;
6707 bool updating_;
6708 // XXX: ok, "updatedelegate_"?...
6709 _transient NSObject<CydiaDelegate> *updatedelegate_;
f79a4512 6710
5829aea2 6711 id root_;
9f99f3da
GP
6712 UIViewController *remembered_;
6713 _transient UIViewController *transient_;
7b0ce2da
JF
6714}
6715
35f0a3b5 6716- (NSArray *) navigationURLCollection;
5829aea2
GP
6717- (void) dropBar:(BOOL)animated;
6718- (void) beginUpdate;
6719- (void) raiseBar:(BOOL)animated;
6720- (BOOL) updating;
1cedb821 6721
5829aea2 6722@end
2fc76a2d 6723
5829aea2 6724@implementation CYTabBarController
3e9c9e85 6725
9f99f3da
GP
6726- (void) setUnselectedViewController:(UIViewController *)transient {
6727 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6728 if (transient != nil) {
6729 if (transient_ == nil)
6730 remembered_ = [[controllers objectAtIndex:0] retain];
6731 transient_ = transient;
6732 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6733 [controllers replaceObjectAtIndex:0 withObject:transient_];
6734 [self setSelectedIndex:0];
6735 [self setViewControllers:controllers];
6736 [self concealTabBarSelection];
6737 } else if (remembered_ != nil) {
6738 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6739 transient_ = transient;
6740 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6741 [remembered_ release];
6742 remembered_ = nil;
6743 [self setViewControllers:controllers];
6744 [self revealTabBarSelection];
6745 }
6746}
6747
6748- (UIViewController *) unselectedViewController {
6749 return transient_;
6750}
6751
6752- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6753 if ([self unselectedViewController])
6754 [self setUnselectedViewController:nil];
6755}
6756
35f0a3b5 6757- (NSArray *) navigationURLCollection {
fe8e721f
GP
6758 NSMutableArray *items([NSMutableArray array]);
6759
35f0a3b5 6760 // XXX: Should this deal with transient view controllers?
fe8e721f 6761 for (id navigation in [self viewControllers]) {
35f0a3b5 6762 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
fe8e721f
GP
6763 if (stack != nil)
6764 [items addObject:stack];
2fc76a2d 6765 }
c713af59 6766
fe8e721f
GP
6767 return items;
6768}
6769
5829aea2 6770- (void) reloadData {
35f0a3b5
GP
6771 for (CYViewController *controller in [self viewControllers])
6772 [controller reloadData];
c713af59 6773
9f99f3da 6774 [(CYNavigationController *)[self unselectedViewController] reloadData];
7b0ce2da
JF
6775}
6776
35f0a3b5
GP
6777- (void) dealloc {
6778 [refreshbar_ release];
6779 [[NSNotificationCenter defaultCenter] removeObserver:self];
6780
6781 [super dealloc];
6782}
6783
b5e7eebb
GP
6784- (id) initWithDatabase:(Database *)database {
6785 if ((self = [super init]) != nil) {
7b0ce2da 6786 database_ = database;
9f99f3da 6787 [self setDelegate:self];
04fe1349 6788
5829aea2
GP
6789 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6790 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7b0ce2da 6791
5829aea2 6792 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7b0ce2da
JF
6793 } return self;
6794}
6795
5829aea2
GP
6796- (void) setUpdate:(NSDate *)date {
6797 [self beginUpdate];
6798}
1cedb821 6799
5829aea2
GP
6800- (void) beginUpdate {
6801 [refreshbar_ start];
6802 [self dropBar:YES];
7b0ce2da 6803
5829aea2
GP
6804 [updatedelegate_ retainNetworkActivityIndicator];
6805 updating_ = true;
7b0ce2da 6806
5829aea2
GP
6807 [NSThread
6808 detachNewThreadSelector:@selector(performUpdate)
6809 toTarget:self
6810 withObject:nil
6811 ];
7b0ce2da
JF
6812}
6813
5829aea2
GP
6814- (void) performUpdate { _pooled
6815 Status status;
6816 status.setDelegate(self);
6817 [database_ updateWithStatus:status];
6818
6819 [self
6820 performSelectorOnMainThread:@selector(completeUpdate)
6821 withObject:nil
6822 waitUntilDone:NO
6823 ];
f6e13561
GP
6824}
6825
5829aea2
GP
6826- (void) stopUpdateWithSelector:(SEL)selector {
6827 updating_ = false;
6828 [updatedelegate_ releaseNetworkActivityIndicator];
b5e7eebb 6829
5829aea2
GP
6830 [self raiseBar:YES];
6831 [refreshbar_ stop];
bc11cf5b 6832
5829aea2 6833 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
2bdd73bd
GP
6834}
6835
5829aea2
GP
6836- (void) completeUpdate {
6837 if (!updating_)
6838 return;
6839 [self stopUpdateWithSelector:@selector(reloadData)];
7b0ce2da
JF
6840}
6841
5829aea2
GP
6842- (void) cancelUpdate {
6843 [self stopUpdateWithSelector:@selector(updateData)];
7b0ce2da
JF
6844}
6845
5829aea2
GP
6846- (void) cancelPressed {
6847 [self cancelUpdate];
6848}
7b0ce2da 6849
5829aea2
GP
6850- (BOOL) updating {
6851 return updating_;
7b0ce2da
JF
6852}
6853
6915b806
JF
6854- (void) addProgressEvent:(CydiaProgressEvent *)event {
6855 [refreshbar_ setPrompt:[event compoundMessage]];
5829aea2 6856}
c21004b9 6857
ff2d5dcd 6858- (bool) isProgressCancelled {
5829aea2
GP
6859 return !updating_;
6860}
7b0ce2da 6861
aaae308d
JF
6862- (void) setProgressCancellable:(NSNumber *)cancellable {
6863 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6864}
6865
d885343d 6866- (void) setProgressPercent:(NSNumber *)percent {
5829aea2 6867 [refreshbar_ setProgress:[percent floatValue]];
7b0ce2da
JF
6868}
6869
bcbac8f7
JF
6870- (void) setProgressStatus:(NSDictionary *)status {
6871 if (status != nil)
6872 [self setProgressPercent:[status objectForKey:@"Percent"]];
6873}
6874
5829aea2
GP
6875- (void) setUpdateDelegate:(id)delegate {
6876 updatedelegate_ = delegate;
7b0ce2da
JF
6877}
6878
5829aea2
GP
6879- (CGFloat) statusBarHeight {
6880 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6881 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6882 } else {
6883 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6884 }
7b0ce2da
JF
6885}
6886
5829aea2
GP
6887- (UIView *) transitionView {
6888 if ([self respondsToSelector:@selector(_transitionView)])
6889 return [self _transitionView];
6890 else
6891 return MSHookIvar<id>(self, "_viewControllerTransitionView");
f641a0e5
JF
6892}
6893
5829aea2
GP
6894- (void) dropBar:(BOOL)animated {
6895 if (dropped_)
6896 return;
6897 dropped_ = true;
7b0ce2da 6898
5829aea2
GP
6899 UIView *transition([self transitionView]);
6900 [[self view] addSubview:refreshbar_];
f6e13561 6901
5829aea2 6902 CGRect barframe([refreshbar_ frame]);
f6e13561 6903
a23207d2 6904 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5829aea2
GP
6905 barframe.origin.y = [self statusBarHeight];
6906 else
6907 barframe.origin.y = 0;
f6e13561 6908
5829aea2 6909 [refreshbar_ setFrame:barframe];
f6e13561 6910
5829aea2
GP
6911 if (animated)
6912 [UIView beginAnimations:nil context:NULL];
f6e13561 6913
5829aea2
GP
6914 CGRect viewframe = [transition frame];
6915 viewframe.origin.y += barframe.size.height;
6916 viewframe.size.height -= barframe.size.height;
6917 [transition setFrame:viewframe];
f6e13561 6918
5829aea2
GP
6919 if (animated)
6920 [UIView commitAnimations];
f6e13561 6921
5829aea2
GP
6922 // Ensure bar has the proper width for our view, it might have changed
6923 barframe.size.width = viewframe.size.width;
6924 [refreshbar_ setFrame:barframe];
f6e13561 6925
5829aea2
GP
6926 // XXX: fix Apple's layout bug
6927 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
f6e13561
GP
6928}
6929
5829aea2
GP
6930- (void) raiseBar:(BOOL)animated {
6931 if (!dropped_)
6932 return;
6933 dropped_ = false;
f6e13561 6934
5829aea2
GP
6935 UIView *transition([self transitionView]);
6936 [refreshbar_ removeFromSuperview];
7b0ce2da 6937
5829aea2 6938 CGRect barframe([refreshbar_ frame]);
7b0ce2da 6939
5829aea2
GP
6940 if (animated)
6941 [UIView beginAnimations:nil context:NULL];
7b0ce2da 6942
5829aea2
GP
6943 CGRect viewframe = [transition frame];
6944 viewframe.origin.y -= barframe.size.height;
6945 viewframe.size.height += barframe.size.height;
6946 [transition setFrame:viewframe];
9daa0bdc 6947
5829aea2
GP
6948 if (animated)
6949 [UIView commitAnimations];
526ea480 6950
5829aea2
GP
6951 // XXX: fix Apple's layout bug
6952 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
bfc87a4d
JF
6953}
6954
5829aea2
GP
6955#if 0
6956- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6957 // XXX: fix Apple's layout bug
6958 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6959}
6960#endif
526ea480 6961
5829aea2
GP
6962- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6963 bool dropped(dropped_);
7b0ce2da 6964
5829aea2
GP
6965 if (dropped)
6966 [self raiseBar:NO];
7b0ce2da 6967
5829aea2 6968 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7b0ce2da 6969
5829aea2
GP
6970 if (dropped)
6971 [self dropBar:NO];
9daa0bdc 6972
5829aea2
GP
6973 // XXX: fix Apple's layout bug
6974 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
b5e7eebb
GP
6975}
6976
5829aea2
GP
6977- (void) statusBarFrameChanged:(NSNotification *)notification {
6978 if (dropped_) {
6979 [self raiseBar:NO];
6980 [self dropBar:NO];
6981 }
b5e7eebb
GP
6982}
6983
7b0ce2da 6984@end
98228790 6985/* }}} */
5829aea2
GP
6986/* Cydia Navigation Controller {{{ */
6987@interface CYNavigationController : UINavigationController {
6988 _transient Database *database_;
6989 _transient id<UINavigationControllerDelegate> delegate_;
7b0ce2da
JF
6990}
6991
35f0a3b5 6992- (NSArray *) navigationURLCollection;
5829aea2
GP
6993- (id) initWithDatabase:(Database *)database;
6994- (void) reloadData;
7b0ce2da 6995
5829aea2 6996@end
bc11cf5b 6997
f6e13561 6998
5829aea2 6999@implementation CYNavigationController
bc11cf5b 7000
35f0a3b5 7001- (NSArray *) navigationURLCollection {
fe8e721f
GP
7002 NSMutableArray *stack([NSMutableArray array]);
7003
7004 for (CYViewController *controller in [self viewControllers]) {
7005 NSString *url = [[controller navigationURL] absoluteString];
7006 if (url != nil)
7007 [stack addObject:url];
7008 }
7009
7010 return stack;
7011}
7012
5829aea2 7013- (void) reloadData {
35f0a3b5 7014 for (CYViewController *page in [self viewControllers]) {
c026045a
GP
7015 // Only reload controllers that have already loaded.
7016 // This prevents a page from accidentally loading too
7017 // early if it hasn't been shown on the screen yet.
35f0a3b5
GP
7018 if ([page hasLoaded])
7019 [page reloadData];
5829aea2 7020 }
dc63e78f
JF
7021}
7022
5829aea2
GP
7023- (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7024 delegate_ = delegate;
eb97a3a8
GP
7025}
7026
5829aea2
GP
7027- (id) initWithDatabase:(Database *)database {
7028 if ((self = [super init]) != nil) {
7029 database_ = database;
7030 } return self;
dc63e78f
JF
7031}
7032
5829aea2
GP
7033@end
7034/* }}} */
7b0ce2da 7035
5829aea2
GP
7036/* Cydia:// Protocol {{{ */
7037@interface CydiaURLProtocol : NSURLProtocol {
9fe5e5f8
JF
7038}
7039
7b0ce2da
JF
7040@end
7041
5829aea2
GP
7042@implementation CydiaURLProtocol
7043
7044+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
7045 NSURL *url([request URL]);
7046 if (url == nil)
7047 return NO;
b0a2900d 7048
5829aea2 7049 NSString *scheme([[url scheme] lowercaseString]);
b0a2900d
JF
7050 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7051 return YES;
7052 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7053 return YES;
7054
7055 return NO;
aa5e5990
JF
7056}
7057
5829aea2
GP
7058+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7059 return request;
7060}
aa5e5990 7061
5829aea2
GP
7062- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7063 id<NSURLProtocolClient> client([self client]);
7064 if (icon == nil)
7065 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7066 else {
7067 NSData *data(UIImagePNGRepresentation(icon));
01d93940 7068
5829aea2
GP
7069 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7070 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7071 [client URLProtocol:self didLoadData:data];
7072 [client URLProtocolDidFinishLoading:self];
7073 }
3931b718
JF
7074}
7075
5829aea2
GP
7076- (void) startLoading {
7077 id<NSURLProtocolClient> client([self client]);
7078 NSURLRequest *request([self request]);
bc11cf5b 7079
5829aea2
GP
7080 NSURL *url([request URL]);
7081 NSString *href([url absoluteString]);
b0a2900d
JF
7082 NSString *scheme([[url scheme] lowercaseString]);
7083
7084 NSString *path;
7085
7086 if ([scheme isEqualToString:@"cydia"])
7087 path = [href substringFromIndex:8];
7088 else if ([scheme isEqualToString:@"about"])
7089 path = [href substringFromIndex:12];
7090 else _assert(false);
bc11cf5b 7091
5829aea2 7092 NSRange slash([path rangeOfString:@"/"]);
bc11cf5b 7093
5829aea2
GP
7094 NSString *command;
7095 if (slash.location == NSNotFound) {
7096 command = path;
7097 path = nil;
7098 } else {
7099 command = [path substringToIndex:slash.location];
7100 path = [path substringFromIndex:(slash.location + 1)];
7101 }
39cda3a8 7102
5829aea2 7103 Database *database([Database sharedInstance]);
bc11cf5b 7104
5829aea2
GP
7105 if ([command isEqualToString:@"package-icon"]) {
7106 if (path == nil)
7107 goto fail;
7108 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7109 Package *package([database packageWithName:path]);
7110 if (package == nil)
7111 goto fail;
7112 UIImage *icon([package icon]);
7113 [self _returnPNGWithImage:icon forRequest:request];
7114 } else if ([command isEqualToString:@"source-icon"]) {
7115 if (path == nil)
7116 goto fail;
7117 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7118 NSString *source(Simplify(path));
7119 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7120 if (icon == nil)
7121 icon = [UIImage applicationImageNamed:@"unknown.png"];
7122 [self _returnPNGWithImage:icon forRequest:request];
7123 } else if ([command isEqualToString:@"uikit-image"]) {
7124 if (path == nil)
7125 goto fail;
7126 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7127 UIImage *icon(_UIImageWithName(path));
7128 [self _returnPNGWithImage:icon forRequest:request];
7129 } else if ([command isEqualToString:@"section-icon"]) {
7130 if (path == nil)
7131 goto fail;
7132 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7133 NSString *section(Simplify(path));
7134 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7135 if (icon == nil)
7136 icon = [UIImage applicationImageNamed:@"unknown.png"];
7137 [self _returnPNGWithImage:icon forRequest:request];
7138 } else fail: {
7139 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7140 }
39cda3a8
GP
7141}
7142
5829aea2
GP
7143- (void) stopLoading {
7144}
807ae6d7 7145
5829aea2
GP
7146@end
7147/* }}} */
807ae6d7 7148
5829aea2 7149/* Section Controller {{{ */
f50860ee 7150@interface SectionController : FilteredPackageListController {
123b380c 7151 _H<NSString> section_;
5829aea2 7152}
807ae6d7 7153
5829aea2 7154- (id) initWithDatabase:(Database *)database section:(NSString *)section;
807ae6d7 7155
5829aea2 7156@end
bc11cf5b 7157
5829aea2 7158@implementation SectionController
bc11cf5b 7159
fe8e721f
GP
7160- (NSURL *) navigationURL {
7161 NSString *name = section_;
7162 if (name == nil)
7163 name = @"all";
7164
7165 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7166}
7167
5829aea2
GP
7168- (id) initWithDatabase:(Database *)database section:(NSString *)name {
7169 NSString *title;
3707eb56 7170 if (name == nil)
5829aea2 7171 title = UCLocalize("ALL_PACKAGES");
3707eb56 7172 else if (![name isEqual:@""])
5829aea2 7173 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
3707eb56 7174 else
5829aea2 7175 title = UCLocalize("NO_SECTION");
fe8e721f 7176
5829aea2 7177 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
3707eb56 7178 section_ = name;
5829aea2 7179 } return self;
b5e7eebb
GP
7180}
7181
b5e7eebb
GP
7182@end
7183/* }}} */
5829aea2
GP
7184/* Sections Controller {{{ */
7185@interface SectionsController : CYViewController <
7186 UITableViewDataSource,
7187 UITableViewDelegate
7585ce66 7188> {
3931b718 7189 _transient Database *database_;
5829aea2
GP
7190 NSMutableArray *sections_;
7191 NSMutableArray *filtered_;
7192 UITableView *list_;
5829aea2 7193 BOOL editing_;
b5e7eebb
GP
7194}
7195
5829aea2 7196- (id) initWithDatabase:(Database *)database;
5829aea2 7197- (void) editButtonClicked;
7585ce66 7198
bc11cf5b 7199@end
b5e7eebb 7200
5829aea2 7201@implementation SectionsController
b5e7eebb 7202
5829aea2 7203- (void) dealloc {
fe8e721f 7204 [self releaseSubviews];
5829aea2
GP
7205 [sections_ release];
7206 [filtered_ release];
fe8e721f 7207
5829aea2
GP
7208 [super dealloc];
7209}
7585ce66 7210
fe8e721f
GP
7211- (NSURL *) navigationURL {
7212 return [NSURL URLWithString:@"cydia://sections"];
7213}
7214
a784d0a4
GP
7215- (void) updateNavigationItem {
7216 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7217 if ([sections_ count] == 0) {
7218 [[self navigationItem] setRightBarButtonItem:nil];
7219 } else {
7220 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7221 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7222 target:self
7223 action:@selector(editButtonClicked)
7224 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7225 }
7226}
7227
35f0a3b5
GP
7228- (BOOL) isEditing {
7229 return editing_;
7230}
7231
5829aea2
GP
7232- (void) setEditing:(BOOL)editing {
7233 if ((editing_ = editing))
7234 [list_ reloadData];
7235 else
7236 [delegate_ updateData];
7585ce66 7237
a784d0a4 7238 [self updateNavigationItem];
b5e7eebb
GP
7239}
7240
5829aea2
GP
7241- (void) viewDidAppear:(BOOL)animated {
7242 [super viewDidAppear:animated];
7243 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7585ce66
JF
7244}
7245
5829aea2
GP
7246- (void) viewWillDisappear:(BOOL)animated {
7247 [super viewWillDisappear:animated];
7248 if (editing_) [self setEditing:NO];
7585ce66
JF
7249}
7250
5829aea2
GP
7251- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7252 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7253 return section;
7254}
7585ce66 7255
5829aea2
GP
7256- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7257 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7585ce66
JF
7258}
7259
5829aea2
GP
7260/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7261 return 45.0f;
7262}*/
7585ce66 7263
5829aea2
GP
7264- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7265 static NSString *reuseIdentifier = @"SectionCell";
7585ce66 7266
35f0a3b5 7267 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5829aea2
GP
7268 if (cell == nil)
7269 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7585ce66 7270
5829aea2 7271 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
54043703 7272
5829aea2 7273 return cell;
54043703
JF
7274}
7275
5829aea2
GP
7276- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7277 if (editing_)
54043703 7278 return;
7585ce66 7279
5829aea2 7280 Section *section = [self sectionAtIndexPath:indexPath];
7585ce66 7281
5829aea2
GP
7282 SectionController *controller = [[[SectionController alloc]
7283 initWithDatabase:database_
7284 section:[section name]
7285 ] autorelease];
7286 [controller setDelegate:delegate_];
7585ce66 7287
5829aea2 7288 [[self navigationController] pushViewController:controller animated:YES];
7585ce66
JF
7289}
7290
fe8e721f
GP
7291- (void) loadView {
7292 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7293
7294 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7295 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7296 [list_ setRowHeight:45.0f];
7297 [list_ setDataSource:self];
7298 [list_ setDelegate:self];
7299 [[self view] addSubview:list_];
7300}
7301
7302- (void) viewDidLoad {
7303 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7304}
7305
7306- (void) releaseSubviews {
7307 [list_ release];
7308 list_ = nil;
7309}
7310
5829aea2
GP
7311- (id) initWithDatabase:(Database *)database {
7312 if ((self = [super init]) != nil) {
7313 database_ = database;
7585ce66 7314
5829aea2
GP
7315 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7316 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
5829aea2 7317 } return self;
7585ce66
JF
7318}
7319
5829aea2 7320- (void) reloadData {
fe8e721f
GP
7321 [super reloadData];
7322
5829aea2 7323 NSArray *packages = [database_ packages];
7585ce66 7324
5829aea2
GP
7325 [sections_ removeAllObjects];
7326 [filtered_ removeAllObjects];
7585ce66 7327
5829aea2 7328 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7585ce66 7329
5829aea2
GP
7330 _trace();
7331 for (Package *package in packages) {
7332 NSString *name([package section]);
7333 NSString *key(name == nil ? @"" : name);
7585ce66 7334
5829aea2 7335 Section *section;
7585ce66 7336
5829aea2
GP
7337 _profile(SectionsView$reloadData$Section)
7338 section = [sections objectForKey:key];
7339 if (section == nil) {
7340 _profile(SectionsView$reloadData$Section$Allocate)
729bc910 7341 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
5829aea2
GP
7342 [sections setObject:section forKey:key];
7343 _end
7344 }
7345 _end
7585ce66 7346
5829aea2 7347 [section addToCount];
7585ce66 7348
5829aea2
GP
7349 _profile(SectionsView$reloadData$Filter)
7350 if (![package valid] || ![package visible])
7351 continue;
7352 _end
7585ce66 7353
5829aea2
GP
7354 [section addToRow];
7355 }
7356 _trace();
7585ce66 7357
5829aea2 7358 [sections_ addObjectsFromArray:[sections allValues]];
7585ce66 7359
5829aea2 7360 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7585ce66 7361
5829aea2
GP
7362 for (Section *section in sections_) {
7363 size_t count([section row]);
7364 if (count == 0)
7365 continue;
7585ce66 7366
5829aea2
GP
7367 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7368 [section setCount:count];
7369 [filtered_ addObject:section];
7370 }
7585ce66 7371
a784d0a4 7372 [self updateNavigationItem];
5829aea2
GP
7373 [list_ reloadData];
7374 _trace();
7375}
7585ce66 7376
6840bff3
JF
7377- (void) editButtonClicked {
7378 [self setEditing:(!editing_)];
5829aea2 7379}
7585ce66 7380
5829aea2
GP
7381@end
7382/* }}} */
7585ce66 7383
5829aea2
GP
7384/* Changes Controller {{{ */
7385@interface ChangesController : CYViewController <
7386 UITableViewDataSource,
7387 UITableViewDelegate
7388> {
7389 _transient Database *database_;
7390 unsigned era_;
7391 CFMutableArrayRef packages_;
7392 NSMutableArray *sections_;
7393 UITableView *list_;
7394 unsigned upgrades_;
7395 BOOL hasSentFirstLoad_;
7396}
7585ce66 7397
ea3bb538 7398- (id) initWithDatabase:(Database *)database;
7585ce66 7399
5829aea2 7400@end
7585ce66 7401
5829aea2 7402@implementation ChangesController
7585ce66 7403
5829aea2 7404- (void) dealloc {
fe8e721f 7405 [self releaseSubviews];
5829aea2 7406 CFRelease(packages_);
5829aea2 7407 [sections_ release];
fe8e721f 7408
5829aea2 7409 [super dealloc];
7585ce66
JF
7410}
7411
fe8e721f
GP
7412- (NSURL *) navigationURL {
7413 return [NSURL URLWithString:@"cydia://changes"];
7414}
7415
35f0a3b5
GP
7416- (void) viewWillAppear:(BOOL)animated {
7417 // Loads after it appears, so don't load beforehand.
7418 loaded_ = YES;
7419 [super viewWillAppear:animated];
7420}
7421
5829aea2
GP
7422- (void) viewDidAppear:(BOOL)animated {
7423 [super viewDidAppear:animated];
fe8e721f 7424
5829aea2
GP
7425 if (!hasSentFirstLoad_) {
7426 hasSentFirstLoad_ = YES;
7427 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7428 } else {
7429 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7585ce66
JF
7430 }
7431}
7432
5829aea2
GP
7433- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7434 NSInteger count([sections_ count]);
7435 return count == 0 ? 1 : count;
7585ce66
JF
7436}
7437
5829aea2
GP
7438- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7439 if ([sections_ count] == 0)
7440 return nil;
7441 return [[sections_ objectAtIndex:section] name];
b5e7eebb
GP
7442}
7443
5829aea2
GP
7444- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7445 if ([sections_ count] == 0)
7446 return 0;
7447 return [[sections_ objectAtIndex:section] count];
7448}
b5e7eebb 7449
5829aea2
GP
7450- (Package *) packageAtIndex:(NSUInteger)index {
7451 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7452}
b5e7eebb 7453
5829aea2
GP
7454- (Package *) packageAtIndexPath:(NSIndexPath *)path {
7455@synchronized (database_) {
7456 if ([database_ era] != era_)
7457 return nil;
b5e7eebb 7458
5829aea2
GP
7459 NSUInteger sectionIndex([path section]);
7460 if (sectionIndex >= [sections_ count])
7461 return nil;
7462 Section *section([sections_ objectAtIndex:sectionIndex]);
7463 NSInteger row([path row]);
7464 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7465} }
b5e7eebb 7466
5829aea2
GP
7467- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7468 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7469 if (cell == nil)
7470 cell = [[[PackageCell alloc] init] autorelease];
7471 [cell setPackage:[self packageAtIndexPath:path]];
7472 return cell;
9cb0bff2
GP
7473}
7474
5829aea2
GP
7475- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7476 Package *package([self packageAtIndexPath:path]);
57e8b225 7477 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5829aea2 7478 [view setDelegate:delegate_];
5829aea2
GP
7479 [[self navigationController] pushViewController:view animated:YES];
7480 return path;
b5e7eebb
GP
7481}
7482
5829aea2
GP
7483- (void) refreshButtonClicked {
7484 [delegate_ beginUpdate];
7485 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
b5e7eebb
GP
7486}
7487
5829aea2
GP
7488- (void) upgradeButtonClicked {
7489 [delegate_ distUpgrade];
b5e7eebb
GP
7490}
7491
fe8e721f
GP
7492- (void) loadView {
7493 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7494
7495 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7496 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7497 [list_ setRowHeight:73];
7498 [list_ setDataSource:self];
7499 [list_ setDelegate:self];
7500 [[self view] addSubview:list_];
7501}
7502
7503- (void) viewDidLoad {
7504 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7505}
7506
7507- (void) releaseSubviews {
7508 [list_ release];
7509 list_ = nil;
7510}
5829aea2 7511
ea3bb538 7512- (id) initWithDatabase:(Database *)database {
b5e7eebb
GP
7513 if ((self = [super init]) != nil) {
7514 database_ = database;
b5e7eebb 7515
5829aea2 7516 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
5829aea2 7517 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5829aea2 7518 } return self;
807ae6d7
JF
7519}
7520
6c0ea9c3
JF
7521// this mostly works because reloadData (below) is @synchronized (database_)
7522// XXX: that said, I've been running into problems with NSRangeExceptions :(
5829aea2
GP
7523- (void) _reloadPackages:(NSArray *)packages {
7524 CFRelease(packages_);
7525 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
9fe5e5f8 7526
5829aea2
GP
7527 _trace();
7528 _profile(ChangesController$_reloadPackages$Filter)
7529 for (Package *package in packages)
7530 if ([package upgradableAndEssential:YES] || [package visible])
7531 CFArrayAppendValue(packages_, package);
7532 _end
7533 _trace();
7534 _profile(ChangesController$_reloadPackages$radixSort)
7535 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7536 _end
7537 _trace();
9fe5e5f8
JF
7538}
7539
5829aea2
GP
7540- (void) reloadData {
7541@synchronized (database_) {
7542 era_ = [database_ era];
7543 NSArray *packages = [database_ packages];
807ae6d7 7544
5829aea2 7545 [sections_ removeAllObjects];
807ae6d7 7546
5829aea2
GP
7547#if 1
7548 UIProgressHUD *hud([delegate_ addProgressHUD]);
7549 [hud setText:UCLocalize("LOADING")];
7550 //NSLog(@"HUD:%@::%@", delegate_, hud);
7551 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7552 [delegate_ removeProgressHUD:hud];
7553#else
7554 [self _reloadPackages:packages];
7555#endif
807ae6d7 7556
5829aea2
GP
7557 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7558 Section *ignored = nil;
7559 Section *section = nil;
7560 time_t last = 0;
807ae6d7 7561
5829aea2
GP
7562 upgrades_ = 0;
7563 bool unseens = false;
807ae6d7 7564
5829aea2 7565 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
807ae6d7 7566
5829aea2
GP
7567 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7568 Package *package = [self packageAtIndex:offset];
807ae6d7 7569
5829aea2 7570 BOOL uae = [package upgradableAndEssential:YES];
807ae6d7 7571
5829aea2
GP
7572 if (!uae) {
7573 unseens = true;
7574 time_t seen([package seen]);
d90a4cd6 7575
5829aea2
GP
7576 if (section == nil || last != seen) {
7577 last = seen;
7578
7579 NSString *name;
7580 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7581 [name autorelease];
7582
7583 _profile(ChangesController$reloadData$Allocate)
7584 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7585 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7586 [sections_ addObject:section];
7587 _end
7588 }
7589
7590 [section addToCount];
7591 } else if ([package ignored]) {
7592 if (ignored == nil) {
7593 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7594 }
7595 [ignored addToCount];
7596 } else {
7597 ++upgrades_;
7598 [upgradable addToCount];
7599 }
7600 }
7601 _trace();
7602
7603 CFRelease(formatter);
7604
7605 if (unseens) {
7606 Section *last = [sections_ lastObject];
7607 size_t count = [last count];
7608 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7609 [sections_ removeLastObject];
7610 }
7611
7612 if ([ignored count] != 0)
7613 [sections_ insertObject:ignored atIndex:0];
7614 if (upgrades_ != 0)
7615 [sections_ insertObject:upgradable atIndex:0];
7616
7617 [list_ reloadData];
7618
7619 if (upgrades_ > 0)
7620 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7621 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7622 style:UIBarButtonItemStylePlain
7623 target:self
7624 action:@selector(upgradeButtonClicked)
7625 ] autorelease]];
7626
7627 if (![delegate_ updating])
7628 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7629 initWithTitle:UCLocalize("REFRESH")
7630 style:UIBarButtonItemStylePlain
7631 target:self
7632 action:@selector(refreshButtonClicked)
7633 ] autorelease]];
7634
7635 PrintTimes();
7636} }
7637
7638@end
7639/* }}} */
7640/* Search Controller {{{ */
f50860ee 7641@interface SearchController : FilteredPackageListController <
5829aea2
GP
7642 UISearchBarDelegate
7643> {
900095fd 7644 _H<UISearchBar> search_;
fe8e721f 7645 BOOL searchloaded_;
5829aea2
GP
7646}
7647
7648- (id) initWithDatabase:(Database *)database;
7649- (void) setSearchTerm:(NSString *)term;
7650- (void) reloadData;
d90a4cd6
GP
7651
7652@end
7653
5829aea2 7654@implementation SearchController
d90a4cd6
GP
7655
7656- (void) dealloc {
900095fd 7657 [search_ setDelegate:nil];
d90a4cd6
GP
7658 [super dealloc];
7659}
7660
fe8e721f 7661- (NSURL *) navigationURL {
35f0a3b5
GP
7662 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7663 return [NSURL URLWithString:@"cydia://search"];
7664 else
7665 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
fe8e721f
GP
7666}
7667
5829aea2
GP
7668- (void) setSearchTerm:(NSString *)searchTerm {
7669 [search_ setText:searchTerm];
fe8e721f 7670 [self reloadData];
5829aea2 7671}
d90a4cd6 7672
5829aea2 7673- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
f50860ee 7674 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
5829aea2
GP
7675 [search_ resignFirstResponder];
7676 [self reloadData];
7677}
7678
7679- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
f50860ee 7680 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
5829aea2
GP
7681 [self reloadData];
7682}
7683
7684- (id) initWithDatabase:(Database *)database {
fe8e721f 7685 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
900095fd
JF
7686 search_ = [[[UISearchBar alloc] init] autorelease];
7687 [search_ setDelegate:self];
fe8e721f 7688 } return self;
5829aea2
GP
7689}
7690
6840bff3 7691- (void) viewDidAppear:(BOOL)animated {
5829aea2 7692 [super viewDidAppear:animated];
fe8e721f
GP
7693
7694 if (!searchloaded_) {
7695 searchloaded_ = YES;
7696 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
5829aea2
GP
7697 [search_ layoutSubviews];
7698 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7699
7700 UITextField *textField;
7701 if ([search_ respondsToSelector:@selector(searchField)])
7702 textField = [search_ searchField];
7703 else
7704 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7705
7706 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
5829aea2
GP
7707 [textField setEnablesReturnKeyAutomatically:NO];
7708 [[self navigationItem] setTitleView:textField];
d90a4cd6 7709 }
5829aea2 7710}
d90a4cd6 7711
d90a4cd6 7712- (void) reloadData {
35f0a3b5 7713 [self setObject:[search_ text]];
fe8e721f 7714 [super reloadData];
f50860ee 7715 [self resetCursor];
d90a4cd6
GP
7716}
7717
5829aea2
GP
7718- (void) didSelectPackage:(Package *)package {
7719 [search_ resignFirstResponder];
7720 [super didSelectPackage:package];
d90a4cd6
GP
7721}
7722
7723@end
7724/* }}} */
5829aea2
GP
7725/* Package Settings Controller {{{ */
7726@interface PackageSettingsController : CYViewController <
c21004b9
JF
7727 UITableViewDataSource,
7728 UITableViewDelegate
7729> {
807ae6d7 7730 _transient Database *database_;
5829aea2
GP
7731 NSString *name_;
7732 Package *package_;
7733 UITableView *table_;
7734 UISwitch *subscribedSwitch_;
7735 UISwitch *ignoredSwitch_;
7736 UITableViewCell *subscribedCell_;
7737 UITableViewCell *ignoredCell_;
807ae6d7
JF
7738}
7739
5829aea2 7740- (id) initWithDatabase:(Database *)database package:(NSString *)package;
c21004b9 7741
807ae6d7
JF
7742@end
7743
5829aea2 7744@implementation PackageSettingsController
807ae6d7
JF
7745
7746- (void) dealloc {
fe8e721f 7747 [self releaseSubviews];
5829aea2 7748 [name_ release];
fe8e721f 7749 [package_ release];
807ae6d7 7750
807ae6d7
JF
7751 [super dealloc];
7752}
7753
fe8e721f
GP
7754- (NSURL *) navigationURL {
7755 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7756}
7757
5829aea2
GP
7758- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7759 if (package_ == nil)
7760 return 0;
e954c30a 7761
2136717a
DH
7762 if ([package_ installed] == nil)
7763 return 1;
7764 else
7765 return 2;
e954c30a
GP
7766}
7767
5829aea2
GP
7768- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7769 if (package_ == nil)
7770 return 0;
7771
2136717a
DH
7772 // both sections contain just one item right now.
7773 return 1;
b5e7eebb
GP
7774}
7775
5829aea2 7776- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
2136717a 7777 return nil;
e954c30a
GP
7778}
7779
5829aea2 7780- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
2136717a
DH
7781 if (section == 0)
7782 return UCLocalize("SHOW_ALL_CHANGES_EX");
7783 else
7784 return UCLocalize("IGNORE_UPGRADES_EX");
807ae6d7
JF
7785}
7786
5829aea2
GP
7787- (void) onSubscribed:(id)control {
7788 bool value([control isOn]);
7789 if (package_ == nil)
7790 return;
7791 if ([package_ setSubscribed:value])
7792 [delegate_ updateData];
807ae6d7
JF
7793}
7794
e5e70358
JF
7795- (void) _updateIgnored {
7796 const char *package([name_ UTF8String]);
7797 bool on([ignoredSwitch_ isOn]);
7798
7799 pid_t pid(ExecFork());
7800 if (pid == 0) {
7801 FILE *dpkg(popen("dpkg --set-selections", "w"));
7802 fwrite(package, strlen(package), 1, dpkg);
7803
7804 if (on)
7805 fwrite(" hold\n", 6, 1, dpkg);
7806 else
7807 fwrite(" install\n", 9, 1, dpkg);
7808
7809 pclose(dpkg);
7810
7811 exit(0);
7812 _assert(false);
7813 }
7814
7815 _forever {
7816 int status;
7817 int result(waitpid(pid, &status, 0));
7818
7819 if (result != -1) {
7820 _assert(result == pid);
7821 break;
7822 }
7823 }
7824}
7825
5829aea2 7826- (void) onIgnored:(id)control {
e5e70358
JF
7827 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7828 [invocation setTarget:self];
7829 [invocation setSelector:@selector(_updateIgnored)];
7830
7831 [delegate_ reloadDataWithInvocation:invocation];
5829aea2 7832}
807ae6d7 7833
46aa9775 7834- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5829aea2
GP
7835 if (package_ == nil)
7836 return nil;
b5e7eebb 7837
2136717a 7838 switch ([indexPath section]) {
5829aea2
GP
7839 case 0: return subscribedCell_;
7840 case 1: return ignoredCell_;
36fbb2aa 7841
5829aea2
GP
7842 _nodefault
7843 }
807ae6d7 7844
5829aea2 7845 return nil;
807ae6d7
JF
7846}
7847
fe8e721f
GP
7848- (void) loadView {
7849 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
807ae6d7 7850
fe8e721f
GP
7851 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7852 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7853 [table_ setDataSource:self];
7854 [table_ setDelegate:self];
7855 [[self view] addSubview:table_];
807ae6d7 7856
fe8e721f
GP
7857 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7858 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7859 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
807ae6d7 7860
fe8e721f
GP
7861 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7862 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7863 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
807ae6d7 7864
fe8e721f
GP
7865 subscribedCell_ = [[UITableViewCell alloc] init];
7866 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7867 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7868 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
5829aea2 7869
fe8e721f
GP
7870 ignoredCell_ = [[UITableViewCell alloc] init];
7871 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7872 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7873 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
fe8e721f 7874}
5829aea2 7875
fe8e721f
GP
7876- (void) viewDidLoad {
7877 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7878}
5829aea2 7879
fe8e721f
GP
7880- (void) releaseSubviews {
7881 [ignoredCell_ release];
7882 ignoredCell_ = nil;
5829aea2 7883
fe8e721f
GP
7884 [subscribedCell_ release];
7885 subscribedCell_ = nil;
807ae6d7 7886
fe8e721f
GP
7887 [table_ release];
7888 table_ = nil;
7889
7890 [ignoredSwitch_ release];
7891 ignoredSwitch_ = nil;
7892
7893 [subscribedSwitch_ release];
7894 subscribedSwitch_ = nil;
7895}
7896
7897- (id) initWithDatabase:(Database *)database package:(NSString *)package {
6840bff3 7898 if ((self = [super init]) != nil) {
fe8e721f
GP
7899 database_ = database;
7900 name_ = [package retain];
807ae6d7
JF
7901 } return self;
7902}
7903
7904- (void) reloadData {
fe8e721f
GP
7905 [super reloadData];
7906
5829aea2
GP
7907 if (package_ != nil)
7908 [package_ autorelease];
7909 package_ = [database_ packageWithName:name_];
f3e2c0ac 7910
5829aea2 7911 if (package_ != nil) {
f3e2c0ac 7912 package_ = [package_ retain];
5829aea2
GP
7913 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7914 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
f3e2c0ac 7915 } // XXX: what now, G?
dc5812ec 7916
5829aea2
GP
7917 [table_ reloadData];
7918}
6d9712c4 7919
dc5812ec 7920@end
2367a917 7921/* }}} */
d90a4cd6 7922
5829aea2 7923/* Installed Controller {{{ */
f50860ee 7924@interface InstalledController : FilteredPackageListController {
5829aea2 7925 BOOL expert_;
dc5812ec
JF
7926}
7927
5829aea2
GP
7928- (id) initWithDatabase:(Database *)database;
7929
7930- (void) updateRoleButton;
7931- (void) queueStatusDidChange;
dc5812ec 7932
dc5812ec
JF
7933@end
7934
5829aea2 7935@implementation InstalledController
b4d89997
JF
7936
7937- (void) dealloc {
b4d89997
JF
7938 [super dealloc];
7939}
dc5812ec 7940
fe8e721f
GP
7941- (NSURL *) navigationURL {
7942 return [NSURL URLWithString:@"cydia://installed"];
7943}
b5e7eebb 7944
5829aea2
GP
7945- (id) initWithDatabase:(Database *)database {
7946 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7947 [self updateRoleButton];
7948 [self queueStatusDidChange];
7949 } return self;
dc5812ec
JF
7950}
7951
5829aea2
GP
7952#if !AlwaysReload
7953- (void) queueButtonClicked {
7954 [delegate_ queue];
dc5812ec 7955}
5829aea2 7956#endif
dc5812ec 7957
5829aea2
GP
7958- (void) queueStatusDidChange {
7959#if !AlwaysReload
7960 if (IsWildcat_) {
7961 if (Queuing_) {
7962 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7963 initWithTitle:UCLocalize("QUEUE")
7964 style:UIBarButtonItemStyleDone
7965 target:self
7966 action:@selector(queueButtonClicked)
7967 ] autorelease]];
7968 } else {
7969 [[self navigationItem] setLeftBarButtonItem:nil];
7970 }
7971 }
7972#endif
dc5812ec
JF
7973}
7974
5829aea2
GP
7975- (void) updateRoleButton {
7976 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7977 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7978 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7979 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7980 target:self
7981 action:@selector(roleButtonClicked)
7982 ] autorelease]];
dc5812ec
JF
7983}
7984
5829aea2 7985- (void) roleButtonClicked {
f50860ee
GP
7986 [self setObject:[NSNumber numberWithBool:expert_]];
7987 [self reloadData];
5829aea2 7988 expert_ = !expert_;
dc5812ec 7989
5829aea2 7990 [self updateRoleButton];
9a7b04c5
JF
7991}
7992
5829aea2
GP
7993@end
7994/* }}} */
b5e7eebb 7995
5829aea2
GP
7996/* Source Cell {{{ */
7997@interface SourceCell : CYTableViewCell <
7998 ContentDelegate
7999> {
8000 UIImage *icon_;
8001 NSString *origin_;
8002 NSString *label_;
8003}
dc5812ec 8004
5829aea2 8005- (void) setSource:(Source *)source;
6da1297d 8006
5829aea2 8007@end
dc5812ec 8008
5829aea2 8009@implementation SourceCell
36bb2ca2 8010
5829aea2
GP
8011- (void) clearSource {
8012 [icon_ release];
8013 [origin_ release];
8014 [label_ release];
dc5812ec 8015
5829aea2
GP
8016 icon_ = nil;
8017 origin_ = nil;
8018 label_ = nil;
dc5812ec
JF
8019}
8020
5829aea2
GP
8021- (void) setSource:(Source *)source {
8022 [self clearSource];
2367a917 8023
5829aea2
GP
8024 if (icon_ == nil)
8025 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8026 if (icon_ == nil)
8027 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8028 icon_ = [icon_ retain];
8029
8030 origin_ = [[source name] retain];
8031 label_ = [[source uri] retain];
8032
8033 [content_ setNeedsDisplay];
77801ff1
JF
8034}
8035
5829aea2
GP
8036- (void) dealloc {
8037 [self clearSource];
8038 [super dealloc];
8039}
77801ff1 8040
5829aea2
GP
8041- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8042 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8043 UIView *content([self contentView]);
8044 CGRect bounds([content bounds]);
77801ff1 8045
5829aea2
GP
8046 content_ = [[ContentView alloc] initWithFrame:bounds];
8047 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8048 [content_ setBackgroundColor:[UIColor whiteColor]];
8049 [content addSubview:content_];
dc5812ec 8050
5829aea2
GP
8051 [content_ setDelegate:self];
8052 [content_ setOpaque:YES];
8053 } return self;
8054}
b4d89997 8055
003fc610
GP
8056- (NSString *) accessibilityLabel {
8057 return label_;
8058}
8059
5829aea2
GP
8060- (void) drawContentRect:(CGRect)rect {
8061 bool highlighted(highlighted_);
8062 float width(rect.size.width);
36bb2ca2 8063
5829aea2
GP
8064 if (icon_ != nil)
8065 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
36bb2ca2 8066
5829aea2
GP
8067 if (highlighted)
8068 UISetColor(White_);
dc5812ec 8069
5829aea2
GP
8070 if (!highlighted)
8071 UISetColor(Black_);
8072 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
f79a4512 8073
5829aea2
GP
8074 if (!highlighted)
8075 UISetColor(Blue_);
8076 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8077}
dc5812ec 8078
5829aea2
GP
8079@end
8080/* }}} */
3f8edf70 8081/* Source Controller {{{ */
f50860ee 8082@interface SourceController : FilteredPackageListController {
2d5372fc 8083 _transient Source *source_;
017b54a2 8084 NSString *key_;
3f8edf70
GP
8085}
8086
8087- (id) initWithDatabase:(Database *)database source:(Source *)source;
8088
8089@end
8090
8091@implementation SourceController
8092
fe8e721f
GP
8093- (NSURL *) navigationURL {
8094 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8095}
8096
3f8edf70 8097- (id) initWithDatabase:(Database *)database source:(Source *)source {
7c642bd6
JF
8098 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8099 source_ = source;
8100 key_ = [[source key] retain];
3f8edf70
GP
8101 } return self;
8102}
8103
2d5372fc 8104- (void) reloadData {
d669236d
GP
8105 source_ = [database_ sourceWithKey:key_];
8106 [key_ release];
8107 key_ = [[source_ key] retain];
2d5372fc 8108 [self setObject:source_];
b6494e70 8109 [[self navigationItem] setTitle:[source_ label]];
2d5372fc
GP
8110
8111 [super reloadData];
8112}
8113
3f8edf70
GP
8114@end
8115/* }}} */
8116/* Sources Controller {{{ */
5829aea2
GP
8117@interface SourcesController : CYViewController <
8118 UITableViewDataSource,
8119 UITableViewDelegate
8120> {
8121 _transient Database *database_;
8122 UITableView *list_;
8123 NSMutableArray *sources_;
8124 int offset_;
723a0072 8125
5829aea2
GP
8126 NSString *href_;
8127 UIProgressHUD *hud_;
8128 NSError *error_;
dc63e78f 8129
5829aea2
GP
8130 //NSURLConnection *installer_;
8131 NSURLConnection *trivial_;
8132 NSURLConnection *trivial_bz2_;
8133 NSURLConnection *trivial_gz_;
8134 //NSURLConnection *automatic_;
b4d89997 8135
5829aea2
GP
8136 BOOL cydia_;
8137}
dc5812ec 8138
5829aea2 8139- (id) initWithDatabase:(Database *)database;
5829aea2
GP
8140- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8141
8142@end
8143
8144@implementation SourcesController
8145
8146- (void) _releaseConnection:(NSURLConnection *)connection {
8147 if (connection != nil) {
8148 [connection cancel];
8149 //[connection setDelegate:nil];
8150 [connection release];
36bb2ca2 8151 }
5829aea2 8152}
dc5812ec 8153
5829aea2 8154- (void) dealloc {
fe8e721f
GP
8155 [self releaseSubviews];
8156
8157 [href_ release];
8158 [hud_ release];
8159 [error_ release];
c25a610d 8160
5829aea2
GP
8161 //[self _releaseConnection:installer_];
8162 [self _releaseConnection:trivial_];
8163 [self _releaseConnection:trivial_gz_];
8164 [self _releaseConnection:trivial_bz2_];
8165 //[self _releaseConnection:automatic_];
3178d79b 8166
5829aea2 8167 [sources_ release];
5829aea2
GP
8168 [super dealloc];
8169}
b5e7eebb 8170
fe8e721f
GP
8171- (NSURL *) navigationURL {
8172 return [NSURL URLWithString:@"cydia://sources"];
8173}
8174
5829aea2
GP
8175- (void) viewDidAppear:(BOOL)animated {
8176 [super viewDidAppear:animated];
8177 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8178}
9bb3b295 8179
5829aea2
GP
8180- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8181 return offset_ == 0 ? 1 : 2;
8182}
8fe19fc1 8183
5829aea2
GP
8184- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8185 switch (section + (offset_ == 0 ? 1 : 0)) {
8186 case 0: return UCLocalize("ENTERED_BY_USER");
8187 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8188
8189 _nodefault
8190 }
36bb2ca2 8191}
b4d89997 8192
5829aea2
GP
8193- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8194 int count = [sources_ count];
8195 switch (section) {
8196 case 0: return (offset_ == 0 ? count : offset_);
8197 case 1: return count - offset_;
b4d89997 8198
5829aea2
GP
8199 _nodefault
8200 }
8201}
3178d79b 8202
5829aea2
GP
8203- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8204 unsigned idx = 0;
8205 switch (indexPath.section) {
8206 case 0: idx = indexPath.row; break;
8207 case 1: idx = indexPath.row + offset_; break;
3178d79b 8208
5829aea2
GP
8209 _nodefault
8210 }
8211 return [sources_ objectAtIndex:idx];
b4d89997
JF
8212}
8213
5829aea2
GP
8214- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8215 static NSString *cellIdentifier = @"SourceCell";
8216
8217 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8218 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8219 [cell setSource:[self sourceAtIndexPath:indexPath]];
b89fa270 8220 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
5829aea2
GP
8221
8222 return cell;
f6e13561
GP
8223}
8224
5829aea2
GP
8225- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8226 Source *source = [self sourceAtIndexPath:indexPath];
8227
3f8edf70 8228 SourceController *controller = [[[SourceController alloc]
5829aea2 8229 initWithDatabase:database_
3f8edf70 8230 source:source
5829aea2
GP
8231 ] autorelease];
8232
3f8edf70 8233 [controller setDelegate:delegate_];
5829aea2 8234
3f8edf70 8235 [[self navigationController] pushViewController:controller animated:YES];
36bb2ca2 8236}
b4d89997 8237
6840bff3 8238- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5829aea2
GP
8239 Source *source = [self sourceAtIndexPath:indexPath];
8240 return [source record] != nil;
dcb47737
RP
8241}
8242
6840bff3 8243- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5829aea2
GP
8244 Source *source = [self sourceAtIndexPath:indexPath];
8245 [Sources_ removeObjectForKey:[source key]];
8246 [delegate_ syncData];
8247}
bcccf498 8248
5829aea2 8249- (void) complete {
93460555 8250 [delegate_ addTrivialSource:href_];
5829aea2 8251 [delegate_ syncData];
3178d79b
JF
8252}
8253
5829aea2
GP
8254- (NSString *) getWarning {
8255 NSString *href(href_);
8256 NSRange colon([href rangeOfString:@"://"]);
8257 if (colon.location != NSNotFound)
8258 href = [href substringFromIndex:(colon.location + 3)];
8259 href = [href stringByAddingPercentEscapes];
8260 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8261 href = [href stringByCachingURLWithCurrentCDN];
8262
8263 NSURL *url([NSURL URLWithString:href]);
8264
8265 NSStringEncoding encoding;
8266 NSError *error(nil);
8267
8268 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8269 return [warning length] == 0 ? nil : warning;
8270 return nil;
807ae6d7 8271}
b4d89997 8272
5829aea2
GP
8273- (void) _endConnection:(NSURLConnection *)connection {
8274 // XXX: the memory management in this method is horribly awkward
8275
8276 NSURLConnection **field = NULL;
8277 if (connection == trivial_)
8278 field = &trivial_;
8279 else if (connection == trivial_bz2_)
8280 field = &trivial_bz2_;
8281 else if (connection == trivial_gz_)
8282 field = &trivial_gz_;
8283 _assert(field != NULL);
8284 [connection release];
8285 *field = nil;
8286
8287 if (
8288 trivial_ == nil &&
8289 trivial_bz2_ == nil &&
8290 trivial_gz_ == nil
8291 ) {
8292 bool defer(false);
8293
8294 if (cydia_) {
8295 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8296 defer = true;
8297
8298 UIAlertView *alert = [[[UIAlertView alloc]
8299 initWithTitle:UCLocalize("SOURCE_WARNING")
8300 message:warning
8301 delegate:self
8302 cancelButtonTitle:UCLocalize("CANCEL")
1aa29546
JF
8303 otherButtonTitles:
8304 UCLocalize("ADD_ANYWAY"),
8305 nil
5829aea2
GP
8306 ] autorelease];
8307
8308 [alert setContext:@"warning"];
8309 [alert setNumberOfRows:1];
8310 [alert show];
8311 } else
8312 [self complete];
8313 } else if (error_ != nil) {
8314 UIAlertView *alert = [[[UIAlertView alloc]
8315 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8316 message:[error_ localizedDescription]
8317 delegate:self
8318 cancelButtonTitle:UCLocalize("OK")
8319 otherButtonTitles:nil
8320 ] autorelease];
8321
8322 [alert setContext:@"urlerror"];
8323 [alert show];
8324 } else {
8325 UIAlertView *alert = [[[UIAlertView alloc]
8326 initWithTitle:UCLocalize("NOT_REPOSITORY")
8327 message:UCLocalize("NOT_REPOSITORY_EX")
8328 delegate:self
8329 cancelButtonTitle:UCLocalize("OK")
8330 otherButtonTitles:nil
8331 ] autorelease];
8332
8333 [alert setContext:@"trivial"];
8334 [alert show];
8335 }
8336
dcaecde2 8337 [delegate_ releaseNetworkActivityIndicator];
5829aea2 8338
dcaecde2 8339 [delegate_ removeProgressHUD:hud_];
5829aea2
GP
8340 [hud_ autorelease];
8341 hud_ = nil;
8342
8343 if (!defer) {
8344 [href_ release];
8345 href_ = nil;
8346 }
8347
8348 if (error_ != nil) {
8349 [error_ release];
8350 error_ = nil;
8351 }
8352 }
807ae6d7 8353}
8fe19fc1 8354
5829aea2
GP
8355- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8356 switch ([response statusCode]) {
8357 case 200:
8358 cydia_ = YES;
8359 }
8e05f686
RP
8360}
8361
5829aea2
GP
8362- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8363 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8364 if (error_ != nil)
8365 error_ = [error retain];
8366 [self _endConnection:connection];
807ae6d7 8367}
b4d89997 8368
5829aea2
GP
8369- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8370 [self _endConnection:connection];
8371}
b4d89997 8372
5829aea2
GP
8373- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8374 NSMutableURLRequest *request = [NSMutableURLRequest
8375 requestWithURL:[NSURL URLWithString:href]
8376 cachePolicy:NSURLRequestUseProtocolCachePolicy
8377 timeoutInterval:120.0
8378 ];
bc11cf5b 8379
5829aea2 8380 [request setHTTPMethod:method];
b4d89997 8381
5829aea2
GP
8382 if (Machine_ != NULL)
8383 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8384 if (UniqueID_ != nil)
8385 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
b4d89997 8386
5829aea2 8387 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
3178d79b
JF
8388}
8389
6840bff3 8390- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5829aea2 8391 NSString *context([alert context]);
dc5812ec 8392
5829aea2
GP
8393 if ([context isEqualToString:@"source"]) {
8394 switch (button) {
8395 case 1: {
8396 NSString *href = [[alert textField] text];
baf80942 8397
5829aea2 8398 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
f6e13561 8399
5829aea2
GP
8400 if (![href hasSuffix:@"/"])
8401 href_ = [href stringByAppendingString:@"/"];
8402 else
8403 href_ = href;
8404 href_ = [href_ retain];
b4d89997 8405
5829aea2
GP
8406 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8407 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8408 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8409 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
b4d89997 8410
5829aea2 8411 cydia_ = false;
8fe19fc1 8412
5829aea2
GP
8413 // XXX: this is stupid
8414 hud_ = [[delegate_ addProgressHUD] retain];
8415 [hud_ setText:UCLocalize("VERIFYING_URL")];
dcaecde2 8416 [delegate_ retainNetworkActivityIndicator];
5829aea2 8417 } break;
770f2a8e 8418
5829aea2
GP
8419 case 0:
8420 break;
bc11cf5b 8421
5829aea2
GP
8422 _nodefault
8423 }
770f2a8e 8424
5829aea2
GP
8425 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8426 } else if ([context isEqualToString:@"trivial"])
8427 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8428 else if ([context isEqualToString:@"urlerror"])
8429 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8430 else if ([context isEqualToString:@"warning"]) {
8431 switch (button) {
8432 case 1:
8433 [self complete];
8434 break;
770f2a8e 8435
5829aea2
GP
8436 case 0:
8437 break;
b5e7eebb 8438
5829aea2
GP
8439 _nodefault
8440 }
770f2a8e 8441
5829aea2
GP
8442 [href_ release];
8443 href_ = nil;
b5e7eebb 8444
5829aea2
GP
8445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8446 }
8447}
770f2a8e 8448
fe8e721f
GP
8449- (void) loadView {
8450 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
770f2a8e 8451
fe8e721f
GP
8452 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8453 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8454 [list_ setRowHeight:56];
8455 [list_ setDataSource:self];
8456 [list_ setDelegate:self];
8457 [[self view] addSubview:list_];
8458}
770f2a8e 8459
fe8e721f
GP
8460- (void) viewDidLoad {
8461 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8462 [self updateButtonsForEditingStatus:NO animated:NO];
8463}
770f2a8e 8464
fe8e721f
GP
8465- (void) releaseSubviews {
8466 [list_ release];
8467 list_ = nil;
8468}
770f2a8e 8469
fe8e721f
GP
8470- (id) initWithDatabase:(Database *)database {
8471 if ((self = [super init]) != nil) {
8472 database_ = database;
8473 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
807ae6d7
JF
8474 } return self;
8475}
770f2a8e 8476
807ae6d7 8477- (void) reloadData {
fe8e721f
GP
8478 [super reloadData];
8479
5829aea2 8480 pkgSourceList list;
53ca7fdd 8481 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
5829aea2
GP
8482 return;
8483
8484 [sources_ removeAllObjects];
8485 [sources_ addObjectsFromArray:[database_ sources]];
8486 _trace();
8487 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8488 _trace();
8489
8490 int count([sources_ count]);
8491 offset_ = 0;
8492 for (int i = 0; i != count; i++) {
8493 if ([[sources_ objectAtIndex:i] record] == nil)
8494 break;
8495 offset_++;
770f2a8e 8496 }
807ae6d7 8497
5829aea2
GP
8498 [list_ setEditing:NO];
8499 [self updateButtonsForEditingStatus:NO animated:NO];
8500 [list_ reloadData];
770f2a8e
JF
8501}
8502
5829aea2
GP
8503- (void) showAddSourcePrompt {
8504 UIAlertView *alert = [[[UIAlertView alloc]
8505 initWithTitle:UCLocalize("ENTER_APT_URL")
8506 message:nil
8507 delegate:self
8508 cancelButtonTitle:UCLocalize("CANCEL")
1aa29546
JF
8509 otherButtonTitles:
8510 UCLocalize("ADD_SOURCE"),
8511 nil
5829aea2 8512 ] autorelease];
770f2a8e 8513
5829aea2
GP
8514 [alert setContext:@"source"];
8515 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
770f2a8e 8516
5829aea2
GP
8517 [alert setNumberOfRows:1];
8518 [alert addTextFieldWithValue:@"http://" label:@""];
770f2a8e 8519
5829aea2
GP
8520 UITextInputTraits *traits = [[alert textField] textInputTraits];
8521 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8522 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8523 [traits setKeyboardType:UIKeyboardTypeURL];
8524 // XXX: UIReturnKeyDone
8525 [traits setReturnKeyType:UIReturnKeyNext];
770f2a8e 8526
5829aea2 8527 [alert show];
770f2a8e
JF
8528}
8529
5829aea2
GP
8530- (void) addButtonClicked {
8531 [self showAddSourcePrompt];
770f2a8e
JF
8532}
8533
5829aea2
GP
8534- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8535 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8536 initWithTitle:UCLocalize("ADD")
8537 style:UIBarButtonItemStylePlain
8538 target:self
8539 action:@selector(addButtonClicked)
8540 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8541
8542 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8543 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8544 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8545 target:self
8546 action:@selector(editButtonClicked)
8547 ] autorelease] animated:animated];
8548
8549 if (IsWildcat_ && !editing)
8550 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8551 initWithTitle:UCLocalize("SETTINGS")
8552 style:UIBarButtonItemStylePlain
8553 target:self
8554 action:@selector(settingsButtonClicked)
8555 ] autorelease]];
770f2a8e
JF
8556}
8557
5829aea2
GP
8558- (void) settingsButtonClicked {
8559 [delegate_ showSettings];
8560}
8561
8562- (void) editButtonClicked {
8563 [list_ setEditing:![list_ isEditing] animated:YES];
8564
8565 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
770f2a8e
JF
8566}
8567
21c6da4b
GP
8568@end
8569/* }}} */
f3e11d24 8570
5829aea2
GP
8571/* Settings Controller {{{ */
8572@interface SettingsController : CYViewController <
c21004b9
JF
8573 UITableViewDataSource,
8574 UITableViewDelegate
8575> {
21c6da4b 8576 _transient Database *database_;
3931b718
JF
8577 // XXX: ok, "roledelegate_"?...
8578 _transient id roledelegate_;
21c6da4b
GP
8579 UITableView *table_;
8580 UISegmentedControl *segment_;
8581 UIView *container_;
8582}
c21004b9
JF
8583
8584- (void) showDoneButton;
8585- (void) resizeSegmentedControl;
8586
21c6da4b
GP
8587@end
8588
5829aea2 8589@implementation SettingsController
fe8e721f 8590
21c6da4b 8591- (void) dealloc {
fe8e721f
GP
8592 [self releaseSubviews];
8593
8594 [super dealloc];
8595}
8596
8597- (void) loadView {
8598 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8599
8600 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8601 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8602 [table_ setDelegate:self];
8603 [table_ setDataSource:self];
8604 [[self view] addSubview:table_];
8605
8606 NSArray *items = [NSArray arrayWithObjects:
8607 UCLocalize("USER"),
8608 UCLocalize("HACKER"),
8609 UCLocalize("DEVELOPER"),
8610 nil];
8611 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8612 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8613 [container_ addSubview:segment_];
8614}
8615
8616- (void) viewDidLoad {
8617 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8618
8619 int index = -1;
8620 if ([Role_ isEqualToString:@"User"]) index = 0;
8621 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8622 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8623 if (index != -1) {
8624 [segment_ setSelectedSegmentIndex:index];
8625 [self showDoneButton];
8626 }
8627
8628 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8629 [self resizeSegmentedControl];
8630}
8631
8632- (void) releaseSubviews {
21c6da4b 8633 [table_ release];
fe8e721f
GP
8634 table_ = nil;
8635
21c6da4b 8636 [segment_ release];
fe8e721f 8637 segment_ = nil;
bc11cf5b 8638
fe8e721f
GP
8639 [container_ release];
8640 container_ = nil;
21c6da4b
GP
8641}
8642
8643- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
6840bff3 8644 if ((self = [super init]) != nil) {
21c6da4b
GP
8645 database_ = database;
8646 roledelegate_ = delegate;
21c6da4b
GP
8647 } return self;
8648}
8649
e62f29c6
GP
8650- (void) resizeSegmentedControl {
8651 CGFloat width = [[self view] frame].size.width;
8652 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8653}
8654
2bdd73bd
GP
8655- (void) viewWillAppear:(BOOL)animated {
8656 [super viewWillAppear:animated];
bc11cf5b 8657
e62f29c6
GP
8658 [self resizeSegmentedControl];
8659}
8660
8661- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8662 [self resizeSegmentedControl];
8663}
8664
8665- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8666 [self resizeSegmentedControl];
2bdd73bd
GP
8667}
8668
21c6da4b 8669- (void) save {
fed0d010 8670 NSString *role(nil);
bc11cf5b 8671
21c6da4b 8672 switch ([segment_ selectedSegmentIndex]) {
124c6201
GP
8673 case 0: role = @"User"; break;
8674 case 1: role = @"Hacker"; break;
8675 case 2: role = @"Developer"; break;
21c6da4b
GP
8676
8677 _nodefault
8678 }
8679
124c6201 8680 if (![role isEqualToString:Role_]) {
fed0d010 8681 bool rolling(Role_ == nil);
124c6201 8682 Role_ = role;
bc11cf5b 8683
124c6201
GP
8684 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8685 Role_, @"Role",
8686 nil];
21c6da4b 8687
124c6201 8688 [Metadata_ setObject:Settings_ forKey:@"Settings"];
124c6201 8689 Changed_ = true;
bc11cf5b 8690
fed0d010
JF
8691 if (rolling)
8692 [roledelegate_ loadData];
8693 else
8694 [roledelegate_ updateData];
124c6201 8695 }
21c6da4b
GP
8696}
8697
8698- (void) segmentChanged:(UISegmentedControl *)control {
8699 [self showDoneButton];
8700}
8701
8576ab50 8702- (void) saveAndClose {
21c6da4b 8703 [self save];
8576ab50
GP
8704
8705 [[self navigationItem] setRightBarButtonItem:nil];
21c6da4b
GP
8706 [[self navigationController] dismissModalViewControllerAnimated:YES];
8707}
8708
8576ab50
GP
8709- (void) doneButtonClicked {
8710 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8711 [spinner startAnimating];
8712 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8713 [[self navigationItem] setRightBarButtonItem:spinItem];
8714
8715 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8716}
8717
21c6da4b 8718- (void) showDoneButton {
dd9de556 8719 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
21c6da4b
GP
8720 initWithTitle:UCLocalize("DONE")
8721 style:UIBarButtonItemStyleDone
8722 target:self
8723 action:@selector(doneButtonClicked)
dd9de556 8724 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
21c6da4b
GP
8725}
8726
8727- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
e62f29c6
GP
8728 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8729 return 6;
21c6da4b
GP
8730}
8731
8732- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8733 return 0; // :(
8734}
8735
6840bff3 8736- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
21c6da4b
GP
8737 return nil; // This method is required by the protocol.
8738}
8739
8740- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
bc11cf5b 8741 if (section == 1)
21c6da4b 8742 return UCLocalize("ROLE_EX");
bc11cf5b 8743 if (section == 4)
21c6da4b
GP
8744 return [NSString stringWithFormat:
8745 @"%@: %@\n%@: %@\n%@: %@",
bc11cf5b
JF
8746 UCLocalize("USER"), UCLocalize("USER_EX"),
8747 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
21c6da4b
GP
8748 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8749 ];
8750 else return nil;
8751}
8752
8753- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
36fbb2aa 8754 return section == 3 ? 44.0f : 0;
21c6da4b
GP
8755}
8756
8757- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
36fbb2aa 8758 return section == 3 ? container_ : nil;
21c6da4b
GP
8759}
8760
fe8e721f
GP
8761- (void) reloadData {
8762 [super reloadData];
8763 [table_ reloadData];
8764}
8765
f3e11d24
GP
8766@end
8767/* }}} */
8768/* Stash Controller {{{ */
5829aea2 8769@interface StashController : CYViewController {
fe8e721f
GP
8770 UIActivityIndicatorView *spinner_;
8771 UILabel *status_;
8772 UILabel *caption_;
f3e11d24 8773}
6840bff3 8774
f3e11d24
GP
8775@end
8776
5829aea2 8777@implementation StashController
f3e11d24 8778
fe8e721f
GP
8779- (void) dealloc {
8780 [self releaseSubviews];
f3e11d24 8781
fe8e721f
GP
8782 [super dealloc];
8783}
8784
8785- (void) loadView {
8786 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8787 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8788
8789 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8790 CGRect spinrect = [spinner_ frame];
8791 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8792 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8793 [spinner_ setFrame:spinrect];
8794 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8795 [[self view] addSubview:spinner_];
8796 [spinner_ startAnimating];
8797
8798 CGRect captrect;
8799 captrect.size.width = [[self view] frame].size.width;
8800 captrect.size.height = 40.0f;
8801 captrect.origin.x = 0;
8802 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8803 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8804 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8805 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8806 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8807 [caption_ setTextColor:[UIColor whiteColor]];
8808 [caption_ setBackgroundColor:[UIColor clearColor]];
8809 [caption_ setShadowColor:[UIColor blackColor]];
8810 [caption_ setTextAlignment:UITextAlignmentCenter];
8811 [[self view] addSubview:caption_];
8812
8813 CGRect statusrect;
8814 statusrect.size.width = [[self view] frame].size.width;
8815 statusrect.size.height = 30.0f;
8816 statusrect.origin.x = 0;
8817 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8818 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8819 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8820 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8821 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8822 [status_ setTextColor:[UIColor whiteColor]];
8823 [status_ setBackgroundColor:[UIColor clearColor]];
8824 [status_ setShadowColor:[UIColor blackColor]];
8825 [status_ setTextAlignment:UITextAlignmentCenter];
8826 [[self view] addSubview:status_];
8827}
8828
8829- (void) releaseSubviews {
8830 [spinner_ release];
8831 spinner_ = nil;
8832
8833 [status_ release];
8834 status_ = nil;
8835
8836 [caption_ release];
8837 caption_ = nil;
f3e11d24
GP
8838}
8839
770f2a8e 8840@end
807ae6d7 8841/* }}} */
770f2a8e 8842
2367a917 8843@interface Cydia : UIApplication <
adb61bda 8844 ConfirmationControllerDelegate,
6915b806 8845 DatabaseDelegate,
eb30da80 8846 CydiaDelegate,
68046ccc
JF
8847 UINavigationControllerDelegate,
8848 UITabBarControllerDelegate
2367a917 8849> {
3931b718
JF
8850 // XXX: evaluate all fields for _transient
8851
dc5812ec 8852 UIWindow *window_;
68046ccc 8853 CYTabBarController *tabbar_;
6915b806 8854 CYEmulatedLoadingController *emulated_;
9bedffaa 8855
a54b1c10 8856 NSMutableArray *essential_;
9bedffaa 8857 NSMutableArray *broken_;
dc5812ec
JF
8858
8859 Database *database_;
dc5812ec 8860
54043703 8861 NSURL *starturl_;
54043703 8862
235f5487 8863 unsigned locked_;
54043703 8864 unsigned activity_;
9b619239 8865
5829aea2 8866 StashController *stash_;
f3e11d24 8867
8c02abc8 8868 bool loaded_;
dc5812ec
JF
8869}
8870
fed0d010 8871- (void) loadData;
670a0494 8872
dc5812ec
JF
8873@end
8874
8875@implementation Cydia
8876
b5e7eebb 8877- (void) beginUpdate {
7585ce66 8878 [tabbar_ beginUpdate];
b5e7eebb
GP
8879}
8880
8881- (BOOL) updating {
7585ce66 8882 return [tabbar_ updating];
b5e7eebb
GP
8883}
8884
9bedffaa
JF
8885- (void) _loaded {
8886 if ([broken_ count] != 0) {
8887 int count = [broken_ count];
8888
37d2b2a9 8889 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 8890 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
b5e7eebb
GP
8891 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8892 delegate:self
8893 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
1aa29546
JF
8894 otherButtonTitles:
8895 UCLocalize("TEMPORARY_IGNORE"),
8896 nil
9bedffaa
JF
8897 ] autorelease];
8898
37d2b2a9 8899 [alert setContext:@"fixhalf"];
59befad5 8900 [alert setNumberOfRows:2];
37d2b2a9 8901 [alert show];
9bedffaa
JF
8902 } else if (!Ignored_ && [essential_ count] != 0) {
8903 int count = [essential_ count];
8904
37d2b2a9 8905 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 8906 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
b5e7eebb
GP
8907 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8908 delegate:self
8909 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
1aa29546
JF
8910 otherButtonTitles:
8911 UCLocalize("UPGRADE_ESSENTIAL"),
8912 UCLocalize("COMPLETE_UPGRADE"),
8913 nil
9bedffaa
JF
8914 ] autorelease];
8915
37d2b2a9
GP
8916 [alert setContext:@"upgrade"];
8917 [alert show];
9bedffaa
JF
8918 }
8919}
8920
7623f855 8921- (void) _saveConfig {
ffbb3bd5
JF
8922 _trace();
8923 MetaFile_.Sync();
8924 _trace();
8925
7623f855 8926 if (Changed_) {
7623f855 8927 NSString *error(nil);
ffbb3bd5 8928
7623f855
JF
8929 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8930 _trace();
8931 NSError *error(nil);
8932 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8933 NSLog(@"failure to save metadata data: %@", error);
8934 _trace();
ffbb3bd5
JF
8935
8936 Changed_ = false;
7623f855
JF
8937 } else {
8938 NSLog(@"failure to serialize metadata: %@", error);
7623f855 8939 }
7623f855
JF
8940 }
8941}
8942
89571a5b
GP
8943// Navigation controller for the queuing badge.
8944- (CYNavigationController *) queueNavigationController {
8945 NSArray *controllers = [tabbar_ viewControllers];
8946 return [controllers objectAtIndex:3];
8947}
8948
7623f855
JF
8949- (void) _updateData {
8950 [self _saveConfig];
8951
f6e13561 8952 [tabbar_ reloadData];
f6371a33 8953
89571a5b 8954 CYNavigationController *navigation = [self queueNavigationController];
b5e7eebb 8955
4305896c 8956 id queuedelegate = nil;
89571a5b
GP
8957 if ([[navigation viewControllers] count] > 0)
8958 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
bc11cf5b 8959
89571a5b
GP
8960 [queuedelegate queueStatusDidChange];
8961 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
7623f855
JF
8962}
8963
53fb38da 8964- (void) _refreshIfPossible:(NSDate *)update {
8c02abc8 8965 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
bc11cf5b 8966
45e21ffa 8967 bool recently = false;
45e21ffa
GP
8968 if (update != nil) {
8969 NSTimeInterval interval([update timeIntervalSinceNow]);
8970 if (interval <= 0 && interval > -(15*60))
8971 recently = true;
8972 }
8973
8974 // Don't automatic refresh if:
8975 // - We already refreshed recently.
8976 // - We already auto-refreshed this launch.
8977 // - Auto-refresh is disabled.
8978 if (recently || loaded_ || ManualRefresh) {
8979 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8980
35f0a3b5 8981 // If we are cancelling, we need to make sure it knows it's already loaded.
45e21ffa
GP
8982 loaded_ = true;
8983 return;
8984 } else {
8985 // We are going to load, so remember that.
8986 loaded_ = true;
8987 }
8988
afb5333a
JF
8989 SCNetworkReachabilityFlags flags; {
8990 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8991 SCNetworkReachabilityGetFlags(reachability, &flags);
8992 CFRelease(reachability);
8993 }
8994
8995 // XXX: this elaborate mess is what Apple is using to determine this? :(
8996 // XXX: do we care if the user has to intervene? maybe that's ok?
8997 bool reachable(
8998 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8999 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9000 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9001 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9002 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9003 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9004 )
9005 );
bc11cf5b 9006
45e21ffa
GP
9007 // If we can reach the server, auto-refresh!
9008 if (reachable)
7585ce66 9009 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9aecdc9c 9010
8c02abc8 9011 [pool release];
9aecdc9c
GP
9012}
9013
9014- (void) refreshIfPossible {
53fb38da 9015 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9aecdc9c
GP
9016}
9017
4ba8f30a 9018- (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
851f4a99
GP
9019 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9020 [hud setText:UCLocalize("RELOADING_DATA")];
dc5812ec 9021
4ba8f30a 9022 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
d061f4ba 9023
36fbb2aa
JF
9024 if (hud != nil)
9025 [self removeProgressHUD:hud];
c25a610d 9026
36bb2ca2 9027 size_t changes(0);
9bedffaa 9028
a54b1c10 9029 [essential_ removeAllObjects];
9bedffaa 9030 [broken_ removeAllObjects];
b4d89997 9031
670a0494 9032 NSArray *packages([database_ packages]);
affeffc7 9033 for (Package *package in packages) {
9bedffaa
JF
9034 if ([package half])
9035 [broken_ addObject:package];
31f3cfff 9036 if ([package upgradableAndEssential:NO]) {
a54b1c10
JF
9037 if ([package essential])
9038 [essential_ addObject:package];
36bb2ca2 9039 ++changes;
a54b1c10 9040 }
36bb2ca2 9041 }
b4d89997 9042
0e1784b4
JF
9043 NSLog(@"changes:#%u", changes);
9044
89571a5b 9045 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
36bb2ca2 9046 if (changes != 0) {
0e1784b4 9047 _trace();
36bb2ca2 9048 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
45e21ffa 9049 [changesItem setBadgeValue:badge];
65a03a7a 9050 [changesItem setAnimatedBadge:([essential_ count] > 0)];
0e1784b4 9051 [self setApplicationIconBadgeNumber:changes];
c25a610d 9052 } else {
0e1784b4 9053 _trace();
45e21ffa
GP
9054 [changesItem setBadgeValue:nil];
9055 [changesItem setAnimatedBadge:NO];
0e1784b4 9056 [self setApplicationIconBadgeNumber:0];
c25a610d 9057 }
b4d89997 9058
7623f855 9059 [self _updateData];
6d9712c4 9060
8c02abc8 9061 [self refreshIfPossible];
6d9712c4
JF
9062}
9063
7b0ce2da 9064- (void) updateData {
7623f855 9065 [self _updateData];
b4d89997
JF
9066}
9067
7b0ce2da
JF
9068- (void) update_ {
9069 [database_ update];
9070}
9071
6915b806
JF
9072- (void) complete {
9073 @synchronized (self) {
9074 [self _reloadDataWithInvocation:nil];
9075 }
9076}
9077
2e9123cb
JF
9078- (void) disemulate {
9079 if (emulated_ == nil)
9080 return;
9081
9082 [window_ addSubview:[tabbar_ view]];
9083 [[emulated_ view] removeFromSuperview];
9084 [emulated_ release];
9085 emulated_ = nil;
9086 [window_ setUserInteractionEnabled:YES];
9087}
9088
9089- (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
6915b806
JF
9090 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9091 if (IsWildcat_)
9092 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
2e9123cb
JF
9093
9094 UIViewController *parent;
9095 if (emulated_ == nil)
9096 parent = tabbar_;
9097 else if (!force)
9098 parent = emulated_;
9099 else {
9100 [self disemulate];
9101 parent = tabbar_;
9102 }
9103
9104 [parent presentModalViewController:navigation animated:YES];
6915b806
JF
9105}
9106
9107- (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9108 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9109
9110 if (navigation != nil)
9111 [navigation pushViewController:progress animated:YES];
9112 else
2e9123cb 9113 [self presentModalViewController:progress force:YES];
6915b806
JF
9114
9115 [progress invoke:invocation withTitle:title];
9116 return progress;
9117}
9118
9119- (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9120 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9121}
9122
9123- (void) repairWithInvocation:(NSInvocation *)invocation {
9124 _trace();
8d5bc2ad 9125 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
6915b806
JF
9126 _trace();
9127}
9128
9129- (void) repairWithSelector:(SEL)selector {
9130 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9131}
9132
7b0ce2da 9133- (void) syncData {
1fe5dc43
JF
9134 [self _saveConfig];
9135
670a0494 9136 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7b0ce2da
JF
9137 _assert(file != NULL);
9138
670a0494
JF
9139 for (NSString *key in [Sources_ allKeys]) {
9140 NSDictionary *source([Sources_ objectForKey:key]);
7b0ce2da
JF
9141
9142 fprintf(file, "%s %s %s\n",
9143 [[source objectForKey:@"Type"] UTF8String],
9144 [[source objectForKey:@"URI"] UTF8String],
9145 [[source objectForKey:@"Distribution"] UTF8String]
9146 );
9147 }
9148
9149 fclose(file);
9150
8d5bc2ad 9151 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
b5e7eebb 9152
6915b806 9153 [self complete];
7b0ce2da
JF
9154}
9155
93460555
JF
9156- (void) addTrivialSource:(NSString *)href {
9157 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9158 @"deb", @"Type",
9159 href, @"URI",
9160 @"./", @"Distribution",
9161 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
516d1d40
JF
9162
9163 Changed_ = true;
93460555
JF
9164}
9165
4ba8f30a 9166- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
36bb2ca2 9167 @synchronized (self) {
4ba8f30a 9168 [self _reloadDataWithInvocation:invocation];
36bb2ca2 9169 }
b4d89997
JF
9170}
9171
4ba8f30a
JF
9172- (void) reloadData {
9173 [self reloadDataWithInvocation:nil];
9174}
9175
b4d89997
JF
9176- (void) resolve {
9177 pkgProblemResolver *resolver = [database_ resolver];
9178
9179 resolver->InstallProtect();
9180 if (!resolver->Resolve(true))
9181 _error->Discard();
2367a917
JF
9182}
9183
670a0494 9184- (bool) perform {
d6c371f5
JF
9185 // XXX: this is a really crappy way of doing this.
9186 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9187 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9188 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9189 if ([tabbar_ updating])
9190 [tabbar_ cancelUpdate];
9191
670a0494
JF
9192 if (![database_ prepare])
9193 return false;
49048579 9194
adb61bda 9195 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
affeffc7 9196 [page setDelegate:self];
3931b718 9197 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
b5e7eebb 9198 [confirm_ setDelegate:self];
49048579 9199
36fbb2aa
JF
9200 if (IsWildcat_)
9201 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
7585ce66 9202 [tabbar_ presentModalViewController:confirm_ animated:YES];
670a0494
JF
9203
9204 return true;
3178d79b
JF
9205}
9206
dc63e78f
JF
9207- (void) queue {
9208 @synchronized (self) {
9209 [self perform];
9210 }
9211}
9212
9213- (void) clearPackage:(Package *)package {
9214 @synchronized (self) {
9215 [package clear];
9216 [self resolve];
9217 [self perform];
9218 }
9219}
9220
77801ff1
JF
9221- (void) installPackages:(NSArray *)packages {
9222 @synchronized (self) {
9223 for (Package *package in packages)
9224 [package install];
9225 [self resolve];
9226 [self perform];
9227 }
9228}
9229
36bb2ca2
JF
9230- (void) installPackage:(Package *)package {
9231 @synchronized (self) {
9232 [package install];
9233 [self resolve];
9234 [self perform];
9235 }
9236}
9237
9238- (void) removePackage:(Package *)package {
9239 @synchronized (self) {
9240 [package remove];
9241 [self resolve];
9242 [self perform];
9243 }
9244}
9245
9246- (void) distUpgrade {
9247 @synchronized (self) {
670a0494
JF
9248 if (![database_ upgrade])
9249 return;
36bb2ca2
JF
9250 [self perform];
9251 }
b4d89997
JF
9252}
9253
b5e7eebb 9254- (void) confirmWithNavigationController:(UINavigationController *)navigation {
f6371a33 9255 Queuing_ = false;
235f5487 9256 ++locked_;
8d5bc2ad 9257 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
235f5487 9258 --locked_;
dc63e78f 9259 [self complete];
dc5812ec
JF
9260}
9261
21c6da4b 9262- (void) showSettings {
5829aea2 9263 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
3931b718 9264 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
36fbb2aa
JF
9265 if (IsWildcat_)
9266 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
7585ce66 9267 [tabbar_ presentModalViewController:nav animated:YES];
7b0ce2da
JF
9268}
9269
54043703
JF
9270- (void) retainNetworkActivityIndicator {
9271 if (activity_++ == 0)
9272 [self setNetworkActivityIndicatorVisible:YES];
848ed88b
JF
9273
9274#if TraceLogging
9275 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9276#endif
54043703
JF
9277}
9278
9279- (void) releaseNetworkActivityIndicator {
9280 if (--activity_ == 0)
9281 [self setNetworkActivityIndicatorVisible:NO];
848ed88b
JF
9282
9283#if TraceLogging
9284 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9285#endif
9286
54043703
JF
9287}
9288
674dce72
GP
9289- (void) cancelAndClear:(bool)clear {
9290 @synchronized (self) {
9291 if (clear) {
c6ca67ba 9292 [database_ clear];
b5e7eebb 9293 Queuing_ = false;
674dce72 9294 } else {
b5e7eebb 9295 Queuing_ = true;
6067f1b8
JF
9296 }
9297
a4217bbb 9298 [self _updateData];
674dce72 9299 }
37d2b2a9 9300}
7b0ce2da 9301
b5e7eebb
GP
9302- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9303 NSString *context([alert context]);
bc11cf5b 9304
6915b806
JF
9305 if ([context isEqualToString:@"conffile"]) {
9306 FILE *input = [database_ input];
9307 if (button == [alert cancelButtonIndex])
9308 fprintf(input, "N\n");
9309 else if (button == [alert firstOtherButtonIndex])
9310 fprintf(input, "Y\n");
9311 fflush(input);
9312
9313 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9314 } else if ([context isEqualToString:@"fixhalf"]) {
efa53fa9 9315 if (button == [alert cancelButtonIndex]) {
37d2b2a9
GP
9316 @synchronized (self) {
9317 for (Package *broken in broken_) {
9318 [broken remove];
9319
9320 NSString *id = [broken id];
9321 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9322 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9323 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9324 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9325 }
7b0ce2da 9326
37d2b2a9
GP
9327 [self resolve];
9328 [self perform];
9329 }
efa53fa9 9330 } else if (button == [alert firstOtherButtonIndex]) {
37d2b2a9
GP
9331 [broken_ removeAllObjects];
9332 [self _loaded];
7b0ce2da
JF
9333 }
9334
37d2b2a9 9335 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 9336 } else if ([context isEqualToString:@"upgrade"]) {
37d2b2a9
GP
9337 if (button == [alert firstOtherButtonIndex]) {
9338 @synchronized (self) {
9339 for (Package *essential in essential_)
9340 [essential install];
7b0ce2da 9341
37d2b2a9
GP
9342 [self resolve];
9343 [self perform];
9344 }
9345 } else if (button == [alert firstOtherButtonIndex] + 1) {
9346 [self distUpgrade];
9347 } else if (button == [alert cancelButtonIndex]) {
9348 Ignored_ = YES;
7b0ce2da
JF
9349 }
9350
37d2b2a9 9351 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 9352 }
7b0ce2da
JF
9353}
9354
670a0494 9355- (void) system:(NSString *)command { _pooled
985d2dff 9356 _trace();
670a0494 9357 system([command UTF8String]);
985d2dff 9358 _trace();
670a0494
JF
9359}
9360
9361- (void) applicationWillSuspend {
9362 [database_ clean];
9363 [super applicationWillSuspend];
bd150f54
JF
9364}
9365
235f5487 9366- (BOOL) isSafeToSuspend {
5927fe03
JF
9367 if (locked_ != 0) {
9368#if !ForRelease
9369 NSLog(@"isSafeToSuspend: locked_ != 0");
9370#endif
9371 return false;
9372 }
9373
262afe11
GP
9374 // Use external process status API internally.
9375 // This is probably a really bad idea.
235f5487 9376 // XXX: what is the point of this? does this solve anything at all?
262afe11
GP
9377 uint64_t status = 0;
9378 int notify_token;
9379 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9380 notify_get_state(notify_token, &status);
9381 notify_cancel(notify_token);
9382 }
9383
5927fe03
JF
9384 if (status != 0) {
9385#if !ForRelease
9386 NSLog(@"isSafeToSuspend: status != 0");
9387#endif
9388 return false;
9389 }
9390
9391#if !ForRelease
9392 NSLog(@"isSafeToSuspend: -> true");
9393#endif
9394 return true;
235f5487
JF
9395}
9396
9397- (void) applicationSuspend:(__GSEvent *)event {
9398 if ([self isSafeToSuspend])
bd150f54 9399 [super applicationSuspend:event];
bd150f54
JF
9400}
9401
6d9712c4 9402- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
235f5487 9403 if ([self isSafeToSuspend])
6d9712c4
JF
9404 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9405}
9406
9407- (void) _setSuspended:(BOOL)value {
235f5487 9408 if ([self isSafeToSuspend])
6d9712c4
JF
9409 [super _setSuspended:value];
9410}
9411
7b0ce2da 9412- (UIProgressHUD *) addProgressHUD {
d061f4ba 9413 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
04fe1349
JF
9414 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9415
d061f4ba 9416 [window_ setUserInteractionEnabled:NO];
7b0ce2da 9417 [hud show:YES];
534e31fc 9418
7585ce66 9419 UIViewController *target = tabbar_;
534e31fc
GP
9420 while ([target modalViewController] != nil) target = [target modalViewController];
9421 [[target view] addSubview:hud];
9422
235f5487 9423 ++locked_;
7b0ce2da
JF
9424 return hud;
9425}
9426
d061f4ba
JF
9427- (void) removeProgressHUD:(UIProgressHUD *)hud {
9428 [hud show:NO];
9429 [hud removeFromSuperview];
9430 [window_ setUserInteractionEnabled:YES];
235f5487 9431 --locked_;
d061f4ba
JF
9432}
9433
9b623dac 9434- (CYViewController *) pageForPackage:(NSString *)name {
57e8b225 9435 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
c390d3ab
JF
9436}
9437
028dbd1c 9438- (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
e47c4742 9439 NSString *scheme([[url scheme] lowercaseString]);
f6e13561 9440 if ([[url absoluteString] length] <= [scheme length] + 3)
e47c4742 9441 return nil;
f6e13561
GP
9442 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9443 NSArray *components([path pathComponents]);
9444
f5a17517 9445 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
f6e13561
GP
9446 return [self pageForPackage:[components objectAtIndex:1]];
9447
9448 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
e47c4742 9449 return nil;
f6e13561
GP
9450
9451 NSString *base([components objectAtIndex:0]);
9452
f5a17517
GP
9453 CYViewController *controller = nil;
9454
f70ea899 9455 if ([base isEqualToString:@"url"]) {
106d645f
GP
9456 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9457 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
eb09425a 9458 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
028dbd1c 9459 } else if (!external && [components count] == 1) {
fe8e721f
GP
9460 if ([base isEqualToString:@"manage"]) {
9461 controller = [[[ManageController alloc] init] autorelease];
9462 }
9463
f6e13561 9464 if ([base isEqualToString:@"sources"]) {
f5a17517 9465 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
f6e13561
GP
9466 }
9467
9468 if ([base isEqualToString:@"home"]) {
f5a17517 9469 controller = [[[HomeController alloc] init] autorelease];
f6e13561
GP
9470 }
9471
9472 if ([base isEqualToString:@"sections"]) {
f5a17517 9473 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
f6e13561
GP
9474 }
9475
9476 if ([base isEqualToString:@"search"]) {
f5a17517 9477 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
f6e13561
GP
9478 }
9479
9480 if ([base isEqualToString:@"changes"]) {
ea3bb538 9481 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
f6e13561
GP
9482 }
9483
9484 if ([base isEqualToString:@"installed"]) {
f5a17517 9485 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
f6e13561
GP
9486 }
9487 } else if ([components count] == 2) {
9488 NSString *argument = [components objectAtIndex:1];
9489
9490 if ([base isEqualToString:@"package"]) {
f5a17517 9491 controller = [self pageForPackage:argument];
f6e13561
GP
9492 }
9493
028dbd1c 9494 if (!external && [base isEqualToString:@"search"]) {
f5a17517
GP
9495 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9496 [(SearchController *)controller setSearchTerm:argument];
f6e13561
GP
9497 }
9498
028dbd1c 9499 if (!external && [base isEqualToString:@"sections"]) {
f6e13561
GP
9500 if ([argument isEqualToString:@"all"])
9501 argument = nil;
f5a17517 9502 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
f6e13561
GP
9503 }
9504
028dbd1c 9505 if (!external && [base isEqualToString:@"sources"]) {
f6e13561 9506 if ([argument isEqualToString:@"add"]) {
f5a17517
GP
9507 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9508 [(SourcesController *)controller showAddSourcePrompt];
f6e13561 9509 } else {
d669236d
GP
9510 Source *source = [database_ sourceWithKey:argument];
9511 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
f6e13561
GP
9512 }
9513 }
9514
028dbd1c 9515 if (!external && [base isEqualToString:@"launch"]) {
f6e13561 9516 [self launchApplicationWithIdentifier:argument suspended:NO];
f5a17517 9517 return nil;
f6e13561 9518 }
028dbd1c 9519 } else if (!external && [components count] == 3) {
f6e13561
GP
9520 NSString *arg1 = [components objectAtIndex:1];
9521 NSString *arg2 = [components objectAtIndex:2];
9522
9523 if ([base isEqualToString:@"package"]) {
9524 if ([arg2 isEqualToString:@"settings"]) {
f5a17517 9525 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
f6e13561
GP
9526 } else if ([arg2 isEqualToString:@"files"]) {
9527 if (Package *package = [database_ packageWithName:arg1]) {
f5a17517
GP
9528 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9529 [(FileTable *)controller setPackage:package];
f6e13561
GP
9530 }
9531 }
c390d3ab
JF
9532 }
9533 }
9534
f5a17517
GP
9535 [controller setDelegate:self];
9536 return controller;
c390d3ab
JF
9537}
9538
028dbd1c
JF
9539- (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9540 CYViewController *page([self pageForURL:url forExternal:external]);
40364973 9541
c713af59
GP
9542 if (page != nil) {
9543 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9544 [nav setViewControllers:[NSArray arrayWithObject:page]];
9f99f3da 9545 [tabbar_ setUnselectedViewController:nav];
c713af59 9546 }
40364973 9547
f6e13561 9548 return page != nil;
40364973
GP
9549}
9550
c390d3ab
JF
9551- (void) applicationOpenURL:(NSURL *)url {
9552 [super applicationOpenURL:url];
d817e4de 9553
40364973 9554 if (!loaded_) starturl_ = [url retain];
028dbd1c 9555 else [self openCydiaURL:url forExternal:YES];
c390d3ab
JF
9556}
9557
bc11cf5b 9558- (void) applicationWillResignActive:(UIApplication *)application {
7eff7ea6 9559 // Stop refreshing if you get a phone call or lock the device.
7585ce66
JF
9560 if ([tabbar_ updating])
9561 [tabbar_ cancelUpdate];
bc11cf5b 9562
ca584c15
GP
9563 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9564 [super applicationWillResignActive:application];
7eff7ea6
GP
9565}
9566
fe8e721f 9567- (void) applicationWillTerminate:(UIApplication *)application {
35f0a3b5
GP
9568 Changed_ = true;
9569 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
fe8e721f
GP
9570 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9571 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9572
9573 [self _saveConfig];
9574}
9575
6915b806
JF
9576- (void) setConfigurationData:(NSString *)data {
9577 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9578
9579 if (!conffile_r(data)) {
9580 lprintf("E:invalid conffile\n");
9581 return;
9582 }
9583
9584 NSString *ofile = conffile_r[1];
9585 //NSString *nfile = conffile_r[2];
9586
9587 UIAlertView *alert = [[[UIAlertView alloc]
9588 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9589 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9590 delegate:self
9591 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9592 otherButtonTitles:
9593 UCLocalize("ACCEPT_NEW_COPY"),
9594 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9595 nil
9596 ] autorelease];
9597
9598 [alert setContext:@"conffile"];
a08145a8 9599 [alert setNumberOfRows:2];
6915b806
JF
9600 [alert show];
9601}
9602
f3e11d24 9603- (void) addStashController {
235f5487 9604 ++locked_;
5829aea2 9605 stash_ = [[StashController alloc] init];
f3e11d24
GP
9606 [window_ addSubview:[stash_ view]];
9607}
9608
9609- (void) removeStashController {
9610 [[stash_ view] removeFromSuperview];
9611 [stash_ release];
235f5487 9612 --locked_;
f3e11d24
GP
9613}
9614
9615- (void) stash {
9616 [self setIdleTimerDisabled:YES];
9617
9e1f1e91 9618 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
f3e11d24 9619 UpdateExternalStatus(1);
f3e11d24 9620 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
f3e11d24 9621 UpdateExternalStatus(0);
f3e11d24
GP
9622
9623 [self removeStashController];
9624
9625 if (ExecFork() == 0) {
9626 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9627 perror("launchctl stop");
9628 }
9629}
9630
f6e13561 9631- (void) setupViewControllers {
851f4a99 9632 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
851f4a99
GP
9633
9634 NSMutableArray *items([NSMutableArray arrayWithObjects:
89571a5b
GP
9635 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9636 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9637 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9638 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
f6e13561
GP
9639 nil]);
9640
851f4a99 9641 if (IsWildcat_) {
89571a5b
GP
9642 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9643 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
851f4a99 9644 } else {
89571a5b 9645 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
851f4a99
GP
9646 }
9647
9648 NSMutableArray *controllers([NSMutableArray array]);
851f4a99
GP
9649 for (UITabBarItem *item in items) {
9650 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9651 [controller setTabBarItem:item];
9652 [controllers addObject:controller];
9653 }
851f4a99 9654 [tabbar_ setViewControllers:controllers];
4305896c 9655
f6e13561 9656 [tabbar_ setUpdateDelegate:self];
851f4a99
GP
9657}
9658
3171f7fe
JF
9659- (void) addCydiaHost:(NSString *)host {
9660 [CydiaHosts_ addObject:host];
9661}
9662
bd150f54 9663- (void) applicationDidFinishLaunching:(id)unused {
7e30ba6d 9664_trace();
1e94d48b
JF
9665 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9666 [self setApplicationSupportsShakeToEdit:NO];
9667
3171f7fe
JF
9668 [self addCydiaHost:[[NSURL URLWithString:CydiaURL(@"")] host]];
9669
71cc7be1
JF
9670 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9671 initWithMemoryCapacity:524288
9672 diskCapacity:10485760
9673 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9674 ] autorelease]];
9675
b5e7eebb 9676 [CYBrowserController _initialize];
ea173384 9677
bfc87a4d
JF
9678 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9679
f641a0e5
JF
9680 Font12_ = [[UIFont systemFontOfSize:12] retain];
9681 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9682 Font14_ = [[UIFont systemFontOfSize:14] retain];
9683 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9684 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9685
bd150f54
JF
9686 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9687 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9688
4fe4bdc3 9689 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
f641a0e5
JF
9690 [window_ orderFront:self];
9691 [window_ makeKey:self];
c390d3ab 9692 [window_ setHidden:NO];
04fe1349 9693
f3e11d24
GP
9694 if (
9695 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9696 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9697 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9698 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9699 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9700 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9701 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9702 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9703 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9704 false
9705 ) {
9706 [self addStashController];
3931b718
JF
9707 // XXX: this would be much cleaner as a yieldToSelector:
9708 // that way the removeStashController could happen right here inline
9709 // we also could no longer require the useless stash_ field anymore
f3e11d24
GP
9710 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9711 return;
9712 }
9713
770f2a8e 9714 database_ = [Database sharedInstance];
6915b806 9715 [database_ setDelegate:self];
bfc87a4d 9716
89571a5b 9717 [window_ setUserInteractionEnabled:NO];
0be165c8 9718 [self setupViewControllers];
6915b806
JF
9719
9720 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9721 [window_ addSubview:[emulated_ view]];
5ccb47d8 9722
fed0d010 9723 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
c626a63f 9724_trace();
fed0d010
JF
9725}
9726
9727- (void) loadData {
c626a63f 9728_trace();
fed0d010 9729 if (Role_ == nil) {
0c1cb67a 9730 [window_ setUserInteractionEnabled:YES];
2e9123cb 9731 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
fed0d010 9732 return;
0c1cb67a 9733 } else {
6915b806
JF
9734 if ([emulated_ modalViewController] != nil)
9735 [emulated_ dismissModalViewControllerAnimated:YES];
0c1cb67a 9736 [window_ setUserInteractionEnabled:NO];
fed0d010
JF
9737 }
9738
851f4a99 9739 [self reloadData];
670a0494 9740 PrintTimes();
5ccb47d8 9741
2e9123cb 9742 [self disemulate];
5ccb47d8 9743
fe8e721f
GP
9744 int selectedIndex = 0;
9745 NSMutableArray *items = nil;
9746
9747 bool recently = false;
9748 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9749 if (closed != nil) {
9750 NSTimeInterval interval([closed timeIntervalSinceNow]);
9751 // XXX: Is 15 minutes the optimal time here?
9752 if (interval <= 0 && interval > -(15*60))
9753 recently = true;
9754 }
9755
efa53fa9
GP
9756 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9757 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9758
9759 BOOL enough = YES;
9760 for (NSArray *entry in items)
9761 if ([entry count] <= 0)
9762 enough = NO;
9763
9764 if (!recently || !items || !enough) {
727edc18 9765 selectedIndex = 0;
fe8e721f
GP
9766 items = [NSMutableArray array];
9767 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9768 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9769 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9770 if (!IsWildcat_) {
9771 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9772 } else {
9773 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9774 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9775 }
9776 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9777 }
9778
9779 [tabbar_ setSelectedIndex:selectedIndex];
9780 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9781 NSArray *stack = [items objectAtIndex:tab];
9782 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9783 NSMutableArray *current = [NSMutableArray array];
9784
9785 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9786 NSString *addr = [stack objectAtIndex:nav];
9787 NSURL *url = [NSURL URLWithString:addr];
028dbd1c 9788 CYViewController *page = [self pageForURL:url forExternal:NO];
fe8e721f
GP
9789 if (page != nil)
9790 [current addObject:page];
9791 }
9792
9793 [navigation setViewControllers:current];
9794 }
f6e13561 9795
89571a5b 9796 // (Try to) show the startup URL.
f6e13561 9797 if (starturl_ != nil) {
028dbd1c 9798 [self openCydiaURL:starturl_ forExternal:NO];
f6e13561
GP
9799 [starturl_ release];
9800 starturl_ = nil;
9801 }
bd150f54
JF
9802}
9803
b5e7eebb 9804- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
674dce72 9805 if (item != nil && IsWildcat_) {
b5e7eebb 9806 [sheet showFromBarButtonItem:item animated:YES];
674dce72
GP
9807 } else {
9808 [sheet showInView:window_];
9809 }
36bb2ca2
JF
9810}
9811
6915b806
JF
9812- (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9813 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9814 [progress setTitle:task];
9815 [progress addProgressEvent:event];
9816}
9817
9818- (void) addProgressEventForTask:(NSArray *)data {
9819 CydiaProgressEvent *event([data objectAtIndex:0]);
9820 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9821 [self addProgressEvent:event forTask:task];
9822}
9823
9824- (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9825 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9826}
9827
dc5812ec
JF
9828@end
9829
b4d89997
JF
9830/*IMP alloc_;
9831id Alloc_(id self, SEL selector) {
9832 id object = alloc_(self, selector);
c390d3ab 9833 lprintf("[%s]A-%p\n", self->isa->name, object);
b4d89997
JF
9834 return object;
9835}*/
9836
36bb2ca2
JF
9837/*IMP dealloc_;
9838id Dealloc_(id self, SEL selector) {
9839 id object = dealloc_(self, selector);
c390d3ab 9840 lprintf("[%s]D-%p\n", self->isa->name, object);
36bb2ca2
JF
9841 return object;
9842}*/
b4d89997 9843
f79a4512
JF
9844Class $WebDefaultUIKitDelegate;
9845
d791dce4 9846MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
f79a4512
JF
9847 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9848 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
d791dce4 9849 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
f79a4512
JF
9850}
9851
10d65752
RP
9852static NSNumber *shouldPlayKeyboardSounds;
9853
9854Class $UIHardware;
9855
b72246b0
JF
9856MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9857 switch (sound) {
10d65752
RP
9858 case 1104: // Keyboard Button Clicked
9859 case 1105: // Keyboard Delete Repeated
b72246b0
JF
9860 if (shouldPlayKeyboardSounds == nil) {
9861 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9862 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
10d65752 9863 }
b72246b0 9864
10d65752
RP
9865 if (![shouldPlayKeyboardSounds boolValue])
9866 break;
b72246b0 9867
10d65752 9868 default:
b72246b0 9869 _UIHardware$_playSystemSound$(self, _cmd, sound);
10d65752
RP
9870 }
9871}
9872
79b42fd1
GP
9873Class $UIApplication;
9874
9875MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9876 static BOOL initialized = NO;
9877 static BOOL started = NO;
9878
9879 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9880 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9881
9882 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9883 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9884 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9885 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9886
9887 if (initialized && !enabled) {
9888 initialized = NO;
9889 [bundle performSelector:@selector(_accessibilityStopServer)];
9890 } else if (enabled) {
9891 initialized = YES;
9892 if (!started) {
9893 started = YES;
9894 [bundle performSelector:@selector(_accessibilityStartServer)];
9895 }
9896 }
9897 }
9898}
9899
affeffc7 9900int main(int argc, char *argv[]) { _pooled
d6dad1b4 9901 _trace();
f79a4512 9902
9a60abe5
JF
9903 UpdateExternalStatus(0);
9904
01d93940
JF
9905 if (Class $UIDevice = objc_getClass("UIDevice")) {
9906 UIDevice *device([$UIDevice currentDevice]);
9907 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9908 } else
9909 IsWildcat_ = false;
9910
57e8b225
JF
9911 UIScreen *screen([UIScreen mainScreen]);
9912 if ([screen respondsToSelector:@selector(scale)])
9913 ScreenScale_ = [screen scale];
9914 else
9915 ScreenScale_ = 1;
9916
c138614d
JF
9917 UIDevice *device([UIDevice currentDevice]);
9918 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9919 Idiom_ = @"iphone";
9920 else {
9921 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9922 if (idiom == UIUserInterfaceIdiomPhone)
9923 Idiom_ = @"iphone";
9924 else if (idiom == UIUserInterfaceIdiomPad)
9925 Idiom_ = @"ipad";
9926 else
9927 NSLog(@"unknown UIUserInterfaceIdiom!");
9928 }
9929
3171f7fe 9930 CydiaHosts_ = [NSMutableSet setWithCapacity:2];
5df7ecfb 9931
c138614d 9932 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
57e8b225 9933
df213583 9934 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
677b8415 9935
7376b55c
JF
9936 /* Library Hacks {{{ */
9937 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9938
9939 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9940 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9941 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9942 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9943 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9944 }
10d65752
RP
9945
9946 $UIHardware = objc_getClass("UIHardware");
9947 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9948 if (UIHardware$_playSystemSound$ != NULL) {
9949 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9950 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9951 }
79b42fd1
GP
9952
9953 $UIApplication = objc_getClass("UIApplication");
9954 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9955 if (UIApplication$_updateApplicationAccessibility != NULL) {
9956 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9957 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9958 }
7376b55c
JF
9959 /* }}} */
9960 /* Set Locale {{{ */
f79a4512 9961 Locale_ = CFLocaleCopyCurrent();
b1ce61ec
JF
9962 Languages_ = [NSLocale preferredLanguages];
9963 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
18876387 9964 //NSLog(@"%@", [Languages_ description]);
78430d06 9965
b1ce61ec
JF
9966 const char *lang;
9967 if (Languages_ == nil || [Languages_ count] == 0)
78430d06 9968 // XXX: consider just setting to C and then falling through?
b1ce61ec 9969 lang = NULL;
78430d06 9970 else {
b1ce61ec 9971 lang = [[Languages_ objectAtIndex:0] UTF8String];
78430d06 9972 setenv("LANG", lang, true);
262393b9 9973 std::setlocale(LC_ALL, lang);
78430d06
JF
9974 }
9975
b1ce61ec 9976 NSLog(@"Setting Language: %s", lang);
7376b55c 9977 /* }}} */
f79a4512 9978
d791dce4 9979 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
f79a4512 9980
7376b55c 9981 /* Parse Arguments {{{ */
de3b1ab4
JF
9982 bool substrate(false);
9983
9984 if (argc != 0) {
9985 char **args(argv);
9986 int arge(1);
9987
9988 for (int argi(1); argi != argc; ++argi)
9989 if (strcmp(argv[argi], "--") == 0) {
9990 arge = argi;
9991 argv[argi] = argv[0];
9992 argv += argi;
9993 argc -= argi;
9994 break;
9995 }
9996
9997 for (int argi(1); argi != arge; ++argi)
d791dce4 9998 if (strcmp(args[argi], "--substrate") == 0)
de3b1ab4
JF
9999 substrate = true;
10000 else
10001 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10002 }
7376b55c 10003 /* }}} */
d73cede2 10004
7376b55c 10005 App_ = [[NSBundle mainBundle] bundlePath];
d791dce4 10006 Advanced_ = YES;
7376b55c 10007
b4d89997
JF
10008 setuid(0);
10009 setgid(0);
10010
10011 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10012 alloc_ = alloc->method_imp;
10013 alloc->method_imp = (IMP) &Alloc_;*/
10014
36bb2ca2
JF
10015 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10016 dealloc_ = dealloc->method_imp;
10017 dealloc->method_imp = (IMP) &Dealloc_;*/
10018
d791dce4 10019 /* System Information {{{ */
3178d79b 10020 size_t size;
c390d3ab
JF
10021
10022 int maxproc;
10023 size = sizeof(maxproc);
10024 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10025 perror("sysctlbyname(\"kern.maxproc\", ?)");
10026 else if (maxproc < 64) {
10027 maxproc = 64;
10028 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10029 perror("sysctlbyname(\"kern.maxproc\", #)");
10030 }
10031
bfc87a4d
JF
10032 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10033 char *osversion = new char[size];
10034 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10035 perror("sysctlbyname(\"kern.osversion\", ?)");
10036 else
10037 System_ = [NSString stringWithUTF8String:osversion];
10038
3178d79b
JF
10039 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10040 char *machine = new char[size];
c390d3ab
JF
10041 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10042 perror("sysctlbyname(\"hw.machine\", ?)");
10043 else
10044 Machine_ = machine;
3178d79b 10045
59dbe296
JF
10046 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10047 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10048 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
bfc87a4d 10049 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
59dbe296
JF
10050 CFRelease(serial);
10051 }
10052
10053 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10054 NSData *data((NSData *) ecid);
10055 size_t length([data length]);
10056 uint8_t bytes[length];
10057 [data getBytes:bytes];
10058 char string[length * 2 + 1];
10059 for (size_t i(0); i != length; ++i)
10060 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
bfc87a4d 10061 ChipID_ = [NSString stringWithUTF8String:string];
59dbe296
JF
10062 CFRelease(ecid);
10063 }
10064
10065 IOObjectRelease(service);
10066 }
10067 }
10068
87f46a96 10069 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
3178d79b 10070
567e3972
JF
10071 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10072 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10073 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10074
10075 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10076 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10077 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10078
10079 if (mcc != NULL && mnc != NULL)
10080 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10081
10082 if (mnc != NULL)
10083 CFRelease(mnc);
10084 if (mcc != NULL)
10085 CFRelease(mcc);
10086
ad5d065e
JF
10087 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10088 Build_ = [system objectForKey:@"ProductBuildVersion"];
3e9c9e85
JF
10089 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10090 Product_ = [info objectForKey:@"SafariProductVersion"];
10091 Safari_ = [info objectForKey:@"CFBundleVersion"];
10092 }
d791dce4 10093 /* }}} */
7376b55c 10094 /* Load Database {{{ */
d6dad1b4 10095 _trace();
f79a4512
JF
10096 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10097 _trace();
10098 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
d6dad1b4
JF
10099
10100 if (Metadata_ == NULL)
f79a4512 10101 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
6d9712c4 10102 else {
2bdd73bd 10103 Settings_ = [Metadata_ objectForKey:@"Settings"];
7b0ce2da 10104
b4d89997 10105 Packages_ = [Metadata_ objectForKey:@"Packages"];
6d9712c4 10106 Sections_ = [Metadata_ objectForKey:@"Sections"];
7b0ce2da 10107 Sources_ = [Metadata_ objectForKey:@"Sources"];
ef055c6c
JF
10108
10109 Token_ = [Metadata_ objectForKey:@"Token"];
7b0ce2da
JF
10110 }
10111
10112 if (Settings_ != nil)
10113 Role_ = [Settings_ objectForKey:@"Role"];
10114
7b0ce2da
JF
10115 if (Sections_ == nil) {
10116 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10117 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10118 }
10119
10120 if (Sources_ == nil) {
10121 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10122 [Metadata_ setObject:Sources_ forKey:@"Sources"];
6d9712c4 10123 }
7376b55c 10124 /* }}} */
b4d89997 10125
94b0b3e5
JF
10126 _trace();
10127 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10128 _trace();
10129
10130 if (Packages_ != nil) {
c65611b9
JF
10131 bool fail(false);
10132 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
94b0b3e5 10133 _trace();
c65611b9
JF
10134
10135 if (!fail) {
10136 [Metadata_ removeObjectForKey:@"Packages"];
10137 Packages_ = nil;
10138 Changed_ = true;
10139 }
94b0b3e5
JF
10140 }
10141
d791dce4
JF
10142 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10143
d71f3a07 10144#define MobileSubstrate_(name) \
d13577cf
JF
10145 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10146 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10147 if (handle == NULL) \
10148 NSLog(@"%s", dlerror()); \
10149 }
d71f3a07
JF
10150
10151 MobileSubstrate_(Activator)
10152 MobileSubstrate_(libstatusbar)
10153 MobileSubstrate_(SimulatedKeyEvents)
10154 MobileSubstrate_(WinterBoard)
10155
9dd60d81
JF
10156 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10157 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
dddbc481 10158
01d93940
JF
10159 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10160
3b0f10b0 10161 if (access("/tmp/.cydia.fw", F_OK) == 0) {
ea173384 10162 unlink("/tmp/.cydia.fw");
3b0f10b0 10163 goto firmware;
a4d8c84e 10164 } else if (access("/User", F_OK) != 0 || version < 4) {
3b0f10b0 10165 firmware:
d6dad1b4 10166 _trace();
26c2dd8c 10167 system("/usr/libexec/cydia/firmware.sh");
d6dad1b4
JF
10168 _trace();
10169 }
9e98e020 10170
87f46a96
JF
10171 _assert([[NSFileManager defaultManager]
10172 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10173 withIntermediateDirectories:YES
10174 attributes:nil
10175 error:NULL
10176 ]);
10177
7376b55c
JF
10178 if (access("/tmp/cydia.chk", F_OK) == 0) {
10179 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10180 _assert(errno == ENOENT);
10181 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10182 _assert(errno == ENOENT);
10183 }
10184
59dbe296 10185 /* APT Initialization {{{ */
b1ce61ec
JF
10186 _assert(pkgInitConfig(*_config));
10187 _assert(pkgInitSystem(*_config, _system));
10188
10189 if (lang != NULL)
10190 _config->Set("APT::Acquire::Translation", lang);
cb94ff21
JF
10191
10192 // XXX: this timeout might be important :(
10193 //_config->Set("Acquire::http::Timeout", 15);
10194
7623f855 10195 _config->Set("Acquire::http::MaxParallel", 3);
59dbe296 10196 /* }}} */
7376b55c 10197 /* Color Choices {{{ */
36bb2ca2
JF
10198 space_ = CGColorSpaceCreateDeviceRGB();
10199
f641a0e5 10200 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
77fcccaf 10201 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
36bb2ca2 10202 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
baf80942 10203 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
36bb2ca2 10204 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
7b0ce2da 10205 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
3bd1c2a2
JF
10206 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10207 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10208 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
59dbe296 10209
dc63e78f
JF
10210 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10211 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
7376b55c 10212 /* }}}*/
7376b55c 10213 /* UIKit Configuration {{{ */
f79a4512
JF
10214 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10215 if ($GSFontSetUseLegacyFontMetrics != NULL)
10216 $GSFontSetUseLegacyFontMetrics(YES);
7b0ce2da 10217
600d005d
JF
10218 // XXX: I have a feeling this was important
10219 //UIKeyboardDisableAutomaticAppearance();
7376b55c 10220 /* }}} */
87f46a96 10221
670a0494 10222 Colon_ = UCLocalize("COLON_DELIMITED");
72fb3616 10223 Elision_ = UCLocalize("ELISION");
670a0494
JF
10224 Error_ = UCLocalize("ERROR");
10225 Warning_ = UCLocalize("WARNING");
10226
d6dad1b4 10227 _trace();
77df4f82 10228 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
36bb2ca2
JF
10229
10230 CGColorSpaceRelease(space_);
199d0ba5 10231 CFRelease(Locale_);
36bb2ca2 10232
36bb2ca2 10233 return value;
6d166849 10234}