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