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