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