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