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