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