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