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