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