]> git.saurik.com Git - cydia.git/blame - MobileCydia.mm
Fixed cancel button sizing; blackified dropbar.
[cydia.git] / MobileCydia.mm
CommitLineData
36bb2ca2 1/* Cydia - iPhone UIKit Front-End for Debian APT
77801ff1 2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
36bb2ca2
JF
3*/
4
bfc87a4d 5/* Modified BSD License {{{ */
36bb2ca2
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*/
bfc87a4d 38/* }}} */
36bb2ca2 39
b0ad8dee
JF
40// XXX: wtf/FastMalloc.h... wtf?
41#define USE_SYSTEM_MALLOC 1
42
dc5812ec 43/* #include Directives {{{ */
c21004b9
JF
44#include "UICaboodle/UCPlatform.h"
45#include "UICaboodle/UCLocalize.h"
807ae6d7 46
ab398adf
JF
47#include <objc/objc.h>
48#include <objc/runtime.h>
49
5f6bff8c 50#include <CoreGraphics/CoreGraphics.h>
5f6bff8c 51#include <Foundation/Foundation.h>
7d2ac47f 52
eef4ccaf
JF
53#if 0
54#define DEPLOYMENT_TARGET_MACOSX 1
55#define CF_BUILDING_CF 1
56#include <CoreFoundation/CFInternal.h>
57#endif
58
677b8415
JF
59#include <CoreFoundation/CFPriv.h>
60#include <CoreFoundation/CFUniChar.h>
61
afb5333a
JF
62#include <SystemConfiguration/SystemConfiguration.h>
63
c21004b9
JF
64#include <UIKit/UIKit.h>
65#include "iPhonePrivate.h"
66
67#include <IOKit/IOKitLib.h>
a9543575 68
f79a4512 69#include <WebCore/WebCoreThread.h>
7e9a36b6 70
677b8415 71#include <algorithm>
808c6eb6 72#include <iomanip>
2367a917 73#include <sstream>
a0be02eb
JF
74#include <string>
75
2367a917
JF
76#include <ext/stdio_filebuf.h>
77
e59669fd
JF
78#undef ABS
79
dc5812ec
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>
77fcccaf 84#include <apt-pkg/clean.h>
dc5812ec 85#include <apt-pkg/configuration.h>
7376b55c 86#include <apt-pkg/debindexfile.h>
3178d79b 87#include <apt-pkg/debmetaindex.h>
dc5812ec
JF
88#include <apt-pkg/error.h>
89#include <apt-pkg/init.h>
dddbc481 90#include <apt-pkg/mmap.h>
dc5812ec 91#include <apt-pkg/pkgrecords.h>
dddbc481 92#include <apt-pkg/sha1.h>
dc5812ec 93#include <apt-pkg/sourcelist.h>
2367a917 94#include <apt-pkg/sptr.h>
affeffc7 95#include <apt-pkg/strutl.h>
f9f6d9e8 96#include <apt-pkg/tagfile.h>
dc5812ec 97
f79a4512
JF
98#include <apr-1/apr_pools.h>
99
87f46a96
JF
100#include <sys/types.h>
101#include <sys/stat.h>
3178d79b 102#include <sys/sysctl.h>
59c011d8
JF
103#include <sys/param.h>
104#include <sys/mount.h>
87f46a96 105
c21004b9 106#include <fcntl.h>
2a8d9add 107#include <notify.h>
dddbc481 108#include <dlfcn.h>
3178d79b 109
b4d89997
JF
110extern "C" {
111#include <mach-o/nlist.h>
112}
113
a0be02eb
JF
114#include <cstdio>
115#include <cstdlib>
116#include <cstring>
b4d89997 117
2367a917 118#include <errno.h>
dc5812ec 119#include <pcre.h>
a9543575 120
94b0b3e5
JF
121#include <Cytore.hpp>
122
c21004b9 123#include "UICaboodle/BrowserView.h"
71cc7be1 124#include "SDURLCache/SDURLCache.h"
fd7853a6 125
c21004b9 126#include "substrate.h"
b5e7eebb
GP
127/* }}} */
128
bfc87a4d 129/* Profiler {{{ */
807ae6d7
JF
130struct timeval _ltv;
131bool _itv;
132
2083b866
JF
133#define _timestamp ({ \
134 struct timeval tv; \
135 gettimeofday(&tv, NULL); \
136 tv.tv_sec * 1000000 + tv.tv_usec; \
137})
138
808c6eb6
JF
139typedef std::vector<class ProfileTime *> TimeList;
140TimeList times_;
141
142class ProfileTime {
143 private:
144 const char *name_;
145 uint64_t total_;
76933519 146 uint64_t count_;
808c6eb6
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;
76933519 158 ++count_;
808c6eb6
JF
159 }
160
161 void Print() {
162 if (total_ != 0)
76933519 163 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
808c6eb6 164 total_ = 0;
76933519 165 count_ = 0;
808c6eb6
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 }
f79a4512 197/* }}} */
affeffc7
JF
198
199#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200
53bed0ff
JF
201#define CYPoolStart() \
202 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
203 do
204#define CYPoolEnd() \
205 while (false); \
206 [_pool release];
207
94b0b3e5
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
04fe1349
JF
217static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
218
bf8476c8
JF
219void NSLogPoint(const char *fix, const CGPoint &point) {
220 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
221}
222
affeffc7
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);
1e7a90f5
JF
225}
226
670a0494
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
ef494bd8
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
bfc87a4d 246/* [NSObject yieldToSelector:(withObject:)] {{{*/
d061f4ba 247@interface NSObject (Cydia)
2fc76a2d
JF
248- (id) yieldToSelector:(SEL)selector withObject:(id)object;
249- (id) yieldToSelector:(SEL)selector;
d061f4ba
JF
250@end
251
252@implementation NSObject (Cydia)
253
254- (void) doNothing {
255}
256
2fc76a2d 257- (void) _yieldToContext:(NSMutableArray *)context { _pooled
d061f4ba
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
2fc76a2d
JF
262 /* XXX: deal with exceptions */
263 id value([self performSelector:selector withObject:object]);
264
677b8415 265 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
2fc76a2d 266 [context removeAllObjects];
677b8415 267 if ([signature methodReturnLength] != 0 && value != nil)
2fc76a2d 268 [context addObject:value];
d061f4ba
JF
269
270 stopped = true;
271
272 [self
273 performSelectorOnMainThread:@selector(doNothing)
274 withObject:nil
275 waitUntilDone:NO
276 ];
277}
278
2fc76a2d 279- (id) yieldToSelector:(SEL)selector withObject:(id)object {
d061f4ba
JF
280 volatile bool stopped(false);
281
2fc76a2d 282 NSMutableArray *context([NSMutableArray arrayWithObjects:
d061f4ba
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]);
2fc76a2d
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];
d061f4ba
JF
306}
307
308@end
bfc87a4d 309/* }}} */
d061f4ba 310
718bf014 311/* Cydia Action Sheet {{{ */
38be2c4b 312@interface CYActionSheet : UIAlertView {
670a0494
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 {
38be2c4b 322 if ((self = [super init])) {
b5e7eebb
GP
323 [self setTitle:title];
324 [self setDelegate:self];
325 for (NSString *button in buttons) [self addButtonWithTitle:button];
326 [self setCancelButtonIndex:index];
670a0494
JF
327 } return self;
328}
329
6f6d34ec 330- (void) _updateFrameForDisplay {
31f8d96a
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
38be2c4b
GP
342- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
343 button_ = buttonIndex + 1;
670a0494
JF
344}
345
be2b3d7b 346- (void) dismiss {
b5e7eebb 347 [self dismissWithClickedButtonIndex:-1 animated:YES];
be2b3d7b
GP
348}
349
670a0494 350- (int) yieldToPopupAlertAnimated:(BOOL)animated {
a07b7e8b 351 [self setRunsModal:YES];
670a0494 352 button_ = 0;
be2b3d7b 353 [self show];
670a0494
JF
354 return button_;
355}
356
357@end
718bf014 358/* }}} */
670a0494 359
68f1828e 360/* NSForcedOrderingSearch doesn't work on the iPhone */
808c6eb6 361static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
677b8415
JF
362static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
363static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
1e7a90f5 364
6e201c55
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 {
bfc87a4d 385 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
6e201c55
JF
386}
387
388@end
389/* }}} */
390
c390d3ab 391#define lprintf(args...) fprintf(stderr, args)
a9543575 392
14d60a3f 393#define ForRelease 1
ab92ad73 394#define TraceLogging (1 && !ForRelease)
1539387a 395#define HistogramInsertionSort (!ForRelease ? 0 : 0)
f9f6d9e8 396#define ProfileTimes (0 && !ForRelease)
123c5344 397#define ForSaurik (0 && !ForRelease)
670a0494 398#define LogBrowser (0 && !ForRelease)
b1ce61ec 399#define TrackResize (0 && !ForRelease)
2634b249 400#define ManualRefresh (1 && !ForRelease)
f79a4512 401#define ShowInternals (0 && !ForRelease)
b0ad8dee 402#define IgnoreInstall (0 && !ForRelease)
2634b249 403#define AlwaysReload (0 && !ForRelease)
795d26fc 404
ab92ad73 405#if !TraceLogging
189a73d0
JF
406#undef _trace
407#define _trace(args...)
ab92ad73
JF
408#endif
409
410#if !ProfileTimes
808c6eb6 411#undef _profile
3e9c9e85 412#define _profile(name) {
808c6eb6 413#undef _end
3e9c9e85 414#define _end }
2fc76a2d 415#define PrintTimes() do {} while (false)
189a73d0
JF
416#endif
417
807ae6d7 418/* Radix Sort {{{ */
df213583
JF
419typedef uint32_t (*SKRadixFunction)(id, void *);
420
807ae6d7 421@interface NSMutableArray (Radix)
df213583 422- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
807ae6d7
JF
423@end
424
f79a4512
JF
425struct RadixItem_ {
426 size_t index;
427 uint32_t key;
428};
807ae6d7 429
b0403ab1
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
f79a4512 444 struct RadixItem_ *lhs(swap), *rhs(swap + count);
807ae6d7 445
ec3f2f53 446 static const size_t width = 32;
807ae6d7
JF
447 static const size_t bits = 11;
448 static const size_t slots = 1 << bits;
ec3f2f53 449 static const size_t passes = (width + (bits - 1)) / bits;
807ae6d7
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;
ec3f2f53 459 key &= _not(uint32_t) >> width - bits;
807ae6d7
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;
ec3f2f53 473 key &= _not(uint32_t) >> width - bits;
807ae6d7
JF
474 rhs[hist[key]++] = lhs[i];
475 }
476
f79a4512 477 RadixItem_ *tmp(lhs);
807ae6d7
JF
478 lhs = rhs;
479 rhs = tmp;
480 }
481
482 delete [] hist;
483
fd119f42 484 const void **values(new const void *[count]);
807ae6d7 485 for (size_t i(0); i != count; ++i)
fd119f42
JF
486 values[i] = [self objectAtIndex:lhs[i].index];
487 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
488 delete [] values;
807ae6d7
JF
489
490 delete [] swap;
491}
492
493@end
eef4ccaf
JF
494/* }}} */
495/* Insertion Sort {{{ */
496
df213583
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);
b5e7eebb 503 if (0 == cr) return (probe - (const char *)list) / elementSize;
df213583
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
eef4ccaf
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);
b5e7eebb 516 if (0 == cr) return (probe - (const char *)list) / elementSize;
eef4ccaf
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
1539387a 529#if HistogramInsertionSort > 0
df213583
JF
530 uint32_t total(0), *offsets(new uint32_t[range.length]);
531#endif
532
eef4ccaf
JF
533 for (CFIndex index(1); index != range.length; ++index) {
534 const void *value(values[index]);
df213583
JF
535 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
536 CFIndex correct(index);
1539387a
JF
537 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
538#if HistogramInsertionSort > 1
539 NSLog(@"%@ < %@", value, values[correct - 1]);
540#endif
df213583
JF
541 if (--correct == 0)
542 break;
1539387a 543 }
eef4ccaf 544 if (correct != index) {
df213583
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);
eef4ccaf
JF
553 values[correct] = value;
554 }
555 }
556
557 CFArrayReplaceValues(array, range, values, range.length);
558 delete [] values;
df213583 559
1539387a 560#if HistogramInsertionSort > 0
df213583
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
eef4ccaf
JF
567}
568
807ae6d7
JF
569/* }}} */
570
bf8476c8
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
3c216e5e
JF
599@implementation WebScriptObject (NSFastEnumeration)
600
601- (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
77801ff1
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
3c216e5e
JF
614@end
615
680eb135
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
bfc87a4d 629/* Cydia NSString Additions {{{ */
2388b078 630@interface NSString (Cydia)
808c6eb6 631+ (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
f79a4512 632+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
2388b078 633+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
a54b1c10 634- (NSComparisonResult) compareByPath:(NSString *)other;
2fc76a2d
JF
635- (NSString *) stringByCachingURLWithCurrentCDN;
636- (NSString *) stringByAddingPercentEscapesIncludingReserved;
2388b078
JF
637@end
638
639@implementation NSString (Cydia)
640
808c6eb6
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
f79a4512
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
2388b078 651+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
2083b866 652 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
2388b078
JF
653}
654
a54b1c10
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
2fc76a2d
JF
685- (NSString *) stringByCachingURLWithCurrentCDN {
686 return [self
65c27c56
JF
687 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
688 withString:@"://cache.cydia.saurik.com/"
2fc76a2d
JF
689 ];
690}
691
692- (NSString *) stringByAddingPercentEscapesIncludingReserved {
693 return [(id)CFURLCreateStringByAddingPercentEscapes(
bc11cf5b 694 kCFAllocatorDefault,
2fc76a2d
JF
695 (CFStringRef) self,
696 NULL,
697 CFSTR(";/?:@&=+$,"),
698 kCFStringEncodingUTF8
699 ) autorelease];
700}
701
2388b078 702@end
bfc87a4d 703/* }}} */
2388b078 704
bfc87a4d 705/* C++ NSString Wrapper Cache {{{ */
8e8fca7f
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
f79a4512
JF
716class CYString {
717 private:
718 char *data_;
719 size_t size_;
720 CFStringRef cache_;
721
722 _finline void clear_() {
18873623 723 if (cache_ != NULL) {
f79a4512 724 CFRelease(cache_);
18873623
JF
725 cache_ = NULL;
726 }
f79a4512
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),
18873623 750 cache_(NULL)
f79a4512
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
97814287
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
f79a4512
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
97814287 781 data_ = const_cast<char *>(data);
f79a4512 782 size_ = size;
97814287
JF
783
784 if (pool != NULL)
785 copy(pool);
f79a4512
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
8e8fca7f
JF
801 _finline operator CFStringRef() {
802 if (cache_ == NULL)
803 cache_ = CYStringCreate(data_, size_);
804 return cache_;
df213583
JF
805 }
806
807 _finline operator id() {
808 return (NSString *) static_cast<CFStringRef>(*this);
f79a4512 809 }
4c0ed943
JF
810
811 _finline operator const char *() {
812 return reinterpret_cast<const char *>(data_);
813 }
f79a4512 814};
bfc87a4d
JF
815/* }}} */
816/* C++ NSString Algorithm Adapters {{{ */
f79a4512
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};
bfc87a4d 846/* }}} */
f79a4512 847
b4d89997
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) {
c390d3ab 866 lprintf("%d:%s\n", offset, error);
b4d89997
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) {
2388b078 880 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
b4d89997
JF
881 }
882
8b29f8e6
JF
883 bool operator ()(NSString *data) {
884 // XXX: length is for characters, not for bytes
885 return operator ()([data UTF8String], [data length]);
886 }
887
b4d89997
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/* }}} */
36bb2ca2 894/* Mime Addresses {{{ */
36bb2ca2
JF
895@interface Address : NSObject {
896 NSString *name_;
6f1a15d9 897 NSString *address_;
36bb2ca2
JF
898}
899
900- (NSString *) name;
6f1a15d9 901- (NSString *) address;
36bb2ca2 902
dc63e78f
JF
903- (void) setAddress:(NSString *)address;
904
36bb2ca2
JF
905+ (Address *) addressWithString:(NSString *)string;
906- (Address *) initWithString:(NSString *)string;
907@end
908
909@implementation Address
910
911- (void) dealloc {
912 [name_ release];
6f1a15d9
JF
913 if (address_ != nil)
914 [address_ release];
36bb2ca2
JF
915 [super dealloc];
916}
917
918- (NSString *) name {
919 return name_;
920}
921
6f1a15d9
JF
922- (NSString *) address {
923 return address_;
36bb2ca2
JF
924}
925
dc63e78f
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
36bb2ca2
JF
935+ (Address *) addressWithString:(NSString *)string {
936 return [[[Address alloc] initWithString:string] autorelease];
937}
938
6f1a15d9
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
36bb2ca2
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
6f1a15d9 956 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
7b0ce2da 957
6f1a15d9
JF
958 if (address_r(data, size)) {
959 name_ = [address_r[1] retain];
960 address_ = [address_r[2] retain];
36bb2ca2 961 } else {
affeffc7 962 name_ = [string retain];
6f1a15d9 963 address_ = nil;
36bb2ca2
JF
964 }
965 } return self;
966}
967
968@end
969/* }}} */
5f6bff8c 970/* CoreGraphics Primitives {{{ */
02012733 971class CYColor {
b4d89997
JF
972 private:
973 CGColorRef color_;
974
6a575b5e
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
b4d89997 980 public:
02012733 981 CYColor() :
36bb2ca2
JF
982 color_(NULL)
983 {
984 }
985
02012733 986 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
6a575b5e 987 color_(Create_(space, red, green, blue, alpha))
36bb2ca2
JF
988 {
989 Set(space, red, green, blue, alpha);
990 }
991
992 void Clear() {
993 if (color_ != NULL)
994 CGColorRelease(color_);
b4d89997
JF
995 }
996
02012733 997 ~CYColor() {
36bb2ca2
JF
998 Clear();
999 }
1000
1001 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1002 Clear();
6a575b5e 1003 color_ = Create_(space, red, green, blue, alpha);
b4d89997
JF
1004 }
1005
1006 operator CGColorRef() {
1007 return color_;
1008 }
1009};
b4d89997
JF
1010/* }}} */
1011
36bb2ca2 1012/* Random Global Variables {{{ */
3178d79b 1013static const int PulseInterval_ = 50000;
58241d4c 1014static const int ButtonBarWidth_ = 60;
2388b078 1015static const int ButtonBarHeight_ = 48;
6d9712c4 1016static const float KeyboardTime_ = 0.3f;
affeffc7 1017
d791dce4
JF
1018static int Finish_;
1019static NSArray *Finishes_;
1020
affeffc7 1021#define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
22f8bed9 1022#define NotifyConfig_ "/etc/notify.conf"
2a8d9add 1023
dc63e78f
JF
1024static bool Queuing_;
1025
02012733
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_;
3bd1c2a2 1035
dc63e78f
JF
1036static UIColor *InstallingColor_;
1037static UIColor *RemovingColor_;
36bb2ca2 1038
7d2ac47f 1039static NSString *App_;
d73cede2 1040static NSString *Home_;
d73cede2 1041
2388b078 1042static BOOL Advanced_;
a54b1c10 1043static BOOL Ignored_;
2388b078 1044
f641a0e5
JF
1045static UIFont *Font12_;
1046static UIFont *Font12Bold_;
1047static UIFont *Font14_;
1048static UIFont *Font18Bold_;
1049static UIFont *Font22Bold_;
1050
87f46a96 1051static const char *Machine_ = NULL;
f4b1c57f 1052static NSString *System_ = nil;
56127854
JF
1053static NSString *SerialNumber_ = nil;
1054static NSString *ChipID_ = nil;
1055static NSString *Token_ = nil;
1056static NSString *UniqueID_ = nil;
567e3972 1057static NSString *PLMN_ = nil;
56127854
JF
1058static NSString *Build_ = nil;
1059static NSString *Product_ = nil;
1060static NSString *Safari_ = nil;
2a8d9add 1061
d791dce4
JF
1062static CFLocaleRef Locale_;
1063static NSArray *Languages_;
1064static CGColorSpaceRef space_;
36bb2ca2 1065
46dbfd32 1066static NSDictionary *SectionMap_;
b4d89997 1067static NSMutableDictionary *Metadata_;
7b0ce2da
JF
1068static _transient NSMutableDictionary *Settings_;
1069static _transient NSString *Role_;
1070static _transient NSMutableDictionary *Packages_;
1071static _transient NSMutableDictionary *Sections_;
1072static _transient NSMutableDictionary *Sources_;
bbb879fb 1073static bool Changed_;
31bc18a7 1074static time_t now_;
8da60fb7 1075
01d93940 1076static bool IsWildcat_;
36bb2ca2 1077/* }}} */
d791dce4 1078
36bb2ca2
JF
1079/* Display Helpers {{{ */
1080inline float Interpolate(float begin, float end, float fraction) {
1081 return (end - begin) * fraction + begin;
1082}
2367a917 1083
f79a4512 1084/* XXX: localize this! */
8fe19fc1 1085NSString *SizeString(double size) {
affeffc7
JF
1086 bool negative = size < 0;
1087 if (negative)
1088 size = -size;
1089
8fe19fc1
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
86316a91 1098 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
8fe19fc1
JF
1099}
1100
1c1dfc2d 1101static _finline const char *StripVersion_(const char *version) {
6a155117 1102 const char *colon(strchr(version, ':'));
673ad3c3 1103 return colon == NULL ? version : colon + 1;
6a155117
JF
1104}
1105
f79a4512 1106NSString *LocalizeSection(NSString *section) {
b1ce61ec 1107 static Pcre title_r("^(.*?) \\((.*)\\)$");
9fcbca29
JF
1108 if (title_r(section)) {
1109 NSString *parent(title_r[1]);
1110 NSString *child(title_r[2]);
1111
43f3d7f6 1112 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
9fcbca29
JF
1113 LocalizeSection(parent),
1114 LocalizeSection(child)
b1ce61ec 1115 ];
9fcbca29 1116 }
b1ce61ec
JF
1117
1118 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
f79a4512
JF
1119}
1120
4cf4165e
JF
1121NSString *Simplify(NSString *title) {
1122 const char *data = [title UTF8String];
1123 size_t size = [title length];
1124
7b0ce2da
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
b1ce61ec 1133 static Pcre title_r("^(.*?) \\((.*)\\)$");
4cf4165e 1134 if (title_r(data, size))
7b0ce2da
JF
1135 return Simplify(title_r[1]);
1136
1137 return title;
4cf4165e 1138}
36bb2ca2
JF
1139/* }}} */
1140
d791dce4
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
6d9712c4 1155bool isSectionVisible(NSString *section) {
677b8415
JF
1156 NSDictionary *metadata([Sections_ objectForKey:section]);
1157 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
6d9712c4
JF
1158 return hidden == nil || ![hidden boolValue];
1159}
1160
9cb0bff2
GP
1161@class Cydia;
1162
d36e83a3 1163/* Delegate Prototypes {{{ */
36bb2ca2
JF
1164@class Package;
1165@class Source;
1166
31f3cfff
JF
1167@interface NSObject (ProgressDelegate)
1168@end
1169
36bb2ca2 1170@protocol ProgressDelegate
670a0494 1171- (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
36bb2ca2
JF
1172- (void) setProgressTitle:(NSString *)title;
1173- (void) setProgressPercent:(float)percent;
baf80942 1174- (void) startProgress;
36bb2ca2 1175- (void) addProgressOutput:(NSString *)output;
baf80942 1176- (bool) isCancelling:(size_t)received;
36bb2ca2
JF
1177@end
1178
8b29f8e6 1179@protocol ConfigurationDelegate
5a09ae08 1180- (void) repairWithSelector:(SEL)selector;
8b29f8e6
JF
1181- (void) setConfigurationData:(NSString *)data;
1182@end
1183
adb61bda 1184@class PackageController;
f79a4512 1185
36bb2ca2 1186@protocol CydiaDelegate
54043703
JF
1187- (void) retainNetworkActivityIndicator;
1188- (void) releaseNetworkActivityIndicator;
adb61bda 1189- (void) setPackageController:(PackageController *)view;
dc63e78f 1190- (void) clearPackage:(Package *)package;
36bb2ca2 1191- (void) installPackage:(Package *)package;
77801ff1 1192- (void) installPackages:(NSArray *)packages;
36bb2ca2 1193- (void) removePackage:(Package *)package;
c21004b9
JF
1194- (void) beginUpdate;
1195- (BOOL) updating;
36bb2ca2 1196- (void) distUpgrade;
fed0d010 1197- (void) loadData;
6d9712c4 1198- (void) updateData;
7b0ce2da 1199- (void) syncData;
21c6da4b 1200- (void) showSettings;
7b0ce2da 1201- (UIProgressHUD *) addProgressHUD;
d061f4ba 1202- (void) removeProgressHUD:(UIProgressHUD *)hud;
9b623dac 1203- (CYViewController *) pageForPackage:(NSString *)name;
adb61bda 1204- (PackageController *) packageController;
9daa7f25 1205- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
36bb2ca2 1206@end
54043703
JF
1207
1208static id<CydiaDelegate> CydiaApp;
d36e83a3 1209/* }}} */
b4d89997 1210
dc5812ec
JF
1211/* Status Delegation {{{ */
1212class Status :
1213 public pkgAcquireStatus
1214{
1215 private:
31f3cfff 1216 _transient NSObject<ProgressDelegate> *delegate_;
dc5812ec
JF
1217
1218 public:
1219 Status() :
1220 delegate_(nil)
1221 {
1222 }
1223
1224 void setDelegate(id delegate) {
1225 delegate_ = delegate;
1226 }
1227
670a0494
JF
1228 NSObject<ProgressDelegate> *getDelegate() const {
1229 return delegate_;
1230 }
1231
dc5812ec
JF
1232 virtual bool MediaChange(std::string media, std::string drive) {
1233 return false;
1234 }
1235
1236 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
dc5812ec
JF
1237 }
1238
1239 virtual void Fetch(pkgAcquire::ItemDesc &item) {
9487f027 1240 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
670a0494 1241 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
dc5812ec
JF
1242 }
1243
1244 virtual void Done(pkgAcquire::ItemDesc &item) {
dc5812ec
JF
1245 }
1246
1247 virtual void Fail(pkgAcquire::ItemDesc &item) {
1d80f6b9
JF
1248 if (
1249 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1250 item.Owner->Status == pkgAcquire::Item::StatDone
1251 )
1252 return;
1253
affeffc7
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
670a0494 1262 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
affeffc7
JF
1263 withObject:[NSArray arrayWithObjects:
1264 [NSString stringWithUTF8String:error.c_str()],
1265 source,
1266 nil]
31f3cfff
JF
1267 waitUntilDone:YES
1268 ];
dc5812ec
JF
1269 }
1270
1271 virtual bool Pulse(pkgAcquire *Owner) {
2367a917
JF
1272 bool value = pkgAcquireStatus::Pulse(Owner);
1273
1274 float percent(
1275 double(CurrentBytes + CurrentItems) /
1276 double(TotalBytes + TotalItems)
1277 );
1278
36bb2ca2 1279 [delegate_ setProgressPercent:percent];
baf80942 1280 return [delegate_ isCancelling:CurrentBytes] ? false : value;
dc5812ec
JF
1281 }
1282
1283 virtual void Start() {
baf80942 1284 [delegate_ startProgress];
dc5812ec
JF
1285 }
1286
1287 virtual void Stop() {
dc5812ec
JF
1288 }
1289};
1290/* }}} */
1291/* Progress Delegation {{{ */
1292class Progress :
1293 public OpProgress
1294{
1295 private:
36bb2ca2 1296 _transient id<ProgressDelegate> delegate_;
bfc87a4d 1297 float percent_;
dc5812ec
JF
1298
1299 protected:
1300 virtual void Update() {
670a0494
JF
1301 /*if (abs(Percent - percent_) > 2)
1302 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
bfc87a4d 1303 percent_ = Percent;
670a0494 1304 }*/
bfc87a4d 1305
8eed3ec6
JF
1306 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1307 [delegate_ setProgressPercent:(Percent / 100)];*/
dc5812ec
JF
1308 }
1309
1310 public:
1311 Progress() :
bfc87a4d
JF
1312 delegate_(nil),
1313 percent_(0)
dc5812ec
JF
1314 {
1315 }
1316
1317 void setDelegate(id delegate) {
1318 delegate_ = delegate;
1319 }
1320
670a0494
JF
1321 id getDelegate() const {
1322 return delegate_;
1323 }
1324
dc5812ec 1325 virtual void Done() {
670a0494 1326 //NSLog(@"DONE");
8eed3ec6 1327 //[delegate_ setProgressPercent:1];
dc5812ec
JF
1328 }
1329};
1330/* }}} */
1331
36bb2ca2 1332/* Database Interface {{{ */
68d927e2
JF
1333typedef std::map< unsigned long, _H<Source> > SourceMap;
1334
36bb2ca2 1335@interface Database : NSObject {
f79a4512
JF
1336 NSZone *zone_;
1337 apr_pool_t *pool_;
1338
a1440b10
JF
1339 unsigned era_;
1340
36bb2ca2 1341 pkgCacheFile cache_;
5a09ae08 1342 pkgDepCache::Policy *policy_;
36bb2ca2
JF
1343 pkgRecords *records_;
1344 pkgProblemResolver *resolver_;
1345 pkgAcquire *fetcher_;
1346 FileFd *lock_;
1347 SPtr<pkgPackageManager> manager_;
1348 pkgSourceList *list_;
5f6bff8c 1349
68d927e2 1350 SourceMap sources_;
077e9d90 1351 CFMutableArrayRef packages_;
b4d89997 1352
31f3cfff 1353 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
36bb2ca2
JF
1354 Status status_;
1355 Progress progress_;
8b29f8e6 1356
77fcccaf 1357 int cydiafd_;
36bb2ca2 1358 int statusfd_;
8b29f8e6 1359 FILE *input_;
dc5812ec
JF
1360}
1361
770f2a8e 1362+ (Database *) sharedInstance;
a1440b10 1363- (unsigned) era;
770f2a8e 1364
77fcccaf 1365- (void) _readCydia:(NSNumber *)fd;
36bb2ca2
JF
1366- (void) _readStatus:(NSNumber *)fd;
1367- (void) _readOutput:(NSNumber *)fd;
2367a917 1368
8b29f8e6
JF
1369- (FILE *) input;
1370
36bb2ca2 1371- (Package *) packageWithName:(NSString *)name;
dc5812ec 1372
36bb2ca2 1373- (pkgCacheFile &) cache;
5a09ae08 1374- (pkgDepCache::Policy *) policy;
36bb2ca2
JF
1375- (pkgRecords *) records;
1376- (pkgProblemResolver *) resolver;
1377- (pkgAcquire &) fetcher;
a3328c28 1378- (pkgSourceList &) list;
36bb2ca2 1379- (NSArray *) packages;
7b0ce2da 1380- (NSArray *) sources;
36bb2ca2
JF
1381- (void) reloadData;
1382
5a09ae08 1383- (void) configure;
670a0494 1384- (bool) prepare;
36bb2ca2 1385- (void) perform;
670a0494 1386- (bool) upgrade;
36bb2ca2
JF
1387- (void) update;
1388
670a0494 1389- (void) updateWithStatus:(Status &)status;
36bb2ca2
JF
1390
1391- (void) setDelegate:(id)delegate;
7376b55c 1392- (Source *) getSource:(pkgCache::PkgFileIterator)file;
670a0494
JF
1393@end
1394/* }}} */
1395/* Delegate Helpers {{{ */
c21004b9 1396@implementation NSObject (ProgressDelegate)
670a0494
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];
6067f1b8 1421
eb30da80
GP
1422 [self performSelector:@selector(setProgressError:withTitle:)
1423 withObject:error
1424 withObject:(package == nil ? id : [package name])
1425 ];
670a0494
JF
1426}
1427
dc5812ec 1428@end
36bb2ca2 1429/* }}} */
dc5812ec 1430
94b0b3e5
JF
1431// Cytore Definitions {{{
1432struct PackageValue :
1433 Cytore::Block
1434{
94b0b3e5
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{
9f357d11 1454 uint32_t active_;
94b0b3e5
JF
1455 Cytore::Offset<PackageValue> packages_[1 << 16];
1456};
1457
1458static Cytore::File<MetaValue> MetaFile_;
1459// }}}
1460// Cytore Helper Functions {{{
bb6bb6d6 1461static PackageValue *PackageFind(const char *name, size_t length) {
94b0b3e5
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
94b0b3e5
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
5a933937
JF
1505 bool versioned(false);
1506
94b0b3e5
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;
5a933937 1511 versioned = true;
94b0b3e5 1512 }
5a933937
JF
1513 } else if (metadata->last_ == 0) {
1514 metadata->last_ = metadata->first_;
1515 if (metadata->version_[0] == '\0')
1516 versioned = true;
1517 }
94b0b3e5 1518
5a933937
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));
94b0b3e5 1524
5a933937
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 }
94b0b3e5
JF
1531}
1532// }}}
1533
36bb2ca2
JF
1534/* Source Class {{{ */
1535@interface Source : NSObject {
6204f56a 1536 CYString depiction_;
f9f6d9e8
JF
1537 CYString description_;
1538 CYString label_;
1539 CYString origin_;
1540 CYString support_;
dc5812ec 1541
f9f6d9e8
JF
1542 CYString uri_;
1543 CYString distribution_;
1544 CYString type_;
1545 CYString version_;
2367a917 1546
f9f6d9e8 1547 NSString *host_;
10bf7bbb 1548 NSString *authority_;
f9f6d9e8
JF
1549
1550 CYString defaultIcon_;
dc5812ec 1551
7b0ce2da 1552 NSDictionary *record_;
36bb2ca2 1553 BOOL trusted_;
dc5812ec
JF
1554}
1555
f9f6d9e8 1556- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
dc5812ec 1557
7b0ce2da
JF
1558- (NSComparisonResult) compareByNameAndType:(Source *)source;
1559
6204f56a 1560- (NSString *) depictionForPackage:(NSString *)package;
dc63e78f
JF
1561- (NSString *) supportForPackage:(NSString *)package;
1562
7b0ce2da 1563- (NSDictionary *) record;
36bb2ca2 1564- (BOOL) trusted;
dc5812ec 1565
36bb2ca2
JF
1566- (NSString *) uri;
1567- (NSString *) distribution;
1568- (NSString *) type;
7b0ce2da
JF
1569- (NSString *) key;
1570- (NSString *) host;
36bb2ca2 1571
7b0ce2da 1572- (NSString *) name;
36bb2ca2
JF
1573- (NSString *) description;
1574- (NSString *) label;
1575- (NSString *) origin;
1576- (NSString *) version;
dc5812ec 1577
36bb2ca2 1578- (NSString *) defaultIcon;
7b0ce2da 1579
dc5812ec 1580@end
dc5812ec 1581
36bb2ca2 1582@implementation Source
dc5812ec 1583
a3328c28 1584- (void) _clear {
f9f6d9e8
JF
1585 uri_.clear();
1586 distribution_.clear();
1587 type_.clear();
a3328c28 1588
f9f6d9e8
JF
1589 description_.clear();
1590 label_.clear();
1591 origin_.clear();
6204f56a 1592 depiction_.clear();
f9f6d9e8
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 }
7623f855
JF
1606
1607 if (authority_ != nil) {
1608 [authority_ release];
1609 authority_ = nil;
1610 }
a3328c28 1611}
dc5812ec 1612
a3328c28 1613- (void) dealloc {
3931b718 1614 // XXX: this is a very inefficient way to call these deconstructors
a3328c28 1615 [self _clear];
36bb2ca2 1616 [super dealloc];
dc5812ec
JF
1617}
1618
6f1a15d9
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
f9f6d9e8 1631- (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
a3328c28 1632 [self _clear];
dc5812ec 1633
a3328c28
JF
1634 trusted_ = index->IsTrusted();
1635
f9f6d9e8
JF
1636 uri_.set(pool, index->GetURI());
1637 distribution_.set(pool, index->GetDist());
1638 type_.set(pool, index->GetType());
a3328c28
JF
1639
1640 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1641 if (dindex != NULL) {
18873623
JF
1642 FileFd fd;
1643 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1644 _error->Discard();
1645 else {
1646 pkgTagFile tags(&fd);
f9f6d9e8 1647
18873623
JF
1648 pkgTagSection section;
1649 tags.Step(section);
a3328c28 1650
18873623
JF
1651 struct {
1652 const char *name_;
1653 CYString *value_;
1654 } names[] = {
1655 {"default-icon", &defaultIcon_},
6204f56a 1656 {"depiction", &depiction_},
18873623
JF
1657 {"description", &description_},
1658 {"label", &label_},
1659 {"origin", &origin_},
1660 {"support", &support_},
1661 {"version", &version_},
1662 };
f9f6d9e8 1663
18873623
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 }
f9f6d9e8 1671 }
36bb2ca2 1672 }
a3328c28 1673 }
7b0ce2da 1674
a3328c28
JF
1675 record_ = [Sources_ objectForKey:[self key]];
1676 if (record_ != nil)
1677 record_ = [record_ retain];
f9f6d9e8 1678
7623f855
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)
a6884de3 1686 authority_ = host_;
7623f855
JF
1687 else
1688 authority_ = [url path];
a6884de3
JF
1689
1690 if (authority_ != nil)
1691 authority_ = [authority_ retain];
a3328c28
JF
1692}
1693
f9f6d9e8 1694- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
a3328c28 1695 if ((self = [super init]) != nil) {
f9f6d9e8 1696 [self setMetaIndex:index inPool:pool];
36bb2ca2 1697 } return self;
2367a917 1698}
dc5812ec 1699
7b0ce2da
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
68f1828e 1720 return [lhs compare:rhs options:LaxCompareOptions_];
7b0ce2da
JF
1721}
1722
6204f56a 1723- (NSString *) depictionForPackage:(NSString *)package {
89b0ea4a 1724 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
6204f56a
JF
1725}
1726
dc63e78f 1727- (NSString *) supportForPackage:(NSString *)package {
89b0ea4a 1728 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
dc63e78f
JF
1729}
1730
7b0ce2da
JF
1731- (NSDictionary *) record {
1732 return record_;
1733}
1734
36bb2ca2
JF
1735- (BOOL) trusted {
1736 return trusted_;
1737}
3178d79b 1738
36bb2ca2
JF
1739- (NSString *) uri {
1740 return uri_;
1741}
ec97ef06 1742
36bb2ca2
JF
1743- (NSString *) distribution {
1744 return distribution_;
1745}
dc5812ec 1746
36bb2ca2
JF
1747- (NSString *) type {
1748 return type_;
dc5812ec
JF
1749}
1750
7b0ce2da 1751- (NSString *) key {
f9f6d9e8 1752 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
7b0ce2da
JF
1753}
1754
1755- (NSString *) host {
f9f6d9e8 1756 return host_;
7b0ce2da
JF
1757}
1758
1759- (NSString *) name {
7623f855 1760 return origin_.empty() ? authority_ : origin_;
7b0ce2da
JF
1761}
1762
36bb2ca2
JF
1763- (NSString *) description {
1764 return description_;
1765}
b4d89997 1766
36bb2ca2 1767- (NSString *) label {
7623f855 1768 return label_.empty() ? authority_ : label_;
36bb2ca2 1769}
3178d79b 1770
36bb2ca2
JF
1771- (NSString *) origin {
1772 return origin_;
1773}
3178d79b 1774
36bb2ca2
JF
1775- (NSString *) version {
1776 return version_;
1777}
2367a917 1778
36bb2ca2
JF
1779- (NSString *) defaultIcon {
1780 return defaultIcon_;
1781}
2367a917 1782
2388b078
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
dc5812ec 1818@end
b4d89997 1819/* }}} */
36bb2ca2 1820/* Package Class {{{ */
12016ee5
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
36bb2ca2 1836@interface Package : NSObject {
aab28f8b
JF
1837 uint32_t era_ : 29;
1838 uint32_t essential_ : 1;
1839 uint32_t obsolete_ : 1;
1840 uint32_t ignored_ : 1;
1841
68d927e2 1842 apr_pool_t *pool_;
a1440b10 1843
aab28f8b
JF
1844 _transient Database *database_;
1845
7376b55c 1846 pkgCache::VerIterator version_;
36bb2ca2 1847 pkgCache::PkgIterator iterator_;
36bb2ca2 1848 pkgCache::VerFileIterator file_;
bbb879fb 1849
aab28f8b
JF
1850 CYString id_;
1851 CYString name_;
807ae6d7 1852
4c0ed943 1853 CYString latest_;
6a155117 1854 CYString installed_;
dc5812ec 1855
aab28f8b
JF
1856 CYString section_;
1857 _transient NSString *section$_;
f79a4512 1858
aab28f8b 1859 Source *source_;
2388b078 1860
bb6bb6d6 1861 PackageValue *metadata_;
aab28f8b 1862 ParsedPackage *parsed_;
94b0b3e5 1863
aab28f8b
JF
1864 NSMutableArray *tags_;
1865 NSString *role_;
b4d89997
JF
1866}
1867
7376b55c 1868- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
f79a4512 1869+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
b4d89997 1870
2388b078 1871- (pkgCache::PkgIterator) iterator;
68d927e2 1872- (void) parse;
2388b078 1873
36bb2ca2 1874- (NSString *) section;
dec6029f
JF
1875- (NSString *) simpleSection;
1876
f79a4512
JF
1877- (NSString *) longSection;
1878- (NSString *) shortSection;
1879
a3328c28
JF
1880- (NSString *) uri;
1881
36bb2ca2
JF
1882- (Address *) maintainer;
1883- (size_t) size;
eef4ccaf
JF
1884- (NSString *) longDescription;
1885- (NSString *) shortDescription;
808c6eb6 1886- (unichar) index;
dc5812ec 1887
94b0b3e5 1888- (PackageValue *) metadata;
31bc18a7 1889- (time_t) seen;
94b0b3e5
JF
1890
1891- (bool) subscribed;
1892- (bool) setSubscribed:(bool)subscribed;
1893
807ae6d7 1894- (BOOL) ignored;
9e98e020 1895
36bb2ca2
JF
1896- (NSString *) latest;
1897- (NSString *) installed;
6a155117 1898- (BOOL) uninstalled;
5a09ae08
JF
1899
1900- (BOOL) valid;
31f3cfff 1901- (BOOL) upgradableAndEssential:(BOOL)essential;
36bb2ca2
JF
1902- (BOOL) essential;
1903- (BOOL) broken;
7d2ac47f 1904- (BOOL) unfiltered;
6d9712c4 1905- (BOOL) visible;
b4d89997 1906
9bedffaa
JF
1907- (BOOL) half;
1908- (BOOL) halfConfigured;
1909- (BOOL) halfInstalled;
1910- (BOOL) hasMode;
1911- (NSString *) mode;
1912
36bb2ca2
JF
1913- (NSString *) id;
1914- (NSString *) name;
770f2a8e 1915- (UIImage *) icon;
6f1a15d9 1916- (NSString *) homepage;
25a2158d 1917- (NSString *) depiction;
77fcccaf 1918- (Address *) author;
b4d89997 1919
dc63e78f
JF
1920- (NSString *) support;
1921
affeffc7 1922- (NSArray *) files;
affeffc7
JF
1923- (NSArray *) warnings;
1924- (NSArray *) applications;
2388b078 1925
36bb2ca2 1926- (Source *) source;
7b0ce2da 1927- (NSString *) role;
b4d89997 1928
36bb2ca2 1929- (BOOL) matches:(NSString *)text;
b4d89997 1930
7b0ce2da 1931- (bool) hasSupportingRole;
6d9712c4 1932- (BOOL) hasTag:(NSString *)tag;
c390d3ab 1933- (NSString *) primaryPurpose;
770f2a8e 1934- (NSArray *) purposes;
3bd1c2a2 1935- (bool) isCommercial;
6d9712c4 1936
cd95e390
JF
1937- (void) setIndex:(size_t)index;
1938
df213583
JF
1939- (CYString &) cyname;
1940
f79a4512 1941- (uint32_t) compareBySection:(NSArray *)sections;
807ae6d7 1942
36bb2ca2
JF
1943- (void) install;
1944- (void) remove;
06aa974d 1945
0a3b45ef 1946- (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
01d93940 1947- (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
e4f3d6e9 1948- (bool) isInstalledAndUnfiltered:(NSNumber *)number;
670a0494 1949- (bool) isVisibleInSection:(NSString *)section;
0a3b45ef 1950- (bool) isVisibleInSource:(Source *)source;
b4d89997 1951
36bb2ca2 1952@end
b4d89997 1953
f79a4512
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 {
36047c66 1973 value.bits.timestamp = [self seen] >> 2;
f79a4512
JF
1974 value.bits.ignored = 0;
1975 value.bits.upgradable = 0;
1976 }
1977
1978 return _not(uint32_t) - value.key;
1979}
1980
df213583
JF
1981uint32_t PackagePrefixRadix(Package *self, void *context) {
1982 size_t offset(reinterpret_cast<size_t>(context));
1983 CYString &name([self cyname]);
677b8415 1984
df213583
JF
1985 size_t size(name.size());
1986 if (size == 0)
1987 return 0;
1988 char *text(name.data());
677b8415 1989
df213583
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 }
677b8415 2000
df213583
JF
2001 uint8_t data[4];
2002
df213583
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]))
a7a59ee1 2023 data[i] |= 0x20;
df213583
JF
2024 }
2025
2026 if (offset == 0)
a7a59ee1
JF
2027 if (data[0] == '@')
2028 data[0] = 0x7f;
2029 else
2030 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
df213583
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);
677b8415 2043
5358f56f
JF
2044 if (lhn == NULL)
2045 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2046 else if (rhn == NULL)
2047 return NSOrderedDescending;
2048
677b8415 2049 _profile(PackageNameCompare$NumbersLast)
df213583 2050 if (!lhi.empty() && !rhi.empty()) {
677b8415
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
df213583
JF
2059 CFIndex length = CFStringGetLength(lhn);
2060
677b8415
JF
2061 _profile(PackageNameCompare$Compare)
2062 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2063 _end
2064 _end
2065}
2066
eef4ccaf
JF
2067CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2068 return PackageNameCompare(*lhs, *rhs, context);
677b8415
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
36bb2ca2 2079@implementation Package
b4d89997 2080
df213583
JF
2081- (NSString *) description {
2082 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2083}
2084
36bb2ca2 2085- (void) dealloc {
12016ee5
JF
2086 if (parsed_ != NULL)
2087 delete parsed_;
2088
bbb879fb
JF
2089 if (source_ != nil)
2090 [source_ release];
807ae6d7 2091
6d9712c4
JF
2092 if (tags_ != nil)
2093 [tags_ release];
7b0ce2da
JF
2094 if (role_ != nil)
2095 [role_ release];
9e98e020 2096
36bb2ca2 2097 [super dealloc];
b4d89997
JF
2098}
2099
3bd1c2a2
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
6f1a15d9 2111+ (NSArray *) _attributeKeys {
eef4ccaf 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];
6f1a15d9
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
68d927e2 2123- (void) parse {
12016ee5 2124 if (parsed_ != NULL)
68d927e2 2125 return;
12016ee5
JF
2126@synchronized (database_) {
2127 if ([database_ era] != era_ || file_.end())
68d927e2
JF
2128 return;
2129
12016ee5
JF
2130 ParsedPackage *parsed(new ParsedPackage);
2131 parsed_ = parsed;
2132
68d927e2
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[] = {
12016ee5
JF
2147 {"icon", &parsed->icon_},
2148 {"depiction", &parsed->depiction_},
2149 {"homepage", &parsed->homepage_},
68d927e2 2150 {"website", &website},
12016ee5
JF
2151 {"bugs", &parsed->bugs_},
2152 {"support", &parsed->support_},
2153 {"sponsor", &parsed->sponsor_},
2154 {"author", &parsed->author_},
68d927e2
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;
0dd0c302 2171 if (parser->ShortDesc(start, end)) {
68d927e2
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;
12016ee5 2177 parsed->tagline_.set(pool_, start, stop - start);
68d927e2
JF
2178 }
2179 _end
2180
2181 _profile(Package$parse$Retain)
12016ee5
JF
2182 if (parsed->homepage_.empty())
2183 parsed->homepage_ = website;
2184 if (parsed->homepage_ == parsed->depiction_)
2185 parsed->homepage_.clear();
68d927e2
JF
2186 _end
2187 _end
12016ee5 2188} }
68d927e2 2189
7376b55c 2190- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
a1440b10 2191 if ((self = [super init]) != nil) {
7376b55c 2192 _profile(Package$initWithVersion)
68d927e2 2193 pool_ = pool;
a1440b10 2194
36bb2ca2 2195 database_ = database;
aab28f8b 2196 era_ = [database era];
b4d89997 2197
aab28f8b 2198 version_ = version;
2083b866 2199
aab28f8b
JF
2200 pkgCache::PkgIterator iterator(version.ParentPkg());
2201 iterator_ = iterator;
06aa974d 2202
aab28f8b 2203 _profile(Package$initWithVersion$Version)
68d927e2
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
808c6eb6 2211
aab28f8b 2212 _profile(Package$initWithVersion$Cache)
aab28f8b
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()));
808c6eb6
JF
2220 _end
2221
7376b55c 2222 _profile(Package$initWithVersion$Tags)
aab28f8b 2223 pkgCache::TagIterator tag(iterator.TagList());
0dd0c302
JF
2224 if (!tag.end()) {
2225 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2226 do {
2227 const char *name(tag.Name());
3931b718 2228 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
0a377825 2229
70d45c1e 2230 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
8e8fca7f 2231 role_ = (NSString *) CYStringCreate(name + 6);
0a377825
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
0dd0c302
JF
2240 ++tag;
2241 } while (!tag.end());
2242 }
808c6eb6 2243 _end
7b0ce2da 2244
7376b55c 2245 _profile(Package$initWithVersion$Metadata)
029c8b74
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));
bb6bb6d6 2255 metadata_ = metadata;
677b8415 2256
029c8b74
JF
2257 id_.set(NULL, metadata->name_, size);
2258
94b0b3e5
JF
2259 const char *latest(version_.VerStr());
2260 size_t length(strlen(latest));
a4b0ec52 2261
94b0b3e5 2262 uint16_t vhash(hashlittle(latest, length));
677b8415 2263
94b0b3e5
JF
2264 size_t capped(std::min<size_t>(8, length));
2265 latest = latest + length - capped;
677b8415 2266
94b0b3e5
JF
2267 if (metadata->first_ == 0)
2268 metadata->first_ = now_;
808c6eb6 2269
5a933937
JF
2270 if (metadata->last_ == 0)
2271 metadata->last_ = metadata->first_;
2272
94b0b3e5 2273 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
5a933937
JF
2274 if (metadata->version_[0] != '\0')
2275 metadata->last_ = now_;
94b0b3e5
JF
2276 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2277 metadata->vhash_ = vhash;
5a933937 2278 }
808c6eb6 2279 _end
a1440b10 2280
7376b55c 2281 _profile(Package$initWithVersion$Section)
aab28f8b 2282 section_.set(NULL, iterator.Section());
f79a4512 2283 _end
a1440b10 2284
aab28f8b
JF
2285 _profile(Package$initWithVersion$Flags)
2286 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2287 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
4fa77608 2288 _end
3dd53516 2289 _end } return self;
dc5812ec
JF
2290}
2291
f79a4512 2292+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
b1ce61ec
JF
2293 pkgCache::VerIterator version;
2294
2295 _profile(Package$packageWithIterator$GetCandidateVer)
2296 version = [database policy]->GetCandidateVer(iterator);
2297 _end
2298
7376b55c
JF
2299 if (version.end())
2300 return nil;
b1ce61ec 2301
8564efc1
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;
3dd53516 2322}
dc5812ec 2323
2388b078
JF
2324- (pkgCache::PkgIterator) iterator {
2325 return iterator_;
2326}
2327
36bb2ca2 2328- (NSString *) section {
f79a4512
JF
2329 if (section$_ == nil) {
2330 if (section_.empty())
2331 return nil;
2332
e4f3d6e9
JF
2333 _profile(Package$section)
2334 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2335 NSString *name(section_);
07befb0c 2336 section$_ = [SectionMap_ objectForKey:name] ?: name;
e4f3d6e9 2337 _end
f79a4512 2338 } return section$_;
dc5812ec
JF
2339}
2340
dec6029f
JF
2341- (NSString *) simpleSection {
2342 if (NSString *section = [self section])
2343 return Simplify(section);
2344 else
2345 return nil;
a3328c28 2346}
dec6029f 2347
f79a4512 2348- (NSString *) longSection {
18873623 2349 return LocalizeSection([self section]);
f79a4512
JF
2350}
2351
2352- (NSString *) shortSection {
2353 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2354}
2355
a3328c28
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
dec6029f
JF
2367}
2368
36bb2ca2 2369- (Address *) maintainer {
884171d6
JF
2370@synchronized (database_) {
2371 if ([database_ era] != era_ || file_.end())
5a09ae08 2372 return nil;
884171d6 2373
36bb2ca2 2374 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
00e2109e
JF
2375 const std::string &maintainer(parser->Maintainer());
2376 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
884171d6 2377} }
8fe19fc1 2378
36bb2ca2 2379- (size_t) size {
884171d6
JF
2380@synchronized (database_) {
2381 if ([database_ era] != era_ || version_.end())
2382 return 0;
2383
2384 return version_->InstalledSize;
2385} }
dc5812ec 2386
eef4ccaf 2387- (NSString *) longDescription {
3dd53516
JF
2388@synchronized (database_) {
2389 if ([database_ era] != era_ || file_.end())
5a09ae08 2390 return nil;
3dd53516 2391
36bb2ca2 2392 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2388b078 2393 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
8fe19fc1 2394
36bb2ca2
JF
2395 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2396 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2397 if ([lines count] < 2)
2398 return nil;
3178d79b 2399
36bb2ca2 2400 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
c4dcf2c2 2401 for (size_t i(1), e([lines count]); i != e; ++i) {
36bb2ca2
JF
2402 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2403 [trimmed addObject:trim];
2404 }
3178d79b 2405
36bb2ca2 2406 return [trimmed componentsJoinedByString:@"\n"];
3dd53516 2407} }
dc5812ec 2408
eef4ccaf 2409- (NSString *) shortDescription {
12016ee5 2410 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
eef4ccaf
JF
2411}
2412
808c6eb6
JF
2413- (unichar) index {
2414 _profile(Package$index)
677b8415
JF
2415 CFStringRef name((CFStringRef) [self name]);
2416 if (CFStringGetLength(name) == 0)
808c6eb6 2417 return '#';
677b8415
JF
2418 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2419 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
808c6eb6 2420 return '#';
447db19d 2421 return toupper(character);
808c6eb6 2422 _end
36bb2ca2 2423}
3178d79b 2424
94b0b3e5 2425- (PackageValue *) metadata {
bb6bb6d6 2426 return metadata_;
807ae6d7
JF
2427}
2428
31bc18a7 2429- (time_t) seen {
94b0b3e5
JF
2430 PackageValue *metadata([self metadata]);
2431 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
3178d79b
JF
2432}
2433
94b0b3e5
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;
807ae6d7
JF
2444}
2445
2446- (BOOL) ignored {
1b18f026 2447 return ignored_;
807ae6d7
JF
2448}
2449
36bb2ca2
JF
2450- (NSString *) latest {
2451 return latest_;
8fe19fc1
JF
2452}
2453
36bb2ca2
JF
2454- (NSString *) installed {
2455 return installed_;
3178d79b
JF
2456}
2457
6a155117
JF
2458- (BOOL) uninstalled {
2459 return installed_.empty();
2460}
2461
5a09ae08
JF
2462- (BOOL) valid {
2463 return !version_.end();
2464}
2465
31f3cfff 2466- (BOOL) upgradableAndEssential:(BOOL)essential {
677b8415
JF
2467 _profile(Package$upgradableAndEssential)
2468 pkgCache::VerIterator current(iterator_.CurrentVer());
2469 if (current.end())
e4f3d6e9 2470 return essential && essential_;
677b8415 2471 else
e4f3d6e9 2472 return !version_.end() && version_ != current;
677b8415 2473 _end
36bb2ca2 2474}
3178d79b 2475
36bb2ca2 2476- (BOOL) essential {
a1440b10 2477 return essential_;
3178d79b
JF
2478}
2479
36bb2ca2 2480- (BOOL) broken {
9bedffaa
JF
2481 return [database_ cache][iterator_].InstBroken();
2482}
2483
7d2ac47f 2484- (BOOL) unfiltered {
4fa77608
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
e4f3d6e9
JF
2495 return true;
2496}
4fa77608 2497
e4f3d6e9
JF
2498- (BOOL) visible {
2499 if (![self unfiltered])
2500 return false;
2501
2502 NSString *section([self section]);
4fa77608 2503
e4f3d6e9 2504 _profile(Package$visible$isSectionVisible)
4fa77608
JF
2505 if (section != nil && !isSectionVisible(section))
2506 return false;
2507 _end
2508
2509 return true;
7d2ac47f
JF
2510}
2511
9bedffaa 2512- (BOOL) half {
677b8415 2513 unsigned char current(iterator_->CurrentState);
9bedffaa
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)
f79a4512 2536 return @"PURGE";
9bedffaa 2537 else
f79a4512 2538 return @"REMOVE";
9bedffaa 2539 case pkgDepCache::ModeKeep:
dc63e78f 2540 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
f79a4512 2541 return @"REINSTALL";
dc63e78f
JF
2542 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2543 return nil;*/
9bedffaa
JF
2544 else
2545 return nil;
9bedffaa 2546 case pkgDepCache::ModeInstall:
dc63e78f 2547 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
f79a4512 2548 return @"REINSTALL";
dc63e78f 2549 else*/ switch (state.Status) {
9bedffaa 2550 case -1:
f79a4512 2551 return @"DOWNGRADE";
9bedffaa 2552 case 0:
f79a4512 2553 return @"INSTALL";
9bedffaa 2554 case 1:
f79a4512 2555 return @"UPGRADE";
9bedffaa 2556 case 2:
f79a4512 2557 return @"NEW_INSTALL";
670a0494 2558 _nodefault
9bedffaa 2559 }
670a0494 2560 _nodefault
9bedffaa 2561 }
8fe19fc1
JF
2562}
2563
36bb2ca2
JF
2564- (NSString *) id {
2565 return id_;
8fe19fc1
JF
2566}
2567
36bb2ca2 2568- (NSString *) name {
9fcbca29 2569 return name_.empty() ? id_ : name_;
36bb2ca2 2570}
8fe19fc1 2571
770f2a8e 2572- (UIImage *) icon {
dec6029f 2573 NSString *section = [self simpleSection];
770f2a8e
JF
2574
2575 UIImage *icon(nil);
12016ee5
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]];
770f2a8e
JF
2581 if (icon == nil) if (section != nil)
2582 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
b9956841 2583 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
189a73d0 2584 if ([dicon hasPrefix:@"file:///"])
ac308d3e 2585 // XXX: correct escaping
189a73d0 2586 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
770f2a8e
JF
2587 if (icon == nil)
2588 icon = [UIImage applicationImageNamed:@"unknown.png"];
2589 return icon;
36bb2ca2 2590}
8fe19fc1 2591
6f1a15d9 2592- (NSString *) homepage {
12016ee5 2593 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
8fe19fc1
JF
2594}
2595
25a2158d 2596- (NSString *) depiction {
12016ee5 2597 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
25a2158d
JF
2598}
2599
795d26fc 2600- (Address *) sponsor {
12016ee5 2601 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
795d26fc
JF
2602}
2603
77fcccaf 2604- (Address *) author {
12016ee5 2605 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
77fcccaf
JF
2606}
2607
dc63e78f 2608- (NSString *) support {
12016ee5 2609 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
dc63e78f
JF
2610}
2611
affeffc7 2612- (NSArray *) files {
9fcbca29 2613 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
affeffc7
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
affeffc7
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:
43f3d7f6 2634 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
affeffc7
JF
2635 else for (size_t i(0); i != length; ++i)
2636 if (
9dd60d81
JF
2637 /* XXX: technically this is not allowed */
2638 (name[i] < 'A' || name[i] > 'Z') &&
affeffc7
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;
7623f855 2646 bool user = false;
9dd60d81 2647 bool _private = false;
affeffc7
JF
2648 bool stash = false;
2649
9dd60d81
JF
2650 bool repository = [[self section] isEqualToString:@"Repositories"];
2651
affeffc7
JF
2652 if (NSArray *files = [self files])
2653 for (NSString *file in files)
2654 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2655 cydia = true;
7623f855
JF
2656 else if (!user && [file isEqualToString:@"/User"])
2657 user = true;
9dd60d81
JF
2658 else if (!_private && [file isEqualToString:@"/private"])
2659 _private = true;
affeffc7
JF
2660 else if (!stash && [file isEqualToString:@"/var/stash"])
2661 stash = true;
2662
9dd60d81
JF
2663 /* XXX: this is not sensitive enough. only some folders are valid. */
2664 if (cydia && !repository)
43f3d7f6 2665 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
7623f855
JF
2666 if (user)
2667 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
9dd60d81 2668 if (_private)
43f3d7f6 2669 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
affeffc7 2670 if (stash)
43f3d7f6 2671 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
affeffc7
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
36bb2ca2 2712- (Source *) source {
5699667a 2713 if (source_ == nil) {
a1440b10
JF
2714 @synchronized (database_) {
2715 if ([database_ era] != era_ || file_.end())
5699667a
JF
2716 source_ = (Source *) [NSNull null];
2717 else
2718 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
a1440b10 2719 }
bbb879fb
JF
2720 }
2721
5699667a 2722 return source_ == (Source *) [NSNull null] ? nil : source_;
8fe19fc1
JF
2723}
2724
7b0ce2da
JF
2725- (NSString *) role {
2726 return role_;
2727}
2728
36bb2ca2
JF
2729- (BOOL) matches:(NSString *)text {
2730 if (text == nil)
2731 return NO;
8fe19fc1 2732
36bb2ca2 2733 NSRange range;
8fe19fc1 2734
808c6eb6 2735 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2
JF
2736 if (range.location != NSNotFound)
2737 return YES;
8fe19fc1 2738
808c6eb6 2739 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2
JF
2740 if (range.location != NSNotFound)
2741 return YES;
8fe19fc1 2742
01d93940 2743 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
36bb2ca2 2744 if (range.location != NSNotFound)
01d93940 2745 return YES;
8fe19fc1 2746
36bb2ca2
JF
2747 return NO;
2748}
8fe19fc1 2749
7b0ce2da
JF
2750- (bool) hasSupportingRole {
2751 if (role_ == nil)
6d9712c4 2752 return true;
7b0ce2da
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);
6d9712c4
JF
2766}
2767
2768- (BOOL) hasTag:(NSString *)tag {
2769 return tags_ == nil ? NO : [tags_ containsObject:tag];
2770}
2771
c390d3ab
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
770f2a8e
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
3bd1c2a2
JF
2787- (bool) isCommercial {
2788 return [self hasTag:@"cydia::commercial"];
2789}
2790
cd95e390
JF
2791- (void) setIndex:(size_t)index {
2792 if (metadata_->index_ != index)
2793 metadata_->index_ = index;
2794}
2795
df213583
JF
2796- (CYString &) cyname {
2797 return name_.empty() ? id_ : name_;
f79a4512
JF
2798}
2799
f79a4512
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;
36bb2ca2 2805 }
3178d79b 2806
f79a4512 2807 return _not(uint32_t);
36bb2ca2 2808}
3178d79b 2809
dc63e78f 2810- (void) clear {
c6ca67ba 2811@synchronized (database_) {
dc63e78f
JF
2812 pkgProblemResolver *resolver = [database_ resolver];
2813 resolver->Clear(iterator_);
c6ca67ba
JF
2814
2815 pkgCacheFile &cache([database_ cache]);
2816 cache->SetReInstall(iterator_, false);
2817 cache->MarkKeep(iterator_, false);
2818} }
dc63e78f 2819
36bb2ca2 2820- (void) install {
c6ca67ba 2821@synchronized (database_) {
36bb2ca2
JF
2822 pkgProblemResolver *resolver = [database_ resolver];
2823 resolver->Clear(iterator_);
2824 resolver->Protect(iterator_);
c6ca67ba 2825
36bb2ca2 2826 pkgCacheFile &cache([database_ cache]);
c6ca67ba 2827 cache->SetReInstall(iterator_, false);
36bb2ca2 2828 cache->MarkInstall(iterator_, false);
c6ca67ba 2829
36bb2ca2
JF
2830 pkgDepCache::StateCache &state((*cache)[iterator_]);
2831 if (!state.Install())
2832 cache->SetReInstall(iterator_, true);
c6ca67ba 2833} }
68a238ec 2834
36bb2ca2 2835- (void) remove {
c6ca67ba 2836@synchronized (database_) {
36bb2ca2
JF
2837 pkgProblemResolver *resolver = [database_ resolver];
2838 resolver->Clear(iterator_);
36bb2ca2 2839 resolver->Remove(iterator_);
c6ca67ba
JF
2840 resolver->Protect(iterator_);
2841
2842 pkgCacheFile &cache([database_ cache]);
2843 cache->SetReInstall(iterator_, false);
2844 cache->MarkDelete(iterator_, true);
2845} }
8fe19fc1 2846
0a3b45ef 2847- (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
808c6eb6
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
0a3b45ef 2859 return value;
808c6eb6 2860 _end
36bb2ca2 2861}
8fe19fc1 2862
01d93940 2863- (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
ef055c6c
JF
2864 if ([search length] == 0)
2865 return false;
2866
01d93940
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
e4f3d6e9
JF
2882- (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2883 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
36bb2ca2 2884}
8fe19fc1 2885
670a0494 2886- (bool) isVisibleInSection:(NSString *)name {
e4f3d6e9 2887 NSString *section([self section]);
5a09ae08 2888
e4f3d6e9
JF
2889 return (
2890 name == nil ||
2891 section == nil && [name length] == 0 ||
2892 [name isEqualToString:section]
2893 ) && [self visible];
7b0ce2da
JF
2894}
2895
0a3b45ef
JF
2896- (bool) isVisibleInSource:(Source *)source {
2897 return [self source] == source && [self visible];
36bb2ca2 2898}
8fe19fc1 2899
36bb2ca2
JF
2900@end
2901/* }}} */
2902/* Section Class {{{ */
2903@interface Section : NSObject {
2904 NSString *name_;
808c6eb6 2905 unichar index_;
36bb2ca2
JF
2906 size_t row_;
2907 size_t count_;
f79a4512 2908 NSString *localized_;
36bb2ca2 2909}
3178d79b 2910
677b8415 2911- (NSComparisonResult) compareByLocalized:(Section *)section;
9fcbca29
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;
808c6eb6 2915- (Section *) initWithIndex:(unichar)index row:(size_t)row;
36bb2ca2 2916- (NSString *) name;
808c6eb6 2917- (unichar) index;
f79a4512 2918
36bb2ca2
JF
2919- (size_t) row;
2920- (size_t) count;
f79a4512
JF
2921
2922- (void) addToRow;
36bb2ca2 2923- (void) addToCount;
b19871dd 2924
f79a4512 2925- (void) setCount:(size_t)count;
677b8415 2926- (NSString *) localized;
f79a4512 2927
36bb2ca2 2928@end
b19871dd 2929
36bb2ca2 2930@implementation Section
b19871dd 2931
36bb2ca2
JF
2932- (void) dealloc {
2933 [name_ release];
f79a4512
JF
2934 if (localized_ != nil)
2935 [localized_ release];
36bb2ca2
JF
2936 [super dealloc];
2937}
b19871dd 2938
677b8415 2939- (NSComparisonResult) compareByLocalized:(Section *)section {
9fcbca29
JF
2940 NSString *lhs(localized_);
2941 NSString *rhs([section localized]);
6d9712c4 2942
9fcbca29 2943 /*if ([lhs length] != 0 && [rhs length] != 0) {
6d9712c4
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;
9fcbca29 2951 }*/
6d9712c4 2952
68f1828e 2953 return [lhs compare:rhs options:LaxCompareOptions_];
6d9712c4
JF
2954}
2955
9fcbca29
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];
6d9712c4
JF
2965}
2966
9fcbca29 2967- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
36bb2ca2
JF
2968 if ((self = [super init]) != nil) {
2969 name_ = [name retain];
808c6eb6
JF
2970 index_ = '\0';
2971 row_ = row;
9fcbca29
JF
2972 if (localize)
2973 localized_ = [LocalizeSection(name_) retain];
808c6eb6
JF
2974 } return self;
2975}
2976
f79a4512 2977/* XXX: localize the index thingees */
808c6eb6
JF
2978- (Section *) initWithIndex:(unichar)index row:(size_t)row {
2979 if ((self = [super init]) != nil) {
327624b6 2980 name_ = [[NSString stringWithCharacters:&index length:1] retain];
808c6eb6 2981 index_ = index;
36bb2ca2 2982 row_ = row;
b19871dd
JF
2983 } return self;
2984}
2985
36bb2ca2
JF
2986- (NSString *) name {
2987 return name_;
2988}
2989
808c6eb6
JF
2990- (unichar) index {
2991 return index_;
2992}
2993
36bb2ca2
JF
2994- (size_t) row {
2995 return row_;
2996}
2997
2998- (size_t) count {
2999 return count_;
3000}
3001
f79a4512
JF
3002- (void) addToRow {
3003 ++row_;
3004}
3005
36bb2ca2
JF
3006- (void) addToCount {
3007 ++count_;
3008}
3009
f79a4512
JF
3010- (void) setCount:(size_t)count {
3011 count_ = count;
3012}
3013
3014- (NSString *) localized {
3015 return localized_;
3016}
3017
b19871dd
JF
3018@end
3019/* }}} */
3020
670a0494 3021static NSString *Colon_;
72fb3616 3022static NSString *Elision_;
670a0494
JF
3023static NSString *Error_;
3024static NSString *Warning_;
3025
36bb2ca2
JF
3026/* Database Implementation {{{ */
3027@implementation Database
ec97ef06 3028
770f2a8e
JF
3029+ (Database *) sharedInstance {
3030 static Database *instance;
3031 if (instance == nil)
3032 instance = [[Database alloc] init];
3033 return instance;
3034}
3035
a1440b10
JF
3036- (unsigned) era {
3037 return era_;
3038}
3039
0944377b
JF
3040- (void) releasePackages {
3041 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3042 CFArrayRemoveAllValues(packages_);
3043}
3044
36bb2ca2 3045- (void) dealloc {
3931b718 3046 // XXX: actually implement this thing
36bb2ca2 3047 _assert(false);
0944377b 3048 [self releasePackages];
f79a4512 3049 apr_pool_destroy(pool_);
0944377b 3050 NSRecycleZone(zone_);
36bb2ca2
JF
3051 [super dealloc];
3052}
ec97ef06 3053
affeffc7 3054- (void) _readCydia:(NSNumber *)fd { _pooled
77fcccaf
JF
3055 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3056 std::istream is(&ib);
3057 std::string line;
3058
bc8cd583
JF
3059 static Pcre finish_r("^finish:([^:]*)$");
3060
77fcccaf
JF
3061 while (std::getline(is, line)) {
3062 const char *data(line.c_str());
bc8cd583 3063 size_t size = line.size();
c390d3ab 3064 lprintf("C:%s\n", data);
bc8cd583
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 }
77fcccaf
JF
3072 }
3073
670a0494 3074 _assume(false);
77fcccaf
JF
3075}
3076
affeffc7 3077- (void) _readStatus:(NSNumber *)fd { _pooled
36bb2ca2
JF
3078 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3079 std::istream is(&ib);
3080 std::string line;
ec97ef06 3081
7b0ce2da
JF
3082 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3083 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
ec97ef06 3084
36bb2ca2
JF
3085 while (std::getline(is, line)) {
3086 const char *data(line.c_str());
670a0494 3087 size_t size(line.size());
c390d3ab 3088 lprintf("S:%s\n", data);
ec97ef06 3089
5a09ae08
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)];
36bb2ca2 3094 [delegate_ setProgressTitle:string];
5a09ae08 3095 } else if (pmstatus_r(data, size)) {
31f3cfff
JF
3096 std::string type([pmstatus_r[1] UTF8String]);
3097 NSString *id = pmstatus_r[2];
3098
5a09ae08
JF
3099 float percent([pmstatus_r[3] floatValue]);
3100 [delegate_ setProgressPercent:(percent / 100)];
3101
3102 NSString *string = pmstatus_r[4];
5a09ae08
JF
3103
3104 if (type == "pmerror")
670a0494 3105 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
31f3cfff
JF
3106 withObject:[NSArray arrayWithObjects:string, id, nil]
3107 waitUntilDone:YES
3108 ];
9487f027 3109 else if (type == "pmstatus") {
5a09ae08 3110 [delegate_ setProgressTitle:string];
9487f027 3111 } else if (type == "pmconffile")
5a09ae08 3112 [delegate_ setConfigurationData:string];
670a0494
JF
3113 else
3114 lprintf("E:unknown pmstatus\n");
3115 } else
3116 lprintf("E:unknown status\n");
36bb2ca2 3117 }
ec97ef06 3118
670a0494 3119 _assume(false);
36bb2ca2 3120}
ec97ef06 3121
affeffc7 3122- (void) _readOutput:(NSNumber *)fd { _pooled
36bb2ca2
JF
3123 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3124 std::istream is(&ib);
3125 std::string line;
3126
5a09ae08 3127 while (std::getline(is, line)) {
c390d3ab 3128 lprintf("O:%s\n", line.c_str());
2388b078 3129 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
5a09ae08 3130 }
36bb2ca2 3131
670a0494 3132 _assume(false);
ec97ef06
JF
3133}
3134
8b29f8e6
JF
3135- (FILE *) input {
3136 return input_;
3137}
3138
36bb2ca2 3139- (Package *) packageWithName:(NSString *)name {
3dd53516 3140@synchronized (self) {
5a09ae08
JF
3141 if (static_cast<pkgDepCache *>(cache_) == NULL)
3142 return nil;
36bb2ca2 3143 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
f79a4512 3144 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
28ce8704 3145} }
36bb2ca2 3146
eb30da80 3147- (id) init {
ec97ef06 3148 if ((self = [super init]) != nil) {
5a09ae08 3149 policy_ = NULL;
36bb2ca2
JF
3150 records_ = NULL;
3151 resolver_ = NULL;
3152 fetcher_ = NULL;
3153 lock_ = NULL;
ec97ef06 3154
f79a4512
JF
3155 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3156 apr_pool_create(&pool_, NULL);
3157
9f357d11
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);
ec97ef06 3165
36bb2ca2 3166 int fds[2];
ec97ef06 3167
77fcccaf
JF
3168 _assert(pipe(fds) != -1);
3169 cydiafd_ = fds[1];
3170
3171 _config->Set("APT::Keep-Fds::", cydiafd_);
bc8cd583 3172 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
77fcccaf
JF
3173
3174 [NSThread
3175 detachNewThreadSelector:@selector(_readCydia:)
3176 toTarget:self
3931b718 3177 withObject:[NSNumber numberWithInt:fds[0]]
77fcccaf
JF
3178 ];
3179
36bb2ca2
JF
3180 _assert(pipe(fds) != -1);
3181 statusfd_ = fds[1];
ec97ef06 3182
36bb2ca2
JF
3183 [NSThread
3184 detachNewThreadSelector:@selector(_readStatus:)
3185 toTarget:self
3931b718 3186 withObject:[NSNumber numberWithInt:fds[0]]
36bb2ca2 3187 ];
ec97ef06 3188
8b29f8e6
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
36bb2ca2
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
3931b718 3202 withObject:[NSNumber numberWithInt:fds[0]]
36bb2ca2 3203 ];
ec97ef06
JF
3204 } return self;
3205}
3206
36bb2ca2
JF
3207- (pkgCacheFile &) cache {
3208 return cache_;
ec97ef06
JF
3209}
3210
5a09ae08
JF
3211- (pkgDepCache::Policy *) policy {
3212 return policy_;
3213}
3214
36bb2ca2
JF
3215- (pkgRecords *) records {
3216 return records_;
ec97ef06
JF
3217}
3218
36bb2ca2
JF
3219- (pkgProblemResolver *) resolver {
3220 return resolver_;
ec97ef06
JF
3221}
3222
36bb2ca2
JF
3223- (pkgAcquire &) fetcher {
3224 return *fetcher_;
ec97ef06
JF
3225}
3226
a3328c28
JF
3227- (pkgSourceList &) list {
3228 return *list_;
3229}
3230
36bb2ca2 3231- (NSArray *) packages {
077e9d90 3232 return (NSArray *) packages_;
ec97ef06
JF
3233}
3234
7b0ce2da 3235- (NSArray *) sources {
68d927e2
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;
7b0ce2da
JF
3240}
3241
affeffc7
JF
3242- (NSArray *) issues {
3243 if (cache_->BrokenCount() == 0)
3244 return nil;
3245
3246 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3247
077e9d90 3248 for (Package *package in [self packages]) {
affeffc7
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
744f398e
JF
3275 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3276 if (Package *package = [self packageWithName:name])
3277 name = [package name];
3278 [failure addObject:name];
affeffc7
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
670a0494
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
ef348024 3330 if (fatal && !message.empty())
670a0494
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
53bed0ff 3340- (void) reloadData { CYPoolStart() {
3dd53516
JF
3341@synchronized (self) {
3342 ++era_;
a1440b10 3343
0944377b 3344 [self releasePackages];
843e75b8
JF
3345 sources_.clear();
3346
36bb2ca2 3347 _error->Discard();
5a09ae08 3348
36bb2ca2 3349 delete list_;
5a09ae08 3350 list_ = NULL;
36bb2ca2
JF
3351 manager_ = NULL;
3352 delete lock_;
5a09ae08 3353 lock_ = NULL;
36bb2ca2 3354 delete fetcher_;
5a09ae08 3355 fetcher_ = NULL;
36bb2ca2 3356 delete resolver_;
5a09ae08 3357 resolver_ = NULL;
36bb2ca2 3358 delete records_;
5a09ae08
JF
3359 records_ = NULL;
3360 delete policy_;
3361 policy_ = NULL;
36bb2ca2 3362
5a09ae08 3363 cache_.Close();
8b29f8e6 3364
f79a4512 3365 apr_pool_clear(pool_);
a020a50e 3366
f79a4512 3367 NSRecycleZone(zone_);
a020a50e 3368 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
f79a4512 3369
7376b55c
JF
3370 int chk(creat("/tmp/cydia.chk", 0644));
3371 if (chk != -1)
3372 close(chk);
3373
670a0494
JF
3374 NSString *title(UCLocalize("DATABASE"));
3375
9487f027 3376 _trace();
670a0494 3377 if (!cache_.Open(progress_, true)) { pop:
8b29f8e6 3378 std::string error;
670a0494 3379 bool warning(!_error->PopMessage(error));
c390d3ab 3380 lprintf("cache_.Open():[%s]\n", error.c_str());
5a09ae08
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)];
9ea8d159
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.")
670a0494
JF
3389 else
3390 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
5a09ae08 3391
670a0494
JF
3392 if (warning)
3393 goto pop;
3394 _error->Discard();
5a09ae08 3395 return;
36bb2ca2 3396 }
9487f027 3397 _trace();
36bb2ca2 3398
7376b55c
JF
3399 unlink("/tmp/cydia.chk");
3400
31bc18a7 3401 now_ = [[NSDate date] timeIntervalSince1970];
36bb2ca2 3402
5a09ae08 3403 policy_ = new pkgDepCache::Policy();
36bb2ca2
JF
3404 records_ = new pkgRecords(cache_);
3405 resolver_ = new pkgProblemResolver(cache_);
3406 fetcher_ = new pkgAcquire(&status_);
3407 lock_ = NULL;
3408
3409 list_ = new pkgSourceList();
670a0494
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 }
36bb2ca2 3417
670a0494
JF
3418 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3419 return;
9bedffaa
JF
3420
3421 if (cache_->BrokenCount() != 0) {
670a0494
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;
9bedffaa
JF
3432 }
3433
68d927e2
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())
f9f6d9e8 3441 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
68d927e2 3442 }
36bb2ca2 3443 }
68d927e2 3444
677b8415 3445 {
9fcbca29 3446 /*std::vector<Package *> packages;
677b8415 3447 packages.reserve(std::max(10000U, [packages_ count] + 1000));
677b8415 3448 [packages_ release];
9fcbca29
JF
3449 packages_ = nil;*/
3450
677b8415
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])
9fcbca29 3455 //packages.push_back(package);
077e9d90 3456 CFArrayAppendValue(packages_, [package retain]);
677b8415
JF
3457
3458 _trace();
3459
9fcbca29 3460 /*if (packages.empty())
677b8415
JF
3461 packages_ = [[NSArray alloc] init];
3462 else
3463 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
9fcbca29
JF
3464 _trace();*/
3465
077e9d90
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)];
9fcbca29
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
eef4ccaf
JF
3480 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3481
077e9d90 3482 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
9fcbca29
JF
3483
3484 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
677b8415
JF
3485
3486 _trace();
cd95e390
JF
3487
3488 size_t count(CFArrayGetCount(packages_));
9f357d11
JF
3489 MetaFile_->active_ = count;
3490
cd95e390
JF
3491 for (size_t index(0); index != count; ++index)
3492 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3493
3494 _trace();
677b8415 3495 }
c626a63f 3496} } CYPoolEnd() _trace(); }
ec97ef06 3497
c6ca67ba
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
5a09ae08
JF
3511- (void) configure {
3512 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3513 system([dpkg UTF8String]);
3514}
3515
670a0494
JF
3516- (bool) clean {
3517 // XXX: I don't remember this condition
77fcccaf 3518 if (lock_ != NULL)
670a0494 3519 return false;
77fcccaf
JF
3520
3521 FileFd Lock;
3522 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
670a0494
JF
3523
3524 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3525
3526 if ([self popErrorWithTitle:title])
3527 return false;
77fcccaf
JF
3528
3529 pkgAcquire fetcher;
3530 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3531
9bedffaa
JF
3532 class LogCleaner :
3533 public pkgArchiveCleaner
3534 {
77fcccaf
JF
3535 protected:
3536 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
9bedffaa 3537 unlink(File);
77fcccaf
JF
3538 }
3539 } cleaner;
3540
670a0494
JF
3541 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3542 return false;
3543
3544 return true;
77fcccaf
JF
3545}
3546
670a0494 3547- (bool) prepare {
744f398e
JF
3548 fetcher_->Shutdown();
3549
36bb2ca2
JF
3550 pkgRecords records(cache_);
3551
3552 lock_ = new FileFd();
3553 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
670a0494
JF
3554
3555 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3556
3557 if ([self popErrorWithTitle:title])
3558 return false;
36bb2ca2
JF
3559
3560 pkgSourceList list;
670a0494
JF
3561 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3562 return false;
36bb2ca2
JF
3563
3564 manager_ = (_system->CreatePM(cache_));
670a0494
JF
3565 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3566 return false;
3567
3568 return true;
ec97ef06
JF
3569}
3570
36bb2ca2 3571- (void) perform {
670a0494
JF
3572 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3573
a72074b2
JF
3574 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3575 pkgSourceList list;
670a0494
JF
3576 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3577 return;
a72074b2
JF
3578 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3579 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3580 }
a0be02eb 3581
eeb9b112
JF
3582 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3583 _trace();
36bb2ca2 3584 return;
eeb9b112
JF
3585 }
3586
54043703
JF
3587 [CydiaApp retainNetworkActivityIndicator];
3588
eeb9b112
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;
6204f56a
JF
3593 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3594 continue;
eeb9b112
JF
3595
3596 std::string uri = (*item)->DescURI();
3597 std::string error = (*item)->ErrorText;
3598
c390d3ab 3599 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
eeb9b112
JF
3600 failed = true;
3601
670a0494 3602 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
a3328c28
JF
3603 withObject:[NSArray arrayWithObjects:
3604 [NSString stringWithUTF8String:error.c_str()],
3605 nil]
eeb9b112
JF
3606 waitUntilDone:YES
3607 ];
3608 }
3609
54043703
JF
3610 [CydiaApp releaseNetworkActivityIndicator];
3611
eeb9b112
JF
3612 if (failed) {
3613 _trace();
3614 return;
3615 }
36bb2ca2
JF
3616
3617 _system->UnLock();
3618 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3619
eeb9b112
JF
3620 if (_error->PendingError()) {
3621 _trace();
36bb2ca2 3622 return;
eeb9b112
JF
3623 }
3624
3625 if (result == pkgPackageManager::Failed) {
3626 _trace();
36bb2ca2 3627 return;
eeb9b112
JF
3628 }
3629
3630 if (result != pkgPackageManager::Completed) {
3631 _trace();
36bb2ca2 3632 return;
eeb9b112 3633 }
a0be02eb 3634
a72074b2
JF
3635 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3636 pkgSourceList list;
670a0494
JF
3637 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3638 return;
a72074b2
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];
ec97ef06
JF
3645}
3646
670a0494
JF
3647- (bool) upgrade {
3648 NSString *title(UCLocalize("UPGRADE"));
3649 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3650 return false;
3651 return true;
c7c6384e
JF
3652}
3653
36bb2ca2
JF
3654- (void) update {
3655 [self updateWithStatus:status_];
3656}
b4d89997 3657
670a0494
JF
3658- (void) updateWithStatus:(Status &)status {
3659 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3660 NSString *title(UCLocalize("REFRESHING_DATA"));
3661
36bb2ca2 3662 pkgSourceList list;
670a0494
JF
3663 if (!list.ReadMainList())
3664 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
b4d89997 3665
36bb2ca2
JF
3666 FileFd lock;
3667 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
670a0494
JF
3668 if ([self popErrorWithTitle:title])
3669 return;
18873623 3670
670a0494 3671 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
eb30da80
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;
36bb2ca2 3674
7623f855
JF
3675 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3676 Changed_ = true;
b4d89997
JF
3677}
3678
36bb2ca2
JF
3679- (void) setDelegate:(id)delegate {
3680 delegate_ = delegate;
3681 status_.setDelegate(delegate);
3682 progress_.setDelegate(delegate);
3683}
b4d89997 3684
7376b55c 3685- (Source *) getSource:(pkgCache::PkgFileIterator)file {
20cb1497
JF
3686 SourceMap::const_iterator i(sources_.find(file->ID));
3687 return i == sources_.end() ? nil : i->second;
b19871dd
JF
3688}
3689
36bb2ca2
JF
3690@end
3691/* }}} */
b4d89997 3692
adb61bda 3693/* Confirmation Controller {{{ */
43f3d7f6
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;
c390d3ab 3707}
b5e7eebb 3708/* }}} */
c390d3ab 3709
43f3d7f6
JF
3710/* Web Scripting {{{ */
3711@interface CydiaObject : NSObject {
3712 id indirect_;
3931b718 3713 _transient id delegate_;
43f3d7f6 3714}
c390d3ab 3715
43f3d7f6 3716- (id) initWithDelegate:(IndirectDelegate *)indirect;
c390d3ab
JF
3717@end
3718
43f3d7f6 3719@implementation CydiaObject
c390d3ab
JF
3720
3721- (void) dealloc {
43f3d7f6 3722 [indirect_ release];
c390d3ab
JF
3723 [super dealloc];
3724}
3725
43f3d7f6
JF
3726- (id) initWithDelegate:(IndirectDelegate *)indirect {
3727 if ((self = [super init]) != nil) {
3728 indirect_ = [indirect retain];
3729 } return self;
3730}
3731
77801ff1
JF
3732- (void) setDelegate:(id)delegate {
3733 delegate_ = delegate;
3734}
3735
43f3d7f6
JF
3736+ (NSArray *) _attributeKeys {
3737 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3738}
3739
3740- (NSArray *) attributeKeys {
3741 return [[self class] _attributeKeys];
c390d3ab
JF
3742}
3743
43f3d7f6
JF
3744+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3745 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
c390d3ab 3746}
43f3d7f6
JF
3747
3748- (NSString *) device {
3749 return [[UIDevice currentDevice] uniqueIdentifier];
c390d3ab
JF
3750}
3751
43f3d7f6
JF
3752#if 0 // XXX: implement!
3753- (NSString *) mac {
3754 if (![indirect_ promptForSensitive:@"Mac Address"])
3755 return nil;
affeffc7
JF
3756}
3757
43f3d7f6
JF
3758- (NSString *) serial {
3759 if (![indirect_ promptForSensitive:@"Serial #"])
3760 return nil;
3761}
86316a91 3762
43f3d7f6
JF
3763- (NSString *) firewire {
3764 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3765 return nil;
affeffc7
JF
3766}
3767
43f3d7f6
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";
8cc8eb1c
JF
3777 else if (selector == @selector(getInstalledPackages))
3778 return @"getInstalledPackages";
43f3d7f6
JF
3779 else if (selector == @selector(getPackageById:))
3780 return @"getPackageById";
77801ff1
JF
3781 else if (selector == @selector(installPackages:))
3782 return @"installPackages";
43f3d7f6
JF
3783 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3784 return @"setButtonImage";
3785 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3786 return @"setButtonTitle";
43f3d7f6
JF
3787 else if (selector == @selector(setPopupHook:))
3788 return @"setPopupHook";
3789 else if (selector == @selector(setSpecial:))
3790 return @"setSpecial";
ef055c6c
JF
3791 else if (selector == @selector(setToken:))
3792 return @"setToken";
43f3d7f6
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";
c390d3ab 3805 else
43f3d7f6
JF
3806 return nil;
3807}
3808
3809+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3810 return [self webScriptNameForSelector:selector] == nil;
c390d3ab
JF
3811}
3812
43f3d7f6
JF
3813- (BOOL) supports:(NSString *)feature {
3814 return [feature isEqualToString:@"window.open"];
3815}
c390d3ab 3816
8cc8eb1c
JF
3817- (NSArray *) getInstalledPackages {
3818 NSArray *packages([[Database sharedInstance] packages]);
f4db946e 3819 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
77801ff1 3820 for (Package *package in packages)
8cc8eb1c
JF
3821 if ([package installed] != nil)
3822 [installed addObject:package];
3823 return installed;
3824}
3825
43f3d7f6 3826- (Package *) getPackageById:(NSString *)id {
043e6a2e
JF
3827 Package *package([[Database sharedInstance] packageWithName:id]);
3828 [package parse];
3829 return package;
43f3d7f6
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
77801ff1
JF
3893- (void) installPackages:(NSArray *)packages {
3894 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3895}
3896
43f3d7f6
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
ef055c6c
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
43f3d7f6
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];
eb30da80 3932 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
43f3d7f6
JF
3933}
3934
3935- (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
a95e0405
JF
3936 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3937 value = nil;
43f3d7f6
JF
3938 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3939 table = nil;
3940 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
c390d3ab
JF
3941}
3942
3943@end
3944/* }}} */
f79a4512 3945
80319240 3946/* Cydia Browser Controller {{{ */
40bfa2e6 3947@interface CYBrowserController : BrowserController {
43f3d7f6
JF
3948 CydiaObject *cydia_;
3949}
a9a0661e 3950
43f3d7f6
JF
3951@end
3952
b5e7eebb 3953@implementation CYBrowserController
43f3d7f6
JF
3954
3955- (void) dealloc {
3956 [cydia_ release];
3957 [super dealloc];
3958}
3959
01d93940
JF
3960- (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3961}
3962
2634b249
JF
3963- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3964 [super webView:view didClearWindowObject:window forFrame:frame];
01d93940
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
77801ff1
JF
3981 if (
3982 [host isEqualToString:@"cydia.saurik.com"] ||
3983 [host hasSuffix:@".cydia.saurik.com"] ||
3984 [scheme isEqualToString:@"file"]
3985 )
ef055c6c 3986 [window setValue:cydia_ forKey:@"cydia"];
43f3d7f6
JF
3987}
3988
bfc87a4d
JF
3989- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3990 if (System_ != NULL)
3991 [request setValue:System_ forHTTPHeaderField:@"X-System"];
43f3d7f6 3992 if (Machine_ != NULL)
bfc87a4d 3993 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
01d93940
JF
3994 if (Token_ != nil)
3995 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
43f3d7f6 3996 if (Role_ != nil)
bfc87a4d
JF
3997 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3998}
43f3d7f6 3999
2634b249
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]);
bfc87a4d 4002 [self _setMoreHeaders:copy];
43f3d7f6 4003 return copy;
a9a0661e
JF
4004}
4005
77801ff1
JF
4006- (void) setDelegate:(id)delegate {
4007 [super setDelegate:delegate];
4008 [cydia_ setDelegate:delegate];
4009}
4010
b5e7eebb 4011- (id) init {
6d166849 4012 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
43f3d7f6
JF
4013 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4014
2634b249 4015 WebView *webview([[webview_ _documentView] webView]);
43f3d7f6
JF
4016
4017 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
35bf217f 4018
43f3d7f6
JF
4019 NSString *application = package == nil ? @"Cydia" : [NSString
4020 stringWithFormat:@"Cydia/%@",
4021 [package installed]
4022 ];
4023
43f3d7f6 4024 if (Safari_ != nil)
9ef18597 4025 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
35bf217f 4026 if (Build_ != nil)
9ef18597 4027 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
35bf217f 4028 if (Product_ != nil)
9ef18597 4029 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
43f3d7f6
JF
4030
4031 [webview setApplicationNameForUserAgent:application];
4032 } return self;
4033}
4034
4035@end
80319240 4036/* }}} */
43f3d7f6 4037
80319240 4038/* Confirmation {{{ */
adb61bda 4039@protocol ConfirmationControllerDelegate
674dce72 4040- (void) cancelAndClear:(bool)clear;
b5e7eebb 4041- (void) confirmWithNavigationController:(UINavigationController *)navigation;
dc63e78f 4042- (void) queue;
36bb2ca2 4043@end
2367a917 4044
adb61bda 4045@interface ConfirmationController : CYBrowserController {
770f2a8e 4046 _transient Database *database_;
3272e699 4047 UIAlertView *essential_;
affeffc7
JF
4048 NSArray *changes_;
4049 NSArray *issues_;
4050 NSArray *sizes_;
a9a0661e 4051 BOOL substrate_;
36bb2ca2 4052}
dc5812ec 4053
b5e7eebb 4054- (id) initWithDatabase:(Database *)database;
b4d89997 4055
dc5812ec
JF
4056@end
4057
adb61bda 4058@implementation ConfirmationController
dc5812ec 4059
2367a917 4060- (void) dealloc {
affeffc7
JF
4061 [changes_ release];
4062 if (issues_ != nil)
4063 [issues_ release];
4064 [sizes_ release];
36bb2ca2
JF
4065 if (essential_ != nil)
4066 [essential_ release];
2367a917
JF
4067 [super dealloc];
4068}
4069
b5e7eebb 4070- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3272e699 4071 NSString *context([alert context]);
9bedffaa 4072
1cedb821 4073 if ([context isEqualToString:@"remove"]) {
b5e7eebb
GP
4074 if (button == [alert cancelButtonIndex]) {
4075 [self dismissModalViewControllerAnimated:YES];
3272e699 4076 } else if (button == [alert firstOtherButtonIndex]) {
b5e7eebb
GP
4077 if (substrate_)
4078 Finish_ = 2;
4079 [delegate_ confirmWithNavigationController:[self navigationController]];
9bedffaa 4080 }
9bedffaa 4081
3272e699 4082 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 4083 } else if ([context isEqualToString:@"unable"]) {
b5e7eebb 4084 [self dismissModalViewControllerAnimated:YES];
3272e699
GP
4085 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4086 } else {
b5e7eebb
GP
4087 [super alertView:alert clickedButtonAtIndex:button];
4088 }
36bb2ca2
JF
4089}
4090
46c46f4f 4091- (void) _doContinue {
21ea11a4
GP
4092 [self dismissModalViewControllerAnimated:YES];
4093 [delegate_ cancelAndClear:NO];
46c46f4f 4094}
bc11cf5b 4095
46c46f4f
JF
4096- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4097 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
21ea11a4
GP
4098 return nil;
4099}
4100
2634b249
JF
4101- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4102 [super webView:view didClearWindowObject:window forFrame:frame];
affeffc7
JF
4103 [window setValue:changes_ forKey:@"changes"];
4104 [window setValue:issues_ forKey:@"issues"];
4105 [window setValue:sizes_ forKey:@"sizes"];
21ea11a4 4106 [window setValue:self forKey:@"queue"];
36bb2ca2
JF
4107}
4108
b5e7eebb
GP
4109- (id) initWithDatabase:(Database *)database {
4110 if ((self = [super init]) != nil) {
770f2a8e
JF
4111 database_ = database;
4112
b5e7eebb
GP
4113 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4114
36bb2ca2
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];
dc5812ec 4120
36bb2ca2 4121 bool remove(false);
dc5812ec 4122
a9a0661e
JF
4123 pkgDepCache::Policy *policy([database_ policy]);
4124
36bb2ca2 4125 pkgCacheFile &cache([database_ cache]);
2388b078 4126 NSArray *packages = [database_ packages];
c4dcf2c2 4127 for (Package *package in packages) {
2388b078 4128 pkgCache::PkgIterator iterator = [package iterator];
36bb2ca2 4129 pkgDepCache::StateCache &state(cache[iterator]);
dc5812ec 4130
2388b078
JF
4131 NSString *name([package name]);
4132
36bb2ca2
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()) {
2388b078 4142 if ([package essential])
36bb2ca2
JF
4143 remove = true;
4144 [removing addObject:name];
a9a0661e
JF
4145 } else continue;
4146
4147 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4148 substrate_ |= DepSubstrate(iterator.CurrentVer());
36bb2ca2 4149 }
ec97ef06 4150
36bb2ca2
JF
4151 if (!remove)
4152 essential_ = nil;
d791dce4 4153 else if (Advanced_) {
43f3d7f6 4154 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
f79a4512 4155
3272e699 4156 essential_ = [[UIAlertView alloc]
43f3d7f6 4157 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
b5e7eebb
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 ];
04fe1349 4163
3272e699 4164 [essential_ setContext:@"remove"];
9bedffaa 4165 } else {
3272e699 4166 essential_ = [[UIAlertView alloc]
43f3d7f6 4167 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
b5e7eebb
GP
4168 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4169 delegate:self
4170 cancelButtonTitle:UCLocalize("OKAY")
4171 otherButtonTitles:nil
36bb2ca2 4172 ];
ec97ef06 4173
b5e7eebb 4174 [essential_ setContext:@"unable"];
36bb2ca2 4175 }
ec97ef06 4176
affeffc7
JF
4177 changes_ = [[NSArray alloc] initWithObjects:
4178 installing,
4179 reinstalling,
4180 upgrading,
4181 downgrading,
4182 removing,
4183 nil];
dc5812ec 4184
affeffc7
JF
4185 issues_ = [database_ issues];
4186 if (issues_ != nil)
4187 issues_ = [issues_ retain];
dc5812ec 4188
affeffc7
JF
4189 sizes_ = [[NSArray alloc] initWithObjects:
4190 SizeString([database_ fetcher].FetchNeeded()),
4191 SizeString([database_ fetcher].PartialPresent()),
affeffc7 4192 nil];
dc5812ec 4193
affeffc7 4194 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
04fe1349 4195
dd9de556 4196 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
21c6da4b
GP
4197 initWithTitle:UCLocalize("CANCEL")
4198 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
b5e7eebb
GP
4199 style:UIBarButtonItemStylePlain
4200 target:self
4201 action:@selector(cancelButtonClicked)
dd9de556 4202 ] autorelease]];
36bb2ca2 4203 } return self;
b4d89997 4204}
8da60fb7 4205
40bfa2e6 4206- (void) applyRightButton {
b5e7eebb 4207#if !AlwaysReload && !IgnoreInstall
dd9de556
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];
40bfa2e6 4217#else
bc11cf5b 4218 [[self navigationItem] setRightBarButtonItem:nil];
b5e7eebb 4219#endif
affeffc7
JF
4220}
4221
b5e7eebb 4222- (void) cancelButtonClicked {
21ea11a4
GP
4223 [self dismissModalViewControllerAnimated:YES];
4224 [delegate_ cancelAndClear:YES];
affeffc7
JF
4225}
4226
9487f027 4227#if !AlwaysReload
b5e7eebb 4228- (void) confirmButtonClicked {
b0ad8dee 4229#if IgnoreInstall
b5e7eebb 4230 return;
b0ad8dee 4231#endif
affeffc7 4232 if (essential_ != nil)
b5e7eebb 4233 [essential_ show];
affeffc7
JF
4234 else {
4235 if (substrate_)
4236 Finish_ = 2;
b5e7eebb 4237 [delegate_ confirmWithNavigationController:[self navigationController]];
affeffc7
JF
4238 }
4239}
9487f027 4240#endif
affeffc7 4241
36bb2ca2
JF
4242@end
4243/* }}} */
8da60fb7 4244
36bb2ca2
JF
4245/* Progress Data {{{ */
4246@interface ProgressData : NSObject {
4247 SEL selector_;
3931b718
JF
4248 // XXX: should these really both be _transient?
4249 _transient id target_;
4250 _transient id object_;
dc5812ec
JF
4251}
4252
36bb2ca2 4253- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
b4d89997 4254
36bb2ca2
JF
4255- (SEL) selector;
4256- (id) target;
4257- (id) object;
4258@end
b4d89997 4259
36bb2ca2 4260@implementation ProgressData
b4d89997 4261
36bb2ca2
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}
b4d89997 4269
36bb2ca2
JF
4270- (SEL) selector {
4271 return selector_;
4272}
b4d89997 4273
36bb2ca2
JF
4274- (id) target {
4275 return target_;
8da60fb7
JF
4276}
4277
36bb2ca2
JF
4278- (id) object {
4279 return object_;
dc5812ec
JF
4280}
4281
2367a917
JF
4282@end
4283/* }}} */
adb61bda
GP
4284/* Progress Controller {{{ */
4285@interface ProgressController : CYViewController <
8b29f8e6 4286 ConfigurationDelegate,
36bb2ca2
JF
4287 ProgressDelegate
4288> {
8b29f8e6 4289 _transient Database *database_;
36bb2ca2
JF
4290 UIProgressBar *progress_;
4291 UITextView *output_;
4292 UITextLabel *status_;
31f3cfff 4293 UIPushButton *close_;
bd150f54 4294 BOOL running_;
dddbc481 4295 SHA1SumValue springlist_;
22f8bed9 4296 SHA1SumValue notifyconf_;
670a0494 4297 NSString *title_;
2367a917
JF
4298}
4299
b5e7eebb 4300- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
2367a917 4301
36bb2ca2
JF
4302- (void) _retachThread;
4303- (void) _detachNewThreadData:(ProgressData *)data;
4304- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
2367a917 4305
bd150f54
JF
4306- (BOOL) isRunning;
4307
2367a917
JF
4308@end
4309
adb61bda
GP
4310@protocol ProgressControllerDelegate
4311- (void) progressControllerIsComplete:(ProgressController *)sender;
36bb2ca2
JF
4312@end
4313
adb61bda 4314@implementation ProgressController
2367a917
JF
4315
4316- (void) dealloc {
b5e7eebb 4317 [database_ setDelegate:nil];
36bb2ca2
JF
4318 [progress_ release];
4319 [output_ release];
4320 [status_ release];
31f3cfff 4321 [close_ release];
670a0494
JF
4322 if (title_ != nil)
4323 [title_ release];
2367a917
JF
4324 [super dealloc];
4325}
4326
b5e7eebb
GP
4327- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4328 if ((self = [super init]) != nil) {
8b29f8e6 4329 database_ = database;
b5e7eebb 4330 [database_ setDelegate:self];
36bb2ca2 4331 delegate_ = delegate;
ec97ef06 4332
c21004b9 4333 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
2367a917 4334
b5e7eebb 4335 progress_ = [[UIProgressBar alloc] init];
04fe1349 4336 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
31f3cfff 4337 [progress_ setStyle:0];
ec97ef06 4338
b5e7eebb 4339 status_ = [[UITextLabel alloc] init];
04fe1349 4340 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
baf80942
JF
4341 [status_ setColor:[UIColor whiteColor]];
4342 [status_ setBackgroundColor:[UIColor clearColor]];
36bb2ca2
JF
4343 [status_ setCentersHorizontally:YES];
4344 //[status_ setFont:font];
ec97ef06 4345
b5e7eebb 4346 output_ = [[UITextView alloc] init];
1d80f6b9 4347
04fe1349 4348 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
36bb2ca2 4349 //[output_ setTextFont:@"Courier New"];
d791dce4 4350 [output_ setFont:[[output_ font] fontWithSize:12]];
baf80942
JF
4351 [output_ setTextColor:[UIColor whiteColor]];
4352 [output_ setBackgroundColor:[UIColor clearColor]];
36bb2ca2
JF
4353 [output_ setMarginTop:0];
4354 [output_ setAllowsRubberBanding:YES];
795d26fc 4355 [output_ setEditable:NO];
b5e7eebb 4356 [[self view] addSubview:output_];
b4d89997 4357
b5e7eebb 4358 close_ = [[UIPushButton alloc] init];
04fe1349 4359 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
31f3cfff
JF
4360 [close_ setAutosizesToFit:NO];
4361 [close_ setDrawsShadow:YES];
4362 [close_ setStretchBackground:YES];
31f3cfff 4363 [close_ setEnabled:YES];
b5e7eebb 4364 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
bfc87a4d 4365 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
31f3cfff
JF
4366 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4367 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
36bb2ca2 4368 } return self;
2367a917
JF
4369}
4370
b5e7eebb
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,
534e31fc 4377 bounds.size.height - prgsize.height - 20
b5e7eebb 4378 }, prgsize};
bc11cf5b 4379
36fbb2aa 4380 float closewidth = std::min(bounds.size.width - 20, 300.0f);
b5e7eebb
GP
4381
4382 [progress_ setFrame:prgrect];
4383 [status_ setFrame:CGRectMake(
4384 10,
534e31fc 4385 bounds.size.height - prgsize.height - 50,
b5e7eebb
GP
4386 bounds.size.width - 20,
4387 24
4388 )];
4389 [output_ setFrame:CGRectMake(
4390 10,
4391 20,
4392 bounds.size.width - 20,
534e31fc 4393 bounds.size.height - 62
b5e7eebb
GP
4394 )];
4395 [close_ setFrame:CGRectMake(
4396 (bounds.size.width - closewidth) / 2,
534e31fc 4397 bounds.size.height - prgsize.height - 50,
b5e7eebb
GP
4398 closewidth,
4399 32 + prgsize.height
4400 )];
4401}
4402
4403- (void) viewWillAppear:(BOOL)animated {
4404 [super viewDidAppear:animated];
4405 [[self navigationItem] setHidesBackButton:YES];
c21004b9 4406 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
bc11cf5b 4407
b5e7eebb 4408 [self positionViews];
2367a917
JF
4409}
4410
b5e7eebb
GP
4411- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4412 [self positionViews];
2367a917
JF
4413}
4414
b5e7eebb 4415- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
969eaf2f 4416 NSString *context([alert context]);
bc8cd583 4417
670a0494 4418 if ([context isEqualToString:@"conffile"]) {
b5e7eebb 4419 FILE *input = [database_ input];
36fbb2aa
JF
4420 if (button == [alert cancelButtonIndex])
4421 fprintf(input, "N\n");
4422 else if (button == [alert firstOtherButtonIndex])
4423 fprintf(input, "Y\n");
b5e7eebb 4424 fflush(input);
670a0494
JF
4425 }
4426}
4427
4428- (void) closeButtonPushed {
4429 running_ = NO;
4430
ef494bd8
RP
4431 UpdateExternalStatus(0);
4432
670a0494
JF
4433 switch (Finish_) {
4434 case 0:
b5e7eebb 4435 [self dismissModalViewControllerAnimated:YES];
670a0494
JF
4436 break;
4437
4438 case 1:
c4899376
JF
4439 [delegate_ terminateWithSuccess];
4440 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4441 [delegate_ suspendWithAnimation:YES];
4442 else
4443 [delegate_ suspend];*/
670a0494
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;
bc8cd583 4457 }
670a0494 4458}
bd150f54 4459
670a0494 4460- (void) _retachThread {
b5e7eebb 4461 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
670a0494 4462
b5e7eebb 4463 [[self view] addSubview:close_];
670a0494
JF
4464 [progress_ removeFromSuperview];
4465 [status_ removeFromSuperview];
4466
4467 [database_ popErrorWithTitle:title_];
adb61bda 4468 [delegate_ progressControllerIsComplete:self];
c390d3ab 4469
22f8bed9 4470 if (Finish_ < 4) {
70d45c1e
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 }
22f8bed9
JF
4481 }
4482
affeffc7 4483 if (Finish_ < 3) {
70d45c1e
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 }
dddbc481
JF
4494 }
4495
bc8cd583 4496 switch (Finish_) {
b5e7eebb 4497 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
43f3d7f6
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;
bc8cd583
JF
4502 }
4503
58241d4c 4504 system("su -c /usr/bin/uicache mobile");
c4ce98df 4505
ef494bd8
RP
4506 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4507
bd150f54 4508 [delegate_ setStatusBarShowsProgress:NO];
31f3cfff
JF
4509}
4510
affeffc7 4511- (void) _detachNewThreadData:(ProgressData *)data { _pooled
36bb2ca2 4512 [[data target] performSelector:[data selector] withObject:[data object]];
36bb2ca2 4513 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
b19871dd
JF
4514}
4515
36bb2ca2 4516- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
ef494bd8
RP
4517 UpdateExternalStatus(1);
4518
670a0494
JF
4519 if (title_ != nil)
4520 [title_ release];
4521 if (title == nil)
4522 title_ = nil;
4523 else
4524 title_ = [title retain];
4525
b5e7eebb 4526 [[self navigationItem] setTitle:title_];
b4d89997 4527
36bb2ca2
JF
4528 [status_ setText:nil];
4529 [output_ setText:@""];
4530 [progress_ setProgress:0];
b19871dd 4531
31f3cfff 4532 [close_ removeFromSuperview];
b5e7eebb
GP
4533 [[self view] addSubview:progress_];
4534 [[self view] addSubview:status_];
31f3cfff 4535
bd150f54
JF
4536 [delegate_ setStatusBarShowsProgress:YES];
4537 running_ = YES;
4538
22f8bed9 4539 {
70d45c1e
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 }
22f8bed9
JF
4549 }
4550
affeffc7 4551 {
70d45c1e
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 }
dddbc481
JF
4561 }
4562
36bb2ca2
JF
4563 [NSThread
4564 detachNewThreadSelector:@selector(_detachNewThreadData:)
4565 toTarget:self
3931b718 4566 withObject:[[[ProgressData alloc]
36bb2ca2
JF
4567 initWithSelector:selector
4568 target:target
4569 object:object
3931b718 4570 ] autorelease]
36bb2ca2 4571 ];
b19871dd
JF
4572}
4573
5a09ae08
JF
4574- (void) repairWithSelector:(SEL)selector {
4575 [self
4576 detachNewThreadSelector:selector
4577 toTarget:database_
4578 withObject:nil
43f3d7f6 4579 title:UCLocalize("REPAIRING")
5a09ae08
JF
4580 ];
4581}
4582
8b29f8e6
JF
4583- (void) setConfigurationData:(NSString *)data {
4584 [self
4585 performSelectorOnMainThread:@selector(_setConfigurationData:)
4586 withObject:data
4587 waitUntilDone:YES
4588 ];
4589}
4590
670a0494
JF
4591- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4592 CYActionSheet *sheet([[[CYActionSheet alloc]
4593 initWithTitle:title
43f3d7f6 4594 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
31f3cfff 4595 defaultButtonIndex:0
670a0494 4596 ] autorelease]);
31f3cfff 4597
be2b3d7b 4598 [sheet setMessage:error];
670a0494
JF
4599 [sheet yieldToPopupAlertAnimated:YES];
4600 [sheet dismiss];
b19871dd
JF
4601}
4602
36bb2ca2
JF
4603- (void) setProgressTitle:(NSString *)title {
4604 [self
4605 performSelectorOnMainThread:@selector(_setProgressTitle:)
4606 withObject:title
4607 waitUntilDone:YES
4608 ];
b19871dd
JF
4609}
4610
36bb2ca2
JF
4611- (void) setProgressPercent:(float)percent {
4612 [self
4613 performSelectorOnMainThread:@selector(_setProgressPercent:)
4614 withObject:[NSNumber numberWithFloat:percent]
4615 waitUntilDone:YES
4616 ];
b19871dd
JF
4617}
4618
baf80942 4619- (void) startProgress {
baf80942
JF
4620}
4621
36bb2ca2
JF
4622- (void) addProgressOutput:(NSString *)output {
4623 [self
4624 performSelectorOnMainThread:@selector(_addProgressOutput:)
4625 withObject:output
4626 waitUntilDone:YES
4627 ];
b19871dd
JF
4628}
4629
baf80942 4630- (bool) isCancelling:(size_t)received {
baf80942
JF
4631 return false;
4632}
4633
8b29f8e6 4634- (void) _setConfigurationData:(NSString *)data {
7b0ce2da
JF
4635 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4636
670a0494
JF
4637 if (!conffile_r(data)) {
4638 lprintf("E:invalid conffile\n");
4639 return;
4640 }
8b29f8e6
JF
4641
4642 NSString *ofile = conffile_r[1];
4643 //NSString *nfile = conffile_r[2];
4644
969eaf2f 4645 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 4646 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
b5e7eebb
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"),
969eaf2f 4651 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
b5e7eebb
GP
4652 nil
4653 ] autorelease];
969eaf2f 4654
b5e7eebb 4655 [alert setContext:@"conffile"];
969eaf2f 4656 [alert show];
8b29f8e6
JF
4657}
4658
36bb2ca2 4659- (void) _setProgressTitle:(NSString *)title {
9487f027
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:@" "]];
b4d89997 4668}
b19871dd 4669
36bb2ca2
JF
4670- (void) _setProgressPercent:(NSNumber *)percent {
4671 [progress_ setProgress:[percent floatValue]];
49048579
JF
4672}
4673
36bb2ca2
JF
4674- (void) _addProgressOutput:(NSString *)output {
4675 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4676 CGSize size = [output_ contentSize];
773cfc9f
DH
4677 CGPoint offset = [output_ contentOffset];
4678 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4679 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4680 [output_ scrollRectToVisible:rect animated:YES];
4681 }
36bb2ca2 4682}
dc088e63 4683
bd150f54 4684- (BOOL) isRunning {
c4ce98df 4685 return running_;
bd150f54
JF
4686}
4687
36bb2ca2
JF
4688@end
4689/* }}} */
dc088e63 4690
46aa9775 4691/* Cell Content View {{{ */
c21004b9
JF
4692@protocol ContentDelegate
4693- (void) drawContentRect:(CGRect)rect;
4694@end
4695
327624b6 4696@interface ContentView : UIView {
c21004b9 4697 _transient id<ContentDelegate> delegate_;
327624b6
JF
4698}
4699
4700@end
4701
46aa9775 4702@implementation ContentView
555aaf71 4703
46aa9775
GP
4704- (id) initWithFrame:(CGRect)frame {
4705 if ((self = [super initWithFrame:frame]) != nil) {
46aa9775
GP
4706 [self setNeedsDisplayOnBoundsChange:YES];
4707 } return self;
4708}
4709
c21004b9 4710- (void) setDelegate:(id<ContentDelegate>)delegate {
46aa9775
GP
4711 delegate_ = delegate;
4712}
4713
4714- (void) drawRect:(CGRect)rect {
4715 [super drawRect:rect];
4716 [delegate_ drawContentRect:rect];
4717}
555aaf71
JF
4718
4719@end
4720/* }}} */
4721/* Cydia TableView Cell {{{ */
4722@interface CYTableViewCell : UITableViewCell {
4723 ContentView *content_;
4724 bool highlighted_;
4725}
4726
4727@end
4728
4729@implementation CYTableViewCell
4730
4731- (void) dealloc {
4732 [content_ release];
4733 [super dealloc];
4734}
4735
4736- (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4737 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4738
4739 if (view == content_) {
4740 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4741 highlighted_ = highlighted;
4742 }
4743
4744 [super _updateHighlightColorsForView:view highlighted:highlighted];
4745}
4746
4747- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4748 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4749 highlighted_ = selected;
4750
4751 [super setSelected:selected animated:animated];
4752 [content_ setNeedsDisplay];
4753}
4754
46aa9775
GP
4755@end
4756/* }}} */
4757/* Package Cell {{{ */
555aaf71 4758@interface PackageCell : CYTableViewCell <
c21004b9
JF
4759 ContentDelegate
4760> {
f641a0e5
JF
4761 UIImage *icon_;
4762 NSString *name_;
4763 NSString *description_;
3bd1c2a2 4764 bool commercial_;
f641a0e5 4765 NSString *source_;
c390d3ab 4766 UIImage *badge_;
dc63e78f 4767 Package *package_;
670a0494 4768 UIImage *placard_;
36bb2ca2 4769}
723a0072 4770
36bb2ca2
JF
4771- (PackageCell *) init;
4772- (void) setPackage:(Package *)package;
ec97ef06 4773
9bedffaa 4774+ (int) heightForPackage:(Package *)package;
327624b6
JF
4775- (void) drawContentRect:(CGRect)rect;
4776
4777@end
4778
36bb2ca2
JF
4779@implementation PackageCell
4780
f641a0e5
JF
4781- (void) clearPackage {
4782 if (icon_ != nil) {
4783 [icon_ release];
4784 icon_ = nil;
4785 }
4786
4787 if (name_ != nil) {
4788 [name_ release];
4789 name_ = nil;
4790 }
4791
4792 if (description_ != nil) {
4793 [description_ release];
4794 description_ = nil;
4795 }
4796
4797 if (source_ != nil) {
4798 [source_ release];
4799 source_ = nil;
4800 }
c390d3ab
JF
4801
4802 if (badge_ != nil) {
4803 [badge_ release];
4804 badge_ = nil;
4805 }
dc63e78f 4806
670a0494
JF
4807 if (placard_ != nil) {
4808 [placard_ release];
4809 placard_ = nil;
4810 }
4811
dc63e78f
JF
4812 [package_ release];
4813 package_ = nil;
f641a0e5
JF
4814}
4815
36bb2ca2 4816- (void) dealloc {
f641a0e5 4817 [self clearPackage];
36bb2ca2 4818 [super dealloc];
b4d89997 4819}
b19871dd 4820
36bb2ca2 4821- (PackageCell *) init {
327624b6
JF
4822 CGRect frame(CGRectMake(0, 0, 320, 74));
4823 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4824 UIView *content([self contentView]);
4825 CGRect bounds([content bounds]);
04fe1349 4826
327624b6 4827 content_ = [[ContentView alloc] initWithFrame:bounds];
04fe1349
JF
4828 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4829 [content addSubview:content_];
4830
327624b6 4831 [content_ setDelegate:self];
327624b6 4832 [content_ setOpaque:YES];
36bb2ca2 4833 } return self;
b4d89997 4834}
b19871dd 4835
327624b6
JF
4836- (void) _setBackgroundColor {
4837 UIColor *color;
4838 if (NSString *mode = [package_ mode]) {
4839 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4840 color = remove ? RemovingColor_ : InstallingColor_;
4841 } else
4842 color = [UIColor whiteColor];
4843
4844 [content_ setBackgroundColor:color];
4845 [self setNeedsDisplay];
4846}
4847
36bb2ca2 4848- (void) setPackage:(Package *)package {
46dbfd32 4849 [self clearPackage];
68d927e2 4850 [package parse];
31f3cfff 4851
36bb2ca2 4852 Source *source = [package source];
b19871dd 4853
770f2a8e 4854 icon_ = [[package icon] retain];
f641a0e5 4855 name_ = [[package name] retain];
ef055c6c
JF
4856
4857 if (IsWildcat_)
4858 description_ = [package longDescription];
4859 if (description_ == nil)
4860 description_ = [package shortDescription];
4861 if (description_ != nil)
4862 description_ = [description_ retain];
4863
3bd1c2a2 4864 commercial_ = [package isCommercial];
36bb2ca2 4865
dc63e78f
JF
4866 package_ = [package retain];
4867
a54b1c10
JF
4868 NSString *label = nil;
4869 bool trusted = false;
b19871dd 4870
36bb2ca2
JF
4871 if (source != nil) {
4872 label = [source label];
4873 trusted = [source trusted];
a54b1c10 4874 } else if ([[package id] isEqualToString:@"firmware"])
43f3d7f6 4875 label = UCLocalize("APPLE");
7b0ce2da 4876 else
43f3d7f6 4877 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
b19871dd 4878
f79a4512 4879 NSString *from(label);
a54b1c10 4880
f79a4512
JF
4881 NSString *section = [package simpleSection];
4882 if (section != nil && ![section isEqualToString:label]) {
4883 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
43f3d7f6 4884 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
f79a4512 4885 }
a54b1c10 4886
43f3d7f6 4887 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
f641a0e5 4888 source_ = [from retain];
36bb2ca2 4889
c390d3ab
JF
4890 if (NSString *purpose = [package primaryPurpose])
4891 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4892 badge_ = [badge_ retain];
4893
670a0494
JF
4894 if ([package installed] != nil)
4895 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4896 placard_ = [placard_ retain];
4897
327624b6
JF
4898 [self _setBackgroundColor];
4899 [content_ setNeedsDisplay];
3bd1c2a2
JF
4900}
4901
327624b6 4902- (void) drawContentRect:(CGRect)rect {
555aaf71 4903 bool highlighted(highlighted_);
ef055c6c 4904 float width([self bounds].size.width);
dc63e78f 4905
327624b6
JF
4906#if 0
4907 CGContextRef context(UIGraphicsGetCurrentContext());
4908 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4909 CGContextFillRect(context, rect);
4910#endif
b19871dd 4911
baf80942
JF
4912 if (icon_ != nil) {
4913 CGRect rect;
4914 rect.size = [icon_ size];
4915
4916 rect.size.width /= 2;
4917 rect.size.height /= 2;
4918
4919 rect.origin.x = 25 - rect.size.width / 2;
4920 rect.origin.y = 25 - rect.size.height / 2;
4921
4922 [icon_ drawInRect:rect];
4923 }
b19871dd 4924
c390d3ab 4925 if (badge_ != nil) {
f79c810d
JF
4926 CGRect rect;
4927 rect.size = [badge_ size];
4928
4929 rect.size.width /= 2;
4930 rect.size.height /= 2;
4931
4932 rect.origin.x = 36 - rect.size.width / 2;
4933 rect.origin.y = 36 - rect.size.height / 2;
c390d3ab 4934
f79c810d 4935 [badge_ drawInRect:rect];
c390d3ab
JF
4936 }
4937
555aaf71 4938 if (highlighted)
f641a0e5 4939 UISetColor(White_);
b19871dd 4940
555aaf71 4941 if (!highlighted)
3bd1c2a2 4942 UISetColor(commercial_ ? Purple_ : Black_);
54b844a0
DH
4943 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4944 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
b19871dd 4945
555aaf71 4946 if (!highlighted)
3bd1c2a2 4947 UISetColor(commercial_ ? Purplish_ : Gray_);
54b844a0 4948 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
670a0494
JF
4949
4950 if (placard_ != nil)
01d93940 4951 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
ec97ef06
JF
4952}
4953
9bedffaa 4954+ (int) heightForPackage:(Package *)package {
68d927e2 4955 return 73;
9bedffaa
JF
4956}
4957
8da60fb7
JF
4958@end
4959/* }}} */
36bb2ca2 4960/* Section Cell {{{ */
555aaf71 4961@interface SectionCell : CYTableViewCell <
c21004b9
JF
4962 ContentDelegate
4963> {
0010fa77 4964 NSString *basic_;
6d9712c4 4965 NSString *section_;
f641a0e5
JF
4966 NSString *name_;
4967 NSString *count_;
4968 UIImage *icon_;
68046ccc 4969 UISwitch *switch_;
6d9712c4 4970 BOOL editing_;
b4d89997 4971}
b19871dd 4972
6d9712c4 4973- (void) setSection:(Section *)section editing:(BOOL)editing;
36bb2ca2 4974
8da60fb7
JF
4975@end
4976
36bb2ca2 4977@implementation SectionCell
8da60fb7 4978
f641a0e5 4979- (void) clearSection {
0010fa77 4980 if (basic_ != nil) {
e59669fd 4981 [basic_ release];
0010fa77
JF
4982 basic_ = nil;
4983 }
4984
f641a0e5 4985 if (section_ != nil) {
6d9712c4 4986 [section_ release];
f641a0e5
JF
4987 section_ = nil;
4988 }
7b0ce2da 4989
f641a0e5
JF
4990 if (name_ != nil) {
4991 [name_ release];
4992 name_ = nil;
4993 }
7b0ce2da 4994
f641a0e5
JF
4995 if (count_ != nil) {
4996 [count_ release];
4997 count_ = nil;
4998 }
7b0ce2da
JF
4999}
5000
f641a0e5
JF
5001- (void) dealloc {
5002 [self clearSection];
5003 [icon_ release];
5004 [switch_ release];
5005 [super dealloc];
7b0ce2da
JF
5006}
5007
46aa9775
GP
5008- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5009 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
f641a0e5 5010 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
68046ccc 5011 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
46aa9775
GP
5012 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5013
5014 UIView *content([self contentView]);
5015 CGRect bounds([content bounds]);
5016
5017 content_ = [[ContentView alloc] initWithFrame:bounds];
5018 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5019 [content addSubview:content_];
5020 [content_ setBackgroundColor:[UIColor whiteColor]];
5021
5022 [content_ setDelegate:self];
b4d89997 5023 } return self;
b19871dd
JF
5024}
5025
6d9712c4 5026- (void) onSwitch:(id)sender {
a171abd4 5027 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6d9712c4
JF
5028 if (metadata == nil) {
5029 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
0010fa77 5030 [Sections_ setObject:metadata forKey:basic_];
6d9712c4
JF
5031 }
5032
46aa9775 5033 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
a171abd4 5034 Changed_ = true;
6d9712c4
JF
5035}
5036
5037- (void) setSection:(Section *)section editing:(BOOL)editing {
5038 if (editing != editing_) {
5039 if (editing_)
5040 [switch_ removeFromSuperview];
5041 else
5042 [self addSubview:switch_];
5043 editing_ = editing;
5044 }
5045
f641a0e5 5046 [self clearSection];
6d9712c4 5047
36bb2ca2 5048 if (section == nil) {
43f3d7f6 5049 name_ = [UCLocalize("ALL_PACKAGES") retain];
f641a0e5 5050 count_ = nil;
36bb2ca2 5051 } else {
e59669fd 5052 basic_ = [section name];
0010fa77
JF
5053 if (basic_ != nil)
5054 basic_ = [basic_ retain];
5055
677b8415 5056 section_ = [section localized];
6d9712c4
JF
5057 if (section_ != nil)
5058 section_ = [section_ retain];
0010fa77 5059
43f3d7f6 5060 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
f641a0e5 5061 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
6d9712c4
JF
5062
5063 if (editing_)
46aa9775 5064 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
36bb2ca2 5065 }
46aa9775 5066
c21004b9 5067 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
0abb648c
JF
5068 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5069
46aa9775 5070 [content_ setNeedsDisplay];
f641a0e5
JF
5071}
5072
77801ff1
JF
5073- (void) setFrame:(CGRect)frame {
5074 [super setFrame:frame];
46aa9775 5075
77801ff1
JF
5076 CGRect rect([switch_ frame]);
5077 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5078}
5079
46aa9775 5080- (void) drawContentRect:(CGRect)rect {
555aaf71 5081 bool highlighted(highlighted_);
bc11cf5b 5082
f641a0e5
JF
5083 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5084
555aaf71 5085 if (highlighted)
f641a0e5
JF
5086 UISetColor(White_);
5087
46aa9775 5088 float width(rect.size.width);
58241d4c 5089 if (editing_)
46aa9775 5090 width -= 87;
58241d4c 5091
555aaf71
JF
5092 if (!highlighted)
5093 UISetColor(Black_);
54b844a0 5094 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
6d9712c4 5095
f641a0e5
JF
5096 CGSize size = [count_ sizeWithFont:Font14_];
5097
5098 UISetColor(White_);
5099 if (count_ != nil)
c390d3ab 5100 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
b19871dd
JF
5101}
5102
36bb2ca2
JF
5103@end
5104/* }}} */
b19871dd 5105
ab398adf 5106/* File Table {{{ */
c21004b9
JF
5107@interface FileTable : CYViewController <
5108 UITableViewDataSource,
5109 UITableViewDelegate
5110> {
36bb2ca2 5111 _transient Database *database_;
ab398adf
JF
5112 Package *package_;
5113 NSString *name_;
5114 NSMutableArray *files_;
46aa9775 5115 UITableView *list_;
ab398adf 5116}
b19871dd 5117
b5e7eebb 5118- (id) initWithDatabase:(Database *)database;
ab398adf
JF
5119- (void) setPackage:(Package *)package;
5120
5121@end
5122
5123@implementation FileTable
5124
5125- (void) dealloc {
5126 if (package_ != nil)
5127 [package_ release];
5128 if (name_ != nil)
5129 [name_ release];
5130 [files_ release];
5131 [list_ release];
5132 [super dealloc];
5133}
5134
eb30da80 5135- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
ab398adf
JF
5136 return files_ == nil ? 0 : [files_ count];
5137}
5138
21ea11a4
GP
5139/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5140 return 24.0f;
5141}*/
ab398adf 5142
46aa9775 5143- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
GP
5144 static NSString *reuseIdentifier = @"Cell";
5145
46aa9775
GP
5146 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5147 if (cell == nil) {
5148 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5149 [cell setFont:[UIFont systemFontOfSize:16]];
ab398adf 5150 }
46aa9775 5151 [cell setText:[files_ objectAtIndex:indexPath.row]];
c21004b9 5152 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
b5e7eebb 5153
46aa9775 5154 return cell;
ab398adf 5155}
b19871dd 5156
b5e7eebb
GP
5157- (id) initWithDatabase:(Database *)database {
5158 if ((self = [super init]) != nil) {
ab398adf 5159 database_ = database;
b19871dd 5160
b5e7eebb
GP
5161 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5162
ab398adf 5163 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
8da60fb7 5164
46aa9775 5165 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
21ea11a4
GP
5166 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5167 [list_ setRowHeight:24.0f];
b5e7eebb 5168 [[self view] addSubview:list_];
ab398adf 5169
ab398adf 5170 [list_ setDataSource:self];
ab398adf 5171 [list_ setDelegate:self];
ab398adf
JF
5172 } return self;
5173}
5174
5175- (void) setPackage:(Package *)package {
5176 if (package_ != nil) {
5177 [package_ autorelease];
5178 package_ = nil;
5179 }
5180
5181 if (name_ != nil) {
5182 [name_ release];
5183 name_ = nil;
5184 }
5185
5186 [files_ removeAllObjects];
5187
5188 if (package != nil) {
5189 package_ = [package retain];
5190 name_ = [[package id] retain];
5191
affeffc7
JF
5192 if (NSArray *files = [package files])
5193 [files_ addObjectsFromArray:files];
ab398adf 5194
9ea8d159
JF
5195 if ([files_ count] != 0) {
5196 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5197 [files_ removeObjectAtIndex:0];
a54b1c10 5198 [files_ sortUsingSelector:@selector(compareByPath:)];
2388b078
JF
5199
5200 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5201 [stack addObject:@"/"];
5202
5203 for (int i(0), e([files_ count]); i != e; ++i) {
5204 NSString *file = [files_ objectAtIndex:i];
5205 while (![file hasPrefix:[stack lastObject]])
5206 [stack removeLastObject];
5207 NSString *directory = [stack lastObject];
5208 [stack addObject:[file stringByAppendingString:@"/"]];
5209 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
a54b1c10 5210 ([stack count] - 2) * 3, "",
2388b078
JF
5211 [file substringFromIndex:[directory length]]
5212 ]];
5213 }
ab398adf
JF
5214 }
5215 }
5216
5217 [list_ reloadData];
5218}
5219
ab398adf
JF
5220- (void) reloadData {
5221 [self setPackage:[database_ packageWithName:name_]];
ab398adf 5222}
b4d89997 5223
b4d89997 5224@end
36bb2ca2 5225/* }}} */
adb61bda 5226/* Package Controller {{{ */
9daa7f25
DH
5227@interface PackageController : CYBrowserController <
5228 UIActionSheetDelegate
5229> {
770f2a8e 5230 _transient Database *database_;
36bb2ca2
JF
5231 Package *package_;
5232 NSString *name_;
3bd1c2a2 5233 bool commercial_;
5a09ae08 5234 NSMutableArray *buttons_;
2634b249 5235 UIBarButtonItem *button_;
b31b87cc
JF
5236}
5237
b5e7eebb 5238- (id) initWithDatabase:(Database *)database;
36bb2ca2 5239- (void) setPackage:(Package *)package;
b4d89997 5240
36bb2ca2 5241@end
b4d89997 5242
adb61bda 5243@implementation PackageController
b4d89997 5244
36bb2ca2 5245- (void) dealloc {
36bb2ca2
JF
5246 if (package_ != nil)
5247 [package_ release];
5248 if (name_ != nil)
5249 [name_ release];
2634b249 5250
5a09ae08 5251 [buttons_ release];
2634b249
JF
5252
5253 if (button_ != nil)
5254 [button_ release];
5255
36bb2ca2
JF
5256 [super dealloc];
5257}
8da60fb7 5258
92d4a16a 5259- (void) release {
f79a4512 5260 if ([self retainCount] == 1)
adb61bda 5261 [delegate_ setPackageController:self];
f79a4512 5262 [super release];
92d4a16a 5263}
f79a4512
JF
5264
5265/* XXX: this is not safe at all... localization of /fail/ */
5a09ae08 5266- (void) _clickButtonWithName:(NSString *)name {
43f3d7f6 5267 if ([name isEqualToString:UCLocalize("CLEAR")])
dc63e78f 5268 [delegate_ clearPackage:package_];
43f3d7f6 5269 else if ([name isEqualToString:UCLocalize("INSTALL")])
5a09ae08 5270 [delegate_ installPackage:package_];
43f3d7f6 5271 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5a09ae08 5272 [delegate_ installPackage:package_];
43f3d7f6 5273 else if ([name isEqualToString:UCLocalize("REMOVE")])
5a09ae08 5274 [delegate_ removePackage:package_];
43f3d7f6 5275 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5a09ae08
JF
5276 [delegate_ installPackage:package_];
5277 else _assert(false);
5278}
5279
674dce72 5280- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
1cedb821 5281 NSString *context([sheet context]);
5a09ae08 5282
1cedb821 5283 if ([context isEqualToString:@"modify"]) {
674dce72
GP
5284 if (button != [sheet cancelButtonIndex]) {
5285 NSString *buttonName = [buttons_ objectAtIndex:button];
5286 [self _clickButtonWithName:buttonName];
5287 }
bc11cf5b 5288
674dce72 5289 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
674dce72 5290 }
b4d89997 5291}
2367a917 5292
2634b249
JF
5293- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5294 [super webView:view didClearWindowObject:window forFrame:frame];
f79a4512 5295 [window setValue:package_ forKey:@"package"];
6f1a15d9
JF
5296}
5297
3e9c9e85 5298- (bool) _allowJavaScriptPanel {
3bd1c2a2 5299 return commercial_;
3e9c9e85
JF
5300}
5301
9487f027 5302#if !AlwaysReload
9daa7f25 5303- (void) _customButtonClicked {
670a0494
JF
5304 int count([buttons_ count]);
5305 if (count == 0)
5306 return;
2367a917 5307
5a09ae08
JF
5308 if (count == 1)
5309 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5310 else {
674dce72 5311 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5a09ae08 5312 [buttons addObjectsFromArray:buttons_];
36bb2ca2 5313
674dce72 5314 UIActionSheet *sheet = [[[UIActionSheet alloc]
9ea8d159 5315 initWithTitle:nil
36bb2ca2 5316 delegate:self
674dce72
GP
5317 cancelButtonTitle:nil
5318 destructiveButtonTitle:nil
5319 otherButtonTitles:nil
5320 ] autorelease];
5321
5322 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5323 if (!IsWildcat_) {
5324 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5325 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5326 }
5327 [sheet setContext:@"modify"];
bc11cf5b 5328
b5e7eebb 5329 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
36bb2ca2 5330 }
b4d89997 5331}
12b59862 5332
a5938ea5
DH
5333// We don't want to allow non-commercial packages to do custom things to the install button,
5334// so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
9daa7f25 5335- (void) customButtonClicked {
a5938ea5
DH
5336 if (commercial_)
5337 [super customButtonClicked];
5338 else
9daa7f25 5339 [self _customButtonClicked];
12b59862 5340}
2e6c1426
GP
5341
5342- (void) reloadButtonClicked {
2fad210a
GP
5343 // Don't reload a package view by clicking the button.
5344}
5345
5346- (void) applyLoadingTitle {
5347 // Don't show "Loading" as the title. Ever.
2e6c1426 5348}
a5938ea5
DH
5349
5350- (UIBarButtonItem *) rightButton {
2634b249 5351 return button_;
a5938ea5 5352}
9487f027 5353#endif
2367a917 5354
b5e7eebb
GP
5355- (id) initWithDatabase:(Database *)database {
5356 if ((self = [super init]) != nil) {
36bb2ca2 5357 database_ = database;
5a09ae08 5358 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
f79a4512 5359 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
36bb2ca2 5360 } return self;
dc5812ec
JF
5361}
5362
36bb2ca2
JF
5363- (void) setPackage:(Package *)package {
5364 if (package_ != nil) {
5365 [package_ autorelease];
5366 package_ = nil;
5367 }
5368
5369 if (name_ != nil) {
5370 [name_ release];
5371 name_ = nil;
5372 }
5373
5a09ae08
JF
5374 [buttons_ removeAllObjects];
5375
36bb2ca2 5376 if (package != nil) {
68d927e2
JF
5377 [package parse];
5378
36bb2ca2
JF
5379 package_ = [package retain];
5380 name_ = [[package id] retain];
3bd1c2a2 5381 commercial_ = [package isCommercial];
36bb2ca2 5382
dc63e78f 5383 if ([package_ mode] != nil)
43f3d7f6 5384 [buttons_ addObject:UCLocalize("CLEAR")];
5a09ae08 5385 if ([package_ source] == nil);
31f3cfff 5386 else if ([package_ upgradableAndEssential:NO])
43f3d7f6 5387 [buttons_ addObject:UCLocalize("UPGRADE")];
6a155117 5388 else if ([package_ uninstalled])
43f3d7f6 5389 [buttons_ addObject:UCLocalize("INSTALL")];
5a09ae08 5390 else
43f3d7f6 5391 [buttons_ addObject:UCLocalize("REINSTALL")];
6a155117 5392 if (![package_ uninstalled])
43f3d7f6 5393 [buttons_ addObject:UCLocalize("REMOVE")];
2634b249 5394 }
f79a4512 5395
2634b249
JF
5396 if (button_ != nil)
5397 [button_ release];
f79a4512 5398
2634b249
JF
5399 NSString *title;
5400 switch ([buttons_ count]) {
5401 case 0: title = nil; break;
5402 case 1: title = [buttons_ objectAtIndex:0]; break;
5403 default: title = UCLocalize("MODIFY"); break;
36bb2ca2 5404 }
2634b249
JF
5405
5406 button_ = [[UIBarButtonItem alloc]
5407 initWithTitle:title
5408 style:UIBarButtonItemStylePlain
5409 target:self
5410 action:@selector(customButtonClicked)
5411 ];
56e88a25
JF
5412
5413 [self reloadURL];
b5e7eebb 5414}
f79a4512 5415
3bd1c2a2
JF
5416- (bool) isLoading {
5417 return commercial_ ? [super isLoading] : false;
9fe5e5f8
JF
5418}
5419
36bb2ca2
JF
5420- (void) reloadData {
5421 [self setPackage:[database_ packageWithName:name_]];
8fe19fc1
JF
5422}
5423
b4d89997
JF
5424@end
5425/* }}} */
b4d89997 5426/* Package Table {{{ */
c21004b9
JF
5427@interface PackageTable : UIView <
5428 UITableViewDataSource,
5429 UITableViewDelegate
5430> {
36bb2ca2 5431 _transient Database *database_;
0175295c 5432 unsigned era_;
36bb2ca2 5433 NSMutableArray *packages_;
b4d89997 5434 NSMutableArray *sections_;
327624b6
JF
5435 UITableView *list_;
5436 NSMutableArray *index_;
5437 NSMutableDictionary *indices_;
3931b718
JF
5438 // XXX: this target_ seems to be delegate_. :(
5439 _transient id target_;
b5e7eebb 5440 SEL action_;
3931b718
JF
5441 // XXX: why do we even have this delegate_?
5442 _transient id delegate_;
dc5812ec
JF
5443}
5444
b5e7eebb 5445- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
b4d89997
JF
5446
5447- (void) setDelegate:(id)delegate;
a0be02eb 5448
36bb2ca2 5449- (void) reloadData;
a0be02eb 5450- (void) resetCursor;
b4d89997 5451
327624b6 5452- (UITableView *) list;
2388b078 5453
ab398adf
JF
5454- (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5455
b5e7eebb
GP
5456- (void) deselectWithAnimation:(BOOL)animated;
5457
b4d89997
JF
5458@end
5459
5460@implementation PackageTable
5461
5462- (void) dealloc {
36bb2ca2 5463 [packages_ release];
b4d89997 5464 [sections_ release];
36bb2ca2 5465 [list_ release];
327624b6
JF
5466 [index_ release];
5467 [indices_ release];
b5e7eebb 5468
b4d89997 5469 [super dealloc];
8fe19fc1
JF
5470}
5471
327624b6
JF
5472- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5473 NSInteger count([sections_ count]);
5474 return count == 0 ? 1 : count;
b4d89997 5475}
2367a917 5476
327624b6
JF
5477- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5478 if ([sections_ count] == 0)
5479 return nil;
b4d89997
JF
5480 return [[sections_ objectAtIndex:section] name];
5481}
dc5812ec 5482
327624b6
JF
5483- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5484 if ([sections_ count] == 0)
5485 return 0;
5486 return [[sections_ objectAtIndex:section] count];
b4d89997 5487}
dc5812ec 5488
327624b6 5489- (Package *) packageAtIndexPath:(NSIndexPath *)path {
0175295c
JF
5490@synchronized (database_) {
5491 if ([database_ era] != era_)
5492 return nil;
5493
327624b6
JF
5494 Section *section([sections_ objectAtIndex:[path section]]);
5495 NSInteger row([path row]);
5496 Package *package([packages_ objectAtIndex:([section row] + row)]);
0175295c
JF
5497 return [[package retain] autorelease];
5498} }
dc5812ec 5499
327624b6 5500- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
c21004b9 5501 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
327624b6
JF
5502 if (cell == nil)
5503 cell = [[[PackageCell alloc] init] autorelease];
5504 [cell setPackage:[self packageAtIndexPath:path]];
5505 return cell;
b4d89997 5506}
dc5812ec 5507
b5e7eebb
GP
5508- (void) deselectWithAnimation:(BOOL)animated {
5509 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5510}
5511
21ea11a4 5512/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
327624b6 5513 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
21ea11a4 5514}*/
dc5812ec 5515
327624b6
JF
5516- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5517 Package *package([self packageAtIndexPath:path]);
59c6ae22 5518 package = [database_ packageWithName:[package id]];
b5e7eebb 5519 [target_ performSelector:action_ withObject:package];
327624b6
JF
5520 return path;
5521}
5522
5523- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5524 return [packages_ count] > 20 ? index_ : nil;
5525}
5526
5527- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5528 return index;
dc5812ec
JF
5529}
5530
b5e7eebb
GP
5531- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5532 if ((self = [super initWithFrame:frame]) != nil) {
36bb2ca2 5533 database_ = database;
b5e7eebb
GP
5534
5535 target_ = target;
5536 action_ = action;
36bb2ca2 5537
327624b6
JF
5538 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5539 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5540
36bb2ca2 5541 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
b4d89997 5542 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 5543
327624b6 5544 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
04fe1349 5545 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 5546 [list_ setRowHeight:73.0f];
04fe1349
JF
5547 [self addSubview:list_];
5548
b4d89997 5549 [list_ setDataSource:self];
327624b6 5550 [list_ setDelegate:self];
b4d89997 5551 } return self;
dc5812ec
JF
5552}
5553
5554- (void) setDelegate:(id)delegate {
2367a917 5555 delegate_ = delegate;
b4d89997
JF
5556}
5557
a3328c28
JF
5558- (bool) hasPackage:(Package *)package {
5559 return true;
a0be02eb
JF
5560}
5561
36bb2ca2 5562- (void) reloadData {
0175295c 5563 era_ = [database_ era];
36bb2ca2 5564 NSArray *packages = [database_ packages];
b4d89997 5565
36bb2ca2 5566 [packages_ removeAllObjects];
b4d89997
JF
5567 [sections_ removeAllObjects];
5568
808c6eb6 5569 _profile(PackageTable$reloadData$Filter)
c4dcf2c2 5570 for (Package *package in packages)
808c6eb6
JF
5571 if ([self hasPackage:package])
5572 [packages_ addObject:package];
808c6eb6 5573 _end
36bb2ca2 5574
327624b6
JF
5575 [index_ removeAllObjects];
5576 [indices_ removeAllObjects];
5577
b4d89997
JF
5578 Section *section = nil;
5579
808c6eb6 5580 _profile(PackageTable$reloadData$Section)
c4dcf2c2
JF
5581 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5582 Package *package;
5583 unichar index;
5584
5585 _profile(PackageTable$reloadData$Section$Package)
5586 package = [packages_ objectAtIndex:offset];
5587 index = [package index];
5588 _end
b4d89997 5589
808c6eb6
JF
5590 if (section == nil || [section index] != index) {
5591 _profile(PackageTable$reloadData$Section$Allocate)
5592 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5593 _end
b4d89997 5594
327624b6
JF
5595 [index_ addObject:[section name]];
5596 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5597
c4dcf2c2
JF
5598 _profile(PackageTable$reloadData$Section$Add)
5599 [sections_ addObject:section];
5600 _end
808c6eb6
JF
5601 }
5602
5603 [section addToCount];
5604 }
5605 _end
b4d89997 5606
c4dcf2c2
JF
5607 _profile(PackageTable$reloadData$List)
5608 [list_ reloadData];
5609 _end
b4d89997
JF
5610}
5611
a0be02eb 5612- (void) resetCursor {
327624b6 5613 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
a0be02eb
JF
5614}
5615
327624b6 5616- (UITableView *) list {
2388b078
JF
5617 return list_;
5618}
5619
ab398adf 5620- (void) setShouldHideHeaderInShortLists:(BOOL)hide {
327624b6 5621 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
ab398adf
JF
5622}
5623
a3328c28
JF
5624@end
5625/* }}} */
5626/* Filtered Package Table {{{ */
5627@interface FilteredPackageTable : PackageTable {
5628 SEL filter_;
76933519 5629 IMP imp_;
a3328c28
JF
5630 id object_;
5631}
5632
5633- (void) setObject:(id)object;
01d93940 5634- (void) setObject:(id)object forFilter:(SEL)filter;
a3328c28 5635
b5e7eebb 5636- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
a3328c28
JF
5637
5638@end
5639
5640@implementation FilteredPackageTable
5641
5642- (void) dealloc {
5643 if (object_ != nil)
5644 [object_ release];
5645 [super dealloc];
5646}
5647
01d93940
JF
5648- (void) setFilter:(SEL)filter {
5649 filter_ = filter;
5650
5651 /* XXX: this is an unsafe optimization of doomy hell */
5652 Method method(class_getInstanceMethod([Package class], filter));
5653 _assert(method != NULL);
5654 imp_ = method_getImplementation(method);
5655 _assert(imp_ != NULL);
5656}
5657
a3328c28
JF
5658- (void) setObject:(id)object {
5659 if (object_ != nil)
5660 [object_ release];
5661 if (object == nil)
5662 object_ = nil;
5663 else
5664 object_ = [object retain];
5665}
5666
01d93940
JF
5667- (void) setObject:(id)object forFilter:(SEL)filter {
5668 [self setFilter:filter];
5669 [self setObject:object];
01d93940
JF
5670}
5671
a3328c28 5672- (bool) hasPackage:(Package *)package {
76933519
JF
5673 _profile(FilteredPackageTable$hasPackage)
5674 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5675 _end
a3328c28
JF
5676}
5677
b5e7eebb
GP
5678- (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5679 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
01d93940 5680 [self setFilter:filter];
b5e7eebb 5681 object_ = [object retain];
189a73d0 5682 [self reloadData];
a3328c28
JF
5683 } return self;
5684}
5685
dc5812ec 5686@end
b4d89997 5687/* }}} */
dc5812ec 5688
adb61bda
GP
5689/* Filtered Package Controller {{{ */
5690@interface FilteredPackageController : CYViewController {
b5e7eebb
GP
5691 _transient Database *database_;
5692 FilteredPackageTable *packages_;
5693 NSString *title_;
5694}
5695
5696- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5697
5698@end
bc11cf5b 5699
adb61bda 5700@implementation FilteredPackageController
b5e7eebb
GP
5701
5702- (void) dealloc {
5703 [packages_ release];
5704 [title_ release];
bc11cf5b 5705
b5e7eebb
GP
5706 [super dealloc];
5707}
5708
5709- (void) viewDidAppear:(BOOL)animated {
5710 [super viewDidAppear:animated];
5711 [packages_ deselectWithAnimation:animated];
5712}
5713
5714- (void) didSelectPackage:(Package *)package {
adb61bda 5715 PackageController *view([delegate_ packageController]);
b5e7eebb
GP
5716 [view setPackage:package];
5717 [view setDelegate:delegate_];
5718 [[self navigationController] pushViewController:view animated:YES];
5719}
5720
eb30da80 5721- (NSString *) title { return title_; }
b5e7eebb
GP
5722
5723- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5724 if ((self = [super init]) != nil) {
5725 database_ = database;
5726 title_ = [title copy];
5727 [[self navigationItem] setTitle:title_];
5728
5729 packages_ = [[FilteredPackageTable alloc]
5730 initWithFrame:[[self view] bounds]
5731 database:database
5732 target:self
5733 action:@selector(didSelectPackage:)
5734 filter:filter
5735 with:object
5736 ];
5737
5738 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5739 [[self view] addSubview:packages_];
5740 } return self;
5741}
5742
5743- (void) reloadData {
5744 [packages_ reloadData];
5745}
5746
5747- (void) setDelegate:(id)delegate {
5748 [super setDelegate:delegate];
5749 [packages_ setDelegate:delegate];
5750}
5751
5752@end
bc11cf5b 5753
b5e7eebb
GP
5754/* }}} */
5755
adb61bda
GP
5756/* Add Source Controller {{{ */
5757@interface AddSourceController : CYViewController {
7b0ce2da 5758 _transient Database *database_;
dc5812ec
JF
5759}
5760
b5e7eebb 5761- (id) initWithDatabase:(Database *)database;
b4d89997 5762
7b0ce2da 5763@end
dc5812ec 5764
adb61bda 5765@implementation AddSourceController
dc5812ec 5766
b5e7eebb
GP
5767- (id) initWithDatabase:(Database *)database {
5768 if ((self = [super init]) != nil) {
7b0ce2da
JF
5769 database_ = database;
5770 } return self;
36bb2ca2 5771}
dc5812ec 5772
7b0ce2da
JF
5773@end
5774/* }}} */
5775/* Source Cell {{{ */
555aaf71 5776@interface SourceCell : CYTableViewCell <
c21004b9
JF
5777 ContentDelegate
5778> {
f641a0e5
JF
5779 UIImage *icon_;
5780 NSString *origin_;
5781 NSString *description_;
5782 NSString *label_;
b4d89997
JF
5783}
5784
46aa9775 5785- (void) setSource:(Source *)source;
b4d89997 5786
7b0ce2da 5787@end
b4d89997 5788
7b0ce2da 5789@implementation SourceCell
b4d89997 5790
46aa9775 5791- (void) clearSource {
f641a0e5 5792 [icon_ release];
7b0ce2da
JF
5793 [origin_ release];
5794 [description_ release];
5795 [label_ release];
46aa9775
GP
5796
5797 icon_ = nil;
5798 origin_ = nil;
5799 description_ = nil;
5800 label_ = nil;
5801}
5802
5803- (void) setSource:(Source *)source {
5804 [self clearSource];
bc11cf5b 5805
46aa9775
GP
5806 if (icon_ == nil)
5807 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5808 if (icon_ == nil)
5809 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5810 icon_ = [icon_ retain];
5811
5812 origin_ = [[source name] retain];
5813 label_ = [[source uri] retain];
5814 description_ = [[source description] retain];
5815
5816 [content_ setNeedsDisplay];
5817}
5818
5819- (void) dealloc {
5820 [self clearSource];
7b0ce2da 5821 [super dealloc];
36bb2ca2 5822}
b4d89997 5823
46aa9775
GP
5824- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5825 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5826 UIView *content([self contentView]);
5827 CGRect bounds([content bounds]);
5828
5829 content_ = [[ContentView alloc] initWithFrame:bounds];
5830 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5831 [content_ setBackgroundColor:[UIColor whiteColor]];
5832 [content addSubview:content_];
5833
5834 [content_ setDelegate:self];
5835 [content_ setOpaque:YES];
7b0ce2da 5836 } return self;
a0376fc1
JF
5837}
5838
46aa9775 5839- (void) drawContentRect:(CGRect)rect {
555aaf71 5840 bool highlighted(highlighted_);
01d93940
JF
5841 float width(rect.size.width);
5842
f641a0e5
JF
5843 if (icon_ != nil)
5844 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7b0ce2da 5845
555aaf71 5846 if (highlighted)
f641a0e5 5847 UISetColor(White_);
7b0ce2da 5848
555aaf71 5849 if (!highlighted)
f641a0e5 5850 UISetColor(Black_);
54b844a0 5851 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7b0ce2da 5852
555aaf71 5853 if (!highlighted)
f641a0e5 5854 UISetColor(Blue_);
54b844a0 5855 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7b0ce2da 5856
555aaf71 5857 if (!highlighted)
f641a0e5 5858 UISetColor(Gray_);
54b844a0 5859 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
7b0ce2da
JF
5860}
5861
5862@end
5863/* }}} */
5864/* Source Table {{{ */
c21004b9
JF
5865@interface SourceTable : CYViewController <
5866 UITableViewDataSource,
5867 UITableViewDelegate
5868> {
7b0ce2da 5869 _transient Database *database_;
46aa9775 5870 UITableView *list_;
7b0ce2da 5871 NSMutableArray *sources_;
7b0ce2da
JF
5872 int offset_;
5873
5874 NSString *href_;
5875 UIProgressHUD *hud_;
5876 NSError *error_;
5877
5878 //NSURLConnection *installer_;
42543928 5879 NSURLConnection *trivial_;
7b0ce2da
JF
5880 NSURLConnection *trivial_bz2_;
5881 NSURLConnection *trivial_gz_;
5882 //NSURLConnection *automatic_;
5883
42543928 5884 BOOL cydia_;
7b0ce2da
JF
5885}
5886
b5e7eebb 5887- (id) initWithDatabase:(Database *)database;
7b0ce2da 5888
c21004b9
JF
5889- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5890
7b0ce2da
JF
5891@end
5892
5893@implementation SourceTable
5894
3931b718 5895- (void) _releaseConnection:(NSURLConnection *)connection {
7b0ce2da
JF
5896 if (connection != nil) {
5897 [connection cancel];
5898 //[connection setDelegate:nil];
5899 [connection release];
5900 }
5901}
5902
5903- (void) dealloc {
7b0ce2da
JF
5904 if (href_ != nil)
5905 [href_ release];
5906 if (hud_ != nil)
5907 [hud_ release];
5908 if (error_ != nil)
5909 [error_ release];
5910
3931b718
JF
5911 //[self _releaseConnection:installer_];
5912 [self _releaseConnection:trivial_];
5913 [self _releaseConnection:trivial_gz_];
5914 [self _releaseConnection:trivial_bz2_];
5915 //[self _releaseConnection:automatic_];
7b0ce2da
JF
5916
5917 [sources_ release];
5918 [list_ release];
5919 [super dealloc];
5920}
5921
b5e7eebb
GP
5922- (void) viewDidAppear:(BOOL)animated {
5923 [super viewDidAppear:animated];
5924 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5925}
5926
eb30da80 5927- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7b0ce2da
JF
5928 return offset_ == 0 ? 1 : 2;
5929}
5930
eb30da80 5931- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7b0ce2da 5932 switch (section + (offset_ == 0 ? 1 : 0)) {
43f3d7f6
JF
5933 case 0: return UCLocalize("ENTERED_BY_USER");
5934 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7b0ce2da 5935
670a0494 5936 _nodefault
7b0ce2da
JF
5937 }
5938}
5939
eb30da80 5940- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
46aa9775
GP
5941 int count = [sources_ count];
5942 switch (section) {
5943 case 0: return (offset_ == 0 ? count : offset_);
5944 case 1: return count - offset_;
7b0ce2da 5945
b5e7eebb 5946 _nodefault
7b0ce2da
JF
5947 }
5948}
5949
46aa9775
GP
5950- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5951 unsigned idx = 0;
5952 switch (indexPath.section) {
5953 case 0: idx = indexPath.row; break;
5954 case 1: idx = indexPath.row + offset_; break;
5955
b5e7eebb 5956 _nodefault
46aa9775
GP
5957 }
5958 return [sources_ objectAtIndex:idx];
7b0ce2da
JF
5959}
5960
46aa9775
GP
5961- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5962 Source *source = [self sourceAtIndexPath:indexPath];
f641a0e5 5963 return [source description] == nil ? 56 : 73;
7b0ce2da
JF
5964}
5965
46aa9775 5966- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb 5967 static NSString *cellIdentifier = @"SourceCell";
7b0ce2da 5968
46aa9775 5969 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
b5e7eebb
GP
5970 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5971 [cell setSource:[self sourceAtIndexPath:indexPath]];
bc11cf5b 5972
46aa9775 5973 return cell;
7b0ce2da
JF
5974}
5975
c21004b9
JF
5976- (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5977 return UITableViewCellAccessoryDisclosureIndicator;
7b0ce2da
JF
5978}
5979
46aa9775
GP
5980- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5981 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da 5982
adb61bda 5983 FilteredPackageController *packages = [[[FilteredPackageController alloc]
b5e7eebb 5984 initWithDatabase:database_
7b0ce2da
JF
5985 title:[source label]
5986 filter:@selector(isVisibleInSource:)
5987 with:source
5988 ] autorelease];
5989
5990 [packages setDelegate:delegate_];
5991
b5e7eebb 5992 [[self navigationController] pushViewController:packages animated:YES];
7b0ce2da
JF
5993}
5994
46aa9775
GP
5995- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5996 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da
JF
5997 return [source record] != nil;
5998}
5999
46aa9775
GP
6000- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
6001 Source *source = [self sourceAtIndexPath:indexPath];
7b0ce2da
JF
6002 [Sources_ removeObjectForKey:[source key]];
6003 [delegate_ syncData];
6004}
6005
2fc76a2d
JF
6006- (void) complete {
6007 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6008 @"deb", @"Type",
6009 href_, @"URI",
6010 @"./", @"Distribution",
6011 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6012
6013 [delegate_ syncData];
6014}
6015
6016- (NSString *) getWarning {
3e9c9e85
JF
6017 NSString *href(href_);
6018 NSRange colon([href rangeOfString:@"://"]);
6019 if (colon.location != NSNotFound)
6020 href = [href substringFromIndex:(colon.location + 3)];
6021 href = [href stringByAddingPercentEscapes];
670a0494 6022 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
2fc76a2d
JF
6023 href = [href stringByCachingURLWithCurrentCDN];
6024
6025 NSURL *url([NSURL URLWithString:href]);
6026
6027 NSStringEncoding encoding;
6028 NSError *error(nil);
6029
6030 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6031 return [warning length] == 0 ? nil : warning;
6032 return nil;
6033}
6034
7b0ce2da 6035- (void) _endConnection:(NSURLConnection *)connection {
3931b718
JF
6036 // XXX: the memory management in this method is horribly awkward
6037
7b0ce2da 6038 NSURLConnection **field = NULL;
42543928
JF
6039 if (connection == trivial_)
6040 field = &trivial_;
6041 else if (connection == trivial_bz2_)
7b0ce2da
JF
6042 field = &trivial_bz2_;
6043 else if (connection == trivial_gz_)
6044 field = &trivial_gz_;
6045 _assert(field != NULL);
6046 [connection release];
6047 *field = nil;
6048
6049 if (
42543928 6050 trivial_ == nil &&
7b0ce2da
JF
6051 trivial_bz2_ == nil &&
6052 trivial_gz_ == nil
6053 ) {
3e9c9e85 6054 bool defer(false);
7b0ce2da 6055
42543928 6056 if (cydia_) {
2fc76a2d 6057 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
3e9c9e85
JF
6058 defer = true;
6059
0fe9a7e8 6060 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 6061 initWithTitle:UCLocalize("SOURCE_WARNING")
b5e7eebb
GP
6062 message:warning
6063 delegate:self
6064 cancelButtonTitle:UCLocalize("CANCEL")
0fe9a7e8 6065 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
2fc76a2d
JF
6066 ] autorelease];
6067
b5e7eebb 6068 [alert setContext:@"warning"];
0fe9a7e8
GP
6069 [alert setNumberOfRows:1];
6070 [alert show];
2fc76a2d
JF
6071 } else
6072 [self complete];
7b0ce2da 6073 } else if (error_ != nil) {
0fe9a7e8 6074 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 6075 initWithTitle:UCLocalize("VERIFICATION_ERROR")
b5e7eebb
GP
6076 message:[error_ localizedDescription]
6077 delegate:self
6078 cancelButtonTitle:UCLocalize("OK")
0fe9a7e8 6079 otherButtonTitles:nil
7b0ce2da
JF
6080 ] autorelease];
6081
b5e7eebb 6082 [alert setContext:@"urlerror"];
0fe9a7e8 6083 [alert show];
7b0ce2da 6084 } else {
0fe9a7e8 6085 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 6086 initWithTitle:UCLocalize("NOT_REPOSITORY")
b5e7eebb
GP
6087 message:UCLocalize("NOT_REPOSITORY_EX")
6088 delegate:self
6089 cancelButtonTitle:UCLocalize("OK")
0fe9a7e8 6090 otherButtonTitles:nil
7b0ce2da
JF
6091 ] autorelease];
6092
b5e7eebb 6093 [alert setContext:@"trivial"];
0fe9a7e8 6094 [alert show];
7b0ce2da
JF
6095 }
6096
3e9c9e85
JF
6097 [delegate_ setStatusBarShowsProgress:NO];
6098 [delegate_ removeProgressHUD:hud_];
6099
6100 [hud_ autorelease];
6101 hud_ = nil;
6102
6103 if (!defer) {
6104 [href_ release];
6105 href_ = nil;
6106 }
7b0ce2da
JF
6107
6108 if (error_ != nil) {
6109 [error_ release];
6110 error_ = nil;
6111 }
6112 }
6113}
6114
6115- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6116 switch ([response statusCode]) {
6117 case 200:
42543928 6118 cydia_ = YES;
7b0ce2da
JF
6119 }
6120}
6121
6122- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
c390d3ab 6123 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7b0ce2da
JF
6124 if (error_ != nil)
6125 error_ = [error retain];
6126 [self _endConnection:connection];
6127}
6128
6129- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6130 [self _endConnection:connection];
6131}
6132
eb30da80 6133- (NSString *) title { return UCLocalize("SOURCES"); }
b5e7eebb 6134
7b0ce2da
JF
6135- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6136 NSMutableURLRequest *request = [NSMutableURLRequest
6137 requestWithURL:[NSURL URLWithString:href]
6138 cachePolicy:NSURLRequestUseProtocolCachePolicy
77801ff1 6139 timeoutInterval:120.0
7b0ce2da
JF
6140 ];
6141
6142 [request setHTTPMethod:method];
6143
f79a4512
JF
6144 if (Machine_ != NULL)
6145 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
77801ff1
JF
6146 if (UniqueID_ != nil)
6147 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
f79a4512
JF
6148 if (Role_ != nil)
6149 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6150
7b0ce2da
JF
6151 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6152}
6153
0fe9a7e8
GP
6154- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6155 NSString *context([alert context]);
1cedb821
JF
6156
6157 if ([context isEqualToString:@"source"]) {
7b0ce2da
JF
6158 switch (button) {
6159 case 1: {
0fe9a7e8 6160 NSString *href = [[alert textField] text];
7b0ce2da
JF
6161
6162 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6163
6164 if (![href hasSuffix:@"/"])
6165 href_ = [href stringByAppendingString:@"/"];
6166 else
6167 href_ = href;
6168 href_ = [href_ retain];
6169
42543928 6170 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7b0ce2da
JF
6171 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6172 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6173 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6174
42543928 6175 cydia_ = false;
7b0ce2da 6176
3931b718 6177 // XXX: this is stupid
d061f4ba 6178 hud_ = [[delegate_ addProgressHUD] retain];
43f3d7f6 6179 [hud_ setText:UCLocalize("VERIFYING_URL")];
7b0ce2da
JF
6180 } break;
6181
0fe9a7e8 6182 case 0:
7b0ce2da
JF
6183 break;
6184
670a0494 6185 _nodefault
7b0ce2da
JF
6186 }
6187
0fe9a7e8 6188 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b49f4c92 6189 } else if ([context isEqualToString:@"trivial"])
0fe9a7e8 6190 [alert dismissWithClickedButtonIndex:-1 animated:YES];
b49f4c92 6191 else if ([context isEqualToString:@"urlerror"])
0fe9a7e8 6192 [alert dismissWithClickedButtonIndex:-1 animated:YES];
2fc76a2d
JF
6193 else if ([context isEqualToString:@"warning"]) {
6194 switch (button) {
6195 case 1:
6196 [self complete];
6197 break;
6198
0fe9a7e8 6199 case 0:
2fc76a2d
JF
6200 break;
6201
670a0494 6202 _nodefault
2fc76a2d
JF
6203 }
6204
3e9c9e85
JF
6205 [href_ release];
6206 href_ = nil;
6207
0fe9a7e8 6208 [alert dismissWithClickedButtonIndex:-1 animated:YES];
2fc76a2d 6209 }
7b0ce2da
JF
6210}
6211
b5e7eebb
GP
6212- (id) initWithDatabase:(Database *)database {
6213 if ((self = [super init]) != nil) {
6214 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6215 [self updateButtonsForEditingStatus:NO animated:NO];
bc11cf5b 6216
7b0ce2da
JF
6217 database_ = database;
6218 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6219
b5e7eebb 6220 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 6221 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b5e7eebb 6222 [[self view] addSubview:list_];
04fe1349 6223
7b0ce2da 6224 [list_ setDataSource:self];
46aa9775 6225 [list_ setDelegate:self];
7b0ce2da
JF
6226
6227 [self reloadData];
6228 } return self;
6229}
6230
6231- (void) reloadData {
6232 pkgSourceList list;
670a0494
JF
6233 if (!list.ReadMainList())
6234 return;
7b0ce2da
JF
6235
6236 [sources_ removeAllObjects];
6237 [sources_ addObjectsFromArray:[database_ sources]];
807ae6d7 6238 _trace();
7b0ce2da 6239 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
807ae6d7 6240 _trace();
7b0ce2da 6241
36fbb2aa 6242 int count([sources_ count]);
46aa9775
GP
6243 offset_ = 0;
6244 for (int i = 0; i != count; i++) {
36fbb2aa
JF
6245 if ([[sources_ objectAtIndex:i] record] == nil)
6246 break;
6247 offset_++;
7b0ce2da
JF
6248 }
6249
46aa9775 6250 [list_ setEditing:NO];
b5e7eebb 6251 [self updateButtonsForEditingStatus:NO animated:NO];
7b0ce2da
JF
6252 [list_ reloadData];
6253}
6254
b5e7eebb 6255- (void) addButtonClicked {
adb61bda 6256 /*[book_ pushPage:[[[AddSourceController alloc]
7b0ce2da
JF
6257 initWithBook:book_
6258 database:database_
6259 ] autorelease]];*/
6260
0fe9a7e8 6261 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 6262 initWithTitle:UCLocalize("ENTER_APT_URL")
b5e7eebb
GP
6263 message:nil
6264 delegate:self
6265 cancelButtonTitle:UCLocalize("CANCEL")
6266 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7b0ce2da
JF
6267 ] autorelease];
6268
b5e7eebb
GP
6269 [alert setContext:@"source"];
6270 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
1cedb821 6271
0fe9a7e8
GP
6272 [alert setNumberOfRows:1];
6273 [alert addTextFieldWithValue:@"http://" label:@""];
7b0ce2da 6274
0fe9a7e8 6275 UITextInputTraits *traits = [[alert textField] textInputTraits];
b49f4c92
JF
6276 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6277 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
1cedb821 6278 [traits setKeyboardType:UIKeyboardTypeURL];
b49f4c92
JF
6279 // XXX: UIReturnKeyDone
6280 [traits setReturnKeyType:UIReturnKeyNext];
7b0ce2da 6281
0fe9a7e8 6282 [alert show];
7b0ce2da
JF
6283}
6284
b5e7eebb 6285- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
dd9de556 6286 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
b5e7eebb
GP
6287 initWithTitle:UCLocalize("ADD")
6288 style:UIBarButtonItemStylePlain
6289 target:self
6290 action:@selector(addButtonClicked)
dd9de556 6291 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
b5e7eebb 6292
dd9de556
JF
6293 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6294 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6295 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
b5e7eebb
GP
6296 target:self
6297 action:@selector(editButtonClicked)
dd9de556 6298 ] autorelease] animated:animated];
bc11cf5b 6299
dd9de556
JF
6300 if (IsWildcat_ && !editing)
6301 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
2bdd73bd
GP
6302 initWithTitle:UCLocalize("SETTINGS")
6303 style:UIBarButtonItemStylePlain
6304 target:self
6305 action:@selector(settingsButtonClicked)
dd9de556 6306 ] autorelease]];
2bdd73bd
GP
6307}
6308
6309- (void) settingsButtonClicked {
6310 [delegate_ showSettings];
7b0ce2da
JF
6311}
6312
b5e7eebb
GP
6313- (void) editButtonClicked {
6314 [list_ setEditing:![list_ isEditing] animated:YES];
bc11cf5b 6315
b5e7eebb 6316 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
7b0ce2da
JF
6317}
6318
6319@end
6320/* }}} */
6321
adb61bda
GP
6322/* Installed Controller {{{ */
6323@interface InstalledController : FilteredPackageController {
f641a0e5 6324 BOOL expert_;
7b0ce2da
JF
6325}
6326
b5e7eebb 6327- (id) initWithDatabase:(Database *)database;
7b0ce2da 6328
c21004b9
JF
6329- (void) updateRoleButton;
6330- (void) queueStatusDidChange;
6331
7b0ce2da
JF
6332@end
6333
adb61bda 6334@implementation InstalledController
7b0ce2da
JF
6335
6336- (void) dealloc {
7b0ce2da
JF
6337 [super dealloc];
6338}
6339
eb30da80 6340- (NSString *) title { return UCLocalize("INSTALLED"); }
baf80942 6341
b5e7eebb 6342- (id) initWithDatabase:(Database *)database {
e4f3d6e9 6343 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
b5e7eebb
GP
6344 [self updateRoleButton];
6345 [self queueStatusDidChange];
7b0ce2da
JF
6346 } return self;
6347}
6348
b5e7eebb
GP
6349#if !AlwaysReload
6350- (void) queueButtonClicked {
6351 [delegate_ queue];
7b0ce2da 6352}
b5e7eebb 6353#endif
7b0ce2da 6354
b5e7eebb
GP
6355- (void) queueStatusDidChange {
6356#if !AlwaysReload
6357 if (IsWildcat_) {
dd9de556
JF
6358 if (Queuing_) {
6359 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6360 initWithTitle:UCLocalize("QUEUE")
6361 style:UIBarButtonItemStyleDone
6362 target:self
6363 action:@selector(queueButtonClicked)
6364 ] autorelease]];
6365 } else {
6366 [[self navigationItem] setLeftBarButtonItem:nil];
6367 }
b5e7eebb
GP
6368 }
6369#endif
f641a0e5
JF
6370}
6371
b5e7eebb
GP
6372- (void) reloadData {
6373 [packages_ reloadData];
7b0ce2da
JF
6374}
6375
b5e7eebb 6376- (void) updateRoleButton {
dd9de556
JF
6377 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6378 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6379 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6380 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6381 target:self
6382 action:@selector(roleButtonClicked)
6383 ] autorelease]];
7b0ce2da
JF
6384}
6385
b5e7eebb
GP
6386- (void) roleButtonClicked {
6387 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6388 [packages_ reloadData];
6389 expert_ = !expert_;
f641a0e5 6390
b5e7eebb 6391 [self updateRoleButton];
f641a0e5
JF
6392}
6393
7b0ce2da
JF
6394- (void) setDelegate:(id)delegate {
6395 [super setDelegate:delegate];
6396 [packages_ setDelegate:delegate];
6397}
6398
6399@end
6400/* }}} */
6401
adb61bda
GP
6402/* Home Controller {{{ */
6403@interface HomeController : CYBrowserController {
7b0ce2da
JF
6404}
6405
6406@end
6407
adb61bda 6408@implementation HomeController
7b0ce2da 6409
bfc87a4d
JF
6410- (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6411 [super _setMoreHeaders:request];
526ea480 6412
bfc87a4d
JF
6413 if (ChipID_ != nil)
6414 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
01d93940
JF
6415 if (UniqueID_ != nil)
6416 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
567e3972
JF
6417 if (PLMN_ != nil)
6418 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
bfc87a4d
JF
6419}
6420
b5e7eebb 6421- (void) aboutButtonClicked {
526ea480
JF
6422 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6423
65c27c56
JF
6424 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6425 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6426 [alert setCancelButtonIndex:0];
7b0ce2da 6427
65c27c56 6428 [alert setMessage:
77801ff1 6429 @"Copyright (C) 2008-2010\n"
7b0ce2da
JF
6430 "Jay Freeman (saurik)\n"
6431 "saurik@saurik.com\n"
42fc47f8 6432 "http://www.saurik.com/"
7b0ce2da
JF
6433 ];
6434
65c27c56 6435 [alert show];
7b0ce2da
JF
6436}
6437
b5e7eebb
GP
6438- (void) viewWillAppear:(BOOL)animated {
6439 [super viewWillAppear:animated];
2411bceb 6440 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
b5e7eebb
GP
6441}
6442
6443- (void) viewWillDisappear:(BOOL)animated {
6444 [super viewWillDisappear:animated];
2411bceb 6445 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
b5e7eebb
GP
6446}
6447
6448- (id) init {
6449 if ((self = [super init]) != nil) {
526ea480 6450 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
b5e7eebb
GP
6451 initWithTitle:UCLocalize("ABOUT")
6452 style:UIBarButtonItemStylePlain
6453 target:self
6454 action:@selector(aboutButtonClicked)
526ea480 6455 ] autorelease]];
b5e7eebb 6456 } return self;
7b0ce2da
JF
6457}
6458
6459@end
98228790 6460/* }}} */
adb61bda
GP
6461/* Manage Controller {{{ */
6462@interface ManageController : CYBrowserController {
7b0ce2da
JF
6463}
6464
c21004b9 6465- (void) queueStatusDidChange;
7b0ce2da
JF
6466@end
6467
adb61bda 6468@implementation ManageController
7b0ce2da 6469
b5e7eebb
GP
6470- (id) init {
6471 if ((self = [super init]) != nil) {
6472 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
bc11cf5b 6473
dd9de556 6474 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
b5e7eebb
GP
6475 initWithTitle:UCLocalize("SETTINGS")
6476 style:UIBarButtonItemStylePlain
6477 target:self
6478 action:@selector(settingsButtonClicked)
dd9de556 6479 ] autorelease]];
bc11cf5b 6480
b5e7eebb
GP
6481 [self queueStatusDidChange];
6482 } return self;
7b0ce2da
JF
6483}
6484
b5e7eebb 6485- (void) settingsButtonClicked {
21c6da4b 6486 [delegate_ showSettings];
7b0ce2da
JF
6487}
6488
bf8476c8 6489#if !AlwaysReload
b5e7eebb
GP
6490- (void) queueButtonClicked {
6491 [delegate_ queue];
dc63e78f
JF
6492}
6493
eb97a3a8
GP
6494- (void) applyLoadingTitle {
6495 // No "Loading" title.
6496}
6497
6498- (void) applyRightButton {
6499 // No right button.
dc63e78f 6500}
eb97a3a8 6501#endif
dc63e78f 6502
b5e7eebb
GP
6503- (void) queueStatusDidChange {
6504#if !AlwaysReload
6505 if (!IsWildcat_ && Queuing_) {
dd9de556 6506 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
b5e7eebb
GP
6507 initWithTitle:UCLocalize("QUEUE")
6508 style:UIBarButtonItemStyleDone
6509 target:self
6510 action:@selector(queueButtonClicked)
dd9de556 6511 ] autorelease]];
b5e7eebb
GP
6512 } else {
6513 [[self navigationItem] setRightBarButtonItem:nil];
6514 }
bf8476c8 6515#endif
b5e7eebb 6516}
7b0ce2da 6517
3bd1c2a2 6518- (bool) isLoading {
9fe5e5f8
JF
6519 return false;
6520}
6521
7b0ce2da 6522@end
98228790 6523/* }}} */
7b0ce2da 6524
b5e7eebb
GP
6525/* Refresh Bar {{{ */
6526@interface RefreshBar : UINavigationBar {
7b0ce2da
JF
6527 UIProgressIndicator *indicator_;
6528 UITextLabel *prompt_;
6529 UIProgressBar *progress_;
baf80942 6530 UINavigationButton *cancel_;
aa5e5990
JF
6531}
6532
aa5e5990 6533@end
aa5e5990 6534
b5e7eebb 6535@implementation RefreshBar
01d93940 6536
3931b718
JF
6537- (void) dealloc {
6538 [indicator_ release];
6539 [prompt_ release];
6540 [progress_ release];
6541 [cancel_ release];
6542 [super dealloc];
6543}
6544
39cda3a8
GP
6545- (void) positionViews {
6546 CGRect frame = [cancel_ frame];
64523317 6547 frame.size = [cancel_ sizeThatFits:frame.size];
39cda3a8
GP
6548 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6549 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6550 [cancel_ setFrame:frame];
bc11cf5b 6551
39cda3a8
GP
6552 CGSize prgsize = {75, 100};
6553 CGRect prgrect = {{
6554 [self frame].size.width - prgsize.width - 10,
6555 ([self frame].size.height - prgsize.height) / 2
6556 } , prgsize};
6557 [progress_ setFrame:prgrect];
bc11cf5b 6558
39cda3a8
GP
6559 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6560 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6561 CGRect indrect = {{indoffset, indoffset}, indsize};
6562 [indicator_ setFrame:indrect];
bc11cf5b 6563
39cda3a8
GP
6564 CGSize prmsize = {215, indsize.height + 4};
6565 CGRect prmrect = {{
6566 indoffset * 2 + indsize.width,
6567 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6568 }, prmsize};
6569 [prompt_ setFrame:prmrect];
6570}
6571
6572- (void)setFrame:(CGRect)frame {
6573 [super setFrame:frame];
bc11cf5b 6574
39cda3a8
GP
6575 [self positionViews];
6576}
6577
b5e7eebb
GP
6578- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6579 if ((self = [super initWithFrame:frame])) {
6580 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
01d93940 6581
c21004b9 6582 [self setBarStyle:UIBarStyleBlack];
01d93940 6583
c21004b9
JF
6584 UIBarStyle barstyle([self _barStyle:NO]);
6585 bool ugly(barstyle == UIBarStyleDefault);
807ae6d7
JF
6586
6587 UIProgressIndicatorStyle style = ugly ?
6588 UIProgressIndicatorStyleMediumBrown :
6589 UIProgressIndicatorStyleMediumWhite;
6590
39cda3a8 6591 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
807ae6d7 6592 [indicator_ setStyle:style];
39cda3a8 6593 [indicator_ startAnimation];
b5e7eebb 6594 [self addSubview:indicator_];
807ae6d7 6595
39cda3a8 6596 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
807ae6d7
JF
6597 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6598 [prompt_ setBackgroundColor:[UIColor clearColor]];
39cda3a8 6599 [prompt_ setFont:[UIFont systemFontOfSize:15]];
b5e7eebb 6600 [self addSubview:prompt_];
807ae6d7 6601
39cda3a8
GP
6602 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6603 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
04fe1349 6604 [progress_ setStyle:0];
39cda3a8 6605 [self addSubview:progress_];
bc11cf5b 6606
43f3d7f6 6607 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
8c02abc8 6608 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
b5e7eebb 6609 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
39cda3a8 6610 [cancel_ setBarStyle:barstyle];
bc11cf5b 6611
39cda3a8 6612 [self positionViews];
807ae6d7
JF
6613 } return self;
6614}
6615
b5e7eebb 6616- (void) cancel {
807ae6d7
JF
6617 [cancel_ removeFromSuperview];
6618}
6619
b5e7eebb
GP
6620- (void) start {
6621 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6622 [progress_ setProgress:0];
6623 [self addSubview:cancel_];
6624}
6625
6626- (void) stop {
6627 [cancel_ removeFromSuperview];
6628}
6629
6630- (void) setPrompt:(NSString *)prompt {
6631 [prompt_ setText:prompt];
6632}
6633
6634- (void) setProgress:(float)progress {
6635 [progress_ setProgress:progress];
6636}
6637
6638@end
6639/* }}} */
6640
c21004b9
JF
6641@class CYNavigationController;
6642
b5e7eebb 6643/* Cydia Tab Bar Controller {{{ */
7585ce66
JF
6644@interface CYTabBarController : UITabBarController <
6645 ProgressDelegate
6646> {
3931b718 6647 _transient Database *database_;
7585ce66
JF
6648 RefreshBar *refreshbar_;
6649
6650 bool dropped_;
6651 bool updating_;
6652 // XXX: ok, "updatedelegate_"?...
6653 _transient NSObject<CydiaDelegate> *updatedelegate_;
6654
6655 id root_;
b5e7eebb
GP
6656}
6657
7585ce66
JF
6658- (void) dropBar:(BOOL)animated;
6659- (void) beginUpdate;
6660- (void) raiseBar:(BOOL)animated;
6661- (BOOL) updating;
6662
bc11cf5b 6663@end
b5e7eebb
GP
6664
6665@implementation CYTabBarController
6666
8c02abc8
GP
6667/* XXX: some logic should probably go here related to
6668freeing the view controllers on tab change */
807ae6d7 6669
b5e7eebb
GP
6670- (void) reloadData {
6671 size_t count([[self viewControllers] count]);
6672 for (size_t i(0); i != count; ++i) {
c21004b9 6673 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
b5e7eebb
GP
6674 [page reloadData];
6675 }
6676}
6677
14d60a3f 6678- (id) initWithDatabase:(Database *)database {
b5e7eebb
GP
6679 if ((self = [super init]) != nil) {
6680 database_ = database;
7585ce66
JF
6681
6682 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6683 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6684
6685 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
b5e7eebb
GP
6686 } return self;
6687}
6688
7585ce66 6689- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
0175295c 6690 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7585ce66
JF
6691}
6692
6693- (void) setUpdate:(NSDate *)date {
6694 [self beginUpdate];
6695}
6696
6697- (void) beginUpdate {
7585ce66 6698 [refreshbar_ start];
54043703 6699 [self dropBar:YES];
7585ce66 6700
54043703 6701 [updatedelegate_ retainNetworkActivityIndicator];
7585ce66
JF
6702 updating_ = true;
6703
6704 [NSThread
6705 detachNewThreadSelector:@selector(performUpdate)
6706 toTarget:self
6707 withObject:nil
6708 ];
6709}
6710
6711- (void) performUpdate { _pooled
6712 Status status;
6713 status.setDelegate(self);
6714 [database_ updateWithStatus:status];
6715
6716 [self
6717 performSelectorOnMainThread:@selector(completeUpdate)
6718 withObject:nil
6719 waitUntilDone:NO
6720 ];
6721}
6722
54043703 6723- (void) stopUpdateWithSelector:(SEL)selector {
7585ce66 6724 updating_ = false;
54043703 6725 [updatedelegate_ releaseNetworkActivityIndicator];
7585ce66
JF
6726
6727 [self raiseBar:YES];
6728 [refreshbar_ stop];
54043703
JF
6729
6730 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6731}
6732
6733- (void) completeUpdate {
6734 if (!updating_)
6735 return;
6736 [self stopUpdateWithSelector:@selector(reloadData)];
7585ce66
JF
6737}
6738
6739- (void) cancelUpdate {
54043703 6740 [self stopUpdateWithSelector:@selector(updateData)];
7585ce66
JF
6741}
6742
6743- (void) cancelPressed {
6744 [self cancelUpdate];
6745}
6746
6747- (BOOL) updating {
6748 return updating_;
6749}
6750
6751- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6752 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6753}
6754
6755- (void) startProgress {
6756}
6757
6758- (void) setProgressTitle:(NSString *)title {
6759 [self
6760 performSelectorOnMainThread:@selector(_setProgressTitle:)
6761 withObject:title
6762 waitUntilDone:YES
6763 ];
6764}
6765
6766- (bool) isCancelling:(size_t)received {
6767 return !updating_;
6768}
6769
6770- (void) setProgressPercent:(float)percent {
6771 [self
6772 performSelectorOnMainThread:@selector(_setProgressPercent:)
6773 withObject:[NSNumber numberWithFloat:percent]
6774 waitUntilDone:YES
6775 ];
6776}
6777
6778- (void) addProgressOutput:(NSString *)output {
6779 [self
6780 performSelectorOnMainThread:@selector(_addProgressOutput:)
6781 withObject:output
6782 waitUntilDone:YES
6783 ];
6784}
6785
6786- (void) _setProgressTitle:(NSString *)title {
6787 [refreshbar_ setPrompt:title];
6788}
6789
6790- (void) _setProgressPercent:(NSNumber *)percent {
6791 [refreshbar_ setProgress:[percent floatValue]];
6792}
6793
6794- (void) _addProgressOutput:(NSString *)output {
6795}
6796
6797- (void) setUpdateDelegate:(id)delegate {
6798 updatedelegate_ = delegate;
6799}
6800
6801- (CGFloat) statusBarHeight {
6802 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6803 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6804 } else {
6805 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6806 }
6807}
6808
6809- (UIView *) transitionView {
6810 if ([self respondsToSelector:@selector(_transitionView)])
6811 return [self _transitionView];
6812 else
6813 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6814}
6815
6816- (void) dropBar:(BOOL)animated {
6817 if (dropped_)
6818 return;
6819 dropped_ = true;
6820
6821 UIView *transition([self transitionView]);
6822 [[self view] addSubview:refreshbar_];
6823
6824 CGRect barframe([refreshbar_ frame]);
6825
6826 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6827 barframe.origin.y = [self statusBarHeight];
6828 else
6829 barframe.origin.y = 0;
6830
6831 [refreshbar_ setFrame:barframe];
6832
6833 if (animated)
6834 [UIView beginAnimations:nil context:NULL];
6835
6836 CGRect viewframe = [transition frame];
6837 viewframe.origin.y += barframe.size.height;
6838 viewframe.size.height -= barframe.size.height;
6839 [transition setFrame:viewframe];
6840
6841 if (animated)
6842 [UIView commitAnimations];
6843
6844 // Ensure bar has the proper width for our view, it might have changed
6845 barframe.size.width = viewframe.size.width;
6846 [refreshbar_ setFrame:barframe];
6847
6848 // XXX: fix Apple's layout bug
6849 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6850}
6851
6852- (void) raiseBar:(BOOL)animated {
6853 if (!dropped_)
6854 return;
6855 dropped_ = false;
6856
6857 UIView *transition([self transitionView]);
6858 [refreshbar_ removeFromSuperview];
6859
6860 CGRect barframe([refreshbar_ frame]);
6861
6862 if (animated)
6863 [UIView beginAnimations:nil context:NULL];
6864
6865 CGRect viewframe = [transition frame];
6866 viewframe.origin.y -= barframe.size.height;
6867 viewframe.size.height += barframe.size.height;
6868 [transition setFrame:viewframe];
6869
6870 if (animated)
6871 [UIView commitAnimations];
6872
6873 // XXX: fix Apple's layout bug
6874 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6875}
6876
6877#if 0
6878- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6879 // XXX: fix Apple's layout bug
6880 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6881}
6882#endif
6883
6884- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6885 bool dropped(dropped_);
6886
6887 if (dropped)
6888 [self raiseBar:NO];
6889
6890 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6891
6892 if (dropped)
6893 [self dropBar:NO];
6894
6895 // XXX: fix Apple's layout bug
6896 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6897}
6898
6899- (void) statusBarFrameChanged:(NSNotification *)notification {
6900 if (dropped_) {
6901 [self raiseBar:NO];
6902 [self dropBar:NO];
6903 }
6904}
6905
6906- (void) dealloc {
6907 [refreshbar_ release];
6908 [[NSNotificationCenter defaultCenter] removeObserver:self];
6909 [super dealloc];
6910}
6911
b5e7eebb
GP
6912@end
6913/* }}} */
6914
6915/* Cydia Navigation Controller {{{ */
c21004b9 6916@interface CYNavigationController : UINavigationController {
b5e7eebb 6917 _transient Database *database_;
3931b718 6918 _transient id<UINavigationControllerDelegate> delegate_;
b5e7eebb
GP
6919}
6920
6921- (id) initWithDatabase:(Database *)database;
6922- (void) reloadData;
6923
6924@end
6925
6926
6927@implementation CYNavigationController
6928
9cb0bff2
GP
6929- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6930 // Inherit autorotation settings for modal parents.
6931 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6932 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6933 } else {
6934 return [super shouldAutorotateToInterfaceOrientation:orientation];
6935 }
6936}
6937
b5e7eebb
GP
6938- (void) dealloc {
6939 [super dealloc];
6940}
6941
6942- (void) reloadData {
6943 size_t count([[self viewControllers] count]);
6944 for (size_t i(0); i != count; ++i) {
c21004b9 6945 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
b5e7eebb
GP
6946 [page reloadData];
6947 }
6948}
6949
eb30da80 6950- (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
b5e7eebb
GP
6951 delegate_ = delegate;
6952}
6953
6954- (id) initWithDatabase:(Database *)database {
6955 if ((self = [super init]) != nil) {
6956 database_ = database;
6957 } return self;
6958}
6959
807ae6d7
JF
6960@end
6961/* }}} */
6962/* Cydia:// Protocol {{{ */
6963@interface CydiaURLProtocol : NSURLProtocol {
6964}
6965
6966@end
6967
6968@implementation CydiaURLProtocol
6969
6970+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
6971 NSURL *url([request URL]);
6972 if (url == nil)
6973 return NO;
6974 NSString *scheme([[url scheme] lowercaseString]);
6975 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6976 return NO;
6977 return YES;
6978}
6979
6980+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6981 return request;
6982}
6983
9fe5e5f8
JF
6984- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6985 id<NSURLProtocolClient> client([self client]);
189a73d0
JF
6986 if (icon == nil)
6987 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6988 else {
6989 NSData *data(UIImagePNGRepresentation(icon));
9fe5e5f8 6990
189a73d0
JF
6991 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6992 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6993 [client URLProtocol:self didLoadData:data];
6994 [client URLProtocolDidFinishLoading:self];
6995 }
9fe5e5f8
JF
6996}
6997
807ae6d7
JF
6998- (void) startLoading {
6999 id<NSURLProtocolClient> client([self client]);
7000 NSURLRequest *request([self request]);
7001
7002 NSURL *url([request URL]);
7003 NSString *href([url absoluteString]);
7004
7005 NSString *path([href substringFromIndex:8]);
7006 NSRange slash([path rangeOfString:@"/"]);
7007
7008 NSString *command;
7009 if (slash.location == NSNotFound) {
7010 command = path;
7011 path = nil;
7012 } else {
7013 command = [path substringToIndex:slash.location];
7014 path = [path substringFromIndex:(slash.location + 1)];
7015 }
7016
7017 Database *database([Database sharedInstance]);
7018
7019 if ([command isEqualToString:@"package-icon"]) {
7020 if (path == nil)
7021 goto fail;
dec6029f 7022 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
807ae6d7
JF
7023 Package *package([database packageWithName:path]);
7024 if (package == nil)
7025 goto fail;
dec6029f 7026 UIImage *icon([package icon]);
9fe5e5f8 7027 [self _returnPNGWithImage:icon forRequest:request];
16f2786b
JF
7028 } else if ([command isEqualToString:@"source-icon"]) {
7029 if (path == nil)
7030 goto fail;
7031 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7032 NSString *source(Simplify(path));
16f2786b
JF
7033 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7034 if (icon == nil)
7035 icon = [UIImage applicationImageNamed:@"unknown.png"];
9fe5e5f8
JF
7036 [self _returnPNGWithImage:icon forRequest:request];
7037 } else if ([command isEqualToString:@"uikit-image"]) {
7038 if (path == nil)
7039 goto fail;
7040 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7041 UIImage *icon(_UIImageWithName(path));
7042 [self _returnPNGWithImage:icon forRequest:request];
dec6029f
JF
7043 } else if ([command isEqualToString:@"section-icon"]) {
7044 if (path == nil)
7045 goto fail;
7046 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7047 NSString *section(Simplify(path));
dec6029f
JF
7048 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7049 if (icon == nil)
7050 icon = [UIImage applicationImageNamed:@"unknown.png"];
9fe5e5f8 7051 [self _returnPNGWithImage:icon forRequest:request];
807ae6d7
JF
7052 } else fail: {
7053 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7054 }
7055}
7056
7057- (void) stopLoading {
7058}
7059
7060@end
7061/* }}} */
7062
adb61bda 7063/* Sections Controller {{{ */
c21004b9
JF
7064@interface SectionsController : CYViewController <
7065 UITableViewDataSource,
7066 UITableViewDelegate
7067> {
807ae6d7
JF
7068 _transient Database *database_;
7069 NSMutableArray *sections_;
7070 NSMutableArray *filtered_;
46aa9775 7071 UITableView *list_;
807ae6d7
JF
7072 UIView *accessory_;
7073 BOOL editing_;
7074}
7075
b5e7eebb 7076- (id) initWithDatabase:(Database *)database;
807ae6d7
JF
7077- (void) reloadData;
7078- (void) resetView;
7079
c21004b9
JF
7080- (void) editButtonClicked;
7081
807ae6d7
JF
7082@end
7083
adb61bda 7084@implementation SectionsController
807ae6d7
JF
7085
7086- (void) dealloc {
7087 [list_ setDataSource:nil];
7088 [list_ setDelegate:nil];
7089
7090 [sections_ release];
7091 [filtered_ release];
807ae6d7
JF
7092 [list_ release];
7093 [accessory_ release];
7094 [super dealloc];
7095}
7096
b5e7eebb
GP
7097- (void) viewDidAppear:(BOOL)animated {
7098 [super viewDidAppear:animated];
7099 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7100}
7101
46aa9775
GP
7102- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7103 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7104 return section;
807ae6d7
JF
7105}
7106
eb30da80 7107- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
46aa9775 7108 return editing_ ? [sections_ count] : [filtered_ count] + 1;
807ae6d7
JF
7109}
7110
21ea11a4
GP
7111/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7112 return 45.0f;
7113}*/
807ae6d7 7114
46aa9775 7115- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
b5e7eebb
GP
7116 static NSString *reuseIdentifier = @"SectionCell";
7117
7118 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
36fbb2aa
JF
7119 if (cell == nil)
7120 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7121
46aa9775 7122 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
807ae6d7 7123
46aa9775 7124 return cell;
807ae6d7
JF
7125}
7126
46aa9775 7127- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
0abb648c
JF
7128 if (editing_)
7129 return;
477de105 7130
0abb648c 7131 Section *section = [self sectionAtIndexPath:indexPath];
46aa9775 7132 NSString *name = [section name];
807ae6d7
JF
7133 NSString *title;
7134
46aa9775 7135 if ([indexPath row] == 0) {
807ae6d7
JF
7136 section = nil;
7137 name = nil;
43f3d7f6 7138 title = UCLocalize("ALL_PACKAGES");
807ae6d7 7139 } else {
28ce8704
JF
7140 if (name != nil) {
7141 name = [NSString stringWithString:name];
f79a4512 7142 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
28ce8704 7143 } else {
807ae6d7 7144 name = @"";
43f3d7f6 7145 title = UCLocalize("NO_SECTION");
807ae6d7
JF
7146 }
7147 }
7148
adb61bda 7149 FilteredPackageController *table = [[[FilteredPackageController alloc]
b5e7eebb 7150 initWithDatabase:database_
807ae6d7 7151 title:title
670a0494 7152 filter:@selector(isVisibleInSection:)
807ae6d7
JF
7153 with:name
7154 ] autorelease];
7155
7156 [table setDelegate:delegate_];
7157
b5e7eebb 7158 [[self navigationController] pushViewController:table animated:YES];
807ae6d7
JF
7159}
7160
eb30da80 7161- (NSString *) title { return UCLocalize("SECTIONS"); }
b5e7eebb
GP
7162
7163- (id) initWithDatabase:(Database *)database {
7164 if ((self = [super init]) != nil) {
807ae6d7
JF
7165 database_ = database;
7166
b5e7eebb
GP
7167 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7168
807ae6d7
JF
7169 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7170 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7171
b5e7eebb 7172 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
04fe1349 7173 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 7174 [list_ setRowHeight:45.0f];
b5e7eebb 7175 [[self view] addSubview:list_];
807ae6d7 7176
46aa9775 7177 [list_ setDataSource:self];
b5e7eebb 7178 [list_ setDelegate:self];
807ae6d7
JF
7179
7180 [self reloadData];
807ae6d7
JF
7181 } return self;
7182}
7183
7184- (void) reloadData {
7185 NSArray *packages = [database_ packages];
7186
7187 [sections_ removeAllObjects];
7188 [filtered_ removeAllObjects];
7189
f79a4512 7190 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
807ae6d7
JF
7191
7192 _trace();
c4dcf2c2 7193 for (Package *package in packages) {
807ae6d7 7194 NSString *name([package section]);
f79a4512 7195 NSString *key(name == nil ? @"" : name);
807ae6d7 7196
f79a4512
JF
7197 Section *section;
7198
7199 _profile(SectionsView$reloadData$Section)
7200 section = [sections objectForKey:key];
807ae6d7 7201 if (section == nil) {
f79a4512 7202 _profile(SectionsView$reloadData$Section$Allocate)
9fcbca29 7203 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
f79a4512
JF
7204 [sections setObject:section forKey:key];
7205 _end
807ae6d7 7206 }
f79a4512
JF
7207 _end
7208
7209 [section addToCount];
6d9712c4 7210
f79a4512 7211 _profile(SectionsView$reloadData$Filter)
670a0494 7212 if (![package valid] || ![package visible])
f79a4512
JF
7213 continue;
7214 _end
7215
7216 [section addToRow];
b4d89997 7217 }
807ae6d7 7218 _trace();
dc5812ec 7219
6d9712c4 7220 [sections_ addObjectsFromArray:[sections allValues]];
6d9712c4 7221
677b8415 7222 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
dc5812ec 7223
f79a4512
JF
7224 for (Section *section in sections_) {
7225 size_t count([section row]);
677b8415 7226 if (count == 0)
f79a4512 7227 continue;
dc5812ec 7228
9fcbca29 7229 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
f79a4512
JF
7230 [section setCount:count];
7231 [filtered_ addObject:section];
b4d89997 7232 }
2367a917 7233
dd9de556
JF
7234 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7235 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
b5e7eebb
GP
7236 style:UIBarButtonItemStylePlain
7237 target:self
7238 action:@selector(editButtonClicked)
dd9de556 7239 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
b5e7eebb 7240
b4d89997 7241 [list_ reloadData];
807ae6d7 7242 _trace();
36bb2ca2 7243}
2367a917 7244
6d9712c4
JF
7245- (void) resetView {
7246 if (editing_)
b5e7eebb 7247 [self editButtonClicked];
36bb2ca2 7248}
2367a917 7249
b5e7eebb 7250- (void) editButtonClicked {
6d9712c4
JF
7251 if ((editing_ = !editing_))
7252 [list_ reloadData];
807ae6d7 7253 else
6d9712c4 7254 [delegate_ updateData];
bc11cf5b 7255
b5e7eebb
GP
7256 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7257 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7258 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
baf80942
JF
7259}
7260
a54b1c10
JF
7261- (UIView *) accessoryView {
7262 return accessory_;
7263}
7264
dc5812ec 7265@end
2367a917 7266/* }}} */
adb61bda 7267/* Changes Controller {{{ */
c21004b9
JF
7268@interface ChangesController : CYViewController <
7269 UITableViewDataSource,
7270 UITableViewDelegate
7271> {
36bb2ca2 7272 _transient Database *database_;
0175295c 7273 unsigned era_;
6da1297d 7274 CFMutableArrayRef packages_;
dc5812ec 7275 NSMutableArray *sections_;
327624b6 7276 UITableView *list_;
36bb2ca2 7277 unsigned upgrades_;
904e4273 7278 BOOL hasSentFirstLoad_;
dc5812ec
JF
7279}
7280
b5e7eebb 7281- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
36bb2ca2 7282- (void) reloadData;
dc5812ec 7283
dc5812ec
JF
7284@end
7285
adb61bda 7286@implementation ChangesController
b4d89997
JF
7287
7288- (void) dealloc {
327624b6 7289 [list_ setDelegate:nil];
36bb2ca2
JF
7290 [list_ setDataSource:nil];
7291
6da1297d
JF
7292 CFRelease(packages_);
7293
b4d89997 7294 [sections_ release];
36bb2ca2 7295 [list_ release];
b4d89997
JF
7296 [super dealloc];
7297}
dc5812ec 7298
b5e7eebb
GP
7299- (void) viewDidAppear:(BOOL)animated {
7300 [super viewDidAppear:animated];
904e4273
RP
7301 if (!hasSentFirstLoad_) {
7302 hasSentFirstLoad_ = YES;
7303 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7304 } else {
7305 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7306 }
b5e7eebb
GP
7307}
7308
327624b6
JF
7309- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7310 NSInteger count([sections_ count]);
7311 return count == 0 ? 1 : count;
dc5812ec
JF
7312}
7313
327624b6
JF
7314- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7315 if ([sections_ count] == 0)
7316 return nil;
dc5812ec
JF
7317 return [[sections_ objectAtIndex:section] name];
7318}
7319
327624b6
JF
7320- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7321 if ([sections_ count] == 0)
7322 return 0;
7323 return [[sections_ objectAtIndex:section] count];
dc5812ec
JF
7324}
7325
6da1297d
JF
7326- (Package *) packageAtIndex:(NSUInteger)index {
7327 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7328}
7329
327624b6 7330- (Package *) packageAtIndexPath:(NSIndexPath *)path {
0175295c
JF
7331@synchronized (database_) {
7332 if ([database_ era] != era_)
7333 return nil;
7334
327624b6
JF
7335 Section *section([sections_ objectAtIndex:[path section]]);
7336 NSInteger row([path row]);
0175295c
JF
7337 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7338} }
dc5812ec 7339
327624b6 7340- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
c21004b9 7341 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
327624b6
JF
7342 if (cell == nil)
7343 cell = [[[PackageCell alloc] init] autorelease];
7344 [cell setPackage:[self packageAtIndexPath:path]];
7345 return cell;
dc5812ec
JF
7346}
7347
21ea11a4 7348/*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
327624b6 7349 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
21ea11a4 7350}*/
dc5812ec 7351
327624b6
JF
7352- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7353 Package *package([self packageAtIndexPath:path]);
adb61bda 7354 PackageController *view([delegate_ packageController]);
36bb2ca2
JF
7355 [view setDelegate:delegate_];
7356 [view setPackage:package];
b5e7eebb 7357 [[self navigationController] pushViewController:view animated:YES];
327624b6 7358 return path;
dc5812ec
JF
7359}
7360
b5e7eebb 7361- (void) refreshButtonClicked {
c21004b9 7362 [delegate_ beginUpdate];
45e21ffa 7363 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
9a7b04c5
JF
7364}
7365
b5e7eebb 7366- (void) upgradeButtonClicked {
36bb2ca2 7367 [delegate_ distUpgrade];
dc5812ec
JF
7368}
7369
eb30da80 7370- (NSString *) title { return UCLocalize("CHANGES"); }
b5e7eebb
GP
7371
7372- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7373 if ((self = [super init]) != nil) {
36bb2ca2 7374 database_ = database;
b5e7eebb 7375 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
dc5812ec 7376
6da1297d
JF
7377 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7378
b4d89997 7379 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
dc5812ec 7380
b5e7eebb 7381 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
04fe1349 7382 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
21ea11a4 7383 [list_ setRowHeight:73.0f];
b5e7eebb 7384 [[self view] addSubview:list_];
36bb2ca2 7385
b4d89997 7386 [list_ setDataSource:self];
327624b6 7387 [list_ setDelegate:self];
dc5812ec 7388
77801ff1 7389 delegate_ = delegate;
dc5812ec
JF
7390 } return self;
7391}
7392
77801ff1 7393- (void) _reloadPackages:(NSArray *)packages {
807ae6d7 7394 _trace();
c4dcf2c2 7395 for (Package *package in packages)
e4f3d6e9 7396 if ([package upgradableAndEssential:YES] || [package visible])
6da1297d 7397 CFArrayAppendValue(packages_, package);
2367a917 7398
807ae6d7 7399 _trace();
6da1297d 7400 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
807ae6d7 7401 _trace();
77801ff1
JF
7402}
7403
7404- (void) reloadData {
0175295c 7405 era_ = [database_ era];
77801ff1
JF
7406 NSArray *packages = [database_ packages];
7407
6da1297d
JF
7408 CFArrayRemoveAllValues(packages_);
7409
77801ff1
JF
7410 [sections_ removeAllObjects];
7411
376c37e8 7412#if 1
77801ff1 7413 UIProgressHUD *hud([delegate_ addProgressHUD]);
376c37e8 7414 [hud setText:UCLocalize("LOADING")];
534e31fc 7415 //NSLog(@"HUD:%@::%@", delegate_, hud);
77801ff1
JF
7416 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7417 [delegate_ removeProgressHUD:hud];
8e4e80cb
JF
7418#else
7419 [self _reloadPackages:packages];
7420#endif
dc5812ec 7421
43f3d7f6 7422 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
1b18f026 7423 Section *ignored = nil;
dc5812ec 7424 Section *section = nil;
31bc18a7 7425 time_t last = 0;
b4d89997 7426
36bb2ca2
JF
7427 upgrades_ = 0;
7428 bool unseens = false;
7429
677b8415 7430 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
36bb2ca2 7431
6da1297d
JF
7432 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7433 Package *package = [self packageAtIndex:offset];
dc5812ec 7434
677b8415 7435 BOOL uae = [package upgradableAndEssential:YES];
f79a4512
JF
7436
7437 if (!uae) {
36bb2ca2 7438 unseens = true;
31bc18a7 7439 time_t seen([package seen]);
dc5812ec 7440
31bc18a7 7441 if (section == nil || last != seen) {
807ae6d7 7442 last = seen;
723a0072 7443
dc63e78f 7444 NSString *name;
31bc18a7
JF
7445 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7446 [name autorelease];
dc63e78f 7447
adb61bda 7448 _profile(ChangesController$reloadData$Allocate)
43f3d7f6 7449 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
9fcbca29 7450 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
f79a4512
JF
7451 [sections_ addObject:section];
7452 _end
b4d89997
JF
7453 }
7454
36bb2ca2 7455 [section addToCount];
1b18f026
DH
7456 } else if ([package ignored]) {
7457 if (ignored == nil) {
7458 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7459 }
807ae6d7 7460 [ignored addToCount];
1b18f026 7461 } else {
807ae6d7
JF
7462 ++upgrades_;
7463 [upgradable addToCount];
b4d89997 7464 }
dc5812ec 7465 }
807ae6d7 7466 _trace();
dc5812ec 7467
36bb2ca2 7468 CFRelease(formatter);
b4d89997 7469
36bb2ca2
JF
7470 if (unseens) {
7471 Section *last = [sections_ lastObject];
7472 size_t count = [last count];
6da1297d 7473 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
36bb2ca2
JF
7474 [sections_ removeLastObject];
7475 }
dc5812ec 7476
807ae6d7
JF
7477 if ([ignored count] != 0)
7478 [sections_ insertObject:ignored atIndex:0];
36bb2ca2
JF
7479 if (upgrades_ != 0)
7480 [sections_ insertObject:upgradable atIndex:0];
c25a610d 7481
36bb2ca2 7482 [list_ reloadData];
3178d79b 7483
dd9de556
JF
7484 if (upgrades_ > 0)
7485 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7486 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7487 style:UIBarButtonItemStylePlain
7488 target:self
7489 action:@selector(upgradeButtonClicked)
7490 ] autorelease]];
b5e7eebb 7491
dd9de556
JF
7492 if (![delegate_ updating])
7493 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7494 initWithTitle:UCLocalize("REFRESH")
7495 style:UIBarButtonItemStylePlain
7496 target:self
7497 action:@selector(refreshButtonClicked)
7498 ] autorelease]];
8fe19fc1
JF
7499}
7500
3178d79b
JF
7501@end
7502/* }}} */
adb61bda 7503/* Search Controller {{{ */
c21004b9
JF
7504@interface SearchController : FilteredPackageController <
7505 UISearchBarDelegate
7506> {
7507 UISearchBar *search_;
36bb2ca2 7508}
b4d89997 7509
b5e7eebb 7510- (id) initWithDatabase:(Database *)database;
36bb2ca2 7511- (void) reloadData;
b4d89997 7512
3178d79b
JF
7513@end
7514
adb61bda 7515@implementation SearchController
3178d79b 7516
b4d89997 7517- (void) dealloc {
b5e7eebb 7518 [search_ release];
36bb2ca2 7519 [super dealloc];
b4d89997
JF
7520}
7521
eb30da80 7522- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
b5e7eebb
GP
7523 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7524 [search_ resignFirstResponder];
01d93940 7525 [self reloadData];
36bb2ca2 7526}
b4d89997 7527
eb30da80 7528- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
b5e7eebb 7529 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
01d93940 7530 [self reloadData];
36bb2ca2 7531}
b4d89997 7532
eb30da80 7533- (NSString *) title { return nil; }
ab398adf 7534
b5e7eebb 7535- (id) initWithDatabase:(Database *)database {
dcb47737
RP
7536 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7537}
7538
7539- (void)viewDidAppear:(BOOL)animated {
bc11cf5b
JF
7540 [super viewDidAppear:animated];
7541 if (!search_) {
c21004b9 7542 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
dcb47737 7543 [search_ layoutSubviews];
b5e7eebb 7544 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
bcccf498
JF
7545
7546 UITextField *textField;
7547 if ([search_ respondsToSelector:@selector(searchField)])
7548 textField = [search_ searchField];
7549 else
7550 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7551
dcb47737 7552 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
b5e7eebb 7553 [search_ setDelegate:self];
dcb47737
RP
7554 [textField setEnablesReturnKeyAutomatically:NO];
7555 [[self navigationItem] setTitleView:textField];
7556 }
3178d79b
JF
7557}
7558
807ae6d7
JF
7559- (void) _reloadData {
7560}
b4d89997 7561
807ae6d7 7562- (void) reloadData {
adb61bda 7563 _profile(SearchController$reloadData)
b5e7eebb 7564 [packages_ reloadData];
808c6eb6
JF
7565 _end
7566 PrintTimes();
b5e7eebb 7567 [packages_ resetCursor];
807ae6d7 7568}
8fe19fc1 7569
8e05f686
RP
7570- (void) didSelectPackage:(Package *)package {
7571 [search_ resignFirstResponder];
7572 [super didSelectPackage:package];
7573}
7574
807ae6d7
JF
7575@end
7576/* }}} */
adb61bda 7577/* Settings Controller {{{ */
c21004b9
JF
7578@interface SettingsController : CYViewController <
7579 UITableViewDataSource,
7580 UITableViewDelegate
7581> {
807ae6d7
JF
7582 _transient Database *database_;
7583 NSString *name_;
7584 Package *package_;
3b7fcecd 7585 UITableView *table_;
68046ccc
JF
7586 UISwitch *subscribedSwitch_;
7587 UISwitch *ignoredSwitch_;
3b7fcecd
GP
7588 UITableViewCell *subscribedCell_;
7589 UITableViewCell *ignoredCell_;
807ae6d7 7590}
b4d89997 7591
b5e7eebb 7592- (id) initWithDatabase:(Database *)database package:(NSString *)package;
b4d89997 7593
807ae6d7 7594@end
b4d89997 7595
adb61bda 7596@implementation SettingsController
b4d89997 7597
807ae6d7 7598- (void) dealloc {
807ae6d7
JF
7599 [name_ release];
7600 if (package_ != nil)
7601 [package_ release];
7602 [table_ release];
7603 [subscribedSwitch_ release];
7604 [ignoredSwitch_ release];
7605 [subscribedCell_ release];
7606 [ignoredCell_ release];
bc11cf5b 7607
807ae6d7
JF
7608 [super dealloc];
7609}
b4d89997 7610
3b7fcecd 7611- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
807ae6d7
JF
7612 if (package_ == nil)
7613 return 0;
b4d89997 7614
3b7fcecd 7615 return 1;
3178d79b
JF
7616}
7617
3b7fcecd 7618- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
807ae6d7
JF
7619 if (package_ == nil)
7620 return 0;
dc5812ec 7621
94b0b3e5 7622 return 2;
3b7fcecd 7623}
baf80942 7624
3b7fcecd
GP
7625- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7626 return UCLocalize("SHOW_ALL_CHANGES_EX");
36bb2ca2 7627}
b4d89997 7628
94b0b3e5
JF
7629- (void) onSubscribed:(id)control {
7630 bool value([control isOn]);
807ae6d7
JF
7631 if (package_ == nil)
7632 return;
94b0b3e5 7633 if ([package_ setSubscribed:value])
807ae6d7 7634 [delegate_ updateData];
36bb2ca2 7635}
b4d89997 7636
3b7fcecd 7637- (void) onIgnored:(id)control {
1b18f026 7638 // TODO: set Held state - possibly call out to dpkg, etc.
8fe19fc1
JF
7639}
7640
3b7fcecd 7641- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
807ae6d7
JF
7642 if (package_ == nil)
7643 return nil;
770f2a8e 7644
3b7fcecd
GP
7645 switch ([indexPath row]) {
7646 case 0: return subscribedCell_;
7647 case 1: return ignoredCell_;
bc11cf5b 7648
670a0494 7649 _nodefault
807ae6d7 7650 }
770f2a8e 7651
807ae6d7 7652 return nil;
770f2a8e
JF
7653}
7654
eb30da80 7655- (NSString *) title { return UCLocalize("SETTINGS"); }
b5e7eebb
GP
7656
7657- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7658 if ((self = [super init])) {
807ae6d7
JF
7659 database_ = database;
7660 name_ = [package retain];
770f2a8e 7661
b5e7eebb
GP
7662 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7663
3b7fcecd
GP
7664 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7665 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b5e7eebb 7666 [[self view] addSubview:table_];
770f2a8e 7667
68046ccc 7668 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
3b7fcecd
GP
7669 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7670 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
770f2a8e 7671
68046ccc 7672 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
3b7fcecd
GP
7673 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7674 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
770f2a8e 7675
3b7fcecd
GP
7676 subscribedCell_ = [[UITableViewCell alloc] init];
7677 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7678 [subscribedCell_ setAccessoryView:subscribedSwitch_];
33a97e4f 7679 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
770f2a8e 7680
3b7fcecd
GP
7681 ignoredCell_ = [[UITableViewCell alloc] init];
7682 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7683 [ignoredCell_ setAccessoryView:ignoredSwitch_];
33a97e4f 7684 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
770f2a8e 7685
807ae6d7 7686 [table_ setDataSource:self];
3b7fcecd 7687 [table_ setDelegate:self];
807ae6d7
JF
7688 [self reloadData];
7689 } return self;
7690}
770f2a8e 7691
807ae6d7
JF
7692- (void) reloadData {
7693 if (package_ != nil)
7694 [package_ autorelease];
7695 package_ = [database_ packageWithName:name_];
7696 if (package_ != nil) {
7697 [package_ retain];
3b7fcecd
GP
7698 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7699 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
770f2a8e 7700 }
807ae6d7
JF
7701
7702 [table_ reloadData];
770f2a8e
JF
7703}
7704
770f2a8e 7705@end
bfc87a4d 7706/* }}} */
adb61bda
GP
7707/* Signature Controller {{{ */
7708@interface SignatureController : CYBrowserController {
770f2a8e
JF
7709 _transient Database *database_;
7710 NSString *package_;
7711}
7712
b5e7eebb 7713- (id) initWithDatabase:(Database *)database package:(NSString *)package;
770f2a8e
JF
7714
7715@end
7716
adb61bda 7717@implementation SignatureController
770f2a8e
JF
7718
7719- (void) dealloc {
7720 [package_ release];
7721 [super dealloc];
7722}
7723
2634b249 7724- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
770f2a8e 7725 // XXX: dude!
2634b249 7726 [super webView:view didClearWindowObject:window forFrame:frame];
770f2a8e
JF
7727}
7728
b5e7eebb
GP
7729- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7730 if ((self = [super init]) != nil) {
770f2a8e
JF
7731 database_ = database;
7732 package_ = [package retain];
7733 [self reloadData];
7734 } return self;
7735}
7736
7737- (void) reloadData {
7738 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7739}
7740
21c6da4b
GP
7741@end
7742/* }}} */
f3e11d24 7743
21c6da4b 7744/* Role Controller {{{ */
c21004b9
JF
7745@interface RoleController : CYViewController <
7746 UITableViewDataSource,
7747 UITableViewDelegate
7748> {
21c6da4b 7749 _transient Database *database_;
3931b718
JF
7750 // XXX: ok, "roledelegate_"?...
7751 _transient id roledelegate_;
21c6da4b
GP
7752 UITableView *table_;
7753 UISegmentedControl *segment_;
7754 UIView *container_;
7755}
c21004b9
JF
7756
7757- (void) showDoneButton;
7758- (void) resizeSegmentedControl;
7759
21c6da4b
GP
7760@end
7761
7762@implementation RoleController
7763- (void) dealloc {
7764 [table_ release];
7765 [segment_ release];
7766 [container_ release];
bc11cf5b 7767
21c6da4b
GP
7768 [super dealloc];
7769}
7770
7771- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7772 if ((self = [super init])) {
7773 database_ = database;
7774 roledelegate_ = delegate;
bc11cf5b 7775
21c6da4b 7776 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
bc11cf5b 7777
21c6da4b 7778 NSArray *items = [NSArray arrayWithObjects:
bc11cf5b 7779 UCLocalize("USER"),
21c6da4b
GP
7780 UCLocalize("HACKER"),
7781 UCLocalize("DEVELOPER"),
7782 nil];
7783 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7784 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7785 [container_ addSubview:segment_];
bc11cf5b 7786
21c6da4b
GP
7787 int index = -1;
7788 if ([Role_ isEqualToString:@"User"]) index = 0;
7789 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7790 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7791 if (index != -1) {
7792 [segment_ setSelectedSegmentIndex:index];
7793 [self showDoneButton];
7794 }
bc11cf5b 7795
21c6da4b 7796 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
e62f29c6 7797 [self resizeSegmentedControl];
bc11cf5b 7798
21c6da4b
GP
7799 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7800 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7801 [table_ setDelegate:self];
7802 [table_ setDataSource:self];
7803 [[self view] addSubview:table_];
7804 [table_ reloadData];
7805 } return self;
7806}
7807
e62f29c6
GP
7808- (void) resizeSegmentedControl {
7809 CGFloat width = [[self view] frame].size.width;
7810 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7811}
7812
2bdd73bd
GP
7813- (void) viewWillAppear:(BOOL)animated {
7814 [super viewWillAppear:animated];
bc11cf5b 7815
e62f29c6
GP
7816 [self resizeSegmentedControl];
7817}
7818
7819- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7820 [self resizeSegmentedControl];
7821}
7822
7823- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7824 [self resizeSegmentedControl];
2bdd73bd
GP
7825}
7826
21c6da4b 7827- (void) save {
fed0d010 7828 NSString *role(nil);
bc11cf5b 7829
21c6da4b 7830 switch ([segment_ selectedSegmentIndex]) {
124c6201
GP
7831 case 0: role = @"User"; break;
7832 case 1: role = @"Hacker"; break;
7833 case 2: role = @"Developer"; break;
21c6da4b
GP
7834
7835 _nodefault
7836 }
7837
124c6201 7838 if (![role isEqualToString:Role_]) {
fed0d010 7839 bool rolling(Role_ == nil);
124c6201 7840 Role_ = role;
bc11cf5b 7841
124c6201
GP
7842 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7843 Role_, @"Role",
7844 nil];
21c6da4b 7845
124c6201 7846 [Metadata_ setObject:Settings_ forKey:@"Settings"];
124c6201 7847 Changed_ = true;
bc11cf5b 7848
fed0d010
JF
7849 if (rolling)
7850 [roledelegate_ loadData];
7851 else
7852 [roledelegate_ updateData];
124c6201 7853 }
21c6da4b
GP
7854}
7855
7856- (void) segmentChanged:(UISegmentedControl *)control {
7857 [self showDoneButton];
7858}
7859
8576ab50 7860- (void) saveAndClose {
21c6da4b 7861 [self save];
8576ab50
GP
7862
7863 [[self navigationItem] setRightBarButtonItem:nil];
21c6da4b
GP
7864 [[self navigationController] dismissModalViewControllerAnimated:YES];
7865}
7866
8576ab50
GP
7867- (void) doneButtonClicked {
7868 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7869 [spinner startAnimating];
7870 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7871 [[self navigationItem] setRightBarButtonItem:spinItem];
7872
7873 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7874}
7875
21c6da4b 7876- (void) showDoneButton {
dd9de556 7877 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
21c6da4b
GP
7878 initWithTitle:UCLocalize("DONE")
7879 style:UIBarButtonItemStyleDone
7880 target:self
7881 action:@selector(doneButtonClicked)
dd9de556 7882 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
21c6da4b
GP
7883}
7884
7885- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
e62f29c6
GP
7886 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7887 return 6;
21c6da4b
GP
7888}
7889
7890- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7891 return 0; // :(
7892}
7893
7894- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7895 return nil; // This method is required by the protocol.
7896}
7897
7898- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
bc11cf5b 7899 if (section == 1)
21c6da4b 7900 return UCLocalize("ROLE_EX");
bc11cf5b 7901 if (section == 4)
21c6da4b
GP
7902 return [NSString stringWithFormat:
7903 @"%@: %@\n%@: %@\n%@: %@",
bc11cf5b
JF
7904 UCLocalize("USER"), UCLocalize("USER_EX"),
7905 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
21c6da4b
GP
7906 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7907 ];
7908 else return nil;
7909}
7910
7911- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
36fbb2aa 7912 return section == 3 ? 44.0f : 0;
21c6da4b
GP
7913}
7914
7915- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
36fbb2aa 7916 return section == 3 ? container_ : nil;
21c6da4b
GP
7917}
7918
f3e11d24
GP
7919@end
7920/* }}} */
7921/* Stash Controller {{{ */
7922@interface CYStashController : CYViewController {
3931b718
JF
7923 // XXX: just delete these things
7924 _transient UIActivityIndicatorView *spinner_;
7925 _transient UILabel *status_;
7926 _transient UILabel *caption_;
f3e11d24
GP
7927}
7928@end
7929
7930@implementation CYStashController
7931- (id) init {
7932 if ((self = [super init])) {
e61a973c 7933 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
f3e11d24 7934
dd9de556 7935 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
e61a973c 7936 CGRect spinrect = [spinner_ frame];
f3e11d24
GP
7937 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7938 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7939 [spinner_ setFrame:spinrect];
7940 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
e61a973c 7941 [[self view] addSubview:spinner_];
e61a973c 7942 [spinner_ startAnimating];
f3e11d24
GP
7943
7944 CGRect captrect;
7945 captrect.size.width = [[self view] frame].size.width;
7946 captrect.size.height = 40.0f;
7947 captrect.origin.x = 0;
7948 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
dd9de556 7949 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
f3e11d24 7950 [caption_ setText:@"Initializing Filesystem"];
851f4a99 7951 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
f3e11d24
GP
7952 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7953 [caption_ setTextColor:[UIColor whiteColor]];
7954 [caption_ setBackgroundColor:[UIColor clearColor]];
7955 [caption_ setShadowColor:[UIColor blackColor]];
7956 [caption_ setTextAlignment:UITextAlignmentCenter];
7957 [[self view] addSubview:caption_];
f3e11d24
GP
7958
7959 CGRect statusrect;
7960 statusrect.size.width = [[self view] frame].size.width;
7961 statusrect.size.height = 30.0f;
7962 statusrect.origin.x = 0;
7963 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
dd9de556 7964 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
851f4a99 7965 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
f3e11d24
GP
7966 [status_ setText:@"(Cydia will exit when complete.)"];
7967 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7968 [status_ setTextColor:[UIColor whiteColor]];
7969 [status_ setBackgroundColor:[UIColor clearColor]];
7970 [status_ setShadowColor:[UIColor blackColor]];
7971 [status_ setTextAlignment:UITextAlignmentCenter];
7972 [[self view] addSubview:status_];
f3e11d24
GP
7973 } return self;
7974}
7975
7976- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7977 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7978}
770f2a8e 7979@end
807ae6d7 7980/* }}} */
770f2a8e 7981
b5e7eebb
GP
7982typedef enum {
7983 kCydiaTag = 0,
7984 kSectionsTag = 1,
7985 kChangesTag = 2,
7986 kManageTag = 3,
7987 kInstalledTag = 4,
7988 kSourcesTag = 5,
7989 kSearchTag = 6
7990} CYTabTag;
04fe1349 7991
2367a917 7992@interface Cydia : UIApplication <
adb61bda
GP
7993 ConfirmationControllerDelegate,
7994 ProgressControllerDelegate,
eb30da80 7995 CydiaDelegate,
68046ccc
JF
7996 UINavigationControllerDelegate,
7997 UITabBarControllerDelegate
2367a917 7998> {
3931b718
JF
7999 // XXX: evaluate all fields for _transient
8000
dc5812ec 8001 UIWindow *window_;
68046ccc 8002 CYTabBarController *tabbar_;
9bedffaa 8003
a54b1c10 8004 NSMutableArray *essential_;
9bedffaa 8005 NSMutableArray *broken_;
dc5812ec
JF
8006
8007 Database *database_;
dc5812ec 8008
54043703 8009 NSURL *starturl_;
aeed65a6 8010 int tag_;
54043703 8011
235f5487 8012 unsigned locked_;
54043703 8013 unsigned activity_;
9b619239 8014
adb61bda
GP
8015 SectionsController *sections_;
8016 ChangesController *changes_;
8017 ManageController *manage_;
8018 SearchController *search_;
b5e7eebb 8019 SourceTable *sources_;
adb61bda 8020 InstalledController *installed_;
b5e7eebb 8021 id queueDelegate_;
f79a4512 8022
f3e11d24
GP
8023 CYStashController *stash_;
8024
8c02abc8 8025 bool loaded_;
dc5812ec
JF
8026}
8027
9b623dac
JF
8028- (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8029- (void) setPage:(CYViewController *)page;
fed0d010 8030- (void) loadData;
670a0494 8031
f6371a33
JF
8032// XXX: I hate prototypes
8033- (id) queueBadgeController;
8034
dc5812ec
JF
8035@end
8036
670a0494 8037static _finline void _setHomePage(Cydia *self) {
adb61bda 8038 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
670a0494
JF
8039}
8040
dc5812ec
JF
8041@implementation Cydia
8042
b5e7eebb 8043- (void) beginUpdate {
7585ce66 8044 [tabbar_ beginUpdate];
b5e7eebb
GP
8045}
8046
8047- (BOOL) updating {
7585ce66 8048 return [tabbar_ updating];
b5e7eebb
GP
8049}
8050
01d93940
JF
8051- (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8052 return window_;
8053}
8054
9bedffaa
JF
8055- (void) _loaded {
8056 if ([broken_ count] != 0) {
8057 int count = [broken_ count];
8058
37d2b2a9 8059 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 8060 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
b5e7eebb
GP
8061 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8062 delegate:self
8063 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8064 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
9bedffaa
JF
8065 ] autorelease];
8066
37d2b2a9
GP
8067 [alert setContext:@"fixhalf"];
8068 [alert show];
9bedffaa
JF
8069 } else if (!Ignored_ && [essential_ count] != 0) {
8070 int count = [essential_ count];
8071
37d2b2a9 8072 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 8073 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
b5e7eebb
GP
8074 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8075 delegate:self
8076 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
37d2b2a9 8077 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
9bedffaa
JF
8078 ] autorelease];
8079
37d2b2a9
GP
8080 [alert setContext:@"upgrade"];
8081 [alert show];
9bedffaa
JF
8082 }
8083}
8084
7623f855 8085- (void) _saveConfig {
ffbb3bd5
JF
8086 _trace();
8087 MetaFile_.Sync();
8088 _trace();
8089
7623f855 8090 if (Changed_) {
7623f855 8091 NSString *error(nil);
ffbb3bd5 8092
7623f855
JF
8093 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8094 _trace();
8095 NSError *error(nil);
8096 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8097 NSLog(@"failure to save metadata data: %@", error);
8098 _trace();
ffbb3bd5
JF
8099
8100 Changed_ = false;
7623f855
JF
8101 } else {
8102 NSLog(@"failure to serialize metadata: %@", error);
7623f855 8103 }
7623f855
JF
8104 }
8105}
8106
8107- (void) _updateData {
8108 [self _saveConfig];
8109
8110 /* XXX: this is just stupid */
aeed65a6 8111 if (tag_ != 1 && sections_ != nil)
7623f855 8112 [sections_ reloadData];
aeed65a6 8113 if (tag_ != 2 && changes_ != nil)
7623f855 8114 [changes_ reloadData];
aeed65a6 8115 if (tag_ != 4 && search_ != nil)
7623f855
JF
8116 [search_ reloadData];
8117
c21004b9 8118 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
f6371a33
JF
8119
8120 [queueDelegate_ queueStatusDidChange];
8121 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
b5e7eebb
GP
8122}
8123
8124- (int)indexOfTabWithTag:(int)tag {
8125 int i = 0;
8126 for (UINavigationController *controller in [tabbar_ viewControllers]) {
36fbb2aa
JF
8127 if ([[controller tabBarItem] tag] == tag)
8128 return i;
b5e7eebb
GP
8129 i += 1;
8130 }
bc11cf5b 8131
b5e7eebb 8132 return -1;
7623f855
JF
8133}
8134
9aecdc9c 8135- (void) _refreshIfPossible {
8c02abc8 8136 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
bc11cf5b 8137
45e21ffa
GP
8138 bool recently = false;
8139 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8140 if (update != nil) {
8141 NSTimeInterval interval([update timeIntervalSinceNow]);
8142 if (interval <= 0 && interval > -(15*60))
8143 recently = true;
8144 }
8145
8146 // Don't automatic refresh if:
8147 // - We already refreshed recently.
8148 // - We already auto-refreshed this launch.
8149 // - Auto-refresh is disabled.
8150 if (recently || loaded_ || ManualRefresh) {
8151 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8152
8153 // If we are cancelling due to ManualRefresh or a recent refresh
8154 // we need to make sure it knows it's already loaded.
8155 loaded_ = true;
8156 return;
8157 } else {
8158 // We are going to load, so remember that.
8159 loaded_ = true;
8160 }
8161
afb5333a
JF
8162 SCNetworkReachabilityFlags flags; {
8163 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8164 SCNetworkReachabilityGetFlags(reachability, &flags);
8165 CFRelease(reachability);
8166 }
8167
8168 // XXX: this elaborate mess is what Apple is using to determine this? :(
8169 // XXX: do we care if the user has to intervene? maybe that's ok?
8170 bool reachable(
8171 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8172 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8173 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8174 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8175 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8176 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8177 )
8178 );
bc11cf5b 8179
45e21ffa
GP
8180 // If we can reach the server, auto-refresh!
8181 if (reachable)
7585ce66 8182 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9aecdc9c 8183
8c02abc8 8184 [pool release];
9aecdc9c
GP
8185}
8186
8187- (void) refreshIfPossible {
8c02abc8 8188 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9aecdc9c
GP
8189}
8190
36bb2ca2 8191- (void) _reloadData {
851f4a99
GP
8192 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8193 [hud setText:UCLocalize("RELOADING_DATA")];
dc5812ec 8194
d061f4ba 8195 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
d061f4ba 8196
36fbb2aa
JF
8197 if (hud != nil)
8198 [self removeProgressHUD:hud];
c25a610d 8199
36bb2ca2 8200 size_t changes(0);
9bedffaa 8201
a54b1c10 8202 [essential_ removeAllObjects];
9bedffaa 8203 [broken_ removeAllObjects];
b4d89997 8204
670a0494 8205 NSArray *packages([database_ packages]);
affeffc7 8206 for (Package *package in packages) {
9bedffaa
JF
8207 if ([package half])
8208 [broken_ addObject:package];
31f3cfff 8209 if ([package upgradableAndEssential:NO]) {
a54b1c10
JF
8210 if ([package essential])
8211 [essential_ addObject:package];
36bb2ca2 8212 ++changes;
a54b1c10 8213 }
36bb2ca2 8214 }
b4d89997 8215
45e21ffa 8216 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
36bb2ca2
JF
8217 if (changes != 0) {
8218 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
45e21ffa 8219 [changesItem setBadgeValue:badge];
65a03a7a 8220 [changesItem setAnimatedBadge:([essential_ count] > 0)];
bc11cf5b 8221
f79a4512
JF
8222 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8223 [self setApplicationBadge:badge];
8224 else
8225 [self setApplicationBadgeString:badge];
c25a610d 8226 } else {
45e21ffa
GP
8227 [changesItem setBadgeValue:nil];
8228 [changesItem setAnimatedBadge:NO];
bc11cf5b 8229
f79a4512
JF
8230 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8231 [self removeApplicationBadge];
8232 else // XXX: maybe use setApplicationBadgeString also?
8233 [self setApplicationIconBadgeNumber:0];
c25a610d 8234 }
b4d89997 8235
7623f855 8236 [self _updateData];
6d9712c4 8237
8c02abc8 8238 [self refreshIfPossible];
6d9712c4
JF
8239}
8240
7b0ce2da 8241- (void) updateData {
7623f855 8242 [self _updateData];
b4d89997
JF
8243}
8244
7b0ce2da
JF
8245- (void) update_ {
8246 [database_ update];
8247}
8248
8249- (void) syncData {
670a0494 8250 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7b0ce2da
JF
8251 _assert(file != NULL);
8252
670a0494
JF
8253 for (NSString *key in [Sources_ allKeys]) {
8254 NSDictionary *source([Sources_ objectForKey:key]);
7b0ce2da
JF
8255
8256 fprintf(file, "%s %s %s\n",
8257 [[source objectForKey:@"Type"] UTF8String],
8258 [[source objectForKey:@"URI"] UTF8String],
8259 [[source objectForKey:@"Distribution"] UTF8String]
8260 );
8261 }
8262
8263 fclose(file);
8264
8265 [self _saveConfig];
8266
adb61bda 8267 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
eb30da80 8268 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
36fbb2aa
JF
8269 if (IsWildcat_)
8270 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
7585ce66 8271 [tabbar_ presentModalViewController:navigation animated:YES];
b5e7eebb
GP
8272
8273 [progress
7b0ce2da
JF
8274 detachNewThreadSelector:@selector(update_)
8275 toTarget:self
8276 withObject:nil
43f3d7f6 8277 title:UCLocalize("UPDATING_SOURCES")
7b0ce2da
JF
8278 ];
8279}
8280
36bb2ca2
JF
8281- (void) reloadData {
8282 @synchronized (self) {
b5e7eebb 8283 [self _reloadData];
36bb2ca2 8284 }
b4d89997
JF
8285}
8286
8287- (void) resolve {
8288 pkgProblemResolver *resolver = [database_ resolver];
8289
8290 resolver->InstallProtect();
8291 if (!resolver->Resolve(true))
8292 _error->Discard();
2367a917
JF
8293}
8294
aa5d0de7 8295- (CGRect) popUpBounds {
b5e7eebb 8296 return [[tabbar_ view] bounds];
aa5d0de7
JF
8297}
8298
670a0494
JF
8299- (bool) perform {
8300 if (![database_ prepare])
8301 return false;
49048579 8302
adb61bda 8303 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
affeffc7 8304 [page setDelegate:self];
3931b718 8305 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
b5e7eebb 8306 [confirm_ setDelegate:self];
49048579 8307
36fbb2aa
JF
8308 if (IsWildcat_)
8309 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
7585ce66 8310 [tabbar_ presentModalViewController:confirm_ animated:YES];
670a0494
JF
8311
8312 return true;
3178d79b
JF
8313}
8314
dc63e78f
JF
8315- (void) queue {
8316 @synchronized (self) {
8317 [self perform];
8318 }
8319}
8320
8321- (void) clearPackage:(Package *)package {
8322 @synchronized (self) {
8323 [package clear];
8324 [self resolve];
8325 [self perform];
8326 }
8327}
8328
77801ff1
JF
8329- (void) installPackages:(NSArray *)packages {
8330 @synchronized (self) {
8331 for (Package *package in packages)
8332 [package install];
8333 [self resolve];
8334 [self perform];
8335 }
8336}
8337
36bb2ca2
JF
8338- (void) installPackage:(Package *)package {
8339 @synchronized (self) {
8340 [package install];
8341 [self resolve];
8342 [self perform];
8343 }
8344}
8345
8346- (void) removePackage:(Package *)package {
8347 @synchronized (self) {
8348 [package remove];
8349 [self resolve];
8350 [self perform];
8351 }
8352}
8353
8354- (void) distUpgrade {
8355 @synchronized (self) {
670a0494
JF
8356 if (![database_ upgrade])
8357 return;
36bb2ca2
JF
8358 [self perform];
8359 }
b4d89997
JF
8360}
8361
dc63e78f 8362- (void) complete {
36bb2ca2 8363 @synchronized (self) {
36bb2ca2
JF
8364 [self _reloadData];
8365 }
3178d79b
JF
8366}
8367
b5e7eebb 8368- (void) confirmWithNavigationController:(UINavigationController *)navigation {
f6371a33
JF
8369 Queuing_ = false;
8370
adb61bda 8371 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
bc11cf5b 8372
b5e7eebb
GP
8373 if (navigation != nil) {
8374 [navigation pushViewController:progress animated:YES];
8375 } else {
9cb0bff2 8376 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
36fbb2aa
JF
8377 if (IsWildcat_)
8378 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
7585ce66 8379 [tabbar_ presentModalViewController:navigation animated:YES];
b5e7eebb 8380 }
bc11cf5b 8381
b5e7eebb 8382 [progress
2367a917
JF
8383 detachNewThreadSelector:@selector(perform)
8384 toTarget:database_
8385 withObject:nil
43f3d7f6 8386 title:UCLocalize("RUNNING")
2367a917 8387 ];
235f5487
JF
8388
8389 ++locked_;
2367a917
JF
8390}
8391
39cda3a8 8392- (void) progressControllerIsComplete:(ProgressController *)progress {
235f5487 8393 --locked_;
dc63e78f 8394 [self complete];
dc5812ec
JF
8395}
8396
9b623dac 8397- (void) setPage:(CYViewController *)page {
36bb2ca2 8398 [page setDelegate:self];
b5e7eebb 8399
c21004b9 8400 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
a59e2ee6 8401 [navController setViewControllers:[NSArray arrayWithObject:page]];
36fbb2aa
JF
8402 for (CYNavigationController *page in [tabbar_ viewControllers])
8403 if (page != navController)
8404 [page setViewControllers:nil];
dc5812ec
JF
8405}
8406
9b623dac 8407- (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
b5e7eebb 8408 CYBrowserController *browser = [[[_class alloc] init] autorelease];
7b0ce2da 8409 [browser loadURL:url];
36bb2ca2 8410 return browser;
2367a917
JF
8411}
8412
adb61bda 8413- (SectionsController *) sectionsController {
f79a4512 8414 if (sections_ == nil)
adb61bda 8415 sections_ = [[SectionsController alloc] initWithDatabase:database_];
f79a4512
JF
8416 return sections_;
8417}
8418
adb61bda 8419- (ChangesController *) changesController {
01d93940 8420 if (changes_ == nil)
adb61bda 8421 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
01d93940
JF
8422 return changes_;
8423}
8424
adb61bda 8425- (ManageController *) manageController {
b5e7eebb 8426 if (manage_ == nil) {
adb61bda 8427 manage_ = (ManageController *) [[self
01d93940 8428 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
adb61bda 8429 withClass:[ManageController class]
01d93940 8430 ] retain];
36fbb2aa
JF
8431 if (!IsWildcat_)
8432 queueDelegate_ = manage_;
b5e7eebb 8433 }
01d93940
JF
8434 return manage_;
8435}
8436
adb61bda 8437- (SearchController *) searchController {
01d93940 8438 if (search_ == nil)
adb61bda 8439 search_ = [[SearchController alloc] initWithDatabase:database_];
01d93940
JF
8440 return search_;
8441}
8442
adb61bda 8443- (SourceTable *) sourcesController {
b5e7eebb
GP
8444 if (sources_ == nil)
8445 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8446 return sources_;
8447}
8448
adb61bda 8449- (InstalledController *) installedController {
b5e7eebb 8450 if (installed_ == nil) {
adb61bda 8451 installed_ = [[InstalledController alloc] initWithDatabase:database_];
36fbb2aa
JF
8452 if (IsWildcat_)
8453 queueDelegate_ = installed_;
b5e7eebb
GP
8454 }
8455 return installed_;
8456}
8457
68046ccc 8458- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
b5e7eebb 8459 int tag = [[viewController tabBarItem] tag];
559dec34 8460 if (tag == tag_) {
c21004b9 8461 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
559dec34 8462 return;
b5e7eebb 8463 } else if (tag_ == 1) {
adb61bda 8464 [[self sectionsController] resetView];
b5e7eebb 8465 }
dc5812ec 8466
06aa974d 8467 switch (tag) {
b5e7eebb 8468 case kCydiaTag: _setHomePage(self); break;
36bb2ca2 8469
adb61bda
GP
8470 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8471 case kChangesTag: [self setPage:[self changesController]]; break;
8472 case kManageTag: [self setPage:[self manageController]]; break;
8473 case kInstalledTag: [self setPage:[self installedController]]; break;
8474 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8475 case kSearchTag: [self setPage:[self searchController]]; break;
36bb2ca2 8476
670a0494 8477 _nodefault
dc5812ec
JF
8478 }
8479
06aa974d 8480 tag_ = tag;
06aa974d
JF
8481}
8482
21c6da4b 8483- (void) showSettings {
3931b718
JF
8484 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8485 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
36fbb2aa
JF
8486 if (IsWildcat_)
8487 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
7585ce66 8488 [tabbar_ presentModalViewController:nav animated:YES];
7b0ce2da
JF
8489}
8490
54043703
JF
8491- (void) retainNetworkActivityIndicator {
8492 if (activity_++ == 0)
8493 [self setNetworkActivityIndicatorVisible:YES];
8494}
8495
8496- (void) releaseNetworkActivityIndicator {
8497 if (--activity_ == 0)
8498 [self setNetworkActivityIndicatorVisible:NO];
8499}
8500
adb61bda 8501- (void) setPackageController:(PackageController *)view {
7592e053
JF
8502 WebThreadLock();
8503 [view setPackage:nil];
7592e053
JF
8504 WebThreadUnlock();
8505}
8506
adb61bda
GP
8507- (PackageController *) _packageController {
8508 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
f79a4512
JF
8509}
8510
adb61bda 8511- (PackageController *) packageController {
adb61bda 8512 return [self _packageController];
f79a4512
JF
8513}
8514
09c01bb0
GP
8515// Returns the navigation controller for the queuing badge.
8516- (id) queueBadgeController {
8517 int index = [self indexOfTabWithTag:kManageTag];
36fbb2aa
JF
8518 if (index == -1)
8519 index = [self indexOfTabWithTag:kInstalledTag];
6067f1b8 8520
09c01bb0
GP
8521 return [[tabbar_ viewControllers] objectAtIndex:index];
8522}
8523
674dce72
GP
8524- (void) cancelAndClear:(bool)clear {
8525 @synchronized (self) {
8526 if (clear) {
c6ca67ba 8527 [database_ clear];
b5e7eebb 8528 Queuing_ = false;
674dce72 8529 } else {
b5e7eebb 8530 Queuing_ = true;
6067f1b8
JF
8531 }
8532
a4217bbb 8533 [self _updateData];
674dce72 8534 }
37d2b2a9 8535}
7b0ce2da 8536
b5e7eebb
GP
8537- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8538 NSString *context([alert context]);
bc11cf5b 8539
b5e7eebb
GP
8540 if ([context isEqualToString:@"fixhalf"]) {
8541 if (button == [alert firstOtherButtonIndex]) {
37d2b2a9
GP
8542 @synchronized (self) {
8543 for (Package *broken in broken_) {
8544 [broken remove];
8545
8546 NSString *id = [broken id];
8547 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8548 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8549 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8550 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8551 }
7b0ce2da 8552
37d2b2a9
GP
8553 [self resolve];
8554 [self perform];
8555 }
b5e7eebb 8556 } else if (button == [alert cancelButtonIndex]) {
37d2b2a9
GP
8557 [broken_ removeAllObjects];
8558 [self _loaded];
7b0ce2da
JF
8559 }
8560
37d2b2a9 8561 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 8562 } else if ([context isEqualToString:@"upgrade"]) {
37d2b2a9
GP
8563 if (button == [alert firstOtherButtonIndex]) {
8564 @synchronized (self) {
8565 for (Package *essential in essential_)
8566 [essential install];
7b0ce2da 8567
37d2b2a9
GP
8568 [self resolve];
8569 [self perform];
8570 }
8571 } else if (button == [alert firstOtherButtonIndex] + 1) {
8572 [self distUpgrade];
8573 } else if (button == [alert cancelButtonIndex]) {
8574 Ignored_ = YES;
7b0ce2da
JF
8575 }
8576
37d2b2a9 8577 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 8578 }
7b0ce2da
JF
8579}
8580
670a0494
JF
8581- (void) system:(NSString *)command { _pooled
8582 system([command UTF8String]);
8583}
8584
8585- (void) applicationWillSuspend {
8586 [database_ clean];
8587 [super applicationWillSuspend];
bd150f54
JF
8588}
8589
235f5487 8590- (BOOL) isSafeToSuspend {
262afe11
GP
8591 // Use external process status API internally.
8592 // This is probably a really bad idea.
235f5487 8593 // XXX: what is the point of this? does this solve anything at all?
262afe11
GP
8594 uint64_t status = 0;
8595 int notify_token;
8596 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
8597 notify_get_state(notify_token, &status);
8598 notify_cancel(notify_token);
8599 }
8600
235f5487
JF
8601 return locked_ == 0 && status == 0;
8602}
8603
8604- (void) applicationSuspend:(__GSEvent *)event {
8605 if ([self isSafeToSuspend])
bd150f54 8606 [super applicationSuspend:event];
bd150f54
JF
8607}
8608
6d9712c4 8609- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
235f5487 8610 if ([self isSafeToSuspend])
6d9712c4
JF
8611 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8612}
8613
8614- (void) _setSuspended:(BOOL)value {
235f5487 8615 if ([self isSafeToSuspend])
6d9712c4
JF
8616 [super _setSuspended:value];
8617}
8618
7b0ce2da 8619- (UIProgressHUD *) addProgressHUD {
d061f4ba 8620 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
04fe1349
JF
8621 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8622
d061f4ba 8623 [window_ setUserInteractionEnabled:NO];
7b0ce2da 8624 [hud show:YES];
534e31fc 8625
7585ce66 8626 UIViewController *target = tabbar_;
534e31fc
GP
8627 while ([target modalViewController] != nil) target = [target modalViewController];
8628 [[target view] addSubview:hud];
8629
235f5487 8630 ++locked_;
7b0ce2da
JF
8631 return hud;
8632}
8633
d061f4ba
JF
8634- (void) removeProgressHUD:(UIProgressHUD *)hud {
8635 [hud show:NO];
8636 [hud removeFromSuperview];
8637 [window_ setUserInteractionEnabled:YES];
235f5487 8638 --locked_;
d061f4ba
JF
8639}
8640
9b623dac 8641- (CYViewController *) pageForPackage:(NSString *)name {
c390d3ab 8642 if (Package *package = [database_ packageWithName:name]) {
adb61bda 8643 PackageController *view([self packageController]);
c390d3ab
JF
8644 [view setPackage:package];
8645 return view;
8646 } else {
670a0494
JF
8647 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8648 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
b5e7eebb 8649 return [self _pageForURL:url withClass:[CYBrowserController class]];
c390d3ab
JF
8650 }
8651}
8652
9b623dac 8653- (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
c390d3ab 8654 if (tag != NULL)
aeed65a6 8655 *tag = -1;
c390d3ab 8656
43f3d7f6
JF
8657 NSString *href([url absoluteString]);
8658 if ([href hasPrefix:@"apptapp://package/"])
8659 return [self pageForPackage:[href substringFromIndex:18]];
8660
e47c4742
JF
8661 NSString *scheme([[url scheme] lowercaseString]);
8662 if (![scheme isEqualToString:@"cydia"])
8663 return nil;
8664 NSString *path([url absoluteString]);
8665 if ([path length] < 8)
8666 return nil;
8667 path = [path substringFromIndex:8];
8668 if (![path hasPrefix:@"/"])
8669 path = [@"/" stringByAppendingString:path];
8670
8671 if ([path isEqualToString:@"/add-source"])
adb61bda 8672 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
e47c4742 8673 else if ([path isEqualToString:@"/storage"])
b5e7eebb 8674 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
e47c4742 8675 else if ([path isEqualToString:@"/sources"])
b5e7eebb 8676 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
e47c4742 8677 else if ([path isEqualToString:@"/packages"])
adb61bda 8678 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
e47c4742 8679 else if ([path hasPrefix:@"/url/"])
b5e7eebb 8680 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
e47c4742
JF
8681 else if ([path hasPrefix:@"/launch/"])
8682 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8683 else if ([path hasPrefix:@"/package-settings/"])
adb61bda 8684 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
e47c4742 8685 else if ([path hasPrefix:@"/package-signature/"])
adb61bda 8686 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
e47c4742
JF
8687 else if ([path hasPrefix:@"/package/"])
8688 return [self pageForPackage:[path substringFromIndex:9]];
8689 else if ([path hasPrefix:@"/files/"]) {
8690 NSString *name = [path substringFromIndex:7];
c390d3ab
JF
8691
8692 if (Package *package = [database_ packageWithName:name]) {
b5e7eebb 8693 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
c390d3ab
JF
8694 [files setPackage:package];
8695 return files;
8696 }
8697 }
8698
8699 return nil;
8700}
8701
40364973
GP
8702- (BOOL) openCydiaURL:(NSURL *)url {
8703 CYViewController *page = nil;
8704 int tag = 0;
8705
2b4a4d25
GP
8706 NSLog(@"open url: %@", url);
8707
8708 if ((page = [self pageForURL:url hasTag:&tag])) {
40364973
GP
8709 [self setPage:page];
8710 tag_ = tag;
8711 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8712 }
8713
8714 return !!page;
8715}
8716
c390d3ab
JF
8717- (void) applicationOpenURL:(NSURL *)url {
8718 [super applicationOpenURL:url];
2b4a4d25 8719 NSLog(@"first: %@", url);
40364973
GP
8720 if (!loaded_) starturl_ = [url retain];
8721 else [self openCydiaURL:url];
c390d3ab
JF
8722}
8723
bc11cf5b 8724- (void) applicationWillResignActive:(UIApplication *)application {
7eff7ea6 8725 // Stop refreshing if you get a phone call or lock the device.
7585ce66
JF
8726 if ([tabbar_ updating])
8727 [tabbar_ cancelUpdate];
bc11cf5b 8728
ca584c15
GP
8729 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8730 [super applicationWillResignActive:application];
7eff7ea6
GP
8731}
8732
f3e11d24 8733- (void) addStashController {
235f5487 8734 ++locked_;
f3e11d24
GP
8735 stash_ = [[CYStashController alloc] init];
8736 [window_ addSubview:[stash_ view]];
8737}
8738
8739- (void) removeStashController {
8740 [[stash_ view] removeFromSuperview];
8741 [stash_ release];
235f5487 8742 --locked_;
f3e11d24
GP
8743}
8744
8745- (void) stash {
8746 [self setIdleTimerDisabled:YES];
8747
9e1f1e91 8748 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
f3e11d24
GP
8749 [self setStatusBarShowsProgress:YES];
8750 UpdateExternalStatus(1);
8751
8752 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8753
8754 UpdateExternalStatus(0);
8755 [self setStatusBarShowsProgress:NO];
8756
8757 [self removeStashController];
8758
8759 if (ExecFork() == 0) {
8760 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8761 perror("launchctl stop");
8762 }
8763}
8764
851f4a99
GP
8765- (void) setupTabBarController {
8766 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8767 [tabbar_ setDelegate:self];
8768
8769 NSMutableArray *items([NSMutableArray arrayWithObjects:
8770 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8771 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8772 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8773 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8774 nil]);
8775
8776 if (IsWildcat_) {
8777 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8778 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8779 } else {
8780 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8781 }
8782
8783 NSMutableArray *controllers([NSMutableArray array]);
8784
8785 for (UITabBarItem *item in items) {
8786 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8787 [controller setTabBarItem:item];
8788 [controllers addObject:controller];
8789 }
8790
8791 [tabbar_ setViewControllers:controllers];
851f4a99
GP
8792}
8793
bd150f54 8794- (void) applicationDidFinishLaunching:(id)unused {
7e30ba6d 8795_trace();
54043703
JF
8796 CydiaApp = self;
8797
71cc7be1
JF
8798 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8799 initWithMemoryCapacity:524288
8800 diskCapacity:10485760
8801 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8802 ] autorelease]];
8803
b5e7eebb 8804 [CYBrowserController _initialize];
ea173384 8805
bfc87a4d
JF
8806 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8807
f641a0e5
JF
8808 Font12_ = [[UIFont systemFontOfSize:12] retain];
8809 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8810 Font14_ = [[UIFont systemFontOfSize:14] retain];
8811 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8812 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8813
aeed65a6 8814 tag_ = 0;
bd150f54
JF
8815
8816 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8817 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8818
04fe1349
JF
8819 UIScreen *screen([UIScreen mainScreen]);
8820
8821 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
f641a0e5
JF
8822 [window_ orderFront:self];
8823 [window_ makeKey:self];
c390d3ab 8824 [window_ setHidden:NO];
04fe1349 8825
f3e11d24
GP
8826 if (
8827 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8828 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8829 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8830 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8831 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8832 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8833 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8834 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8835 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8836 false
8837 ) {
8838 [self addStashController];
3931b718
JF
8839 // XXX: this would be much cleaner as a yieldToSelector:
8840 // that way the removeStashController could happen right here inline
8841 // we also could no longer require the useless stash_ field anymore
f3e11d24
GP
8842 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8843 return;
8844 }
8845
770f2a8e 8846 database_ = [Database sharedInstance];
bfc87a4d 8847
851f4a99 8848 [self setupTabBarController];
7585ce66
JF
8849 [tabbar_ setUpdateDelegate:self];
8850 [window_ addSubview:[tabbar_ view]];
670a0494 8851
5ccb47d8 8852 // Show pinstripes while loading data.
7585ce66 8853 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
5ccb47d8 8854
fed0d010 8855 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
c626a63f 8856_trace();
fed0d010
JF
8857}
8858
8859- (void) loadData {
c626a63f 8860_trace();
fed0d010
JF
8861 if (Role_ == nil) {
8862 [self showSettings];
8863 return;
8864 }
8865
851f4a99 8866 [window_ setUserInteractionEnabled:NO];
670a0494 8867
dd9de556 8868 UIView *container = [[[UIView alloc] init] autorelease];
851f4a99
GP
8869 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8870
dd9de556 8871 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
851f4a99
GP
8872 [spinner startAnimating];
8873 [container addSubview:spinner];
851f4a99 8874
dd9de556 8875 UILabel *label = [[[UILabel alloc] init] autorelease];
851f4a99
GP
8876 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8877 [label setBackgroundColor:[UIColor clearColor]];
8878 [label setTextColor:[UIColor blackColor]];
8879 [label setShadowColor:[UIColor whiteColor]];
8880 [label setShadowOffset:CGSizeMake(0, 1)];
72fb3616 8881 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
851f4a99 8882 [container addSubview:label];
851f4a99
GP
8883
8884 CGSize viewsize = [[tabbar_ view] frame].size;
8885 CGSize spinnersize = [spinner bounds].size;
8886 CGSize textsize = [[label text] sizeWithFont:[label font]];
8887 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8888
8889 CGRect containrect = {
8890 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8891 CGSizeMake(bothwidth, spinnersize.height)
8892 };
8893 CGRect textrect = {
8894 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8895 textsize
8896 };
8897 CGRect spinrect = {
8898 CGPointZero,
8899 spinnersize
8900 };
8901
8902 [container setFrame:containrect];
8903 [spinner setFrame:spinrect];
8904 [label setFrame:textrect];
7585ce66 8905 [[tabbar_ view] addSubview:container];
851f4a99
GP
8906
8907 [self reloadData];
670a0494
JF
8908 PrintTimes();
8909
23ea638c 8910 // Show the initial page
40364973 8911 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
23ea638c
GP
8912 [tabbar_ setSelectedIndex:0];
8913 _setHomePage(self);
8914 }
8915
2b4a4d25
GP
8916 [starturl_ release];
8917 starturl_ = nil;
8918
851f4a99 8919 [window_ setUserInteractionEnabled:YES];
5ccb47d8
GP
8920
8921 // XXX: does this actually slow anything down?
7585ce66 8922 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
851f4a99 8923 [container removeFromSuperview];
bd150f54
JF
8924}
8925
b5e7eebb 8926- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
674dce72 8927 if (item != nil && IsWildcat_) {
b5e7eebb 8928 [sheet showFromBarButtonItem:item animated:YES];
674dce72
GP
8929 } else {
8930 [sheet showInView:window_];
8931 }
36bb2ca2
JF
8932}
8933
dc5812ec
JF
8934@end
8935
b4d89997
JF
8936/*IMP alloc_;
8937id Alloc_(id self, SEL selector) {
8938 id object = alloc_(self, selector);
c390d3ab 8939 lprintf("[%s]A-%p\n", self->isa->name, object);
b4d89997
JF
8940 return object;
8941}*/
8942
36bb2ca2
JF
8943/*IMP dealloc_;
8944id Dealloc_(id self, SEL selector) {
8945 id object = dealloc_(self, selector);
c390d3ab 8946 lprintf("[%s]D-%p\n", self->isa->name, object);
36bb2ca2
JF
8947 return object;
8948}*/
b4d89997 8949
f79a4512
JF
8950Class $WebDefaultUIKitDelegate;
8951
d791dce4 8952MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
f79a4512
JF
8953 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8954 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
d791dce4 8955 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
f79a4512
JF
8956}
8957
10d65752
RP
8958static NSNumber *shouldPlayKeyboardSounds;
8959
8960Class $UIHardware;
8961
b72246b0
JF
8962MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8963 switch (sound) {
10d65752
RP
8964 case 1104: // Keyboard Button Clicked
8965 case 1105: // Keyboard Delete Repeated
b72246b0
JF
8966 if (shouldPlayKeyboardSounds == nil) {
8967 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8968 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
10d65752 8969 }
b72246b0 8970
10d65752
RP
8971 if (![shouldPlayKeyboardSounds boolValue])
8972 break;
b72246b0 8973
10d65752 8974 default:
b72246b0 8975 _UIHardware$_playSystemSound$(self, _cmd, sound);
10d65752
RP
8976 }
8977}
8978
affeffc7 8979int main(int argc, char *argv[]) { _pooled
d6dad1b4 8980 _trace();
f79a4512 8981
01d93940
JF
8982 if (Class $UIDevice = objc_getClass("UIDevice")) {
8983 UIDevice *device([$UIDevice currentDevice]);
8984 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8985 } else
8986 IsWildcat_ = false;
8987
df213583 8988 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
677b8415 8989
7376b55c
JF
8990 /* Library Hacks {{{ */
8991 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8992
8993 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8994 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8995 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8996 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8997 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8998 }
10d65752
RP
8999
9000 $UIHardware = objc_getClass("UIHardware");
9001 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9002 if (UIHardware$_playSystemSound$ != NULL) {
9003 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9004 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9005 }
7376b55c
JF
9006 /* }}} */
9007 /* Set Locale {{{ */
f79a4512 9008 Locale_ = CFLocaleCopyCurrent();
b1ce61ec
JF
9009 Languages_ = [NSLocale preferredLanguages];
9010 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
18876387 9011 //NSLog(@"%@", [Languages_ description]);
78430d06 9012
b1ce61ec
JF
9013 const char *lang;
9014 if (Languages_ == nil || [Languages_ count] == 0)
78430d06 9015 // XXX: consider just setting to C and then falling through?
b1ce61ec 9016 lang = NULL;
78430d06 9017 else {
b1ce61ec 9018 lang = [[Languages_ objectAtIndex:0] UTF8String];
78430d06
JF
9019 setenv("LANG", lang, true);
9020 }
9021
b1ce61ec
JF
9022 //std::setlocale(LC_ALL, lang);
9023 NSLog(@"Setting Language: %s", lang);
7376b55c 9024 /* }}} */
f79a4512 9025
d791dce4 9026 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
f79a4512 9027
7376b55c 9028 /* Parse Arguments {{{ */
de3b1ab4
JF
9029 bool substrate(false);
9030
9031 if (argc != 0) {
9032 char **args(argv);
9033 int arge(1);
9034
9035 for (int argi(1); argi != argc; ++argi)
9036 if (strcmp(argv[argi], "--") == 0) {
9037 arge = argi;
9038 argv[argi] = argv[0];
9039 argv += argi;
9040 argc -= argi;
9041 break;
9042 }
9043
9044 for (int argi(1); argi != arge; ++argi)
d791dce4 9045 if (strcmp(args[argi], "--substrate") == 0)
de3b1ab4
JF
9046 substrate = true;
9047 else
9048 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9049 }
7376b55c 9050 /* }}} */
d73cede2 9051
7376b55c
JF
9052 App_ = [[NSBundle mainBundle] bundlePath];
9053 Home_ = NSHomeDirectory();
d791dce4 9054 Advanced_ = YES;
7376b55c 9055
b4d89997
JF
9056 setuid(0);
9057 setgid(0);
9058
9059 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9060 alloc_ = alloc->method_imp;
9061 alloc->method_imp = (IMP) &Alloc_;*/
9062
36bb2ca2
JF
9063 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9064 dealloc_ = dealloc->method_imp;
9065 dealloc->method_imp = (IMP) &Dealloc_;*/
9066
d791dce4 9067 /* System Information {{{ */
3178d79b 9068 size_t size;
c390d3ab
JF
9069
9070 int maxproc;
9071 size = sizeof(maxproc);
9072 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9073 perror("sysctlbyname(\"kern.maxproc\", ?)");
9074 else if (maxproc < 64) {
9075 maxproc = 64;
9076 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9077 perror("sysctlbyname(\"kern.maxproc\", #)");
9078 }
9079
bfc87a4d
JF
9080 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9081 char *osversion = new char[size];
9082 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9083 perror("sysctlbyname(\"kern.osversion\", ?)");
9084 else
9085 System_ = [NSString stringWithUTF8String:osversion];
9086
3178d79b
JF
9087 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9088 char *machine = new char[size];
c390d3ab
JF
9089 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9090 perror("sysctlbyname(\"hw.machine\", ?)");
9091 else
9092 Machine_ = machine;
3178d79b 9093
59dbe296
JF
9094 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9095 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9096 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
bfc87a4d 9097 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
59dbe296
JF
9098 CFRelease(serial);
9099 }
9100
9101 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9102 NSData *data((NSData *) ecid);
9103 size_t length([data length]);
9104 uint8_t bytes[length];
9105 [data getBytes:bytes];
9106 char string[length * 2 + 1];
9107 for (size_t i(0); i != length; ++i)
9108 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
bfc87a4d 9109 ChipID_ = [NSString stringWithUTF8String:string];
59dbe296
JF
9110 CFRelease(ecid);
9111 }
9112
9113 IOObjectRelease(service);
9114 }
9115 }
9116
87f46a96 9117 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
3178d79b 9118
567e3972
JF
9119 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9120 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9121 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9122
9123 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9124 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9125 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9126
9127 if (mcc != NULL && mnc != NULL)
9128 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9129
9130 if (mnc != NULL)
9131 CFRelease(mnc);
9132 if (mcc != NULL)
9133 CFRelease(mcc);
9134
ad5d065e
JF
9135 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9136 Build_ = [system objectForKey:@"ProductBuildVersion"];
3e9c9e85
JF
9137 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9138 Product_ = [info objectForKey:@"SafariProductVersion"];
9139 Safari_ = [info objectForKey:@"CFBundleVersion"];
9140 }
d791dce4 9141 /* }}} */
7376b55c 9142 /* Load Database {{{ */
d6dad1b4 9143 _trace();
f79a4512
JF
9144 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9145 _trace();
9146 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
d6dad1b4
JF
9147
9148 if (Metadata_ == NULL)
f79a4512 9149 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
6d9712c4 9150 else {
2bdd73bd 9151 Settings_ = [Metadata_ objectForKey:@"Settings"];
7b0ce2da 9152
b4d89997 9153 Packages_ = [Metadata_ objectForKey:@"Packages"];
6d9712c4 9154 Sections_ = [Metadata_ objectForKey:@"Sections"];
7b0ce2da 9155 Sources_ = [Metadata_ objectForKey:@"Sources"];
ef055c6c
JF
9156
9157 Token_ = [Metadata_ objectForKey:@"Token"];
7b0ce2da
JF
9158 }
9159
9160 if (Settings_ != nil)
9161 Role_ = [Settings_ objectForKey:@"Role"];
9162
7b0ce2da
JF
9163 if (Sections_ == nil) {
9164 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9165 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9166 }
9167
9168 if (Sources_ == nil) {
9169 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9170 [Metadata_ setObject:Sources_ forKey:@"Sources"];
6d9712c4 9171 }
7376b55c 9172 /* }}} */
b4d89997 9173
94b0b3e5
JF
9174 _trace();
9175 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9176 _trace();
9177
9178 if (Packages_ != nil) {
9179 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9180 _trace();
9181 [Metadata_ removeObjectForKey:@"Packages"];
9182 Packages_ = nil;
9183 Changed_ = true;
9184 }
9185
d791dce4
JF
9186 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9187
01d93940
JF
9188 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9189 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9dd60d81
JF
9190 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9191 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9192 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9193 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
dddbc481 9194
01d93940
JF
9195 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9196
3b0f10b0 9197 if (access("/tmp/.cydia.fw", F_OK) == 0) {
ea173384 9198 unlink("/tmp/.cydia.fw");
3b0f10b0 9199 goto firmware;
77801ff1 9200 } else if (access("/User", F_OK) != 0 || version < 2) {
3b0f10b0 9201 firmware:
d6dad1b4 9202 _trace();
26c2dd8c 9203 system("/usr/libexec/cydia/firmware.sh");
d6dad1b4
JF
9204 _trace();
9205 }
9e98e020 9206
87f46a96
JF
9207 _assert([[NSFileManager defaultManager]
9208 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9209 withIntermediateDirectories:YES
9210 attributes:nil
9211 error:NULL
9212 ]);
9213
7376b55c
JF
9214 if (access("/tmp/cydia.chk", F_OK) == 0) {
9215 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9216 _assert(errno == ENOENT);
9217 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9218 _assert(errno == ENOENT);
9219 }
9220
59dbe296 9221 /* APT Initialization {{{ */
b1ce61ec
JF
9222 _assert(pkgInitConfig(*_config));
9223 _assert(pkgInitSystem(*_config, _system));
9224
9225 if (lang != NULL)
9226 _config->Set("APT::Acquire::Translation", lang);
cb94ff21
JF
9227
9228 // XXX: this timeout might be important :(
9229 //_config->Set("Acquire::http::Timeout", 15);
9230
7623f855 9231 _config->Set("Acquire::http::MaxParallel", 3);
59dbe296 9232 /* }}} */
7376b55c 9233 /* Color Choices {{{ */
36bb2ca2
JF
9234 space_ = CGColorSpaceCreateDeviceRGB();
9235
f641a0e5 9236 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
77fcccaf 9237 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
36bb2ca2 9238 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
baf80942 9239 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
36bb2ca2 9240 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
7b0ce2da 9241 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
3bd1c2a2
JF
9242 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9243 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9244 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
59dbe296 9245
dc63e78f
JF
9246 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9247 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
7376b55c 9248 /* }}}*/
7376b55c 9249 /* UIKit Configuration {{{ */
f79a4512
JF
9250 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9251 if ($GSFontSetUseLegacyFontMetrics != NULL)
9252 $GSFontSetUseLegacyFontMetrics(YES);
7b0ce2da 9253
600d005d
JF
9254 // XXX: I have a feeling this was important
9255 //UIKeyboardDisableAutomaticAppearance();
7376b55c 9256 /* }}} */
87f46a96 9257
670a0494 9258 Colon_ = UCLocalize("COLON_DELIMITED");
72fb3616 9259 Elision_ = UCLocalize("ELISION");
670a0494
JF
9260 Error_ = UCLocalize("ERROR");
9261 Warning_ = UCLocalize("WARNING");
9262
d6dad1b4 9263 _trace();
77df4f82 9264 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
36bb2ca2
JF
9265
9266 CGColorSpaceRelease(space_);
199d0ba5 9267 CFRelease(Locale_);
36bb2ca2 9268
36bb2ca2 9269 return value;
6d166849 9270}