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