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