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