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