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