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