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