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