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