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