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