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