]> git.saurik.com Git - cydia.git/blame - Cydia.mm
The role dialog needs to block loading data, which itself needs to happen strictly...
[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
84848968 378#define ForRelease 0
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
JF
2484 if ([icon_ hasPrefix:@"file:///"])
2485 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
dbe0f181
JF
2486 if (icon == nil) if (section != nil)
2487 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
6e673d99
JF
2488 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2489 if ([dicon hasPrefix:@"file:///"])
2490 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
dbe0f181
JF
2491 if (icon == nil)
2492 icon = [UIImage applicationImageNamed:@"unknown.png"];
2493 return icon;
e057ec05 2494}
b6ffa083 2495
ad554f10 2496- (NSString *) homepage {
ff47b800 2497 return homepage_;
b6ffa083
JF
2498}
2499
0235116c 2500- (NSString *) depiction {
9050015e 2501 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
0235116c
JF
2502}
2503
81ab76dc 2504- (Address *) sponsor {
6932575e
JF
2505 if (sponsor$_ == nil) {
2506 if (sponsor_.empty())
2507 return nil;
2508 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2509 } return sponsor$_;
81ab76dc
JF
2510}
2511
d72d91aa 2512- (Address *) author {
6932575e
JF
2513 if (author$_ == nil) {
2514 if (author_.empty())
2515 return nil;
2516 author$_ = [[Address addressWithString:author_] retain];
2517 } return author$_;
d72d91aa
JF
2518}
2519
3ff1504e 2520- (NSString *) support {
419a9efd 2521 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
3ff1504e
JF
2522}
2523
f464053e 2524- (NSArray *) files {
9ee296df 2525 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
f464053e
JF
2526 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2527
2528 std::ifstream fin;
2529 fin.open([path UTF8String]);
2530 if (!fin.is_open())
2531 return nil;
2532
2533 std::string line;
2534 while (std::getline(fin, line))
2535 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2536
2537 return files;
2538}
2539
2a987aa5
JF
2540- (NSArray *) relationships {
2541 return relationships_;
2542}
2543
f464053e
JF
2544- (NSArray *) warnings {
2545 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2546 const char *name(iterator_.Name());
2547
2548 size_t length(strlen(name));
2549 if (length < 2) invalid:
61b13cae 2550 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
f464053e
JF
2551 else for (size_t i(0); i != length; ++i)
2552 if (
8944281a
JF
2553 /* XXX: technically this is not allowed */
2554 (name[i] < 'A' || name[i] > 'Z') &&
f464053e
JF
2555 (name[i] < 'a' || name[i] > 'z') &&
2556 (name[i] < '0' || name[i] > '9') &&
2557 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2558 ) goto invalid;
2559
2560 if (strcmp(name, "cydia") != 0) {
2561 bool cydia = false;
419a9efd 2562 bool user = false;
8944281a 2563 bool _private = false;
f464053e
JF
2564 bool stash = false;
2565
8944281a
JF
2566 bool repository = [[self section] isEqualToString:@"Repositories"];
2567
f464053e
JF
2568 if (NSArray *files = [self files])
2569 for (NSString *file in files)
2570 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2571 cydia = true;
419a9efd
JF
2572 else if (!user && [file isEqualToString:@"/User"])
2573 user = true;
8944281a
JF
2574 else if (!_private && [file isEqualToString:@"/private"])
2575 _private = true;
f464053e
JF
2576 else if (!stash && [file isEqualToString:@"/var/stash"])
2577 stash = true;
2578
8944281a
JF
2579 /* XXX: this is not sensitive enough. only some folders are valid. */
2580 if (cydia && !repository)
61b13cae 2581 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
419a9efd
JF
2582 if (user)
2583 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
8944281a 2584 if (_private)
61b13cae 2585 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
f464053e 2586 if (stash)
61b13cae 2587 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
f464053e
JF
2588 }
2589
2590 return [warnings count] == 0 ? nil : warnings;
2591}
2592
2593- (NSArray *) applications {
2594 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2595
2596 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2597
2598 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2599 if (NSArray *files = [self files])
2600 for (NSString *file in files)
2601 if (application_r(file)) {
2602 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2603 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2604 if ([id isEqualToString:me])
2605 continue;
2606
2607 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2608 if (display == nil)
2609 display = application_r[1];
2610
2611 NSString *bundle([file stringByDeletingLastPathComponent]);
2612 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2613 if (icon == nil || [icon length] == 0)
2614 icon = @"icon.png";
2615 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2616
2617 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2618 [applications addObject:application];
2619
2620 [application addObject:id];
2621 [application addObject:display];
2622 [application addObject:url];
2623 }
2624
2625 return [applications count] == 0 ? nil : applications;
2626}
2627
e057ec05 2628- (Source *) source {
3d37fc0d 2629 if (!cached_) {
a70cf746
JF
2630 @synchronized (database_) {
2631 if ([database_ era] != era_ || file_.end())
2632 source_ = nil;
2633 else {
2634 source_ = [database_ getSource:file_.File()];
2635 if (source_ != nil)
2636 [source_ retain];
2637 }
2638
2639 cached_ = true;
2640 }
3d37fc0d
JF
2641 }
2642
e057ec05 2643 return source_;
b6ffa083
JF
2644}
2645
faf4eb4f
JF
2646- (NSString *) role {
2647 return role_;
2648}
2649
e057ec05
JF
2650- (BOOL) matches:(NSString *)text {
2651 if (text == nil)
2652 return NO;
b6ffa083 2653
e057ec05 2654 NSRange range;
b6ffa083 2655
3bddda52 2656 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
e057ec05
JF
2657 if (range.location != NSNotFound)
2658 return YES;
b6ffa083 2659
3bddda52 2660 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
e057ec05
JF
2661 if (range.location != NSNotFound)
2662 return YES;
b6ffa083 2663
5ec44e34 2664 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
e057ec05 2665 if (range.location != NSNotFound)
5ec44e34 2666 return YES;
b6ffa083 2667
e057ec05
JF
2668 return NO;
2669}
b6ffa083 2670
faf4eb4f
JF
2671- (bool) hasSupportingRole {
2672 if (role_ == nil)
fa7bb92f 2673 return true;
faf4eb4f
JF
2674 if ([role_ isEqualToString:@"enduser"])
2675 return true;
2676 if ([Role_ isEqualToString:@"User"])
2677 return false;
2678 if ([role_ isEqualToString:@"hacker"])
2679 return true;
2680 if ([Role_ isEqualToString:@"Hacker"])
2681 return false;
2682 if ([role_ isEqualToString:@"developer"])
2683 return true;
2684 if ([Role_ isEqualToString:@"Developer"])
2685 return false;
2686 _assert(false);
fa7bb92f
JF
2687}
2688
2689- (BOOL) hasTag:(NSString *)tag {
2690 return tags_ == nil ? NO : [tags_ containsObject:tag];
2691}
2692
cb9c2100
JF
2693- (NSString *) primaryPurpose {
2694 for (NSString *tag in tags_)
2695 if ([tag hasPrefix:@"purpose::"])
2696 return [tag substringFromIndex:9];
2697 return nil;
2698}
2699
dbe0f181
JF
2700- (NSArray *) purposes {
2701 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2702 for (NSString *tag in tags_)
2703 if ([tag hasPrefix:@"purpose::"])
2704 [purposes addObject:[tag substringFromIndex:9]];
2705 return [purposes count] == 0 ? nil : purposes;
2706}
2707
d8d9a65c
JF
2708- (bool) isCommercial {
2709 return [self hasTag:@"cydia::commercial"];
2710}
2711
dd9390c5
JF
2712- (CYString &) cyname {
2713 return name_.empty() ? id_ : name_;
6932575e
JF
2714}
2715
6932575e
JF
2716- (uint32_t) compareBySection:(NSArray *)sections {
2717 NSString *section([self section]);
2718 for (size_t i(0), e([sections count]); i != e; ++i) {
2719 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2720 return i;
e057ec05 2721 }
2d28b35a 2722
6932575e 2723 return _not(uint32_t);
e057ec05 2724}
2d28b35a 2725
f159ecd4
JF
2726- (uint32_t) compareForChanges {
2727 union {
2728 uint32_t key;
2d28b35a 2729
f159ecd4
JF
2730 struct {
2731 uint32_t timestamp : 30;
2732 uint32_t ignored : 1;
2733 uint32_t upgradable : 1;
2734 } bits;
2735 } value;
2d28b35a 2736
5c87d61b
JF
2737 bool upgradable([self upgradableAndEssential:YES]);
2738 value.bits.upgradable = upgradable ? 1 : 0;
b6ffa083 2739
5c87d61b 2740 if (upgradable) {
f159ecd4
JF
2741 value.bits.timestamp = 0;
2742 value.bits.ignored = [self ignored] ? 0 : 1;
2743 value.bits.upgradable = 1;
2744 } else {
2745 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2746 value.bits.ignored = 0;
2747 value.bits.upgradable = 0;
e057ec05 2748 }
b6ffa083 2749
f159ecd4 2750 return _not(uint32_t) - value.key;
e057ec05 2751}
b6ffa083 2752
3ff1504e
JF
2753- (void) clear {
2754 pkgProblemResolver *resolver = [database_ resolver];
2755 resolver->Clear(iterator_);
2756 resolver->Protect(iterator_);
2757}
2758
e057ec05
JF
2759- (void) install {
2760 pkgProblemResolver *resolver = [database_ resolver];
2761 resolver->Clear(iterator_);
2762 resolver->Protect(iterator_);
2763 pkgCacheFile &cache([database_ cache]);
2764 cache->MarkInstall(iterator_, false);
2765 pkgDepCache::StateCache &state((*cache)[iterator_]);
2766 if (!state.Install())
2767 cache->SetReInstall(iterator_, true);
2768}
0f25fa58 2769
e057ec05
JF
2770- (void) remove {
2771 pkgProblemResolver *resolver = [database_ resolver];
2772 resolver->Clear(iterator_);
2773 resolver->Protect(iterator_);
2774 resolver->Remove(iterator_);
2775 [database_ cache]->MarkDelete(iterator_, true);
2776}
b6ffa083 2777
7cf54836 2778- (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3bddda52
JF
2779 _profile(Package$isUnfilteredAndSearchedForBy)
2780 bool value(true);
2781
2782 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2783 value &= [self unfiltered];
2784 _end
2785
2786 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2787 value &= [self matches:search];
2788 _end
2789
7cf54836 2790 return value;
3bddda52 2791 _end
e057ec05 2792}
b6ffa083 2793
5ec44e34 2794- (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
37455cf8
JF
2795 if ([search length] == 0)
2796 return false;
2797
5ec44e34
JF
2798 _profile(Package$isUnfilteredAndSelectedForBy)
2799 bool value(true);
2800
2801 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2802 value &= [self unfiltered];
2803 _end
2804
2805 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2806 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2807 _end
2808
2809 return value;
2810 _end
2811}
2812
7cf54836 2813- (bool) isInstalledAndVisible:(NSNumber *)number {
b4c4fac4 2814 return (![number boolValue] || [self visible]) && ![self uninstalled];
e057ec05 2815}
b6ffa083 2816
6981ccdf 2817- (bool) isVisibleInSection:(NSString *)name {
965edd52
JF
2818 NSString *section = [self section];
2819
7cf54836 2820 return
6981ccdf 2821 [self visible] && (
faf4eb4f
JF
2822 name == nil ||
2823 section == nil && [name length] == 0 ||
2824 [name isEqualToString:section]
7cf54836 2825 );
faf4eb4f
JF
2826}
2827
7cf54836
JF
2828- (bool) isVisibleInSource:(Source *)source {
2829 return [self source] == source && [self visible];
e057ec05 2830}
b6ffa083 2831
e057ec05
JF
2832@end
2833/* }}} */
2834/* Section Class {{{ */
2835@interface Section : NSObject {
2836 NSString *name_;
3bddda52 2837 unichar index_;
e057ec05
JF
2838 size_t row_;
2839 size_t count_;
6932575e 2840 NSString *localized_;
e057ec05 2841}
2d28b35a 2842
43b742af 2843- (NSComparisonResult) compareByLocalized:(Section *)section;
9ee296df
JF
2844- (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2845- (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2846- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3bddda52 2847- (Section *) initWithIndex:(unichar)index row:(size_t)row;
e057ec05 2848- (NSString *) name;
3bddda52 2849- (unichar) index;
6932575e 2850
e057ec05
JF
2851- (size_t) row;
2852- (size_t) count;
6932575e
JF
2853
2854- (void) addToRow;
e057ec05 2855- (void) addToCount;
a933cee2 2856
6932575e 2857- (void) setCount:(size_t)count;
43b742af 2858- (NSString *) localized;
6932575e 2859
e057ec05 2860@end
a933cee2 2861
e057ec05 2862@implementation Section
a933cee2 2863
e057ec05
JF
2864- (void) dealloc {
2865 [name_ release];
6932575e
JF
2866 if (localized_ != nil)
2867 [localized_ release];
e057ec05
JF
2868 [super dealloc];
2869}
a933cee2 2870
43b742af 2871- (NSComparisonResult) compareByLocalized:(Section *)section {
9ee296df
JF
2872 NSString *lhs(localized_);
2873 NSString *rhs([section localized]);
fa7bb92f 2874
9ee296df 2875 /*if ([lhs length] != 0 && [rhs length] != 0) {
fa7bb92f
JF
2876 unichar lhc = [lhs characterAtIndex:0];
2877 unichar rhc = [rhs characterAtIndex:0];
2878
2879 if (isalpha(lhc) && !isalpha(rhc))
2880 return NSOrderedAscending;
2881 else if (!isalpha(lhc) && isalpha(rhc))
2882 return NSOrderedDescending;
9ee296df 2883 }*/
fa7bb92f 2884
9c4e0cbe 2885 return [lhs compare:rhs options:LaxCompareOptions_];
fa7bb92f
JF
2886}
2887
9ee296df
JF
2888- (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2889 if ((self = [self initWithName:name localize:NO]) != nil) {
2890 if (localized != nil)
2891 localized_ = [localized retain];
2892 } return self;
2893}
2894
2895- (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2896 return [self initWithName:name row:0 localize:localize];
fa7bb92f
JF
2897}
2898
9ee296df 2899- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
e057ec05
JF
2900 if ((self = [super init]) != nil) {
2901 name_ = [name retain];
3bddda52
JF
2902 index_ = '\0';
2903 row_ = row;
9ee296df
JF
2904 if (localize)
2905 localized_ = [LocalizeSection(name_) retain];
3bddda52
JF
2906 } return self;
2907}
2908
6932575e 2909/* XXX: localize the index thingees */
3bddda52
JF
2910- (Section *) initWithIndex:(unichar)index row:(size_t)row {
2911 if ((self = [super init]) != nil) {
5d8f1006 2912 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3bddda52 2913 index_ = index;
e057ec05 2914 row_ = row;
a933cee2
JF
2915 } return self;
2916}
2917
e057ec05
JF
2918- (NSString *) name {
2919 return name_;
2920}
2921
3bddda52
JF
2922- (unichar) index {
2923 return index_;
2924}
2925
e057ec05
JF
2926- (size_t) row {
2927 return row_;
2928}
2929
2930- (size_t) count {
2931 return count_;
2932}
2933
6932575e
JF
2934- (void) addToRow {
2935 ++row_;
2936}
2937
e057ec05
JF
2938- (void) addToCount {
2939 ++count_;
2940}
2941
6932575e
JF
2942- (void) setCount:(size_t)count {
2943 count_ = count;
2944}
2945
2946- (NSString *) localized {
2947 return localized_;
2948}
2949
a933cee2
JF
2950@end
2951/* }}} */
2952
6981ccdf
JF
2953static NSString *Colon_;
2954static NSString *Error_;
2955static NSString *Warning_;
2956
e057ec05
JF
2957/* Database Implementation {{{ */
2958@implementation Database
1cb11c5f 2959
dbe0f181
JF
2960+ (Database *) sharedInstance {
2961 static Database *instance;
2962 if (instance == nil)
2963 instance = [[Database alloc] init];
2964 return instance;
2965}
2966
a70cf746
JF
2967- (unsigned) era {
2968 return era_;
2969}
2970
e057ec05
JF
2971- (void) dealloc {
2972 _assert(false);
6932575e
JF
2973 NSRecycleZone(zone_);
2974 // XXX: malloc_destroy_zone(zone_);
2975 apr_pool_destroy(pool_);
e057ec05
JF
2976 [super dealloc];
2977}
1cb11c5f 2978
f464053e 2979- (void) _readCydia:(NSNumber *)fd { _pooled
d72d91aa
JF
2980 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2981 std::istream is(&ib);
2982 std::string line;
2983
03d01f0e
JF
2984 static Pcre finish_r("^finish:([^:]*)$");
2985
d72d91aa
JF
2986 while (std::getline(is, line)) {
2987 const char *data(line.c_str());
03d01f0e 2988 size_t size = line.size();
cb9c2100 2989 lprintf("C:%s\n", data);
03d01f0e
JF
2990
2991 if (finish_r(data, size)) {
2992 NSString *finish = finish_r[1];
2993 int index = [Finishes_ indexOfObject:finish];
2994 if (index != INT_MAX && index > Finish_)
2995 Finish_ = index;
2996 }
d72d91aa
JF
2997 }
2998
6981ccdf 2999 _assume(false);
d72d91aa
JF
3000}
3001
f464053e 3002- (void) _readStatus:(NSNumber *)fd { _pooled
e057ec05
JF
3003 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3004 std::istream is(&ib);
3005 std::string line;
1cb11c5f 3006
faf4eb4f
JF
3007 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3008 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
1cb11c5f 3009
e057ec05
JF
3010 while (std::getline(is, line)) {
3011 const char *data(line.c_str());
6981ccdf 3012 size_t size(line.size());
cb9c2100 3013 lprintf("S:%s\n", data);
1cb11c5f 3014
965edd52
JF
3015 if (conffile_r(data, size)) {
3016 [delegate_ setConfigurationData:conffile_r[1]];
3017 } else if (strncmp(data, "status: ", 8) == 0) {
3018 NSString *string = [NSString stringWithUTF8String:(data + 8)];
e057ec05 3019 [delegate_ setProgressTitle:string];
965edd52 3020 } else if (pmstatus_r(data, size)) {
238b07ce
JF
3021 std::string type([pmstatus_r[1] UTF8String]);
3022 NSString *id = pmstatus_r[2];
3023
965edd52
JF
3024 float percent([pmstatus_r[3] floatValue]);
3025 [delegate_ setProgressPercent:(percent / 100)];
3026
3027 NSString *string = pmstatus_r[4];
965edd52
JF
3028
3029 if (type == "pmerror")
6981ccdf 3030 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
238b07ce
JF
3031 withObject:[NSArray arrayWithObjects:string, id, nil]
3032 waitUntilDone:YES
3033 ];
907a35d6 3034 else if (type == "pmstatus") {
965edd52 3035 [delegate_ setProgressTitle:string];
907a35d6 3036 } else if (type == "pmconffile")
965edd52 3037 [delegate_ setConfigurationData:string];
6981ccdf
JF
3038 else
3039 lprintf("E:unknown pmstatus\n");
3040 } else
3041 lprintf("E:unknown status\n");
e057ec05 3042 }
1cb11c5f 3043
6981ccdf 3044 _assume(false);
e057ec05 3045}
1cb11c5f 3046
f464053e 3047- (void) _readOutput:(NSNumber *)fd { _pooled
e057ec05
JF
3048 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3049 std::istream is(&ib);
3050 std::string line;
3051
965edd52 3052 while (std::getline(is, line)) {
cb9c2100 3053 lprintf("O:%s\n", line.c_str());
2a987aa5 3054 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
965edd52 3055 }
e057ec05 3056
6981ccdf 3057 _assume(false);
1cb11c5f
JF
3058}
3059
7600bd69
JF
3060- (FILE *) input {
3061 return input_;
3062}
3063
e057ec05 3064- (Package *) packageWithName:(NSString *)name {
ca06bb0e 3065@synchronized ([Database class]) {
965edd52
JF
3066 if (static_cast<pkgDepCache *>(cache_) == NULL)
3067 return nil;
e057ec05 3068 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
6932575e 3069 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
ca06bb0e 3070} }
e057ec05
JF
3071
3072- (Database *) init {
1cb11c5f 3073 if ((self = [super init]) != nil) {
965edd52 3074 policy_ = NULL;
e057ec05
JF
3075 records_ = NULL;
3076 resolver_ = NULL;
3077 fetcher_ = NULL;
3078 lock_ = NULL;
1cb11c5f 3079
6932575e
JF
3080 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3081 apr_pool_create(&pool_, NULL);
3082
9ee296df 3083 packages_ = [[NSMutableArray alloc] init];
1cb11c5f 3084
e057ec05 3085 int fds[2];
1cb11c5f 3086
d72d91aa
JF
3087 _assert(pipe(fds) != -1);
3088 cydiafd_ = fds[1];
3089
3090 _config->Set("APT::Keep-Fds::", cydiafd_);
03d01f0e 3091 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
d72d91aa
JF
3092
3093 [NSThread
3094 detachNewThreadSelector:@selector(_readCydia:)
3095 toTarget:self
3096 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3097 ];
3098
e057ec05
JF
3099 _assert(pipe(fds) != -1);
3100 statusfd_ = fds[1];
1cb11c5f 3101
e057ec05
JF
3102 [NSThread
3103 detachNewThreadSelector:@selector(_readStatus:)
3104 toTarget:self
3105 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3106 ];
1cb11c5f 3107
7600bd69
JF
3108 _assert(pipe(fds) != -1);
3109 _assert(dup2(fds[0], 0) != -1);
3110 _assert(close(fds[0]) != -1);
3111
3112 input_ = fdopen(fds[1], "a");
3113
e057ec05
JF
3114 _assert(pipe(fds) != -1);
3115 _assert(dup2(fds[1], 1) != -1);
3116 _assert(close(fds[1]) != -1);
3117
3118 [NSThread
3119 detachNewThreadSelector:@selector(_readOutput:)
3120 toTarget:self
3121 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3122 ];
1cb11c5f
JF
3123 } return self;
3124}
3125
e057ec05
JF
3126- (pkgCacheFile &) cache {
3127 return cache_;
1cb11c5f
JF
3128}
3129
965edd52
JF
3130- (pkgDepCache::Policy *) policy {
3131 return policy_;
3132}
3133
e057ec05
JF
3134- (pkgRecords *) records {
3135 return records_;
1cb11c5f
JF
3136}
3137
e057ec05
JF
3138- (pkgProblemResolver *) resolver {
3139 return resolver_;
1cb11c5f
JF
3140}
3141
e057ec05
JF
3142- (pkgAcquire &) fetcher {
3143 return *fetcher_;
1cb11c5f
JF
3144}
3145
ce09fc27
JF
3146- (pkgSourceList &) list {
3147 return *list_;
3148}
3149
e057ec05
JF
3150- (NSArray *) packages {
3151 return packages_;
1cb11c5f
JF
3152}
3153
faf4eb4f 3154- (NSArray *) sources {
631a0a1e
JF
3155 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3156 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3157 [sources addObject:i->second];
3158 return sources;
faf4eb4f
JF
3159}
3160
f464053e
JF
3161- (NSArray *) issues {
3162 if (cache_->BrokenCount() == 0)
3163 return nil;
3164
3165 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3166
3167 for (Package *package in packages_) {
3168 if (![package broken])
3169 continue;
3170 pkgCache::PkgIterator pkg([package iterator]);
3171
3172 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3173 [entry addObject:[package name]];
3174 [issues addObject:entry];
3175
3176 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3177 if (ver.end())
3178 continue;
3179
3180 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3181 pkgCache::DepIterator start;
3182 pkgCache::DepIterator end;
3183 dep.GlobOr(start, end); // ++dep
3184
3185 if (!cache_->IsImportantDep(end))
3186 continue;
3187 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3188 continue;
3189
3190 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3191 [entry addObject:failure];
3192 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3193
e4765783
JF
3194 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3195 if (Package *package = [self packageWithName:name])
3196 name = [package name];
3197 [failure addObject:name];
f464053e
JF
3198
3199 pkgCache::PkgIterator target(start.TargetPkg());
3200 if (target->ProvidesList != 0)
3201 [failure addObject:@"?"];
3202 else {
3203 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3204 if (!ver.end())
3205 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3206 else if (!cache_[target].CandidateVerIter(cache_).end())
3207 [failure addObject:@"-"];
3208 else if (target->ProvidesList == 0)
3209 [failure addObject:@"!"];
3210 else
3211 [failure addObject:@"%"];
3212 }
3213
3214 _forever {
3215 if (start.TargetVer() != 0)
3216 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3217 if (start == end)
3218 break;
3219 ++start;
3220 }
3221 }
3222 }
3223
3224 return issues;
3225}
3226
6981ccdf
JF
3227- (bool) popErrorWithTitle:(NSString *)title {
3228 bool fatal(false);
3229 std::string message;
3230
3231 while (!_error->empty()) {
3232 std::string error;
3233 bool warning(!_error->PopMessage(error));
3234 if (!warning)
3235 fatal = true;
3236 for (;;) {
3237 size_t size(error.size());
3238 if (size == 0 || error[size - 1] != '\n')
3239 break;
3240 error.resize(size - 1);
3241 }
3242 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3243
3244 if (!message.empty())
3245 message += "\n\n";
3246 message += error;
3247 }
3248
281f523c 3249 if (fatal && !message.empty())
6981ccdf
JF
3250 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3251
3252 return fatal;
3253}
3254
3255- (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3256 return [self popErrorWithTitle:title] || !success;
3257}
3258
7398a389 3259- (void) reloadData { _pooled
ca06bb0e 3260@synchronized ([Database class]) {
a70cf746
JF
3261 @synchronized (self) {
3262 ++era_;
3263 }
3264
98fb9119
JF
3265 [packages_ removeAllObjects];
3266 sources_.clear();
3267
e057ec05 3268 _error->Discard();
965edd52 3269
e057ec05 3270 delete list_;
965edd52 3271 list_ = NULL;
e057ec05
JF
3272 manager_ = NULL;
3273 delete lock_;
965edd52 3274 lock_ = NULL;
e057ec05 3275 delete fetcher_;
965edd52 3276 fetcher_ = NULL;
e057ec05 3277 delete resolver_;
965edd52 3278 resolver_ = NULL;
e057ec05 3279 delete records_;
965edd52
JF
3280 records_ = NULL;
3281 delete policy_;
3282 policy_ = NULL;
e057ec05 3283
98fb9119
JF
3284 if (now_ != nil) {
3285 [now_ release];
3286 now_ = nil;
3287 }
3288
965edd52 3289 cache_.Close();
7600bd69 3290
6932575e
JF
3291 apr_pool_clear(pool_);
3292 NSRecycleZone(zone_);
3293
3e3977a2
JF
3294 int chk(creat("/tmp/cydia.chk", 0644));
3295 if (chk != -1)
3296 close(chk);
3297
6981ccdf
JF
3298 NSString *title(UCLocalize("DATABASE"));
3299
907a35d6 3300 _trace();
6981ccdf 3301 if (!cache_.Open(progress_, true)) { pop:
7600bd69 3302 std::string error;
6981ccdf 3303 bool warning(!_error->PopMessage(error));
cb9c2100 3304 lprintf("cache_.Open():[%s]\n", error.c_str());
965edd52
JF
3305
3306 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3307 [delegate_ repairWithSelector:@selector(configure)];
3308 else if (error == "The package lists or status file could not be parsed or opened.")
3309 [delegate_ repairWithSelector:@selector(update)];
fc19e583
JF
3310 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3311 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3312 // else if (error == "The list of sources could not be read.")
6981ccdf
JF
3313 else
3314 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
965edd52 3315
6981ccdf
JF
3316 if (warning)
3317 goto pop;
3318 _error->Discard();
965edd52 3319 return;
e057ec05 3320 }
907a35d6 3321 _trace();
e057ec05 3322
3e3977a2
JF
3323 unlink("/tmp/cydia.chk");
3324
e057ec05
JF
3325 now_ = [[NSDate date] retain];
3326
965edd52 3327 policy_ = new pkgDepCache::Policy();
e057ec05
JF
3328 records_ = new pkgRecords(cache_);
3329 resolver_ = new pkgProblemResolver(cache_);
3330 fetcher_ = new pkgAcquire(&status_);
3331 lock_ = NULL;
3332
3333 list_ = new pkgSourceList();
6981ccdf
JF
3334 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3335 return;
3336
3337 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3338 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3339 return;
3340 }
e057ec05 3341
6981ccdf
JF
3342 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3343 return;
3319715b
JF
3344
3345 if (cache_->BrokenCount() != 0) {
6981ccdf
JF
3346 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3347 return;
3348
3349 if (cache_->BrokenCount() != 0) {
3350 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3351 return;
3352 }
3353
3354 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3355 return;
3319715b
JF
3356 }
3357
3e3977a2 3358 _trace();
631a0a1e 3359
631a0a1e
JF
3360 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3361 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3362 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3363 // XXX: this could be more intelligent
3364 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3365 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3366 if (!cached.end())
b8b1cfd0 3367 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
631a0a1e 3368 }
e057ec05 3369 }
631a0a1e 3370
3e3977a2 3371 _trace();
e057ec05 3372
43b742af 3373 {
9ee296df 3374 /*std::vector<Package *> packages;
43b742af 3375 packages.reserve(std::max(10000U, [packages_ count] + 1000));
43b742af 3376 [packages_ release];
9ee296df
JF
3377 packages_ = nil;*/
3378
43b742af
JF
3379 _trace();
3380
3381 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3382 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
9ee296df
JF
3383 //packages.push_back(package);
3384 [packages_ addObject:package];
43b742af
JF
3385
3386 _trace();
3387
9ee296df 3388 /*if (packages.empty())
43b742af
JF
3389 packages_ = [[NSArray alloc] init];
3390 else
3391 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
9ee296df
JF
3392 _trace();*/
3393
dd9390c5
JF
3394 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3395 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3396 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
9ee296df
JF
3397
3398 /*_trace();
3399 PrintTimes();
3400 _trace();*/
3401
3402 _trace();
3403
3404 /*if (!packages.empty())
3405 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3406 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3407
66abcbb0
JF
3408 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3409
dd9390c5 3410 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
9ee296df
JF
3411
3412 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
43b742af
JF
3413
3414 _trace();
3415 }
ca06bb0e 3416} }
1cb11c5f 3417
965edd52
JF
3418- (void) configure {
3419 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3420 system([dpkg UTF8String]);
3421}
3422
6981ccdf
JF
3423- (bool) clean {
3424 // XXX: I don't remember this condition
d72d91aa 3425 if (lock_ != NULL)
6981ccdf 3426 return false;
d72d91aa
JF
3427
3428 FileFd Lock;
3429 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
6981ccdf
JF
3430
3431 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3432
3433 if ([self popErrorWithTitle:title])
3434 return false;
d72d91aa
JF
3435
3436 pkgAcquire fetcher;
3437 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3438
3319715b
JF
3439 class LogCleaner :
3440 public pkgArchiveCleaner
3441 {
d72d91aa
JF
3442 protected:
3443 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3319715b 3444 unlink(File);
d72d91aa
JF
3445 }
3446 } cleaner;
3447
6981ccdf
JF
3448 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3449 return false;
3450
3451 return true;
d72d91aa
JF
3452}
3453
6981ccdf 3454- (bool) prepare {
e4765783
JF
3455 fetcher_->Shutdown();
3456
e057ec05
JF
3457 pkgRecords records(cache_);
3458
3459 lock_ = new FileFd();
3460 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
6981ccdf
JF
3461
3462 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3463
3464 if ([self popErrorWithTitle:title])
3465 return false;
e057ec05
JF
3466
3467 pkgSourceList list;
6981ccdf
JF
3468 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3469 return false;
e057ec05
JF
3470
3471 manager_ = (_system->CreatePM(cache_));
6981ccdf
JF
3472 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3473 return false;
3474
3475 return true;
1cb11c5f
JF
3476}
3477
e057ec05 3478- (void) perform {
6981ccdf
JF
3479 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3480
113c9b62
JF
3481 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3482 pkgSourceList list;
6981ccdf
JF
3483 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3484 return;
113c9b62
JF
3485 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3486 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3487 }
8993ad57 3488
2d7f7dea
JF
3489 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3490 _trace();
e057ec05 3491 return;
2d7f7dea
JF
3492 }
3493
3494 bool failed = false;
3495 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3496 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3497 continue;
9050015e
JF
3498 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3499 continue;
2d7f7dea
JF
3500
3501 std::string uri = (*item)->DescURI();
3502 std::string error = (*item)->ErrorText;
3503
cb9c2100 3504 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
2d7f7dea
JF
3505 failed = true;
3506
6981ccdf 3507 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
ce09fc27
JF
3508 withObject:[NSArray arrayWithObjects:
3509 [NSString stringWithUTF8String:error.c_str()],
3510 nil]
2d7f7dea
JF
3511 waitUntilDone:YES
3512 ];
3513 }
3514
3515 if (failed) {
3516 _trace();
3517 return;
3518 }
e057ec05
JF
3519
3520 _system->UnLock();
3521 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3522
2d7f7dea
JF
3523 if (_error->PendingError()) {
3524 _trace();
e057ec05 3525 return;
2d7f7dea
JF
3526 }
3527
3528 if (result == pkgPackageManager::Failed) {
3529 _trace();
e057ec05 3530 return;
2d7f7dea
JF
3531 }
3532
3533 if (result != pkgPackageManager::Completed) {
3534 _trace();
e057ec05 3535 return;
2d7f7dea 3536 }
8993ad57 3537
113c9b62
JF
3538 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3539 pkgSourceList list;
6981ccdf
JF
3540 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3541 return;
113c9b62
JF
3542 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3543 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3544 }
3545
3546 if (![before isEqualToArray:after])
3547 [self update];
1cb11c5f
JF
3548}
3549
6981ccdf
JF
3550- (bool) upgrade {
3551 NSString *title(UCLocalize("UPGRADE"));
3552 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3553 return false;
3554 return true;
1951a333
JF
3555}
3556
e057ec05
JF
3557- (void) update {
3558 [self updateWithStatus:status_];
3559}
686e302f 3560
419a9efd
JF
3561- (void) setVisible {
3562 for (Package *package in packages_)
3563 [package setVisible];
3564}
3565
6981ccdf
JF
3566- (void) updateWithStatus:(Status &)status {
3567 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3568 NSString *title(UCLocalize("REFRESHING_DATA"));
3569
e057ec05 3570 pkgSourceList list;
6981ccdf
JF
3571 if (!list.ReadMainList())
3572 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
686e302f 3573
e057ec05
JF
3574 FileFd lock;
3575 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
6981ccdf
JF
3576 if ([self popErrorWithTitle:title])
3577 return;
f30eaf83 3578
6981ccdf 3579 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
281f523c 3580 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
e057ec05 3581
419a9efd
JF
3582 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3583 Changed_ = true;
686e302f
JF
3584}
3585
e057ec05
JF
3586- (void) setDelegate:(id)delegate {
3587 delegate_ = delegate;
3588 status_.setDelegate(delegate);
3589 progress_.setDelegate(delegate);
3590}
686e302f 3591
3e3977a2 3592- (Source *) getSource:(pkgCache::PkgFileIterator)file {
1636cf29
JF
3593 SourceMap::const_iterator i(sources_.find(file->ID));
3594 return i == sources_.end() ? nil : i->second;
a933cee2
JF
3595}
3596
e057ec05
JF
3597@end
3598/* }}} */
686e302f 3599
f441e717 3600/* Confirmation Controller {{{ */
61b13cae
JF
3601bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3602 if (!iterator.end())
3603 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3604 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3605 continue;
3606 pkgCache::PkgIterator package(dep.TargetPkg());
3607 if (package.end())
3608 continue;
3609 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3610 return true;
3611 }
3612
3613 return false;
cb9c2100 3614}
9ae52960 3615/* }}} */
cb9c2100 3616
61b13cae
JF
3617/* Web Scripting {{{ */
3618@interface CydiaObject : NSObject {
3619 id indirect_;
daf7f6e2 3620 id delegate_;
61b13cae 3621}
cb9c2100 3622
61b13cae 3623- (id) initWithDelegate:(IndirectDelegate *)indirect;
cb9c2100
JF
3624@end
3625
61b13cae 3626@implementation CydiaObject
cb9c2100
JF
3627
3628- (void) dealloc {
61b13cae 3629 [indirect_ release];
cb9c2100
JF
3630 [super dealloc];
3631}
3632
61b13cae
JF
3633- (id) initWithDelegate:(IndirectDelegate *)indirect {
3634 if ((self = [super init]) != nil) {
3635 indirect_ = [indirect retain];
3636 } return self;
3637}
3638
daf7f6e2
JF
3639- (void) setDelegate:(id)delegate {
3640 delegate_ = delegate;
3641}
3642
61b13cae
JF
3643+ (NSArray *) _attributeKeys {
3644 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3645}
3646
3647- (NSArray *) attributeKeys {
3648 return [[self class] _attributeKeys];
cb9c2100
JF
3649}
3650
61b13cae
JF
3651+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3652 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
cb9c2100 3653}
61b13cae
JF
3654
3655- (NSString *) device {
3656 return [[UIDevice currentDevice] uniqueIdentifier];
cb9c2100
JF
3657}
3658
61b13cae
JF
3659#if 0 // XXX: implement!
3660- (NSString *) mac {
3661 if (![indirect_ promptForSensitive:@"Mac Address"])
3662 return nil;
f464053e
JF
3663}
3664
61b13cae
JF
3665- (NSString *) serial {
3666 if (![indirect_ promptForSensitive:@"Serial #"])
3667 return nil;
3668}
56e10908 3669
61b13cae
JF
3670- (NSString *) firewire {
3671 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3672 return nil;
f464053e
JF
3673}
3674
61b13cae
JF
3675- (NSString *) imei {
3676 if (![indirect_ promptForSensitive:@"IMEI"])
3677 return nil;
3678}
3679#endif
3680
3681+ (NSString *) webScriptNameForSelector:(SEL)selector {
3682 if (selector == @selector(close))
3683 return @"close";
22b21e43
JF
3684 else if (selector == @selector(getInstalledPackages))
3685 return @"getInstalledPackages";
61b13cae
JF
3686 else if (selector == @selector(getPackageById:))
3687 return @"getPackageById";
daf7f6e2
JF
3688 else if (selector == @selector(installPackages:))
3689 return @"installPackages";
61b13cae
JF
3690 else if (selector == @selector(setAutoPopup:))
3691 return @"setAutoPopup";
3692 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3693 return @"setButtonImage";
3694 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3695 return @"setButtonTitle";
3696 else if (selector == @selector(setFinishHook:))
3697 return @"setFinishHook";
3698 else if (selector == @selector(setPopupHook:))
3699 return @"setPopupHook";
3700 else if (selector == @selector(setSpecial:))
3701 return @"setSpecial";
37455cf8
JF
3702 else if (selector == @selector(setToken:))
3703 return @"setToken";
61b13cae
JF
3704 else if (selector == @selector(setViewportWidth:))
3705 return @"setViewportWidth";
3706 else if (selector == @selector(supports:))
3707 return @"supports";
3708 else if (selector == @selector(stringWithFormat:arguments:))
3709 return @"format";
3710 else if (selector == @selector(localizedStringForKey:value:table:))
3711 return @"localize";
3712 else if (selector == @selector(du:))
3713 return @"du";
3714 else if (selector == @selector(statfs:))
3715 return @"statfs";
cb9c2100 3716 else
61b13cae
JF
3717 return nil;
3718}
3719
3720+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3721 return [self webScriptNameForSelector:selector] == nil;
cb9c2100
JF
3722}
3723
61b13cae
JF
3724- (BOOL) supports:(NSString *)feature {
3725 return [feature isEqualToString:@"window.open"];
3726}
cb9c2100 3727
22b21e43
JF
3728- (NSArray *) getInstalledPackages {
3729 NSArray *packages([[Database sharedInstance] packages]);
3730 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
daf7f6e2 3731 for (Package *package in packages)
22b21e43
JF
3732 if ([package installed] != nil)
3733 [installed addObject:package];
3734 return installed;
3735}
3736
61b13cae 3737- (Package *) getPackageById:(NSString *)id {
e32f0fcb
JF
3738 Package *package([[Database sharedInstance] packageWithName:id]);
3739 [package parse];
3740 return package;
61b13cae
JF
3741}
3742
3743- (NSArray *) statfs:(NSString *)path {
3744 struct statfs stat;
3745
3746 if (path == nil || statfs([path UTF8String], &stat) == -1)
3747 return nil;
3748
3749 return [NSArray arrayWithObjects:
3750 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3751 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3752 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3753 nil];
3754}
3755
3756- (NSNumber *) du:(NSString *)path {
3757 NSNumber *value(nil);
3758
3759 int fds[2];
3760 _assert(pipe(fds) != -1);
3761
3762 pid_t pid(ExecFork());
3763 if (pid == 0) {
3764 _assert(dup2(fds[1], 1) != -1);
3765 _assert(close(fds[0]) != -1);
3766 _assert(close(fds[1]) != -1);
3767 /* XXX: this should probably not use du */
3768 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3769 exit(1);
3770 _assert(false);
3771 }
3772
3773 _assert(close(fds[1]) != -1);
3774
3775 if (FILE *du = fdopen(fds[0], "r")) {
3776 char line[1024];
3777 while (fgets(line, sizeof(line), du) != NULL) {
3778 size_t length(strlen(line));
3779 while (length != 0 && line[length - 1] == '\n')
3780 line[--length] = '\0';
3781 if (char *tab = strchr(line, '\t')) {
3782 *tab = '\0';
3783 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3784 }
3785 }
3786
3787 fclose(du);
3788 } else _assert(close(fds[0]));
3789
3790 int status;
3791 wait:
3792 if (waitpid(pid, &status, 0) == -1)
3793 if (errno == EINTR)
3794 goto wait;
3795 else _assert(false);
3796
3797 return value;
3798}
3799
3800- (void) close {
3801 [indirect_ close];
3802}
3803
daf7f6e2
JF
3804- (void) installPackages:(NSArray *)packages {
3805 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3806}
3807
61b13cae
JF
3808- (void) setAutoPopup:(BOOL)popup {
3809 [indirect_ setAutoPopup:popup];
3810}
3811
3812- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3813 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3814}
3815
3816- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3817 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3818}
3819
3820- (void) setSpecial:(id)function {
3821 [indirect_ setSpecial:function];
3822}
3823
37455cf8
JF
3824- (void) setToken:(NSString *)token {
3825 if (Token_ != nil)
3826 [Token_ release];
3827 Token_ = [token retain];
3828
3829 [Metadata_ setObject:Token_ forKey:@"Token"];
3830 Changed_ = true;
3831}
3832
61b13cae
JF
3833- (void) setFinishHook:(id)function {
3834 [indirect_ setFinishHook:function];
3835}
3836
3837- (void) setPopupHook:(id)function {
3838 [indirect_ setPopupHook:function];
3839}
3840
3841- (void) setViewportWidth:(float)width {
3842 [indirect_ setViewportWidth:width];
3843}
3844
3845- (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3846 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3847 unsigned count([arguments count]);
3848 id values[count];
3849 for (unsigned i(0); i != count; ++i)
3850 values[i] = [arguments objectAtIndex:i];
3851 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3852}
3853
3854- (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
e1316e10
JF
3855 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3856 value = nil;
61b13cae
JF
3857 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3858 table = nil;
3859 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
cb9c2100
JF
3860}
3861
3862@end
3863/* }}} */
6932575e 3864
9ae52960
GP
3865/* Cydia View Controller {{{ */
3866@interface CYViewController : UCViewController { }
3867@end
3868
3869@implementation CYViewController
3870@end
3871/* }}} */
3872
ed349d9a 3873@interface CYBrowserController : BrowserController {
61b13cae
JF
3874 CydiaObject *cydia_;
3875}
e00439f7 3876
61b13cae
JF
3877@end
3878
9ae52960 3879@implementation CYBrowserController
61b13cae
JF
3880
3881- (void) dealloc {
3882 [cydia_ release];
3883 [super dealloc];
3884}
3885
5ec44e34
JF
3886- (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3887}
3888
61b13cae
JF
3889- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3890 [super webView:sender didClearWindowObject:window forFrame:frame];
5ec44e34
JF
3891
3892 WebDataSource *source([frame dataSource]);
3893 NSURLResponse *response([source response]);
3894 NSURL *url([response URL]);
3895 NSString *scheme([url scheme]);
3896
3897 NSHTTPURLResponse *http;
3898 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3899 http = (NSHTTPURLResponse *) response;
3900 else
3901 http = nil;
3902
3903 NSDictionary *headers([http allHeaderFields]);
3904 NSString *host([url host]);
3905 [self setHeaders:headers forHost:host];
3906
daf7f6e2
JF
3907 if (
3908 [host isEqualToString:@"cydia.saurik.com"] ||
3909 [host hasSuffix:@".cydia.saurik.com"] ||
3910 [scheme isEqualToString:@"file"]
3911 )
37455cf8 3912 [window setValue:cydia_ forKey:@"cydia"];
61b13cae
JF
3913}
3914
017b2b71
JF
3915- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3916 if (System_ != NULL)
3917 [request setValue:System_ forHTTPHeaderField:@"X-System"];
61b13cae 3918 if (Machine_ != NULL)
017b2b71 3919 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5ec44e34
JF
3920 if (Token_ != nil)
3921 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
61b13cae 3922 if (Role_ != nil)
017b2b71
JF
3923 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3924}
61b13cae 3925
017b2b71
JF
3926- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3927 NSMutableURLRequest *copy = [request mutableCopy];
3928 [self _setMoreHeaders:copy];
61b13cae 3929 return copy;
e00439f7
JF
3930}
3931
daf7f6e2
JF
3932- (void) setDelegate:(id)delegate {
3933 [super setDelegate:delegate];
3934 [cydia_ setDelegate:delegate];
3935}
3936
9ae52960 3937- (id) init {
2938b930 3938 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
61b13cae
JF
3939 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3940
84848968 3941 WebView *webview([document_ webView]);
61b13cae
JF
3942
3943 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
0a523b5a 3944
61b13cae
JF
3945 NSString *application = package == nil ? @"Cydia" : [NSString
3946 stringWithFormat:@"Cydia/%@",
3947 [package installed]
3948 ];
3949
61b13cae 3950 if (Safari_ != nil)
f26c1a7f 3951 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
0a523b5a 3952 if (Build_ != nil)
f26c1a7f 3953 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
0a523b5a 3954 if (Product_ != nil)
f26c1a7f 3955 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
61b13cae
JF
3956
3957 [webview setApplicationNameForUserAgent:application];
3958 } return self;
3959}
3960
3961@end
3962
f441e717 3963@protocol ConfirmationControllerDelegate
1ca35d78 3964- (void) cancelAndClear:(bool)clear;
9ae52960 3965- (void) confirmWithNavigationController:(UINavigationController *)navigation;
3ff1504e 3966- (void) queue;
e057ec05 3967@end
4941f41d 3968
f441e717 3969@interface ConfirmationController : CYBrowserController {
dbe0f181 3970 _transient Database *database_;
9c421310 3971 UIAlertView *essential_;
f464053e
JF
3972 NSArray *changes_;
3973 NSArray *issues_;
3974 NSArray *sizes_;
e00439f7 3975 BOOL substrate_;
e057ec05 3976}
a75f53e7 3977
9ae52960 3978- (id) initWithDatabase:(Database *)database;
686e302f 3979
a75f53e7
JF
3980@end
3981
f441e717 3982@implementation ConfirmationController
a75f53e7 3983
4941f41d 3984- (void) dealloc {
f464053e
JF
3985 [changes_ release];
3986 if (issues_ != nil)
3987 [issues_ release];
3988 [sizes_ release];
e057ec05
JF
3989 if (essential_ != nil)
3990 [essential_ release];
4941f41d
JF
3991 [super dealloc];
3992}
3993
9ae52960 3994- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9c421310 3995 NSString *context([alert context]);
3319715b 3996
a5dd312c 3997 if ([context isEqualToString:@"remove"]) {
9ae52960
GP
3998 if (button == [alert cancelButtonIndex]) {
3999 [self dismissModalViewControllerAnimated:YES];
9c421310 4000 } else if (button == [alert firstOtherButtonIndex]) {
9ae52960
GP
4001 if (substrate_)
4002 Finish_ = 2;
4003 [delegate_ confirmWithNavigationController:[self navigationController]];
3319715b 4004 }
3319715b 4005
9c421310 4006 [alert dismissWithClickedButtonIndex:-1 animated:YES];
a5dd312c 4007 } else if ([context isEqualToString:@"unable"]) {
9ae52960 4008 [self dismissModalViewControllerAnimated:YES];
9c421310
GP
4009 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4010 } else {
9ae52960
GP
4011 [super alertView:alert clickedButtonAtIndex:button];
4012 }
e057ec05
JF
4013}
4014
2064d251
GP
4015- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4016 [self dismissModalViewControllerAnimated:YES];
4017 [delegate_ cancelAndClear:NO];
f99f86e2 4018
2064d251
GP
4019 return nil;
4020}
4021
f464053e 4022- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6932575e 4023 [super webView:sender didClearWindowObject:window forFrame:frame];
f464053e
JF
4024 [window setValue:changes_ forKey:@"changes"];
4025 [window setValue:issues_ forKey:@"issues"];
4026 [window setValue:sizes_ forKey:@"sizes"];
2064d251 4027 [window setValue:self forKey:@"queue"];
e057ec05
JF
4028}
4029
9ae52960
GP
4030- (id) initWithDatabase:(Database *)database {
4031 if ((self = [super init]) != nil) {
dbe0f181
JF
4032 database_ = database;
4033
9ae52960
GP
4034 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4035
e057ec05
JF
4036 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4037 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4038 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4039 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4040 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
a75f53e7 4041
e057ec05 4042 bool remove(false);
a75f53e7 4043
e00439f7
JF
4044 pkgDepCache::Policy *policy([database_ policy]);
4045
e057ec05 4046 pkgCacheFile &cache([database_ cache]);
2a987aa5 4047 NSArray *packages = [database_ packages];
9fdd37d0 4048 for (Package *package in packages) {
2a987aa5 4049 pkgCache::PkgIterator iterator = [package iterator];
e057ec05 4050 pkgDepCache::StateCache &state(cache[iterator]);
a75f53e7 4051
2a987aa5
JF
4052 NSString *name([package name]);
4053
e057ec05
JF
4054 if (state.NewInstall())
4055 [installing addObject:name];
4056 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4057 [reinstalling addObject:name];
4058 else if (state.Upgrade())
4059 [upgrading addObject:name];
4060 else if (state.Downgrade())
4061 [downgrading addObject:name];
4062 else if (state.Delete()) {
2a987aa5 4063 if ([package essential])
e057ec05
JF
4064 remove = true;
4065 [removing addObject:name];
e00439f7
JF
4066 } else continue;
4067
4068 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4069 substrate_ |= DepSubstrate(iterator.CurrentVer());
e057ec05 4070 }
1cb11c5f 4071
e057ec05
JF
4072 if (!remove)
4073 essential_ = nil;
c59881cd 4074 else if (Advanced_) {
61b13cae 4075 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
6932575e 4076
9c421310 4077 essential_ = [[UIAlertView alloc]
61b13cae 4078 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
9ae52960
GP
4079 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4080 delegate:self
4081 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4082 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4083 ];
d3bef7bc 4084
9c421310 4085 [essential_ setContext:@"remove"];
3319715b 4086 } else {
9c421310 4087 essential_ = [[UIAlertView alloc]
61b13cae 4088 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
9ae52960
GP
4089 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4090 delegate:self
4091 cancelButtonTitle:UCLocalize("OKAY")
4092 otherButtonTitles:nil
e057ec05 4093 ];
1cb11c5f 4094
9ae52960 4095 [essential_ setContext:@"unable"];
e057ec05 4096 }
1cb11c5f 4097
f464053e
JF
4098 changes_ = [[NSArray alloc] initWithObjects:
4099 installing,
4100 reinstalling,
4101 upgrading,
4102 downgrading,
4103 removing,
4104 nil];
a75f53e7 4105
f464053e
JF
4106 issues_ = [database_ issues];
4107 if (issues_ != nil)
4108 issues_ = [issues_ retain];
a75f53e7 4109
f464053e
JF
4110 sizes_ = [[NSArray alloc] initWithObjects:
4111 SizeString([database_ fetcher].FetchNeeded()),
4112 SizeString([database_ fetcher].PartialPresent()),
f464053e 4113 nil];
a75f53e7 4114
f464053e 4115 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
d3bef7bc 4116
9ae52960 4117 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
c1edf105
GP
4118 initWithTitle:UCLocalize("CANCEL")
4119 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
9ae52960
GP
4120 style:UIBarButtonItemStylePlain
4121 target:self
4122 action:@selector(cancelButtonClicked)
4123 ];
4124 [[self navigationItem] setLeftBarButtonItem:leftItem];
4125 [leftItem release];
e057ec05 4126 } return self;
686e302f 4127}
20dd7407 4128
ed349d9a 4129- (void) applyRightButton {
9ae52960
GP
4130 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4131 initWithTitle:UCLocalize("CONFIRM")
4132 style:UIBarButtonItemStylePlain
4133 target:self
4134 action:@selector(confirmButtonClicked)
4135 ];
4136#if !AlwaysReload && !IgnoreInstall
ed349d9a
GP
4137 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4138 else [super applyRightButton];
4139#else
f99f86e2 4140 [[self navigationItem] setRightBarButtonItem:nil];
9ae52960
GP
4141#endif
4142 [rightItem release];
f464053e
JF
4143}
4144
9ae52960 4145- (void) cancelButtonClicked {
2064d251
GP
4146 [self dismissModalViewControllerAnimated:YES];
4147 [delegate_ cancelAndClear:YES];
f464053e
JF
4148}
4149
907a35d6 4150#if !AlwaysReload
9ae52960 4151- (void) confirmButtonClicked {
83105e6e 4152#if IgnoreInstall
9ae52960 4153 return;
83105e6e 4154#endif
f464053e 4155 if (essential_ != nil)
9ae52960 4156 [essential_ show];
f464053e
JF
4157 else {
4158 if (substrate_)
4159 Finish_ = 2;
9ae52960 4160 [delegate_ confirmWithNavigationController:[self navigationController]];
f464053e
JF
4161 }
4162}
907a35d6 4163#endif
f464053e 4164
e057ec05
JF
4165@end
4166/* }}} */
20dd7407 4167
e057ec05
JF
4168/* Progress Data {{{ */
4169@interface ProgressData : NSObject {
4170 SEL selector_;
4171 id target_;
4172 id object_;
a75f53e7
JF
4173}
4174
e057ec05 4175- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
686e302f 4176
e057ec05
JF
4177- (SEL) selector;
4178- (id) target;
4179- (id) object;
4180@end
686e302f 4181
e057ec05 4182@implementation ProgressData
686e302f 4183
e057ec05
JF
4184- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4185 if ((self = [super init]) != nil) {
4186 selector_ = selector;
4187 target_ = target;
4188 object_ = object;
4189 } return self;
4190}
686e302f 4191
e057ec05
JF
4192- (SEL) selector {
4193 return selector_;
4194}
686e302f 4195
e057ec05
JF
4196- (id) target {
4197 return target_;
20dd7407
JF
4198}
4199
e057ec05
JF
4200- (id) object {
4201 return object_;
a75f53e7
JF
4202}
4203
4941f41d
JF
4204@end
4205/* }}} */
f441e717
GP
4206/* Progress Controller {{{ */
4207@interface ProgressController : CYViewController <
7600bd69 4208 ConfigurationDelegate,
e057ec05
JF
4209 ProgressDelegate
4210> {
7600bd69 4211 _transient Database *database_;
e057ec05
JF
4212 UIProgressBar *progress_;
4213 UITextView *output_;
4214 UITextLabel *status_;
238b07ce 4215 UIPushButton *close_;
b26eb97d 4216 BOOL running_;
1eb0c554 4217 SHA1SumValue springlist_;
bde2d79b 4218 SHA1SumValue notifyconf_;
6981ccdf 4219 NSString *title_;
4941f41d
JF
4220}
4221
9ae52960 4222- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4941f41d 4223
e057ec05
JF
4224- (void) _retachThread;
4225- (void) _detachNewThreadData:(ProgressData *)data;
4226- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4941f41d 4227
b26eb97d
JF
4228- (BOOL) isRunning;
4229
4941f41d
JF
4230@end
4231
f441e717
GP
4232@protocol ProgressControllerDelegate
4233- (void) progressControllerIsComplete:(ProgressController *)sender;
e057ec05
JF
4234@end
4235
f441e717 4236@implementation ProgressController
4941f41d
JF
4237
4238- (void) dealloc {
9ae52960 4239 [database_ setDelegate:nil];
e057ec05
JF
4240 [progress_ release];
4241 [output_ release];
4242 [status_ release];
238b07ce 4243 [close_ release];
6981ccdf
JF
4244 if (title_ != nil)
4245 [title_ release];
4941f41d
JF
4246 [super dealloc];
4247}
4248
9ae52960
GP
4249- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4250 if ((self = [super init]) != nil) {
7600bd69 4251 database_ = database;
9ae52960 4252 [database_ setDelegate:self];
e057ec05 4253 delegate_ = delegate;
1cb11c5f 4254
1e4922b8 4255 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4941f41d 4256
9ae52960 4257 progress_ = [[UIProgressBar alloc] init];
d3bef7bc 4258 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
238b07ce 4259 [progress_ setStyle:0];
1cb11c5f 4260
9ae52960 4261 status_ = [[UITextLabel alloc] init];
d3bef7bc 4262 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
87c76914
JF
4263 [status_ setColor:[UIColor whiteColor]];
4264 [status_ setBackgroundColor:[UIColor clearColor]];
e057ec05
JF
4265 [status_ setCentersHorizontally:YES];
4266 //[status_ setFont:font];
1cb11c5f 4267
9ae52960 4268 output_ = [[UITextView alloc] init];
3325a005 4269
d3bef7bc 4270 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
e057ec05 4271 //[output_ setTextFont:@"Courier New"];
c59881cd 4272 [output_ setFont:[[output_ font] fontWithSize:12]];
87c76914
JF
4273 [output_ setTextColor:[UIColor whiteColor]];
4274 [output_ setBackgroundColor:[UIColor clearColor]];
e057ec05
JF
4275 [output_ setMarginTop:0];
4276 [output_ setAllowsRubberBanding:YES];
81ab76dc 4277 [output_ setEditable:NO];
9ae52960 4278 [[self view] addSubview:output_];
686e302f 4279
9ae52960 4280 close_ = [[UIPushButton alloc] init];
d3bef7bc 4281 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
238b07ce
JF
4282 [close_ setAutosizesToFit:NO];
4283 [close_ setDrawsShadow:YES];
4284 [close_ setStretchBackground:YES];
238b07ce 4285 [close_ setEnabled:YES];
9ae52960 4286 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
017b2b71 4287 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
238b07ce
JF
4288 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4289 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
e057ec05 4290 } return self;
4941f41d
JF
4291}
4292
9ae52960
GP
4293- (void) positionViews {
4294 CGRect bounds = [[self view] bounds];
4295 CGSize prgsize = [UIProgressBar defaultSize];
4296
4297 CGRect prgrect = {{
4298 (bounds.size.width - prgsize.width) / 2,
4299 bounds.size.height - prgsize.height - 64
4300 }, prgsize};
f99f86e2 4301
9ae52960
GP
4302 float closewidth = bounds.size.width - 20;
4303 if (closewidth > 300) closewidth = 300;
4304
4305 [progress_ setFrame:prgrect];
4306 [status_ setFrame:CGRectMake(
4307 10,
4308 bounds.size.height - prgsize.height - 94,
4309 bounds.size.width - 20,
4310 24
4311 )];
4312 [output_ setFrame:CGRectMake(
4313 10,
4314 20,
4315 bounds.size.width - 20,
4316 bounds.size.height - 106
4317 )];
4318 [close_ setFrame:CGRectMake(
4319 (bounds.size.width - closewidth) / 2,
4320 bounds.size.height - prgsize.height - 94,
4321 closewidth,
4322 32 + prgsize.height
4323 )];
4324}
4325
4326- (void) viewWillAppear:(BOOL)animated {
4327 [super viewDidAppear:animated];
4328 [[self navigationItem] setHidesBackButton:YES];
1e4922b8 4329 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
f99f86e2 4330
9ae52960 4331 [self positionViews];
4941f41d
JF
4332}
4333
9ae52960
GP
4334- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4335 [self positionViews];
4941f41d
JF
4336}
4337
9ae52960 4338- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3d257c70 4339 NSString *context([alert context]);
03d01f0e 4340
6981ccdf 4341 if ([context isEqualToString:@"conffile"]) {
9ae52960 4342 FILE *input = [database_ input];
3d257c70
GP
4343 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4344 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
9ae52960 4345 fflush(input);
6981ccdf
JF
4346 }
4347}
4348
4349- (void) closeButtonPushed {
4350 running_ = NO;
4351
864da84b
RP
4352 UpdateExternalStatus(0);
4353
6981ccdf
JF
4354 switch (Finish_) {
4355 case 0:
9ae52960 4356 [self dismissModalViewControllerAnimated:YES];
6981ccdf
JF
4357 break;
4358
4359 case 1:
74a834de
JF
4360 [delegate_ terminateWithSuccess];
4361 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4362 [delegate_ suspendWithAnimation:YES];
4363 else
4364 [delegate_ suspend];*/
6981ccdf
JF
4365 break;
4366
4367 case 2:
4368 system("launchctl stop com.apple.SpringBoard");
4369 break;
4370
4371 case 3:
4372 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4373 break;
4374
4375 case 4:
4376 system("reboot");
4377 break;
03d01f0e 4378 }
6981ccdf 4379}
b26eb97d 4380
6981ccdf 4381- (void) _retachThread {
9ae52960 4382 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
6981ccdf 4383
9ae52960 4384 [[self view] addSubview:close_];
6981ccdf
JF
4385 [progress_ removeFromSuperview];
4386 [status_ removeFromSuperview];
4387
4388 [database_ popErrorWithTitle:title_];
f441e717 4389 [delegate_ progressControllerIsComplete:self];
cb9c2100 4390
bde2d79b 4391 if (Finish_ < 4) {
bd8e54e1
JF
4392 FileFd file;
4393 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4394 _error->Discard();
4395 else {
4396 MMap mmap(file, MMap::ReadOnly);
4397 SHA1Summation sha1;
4398 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4399 if (!(notifyconf_ == sha1.Result()))
4400 Finish_ = 4;
4401 }
bde2d79b
JF
4402 }
4403
f464053e 4404 if (Finish_ < 3) {
bd8e54e1
JF
4405 FileFd file;
4406 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4407 _error->Discard();
4408 else {
4409 MMap mmap(file, MMap::ReadOnly);
4410 SHA1Summation sha1;
4411 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4412 if (!(springlist_ == sha1.Result()))
4413 Finish_ = 3;
4414 }
1eb0c554
JF
4415 }
4416
03d01f0e 4417 switch (Finish_) {
9ae52960 4418 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
61b13cae
JF
4419 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4420 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4421 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4422 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
03d01f0e
JF
4423 }
4424
575ffd3c 4425 system("su -c /usr/bin/uicache mobile");
5f54c108 4426
864da84b
RP
4427 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4428
b26eb97d 4429 [delegate_ setStatusBarShowsProgress:NO];
238b07ce
JF
4430}
4431
f464053e 4432- (void) _detachNewThreadData:(ProgressData *)data { _pooled
e057ec05
JF
4433 [[data target] performSelector:[data selector] withObject:[data object]];
4434 [data release];
a933cee2 4435
e057ec05 4436 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
a933cee2
JF
4437}
4438
e057ec05 4439- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
864da84b
RP
4440 UpdateExternalStatus(1);
4441
6981ccdf
JF
4442 if (title_ != nil)
4443 [title_ release];
4444 if (title == nil)
4445 title_ = nil;
4446 else
4447 title_ = [title retain];
4448
9ae52960 4449 [[self navigationItem] setTitle:title_];
686e302f 4450
e057ec05
JF
4451 [status_ setText:nil];
4452 [output_ setText:@""];
4453 [progress_ setProgress:0];
a933cee2 4454
238b07ce 4455 [close_ removeFromSuperview];
9ae52960
GP
4456 [[self view] addSubview:progress_];
4457 [[self view] addSubview:status_];
238b07ce 4458
b26eb97d
JF
4459 [delegate_ setStatusBarShowsProgress:YES];
4460 running_ = YES;
4461
bde2d79b 4462 {
bd8e54e1
JF
4463 FileFd file;
4464 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4465 _error->Discard();
4466 else {
4467 MMap mmap(file, MMap::ReadOnly);
4468 SHA1Summation sha1;
4469 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4470 notifyconf_ = sha1.Result();
4471 }
bde2d79b
JF
4472 }
4473
f464053e 4474 {
bd8e54e1
JF
4475 FileFd file;
4476 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4477 _error->Discard();
4478 else {
4479 MMap mmap(file, MMap::ReadOnly);
4480 SHA1Summation sha1;
4481 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4482 springlist_ = sha1.Result();
4483 }
1eb0c554
JF
4484 }
4485
e057ec05
JF
4486 [NSThread
4487 detachNewThreadSelector:@selector(_detachNewThreadData:)
4488 toTarget:self
4489 withObject:[[ProgressData alloc]
4490 initWithSelector:selector
4491 target:target
4492 object:object
4493 ]
4494 ];
a933cee2
JF
4495}
4496
965edd52
JF
4497- (void) repairWithSelector:(SEL)selector {
4498 [self
4499 detachNewThreadSelector:selector
4500 toTarget:database_
4501 withObject:nil
61b13cae 4502 title:UCLocalize("REPAIRING")
965edd52
JF
4503 ];
4504}
4505
7600bd69
JF
4506- (void) setConfigurationData:(NSString *)data {
4507 [self
4508 performSelectorOnMainThread:@selector(_setConfigurationData:)
4509 withObject:data
4510 waitUntilDone:YES
4511 ];
4512}
4513
6981ccdf
JF
4514- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4515 CYActionSheet *sheet([[[CYActionSheet alloc]
4516 initWithTitle:title
61b13cae 4517 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
238b07ce 4518 defaultButtonIndex:0
6981ccdf 4519 ] autorelease]);
238b07ce 4520
9e639c5a 4521 [sheet setMessage:error];
6981ccdf
JF
4522 [sheet yieldToPopupAlertAnimated:YES];
4523 [sheet dismiss];
a933cee2
JF
4524}
4525
e057ec05
JF
4526- (void) setProgressTitle:(NSString *)title {
4527 [self
4528 performSelectorOnMainThread:@selector(_setProgressTitle:)
4529 withObject:title
4530 waitUntilDone:YES
4531 ];
a933cee2
JF
4532}
4533
e057ec05
JF
4534- (void) setProgressPercent:(float)percent {
4535 [self
4536 performSelectorOnMainThread:@selector(_setProgressPercent:)
4537 withObject:[NSNumber numberWithFloat:percent]
4538 waitUntilDone:YES
4539 ];
a933cee2
JF
4540}
4541
87c76914 4542- (void) startProgress {
87c76914
JF
4543}
4544
e057ec05
JF
4545- (void) addProgressOutput:(NSString *)output {
4546 [self
4547 performSelectorOnMainThread:@selector(_addProgressOutput:)
4548 withObject:output
4549 waitUntilDone:YES
4550 ];
a933cee2
JF
4551}
4552
87c76914 4553- (bool) isCancelling:(size_t)received {
87c76914
JF
4554 return false;
4555}
4556
7600bd69 4557- (void) _setConfigurationData:(NSString *)data {
faf4eb4f
JF
4558 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4559
6981ccdf
JF
4560 if (!conffile_r(data)) {
4561 lprintf("E:invalid conffile\n");
4562 return;
4563 }
7600bd69
JF
4564
4565 NSString *ofile = conffile_r[1];
4566 //NSString *nfile = conffile_r[2];
4567
3d257c70 4568 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 4569 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9ae52960
GP
4570 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4571 delegate:self
4572 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4573 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
3d257c70 4574 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9ae52960
GP
4575 nil
4576 ] autorelease];
3d257c70 4577
9ae52960 4578 [alert setContext:@"conffile"];
3d257c70 4579 [alert show];
7600bd69
JF
4580}
4581
e057ec05 4582- (void) _setProgressTitle:(NSString *)title {
907a35d6
JF
4583 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4584 for (size_t i(0), e([words count]); i != e; ++i) {
4585 NSString *word([words objectAtIndex:i]);
4586 if (Package *package = [database_ packageWithName:word])
4587 [words replaceObjectAtIndex:i withObject:[package name]];
4588 }
4589
4590 [status_ setText:[words componentsJoinedByString:@" "]];
686e302f 4591}
a933cee2 4592
e057ec05
JF
4593- (void) _setProgressPercent:(NSNumber *)percent {
4594 [progress_ setProgress:[percent floatValue]];
242bcc6d
JF
4595}
4596
e057ec05
JF
4597- (void) _addProgressOutput:(NSString *)output {
4598 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4599 CGSize size = [output_ contentSize];
4600 CGRect rect = {{0, size.height}, {size.width, 0}};
4601 [output_ scrollRectToVisible:rect animated:YES];
4602}
3957dd75 4603
b26eb97d 4604- (BOOL) isRunning {
5f54c108 4605 return running_;
b26eb97d
JF
4606}
4607
e057ec05
JF
4608@end
4609/* }}} */
3957dd75 4610
d4a9ec10 4611/* Cell Content View {{{ */
1e4922b8
JF
4612@protocol ContentDelegate
4613- (void) drawContentRect:(CGRect)rect;
4614@end
4615
5d8f1006 4616@interface ContentView : UIView {
1e4922b8 4617 _transient id<ContentDelegate> delegate_;
5d8f1006
JF
4618}
4619
4620@end
4621
d4a9ec10
GP
4622@implementation ContentView
4623- (id) initWithFrame:(CGRect)frame {
4624 if ((self = [super initWithFrame:frame]) != nil) {
4625 /* Fix landscape stretching. */
4626 [self setNeedsDisplayOnBoundsChange:YES];
4627 } return self;
4628}
4629
1e4922b8 4630- (void) setDelegate:(id<ContentDelegate>)delegate {
d4a9ec10
GP
4631 delegate_ = delegate;
4632}
4633
4634- (void) drawRect:(CGRect)rect {
4635 [super drawRect:rect];
4636 [delegate_ drawContentRect:rect];
4637}
4638@end
4639/* }}} */
4640/* Package Cell {{{ */
1e4922b8
JF
4641@interface PackageCell : UITableViewCell <
4642 ContentDelegate
4643> {
5e563e79
JF
4644 UIImage *icon_;
4645 NSString *name_;
4646 NSString *description_;
d8d9a65c 4647 bool commercial_;
5e563e79 4648 NSString *source_;
cb9c2100 4649 UIImage *badge_;
3ff1504e 4650 Package *package_;
5d8f1006
JF
4651 UIColor *color_;
4652 ContentView *content_;
4653 BOOL faded_;
4654 float fade_;
6981ccdf 4655 UIImage *placard_;
e057ec05 4656}
138ae18d 4657
e057ec05
JF
4658- (PackageCell *) init;
4659- (void) setPackage:(Package *)package;
1cb11c5f 4660
3319715b 4661+ (int) heightForPackage:(Package *)package;
5d8f1006
JF
4662- (void) drawContentRect:(CGRect)rect;
4663
4664@end
4665
e057ec05
JF
4666@implementation PackageCell
4667
5e563e79
JF
4668- (void) clearPackage {
4669 if (icon_ != nil) {
4670 [icon_ release];
4671 icon_ = nil;
4672 }
4673
4674 if (name_ != nil) {
4675 [name_ release];
4676 name_ = nil;
4677 }
4678
4679 if (description_ != nil) {
4680 [description_ release];
4681 description_ = nil;
4682 }
4683
4684 if (source_ != nil) {
4685 [source_ release];
4686 source_ = nil;
4687 }
cb9c2100
JF
4688
4689 if (badge_ != nil) {
4690 [badge_ release];
4691 badge_ = nil;
4692 }
3ff1504e 4693
6981ccdf
JF
4694 if (placard_ != nil) {
4695 [placard_ release];
4696 placard_ = nil;
4697 }
4698
3ff1504e
JF
4699 [package_ release];
4700 package_ = nil;
5e563e79
JF
4701}
4702
e057ec05 4703- (void) dealloc {
5e563e79 4704 [self clearPackage];
5d8f1006
JF
4705 [content_ release];
4706 [color_ release];
e057ec05 4707 [super dealloc];
686e302f 4708}
a933cee2 4709
5d8f1006
JF
4710- (float) fade {
4711 return faded_ ? [self selectionPercent] : fade_;
4712}
4713
e057ec05 4714- (PackageCell *) init {
5d8f1006
JF
4715 CGRect frame(CGRectMake(0, 0, 320, 74));
4716 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4717 UIView *content([self contentView]);
4718 CGRect bounds([content bounds]);
d3bef7bc 4719
5d8f1006 4720 content_ = [[ContentView alloc] initWithFrame:bounds];
d3bef7bc
JF
4721 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4722 [content addSubview:content_];
4723
5d8f1006 4724 [content_ setDelegate:self];
5d8f1006 4725 [content_ setOpaque:YES];
5d8f1006
JF
4726 if ([self respondsToSelector:@selector(selectionPercent)])
4727 faded_ = YES;
e057ec05 4728 } return self;
686e302f 4729}
a933cee2 4730
5d8f1006
JF
4731- (void) _setBackgroundColor {
4732 UIColor *color;
4733 if (NSString *mode = [package_ mode]) {
4734 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4735 color = remove ? RemovingColor_ : InstallingColor_;
4736 } else
4737 color = [UIColor whiteColor];
4738
4739 [content_ setBackgroundColor:color];
4740 [self setNeedsDisplay];
4741}
4742
e057ec05 4743- (void) setPackage:(Package *)package {
d1494d2c 4744 [self clearPackage];
631a0a1e 4745 [package parse];
238b07ce 4746
e057ec05 4747 Source *source = [package source];
a933cee2 4748
dbe0f181 4749 icon_ = [[package icon] retain];
5e563e79 4750 name_ = [[package name] retain];
37455cf8
JF
4751
4752 if (IsWildcat_)
4753 description_ = [package longDescription];
4754 if (description_ == nil)
4755 description_ = [package shortDescription];
4756 if (description_ != nil)
4757 description_ = [description_ retain];
4758
d8d9a65c 4759 commercial_ = [package isCommercial];
e057ec05 4760
3ff1504e
JF
4761 package_ = [package retain];
4762
9e07091a
JF
4763 NSString *label = nil;
4764 bool trusted = false;
a933cee2 4765
e057ec05
JF
4766 if (source != nil) {
4767 label = [source label];
4768 trusted = [source trusted];
9e07091a 4769 } else if ([[package id] isEqualToString:@"firmware"])
61b13cae 4770 label = UCLocalize("APPLE");
faf4eb4f 4771 else
61b13cae 4772 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
a933cee2 4773
6932575e 4774 NSString *from(label);
9e07091a 4775
6932575e
JF
4776 NSString *section = [package simpleSection];
4777 if (section != nil && ![section isEqualToString:label]) {
4778 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
61b13cae 4779 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
6932575e 4780 }
9e07091a 4781
61b13cae 4782 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5e563e79 4783 source_ = [from retain];
e057ec05 4784
cb9c2100
JF
4785 if (NSString *purpose = [package primaryPurpose])
4786 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4787 badge_ = [badge_ retain];
4788
6981ccdf
JF
4789 if ([package installed] != nil)
4790 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4791 placard_ = [placard_ retain];
4792
5d8f1006
JF
4793 [self _setBackgroundColor];
4794 [content_ setNeedsDisplay];
d8d9a65c
JF
4795}
4796
5d8f1006
JF
4797- (void) drawContentRect:(CGRect)rect {
4798 bool selected([self isSelected]);
37455cf8 4799 float width([self bounds].size.width);
3ff1504e 4800
5d8f1006
JF
4801#if 0
4802 CGContextRef context(UIGraphicsGetCurrentContext());
4803 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4804 CGContextFillRect(context, rect);
4805#endif
a933cee2 4806
87c76914
JF
4807 if (icon_ != nil) {
4808 CGRect rect;
4809 rect.size = [icon_ size];
4810
4811 rect.size.width /= 2;
4812 rect.size.height /= 2;
4813
4814 rect.origin.x = 25 - rect.size.width / 2;
4815 rect.origin.y = 25 - rect.size.height / 2;
4816
4817 [icon_ drawInRect:rect];
4818 }
a933cee2 4819
cb9c2100
JF
4820 if (badge_ != nil) {
4821 CGSize size = [badge_ size];
4822
4823 [badge_ drawAtPoint:CGPointMake(
4824 36 - size.width / 2,
4825 36 - size.height / 2
4826 )];
4827 }
4828
5e563e79
JF
4829 if (selected)
4830 UISetColor(White_);
a933cee2 4831
5e563e79 4832 if (!selected)
d8d9a65c 4833 UISetColor(commercial_ ? Purple_ : Black_);
a6c1718e
DH
4834 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4835 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
a933cee2 4836
5e563e79 4837 if (!selected)
d8d9a65c 4838 UISetColor(commercial_ ? Purplish_ : Gray_);
a6c1718e 4839 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
6981ccdf
JF
4840
4841 if (placard_ != nil)
5ec44e34 4842 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
1cb11c5f
JF
4843}
4844
5d8f1006
JF
4845- (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4846 //[self _setBackgroundColor];
4847 [super setSelected:selected animated:fade];
4848 [content_ setNeedsDisplay];
3ff1504e
JF
4849}
4850
3319715b 4851+ (int) heightForPackage:(Package *)package {
631a0a1e 4852 return 73;
3319715b
JF
4853}
4854
20dd7407
JF
4855@end
4856/* }}} */
e057ec05 4857/* Section Cell {{{ */
1e4922b8
JF
4858@interface SectionCell : UITableViewCell <
4859 ContentDelegate
4860> {
4923fbd7 4861 NSString *basic_;
fa7bb92f 4862 NSString *section_;
5e563e79
JF
4863 NSString *name_;
4864 NSString *count_;
4865 UIImage *icon_;
d4a9ec10
GP
4866 ContentView *content_;
4867 id switch_;
fa7bb92f 4868 BOOL editing_;
686e302f 4869}
a933cee2 4870
fa7bb92f 4871- (void) setSection:(Section *)section editing:(BOOL)editing;
e057ec05 4872
20dd7407
JF
4873@end
4874
e057ec05 4875@implementation SectionCell
20dd7407 4876
5e563e79 4877- (void) clearSection {
4923fbd7 4878 if (basic_ != nil) {
7805b429 4879 [basic_ release];
4923fbd7
JF
4880 basic_ = nil;
4881 }
4882
5e563e79 4883 if (section_ != nil) {
fa7bb92f 4884 [section_ release];
5e563e79
JF
4885 section_ = nil;
4886 }
faf4eb4f 4887
5e563e79
JF
4888 if (name_ != nil) {
4889 [name_ release];
4890 name_ = nil;
4891 }
faf4eb4f 4892
5e563e79
JF
4893 if (count_ != nil) {
4894 [count_ release];
4895 count_ = nil;
4896 }
faf4eb4f
JF
4897}
4898
5e563e79
JF
4899- (void) dealloc {
4900 [self clearSection];
4901 [icon_ release];
4902 [switch_ release];
d4a9ec10
GP
4903 [content_ release];
4904
5e563e79 4905 [super dealloc];
faf4eb4f
JF
4906}
4907
d4a9ec10
GP
4908- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4909 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5e563e79 4910 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
d4a9ec10
GP
4911 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4912 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4913
4914 UIView *content([self contentView]);
4915 CGRect bounds([content bounds]);
4916
4917 content_ = [[ContentView alloc] initWithFrame:bounds];
4918 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4919 [content addSubview:content_];
4920 [content_ setBackgroundColor:[UIColor whiteColor]];
4921
4922 [content_ setDelegate:self];
686e302f 4923 } return self;
a933cee2
JF
4924}
4925
fa7bb92f 4926- (void) onSwitch:(id)sender {
4923fbd7 4927 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
fa7bb92f
JF
4928 if (metadata == nil) {
4929 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4923fbd7 4930 [Sections_ setObject:metadata forKey:basic_];
fa7bb92f
JF
4931 }
4932
4933 Changed_ = true;
d4a9ec10 4934 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
fa7bb92f
JF
4935}
4936
4937- (void) setSection:(Section *)section editing:(BOOL)editing {
4938 if (editing != editing_) {
4939 if (editing_)
4940 [switch_ removeFromSuperview];
4941 else
4942 [self addSubview:switch_];
4943 editing_ = editing;
4944 }
4945
5e563e79 4946 [self clearSection];
fa7bb92f 4947
e057ec05 4948 if (section == nil) {
61b13cae 4949 name_ = [UCLocalize("ALL_PACKAGES") retain];
5e563e79 4950 count_ = nil;
e057ec05 4951 } else {
7805b429 4952 basic_ = [section name];
4923fbd7
JF
4953 if (basic_ != nil)
4954 basic_ = [basic_ retain];
4955
43b742af 4956 section_ = [section localized];
fa7bb92f
JF
4957 if (section_ != nil)
4958 section_ = [section_ retain];
4923fbd7 4959
61b13cae 4960 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5e563e79 4961 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
fa7bb92f
JF
4962
4963 if (editing_)
d4a9ec10 4964 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
e057ec05 4965 }
d4a9ec10 4966
1e4922b8 4967 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
d4a9ec10 4968 [content_ setNeedsDisplay];
5e563e79
JF
4969}
4970
daf7f6e2
JF
4971- (void) setFrame:(CGRect)frame {
4972 [super setFrame:frame];
d4a9ec10 4973
daf7f6e2
JF
4974 CGRect rect([switch_ frame]);
4975 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4976}
4977
d4a9ec10
GP
4978- (void) drawContentRect:(CGRect)rect {
4979 BOOL selected = [self isSelected];
f99f86e2 4980
5e563e79
JF
4981 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4982
4983 if (selected)
4984 UISetColor(White_);
4985
4986 if (!selected)
4987 UISetColor(Black_);
575ffd3c 4988
d4a9ec10 4989 float width(rect.size.width);
575ffd3c 4990 if (editing_)
d4a9ec10 4991 width -= 87;
575ffd3c 4992
a6c1718e 4993 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
fa7bb92f 4994
5e563e79
JF
4995 CGSize size = [count_ sizeWithFont:Font14_];
4996
4997 UISetColor(White_);
4998 if (count_ != nil)
cb9c2100 4999 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
a933cee2
JF
5000}
5001
e057ec05
JF
5002@end
5003/* }}} */
a933cee2 5004
59efd93a 5005/* File Table {{{ */
1e4922b8
JF
5006@interface FileTable : CYViewController <
5007 UITableViewDataSource,
5008 UITableViewDelegate
5009> {
e057ec05 5010 _transient Database *database_;
59efd93a
JF
5011 Package *package_;
5012 NSString *name_;
5013 NSMutableArray *files_;
d4a9ec10 5014 UITableView *list_;
59efd93a 5015}
a933cee2 5016
9ae52960 5017- (id) initWithDatabase:(Database *)database;
59efd93a
JF
5018- (void) setPackage:(Package *)package;
5019
5020@end
5021
5022@implementation FileTable
5023
5024- (void) dealloc {
5025 if (package_ != nil)
5026 [package_ release];
5027 if (name_ != nil)
5028 [name_ release];
5029 [files_ release];
5030 [list_ release];
5031 [super dealloc];
5032}
5033
d4a9ec10 5034- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
59efd93a
JF
5035 return files_ == nil ? 0 : [files_ count];
5036}
5037
2064d251
GP
5038/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5039 return 24.0f;
5040}*/
59efd93a 5041
d4a9ec10 5042- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9ae52960
GP
5043 static NSString *reuseIdentifier = @"Cell";
5044
d4a9ec10
GP
5045 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5046 if (cell == nil) {
5047 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5048 [cell setFont:[UIFont systemFontOfSize:16]];
59efd93a 5049 }
d4a9ec10 5050 [cell setText:[files_ objectAtIndex:indexPath.row]];
1e4922b8 5051 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
9ae52960 5052
d4a9ec10 5053 return cell;
59efd93a 5054}
a933cee2 5055
9ae52960
GP
5056- (id) initWithDatabase:(Database *)database {
5057 if ((self = [super init]) != nil) {
59efd93a 5058 database_ = database;
a933cee2 5059
9ae52960
GP
5060 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5061
59efd93a 5062 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
20dd7407 5063
d4a9ec10 5064 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
2064d251
GP
5065 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5066 [list_ setRowHeight:24.0f];
9ae52960 5067 [[self view] addSubview:list_];
59efd93a 5068
59efd93a 5069 [list_ setDataSource:self];
59efd93a 5070 [list_ setDelegate:self];
59efd93a
JF
5071 } return self;
5072}
5073
5074- (void) setPackage:(Package *)package {
5075 if (package_ != nil) {
5076 [package_ autorelease];
5077 package_ = nil;
5078 }
5079
5080 if (name_ != nil) {
5081 [name_ release];
5082 name_ = nil;
5083 }
5084
5085 [files_ removeAllObjects];
5086
5087 if (package != nil) {
5088 package_ = [package retain];
5089 name_ = [[package id] retain];
5090
f464053e
JF
5091 if (NSArray *files = [package files])
5092 [files_ addObjectsFromArray:files];
59efd93a 5093
fc19e583
JF
5094 if ([files_ count] != 0) {
5095 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5096 [files_ removeObjectAtIndex:0];
9e07091a 5097 [files_ sortUsingSelector:@selector(compareByPath:)];
2a987aa5
JF
5098
5099 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5100 [stack addObject:@"/"];
5101
5102 for (int i(0), e([files_ count]); i != e; ++i) {
5103 NSString *file = [files_ objectAtIndex:i];
5104 while (![file hasPrefix:[stack lastObject]])
5105 [stack removeLastObject];
5106 NSString *directory = [stack lastObject];
5107 [stack addObject:[file stringByAppendingString:@"/"]];
5108 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
9e07091a 5109 ([stack count] - 2) * 3, "",
2a987aa5
JF
5110 [file substringFromIndex:[directory length]]
5111 ]];
5112 }
59efd93a
JF
5113 }
5114 }
5115
5116 [list_ reloadData];
5117}
5118
59efd93a
JF
5119- (void) reloadData {
5120 [self setPackage:[database_ packageWithName:name_]];
59efd93a 5121}
686e302f 5122
686e302f 5123@end
e057ec05 5124/* }}} */
f441e717 5125/* Package Controller {{{ */
48861ec9
DH
5126@interface PackageController : CYBrowserController <
5127 UIActionSheetDelegate
5128> {
dbe0f181 5129 _transient Database *database_;
e057ec05
JF
5130 Package *package_;
5131 NSString *name_;
d8d9a65c 5132 bool commercial_;
965edd52 5133 NSMutableArray *buttons_;
df5a7529
JF
5134}
5135
9ae52960 5136- (id) initWithDatabase:(Database *)database;
e057ec05 5137- (void) setPackage:(Package *)package;
686e302f 5138
e057ec05 5139@end
686e302f 5140
f441e717 5141@implementation PackageController
686e302f 5142
e057ec05 5143- (void) dealloc {
e057ec05
JF
5144 if (package_ != nil)
5145 [package_ release];
5146 if (name_ != nil)
5147 [name_ release];
965edd52 5148 [buttons_ release];
e057ec05
JF
5149 [super dealloc];
5150}
20dd7407 5151
d287ae9a 5152- (void) release {
6932575e 5153 if ([self retainCount] == 1)
f441e717 5154 [delegate_ setPackageController:self];
6932575e 5155 [super release];
d287ae9a 5156}
6932575e
JF
5157
5158/* XXX: this is not safe at all... localization of /fail/ */
965edd52 5159- (void) _clickButtonWithName:(NSString *)name {
61b13cae 5160 if ([name isEqualToString:UCLocalize("CLEAR")])
3ff1504e 5161 [delegate_ clearPackage:package_];
61b13cae 5162 else if ([name isEqualToString:UCLocalize("INSTALL")])
965edd52 5163 [delegate_ installPackage:package_];
61b13cae 5164 else if ([name isEqualToString:UCLocalize("REINSTALL")])
965edd52 5165 [delegate_ installPackage:package_];
61b13cae 5166 else if ([name isEqualToString:UCLocalize("REMOVE")])
965edd52 5167 [delegate_ removePackage:package_];
61b13cae 5168 else if ([name isEqualToString:UCLocalize("UPGRADE")])
965edd52
JF
5169 [delegate_ installPackage:package_];
5170 else _assert(false);
5171}
5172
1ca35d78 5173- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
a5dd312c 5174 NSString *context([sheet context]);
965edd52 5175
a5dd312c 5176 if ([context isEqualToString:@"modify"]) {
1ca35d78
GP
5177 if (button != [sheet cancelButtonIndex]) {
5178 NSString *buttonName = [buttons_ objectAtIndex:button];
5179 [self _clickButtonWithName:buttonName];
5180 }
f99f86e2 5181
1ca35d78 5182 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
1ca35d78 5183 }
686e302f 5184}
4941f41d 5185
853d14d3 5186- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
853d14d3
JF
5187 return [super webView:sender didFinishLoadForFrame:frame];
5188}
5189
ad554f10 5190- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
cb9c2100 5191 [super webView:sender didClearWindowObject:window forFrame:frame];
6932575e 5192 [window setValue:package_ forKey:@"package"];
ad554f10
JF
5193}
5194
7b00c562 5195- (bool) _allowJavaScriptPanel {
d8d9a65c 5196 return commercial_;
7b00c562
JF
5197}
5198
907a35d6 5199#if !AlwaysReload
48861ec9 5200- (void) _customButtonClicked {
6981ccdf
JF
5201 int count([buttons_ count]);
5202 if (count == 0)
5203 return;
4941f41d 5204
965edd52
JF
5205 if (count == 1)
5206 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5207 else {
1ca35d78 5208 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
965edd52 5209 [buttons addObjectsFromArray:buttons_];
e057ec05 5210
1ca35d78 5211 UIActionSheet *sheet = [[[UIActionSheet alloc]
fc19e583 5212 initWithTitle:nil
e057ec05 5213 delegate:self
1ca35d78
GP
5214 cancelButtonTitle:nil
5215 destructiveButtonTitle:nil
5216 otherButtonTitles:nil
5217 ] autorelease];
5218
5219 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5220 if (!IsWildcat_) {
5221 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5222 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5223 }
5224 [sheet setContext:@"modify"];
f99f86e2 5225
9ae52960 5226 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
e057ec05 5227 }
686e302f 5228}
1ce016d4 5229
48861ec9 5230- (void) customButtonClicked {
f99f86e2 5231 // Wait until it's done loading.
ed349d9a 5232 if (![self isLoading])
48861ec9 5233 [self _customButtonClicked];
1ce016d4 5234}
c8e3b4b3
GP
5235
5236- (void) reloadButtonClicked {
b36becfc
GP
5237 // Don't reload a package view by clicking the button.
5238}
5239
5240- (void) applyLoadingTitle {
5241 // Don't show "Loading" as the title. Ever.
c8e3b4b3 5242}
907a35d6 5243#endif
4941f41d 5244
9ae52960
GP
5245- (id) initWithDatabase:(Database *)database {
5246 if ((self = [super init]) != nil) {
e057ec05 5247 database_ = database;
965edd52 5248 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
6932575e 5249 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
e057ec05 5250 } return self;
a75f53e7
JF
5251}
5252
e057ec05
JF
5253- (void) setPackage:(Package *)package {
5254 if (package_ != nil) {
5255 [package_ autorelease];
5256 package_ = nil;
5257 }
5258
5259 if (name_ != nil) {
5260 [name_ release];
5261 name_ = nil;
5262 }
5263
965edd52
JF
5264 [buttons_ removeAllObjects];
5265
e057ec05 5266 if (package != nil) {
631a0a1e
JF
5267 [package parse];
5268
e057ec05
JF
5269 package_ = [package retain];
5270 name_ = [[package id] retain];
d8d9a65c 5271 commercial_ = [package isCommercial];
e057ec05 5272
3ff1504e 5273 if ([package_ mode] != nil)
61b13cae 5274 [buttons_ addObject:UCLocalize("CLEAR")];
965edd52 5275 if ([package_ source] == nil);
238b07ce 5276 else if ([package_ upgradableAndEssential:NO])
61b13cae 5277 [buttons_ addObject:UCLocalize("UPGRADE")];
b4c4fac4 5278 else if ([package_ uninstalled])
61b13cae 5279 [buttons_ addObject:UCLocalize("INSTALL")];
965edd52 5280 else
61b13cae 5281 [buttons_ addObject:UCLocalize("REINSTALL")];
b4c4fac4 5282 if (![package_ uninstalled])
61b13cae 5283 [buttons_ addObject:UCLocalize("REMOVE")];
6932575e
JF
5284
5285 if (special_ != NULL) {
84848968 5286 CGRect frame([document_ frame]);
6932575e 5287 frame.size.height = 0;
84848968 5288 [document_ setFrame:frame];
6932575e 5289
575ffd3c
JF
5290 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5291 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5292 else
5293 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
6932575e
JF
5294
5295 WebThreadLock();
84848968 5296 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
6932575e
JF
5297
5298 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5299
5300 [self setFinishHook:nil];
5301 [self setPopupHook:nil];
5302 WebThreadUnlock();
5303
bb9edf8b 5304 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
6932575e
JF
5305 [super callFunction:special_];
5306 }
e057ec05 5307 }
9ae52960 5308}
6932575e 5309
ed349d9a 5310- (void) applyRightButton {
9ae52960
GP
5311 int count = [buttons_ count];
5312 UIBarButtonItem *actionItem = [[UIBarButtonItem alloc]
5313 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5314 style:UIBarButtonItemStylePlain
5315 target:self
48861ec9 5316 action:@selector(customButtonClicked)
9ae52960 5317 ];
ed349d9a 5318 if (![self isLoading]) [[self navigationItem] setRightBarButtonItem:actionItem];
f99f86e2 5319 else [super applyRightButton];
9ae52960 5320 [actionItem release];
a75f53e7
JF
5321}
5322
d8d9a65c
JF
5323- (bool) isLoading {
5324 return commercial_ ? [super isLoading] : false;
a99d2808
JF
5325}
5326
e057ec05
JF
5327- (void) reloadData {
5328 [self setPackage:[database_ packageWithName:name_]];
b6ffa083
JF
5329}
5330
686e302f
JF
5331@end
5332/* }}} */
686e302f 5333/* Package Table {{{ */
1e4922b8
JF
5334@interface PackageTable : UIView <
5335 UITableViewDataSource,
5336 UITableViewDelegate
5337> {
e057ec05 5338 _transient Database *database_;
e057ec05 5339 NSMutableArray *packages_;
686e302f 5340 NSMutableArray *sections_;
5d8f1006
JF
5341 UITableView *list_;
5342 NSMutableArray *index_;
5343 NSMutableDictionary *indices_;
9ae52960
GP
5344 id target_;
5345 SEL action_;
5346 id delegate_;
a75f53e7
JF
5347}
5348
9ae52960 5349- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
686e302f
JF
5350
5351- (void) setDelegate:(id)delegate;
8993ad57 5352
e057ec05 5353- (void) reloadData;
8993ad57 5354- (void) resetCursor;
686e302f 5355
5d8f1006 5356- (UITableView *) list;
2a987aa5 5357
59efd93a
JF
5358- (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5359
9ae52960
GP
5360- (void) deselectWithAnimation:(BOOL)animated;
5361
686e302f
JF
5362@end
5363
5364@implementation PackageTable
5365
5366- (void) dealloc {
e057ec05 5367 [packages_ release];
686e302f 5368 [sections_ release];
e057ec05 5369 [list_ release];
5d8f1006
JF
5370 [index_ release];
5371 [indices_ release];
9ae52960 5372
686e302f 5373 [super dealloc];
b6ffa083
JF
5374}
5375
5d8f1006
JF
5376- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5377 NSInteger count([sections_ count]);
5378 return count == 0 ? 1 : count;
686e302f 5379}
4941f41d 5380
5d8f1006
JF
5381- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5382 if ([sections_ count] == 0)
5383 return nil;
686e302f
JF
5384 return [[sections_ objectAtIndex:section] name];
5385}
a75f53e7 5386
5d8f1006
JF
5387- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5388 if ([sections_ count] == 0)
5389 return 0;
5390 return [[sections_ objectAtIndex:section] count];
686e302f 5391}
a75f53e7 5392
5d8f1006
JF
5393- (Package *) packageAtIndexPath:(NSIndexPath *)path {
5394 Section *section([sections_ objectAtIndex:[path section]]);
5395 NSInteger row([path row]);
5396 Package *package([packages_ objectAtIndex:([section row] + row)]);
5397 return package;
686e302f 5398}
a75f53e7 5399
5d8f1006 5400- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
1e4922b8 5401 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5d8f1006
JF
5402 if (cell == nil)
5403 cell = [[[PackageCell alloc] init] autorelease];
5404 [cell setPackage:[self packageAtIndexPath:path]];
5405 return cell;
686e302f 5406}
a75f53e7 5407
9ae52960
GP
5408- (void) deselectWithAnimation:(BOOL)animated {
5409 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5410}
5411
2064d251 5412/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5d8f1006 5413 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
2064d251 5414}*/
a75f53e7 5415
5d8f1006
JF
5416- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5417 Package *package([self packageAtIndexPath:path]);
c3f582af 5418 package = [database_ packageWithName:[package id]];
9ae52960 5419 [target_ performSelector:action_ withObject:package];
5d8f1006
JF
5420 return path;
5421}
5422
5423- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5424 return [packages_ count] > 20 ? index_ : nil;
5425}
5426
5427- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5428 return index;
a75f53e7
JF
5429}
5430
9ae52960
GP
5431- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5432 if ((self = [super initWithFrame:frame]) != nil) {
e057ec05 5433 database_ = database;
9ae52960
GP
5434
5435 target_ = target;
5436 action_ = action;
e057ec05 5437
5d8f1006
JF
5438 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5439 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5440
e057ec05 5441 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
686e302f 5442 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
a75f53e7 5443
5d8f1006 5444 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
d3bef7bc 5445 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
2064d251 5446 [list_ setRowHeight:73.0f];
d3bef7bc
JF
5447 [self addSubview:list_];
5448
686e302f 5449 [list_ setDataSource:self];
5d8f1006 5450 [list_ setDelegate:self];
686e302f 5451 } return self;
a75f53e7
JF
5452}
5453
5454- (void) setDelegate:(id)delegate {
4941f41d 5455 delegate_ = delegate;
686e302f
JF
5456}
5457
ce09fc27
JF
5458- (bool) hasPackage:(Package *)package {
5459 return true;
8993ad57
JF
5460}
5461
e057ec05
JF
5462- (void) reloadData {
5463 NSArray *packages = [database_ packages];
686e302f 5464
e057ec05 5465 [packages_ removeAllObjects];
686e302f
JF
5466 [sections_ removeAllObjects];
5467
3bddda52 5468 _profile(PackageTable$reloadData$Filter)
9fdd37d0 5469 for (Package *package in packages)
3bddda52
JF
5470 if ([self hasPackage:package])
5471 [packages_ addObject:package];
3bddda52 5472 _end
e057ec05 5473
5d8f1006
JF
5474 [index_ removeAllObjects];
5475 [indices_ removeAllObjects];
5476
686e302f
JF
5477 Section *section = nil;
5478
3bddda52 5479 _profile(PackageTable$reloadData$Section)
9fdd37d0
JF
5480 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5481 Package *package;
5482 unichar index;
5483
5484 _profile(PackageTable$reloadData$Section$Package)
5485 package = [packages_ objectAtIndex:offset];
5486 index = [package index];
5487 _end
686e302f 5488
3bddda52
JF
5489 if (section == nil || [section index] != index) {
5490 _profile(PackageTable$reloadData$Section$Allocate)
5491 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5492 _end
686e302f 5493
5d8f1006
JF
5494 [index_ addObject:[section name]];
5495 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5496
9fdd37d0
JF
5497 _profile(PackageTable$reloadData$Section$Add)
5498 [sections_ addObject:section];
5499 _end
3bddda52
JF
5500 }
5501
5502 [section addToCount];
5503 }
5504 _end
686e302f 5505
9fdd37d0
JF
5506 _profile(PackageTable$reloadData$List)
5507 [list_ reloadData];
5508 _end
686e302f
JF
5509}
5510
8993ad57 5511- (void) resetCursor {
5d8f1006 5512 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
8993ad57
JF
5513}
5514
5d8f1006 5515- (UITableView *) list {
2a987aa5
JF
5516 return list_;
5517}
5518
59efd93a 5519- (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5d8f1006 5520 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
59efd93a
JF
5521}
5522
ce09fc27
JF
5523@end
5524/* }}} */
5525/* Filtered Package Table {{{ */
5526@interface FilteredPackageTable : PackageTable {
5527 SEL filter_;
142bd2db 5528 IMP imp_;
ce09fc27
JF
5529 id object_;
5530}
5531
5532- (void) setObject:(id)object;
5ec44e34 5533- (void) setObject:(id)object forFilter:(SEL)filter;
ce09fc27 5534
9ae52960 5535- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
ce09fc27
JF
5536
5537@end
5538
5539@implementation FilteredPackageTable
5540
5541- (void) dealloc {
5542 if (object_ != nil)
5543 [object_ release];
5544 [super dealloc];
5545}
5546
5ec44e34
JF
5547- (void) setFilter:(SEL)filter {
5548 filter_ = filter;
5549
5550 /* XXX: this is an unsafe optimization of doomy hell */
5551 Method method(class_getInstanceMethod([Package class], filter));
5552 _assert(method != NULL);
5553 imp_ = method_getImplementation(method);
5554 _assert(imp_ != NULL);
5555}
5556
ce09fc27
JF
5557- (void) setObject:(id)object {
5558 if (object_ != nil)
5559 [object_ release];
5560 if (object == nil)
5561 object_ = nil;
5562 else
5563 object_ = [object retain];
5564}
5565
5ec44e34
JF
5566- (void) setObject:(id)object forFilter:(SEL)filter {
5567 [self setFilter:filter];
5568 [self setObject:object];
5ec44e34
JF
5569}
5570
ce09fc27 5571- (bool) hasPackage:(Package *)package {
142bd2db
JF
5572 _profile(FilteredPackageTable$hasPackage)
5573 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5574 _end
ce09fc27
JF
5575}
5576
9ae52960
GP
5577- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5578 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5ec44e34 5579 [self setFilter:filter];
9ae52960 5580 object_ = [object retain];
6e673d99 5581 [self reloadData];
ce09fc27
JF
5582 } return self;
5583}
5584
a75f53e7 5585@end
686e302f 5586/* }}} */
a75f53e7 5587
f441e717
GP
5588/* Filtered Package Controller {{{ */
5589@interface FilteredPackageController : CYViewController {
9ae52960
GP
5590 _transient Database *database_;
5591 FilteredPackageTable *packages_;
5592 NSString *title_;
5593}
5594
5595- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5596
5597@end
f99f86e2 5598
f441e717 5599@implementation FilteredPackageController
9ae52960
GP
5600
5601- (void) dealloc {
5602 [packages_ release];
5603 [title_ release];
f99f86e2 5604
9ae52960
GP
5605 [super dealloc];
5606}
5607
5608- (void) viewDidAppear:(BOOL)animated {
5609 [super viewDidAppear:animated];
5610 [packages_ deselectWithAnimation:animated];
5611}
5612
5613- (void) didSelectPackage:(Package *)package {
f441e717 5614 PackageController *view([delegate_ packageController]);
9ae52960
GP
5615 [view setPackage:package];
5616 [view setDelegate:delegate_];
5617 [[self navigationController] pushViewController:view animated:YES];
5618}
5619
5620- (id) title { return title_; }
5621
5622- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5623 if ((self = [super init]) != nil) {
5624 database_ = database;
5625 title_ = [title copy];
5626 [[self navigationItem] setTitle:title_];
5627
5628 packages_ = [[FilteredPackageTable alloc]
5629 initWithFrame:[[self view] bounds]
5630 database:database
5631 target:self
5632 action:@selector(didSelectPackage:)
5633 filter:filter
5634 with:object
5635 ];
5636
5637 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5638 [[self view] addSubview:packages_];
5639 } return self;
5640}
5641
5642- (void) reloadData {
5643 [packages_ reloadData];
5644}
5645
5646- (void) setDelegate:(id)delegate {
5647 [super setDelegate:delegate];
5648 [packages_ setDelegate:delegate];
5649}
5650
5651@end
f99f86e2 5652
9ae52960
GP
5653/* }}} */
5654
f441e717
GP
5655/* Add Source Controller {{{ */
5656@interface AddSourceController : CYViewController {
faf4eb4f 5657 _transient Database *database_;
a75f53e7
JF
5658}
5659
9ae52960 5660- (id) initWithDatabase:(Database *)database;
686e302f 5661
faf4eb4f 5662@end
a75f53e7 5663
f441e717 5664@implementation AddSourceController
a75f53e7 5665
9ae52960
GP
5666- (id) initWithDatabase:(Database *)database {
5667 if ((self = [super init]) != nil) {
faf4eb4f
JF
5668 database_ = database;
5669 } return self;
e057ec05 5670}
a75f53e7 5671
faf4eb4f
JF
5672@end
5673/* }}} */
5674/* Source Cell {{{ */
1e4922b8
JF
5675@interface SourceCell : UITableViewCell <
5676 ContentDelegate
5677> {
5e563e79
JF
5678 UIImage *icon_;
5679 NSString *origin_;
5680 NSString *description_;
5681 NSString *label_;
d4a9ec10 5682 ContentView *content_;
686e302f
JF
5683}
5684
d4a9ec10 5685- (void) setSource:(Source *)source;
686e302f 5686
faf4eb4f 5687@end
686e302f 5688
faf4eb4f 5689@implementation SourceCell
686e302f 5690
d4a9ec10 5691- (void) clearSource {
5e563e79 5692 [icon_ release];
faf4eb4f
JF
5693 [origin_ release];
5694 [description_ release];
5695 [label_ release];
d4a9ec10
GP
5696
5697 icon_ = nil;
5698 origin_ = nil;
5699 description_ = nil;
5700 label_ = nil;
5701}
5702
5703- (void) setSource:(Source *)source {
5704 [self clearSource];
f99f86e2 5705
d4a9ec10
GP
5706 if (icon_ == nil)
5707 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5708 if (icon_ == nil)
5709 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5710 icon_ = [icon_ retain];
5711
5712 origin_ = [[source name] retain];
5713 label_ = [[source uri] retain];
5714 description_ = [[source description] retain];
5715
5716 [content_ setNeedsDisplay];
5717}
5718
5719- (void) dealloc {
5720 [self clearSource];
5721 [content_ release];
faf4eb4f 5722 [super dealloc];
e057ec05 5723}
686e302f 5724
d4a9ec10
GP
5725- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5726 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5727 UIView *content([self contentView]);
5728 CGRect bounds([content bounds]);
5729
5730 content_ = [[ContentView alloc] initWithFrame:bounds];
5731 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5732 [content_ setBackgroundColor:[UIColor whiteColor]];
5733 [content addSubview:content_];
5734
5735 [content_ setDelegate:self];
5736 [content_ setOpaque:YES];
faf4eb4f 5737 } return self;
48c0461e
JF
5738}
5739
d4a9ec10
GP
5740- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5741 [super setSelected:selected animated:animated];
5742 [content_ setNeedsDisplay];
5743}
5744
5745- (void) drawContentRect:(CGRect)rect {
5746 bool selected([self isSelected]);
5ec44e34
JF
5747 float width(rect.size.width);
5748
5e563e79
JF
5749 if (icon_ != nil)
5750 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
faf4eb4f 5751
5e563e79
JF
5752 if (selected)
5753 UISetColor(White_);
faf4eb4f 5754
5e563e79
JF
5755 if (!selected)
5756 UISetColor(Black_);
a6c1718e 5757 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
faf4eb4f 5758
5e563e79
JF
5759 if (!selected)
5760 UISetColor(Blue_);
a6c1718e 5761 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
faf4eb4f 5762
5e563e79
JF
5763 if (!selected)
5764 UISetColor(Gray_);
a6c1718e 5765 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
faf4eb4f
JF
5766}
5767
5768@end
5769/* }}} */
5770/* Source Table {{{ */
1e4922b8
JF
5771@interface SourceTable : CYViewController <
5772 UITableViewDataSource,
5773 UITableViewDelegate
5774> {
faf4eb4f 5775 _transient Database *database_;
d4a9ec10 5776 UITableView *list_;
faf4eb4f 5777 NSMutableArray *sources_;
faf4eb4f
JF
5778 int offset_;
5779
5780 NSString *href_;
5781 UIProgressHUD *hud_;
5782 NSError *error_;
5783
5784 //NSURLConnection *installer_;
3d3f4666 5785 NSURLConnection *trivial_;
faf4eb4f
JF
5786 NSURLConnection *trivial_bz2_;
5787 NSURLConnection *trivial_gz_;
5788 //NSURLConnection *automatic_;
5789
3d3f4666 5790 BOOL cydia_;
faf4eb4f
JF
5791}
5792
9ae52960 5793- (id) initWithDatabase:(Database *)database;
faf4eb4f 5794
1e4922b8
JF
5795- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5796
faf4eb4f
JF
5797@end
5798
5799@implementation SourceTable
5800
5801- (void) _deallocConnection:(NSURLConnection *)connection {
5802 if (connection != nil) {
5803 [connection cancel];
5804 //[connection setDelegate:nil];
5805 [connection release];
5806 }
5807}
5808
5809- (void) dealloc {
faf4eb4f
JF
5810 if (href_ != nil)
5811 [href_ release];
5812 if (hud_ != nil)
5813 [hud_ release];
5814 if (error_ != nil)
5815 [error_ release];
5816
5817 //[self _deallocConnection:installer_];
3d3f4666 5818 [self _deallocConnection:trivial_];
faf4eb4f
JF
5819 [self _deallocConnection:trivial_gz_];
5820 [self _deallocConnection:trivial_bz2_];
5821 //[self _deallocConnection:automatic_];
5822
5823 [sources_ release];
5824 [list_ release];
5825 [super dealloc];
5826}
5827
9ae52960
GP
5828- (void) viewDidAppear:(BOOL)animated {
5829 [super viewDidAppear:animated];
5830 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5831}
5832
d4a9ec10 5833- (int) numberOfSectionsInTableView:(UITableView *)tableView {
faf4eb4f
JF
5834 return offset_ == 0 ? 1 : 2;
5835}
5836
d4a9ec10 5837- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
faf4eb4f 5838 switch (section + (offset_ == 0 ? 1 : 0)) {
61b13cae
JF
5839 case 0: return UCLocalize("ENTERED_BY_USER");
5840 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
faf4eb4f 5841
6981ccdf 5842 _nodefault
faf4eb4f
JF
5843 }
5844}
5845
d4a9ec10
GP
5846- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5847 int count = [sources_ count];
5848 switch (section) {
5849 case 0: return (offset_ == 0 ? count : offset_);
5850 case 1: return count - offset_;
faf4eb4f 5851
9ae52960 5852 _nodefault
faf4eb4f
JF
5853 }
5854}
5855
d4a9ec10
GP
5856- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5857 unsigned idx = 0;
5858 switch (indexPath.section) {
5859 case 0: idx = indexPath.row; break;
5860 case 1: idx = indexPath.row + offset_; break;
5861
9ae52960 5862 _nodefault
d4a9ec10
GP
5863 }
5864 return [sources_ objectAtIndex:idx];
faf4eb4f
JF
5865}
5866
d4a9ec10
GP
5867- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5868 Source *source = [self sourceAtIndexPath:indexPath];
5e563e79 5869 return [source description] == nil ? 56 : 73;
faf4eb4f
JF
5870}
5871
d4a9ec10 5872- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9ae52960 5873 static NSString *cellIdentifier = @"SourceCell";
faf4eb4f 5874
d4a9ec10 5875 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
9ae52960
GP
5876 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5877 [cell setSource:[self sourceAtIndexPath:indexPath]];
f99f86e2 5878
d4a9ec10 5879 return cell;
faf4eb4f
JF
5880}
5881
1e4922b8
JF
5882- (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5883 return UITableViewCellAccessoryDisclosureIndicator;
faf4eb4f
JF
5884}
5885
d4a9ec10
GP
5886- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5887 Source *source = [self sourceAtIndexPath:indexPath];
faf4eb4f 5888
f441e717 5889 FilteredPackageController *packages = [[[FilteredPackageController alloc]
9ae52960 5890 initWithDatabase:database_
faf4eb4f
JF
5891 title:[source label]
5892 filter:@selector(isVisibleInSource:)
5893 with:source
5894 ] autorelease];
5895
5896 [packages setDelegate:delegate_];
5897
9ae52960 5898 [[self navigationController] pushViewController:packages animated:YES];
faf4eb4f
JF
5899}
5900
d4a9ec10
GP
5901- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5902 Source *source = [self sourceAtIndexPath:indexPath];
faf4eb4f
JF
5903 return [source record] != nil;
5904}
5905
d4a9ec10
GP
5906- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5907 Source *source = [self sourceAtIndexPath:indexPath];
faf4eb4f
JF
5908 [Sources_ removeObjectForKey:[source key]];
5909 [delegate_ syncData];
5910}
5911
b4dff19a
JF
5912- (void) complete {
5913 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5914 @"deb", @"Type",
5915 href_, @"URI",
5916 @"./", @"Distribution",
5917 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5918
5919 [delegate_ syncData];
5920}
5921
5922- (NSString *) getWarning {
7b00c562
JF
5923 NSString *href(href_);
5924 NSRange colon([href rangeOfString:@"://"]);
5925 if (colon.location != NSNotFound)
5926 href = [href substringFromIndex:(colon.location + 3)];
5927 href = [href stringByAddingPercentEscapes];
6981ccdf 5928 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
b4dff19a
JF
5929 href = [href stringByCachingURLWithCurrentCDN];
5930
5931 NSURL *url([NSURL URLWithString:href]);
5932
5933 NSStringEncoding encoding;
5934 NSError *error(nil);
5935
5936 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5937 return [warning length] == 0 ? nil : warning;
5938 return nil;
5939}
5940
faf4eb4f
JF
5941- (void) _endConnection:(NSURLConnection *)connection {
5942 NSURLConnection **field = NULL;
3d3f4666
JF
5943 if (connection == trivial_)
5944 field = &trivial_;
5945 else if (connection == trivial_bz2_)
faf4eb4f
JF
5946 field = &trivial_bz2_;
5947 else if (connection == trivial_gz_)
5948 field = &trivial_gz_;
5949 _assert(field != NULL);
5950 [connection release];
5951 *field = nil;
5952
5953 if (
3d3f4666 5954 trivial_ == nil &&
faf4eb4f
JF
5955 trivial_bz2_ == nil &&
5956 trivial_gz_ == nil
5957 ) {
7b00c562 5958 bool defer(false);
faf4eb4f 5959
3d3f4666 5960 if (cydia_) {
b4dff19a 5961 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7b00c562
JF
5962 defer = true;
5963
1ba930a4 5964 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 5965 initWithTitle:UCLocalize("SOURCE_WARNING")
9ae52960
GP
5966 message:warning
5967 delegate:self
5968 cancelButtonTitle:UCLocalize("CANCEL")
1ba930a4 5969 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
b4dff19a
JF
5970 ] autorelease];
5971
9ae52960 5972 [alert setContext:@"warning"];
1ba930a4
GP
5973 [alert setNumberOfRows:1];
5974 [alert show];
b4dff19a
JF
5975 } else
5976 [self complete];
faf4eb4f 5977 } else if (error_ != nil) {
1ba930a4 5978 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 5979 initWithTitle:UCLocalize("VERIFICATION_ERROR")
9ae52960
GP
5980 message:[error_ localizedDescription]
5981 delegate:self
5982 cancelButtonTitle:UCLocalize("OK")
1ba930a4 5983 otherButtonTitles:nil
faf4eb4f
JF
5984 ] autorelease];
5985
9ae52960 5986 [alert setContext:@"urlerror"];
1ba930a4 5987 [alert show];
faf4eb4f 5988 } else {
1ba930a4 5989 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 5990 initWithTitle:UCLocalize("NOT_REPOSITORY")
9ae52960
GP
5991 message:UCLocalize("NOT_REPOSITORY_EX")
5992 delegate:self
5993 cancelButtonTitle:UCLocalize("OK")
1ba930a4 5994 otherButtonTitles:nil
faf4eb4f
JF
5995 ] autorelease];
5996
9ae52960 5997 [alert setContext:@"trivial"];
1ba930a4 5998 [alert show];
faf4eb4f
JF
5999 }
6000
7b00c562
JF
6001 [delegate_ setStatusBarShowsProgress:NO];
6002 [delegate_ removeProgressHUD:hud_];
6003
6004 [hud_ autorelease];
6005 hud_ = nil;
6006
6007 if (!defer) {
6008 [href_ release];
6009 href_ = nil;
6010 }
faf4eb4f
JF
6011
6012 if (error_ != nil) {
6013 [error_ release];
6014 error_ = nil;
6015 }
6016 }
6017}
6018
6019- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6020 switch ([response statusCode]) {
6021 case 200:
3d3f4666 6022 cydia_ = YES;
faf4eb4f
JF
6023 }
6024}
6025
6026- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
cb9c2100 6027 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
faf4eb4f
JF
6028 if (error_ != nil)
6029 error_ = [error retain];
6030 [self _endConnection:connection];
6031}
6032
6033- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6034 [self _endConnection:connection];
6035}
6036
9ae52960
GP
6037- (id)title { return UCLocalize("SOURCES"); }
6038
faf4eb4f
JF
6039- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6040 NSMutableURLRequest *request = [NSMutableURLRequest
6041 requestWithURL:[NSURL URLWithString:href]
6042 cachePolicy:NSURLRequestUseProtocolCachePolicy
daf7f6e2 6043 timeoutInterval:120.0
faf4eb4f
JF
6044 ];
6045
6046 [request setHTTPMethod:method];
6047
6932575e
JF
6048 if (Machine_ != NULL)
6049 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
daf7f6e2
JF
6050 if (UniqueID_ != nil)
6051 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6932575e
JF
6052 if (Role_ != nil)
6053 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6054
faf4eb4f
JF
6055 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6056}
6057
1ba930a4
GP
6058- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6059 NSString *context([alert context]);
a5dd312c
JF
6060
6061 if ([context isEqualToString:@"source"]) {
faf4eb4f
JF
6062 switch (button) {
6063 case 1: {
1ba930a4 6064 NSString *href = [[alert textField] text];
faf4eb4f
JF
6065
6066 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6067
6068 if (![href hasSuffix:@"/"])
6069 href_ = [href stringByAppendingString:@"/"];
6070 else
6071 href_ = href;
6072 href_ = [href_ retain];
6073
3d3f4666 6074 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
faf4eb4f
JF
6075 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6076 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6077 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6078
3d3f4666 6079 cydia_ = false;
faf4eb4f 6080
7398a389 6081 hud_ = [[delegate_ addProgressHUD] retain];
61b13cae 6082 [hud_ setText:UCLocalize("VERIFYING_URL")];
faf4eb4f
JF
6083 } break;
6084
1ba930a4 6085 case 0:
faf4eb4f
JF
6086 break;
6087
6981ccdf 6088 _nodefault
faf4eb4f
JF
6089 }
6090
1ba930a4 6091 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b7adefda 6092 } else if ([context isEqualToString:@"trivial"])
1ba930a4 6093 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b7adefda 6094 else if ([context isEqualToString:@"urlerror"])
1ba930a4 6095 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b4dff19a
JF
6096 else if ([context isEqualToString:@"warning"]) {
6097 switch (button) {
6098 case 1:
6099 [self complete];
6100 break;
6101
1ba930a4 6102 case 0:
b4dff19a
JF
6103 break;
6104
6981ccdf 6105 _nodefault
b4dff19a
JF
6106 }
6107
7b00c562
JF
6108 [href_ release];
6109 href_ = nil;
6110
1ba930a4 6111 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b4dff19a 6112 }
faf4eb4f
JF
6113}
6114
9ae52960
GP
6115- (id) initWithDatabase:(Database *)database {
6116 if ((self = [super init]) != nil) {
6117 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6118 [self updateButtonsForEditingStatus:NO animated:NO];
f99f86e2 6119
faf4eb4f
JF
6120 database_ = database;
6121 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6122
9ae52960 6123 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
d3bef7bc 6124 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9ae52960 6125 [[self view] addSubview:list_];
d3bef7bc 6126
faf4eb4f 6127 [list_ setDataSource:self];
d4a9ec10 6128 [list_ setDelegate:self];
faf4eb4f
JF
6129
6130 [self reloadData];
6131 } return self;
6132}
6133
6134- (void) reloadData {
6135 pkgSourceList list;
6981ccdf
JF
6136 if (!list.ReadMainList())
6137 return;
faf4eb4f
JF
6138
6139 [sources_ removeAllObjects];
6140 [sources_ addObjectsFromArray:[database_ sources]];
f159ecd4 6141 _trace();
faf4eb4f 6142 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
f159ecd4 6143 _trace();
faf4eb4f 6144
9ae52960 6145 int count([sources_ count]);
d4a9ec10
GP
6146 offset_ = 0;
6147 for (int i = 0; i != count; i++) {
9ae52960
GP
6148 if ([[sources_ objectAtIndex:i] record] == nil) break;
6149 else offset_++;
faf4eb4f
JF
6150 }
6151
d4a9ec10 6152 [list_ setEditing:NO];
9ae52960 6153 [self updateButtonsForEditingStatus:NO animated:NO];
faf4eb4f
JF
6154 [list_ reloadData];
6155}
6156
9ae52960 6157- (void) addButtonClicked {
f441e717 6158 /*[book_ pushPage:[[[AddSourceController alloc]
faf4eb4f
JF
6159 initWithBook:book_
6160 database:database_
6161 ] autorelease]];*/
6162
1ba930a4 6163 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 6164 initWithTitle:UCLocalize("ENTER_APT_URL")
9ae52960
GP
6165 message:nil
6166 delegate:self
6167 cancelButtonTitle:UCLocalize("CANCEL")
6168 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
faf4eb4f
JF
6169 ] autorelease];
6170
9ae52960
GP
6171 [alert setContext:@"source"];
6172 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
a5dd312c 6173
1ba930a4
GP
6174 [alert setNumberOfRows:1];
6175 [alert addTextFieldWithValue:@"http://" label:@""];
faf4eb4f 6176
1ba930a4 6177 UITextInputTraits *traits = [[alert textField] textInputTraits];
b7adefda
JF
6178 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6179 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
a5dd312c 6180 [traits setKeyboardType:UIKeyboardTypeURL];
b7adefda
JF
6181 // XXX: UIReturnKeyDone
6182 [traits setReturnKeyType:UIReturnKeyNext];
faf4eb4f 6183
1ba930a4 6184 [alert show];
faf4eb4f
JF
6185}
6186
9ae52960
GP
6187- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6188 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6189 initWithTitle:UCLocalize("ADD")
6190 style:UIBarButtonItemStylePlain
6191 target:self
6192 action:@selector(addButtonClicked)
6193 ];
6194 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6195 [leftItem release];
6196
6197 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6198 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6199 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6200 target:self
6201 action:@selector(editButtonClicked)
6202 ];
6203 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6204 [rightItem release];
f99f86e2 6205
ca45de84
GP
6206 if (IsWildcat_ && !editing) {
6207 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6208 initWithTitle:UCLocalize("SETTINGS")
6209 style:UIBarButtonItemStylePlain
6210 target:self
6211 action:@selector(settingsButtonClicked)
6212 ];
6213 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6214 [settingsItem release];
6215 }
6216}
6217
6218- (void) settingsButtonClicked {
6219 [delegate_ showSettings];
faf4eb4f
JF
6220}
6221
9ae52960
GP
6222- (void) editButtonClicked {
6223 [list_ setEditing:![list_ isEditing] animated:YES];
f99f86e2 6224
9ae52960 6225 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
faf4eb4f
JF
6226}
6227
6228@end
6229/* }}} */
6230
f441e717
GP
6231/* Installed Controller {{{ */
6232@interface InstalledController : FilteredPackageController {
5e563e79 6233 BOOL expert_;
faf4eb4f
JF
6234}
6235
9ae52960 6236- (id) initWithDatabase:(Database *)database;
faf4eb4f 6237
1e4922b8
JF
6238- (void) updateRoleButton;
6239- (void) queueStatusDidChange;
6240
faf4eb4f
JF
6241@end
6242
f441e717 6243@implementation InstalledController
faf4eb4f
JF
6244
6245- (void) dealloc {
faf4eb4f
JF
6246 [super dealloc];
6247}
6248
9ae52960 6249- (id) title { return UCLocalize("INSTALLED"); }
87c76914 6250
9ae52960
GP
6251- (id) initWithDatabase:(Database *)database {
6252 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6253 [self updateRoleButton];
6254 [self queueStatusDidChange];
faf4eb4f
JF
6255 } return self;
6256}
6257
9ae52960
GP
6258#if !AlwaysReload
6259- (void) queueButtonClicked {
6260 [delegate_ queue];
faf4eb4f 6261}
9ae52960 6262#endif
faf4eb4f 6263
9ae52960
GP
6264- (void) queueStatusDidChange {
6265#if !AlwaysReload
6266 if (IsWildcat_) {
6267 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6268 initWithTitle:UCLocalize("QUEUE")
6269 style:UIBarButtonItemStyleDone
6270 target:self
6271 action:@selector(queueButtonClicked)
6272 ];
6273 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6274 else [[self navigationItem] setLeftBarButtonItem:nil];
6275 [queueItem release];
6276 }
6277#endif
5e563e79
JF
6278}
6279
9ae52960
GP
6280- (void) reloadData {
6281 [packages_ reloadData];
faf4eb4f
JF
6282}
6283
9ae52960
GP
6284- (void) updateRoleButton {
6285 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6286 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6287 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6288 target:self
6289 action:@selector(roleButtonClicked)
6290 ];
6291 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6292 [rightItem release];
faf4eb4f
JF
6293}
6294
9ae52960
GP
6295- (void) roleButtonClicked {
6296 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6297 [packages_ reloadData];
6298 expert_ = !expert_;
5e563e79 6299
9ae52960 6300 [self updateRoleButton];
5e563e79
JF
6301}
6302
faf4eb4f
JF
6303- (void) setDelegate:(id)delegate {
6304 [super setDelegate:delegate];
6305 [packages_ setDelegate:delegate];
6306}
6307
6308@end
6309/* }}} */
6310
f441e717
GP
6311/* Home Controller {{{ */
6312@interface HomeController : CYBrowserController {
faf4eb4f
JF
6313}
6314
6315@end
6316
f441e717 6317@implementation HomeController
faf4eb4f 6318
017b2b71
JF
6319- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6320 [super _setMoreHeaders:request];
6321 if (ChipID_ != nil)
6322 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
5ec44e34
JF
6323 if (UniqueID_ != nil)
6324 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
017b2b71
JF
6325}
6326
9ae52960 6327- (void) aboutButtonClicked {
99dc9e91
JF
6328 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6329 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6330 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6331 [alert setCancelButtonIndex:0];
faf4eb4f 6332
99dc9e91 6333 [alert setMessage:
daf7f6e2 6334 @"Copyright (C) 2008-2010\n"
faf4eb4f
JF
6335 "Jay Freeman (saurik)\n"
6336 "saurik@saurik.com\n"
991507f3 6337 "http://www.saurik.com/"
faf4eb4f
JF
6338 ];
6339
99dc9e91 6340 [alert show];
faf4eb4f
JF
6341}
6342
9ae52960
GP
6343- (void) viewWillAppear:(BOOL)animated {
6344 [super viewWillAppear:animated];
6345 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6346}
6347
6348- (void) viewWillDisappear:(BOOL)animated {
6349 [super viewWillDisappear:animated];
6350 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6351}
6352
6353- (id) init {
6354 if ((self = [super init]) != nil) {
6355 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6356 initWithTitle:UCLocalize("ABOUT")
6357 style:UIBarButtonItemStylePlain
6358 target:self
6359 action:@selector(aboutButtonClicked)
6360 ];
6361 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6362 [aboutItem release];
6363 } return self;
faf4eb4f
JF
6364}
6365
6366@end
1bb0d66c 6367/* }}} */
f441e717
GP
6368/* Manage Controller {{{ */
6369@interface ManageController : CYBrowserController {
faf4eb4f
JF
6370}
6371
1e4922b8 6372- (void) queueStatusDidChange;
faf4eb4f
JF
6373@end
6374
f441e717 6375@implementation ManageController
faf4eb4f 6376
9ae52960
GP
6377- (id) init {
6378 if ((self = [super init]) != nil) {
6379 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
f99f86e2 6380
9ae52960
GP
6381 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6382 initWithTitle:UCLocalize("SETTINGS")
6383 style:UIBarButtonItemStylePlain
6384 target:self
6385 action:@selector(settingsButtonClicked)
6386 ];
6387 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6388 [settingsItem release];
f99f86e2 6389
9ae52960
GP
6390 [self queueStatusDidChange];
6391 } return self;
faf4eb4f
JF
6392}
6393
9ae52960 6394- (void) settingsButtonClicked {
c1edf105 6395 [delegate_ showSettings];
faf4eb4f
JF
6396}
6397
541a556a 6398#if !AlwaysReload
9ae52960
GP
6399- (void) queueButtonClicked {
6400 [delegate_ queue];
3ff1504e
JF
6401}
6402
b38613d7
GP
6403- (void) applyLoadingTitle {
6404 // No "Loading" title.
6405}
6406
6407- (void) applyRightButton {
6408 // No right button.
3ff1504e 6409}
b38613d7 6410#endif
3ff1504e 6411
9ae52960
GP
6412- (void) queueStatusDidChange {
6413#if !AlwaysReload
6414 if (!IsWildcat_ && Queuing_) {
6415 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6416 initWithTitle:UCLocalize("QUEUE")
6417 style:UIBarButtonItemStyleDone
6418 target:self
6419 action:@selector(queueButtonClicked)
6420 ];
6421 [[self navigationItem] setRightBarButtonItem:queueItem];
f99f86e2 6422
9ae52960
GP
6423 [queueItem release];
6424 } else {
6425 [[self navigationItem] setRightBarButtonItem:nil];
6426 }
541a556a 6427#endif
9ae52960 6428}
faf4eb4f 6429
d8d9a65c 6430- (bool) isLoading {
a99d2808
JF
6431 return false;
6432}
6433
faf4eb4f 6434@end
1bb0d66c 6435/* }}} */
faf4eb4f 6436
9ae52960
GP
6437/* Refresh Bar {{{ */
6438@interface RefreshBar : UINavigationBar {
faf4eb4f
JF
6439 UIProgressIndicator *indicator_;
6440 UITextLabel *prompt_;
6441 UIProgressBar *progress_;
87c76914 6442 UINavigationButton *cancel_;
30d83bfe
JF
6443}
6444
30d83bfe 6445@end
30d83bfe 6446
9ae52960 6447@implementation RefreshBar
5ec44e34 6448
ba6cbb36
GP
6449- (void) positionViews {
6450 CGRect frame = [cancel_ frame];
6451 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6452 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6453 [cancel_ setFrame:frame];
f99f86e2 6454
ba6cbb36
GP
6455 CGSize prgsize = {75, 100};
6456 CGRect prgrect = {{
6457 [self frame].size.width - prgsize.width - 10,
6458 ([self frame].size.height - prgsize.height) / 2
6459 } , prgsize};
6460 [progress_ setFrame:prgrect];
f99f86e2 6461
ba6cbb36
GP
6462 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6463 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6464 CGRect indrect = {{indoffset, indoffset}, indsize};
6465 [indicator_ setFrame:indrect];
f99f86e2 6466
ba6cbb36
GP
6467 CGSize prmsize = {215, indsize.height + 4};
6468 CGRect prmrect = {{
6469 indoffset * 2 + indsize.width,
6470 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6471 }, prmsize};
6472 [prompt_ setFrame:prmrect];
6473}
6474
6475- (void)setFrame:(CGRect)frame {
6476 [super setFrame:frame];
f99f86e2 6477
ba6cbb36
GP
6478 [self positionViews];
6479}
6480
9ae52960
GP
6481- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6482 if ((self = [super initWithFrame:frame])) {
6483 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
5ec44e34 6484
9ae52960 6485 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
1e4922b8 6486 [self setBarStyle:UIBarStyleBlack];
5ec44e34 6487
1e4922b8
JF
6488 UIBarStyle barstyle([self _barStyle:NO]);
6489 bool ugly(barstyle == UIBarStyleDefault);
f159ecd4
JF
6490
6491 UIProgressIndicatorStyle style = ugly ?
6492 UIProgressIndicatorStyleMediumBrown :
6493 UIProgressIndicatorStyleMediumWhite;
6494
ba6cbb36 6495 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
f159ecd4 6496 [indicator_ setStyle:style];
ba6cbb36 6497 [indicator_ startAnimation];
9ae52960 6498 [self addSubview:indicator_];
f159ecd4 6499
ba6cbb36 6500 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
f159ecd4
JF
6501 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6502 [prompt_ setBackgroundColor:[UIColor clearColor]];
ba6cbb36 6503 [prompt_ setFont:[UIFont systemFontOfSize:15]];
9ae52960 6504 [self addSubview:prompt_];
f159ecd4 6505
ba6cbb36
GP
6506 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6507 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
d3bef7bc 6508 [progress_ setStyle:0];
ba6cbb36 6509 [self addSubview:progress_];
f99f86e2 6510
61b13cae 6511 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
e7a88a8c 6512 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
9ae52960 6513 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
ba6cbb36 6514 [cancel_ setBarStyle:barstyle];
f99f86e2 6515
ba6cbb36 6516 [self positionViews];
f159ecd4
JF
6517 } return self;
6518}
6519
9ae52960 6520- (void) cancel {
f159ecd4
JF
6521 [cancel_ removeFromSuperview];
6522}
6523
9ae52960
GP
6524- (void) start {
6525 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6526 [progress_ setProgress:0];
6527 [self addSubview:cancel_];
6528}
6529
6530- (void) stop {
6531 [cancel_ removeFromSuperview];
6532}
6533
6534- (void) setPrompt:(NSString *)prompt {
6535 [prompt_ setText:prompt];
6536}
6537
6538- (void) setProgress:(float)progress {
6539 [progress_ setProgress:progress];
6540}
6541
6542@end
6543/* }}} */
6544
1e4922b8
JF
6545@class CYNavigationController;
6546
9ae52960 6547/* Cydia Tab Bar Controller {{{ */
e7a88a8c
GP
6548@interface CYTabBarController : UITabBarController {
6549 Database *database_;
9ae52960
GP
6550}
6551
f99f86e2 6552@end
9ae52960
GP
6553
6554@implementation CYTabBarController
6555
e7a88a8c
GP
6556/* XXX: some logic should probably go here related to
6557freeing the view controllers on tab change */
f159ecd4 6558
9ae52960
GP
6559- (void) reloadData {
6560 size_t count([[self viewControllers] count]);
6561 for (size_t i(0); i != count; ++i) {
1e4922b8 6562 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
9ae52960
GP
6563 [page reloadData];
6564 }
6565}
6566
9ae52960
GP
6567- (id) initWithDatabase: (Database *)database {
6568 if ((self = [super init]) != nil) {
6569 database_ = database;
9ae52960
GP
6570 } return self;
6571}
6572
6573@end
6574/* }}} */
6575
6576/* Cydia Navigation Controller {{{ */
1e4922b8 6577@interface CYNavigationController : UINavigationController {
9ae52960
GP
6578 _transient Database *database_;
6579 id delegate_;
6580}
6581
6582- (id) initWithDatabase:(Database *)database;
6583- (void) reloadData;
6584
6585@end
6586
6587
6588@implementation CYNavigationController
6589
15b41c77
GP
6590- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6591 // Inherit autorotation settings for modal parents.
6592 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6593 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6594 } else {
6595 return [super shouldAutorotateToInterfaceOrientation:orientation];
6596 }
6597}
6598
9ae52960
GP
6599- (void) dealloc {
6600 [super dealloc];
6601}
6602
6603- (void) reloadData {
6604 size_t count([[self viewControllers] count]);
6605 for (size_t i(0); i != count; ++i) {
1e4922b8 6606 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
9ae52960
GP
6607 [page reloadData];
6608 }
6609}
6610
6611- (void) setDelegate:(id)delegate {
6612 delegate_ = delegate;
6613}
6614
6615- (id) initWithDatabase:(Database *)database {
6616 if ((self = [super init]) != nil) {
6617 database_ = database;
6618 } return self;
6619}
6620
f159ecd4
JF
6621@end
6622/* }}} */
6623/* Cydia:// Protocol {{{ */
6624@interface CydiaURLProtocol : NSURLProtocol {
6625}
6626
6627@end
6628
6629@implementation CydiaURLProtocol
6630
6631+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
6632 NSURL *url([request URL]);
6633 if (url == nil)
6634 return NO;
6635 NSString *scheme([[url scheme] lowercaseString]);
6636 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6637 return NO;
6638 return YES;
6639}
6640
6641+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6642 return request;
6643}
6644
a99d2808
JF
6645- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6646 id<NSURLProtocolClient> client([self client]);
6e673d99
JF
6647 if (icon == nil)
6648 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6649 else {
6650 NSData *data(UIImagePNGRepresentation(icon));
a99d2808 6651
6e673d99
JF
6652 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6653 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6654 [client URLProtocol:self didLoadData:data];
6655 [client URLProtocolDidFinishLoading:self];
6656 }
a99d2808
JF
6657}
6658
f159ecd4
JF
6659- (void) startLoading {
6660 id<NSURLProtocolClient> client([self client]);
6661 NSURLRequest *request([self request]);
6662
6663 NSURL *url([request URL]);
6664 NSString *href([url absoluteString]);
6665
6666 NSString *path([href substringFromIndex:8]);
6667 NSRange slash([path rangeOfString:@"/"]);
6668
6669 NSString *command;
6670 if (slash.location == NSNotFound) {
6671 command = path;
6672 path = nil;
6673 } else {
6674 command = [path substringToIndex:slash.location];
6675 path = [path substringFromIndex:(slash.location + 1)];
6676 }
6677
6678 Database *database([Database sharedInstance]);
6679
6680 if ([command isEqualToString:@"package-icon"]) {
6681 if (path == nil)
6682 goto fail;
6b4b3bee 6683 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
f159ecd4
JF
6684 Package *package([database packageWithName:path]);
6685 if (package == nil)
6686 goto fail;
6b4b3bee 6687 UIImage *icon([package icon]);
a99d2808 6688 [self _returnPNGWithImage:icon forRequest:request];
18159e09
JF
6689 } else if ([command isEqualToString:@"source-icon"]) {
6690 if (path == nil)
6691 goto fail;
6692 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6693 NSString *source(Simplify(path));
18159e09
JF
6694 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6695 if (icon == nil)
6696 icon = [UIImage applicationImageNamed:@"unknown.png"];
a99d2808
JF
6697 [self _returnPNGWithImage:icon forRequest:request];
6698 } else if ([command isEqualToString:@"uikit-image"]) {
6699 if (path == nil)
6700 goto fail;
6701 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6702 UIImage *icon(_UIImageWithName(path));
6703 [self _returnPNGWithImage:icon forRequest:request];
6b4b3bee
JF
6704 } else if ([command isEqualToString:@"section-icon"]) {
6705 if (path == nil)
6706 goto fail;
6707 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6708 NSString *section(Simplify(path));
6b4b3bee
JF
6709 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6710 if (icon == nil)
6711 icon = [UIImage applicationImageNamed:@"unknown.png"];
a99d2808 6712 [self _returnPNGWithImage:icon forRequest:request];
f159ecd4
JF
6713 } else fail: {
6714 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6715 }
6716}
6717
6718- (void) stopLoading {
6719}
6720
6721@end
6722/* }}} */
6723
f441e717 6724/* Sections Controller {{{ */
1e4922b8
JF
6725@interface SectionsController : CYViewController <
6726 UITableViewDataSource,
6727 UITableViewDelegate
6728> {
f159ecd4
JF
6729 _transient Database *database_;
6730 NSMutableArray *sections_;
6731 NSMutableArray *filtered_;
d4a9ec10 6732 UITableView *list_;
f159ecd4
JF
6733 UIView *accessory_;
6734 BOOL editing_;
6735}
6736
9ae52960 6737- (id) initWithDatabase:(Database *)database;
f159ecd4
JF
6738- (void) reloadData;
6739- (void) resetView;
6740
1e4922b8
JF
6741- (void) editButtonClicked;
6742
f159ecd4
JF
6743@end
6744
f441e717 6745@implementation SectionsController
f159ecd4
JF
6746
6747- (void) dealloc {
6748 [list_ setDataSource:nil];
6749 [list_ setDelegate:nil];
6750
6751 [sections_ release];
6752 [filtered_ release];
f159ecd4
JF
6753 [list_ release];
6754 [accessory_ release];
6755 [super dealloc];
6756}
6757
9ae52960
GP
6758- (void) viewDidAppear:(BOOL)animated {
6759 [super viewDidAppear:animated];
6760 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6761}
6762
d4a9ec10
GP
6763- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6764 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6765 return section;
f159ecd4
JF
6766}
6767
d4a9ec10
GP
6768- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6769 return editing_ ? [sections_ count] : [filtered_ count] + 1;
f159ecd4
JF
6770}
6771
2064d251
GP
6772/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6773 return 45.0f;
6774}*/
f159ecd4 6775
d4a9ec10 6776- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9ae52960
GP
6777 static NSString *reuseIdentifier = @"SectionCell";
6778
6779 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6780 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
d4a9ec10 6781 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
f159ecd4 6782
d4a9ec10 6783 return cell;
f159ecd4
JF
6784}
6785
d4a9ec10
GP
6786- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6787 Section *section = [self sectionAtIndexPath:indexPath];
6788 NSString *name = [section name];
f159ecd4
JF
6789 NSString *title;
6790
d4a9ec10 6791 if ([indexPath row] == 0) {
f159ecd4
JF
6792 section = nil;
6793 name = nil;
61b13cae 6794 title = UCLocalize("ALL_PACKAGES");
f159ecd4 6795 } else {
ca06bb0e
JF
6796 if (name != nil) {
6797 name = [NSString stringWithString:name];
6932575e 6798 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
ca06bb0e 6799 } else {
f159ecd4 6800 name = @"";
61b13cae 6801 title = UCLocalize("NO_SECTION");
f159ecd4
JF
6802 }
6803 }
6804
f441e717 6805 FilteredPackageController *table = [[[FilteredPackageController alloc]
9ae52960 6806 initWithDatabase:database_
f159ecd4 6807 title:title
6981ccdf 6808 filter:@selector(isVisibleInSection:)
f159ecd4
JF
6809 with:name
6810 ] autorelease];
6811
6812 [table setDelegate:delegate_];
6813
9ae52960 6814 [[self navigationController] pushViewController:table animated:YES];
f159ecd4
JF
6815}
6816
9ae52960
GP
6817- (id) title { return UCLocalize("SECTIONS"); }
6818
6819- (id) initWithDatabase:(Database *)database {
6820 if ((self = [super init]) != nil) {
f159ecd4
JF
6821 database_ = database;
6822
9ae52960
GP
6823 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6824
f159ecd4
JF
6825 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6826 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6827
9ae52960 6828 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
d3bef7bc 6829 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
2064d251 6830 [list_ setRowHeight:45.0f];
9ae52960 6831 [[self view] addSubview:list_];
f159ecd4 6832
d4a9ec10 6833 [list_ setDataSource:self];
9ae52960 6834 [list_ setDelegate:self];
f159ecd4
JF
6835
6836 [self reloadData];
f159ecd4
JF
6837 } return self;
6838}
6839
6840- (void) reloadData {
6841 NSArray *packages = [database_ packages];
6842
6843 [sections_ removeAllObjects];
6844 [filtered_ removeAllObjects];
6845
6932575e
JF
6846#if 0
6847 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6848 SectionMap sections;
6849 sections.resize(64);
6850#else
6851 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6852#endif
f159ecd4
JF
6853
6854 _trace();
9fdd37d0 6855 for (Package *package in packages) {
f159ecd4 6856 NSString *name([package section]);
6932575e 6857 NSString *key(name == nil ? @"" : name);
f159ecd4 6858
6932575e
JF
6859#if 0
6860 Section **section;
6861
6862 _profile(SectionsView$reloadData$Section)
6863 section = &sections[key];
6864 if (*section == nil) {
6865 _profile(SectionsView$reloadData$Section$Allocate)
9ee296df 6866 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6932575e
JF
6867 _end
6868 }
6869 _end
6870
6871 [*section addToCount];
6872
6873 _profile(SectionsView$reloadData$Filter)
6981ccdf 6874 if (![package valid] || ![package visible])
6932575e
JF
6875 continue;
6876 _end
6877
6878 [*section addToRow];
6879#else
6880 Section *section;
6881
6882 _profile(SectionsView$reloadData$Section)
6883 section = [sections objectForKey:key];
f159ecd4 6884 if (section == nil) {
6932575e 6885 _profile(SectionsView$reloadData$Section$Allocate)
9ee296df 6886 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6932575e
JF
6887 [sections setObject:section forKey:key];
6888 _end
f159ecd4 6889 }
6932575e
JF
6890 _end
6891
6892 [section addToCount];
fa7bb92f 6893
6932575e 6894 _profile(SectionsView$reloadData$Filter)
6981ccdf 6895 if (![package valid] || ![package visible])
6932575e
JF
6896 continue;
6897 _end
6898
6899 [section addToRow];
6900#endif
686e302f 6901 }
f159ecd4 6902 _trace();
a75f53e7 6903
6932575e
JF
6904#if 0
6905 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6906 [sections_ addObject:i->second];
6907#else
fa7bb92f 6908 [sections_ addObjectsFromArray:[sections allValues]];
6932575e 6909#endif
fa7bb92f 6910
43b742af 6911 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
a75f53e7 6912
6932575e
JF
6913 for (Section *section in sections_) {
6914 size_t count([section row]);
43b742af 6915 if (count == 0)
6932575e 6916 continue;
a75f53e7 6917
9ee296df 6918 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6932575e
JF
6919 [section setCount:count];
6920 [filtered_ addObject:section];
686e302f 6921 }
4941f41d 6922
9ae52960
GP
6923 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6924 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6925 style:UIBarButtonItemStylePlain
6926 target:self
6927 action:@selector(editButtonClicked)
6928 ];
84aa0f36 6929 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
9ae52960
GP
6930 [rightItem release];
6931
686e302f 6932 [list_ reloadData];
f159ecd4 6933 _trace();
e057ec05 6934}
4941f41d 6935
fa7bb92f
JF
6936- (void) resetView {
6937 if (editing_)
9ae52960 6938 [self editButtonClicked];
e057ec05 6939}
4941f41d 6940
9ae52960 6941- (void) editButtonClicked {
fa7bb92f
JF
6942 if ((editing_ = !editing_))
6943 [list_ reloadData];
f159ecd4 6944 else
fa7bb92f 6945 [delegate_ updateData];
f99f86e2 6946
9ae52960
GP
6947 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6948 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6949 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
87c76914
JF
6950}
6951
9e07091a
JF
6952- (UIView *) accessoryView {
6953 return accessory_;
6954}
6955
a75f53e7 6956@end
4941f41d 6957/* }}} */
f441e717 6958/* Changes Controller {{{ */
1e4922b8
JF
6959@interface ChangesController : CYViewController <
6960 UITableViewDataSource,
6961 UITableViewDelegate
6962> {
e057ec05 6963 _transient Database *database_;
a75f53e7
JF
6964 NSMutableArray *packages_;
6965 NSMutableArray *sections_;
5d8f1006 6966 UITableView *list_;
e057ec05 6967 unsigned upgrades_;
77a4e323 6968 BOOL hasSentFirstLoad_;
a75f53e7
JF
6969}
6970
9ae52960 6971- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
e057ec05 6972- (void) reloadData;
a75f53e7 6973
a75f53e7
JF
6974@end
6975
f441e717 6976@implementation ChangesController
686e302f
JF
6977
6978- (void) dealloc {
5d8f1006 6979 [list_ setDelegate:nil];
e057ec05
JF
6980 [list_ setDataSource:nil];
6981
686e302f
JF
6982 [packages_ release];
6983 [sections_ release];
e057ec05 6984 [list_ release];
686e302f
JF
6985 [super dealloc];
6986}
a75f53e7 6987
9ae52960
GP
6988- (void) viewDidAppear:(BOOL)animated {
6989 [super viewDidAppear:animated];
77a4e323
RP
6990 if (!hasSentFirstLoad_) {
6991 hasSentFirstLoad_ = YES;
6992 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6993 } else {
6994 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6995 }
9ae52960
GP
6996}
6997
5d8f1006
JF
6998- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6999 NSInteger count([sections_ count]);
7000 return count == 0 ? 1 : count;
a75f53e7
JF
7001}
7002
5d8f1006
JF
7003- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7004 if ([sections_ count] == 0)
7005 return nil;
a75f53e7
JF
7006 return [[sections_ objectAtIndex:section] name];
7007}
7008
5d8f1006
JF
7009- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7010 if ([sections_ count] == 0)
7011 return 0;
7012 return [[sections_ objectAtIndex:section] count];
a75f53e7
JF
7013}
7014
5d8f1006
JF
7015- (Package *) packageAtIndexPath:(NSIndexPath *)path {
7016 Section *section([sections_ objectAtIndex:[path section]]);
7017 NSInteger row([path row]);
7018 return [packages_ objectAtIndex:([section row] + row)];
a75f53e7
JF
7019}
7020
5d8f1006 7021- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
1e4922b8 7022 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5d8f1006
JF
7023 if (cell == nil)
7024 cell = [[[PackageCell alloc] init] autorelease];
7025 [cell setPackage:[self packageAtIndexPath:path]];
7026 return cell;
a75f53e7
JF
7027}
7028
2064d251 7029/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5d8f1006 7030 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
2064d251 7031}*/
a75f53e7 7032
5d8f1006
JF
7033- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7034 Package *package([self packageAtIndexPath:path]);
f441e717 7035 PackageController *view([delegate_ packageController]);
e057ec05
JF
7036 [view setDelegate:delegate_];
7037 [view setPackage:package];
9ae52960 7038 [[self navigationController] pushViewController:view animated:YES];
5d8f1006 7039 return path;
a75f53e7
JF
7040}
7041
9ae52960 7042- (void) refreshButtonClicked {
1e4922b8 7043 [delegate_ beginUpdate];
9ae52960 7044 [[self navigationItem] setLeftBarButtonItem:nil];
b7eb9e84
JF
7045}
7046
9ae52960 7047- (void) upgradeButtonClicked {
e057ec05 7048 [delegate_ distUpgrade];
a75f53e7
JF
7049}
7050
9ae52960
GP
7051- (id) title { return UCLocalize("CHANGES"); }
7052
7053- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7054 if ((self = [super init]) != nil) {
e057ec05 7055 database_ = database;
9ae52960 7056 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
a75f53e7 7057
686e302f
JF
7058 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7059 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
a75f53e7 7060
9ae52960 7061 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
d3bef7bc 7062 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
2064d251 7063 [list_ setRowHeight:73.0f];
9ae52960 7064 [[self view] addSubview:list_];
e057ec05 7065
686e302f 7066 [list_ setDataSource:self];
5d8f1006 7067 [list_ setDelegate:self];
a75f53e7 7068
daf7f6e2 7069 delegate_ = delegate;
a75f53e7
JF
7070 } return self;
7071}
7072
daf7f6e2 7073- (void) _reloadPackages:(NSArray *)packages {
f159ecd4 7074 _trace();
9fdd37d0 7075 for (Package *package in packages)
fa7bb92f 7076 if (
b4c4fac4 7077 [package uninstalled] && [package valid] && [package visible] ||
6e673d99 7078 [package upgradableAndEssential:YES]
fa7bb92f 7079 )
686e302f 7080 [packages_ addObject:package];
4941f41d 7081
f159ecd4 7082 _trace();
dd9390c5 7083 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
f159ecd4 7084 _trace();
daf7f6e2
JF
7085}
7086
7087- (void) reloadData {
7088 NSArray *packages = [database_ packages];
7089
7090 [packages_ removeAllObjects];
7091 [sections_ removeAllObjects];
7092
7093 UIProgressHUD *hud([delegate_ addProgressHUD]);
7094 // XXX: localize
7095 [hud setText:@"Loading Changes"];
7096 NSLog(@"HUD:%@::%@", delegate_, hud);
7097 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7098 [delegate_ removeProgressHUD:hud];
a75f53e7 7099
61b13cae
JF
7100 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7101 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
a75f53e7 7102 Section *section = nil;
f159ecd4 7103 NSDate *last = nil;
686e302f 7104
e057ec05
JF
7105 upgrades_ = 0;
7106 bool unseens = false;
7107
43b742af 7108 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
e057ec05 7109
a75f53e7
JF
7110 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7111 Package *package = [packages_ objectAtIndex:offset];
a75f53e7 7112
43b742af 7113 BOOL uae = [package upgradableAndEssential:YES];
6932575e
JF
7114
7115 if (!uae) {
e057ec05 7116 unseens = true;
6932575e 7117 NSDate *seen;
a75f53e7 7118
f441e717 7119 _profile(ChangesController$reloadData$Remember)
6932575e
JF
7120 seen = [package seen];
7121 _end
7122
43b742af 7123 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
f159ecd4 7124 last = seen;
138ae18d 7125
3ff1504e
JF
7126 NSString *name;
7127 if (seen == nil)
61b13cae 7128 name = UCLocalize("UNKNOWN");
3ff1504e 7129 else {
43b742af 7130 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
3ff1504e
JF
7131 [name autorelease];
7132 }
7133
f441e717 7134 _profile(ChangesController$reloadData$Allocate)
61b13cae 7135 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
9ee296df 7136 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6932575e
JF
7137 [sections_ addObject:section];
7138 _end
686e302f
JF
7139 }
7140
e057ec05 7141 [section addToCount];
f159ecd4
JF
7142 } else if ([package ignored])
7143 [ignored addToCount];
7144 else {
7145 ++upgrades_;
7146 [upgradable addToCount];
686e302f 7147 }
a75f53e7 7148 }
f159ecd4 7149 _trace();
a75f53e7 7150
e057ec05 7151 CFRelease(formatter);
686e302f 7152
e057ec05
JF
7153 if (unseens) {
7154 Section *last = [sections_ lastObject];
7155 size_t count = [last count];
7156 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7157 [sections_ removeLastObject];
7158 }
a75f53e7 7159
f159ecd4
JF
7160 if ([ignored count] != 0)
7161 [sections_ insertObject:ignored atIndex:0];
e057ec05
JF
7162 if (upgrades_ != 0)
7163 [sections_ insertObject:upgradable atIndex:0];
d12c6e70 7164
e057ec05 7165 [list_ reloadData];
2d28b35a 7166
9ae52960
GP
7167 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7168 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7169 style:UIBarButtonItemStylePlain
7170 target:self
7171 action:@selector(upgradeButtonClicked)
7172 ];
7173 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7174 [rightItem release];
7175
7176 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7177 initWithTitle:UCLocalize("REFRESH")
7178 style:UIBarButtonItemStylePlain
7179 target:self
7180 action:@selector(refreshButtonClicked)
7181 ];
1e4922b8 7182 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
9ae52960 7183 [leftItem release];
b6ffa083
JF
7184}
7185
2d28b35a
JF
7186@end
7187/* }}} */
f441e717 7188/* Search Controller {{{ */
1e4922b8
JF
7189@interface SearchController : FilteredPackageController <
7190 UISearchBarDelegate
7191> {
7192 UISearchBar *search_;
e057ec05 7193}
686e302f 7194
9ae52960 7195- (id) initWithDatabase:(Database *)database;
e057ec05 7196- (void) reloadData;
686e302f 7197
2d28b35a
JF
7198@end
7199
f441e717 7200@implementation SearchController
2d28b35a 7201
686e302f 7202- (void) dealloc {
9ae52960 7203 [search_ release];
e057ec05 7204 [super dealloc];
686e302f
JF
7205}
7206
9ae52960
GP
7207- (void) searchBarSearchButtonClicked:(id)searchBar {
7208 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7209 [search_ resignFirstResponder];
5ec44e34 7210 [self reloadData];
e057ec05 7211}
686e302f 7212
9ae52960
GP
7213- (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7214 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
5ec44e34 7215 [self reloadData];
e057ec05 7216}
686e302f 7217
9ae52960 7218- (id) title { return nil; }
59efd93a 7219
9ae52960 7220- (id) initWithDatabase:(Database *)database {
2c4fc6f1
RP
7221 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7222}
7223
7224- (void)viewDidAppear:(BOOL)animated {
f99f86e2
JF
7225 [super viewDidAppear:animated];
7226 if (!search_) {
1e4922b8 7227 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
2c4fc6f1 7228 [search_ layoutSubviews];
9ae52960 7229 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
2c4fc6f1
RP
7230 UITextField *textField = [search_ searchField];
7231 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9ae52960 7232 [search_ setDelegate:self];
2c4fc6f1
RP
7233 [textField setEnablesReturnKeyAutomatically:NO];
7234 [[self navigationItem] setTitleView:textField];
7235 }
2d28b35a
JF
7236}
7237
f159ecd4
JF
7238- (void) _reloadData {
7239}
686e302f 7240
f159ecd4 7241- (void) reloadData {
f441e717 7242 _profile(SearchController$reloadData)
9ae52960 7243 [packages_ reloadData];
3bddda52
JF
7244 _end
7245 PrintTimes();
9ae52960 7246 [packages_ resetCursor];
f159ecd4 7247}
b6ffa083 7248
583b5809
RP
7249- (void) didSelectPackage:(Package *)package {
7250 [search_ resignFirstResponder];
7251 [super didSelectPackage:package];
7252}
7253
f159ecd4
JF
7254@end
7255/* }}} */
f441e717 7256/* Settings Controller {{{ */
1e4922b8
JF
7257@interface SettingsController : CYViewController <
7258 UITableViewDataSource,
7259 UITableViewDelegate
7260> {
f159ecd4
JF
7261 _transient Database *database_;
7262 NSString *name_;
7263 Package *package_;
31a8e05a
GP
7264 UITableView *table_;
7265 id subscribedSwitch_;
7266 id ignoredSwitch_;
7267 UITableViewCell *subscribedCell_;
7268 UITableViewCell *ignoredCell_;
f159ecd4 7269}
686e302f 7270
9ae52960 7271- (id) initWithDatabase:(Database *)database package:(NSString *)package;
686e302f 7272
f159ecd4 7273@end
686e302f 7274
f441e717 7275@implementation SettingsController
686e302f 7276
f159ecd4 7277- (void) dealloc {
f159ecd4
JF
7278 [name_ release];
7279 if (package_ != nil)
7280 [package_ release];
7281 [table_ release];
7282 [subscribedSwitch_ release];
7283 [ignoredSwitch_ release];
7284 [subscribedCell_ release];
7285 [ignoredCell_ release];
f99f86e2 7286
f159ecd4
JF
7287 [super dealloc];
7288}
686e302f 7289
31a8e05a 7290- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
f159ecd4
JF
7291 if (package_ == nil)
7292 return 0;
686e302f 7293
31a8e05a 7294 return 1;
2d28b35a
JF
7295}
7296
31a8e05a 7297- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
f159ecd4
JF
7298 if (package_ == nil)
7299 return 0;
a75f53e7 7300
31a8e05a
GP
7301 return 1;
7302}
87c76914 7303
31a8e05a
GP
7304- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7305 return UCLocalize("SHOW_ALL_CHANGES_EX");
e057ec05 7306}
686e302f 7307
31a8e05a 7308- (void) onSomething:(BOOL)value withKey:(NSString *)key {
f159ecd4
JF
7309 if (package_ == nil)
7310 return;
686e302f 7311
f159ecd4 7312 NSMutableDictionary *metadata([package_ metadata]);
87c76914 7313
f159ecd4
JF
7314 BOOL before;
7315 if (NSNumber *number = [metadata objectForKey:key])
7316 before = [number boolValue];
7317 else
7318 before = NO;
e057ec05 7319
f159ecd4
JF
7320 if (value != before) {
7321 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7322 Changed_ = true;
f159ecd4
JF
7323 [delegate_ updateData];
7324 }
87c76914
JF
7325}
7326
31a8e05a
GP
7327- (void) onSubscribed:(id)control {
7328 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
e057ec05 7329}
686e302f 7330
31a8e05a
GP
7331- (void) onIgnored:(id)control {
7332 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
b6ffa083
JF
7333}
7334
31a8e05a 7335- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
f159ecd4
JF
7336 if (package_ == nil)
7337 return nil;
dbe0f181 7338
31a8e05a
GP
7339 switch ([indexPath row]) {
7340 case 0: return subscribedCell_;
7341 case 1: return ignoredCell_;
f99f86e2 7342
6981ccdf 7343 _nodefault
f159ecd4 7344 }
dbe0f181 7345
f159ecd4 7346 return nil;
dbe0f181
JF
7347}
7348
9ae52960
GP
7349- (id) title { return UCLocalize("SETTINGS"); }
7350
7351- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7352 if ((self = [super init])) {
f159ecd4
JF
7353 database_ = database;
7354 name_ = [package retain];
dbe0f181 7355
9ae52960
GP
7356 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7357
31a8e05a
GP
7358 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7359 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7360 [table_ setAllowsSelection:NO];
9ae52960 7361 [[self view] addSubview:table_];
dbe0f181 7362
31a8e05a
GP
7363 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7364 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7365 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
dbe0f181 7366
31a8e05a
GP
7367 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7368 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7369 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
dbe0f181 7370
31a8e05a
GP
7371 subscribedCell_ = [[UITableViewCell alloc] init];
7372 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7373 [subscribedCell_ setAccessoryView:subscribedSwitch_];
dbe0f181 7374
31a8e05a
GP
7375 ignoredCell_ = [[UITableViewCell alloc] init];
7376 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7377 [ignoredCell_ setAccessoryView:ignoredSwitch_];
dbe0f181 7378
f159ecd4 7379 [table_ setDataSource:self];
31a8e05a 7380 [table_ setDelegate:self];
f159ecd4
JF
7381 [self reloadData];
7382 } return self;
7383}
dbe0f181 7384
f159ecd4
JF
7385- (void) reloadData {
7386 if (package_ != nil)
7387 [package_ autorelease];
7388 package_ = [database_ packageWithName:name_];
7389 if (package_ != nil) {
7390 [package_ retain];
31a8e05a
GP
7391 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7392 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
dbe0f181 7393 }
f159ecd4
JF
7394
7395 [table_ reloadData];
dbe0f181
JF
7396}
7397
dbe0f181 7398@end
017b2b71 7399/* }}} */
dbe0f181 7400
f441e717
GP
7401/* Signature Controller {{{ */
7402@interface SignatureController : CYBrowserController {
dbe0f181
JF
7403 _transient Database *database_;
7404 NSString *package_;
7405}
7406
9ae52960 7407- (id) initWithDatabase:(Database *)database package:(NSString *)package;
dbe0f181
JF
7408
7409@end
7410
f441e717 7411@implementation SignatureController
dbe0f181
JF
7412
7413- (void) dealloc {
7414 [package_ release];
7415 [super dealloc];
7416}
7417
7418- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7419 // XXX: dude!
7420 [super webView:sender didClearWindowObject:window forFrame:frame];
7421}
7422
9ae52960
GP
7423- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7424 if ((self = [super init]) != nil) {
dbe0f181
JF
7425 database_ = database;
7426 package_ = [package retain];
7427 [self reloadData];
7428 } return self;
7429}
7430
7431- (void) reloadData {
7432 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7433}
7434
c1edf105
GP
7435@end
7436/* }}} */
7437/* Role Controller {{{ */
1e4922b8
JF
7438@interface RoleController : CYViewController <
7439 UITableViewDataSource,
7440 UITableViewDelegate
7441> {
c1edf105
GP
7442 _transient Database *database_;
7443 id roledelegate_;
7444 UITableView *table_;
7445 UISegmentedControl *segment_;
7446 UIView *container_;
7447}
1e4922b8
JF
7448
7449- (void) showDoneButton;
7450- (void) resizeSegmentedControl;
7451
c1edf105
GP
7452@end
7453
7454@implementation RoleController
7455- (void) dealloc {
7456 [table_ release];
7457 [segment_ release];
7458 [container_ release];
f99f86e2 7459
c1edf105
GP
7460 [super dealloc];
7461}
7462
7463- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7464 if ((self = [super init])) {
7465 database_ = database;
7466 roledelegate_ = delegate;
f99f86e2 7467
c1edf105 7468 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
f99f86e2 7469
c1edf105 7470 NSArray *items = [NSArray arrayWithObjects:
f99f86e2 7471 UCLocalize("USER"),
c1edf105
GP
7472 UCLocalize("HACKER"),
7473 UCLocalize("DEVELOPER"),
7474 nil];
7475 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7476 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7477 [container_ addSubview:segment_];
f99f86e2 7478
c1edf105
GP
7479 int index = -1;
7480 if ([Role_ isEqualToString:@"User"]) index = 0;
7481 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7482 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7483 if (index != -1) {
7484 [segment_ setSelectedSegmentIndex:index];
7485 [self showDoneButton];
7486 }
f99f86e2 7487
c1edf105 7488 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
62d55799 7489 [self resizeSegmentedControl];
f99f86e2 7490
c1edf105
GP
7491 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7492 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7493 [table_ setDelegate:self];
7494 [table_ setDataSource:self];
7495 [[self view] addSubview:table_];
7496 [table_ reloadData];
7497 } return self;
7498}
7499
62d55799
GP
7500- (void) resizeSegmentedControl {
7501 CGFloat width = [[self view] frame].size.width;
7502 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7503}
7504
ca45de84
GP
7505- (void) viewWillAppear:(BOOL)animated {
7506 [super viewWillAppear:animated];
f99f86e2 7507
62d55799
GP
7508 [self resizeSegmentedControl];
7509}
7510
7511- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7512 [self resizeSegmentedControl];
7513}
7514
7515- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7516 [self resizeSegmentedControl];
ca45de84
GP
7517}
7518
c1edf105 7519- (void) save {
90e9a238 7520 NSString *role(nil);
f99f86e2 7521
c1edf105 7522 switch ([segment_ selectedSegmentIndex]) {
fabc4a01
GP
7523 case 0: role = @"User"; break;
7524 case 1: role = @"Hacker"; break;
7525 case 2: role = @"Developer"; break;
c1edf105
GP
7526
7527 _nodefault
7528 }
7529
fabc4a01 7530 if (![role isEqualToString:Role_]) {
90e9a238 7531 bool rolling(Role_ == nil);
fabc4a01 7532 Role_ = role;
f99f86e2 7533
fabc4a01
GP
7534 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7535 Role_, @"Role",
7536 nil];
c1edf105 7537
fabc4a01 7538 [Metadata_ setObject:Settings_ forKey:@"Settings"];
c1edf105 7539
fabc4a01 7540 Changed_ = true;
f99f86e2 7541
90e9a238
JF
7542 if (rolling)
7543 [roledelegate_ loadData];
7544 else
7545 [roledelegate_ updateData];
fabc4a01 7546 }
c1edf105
GP
7547}
7548
7549- (void) segmentChanged:(UISegmentedControl *)control {
7550 [self showDoneButton];
7551}
7552
7553- (void) doneButtonClicked {
7554 [self save];
7555 [[self navigationController] dismissModalViewControllerAnimated:YES];
7556}
7557
7558- (void) showDoneButton {
7559 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7560 initWithTitle:UCLocalize("DONE")
7561 style:UIBarButtonItemStyleDone
7562 target:self
7563 action:@selector(doneButtonClicked)
7564 ];
7565 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7566 [rightItem release];
7567}
7568
7569- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
62d55799
GP
7570 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7571 return 6;
c1edf105
GP
7572}
7573
7574- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7575 return 0; // :(
7576}
7577
7578- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7579 return nil; // This method is required by the protocol.
7580}
7581
7582- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
f99f86e2 7583 if (section == 1)
c1edf105 7584 return UCLocalize("ROLE_EX");
f99f86e2 7585 if (section == 4)
c1edf105
GP
7586 return [NSString stringWithFormat:
7587 @"%@: %@\n%@: %@\n%@: %@",
f99f86e2
JF
7588 UCLocalize("USER"), UCLocalize("USER_EX"),
7589 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
c1edf105
GP
7590 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7591 ];
7592 else return nil;
7593}
7594
7595- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7596 if (section == 3) return 44.0f;
7597 else return 0;
7598}
7599
7600- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7601 if (section == 3) return container_;
7602 else return nil;
7603}
7604
dbe0f181 7605@end
f159ecd4 7606/* }}} */
dbe0f181 7607
e7a88a8c
GP
7608/* Cydia Container {{{ */
7609@interface CYContainer : UIViewController <ProgressDelegate> {
7610 _transient Database *database_;
7611 RefreshBar *refreshbar_;
7612
7613 bool dropped_;
7614 bool updating_;
7615 id updatedelegate_;
1e4922b8 7616 UITabBarController *root_;
e7a88a8c
GP
7617}
7618
1e4922b8
JF
7619- (void) setTabBarController:(UITabBarController *)controller;
7620
7621- (void) dropBar:(BOOL)animated;
7622- (void) beginUpdate;
7623- (void) raiseBar:(BOOL)animated;
7624
e7a88a8c
GP
7625@end
7626
7627@implementation CYContainer
7628
15b41c77
GP
7629// NOTE: UIWindow only sends the top controller these messages,
7630// So we have to forward them on.
7631
7632- (void) viewDidAppear:(BOOL)animated {
7633 [super viewDidAppear:animated];
7634 [root_ viewDidAppear:animated];
7635}
7636
7637- (void) viewWillAppear:(BOOL)animated {
7638 [super viewWillAppear:animated];
7639 [root_ viewWillAppear:animated];
7640}
7641
7642- (void) viewDidDisappear:(BOOL)animated {
7643 [super viewDidDisappear:animated];
7644 [root_ viewDidDisappear:animated];
7645}
7646
7647- (void) viewWillDisappear:(BOOL)animated {
7648 [super viewWillDisappear:animated];
7649 [root_ viewWillDisappear:animated];
7650}
7651
e7a88a8c
GP
7652- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7653 return YES; /* XXX: return YES; */
7654}
7655
1e4922b8 7656- (void) setTabBarController:(UITabBarController *)controller {
e7a88a8c
GP
7657 root_ = controller;
7658 [[self view] addSubview:[root_ view]];
7659}
7660
7661- (void) setUpdate:(NSDate *)date {
7662 [self beginUpdate];
7663}
7664
7665- (void) beginUpdate {
7666 [self dropBar:YES];
7667 [refreshbar_ start];
f99f86e2 7668
e7a88a8c 7669 updating_ = true;
f99f86e2 7670
e7a88a8c
GP
7671 [NSThread
7672 detachNewThreadSelector:@selector(performUpdate)
7673 toTarget:self
7674 withObject:nil
7675 ];
7676}
7677
7678- (void) performUpdate { _pooled
7679 Status status;
7680 status.setDelegate(self);
7681 [database_ updateWithStatus:status];
7682
7683 [self
7684 performSelectorOnMainThread:@selector(completeUpdate)
7685 withObject:nil
7686 waitUntilDone:NO
7687 ];
7688}
7689
7690- (void) completeUpdate {
7691 updating_ = false;
f99f86e2 7692
e7a88a8c
GP
7693 [self raiseBar:YES];
7694 [refreshbar_ stop];
7695 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7696}
7697
7698- (void) cancelUpdate {
7699 [refreshbar_ cancel];
7700 [self completeUpdate];
7701}
7702
7703- (void) cancelPressed {
7704 [self cancelUpdate];
7705}
7706
7707- (BOOL) updating {
7708 return updating_;
7709}
7710
7711- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7712 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7713}
7714
7715- (void) startProgress {
7716}
7717
7718- (void) setProgressTitle:(NSString *)title {
7719 [self
7720 performSelectorOnMainThread:@selector(_setProgressTitle:)
7721 withObject:title
7722 waitUntilDone:YES
7723 ];
7724}
7725
7726- (bool) isCancelling:(size_t)received {
7727 return !updating_;
7728}
7729
7730- (void) setProgressPercent:(float)percent {
7731 [self
7732 performSelectorOnMainThread:@selector(_setProgressPercent:)
7733 withObject:[NSNumber numberWithFloat:percent]
7734 waitUntilDone:YES
7735 ];
7736}
7737
7738- (void) addProgressOutput:(NSString *)output {
7739 [self
7740 performSelectorOnMainThread:@selector(_addProgressOutput:)
7741 withObject:output
7742 waitUntilDone:YES
7743 ];
7744}
7745
7746- (void) _setProgressTitle:(NSString *)title {
7747 [refreshbar_ setPrompt:title];
7748}
7749
7750- (void) _setProgressPercent:(NSNumber *)percent {
7751 [refreshbar_ setProgress:[percent floatValue]];
7752}
7753
7754- (void) _addProgressOutput:(NSString *)output {
7755}
7756
7757- (void) setUpdateDelegate:(id)delegate {
7758 updatedelegate_ = delegate;
7759}
7760
7761- (void) dropBar:(BOOL)animated {
7762 if (dropped_) return;
7763 dropped_ = true;
7764
7765 [[self view] addSubview:refreshbar_];
7766
7767 if (animated) [UIView beginAnimations:nil context:NULL];
7768 CGRect barframe = [refreshbar_ frame];
7769 CGRect viewframe = [[root_ view] frame];
ba6cbb36
GP
7770 viewframe.origin.y += barframe.size.height + 20.0f;
7771 viewframe.size.height -= barframe.size.height + 20.0f;
e7a88a8c
GP
7772 [[root_ view] setFrame:viewframe];
7773 if (animated) [UIView commitAnimations];
7774
15b41c77
GP
7775 // Ensure bar has the proper width for our view, it might have changed
7776 barframe.size.width = viewframe.size.width;
7777 [refreshbar_ setFrame:barframe];
7778
e7a88a8c
GP
7779 // XXX: fix Apple's layout bug
7780 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7781}
7782
7783- (void) raiseBar:(BOOL)animated {
7784 if (!dropped_) return;
7785 dropped_ = false;
7786
7787 [refreshbar_ removeFromSuperview];
7788
7789 if (animated) [UIView beginAnimations:nil context:NULL];
7790 CGRect barframe = [refreshbar_ frame];
7791 CGRect viewframe = [[root_ view] frame];
ba6cbb36
GP
7792 viewframe.origin.y -= barframe.size.height + 20.0f;
7793 viewframe.size.height += barframe.size.height + 20.0f;
e7a88a8c
GP
7794 [[root_ view] setFrame:viewframe];
7795 if (animated) [UIView commitAnimations];
7796
7797 // XXX: fix Apple's layout bug
7798 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7799}
7800
62d55799 7801- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
d6011e10
RP
7802 // XXX: fix Apple's layout bug
7803 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7804}
7805
15b41c77 7806- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
e7a88a8c
GP
7807 if (dropped_) {
7808 [self raiseBar:NO];
7809 [self dropBar:NO];
7810 }
f99f86e2 7811
e7a88a8c
GP
7812 // XXX: fix Apple's layout bug
7813 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7814}
7815
7816- (void) dealloc {
7817 [refreshbar_ release];
7818 [super dealloc];
7819}
7820
7821- (id) initWithDatabase: (Database *)database {
7822 if ((self = [super init]) != nil) {
7823 database_ = database;
7824
15b41c77
GP
7825 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7826
7827 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
e7a88a8c
GP
7828 } return self;
7829}
7830
7831@end
7832/* }}} */
7833
9ae52960
GP
7834typedef enum {
7835 kCydiaTag = 0,
7836 kSectionsTag = 1,
7837 kChangesTag = 2,
7838 kManageTag = 3,
7839 kInstalledTag = 4,
7840 kSourcesTag = 5,
7841 kSearchTag = 6
7842} CYTabTag;
d3bef7bc 7843
4941f41d 7844@interface Cydia : UIApplication <
f441e717
GP
7845 ConfirmationControllerDelegate,
7846 ProgressControllerDelegate,
b0d03ade 7847 CydiaDelegate
4941f41d 7848> {
a75f53e7 7849 UIWindow *window_;
e7a88a8c 7850 CYContainer *container_;
e057ec05 7851
9ae52960 7852 id tabbar_;
3319715b 7853
9e07091a 7854 NSMutableArray *essential_;
3319715b 7855 NSMutableArray *broken_;
a75f53e7
JF
7856
7857 Database *database_;
a75f53e7 7858
84848968 7859 int tag_;
686e302f
JF
7860
7861 UIKeyboard *keyboard_;
b26eb97d 7862 UIProgressHUD *hud_;
e25e221f 7863
f441e717
GP
7864 SectionsController *sections_;
7865 ChangesController *changes_;
7866 ManageController *manage_;
7867 SearchController *search_;
9ae52960 7868 SourceTable *sources_;
f441e717 7869 InstalledController *installed_;
9ae52960 7870 id queueDelegate_;
6932575e 7871
4825688a 7872#if RecyclePackageViews
b452841e 7873 NSMutableArray *details_;
4825688a 7874#endif
d56a0c9b 7875
e7a88a8c 7876 bool loaded_;
a75f53e7
JF
7877}
7878
1e4922b8
JF
7879- (UCViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7880- (void) setPage:(UCViewController *)page;
90e9a238 7881- (void) loadData;
6981ccdf 7882
a75f53e7
JF
7883@end
7884
6981ccdf 7885static _finline void _setHomePage(Cydia *self) {
f441e717 7886 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
6981ccdf
JF
7887}
7888
a75f53e7
JF
7889@implementation Cydia
7890
9ae52960 7891- (void) beginUpdate {
e7a88a8c 7892 [container_ beginUpdate];
9ae52960
GP
7893}
7894
7895- (BOOL) updating {
e7a88a8c 7896 return [container_ updating];
9ae52960
GP
7897}
7898
5ec44e34
JF
7899- (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7900 return window_;
7901}
7902
3319715b
JF
7903- (void) _loaded {
7904 if ([broken_ count] != 0) {
7905 int count = [broken_ count];
7906
7d3e75f4 7907 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 7908 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9ae52960
GP
7909 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7910 delegate:self
7911 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7912 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
3319715b
JF
7913 ] autorelease];
7914
7d3e75f4
GP
7915 [alert setContext:@"fixhalf"];
7916 [alert show];
3319715b
JF
7917 } else if (!Ignored_ && [essential_ count] != 0) {
7918 int count = [essential_ count];
7919
7d3e75f4 7920 UIAlertView *alert = [[[UIAlertView alloc]
61b13cae 7921 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9ae52960
GP
7922 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7923 delegate:self
7924 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7d3e75f4 7925 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
3319715b
JF
7926 ] autorelease];
7927
7d3e75f4
GP
7928 [alert setContext:@"upgrade"];
7929 [alert show];
3319715b
JF
7930 }
7931}
7932
419a9efd
JF
7933- (void) _saveConfig {
7934 if (Changed_) {
7935 _trace();
7936 NSString *error(nil);
7937 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7938 _trace();
7939 NSError *error(nil);
7940 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7941 NSLog(@"failure to save metadata data: %@", error);
7942 _trace();
7943 } else {
7944 NSLog(@"failure to serialize metadata: %@", error);
7945 return;
7946 }
7947
7948 Changed_ = false;
7949 }
7950}
7951
7952- (void) _updateData {
7953 [self _saveConfig];
7954
7955 /* XXX: this is just stupid */
84848968 7956 if (tag_ != 1 && sections_ != nil)
419a9efd 7957 [sections_ reloadData];
84848968 7958 if (tag_ != 2 && changes_ != nil)
419a9efd 7959 [changes_ reloadData];
84848968 7960 if (tag_ != 4 && search_ != nil)
419a9efd
JF
7961 [search_ reloadData];
7962
1e4922b8 7963 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
9ae52960
GP
7964}
7965
7966- (int)indexOfTabWithTag:(int)tag {
7967 int i = 0;
7968 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7969 if ([[controller tabBarItem] tag] == tag) return i;
7970 i += 1;
7971 }
f99f86e2 7972
9ae52960 7973 return -1;
419a9efd
JF
7974}
7975
d56a0c9b 7976- (void) _refreshIfPossible {
e7a88a8c 7977 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
f99f86e2 7978
e7a88a8c
GP
7979 Reachability* reachability = [Reachability reachabilityWithHostName:@"cydia.saurik.com"];
7980 NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
f99f86e2 7981
e7a88a8c 7982 if (loaded_ || ManualRefresh || remoteHostStatus == NotReachable) loaded:
d56a0c9b
GP
7983 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
7984 else {
7985 loaded_ = true;
7986
7987 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7988
7989 if (update != nil) {
7990 NSTimeInterval interval([update timeIntervalSinceNow]);
7991 if (interval <= 0 && interval > -(15*60))
7992 goto loaded;
7993 }
7994
e7a88a8c 7995 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
d56a0c9b
GP
7996 }
7997
e7a88a8c 7998 [pool release];
d56a0c9b
GP
7999}
8000
8001- (void) refreshIfPossible {
e7a88a8c 8002 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
d56a0c9b
GP
8003}
8004
e057ec05 8005- (void) _reloadData {
7398a389 8006 UIProgressHUD *hud([self addProgressHUD]);
d56a0c9b 8007 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
a75f53e7 8008
7398a389
JF
8009 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8010 _trace();
8011
8012 [self removeProgressHUD:hud];
d12c6e70 8013
e057ec05 8014 size_t changes(0);
3319715b 8015
9e07091a 8016 [essential_ removeAllObjects];
3319715b 8017 [broken_ removeAllObjects];
686e302f 8018
6981ccdf 8019 NSArray *packages([database_ packages]);
f464053e 8020 for (Package *package in packages) {
3319715b
JF
8021 if ([package half])
8022 [broken_ addObject:package];
238b07ce 8023 if ([package upgradableAndEssential:NO]) {
9e07091a
JF
8024 if ([package essential])
8025 [essential_ addObject:package];
e057ec05 8026 ++changes;
9e07091a 8027 }
e057ec05 8028 }
686e302f 8029
e057ec05
JF
8030 if (changes != 0) {
8031 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9ae52960
GP
8032 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8033 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
f99f86e2 8034
6932575e
JF
8035 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8036 [self setApplicationBadge:badge];
8037 else
8038 [self setApplicationBadgeString:badge];
d12c6e70 8039 } else {
9ae52960
GP
8040 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8041 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
f99f86e2 8042
6932575e
JF
8043 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8044 [self removeApplicationBadge];
8045 else // XXX: maybe use setApplicationBadgeString also?
8046 [self setApplicationIconBadgeNumber:0];
d12c6e70 8047 }
686e302f 8048
419a9efd 8049 [self _updateData];
fa7bb92f 8050
e7a88a8c 8051 [self refreshIfPossible];
fa7bb92f
JF
8052}
8053
faf4eb4f 8054- (void) updateData {
419a9efd
JF
8055 [database_ setVisible];
8056 [self _updateData];
686e302f
JF
8057}
8058
faf4eb4f
JF
8059- (void) update_ {
8060 [database_ update];
8061}
8062
8063- (void) syncData {
6981ccdf 8064 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
faf4eb4f
JF
8065 _assert(file != NULL);
8066
6981ccdf
JF
8067 for (NSString *key in [Sources_ allKeys]) {
8068 NSDictionary *source([Sources_ objectForKey:key]);
faf4eb4f
JF
8069
8070 fprintf(file, "%s %s %s\n",
8071 [[source objectForKey:@"Type"] UTF8String],
8072 [[source objectForKey:@"URI"] UTF8String],
8073 [[source objectForKey:@"Distribution"] UTF8String]
8074 );
8075 }
8076
8077 fclose(file);
8078
8079 [self _saveConfig];
8080
f441e717 8081 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
15b41c77 8082 UINavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9ae52960 8083 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
e7a88a8c 8084 [container_ presentModalViewController:navigation animated:YES];
9ae52960
GP
8085
8086 [progress
faf4eb4f
JF
8087 detachNewThreadSelector:@selector(update_)
8088 toTarget:self
8089 withObject:nil
61b13cae 8090 title:UCLocalize("UPDATING_SOURCES")
faf4eb4f
JF
8091 ];
8092}
8093
e057ec05
JF
8094- (void) reloadData {
8095 @synchronized (self) {
9ae52960 8096 [self _reloadData];
e057ec05 8097 }
686e302f
JF
8098}
8099
8100- (void) resolve {
8101 pkgProblemResolver *resolver = [database_ resolver];
8102
8103 resolver->InstallProtect();
8104 if (!resolver->Resolve(true))
8105 _error->Discard();
4941f41d
JF
8106}
8107
04700693 8108- (CGRect) popUpBounds {
9ae52960 8109 return [[tabbar_ view] bounds];
04700693
JF
8110}
8111
6981ccdf
JF
8112- (bool) perform {
8113 if (![database_ prepare])
8114 return false;
242bcc6d 8115
f441e717 8116 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
f464053e 8117 [page setDelegate:self];
15b41c77 8118 id confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
9ae52960 8119 [confirm_ setDelegate:self];
242bcc6d 8120
9ae52960 8121 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
e7a88a8c 8122 [container_ presentModalViewController:confirm_ animated:YES];
6981ccdf
JF
8123
8124 return true;
2d28b35a
JF
8125}
8126
3ff1504e
JF
8127- (void) queue {
8128 @synchronized (self) {
8129 [self perform];
8130 }
8131}
8132
8133- (void) clearPackage:(Package *)package {
8134 @synchronized (self) {
8135 [package clear];
8136 [self resolve];
8137 [self perform];
8138 }
8139}
8140
daf7f6e2
JF
8141- (void) installPackages:(NSArray *)packages {
8142 @synchronized (self) {
8143 for (Package *package in packages)
8144 [package install];
8145 [self resolve];
8146 [self perform];
8147 }
8148}
8149
e057ec05
JF
8150- (void) installPackage:(Package *)package {
8151 @synchronized (self) {
8152 [package install];
8153 [self resolve];
8154 [self perform];
8155 }
8156}
8157
8158- (void) removePackage:(Package *)package {
8159 @synchronized (self) {
8160 [package remove];
8161 [self resolve];
8162 [self perform];
8163 }
8164}
8165
8166- (void) distUpgrade {
8167 @synchronized (self) {
6981ccdf
JF
8168 if (![database_ upgrade])
8169 return;
e057ec05
JF
8170 [self perform];
8171 }
686e302f
JF
8172}
8173
3ff1504e 8174- (void) complete {
e057ec05 8175 @synchronized (self) {
e057ec05
JF
8176 [self _reloadData];
8177 }
2d28b35a
JF
8178}
8179
9ae52960 8180- (void) confirmWithNavigationController:(UINavigationController *)navigation {
f441e717 8181 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
f99f86e2 8182
9ae52960
GP
8183 if (navigation != nil) {
8184 [navigation pushViewController:progress animated:YES];
8185 } else {
15b41c77 8186 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9ae52960 8187 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
e7a88a8c 8188 [container_ presentModalViewController:navigation animated:YES];
9ae52960 8189 }
f99f86e2 8190
9ae52960 8191 [progress
4941f41d
JF
8192 detachNewThreadSelector:@selector(perform)
8193 toTarget:database_
8194 withObject:nil
61b13cae 8195 title:UCLocalize("RUNNING")
4941f41d
JF
8196 ];
8197}
8198
ba6cbb36 8199- (void) progressControllerIsComplete:(ProgressController *)progress {
3ff1504e 8200 [self complete];
a75f53e7
JF
8201}
8202
1e4922b8 8203- (void) setPage:(UCViewController *)page {
e057ec05 8204 [page setDelegate:self];
9ae52960 8205
1e4922b8 8206 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
9ae52960 8207 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
1e4922b8 8208 for (CYNavigationController *page in [tabbar_ viewControllers]) {
9ae52960
GP
8209 if (page != navController) [page setViewControllers:nil];
8210 }
a75f53e7
JF
8211}
8212
1e4922b8 8213- (UCViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
9ae52960 8214 CYBrowserController *browser = [[[_class alloc] init] autorelease];
faf4eb4f 8215 [browser loadURL:url];
e057ec05 8216 return browser;
4941f41d
JF
8217}
8218
f441e717 8219- (SectionsController *) sectionsController {
6932575e 8220 if (sections_ == nil)
f441e717 8221 sections_ = [[SectionsController alloc] initWithDatabase:database_];
6932575e
JF
8222 return sections_;
8223}
8224
f441e717 8225- (ChangesController *) changesController {
5ec44e34 8226 if (changes_ == nil)
f441e717 8227 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
5ec44e34
JF
8228 return changes_;
8229}
8230
f441e717 8231- (ManageController *) manageController {
9ae52960 8232 if (manage_ == nil) {
f441e717 8233 manage_ = (ManageController *) [[self
5ec44e34 8234 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
f441e717 8235 withClass:[ManageController class]
5ec44e34 8236 ] retain];
9ae52960
GP
8237 if (!IsWildcat_) queueDelegate_ = manage_;
8238 }
5ec44e34
JF
8239 return manage_;
8240}
8241
f441e717 8242- (SearchController *) searchController {
5ec44e34 8243 if (search_ == nil)
f441e717 8244 search_ = [[SearchController alloc] initWithDatabase:database_];
5ec44e34
JF
8245 return search_;
8246}
8247
f441e717 8248- (SourceTable *) sourcesController {
9ae52960
GP
8249 if (sources_ == nil)
8250 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8251 return sources_;
8252}
8253
f441e717 8254- (InstalledController *) installedController {
9ae52960 8255 if (installed_ == nil) {
f441e717 8256 installed_ = [[InstalledController alloc] initWithDatabase:database_];
9ae52960
GP
8257 if (IsWildcat_) queueDelegate_ = installed_;
8258 }
8259 return installed_;
8260}
8261
f99f86e2 8262- (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
9ae52960 8263 int tag = [[viewController tabBarItem] tag];
97959670 8264 if (tag == tag_) {
1e4922b8 8265 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
97959670 8266 return;
9ae52960 8267 } else if (tag_ == 1) {
f441e717 8268 [[self sectionsController] resetView];
9ae52960 8269 }
a75f53e7 8270
7e986211 8271 switch (tag) {
9ae52960 8272 case kCydiaTag: _setHomePage(self); break;
e057ec05 8273
f441e717
GP
8274 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8275 case kChangesTag: [self setPage:[self changesController]]; break;
8276 case kManageTag: [self setPage:[self manageController]]; break;
8277 case kInstalledTag: [self setPage:[self installedController]]; break;
8278 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8279 case kSearchTag: [self setPage:[self searchController]]; break;
e057ec05 8280
6981ccdf 8281 _nodefault
a75f53e7
JF
8282 }
8283
7e986211 8284 tag_ = tag;
7e986211
JF
8285}
8286
c1edf105
GP
8287- (void) showSettings {
8288 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
e9a716a7 8289 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
ca45de84 8290 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
c1edf105 8291 [container_ presentModalViewController:nav animated:YES];
faf4eb4f
JF
8292}
8293
f441e717 8294- (void) setPackageController:(PackageController *)view {
b452841e
JF
8295 WebThreadLock();
8296 [view setPackage:nil];
4825688a 8297#if RecyclePackageViews
b452841e
JF
8298 if ([details_ count] < 3)
8299 [details_ addObject:view];
4825688a 8300#endif
b452841e
JF
8301 WebThreadUnlock();
8302}
8303
f441e717
GP
8304- (PackageController *) _packageController {
8305 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
6932575e
JF
8306}
8307
f441e717 8308- (PackageController *) packageController {
4825688a 8309#if RecyclePackageViews
f441e717 8310 PackageController *view;
b452841e 8311 size_t count([details_ count]);
6932575e 8312
b452841e 8313 if (count == 0) {
f441e717 8314 view = [self _packageController];
b452841e 8315 renew:
f441e717 8316 [details_ addObject:[self _packageController]];
b452841e
JF
8317 } else {
8318 view = [[[details_ lastObject] retain] autorelease];
8319 [details_ removeLastObject];
8320 if (count == 1)
8321 goto renew;
6932575e
JF
8322 }
8323
8324 return view;
4825688a 8325#else
f441e717 8326 return [self _packageController];
4825688a 8327#endif
6932575e
JF
8328}
8329
1ca35d78
GP
8330- (void) cancelAndClear:(bool)clear {
8331 @synchronized (self) {
8332 if (clear) {
9ae52960
GP
8333 /* XXX: clear marks instead of reloading data */
8334 /*pkgCacheFile &cache([database_ cache]);
8335 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8336 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8337 }
8338
8339 [self updateData];
f99f86e2 8340
9ae52960
GP
8341 Queuing_ = false;
8342 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8343 [queueDelegate_ queueStatusDidChange];*/
8344 [self reloadData];
1ca35d78 8345 } else {
9ae52960
GP
8346 Queuing_ = true;
8347
8348 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
1e4922b8 8349 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
f99f86e2 8350
9ae52960 8351 [queueDelegate_ queueStatusDidChange];
3ff1504e 8352 }
1ca35d78 8353 }
7d3e75f4 8354}
faf4eb4f 8355
9ae52960
GP
8356- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8357 NSString *context([alert context]);
f99f86e2 8358
9ae52960
GP
8359 if ([context isEqualToString:@"fixhalf"]) {
8360 if (button == [alert firstOtherButtonIndex]) {
7d3e75f4
GP
8361 @synchronized (self) {
8362 for (Package *broken in broken_) {
8363 [broken remove];
8364
8365 NSString *id = [broken id];
8366 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8367 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8368 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8369 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8370 }
faf4eb4f 8371
7d3e75f4
GP
8372 [self resolve];
8373 [self perform];
8374 }
9ae52960 8375 } else if (button == [alert cancelButtonIndex]) {
7d3e75f4
GP
8376 [broken_ removeAllObjects];
8377 [self _loaded];
faf4eb4f
JF
8378 }
8379
7d3e75f4 8380 [alert dismissWithClickedButtonIndex:-1 animated:YES];
a5dd312c 8381 } else if ([context isEqualToString:@"upgrade"]) {
7d3e75f4
GP
8382 if (button == [alert firstOtherButtonIndex]) {
8383 @synchronized (self) {
8384 for (Package *essential in essential_)
8385 [essential install];
faf4eb4f 8386
7d3e75f4
GP
8387 [self resolve];
8388 [self perform];
8389 }
8390 } else if (button == [alert firstOtherButtonIndex] + 1) {
8391 [self distUpgrade];
8392 } else if (button == [alert cancelButtonIndex]) {
8393 Ignored_ = YES;
faf4eb4f
JF
8394 }
8395
7d3e75f4 8396 [alert dismissWithClickedButtonIndex:-1 animated:YES];
a5dd312c 8397 }
faf4eb4f
JF
8398}
8399
6981ccdf
JF
8400- (void) system:(NSString *)command { _pooled
8401 system([command UTF8String]);
8402}
8403
8404- (void) applicationWillSuspend {
8405 [database_ clean];
8406 [super applicationWillSuspend];
b26eb97d
JF
8407}
8408
8409- (void) applicationSuspend:(__GSEvent *)event {
2b04cd97
GP
8410 // FIXME: This needs to be fixed, but we no longer have a progress_.
8411 // What's the best solution?
9ae52960 8412 if (hud_ == nil)// && ![progress_ isRunning])
b26eb97d 8413 [super applicationSuspend:event];
b26eb97d
JF
8414}
8415
fa7bb92f
JF
8416- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8417 if (hud_ == nil)
8418 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8419}
8420
8421- (void) _setSuspended:(BOOL)value {
8422 if (hud_ == nil)
8423 [super _setSuspended:value];
8424}
8425
faf4eb4f 8426- (UIProgressHUD *) addProgressHUD {
7398a389 8427 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
d3bef7bc
JF
8428 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8429
7398a389 8430 [window_ setUserInteractionEnabled:NO];
faf4eb4f 8431 [hud show:YES];
0efe9812 8432 [[container_ view] addSubview:hud];
faf4eb4f
JF
8433 return hud;
8434}
8435
7398a389
JF
8436- (void) removeProgressHUD:(UIProgressHUD *)hud {
8437 [hud show:NO];
8438 [hud removeFromSuperview];
8439 [window_ setUserInteractionEnabled:YES];
8440}
8441
1e4922b8 8442- (UCViewController *) pageForPackage:(NSString *)name {
cb9c2100 8443 if (Package *package = [database_ packageWithName:name]) {
f441e717 8444 PackageController *view([self packageController]);
cb9c2100
JF
8445 [view setPackage:package];
8446 return view;
8447 } else {
6981ccdf
JF
8448 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8449 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
9ae52960 8450 return [self _pageForURL:url withClass:[CYBrowserController class]];
cb9c2100
JF
8451 }
8452}
8453
1e4922b8 8454- (UCViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
cb9c2100 8455 if (tag != NULL)
84848968 8456 *tag = -1;
cb9c2100 8457
61b13cae
JF
8458 NSString *href([url absoluteString]);
8459 if ([href hasPrefix:@"apptapp://package/"])
8460 return [self pageForPackage:[href substringFromIndex:18]];
8461
2dfc46f7
JF
8462 NSString *scheme([[url scheme] lowercaseString]);
8463 if (![scheme isEqualToString:@"cydia"])
8464 return nil;
8465 NSString *path([url absoluteString]);
8466 if ([path length] < 8)
8467 return nil;
8468 path = [path substringFromIndex:8];
8469 if (![path hasPrefix:@"/"])
8470 path = [@"/" stringByAppendingString:path];
8471
8472 if ([path isEqualToString:@"/add-source"])
f441e717 8473 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
2dfc46f7 8474 else if ([path isEqualToString:@"/storage"])
9ae52960 8475 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
2dfc46f7 8476 else if ([path isEqualToString:@"/sources"])
9ae52960 8477 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
2dfc46f7 8478 else if ([path isEqualToString:@"/packages"])
f441e717 8479 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
2dfc46f7 8480 else if ([path hasPrefix:@"/url/"])
9ae52960 8481 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
2dfc46f7
JF
8482 else if ([path hasPrefix:@"/launch/"])
8483 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8484 else if ([path hasPrefix:@"/package-settings/"])
f441e717 8485 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
2dfc46f7 8486 else if ([path hasPrefix:@"/package-signature/"])
f441e717 8487 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
2dfc46f7
JF
8488 else if ([path hasPrefix:@"/package/"])
8489 return [self pageForPackage:[path substringFromIndex:9]];
8490 else if ([path hasPrefix:@"/files/"]) {
8491 NSString *name = [path substringFromIndex:7];
cb9c2100
JF
8492
8493 if (Package *package = [database_ packageWithName:name]) {
9ae52960 8494 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
cb9c2100
JF
8495 [files setPackage:package];
8496 return files;
8497 }
8498 }
8499
8500 return nil;
8501}
8502
8503- (void) applicationOpenURL:(NSURL *)url {
8504 [super applicationOpenURL:url];
8505 int tag;
1e4922b8 8506 if (UCViewController *page = [self pageForURL:url hasTag:&tag]) {
cb9c2100 8507 [self setPage:page];
cb9c2100 8508 tag_ = tag;
9ae52960 8509 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
cb9c2100
JF
8510 }
8511}
8512
f99f86e2 8513- (void) applicationWillResignActive:(UIApplication *)application {
57e5156d
GP
8514 // Stop refreshing if you get a phone call or lock the device.
8515 if ([container_ updating]) [container_ cancelUpdate];
f99f86e2 8516
0a6531c7
GP
8517 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8518 [super applicationWillResignActive:application];
57e5156d
GP
8519}
8520
b26eb97d 8521- (void) applicationDidFinishLaunching:(id)unused {
9ae52960 8522 [CYBrowserController _initialize];
4825688a 8523
017b2b71
JF
8524 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8525
5e563e79
JF
8526 Font12_ = [[UIFont systemFontOfSize:12] retain];
8527 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8528 Font14_ = [[UIFont systemFontOfSize:14] retain];
8529 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8530 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8531
84848968 8532 tag_ = 0;
b26eb97d
JF
8533
8534 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8535 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8536
d3bef7bc
JF
8537 UIScreen *screen([UIScreen mainScreen]);
8538
8539 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
5e563e79
JF
8540 [window_ orderFront:self];
8541 [window_ makeKey:self];
cb9c2100 8542 [window_ setHidden:NO];
d3bef7bc 8543
dbe0f181 8544 database_ = [Database sharedInstance];
017b2b71 8545
fa7bb92f 8546 if (
b26eb97d 8547 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
b26eb97d 8548 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
017b2b71
JF
8549 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8550 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
fa7bb92f 8551 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
bd8e54e1 8552 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
fa7bb92f 8553 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
017b2b71
JF
8554 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8555 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8556 false
b26eb97d 8557 ) {
03a2893d
JF
8558 [self setIdleTimerDisabled:YES];
8559
6981ccdf 8560 hud_ = [self addProgressHUD];
9ae52960 8561 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
b26eb97d
JF
8562 [self setStatusBarShowsProgress:YES];
8563
4eca9136 8564 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
6981ccdf
JF
8565
8566 [self setStatusBarShowsProgress:NO];
8567 [self removeProgressHUD:hud_];
8568 hud_ = nil;
8569
8570 if (ExecFork() == 0) {
8571 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8572 perror("launchctl stop");
8573 }
8574
8575 return;
8576 }
8577
6981ccdf 8578 _trace();
6981ccdf 8579
b36d03d7 8580 NSMutableArray *items([NSMutableArray arrayWithObjects:
9ae52960
GP
8581 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8582 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8583 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8584 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
b36d03d7 8585 nil]);
f99f86e2 8586
9ae52960
GP
8587 if (IsWildcat_) {
8588 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8589 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8590 } else {
8591 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8592 }
f99f86e2 8593
b36d03d7
JF
8594 NSMutableArray *controllers([NSMutableArray array]);
8595
8596 for (UITabBarItem *item in items) {
8597 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8598 [controller setTabBarItem:item];
8599 [controllers addObject:controller];
8600 }
e7a88a8c 8601
9ae52960 8602 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9ae52960
GP
8603 [tabbar_ setViewControllers:controllers];
8604 [tabbar_ setDelegate:self];
8605 [tabbar_ setSelectedIndex:0];
e7a88a8c
GP
8606
8607 container_ = [[CYContainer alloc] initWithDatabase:database_];
e7a88a8c 8608 [container_ setUpdateDelegate:self];
1e4922b8 8609 [container_ setTabBarController:tabbar_];
e7a88a8c 8610 [window_ addSubview:[container_ view]];
6981ccdf 8611
90e9a238
JF
8612 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8613}
8614
8615- (void) loadData {
8616 if (Role_ == nil) {
8617 [self showSettings];
8618 return;
8619 }
8620
6981ccdf 8621 [UIKeyboard initImplementationNow];
6981ccdf
JF
8622
8623 [self reloadData];
8624
6981ccdf
JF
8625#if RecyclePackageViews
8626 details_ = [[NSMutableArray alloc] initWithCapacity:4];
f441e717
GP
8627 [details_ addObject:[self _packageController]];
8628 [details_ addObject:[self _packageController]];
6981ccdf
JF
8629#endif
8630
8631 PrintTimes();
8632
8633 _setHomePage(self);
b26eb97d
JF
8634}
8635
9ae52960 8636- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
1ca35d78 8637 if (item != nil && IsWildcat_) {
9ae52960 8638 [sheet showFromBarButtonItem:item animated:YES];
1ca35d78
GP
8639 } else {
8640 [sheet showInView:window_];
8641 }
e057ec05
JF
8642}
8643
a75f53e7
JF
8644@end
8645
686e302f
JF
8646/*IMP alloc_;
8647id Alloc_(id self, SEL selector) {
8648 id object = alloc_(self, selector);
cb9c2100 8649 lprintf("[%s]A-%p\n", self->isa->name, object);
686e302f
JF
8650 return object;
8651}*/
8652
e057ec05
JF
8653/*IMP dealloc_;
8654id Dealloc_(id self, SEL selector) {
8655 id object = dealloc_(self, selector);
cb9c2100 8656 lprintf("[%s]D-%p\n", self->isa->name, object);
e057ec05
JF
8657 return object;
8658}*/
686e302f 8659
6932575e
JF
8660Class $WebDefaultUIKitDelegate;
8661
c59881cd 8662MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
6932575e
JF
8663 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8664 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
c59881cd 8665 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
6932575e
JF
8666}
8667
aaab313d
RP
8668static NSNumber *shouldPlayKeyboardSounds;
8669
8670Class $UIHardware;
8671
d5f224e7
JF
8672MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8673 switch (sound) {
aaab313d
RP
8674 case 1104: // Keyboard Button Clicked
8675 case 1105: // Keyboard Delete Repeated
d5f224e7
JF
8676 if (shouldPlayKeyboardSounds == nil) {
8677 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8678 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
aaab313d 8679 }
d5f224e7 8680
aaab313d
RP
8681 if (![shouldPlayKeyboardSounds boolValue])
8682 break;
d5f224e7 8683
aaab313d 8684 default:
d5f224e7 8685 _UIHardware$_playSystemSound$(self, _cmd, sound);
aaab313d
RP
8686 }
8687}
8688
f464053e 8689int main(int argc, char *argv[]) { _pooled
7ec29c77 8690 _trace();
6932575e 8691
5ec44e34
JF
8692 if (Class $UIDevice = objc_getClass("UIDevice")) {
8693 UIDevice *device([$UIDevice currentDevice]);
8694 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8695 } else
8696 IsWildcat_ = false;
8697
dd9390c5 8698 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
43b742af 8699
3e3977a2 8700 /* Library Hacks {{{ */
daf7f6e2 8701 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
3e3977a2
JF
8702 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8703
8704 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8705 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8706 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8707 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8708 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8709 }
aaab313d
RP
8710
8711 $UIHardware = objc_getClass("UIHardware");
8712 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8713 if (UIHardware$_playSystemSound$ != NULL) {
8714 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8715 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8716 }
3e3977a2
JF
8717 /* }}} */
8718 /* Set Locale {{{ */
6932575e 8719 Locale_ = CFLocaleCopyCurrent();
bb9edf8b
JF
8720 Languages_ = [NSLocale preferredLanguages];
8721 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
f7ee98cb 8722 //NSLog(@"%@", [Languages_ description]);
85e0f0f0 8723
bb9edf8b
JF
8724 const char *lang;
8725 if (Languages_ == nil || [Languages_ count] == 0)
85e0f0f0 8726 // XXX: consider just setting to C and then falling through?
bb9edf8b 8727 lang = NULL;
85e0f0f0 8728 else {
bb9edf8b 8729 lang = [[Languages_ objectAtIndex:0] UTF8String];
85e0f0f0
JF
8730 setenv("LANG", lang, true);
8731 }
8732
bb9edf8b
JF
8733 //std::setlocale(LC_ALL, lang);
8734 NSLog(@"Setting Language: %s", lang);
3e3977a2 8735 /* }}} */
6932575e 8736
c59881cd 8737 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
6932575e 8738
3e3977a2 8739 /* Parse Arguments {{{ */
64da7a2f
JF
8740 bool substrate(false);
8741
8742 if (argc != 0) {
8743 char **args(argv);
8744 int arge(1);
8745
8746 for (int argi(1); argi != argc; ++argi)
8747 if (strcmp(argv[argi], "--") == 0) {
8748 arge = argi;
8749 argv[argi] = argv[0];
8750 argv += argi;
8751 argc -= argi;
8752 break;
8753 }
8754
8755 for (int argi(1); argi != arge; ++argi)
c59881cd 8756 if (strcmp(args[argi], "--substrate") == 0)
64da7a2f
JF
8757 substrate = true;
8758 else
8759 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8760 }
3e3977a2 8761 /* }}} */
0039464f 8762
3e3977a2
JF
8763 App_ = [[NSBundle mainBundle] bundlePath];
8764 Home_ = NSHomeDirectory();
c59881cd 8765 Advanced_ = YES;
3e3977a2 8766
686e302f
JF
8767 setuid(0);
8768 setgid(0);
8769
8770 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8771 alloc_ = alloc->method_imp;
8772 alloc->method_imp = (IMP) &Alloc_;*/
8773
e057ec05
JF
8774 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8775 dealloc_ = dealloc->method_imp;
8776 dealloc->method_imp = (IMP) &Dealloc_;*/
8777
c59881cd 8778 /* System Information {{{ */
2d28b35a 8779 size_t size;
cb9c2100
JF
8780
8781 int maxproc;
8782 size = sizeof(maxproc);
8783 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8784 perror("sysctlbyname(\"kern.maxproc\", ?)");
8785 else if (maxproc < 64) {
8786 maxproc = 64;
8787 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8788 perror("sysctlbyname(\"kern.maxproc\", #)");
8789 }
8790
017b2b71
JF
8791 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8792 char *osversion = new char[size];
8793 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8794 perror("sysctlbyname(\"kern.osversion\", ?)");
8795 else
8796 System_ = [NSString stringWithUTF8String:osversion];
8797
2d28b35a
JF
8798 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8799 char *machine = new char[size];
cb9c2100
JF
8800 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8801 perror("sysctlbyname(\"hw.machine\", ?)");
8802 else
8803 Machine_ = machine;
2d28b35a 8804
6188cfdd
JF
8805 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8806 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8807 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
017b2b71 8808 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
6188cfdd
JF
8809 CFRelease(serial);
8810 }
8811
8812 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8813 NSData *data((NSData *) ecid);
8814 size_t length([data length]);
8815 uint8_t bytes[length];
8816 [data getBytes:bytes];
8817 char string[length * 2 + 1];
8818 for (size_t i(0); i != length; ++i)
8819 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
017b2b71 8820 ChipID_ = [NSString stringWithUTF8String:string];
6188cfdd
JF
8821 CFRelease(ecid);
8822 }
8823
8824 IOObjectRelease(service);
8825 }
8826 }
8827
2cb68ddf 8828 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
2d28b35a 8829
68c05606
JF
8830 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8831 Build_ = [system objectForKey:@"ProductBuildVersion"];
7b00c562
JF
8832 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8833 Product_ = [info objectForKey:@"SafariProductVersion"];
8834 Safari_ = [info objectForKey:@"CFBundleVersion"];
8835 }
c59881cd 8836 /* }}} */
3e3977a2 8837 /* Load Database {{{ */
7ec29c77 8838 _trace();
6932575e
JF
8839 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8840 _trace();
8841 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
7ec29c77
JF
8842 _trace();
8843
8844 if (Metadata_ == NULL)
6932575e 8845 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
fa7bb92f 8846 else {
ca45de84 8847 Settings_ = [Metadata_ objectForKey:@"Settings"];
faf4eb4f 8848
686e302f 8849 Packages_ = [Metadata_ objectForKey:@"Packages"];
fa7bb92f 8850 Sections_ = [Metadata_ objectForKey:@"Sections"];
faf4eb4f 8851 Sources_ = [Metadata_ objectForKey:@"Sources"];
37455cf8
JF
8852
8853 Token_ = [Metadata_ objectForKey:@"Token"];
faf4eb4f
JF
8854 }
8855
8856 if (Settings_ != nil)
8857 Role_ = [Settings_ objectForKey:@"Role"];
8858
8859 if (Packages_ == nil) {
8860 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8861 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8862 }
8863
8864 if (Sections_ == nil) {
8865 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8866 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8867 }
8868
8869 if (Sources_ == nil) {
8870 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8871 [Metadata_ setObject:Sources_ forKey:@"Sources"];
fa7bb92f 8872 }
3e3977a2 8873 /* }}} */
686e302f 8874
f464053e 8875#if RecycleWebViews
87c76914 8876 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
f464053e 8877#endif
87c76914 8878
c59881cd
JF
8879 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8880
5ec44e34
JF
8881 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8882 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8944281a
JF
8883 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8884 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8885 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8886 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
1eb0c554 8887
5ec44e34
JF
8888 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8889
17f91215 8890 if (access("/tmp/.cydia.fw", F_OK) == 0) {
4825688a 8891 unlink("/tmp/.cydia.fw");
17f91215 8892 goto firmware;
daf7f6e2 8893 } else if (access("/User", F_OK) != 0 || version < 2) {
17f91215 8894 firmware:
7ec29c77 8895 _trace();
6a0db335 8896 system("/usr/libexec/cydia/firmware.sh");
7ec29c77
JF
8897 _trace();
8898 }
63a1e4b8 8899
2cb68ddf
JF
8900 _assert([[NSFileManager defaultManager]
8901 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8902 withIntermediateDirectories:YES
8903 attributes:nil
8904 error:NULL
8905 ]);
8906
3e3977a2
JF
8907 if (access("/tmp/cydia.chk", F_OK) == 0) {
8908 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8909 _assert(errno == ENOENT);
8910 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8911 _assert(errno == ENOENT);
8912 }
8913
6188cfdd 8914 /* APT Initialization {{{ */
bb9edf8b
JF
8915 _assert(pkgInitConfig(*_config));
8916 _assert(pkgInitSystem(*_config, _system));
8917
8918 if (lang != NULL)
8919 _config->Set("APT::Acquire::Translation", lang);
43b742af 8920 _config->Set("Acquire::http::Timeout", 15);
419a9efd 8921 _config->Set("Acquire::http::MaxParallel", 3);
6188cfdd 8922 /* }}} */
3e3977a2 8923 /* Color Choices {{{ */
e057ec05
JF
8924 space_ = CGColorSpaceCreateDeviceRGB();
8925
5e563e79 8926 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
d72d91aa 8927 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
e057ec05 8928 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
87c76914 8929 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
e057ec05 8930 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
faf4eb4f 8931 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
d8d9a65c
JF
8932 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8933 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8934 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
6188cfdd 8935
3ff1504e
JF
8936 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8937 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
3e3977a2 8938 /* }}}*/
3e3977a2 8939 /* UIKit Configuration {{{ */
6932575e
JF
8940 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8941 if ($GSFontSetUseLegacyFontMetrics != NULL)
8942 $GSFontSetUseLegacyFontMetrics(YES);
faf4eb4f 8943
d4f84362
JF
8944 // XXX: I have a feeling this was important
8945 //UIKeyboardDisableAutomaticAppearance();
3e3977a2 8946 /* }}} */
2cb68ddf 8947
6981ccdf
JF
8948 Colon_ = UCLocalize("COLON_DELIMITED");
8949 Error_ = UCLocalize("ERROR");
8950 Warning_ = UCLocalize("WARNING");
8951
7ec29c77 8952 _trace();
bf50bdfa 8953 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
e057ec05
JF
8954
8955 CGColorSpaceRelease(space_);
b27f0a94 8956 CFRelease(Locale_);
e057ec05 8957
e057ec05 8958 return value;
2938b930 8959}