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