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