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