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