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