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