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