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