]> git.saurik.com Git - cydia.git/blame - Cydia.mm
Various stability issues.
[cydia.git] / Cydia.mm
CommitLineData
e057ec05
JF
1/* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008 Jay Freeman (saurik)
3*/
4
5/*
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
9 *
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
17 * distribution.
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36*/
37
83105e6e
JF
38// XXX: wtf/FastMalloc.h... wtf?
39#define USE_SYSTEM_MALLOC 1
40
a75f53e7 41/* #include Directives {{{ */
f159ecd4
JF
42#import "UICaboodle.h"
43
7cf54836 44#include <objc/message.h>
59efd93a
JF
45#include <objc/objc.h>
46#include <objc/runtime.h>
47
b0d03ade 48#include <CoreGraphics/CoreGraphics.h>
9856894f 49#include <GraphicsServices/GraphicsServices.h>
b0d03ade 50#include <Foundation/Foundation.h>
853d14d3 51
66abcbb0
JF
52#if 0
53#define DEPLOYMENT_TARGET_MACOSX 1
54#define CF_BUILDING_CF 1
55#include <CoreFoundation/CFInternal.h>
56#endif
57
43b742af
JF
58#include <CoreFoundation/CFPriv.h>
59#include <CoreFoundation/CFUniChar.h>
60
853d14d3 61#import <QuartzCore/CALayer.h>
87c76914 62#import <UIKit/UIKit.h>
d210b85d 63
6932575e
JF
64#include <WebCore/WebCoreThread.h>
65#import <WebKit/WebDefaultUIKitDelegate.h>
77f175ac 66
43b742af 67#include <algorithm>
3bddda52 68#include <iomanip>
4941f41d 69#include <sstream>
8993ad57
JF
70#include <string>
71
4941f41d
JF
72#include <ext/stdio_filebuf.h>
73
a75f53e7
JF
74#include <apt-pkg/acquire.h>
75#include <apt-pkg/acquire-item.h>
76#include <apt-pkg/algorithms.h>
77#include <apt-pkg/cachefile.h>
d72d91aa 78#include <apt-pkg/clean.h>
a75f53e7 79#include <apt-pkg/configuration.h>
3e3977a2 80#include <apt-pkg/debindexfile.h>
2d28b35a 81#include <apt-pkg/debmetaindex.h>
a75f53e7
JF
82#include <apt-pkg/error.h>
83#include <apt-pkg/init.h>
1eb0c554 84#include <apt-pkg/mmap.h>
a75f53e7 85#include <apt-pkg/pkgrecords.h>
1eb0c554 86#include <apt-pkg/sha1.h>
a75f53e7 87#include <apt-pkg/sourcelist.h>
4941f41d 88#include <apt-pkg/sptr.h>
f464053e 89#include <apt-pkg/strutl.h>
b8b1cfd0 90#include <apt-pkg/tagfile.h>
a75f53e7 91
6932575e
JF
92#include <apr-1/apr_pools.h>
93
2cb68ddf
JF
94#include <sys/types.h>
95#include <sys/stat.h>
2d28b35a 96#include <sys/sysctl.h>
65fe894c
JF
97#include <sys/param.h>
98#include <sys/mount.h>
2cb68ddf 99
fc675b93 100#include <notify.h>
1eb0c554 101#include <dlfcn.h>
2d28b35a 102
686e302f
JF
103extern "C" {
104#include <mach-o/nlist.h>
105}
106
8993ad57
JF
107#include <cstdio>
108#include <cstdlib>
109#include <cstring>
686e302f 110
4941f41d 111#include <errno.h>
a75f53e7 112#include <pcre.h>
d210b85d 113
6932575e
JF
114#include <ext/hash_map>
115
d210b85d
JF
116#import "BrowserView.h"
117#import "ResetView.h"
2bfeaf6f
JF
118
119#import "substrate.h"
a75f53e7 120/* }}} */
2d28b35a 121
f464053e
JF
122//#define _finline __attribute__((force_inline))
123#define _finline inline
4d2ac731 124
f159ecd4
JF
125struct timeval _ltv;
126bool _itv;
127
128#define _limit(count) do { \
129 static size_t _count(0); \
130 if (++_count == count) \
131 exit(0); \
132} while (false)
133
6932575e 134/* Profiler {{{ */
e2a207dd
JF
135#define _timestamp ({ \
136 struct timeval tv; \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
139})
140
3bddda52
JF
141typedef std::vector<class ProfileTime *> TimeList;
142TimeList times_;
143
144class ProfileTime {
145 private:
146 const char *name_;
147 uint64_t total_;
142bd2db 148 uint64_t count_;
3bddda52
JF
149
150 public:
151 ProfileTime(const char *name) :
152 name_(name),
153 total_(0)
154 {
155 times_.push_back(this);
156 }
157
158 void AddTime(uint64_t time) {
159 total_ += time;
142bd2db 160 ++count_;
3bddda52
JF
161 }
162
163 void Print() {
164 if (total_ != 0)
142bd2db 165 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
3bddda52 166 total_ = 0;
142bd2db 167 count_ = 0;
3bddda52
JF
168 }
169};
170
171class ProfileTimer {
172 private:
173 ProfileTime &time_;
174 uint64_t start_;
175
176 public:
177 ProfileTimer(ProfileTime &time) :
178 time_(time),
179 start_(_timestamp)
180 {
181 }
182
183 ~ProfileTimer() {
184 time_.AddTime(_timestamp - start_);
185 }
186};
187
188void PrintTimes() {
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 (*i)->Print();
191 std::cerr << "========" << std::endl;
192}
193
194#define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
197
198#define _end }
6932575e 199/* }}} */
f464053e
JF
200/* Objective-C Handle<> {{{ */
201template <typename Type_>
202class _H {
203 typedef _H<Type_> This_;
c045fc11 204
f464053e
JF
205 private:
206 Type_ *value_;
c045fc11 207
f464053e
JF
208 _finline void Retain_() {
209 if (value_ != nil)
210 [value_ retain];
211 }
c045fc11 212
f464053e
JF
213 _finline void Clear_() {
214 if (value_ != nil)
215 [value_ release];
216 }
c045fc11 217
f464053e
JF
218 public:
219 _finline _H(Type_ *value = NULL, bool mended = false) :
220 value_(value)
221 {
222 if (!mended)
223 Retain_();
224 }
171bba0e 225
f464053e
JF
226 _finline ~_H() {
227 Clear_();
228 }
c045fc11 229
631a0a1e
JF
230 _finline operator Type_ *() const {
231 return value_;
232 }
233
f464053e
JF
234 _finline This_ &operator =(Type_ *value) {
235 if (value_ != value) {
631a0a1e 236 Type_ *old(value_);
f464053e
JF
237 value_ = value;
238 Retain_();
631a0a1e
JF
239 if (old != nil)
240 [old release];
241 } return *this;
f464053e
JF
242 }
243};
244/* }}} */
245
246#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
247
541a556a
JF
248void NSLogPoint(const char *fix, const CGPoint &point) {
249 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
250}
251
f464053e
JF
252void NSLogRect(const char *fix, const CGRect &rect) {
253 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
c045fc11
JF
254}
255
7398a389 256@interface NSObject (Cydia)
b4dff19a
JF
257- (id) yieldToSelector:(SEL)selector withObject:(id)object;
258- (id) yieldToSelector:(SEL)selector;
7398a389
JF
259@end
260
261@implementation NSObject (Cydia)
262
263- (void) doNothing {
264}
265
b4dff19a 266- (void) _yieldToContext:(NSMutableArray *)context { _pooled
7398a389
JF
267 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
268 id object([[context objectAtIndex:1] nonretainedObjectValue]);
269 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
270
b4dff19a
JF
271 /* XXX: deal with exceptions */
272 id value([self performSelector:selector withObject:object]);
273
43b742af 274 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
b4dff19a 275 [context removeAllObjects];
43b742af 276 if ([signature methodReturnLength] != 0 && value != nil)
b4dff19a 277 [context addObject:value];
7398a389
JF
278
279 stopped = true;
280
281 [self
282 performSelectorOnMainThread:@selector(doNothing)
283 withObject:nil
284 waitUntilDone:NO
285 ];
286}
287
b4dff19a 288- (id) yieldToSelector:(SEL)selector withObject:(id)object {
7b00c562 289 /*return [self performSelector:selector withObject:object];*/
3bddda52 290
7398a389
JF
291 volatile bool stopped(false);
292
b4dff19a 293 NSMutableArray *context([NSMutableArray arrayWithObjects:
7398a389
JF
294 [NSValue valueWithPointer:selector],
295 [NSValue valueWithNonretainedObject:object],
296 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
297 nil]);
298
299 NSThread *thread([[[NSThread alloc]
300 initWithTarget:self
301 selector:@selector(_yieldToContext:)
302 object:context
303 ] autorelease]);
304
305 [thread start];
306
307 NSRunLoop *loop([NSRunLoop currentRunLoop]);
308 NSDate *future([NSDate distantFuture]);
309
310 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
b4dff19a
JF
311
312 return [context count] == 0 ? nil : [context objectAtIndex:0];
313}
314
315- (id) yieldToSelector:(SEL)selector {
316 return [self yieldToSelector:selector withObject:nil];
7398a389
JF
317}
318
319@end
320
9c4e0cbe 321/* NSForcedOrderingSearch doesn't work on the iPhone */
3bddda52 322static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
43b742af
JF
323static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
324static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
c045fc11 325
f464053e
JF
326/* iPhoneOS 2.0 Compatibility {{{ */
327#ifdef __OBJC2__
c045fc11
JF
328@interface UITextView (iPhoneOS)
329- (void) setTextSize:(float)size;
330@end
331
332@implementation UITextView (iPhoneOS)
333
334- (void) setTextSize:(float)size {
335 [self setFont:[[self font] fontWithSize:size]];
336}
337
338@end
242bcc6d 339#endif
c045fc11 340/* }}} */
242bcc6d 341
cb9c2100
JF
342extern NSString * const kCAFilterNearest;
343
7f9c29fa
JF
344/* Information Dictionaries {{{ */
345@interface NSMutableArray (Cydia)
346- (void) addInfoDictionary:(NSDictionary *)info;
347@end
348
349@implementation NSMutableArray (Cydia)
350
351- (void) addInfoDictionary:(NSDictionary *)info {
352 [self addObject:info];
353}
354
355@end
356
357@interface NSMutableDictionary (Cydia)
358- (void) addInfoDictionary:(NSDictionary *)info;
359@end
360
361@implementation NSMutableDictionary (Cydia)
362
363- (void) addInfoDictionary:(NSDictionary *)info {
364 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
365 [self setObject:info forKey:bundle];
366}
367
f464053e
JF
368@end
369/* }}} */
370/* Pop Transitions {{{ */
371@interface PopTransitionView : UITransitionView {
372}
373
374@end
375
376@implementation PopTransitionView
377
0a7e5478 378- (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
f464053e
JF
379 if (from != nil && to == nil)
380 [self removeFromSuperview];
381}
382
383@end
384
f464053e
JF
385@implementation UIView (PopUpView)
386
387- (void) popFromSuperviewAnimated:(BOOL)animated {
388 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
389}
390
391- (void) popSubview:(UIView *)view {
392 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
393 [transition setDelegate:transition];
394 [self addSubview:transition];
395
396 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
397 [transition transition:UITransitionNone toView:blank];
398 [transition transition:UITransitionPushFromBottom toView:view];
399}
400
7f9c29fa
JF
401@end
402/* }}} */
403
cb9c2100 404#define lprintf(args...) fprintf(stderr, args)
d210b85d 405
6932575e 406#define ForRelease 0
1ff58dbb 407#define TraceLogging (1 && !ForRelease)
956b73c3 408#define HistogramInsertionSort (0 && !ForRelease)
b8b1cfd0 409#define ProfileTimes (0 && !ForRelease)
7afcea1c 410#define ForSaurik (0 && !ForRelease)
b8b1cfd0 411#define LogBrowser (1 && !ForRelease)
bb9edf8b 412#define TrackResize (0 && !ForRelease)
d8d9a65c 413#define ManualRefresh (1 && !ForRelease)
6932575e 414#define ShowInternals (0 && !ForRelease)
83105e6e 415#define IgnoreInstall (0 && !ForRelease)
f464053e 416#define RecycleWebViews 0
6932575e 417#define AlwaysReload (1 && !ForRelease)
81ab76dc 418
1ff58dbb 419#if !TraceLogging
6e673d99
JF
420#undef _trace
421#define _trace(args...)
1ff58dbb
JF
422#endif
423
424#if !ProfileTimes
3bddda52 425#undef _profile
7b00c562 426#define _profile(name) {
3bddda52 427#undef _end
7b00c562 428#define _end }
b4dff19a 429#define PrintTimes() do {} while (false)
6e673d99
JF
430#endif
431
f159ecd4 432/* Radix Sort {{{ */
dd9390c5
JF
433typedef uint32_t (*SKRadixFunction)(id, void *);
434
f159ecd4 435@interface NSMutableArray (Radix)
907a35d6 436- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
dd9390c5 437- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
f159ecd4
JF
438@end
439
6932575e
JF
440struct RadixItem_ {
441 size_t index;
442 uint32_t key;
443};
f159ecd4 444
6932575e
JF
445static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
446 struct RadixItem_ *lhs(swap), *rhs(swap + count);
f159ecd4 447
890c1d38 448 static const size_t width = 32;
f159ecd4
JF
449 static const size_t bits = 11;
450 static const size_t slots = 1 << bits;
890c1d38 451 static const size_t passes = (width + (bits - 1)) / bits;
f159ecd4
JF
452
453 size_t *hist(new size_t[slots]);
454
455 for (size_t pass(0); pass != passes; ++pass) {
456 memset(hist, 0, sizeof(size_t) * slots);
457
458 for (size_t i(0); i != count; ++i) {
459 uint32_t key(lhs[i].key);
460 key >>= pass * bits;
890c1d38 461 key &= _not(uint32_t) >> width - bits;
f159ecd4
JF
462 ++hist[key];
463 }
464
465 size_t offset(0);
466 for (size_t i(0); i != slots; ++i) {
467 size_t local(offset);
468 offset += hist[i];
469 hist[i] = local;
470 }
471
472 for (size_t i(0); i != count; ++i) {
473 uint32_t key(lhs[i].key);
474 key >>= pass * bits;
890c1d38 475 key &= _not(uint32_t) >> width - bits;
f159ecd4
JF
476 rhs[hist[key]++] = lhs[i];
477 }
478
6932575e 479 RadixItem_ *tmp(lhs);
f159ecd4
JF
480 lhs = rhs;
481 rhs = tmp;
482 }
483
484 delete [] hist;
485
486 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
487 for (size_t i(0); i != count; ++i)
488 [values addObject:[self objectAtIndex:lhs[i].index]];
489 [self setArray:values];
490
491 delete [] swap;
492}
493
6932575e
JF
494@implementation NSMutableArray (Radix)
495
496- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
66abcbb0
JF
497 size_t count([self count]);
498 if (count == 0)
499 return;
500
501#if 0
6932575e
JF
502 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
503 [invocation setSelector:selector];
504 [invocation setArgument:&object atIndex:2];
66abcbb0
JF
505#else
506 /* XXX: this is an unsafe optimization of doomy hell */
507 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
508 _assert(method != NULL);
509 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
510 _assert(imp != NULL);
511#endif
6932575e 512
6932575e
JF
513 struct RadixItem_ *swap(new RadixItem_[count * 2]);
514
515 for (size_t i(0); i != count; ++i) {
516 RadixItem_ &item(swap[i]);
517 item.index = i;
518
519 id object([self objectAtIndex:i]);
6932575e 520
66abcbb0
JF
521#if 0
522 [invocation setTarget:object];
6932575e
JF
523 [invocation invoke];
524 [invocation getReturnValue:&item.key];
66abcbb0
JF
525#else
526 item.key = imp(object, selector, object);
527#endif
6932575e
JF
528 }
529
530 RadixSort_(self, count, swap);
531}
532
dd9390c5 533- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
6932575e
JF
534 size_t count([self count]);
535 struct RadixItem_ *swap(new RadixItem_[count * 2]);
536
537 for (size_t i(0); i != count; ++i) {
538 RadixItem_ &item(swap[i]);
539 item.index = i;
540
541 id object([self objectAtIndex:i]);
542 item.key = function(object, argument);
543 }
544
545 RadixSort_(self, count, swap);
546}
547
f159ecd4 548@end
66abcbb0
JF
549/* }}} */
550/* Insertion Sort {{{ */
551
dd9390c5
JF
552CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
553 const char *ptr = (const char *)list;
554 while (0 < count) {
555 CFIndex half = count / 2;
556 const char *probe = ptr + elementSize * half;
557 CFComparisonResult cr = comparator(element, probe, context);
558 if (0 == cr) return (probe - (const char *)list) / elementSize;
559 ptr = (cr < 0) ? ptr : probe + elementSize;
560 count = (cr < 0) ? half : (half + (count & 1) - 1);
561 }
562 return (ptr - (const char *)list) / elementSize;
563}
564
66abcbb0
JF
565CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
566 const char *ptr = (const char *)list;
567 while (0 < count) {
568 CFIndex half = count / 2;
569 const char *probe = ptr + elementSize * half;
570 CFComparisonResult cr = comparator(element, probe, context);
571 if (0 == cr) return (probe - (const char *)list) / elementSize;
572 ptr = (cr < 0) ? ptr : probe + elementSize;
573 count = (cr < 0) ? half : (half + (count & 1) - 1);
574 }
575 return (ptr - (const char *)list) / elementSize;
576}
577
578void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
579 if (range.length == 0)
580 return;
581 const void **values(new const void *[range.length]);
582 CFArrayGetValues(array, range, values);
583
dd9390c5
JF
584#if HistogramInsertionSort
585 uint32_t total(0), *offsets(new uint32_t[range.length]);
586#endif
587
66abcbb0
JF
588 for (CFIndex index(1); index != range.length; ++index) {
589 const void *value(values[index]);
dd9390c5
JF
590 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
591 CFIndex correct(index);
592 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
593 if (--correct == 0)
594 break;
66abcbb0 595 if (correct != index) {
dd9390c5
JF
596 size_t offset(index - correct);
597#if HistogramInsertionSort
598 total += offset;
599 ++offsets[offset];
600 if (offset > 10)
601 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
602#endif
603 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
66abcbb0
JF
604 values[correct] = value;
605 }
606 }
607
608 CFArrayReplaceValues(array, range, values, range.length);
609 delete [] values;
dd9390c5
JF
610
611#if HistogramInsertionSort
612 for (CFIndex index(0); index != range.length; ++index)
613 if (offsets[index] != 0)
614 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
615 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
616 delete [] offsets;
617#endif
66abcbb0
JF
618}
619
f159ecd4
JF
620/* }}} */
621
541a556a
JF
622/* Apple Bug Fixes {{{ */
623@implementation UIWebDocumentView (Cydia)
624
625- (void) _setScrollerOffset:(CGPoint)offset {
626 UIScroller *scroller([self _scroller]);
627
628 CGSize size([scroller contentSize]);
629 CGSize bounds([scroller bounds].size);
630
631 CGPoint max;
632 max.x = size.width - bounds.width;
633 max.y = size.height - bounds.height;
634
635 // wtf Apple?!
636 if (max.x < 0)
637 max.x = 0;
638 if (max.y < 0)
639 max.y = 0;
640
641 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
642 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
643
644 [scroller setOffset:offset];
645}
646
647@end
648/* }}} */
649
238b07ce
JF
650typedef enum {
651 kUIControlEventMouseDown = 1 << 0,
652 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
653 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
654 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
655 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
656 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
657} UIControlEventMasks;
658
cd8bec2f
JF
659NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
660 size_t length([self length] - state->state);
661 if (length <= 0)
662 return 0;
663 else if (length > count)
664 length = count;
665 for (size_t i(0); i != length; ++i)
666 objects[i] = [self item:state->state++];
667 state->itemsPtr = objects;
668 state->mutationsPtr = (unsigned long *) self;
669 return length;
670}
671
2a987aa5
JF
672@interface NSString (UIKit)
673- (NSString *) stringByAddingPercentEscapes;
674- (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
675@end
676
677@interface NSString (Cydia)
3bddda52 678+ (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
6932575e 679+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
2a987aa5 680+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
9e07091a 681- (NSComparisonResult) compareByPath:(NSString *)other;
b4dff19a
JF
682- (NSString *) stringByCachingURLWithCurrentCDN;
683- (NSString *) stringByAddingPercentEscapesIncludingReserved;
2a987aa5
JF
684@end
685
686@implementation NSString (Cydia)
687
3bddda52
JF
688+ (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
689 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
690}
691
6932575e
JF
692+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
693 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
694 memcpy(data, bytes, length);
695 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
696}
697
2a987aa5 698+ (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
e2a207dd 699 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
2a987aa5
JF
700}
701
9e07091a
JF
702- (NSComparisonResult) compareByPath:(NSString *)other {
703 NSString *prefix = [self commonPrefixWithString:other options:0];
704 size_t length = [prefix length];
705
706 NSRange lrange = NSMakeRange(length, [self length] - length);
707 NSRange rrange = NSMakeRange(length, [other length] - length);
708
709 lrange = [self rangeOfString:@"/" options:0 range:lrange];
710 rrange = [other rangeOfString:@"/" options:0 range:rrange];
711
712 NSComparisonResult value;
713
714 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
715 value = NSOrderedSame;
716 else if (lrange.location == NSNotFound)
717 value = NSOrderedAscending;
718 else if (rrange.location == NSNotFound)
719 value = NSOrderedDescending;
720 else
721 value = NSOrderedSame;
722
723 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
724 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
725 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
726 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
727
728 NSComparisonResult result = [lpath compare:rpath];
729 return result == NSOrderedSame ? value : result;
730}
731
b4dff19a
JF
732- (NSString *) stringByCachingURLWithCurrentCDN {
733 return [self
734 stringByReplacingOccurrencesOfString:@"://"
735 withString:@"://ne.edgecastcdn.net/8003A4/"
736 options:0
737 /* XXX: this is somewhat inaccurate */
738 range:NSMakeRange(0, 10)
739 ];
740}
741
742- (NSString *) stringByAddingPercentEscapesIncludingReserved {
743 return [(id)CFURLCreateStringByAddingPercentEscapes(
744 kCFAllocatorDefault,
745 (CFStringRef) self,
746 NULL,
747 CFSTR(";/?:@&=+$,"),
748 kCFStringEncodingUTF8
749 ) autorelease];
750}
751
2a987aa5
JF
752@end
753
6932575e
JF
754static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
755 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
756}
757
758#define CYLocalize(key) CYLocalizeEx(@ key)
759
760class CYString {
761 private:
762 char *data_;
763 size_t size_;
764 CFStringRef cache_;
765
766 _finline void clear_() {
767 if (cache_ != nil)
768 CFRelease(cache_);
769 }
770
771 public:
772 _finline bool empty() const {
773 return size_ == 0;
774 }
775
776 _finline size_t size() const {
777 return size_;
778 }
779
780 _finline char *data() const {
781 return data_;
782 }
783
784 _finline void clear() {
785 size_ = 0;
786 clear_();
787 }
788
789 _finline CYString() :
790 data_(0),
791 size_(0),
792 cache_(nil)
793 {
794 }
795
796 _finline ~CYString() {
797 clear_();
798 }
799
800 void operator =(const CYString &rhs) {
801 data_ = rhs.data_;
802 size_ = rhs.size_;
803
804 if (rhs.cache_ == nil)
805 cache_ = NULL;
806 else
807 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
808 }
809
810 void set(apr_pool_t *pool, const char *data, size_t size) {
811 if (size == 0)
812 clear();
813 else {
814 clear_();
815
9ee296df 816 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
6932575e 817 memcpy(temp, data, size);
9ee296df 818 temp[size] = '\0';
6932575e
JF
819 data_ = temp;
820 size_ = size;
821 }
822 }
823
824 _finline void set(apr_pool_t *pool, const char *data) {
825 set(pool, data, data == NULL ? 0 : strlen(data));
826 }
827
828 _finline void set(apr_pool_t *pool, const std::string &rhs) {
829 set(pool, rhs.data(), rhs.size());
830 }
831
832 bool operator ==(const CYString &rhs) const {
833 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
834 }
835
dd9390c5 836 operator CFStringRef() {
6932575e
JF
837 if (cache_ == NULL) {
838 if (size_ == 0)
839 return nil;
840 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
dd9390c5
JF
841 } return cache_;
842 }
843
844 _finline operator id() {
845 return (NSString *) static_cast<CFStringRef>(*this);
6932575e
JF
846 }
847};
848
849extern "C" {
850 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
851}
852
853struct NSStringMapHash :
854 std::unary_function<NSString *, size_t>
855{
856 _finline size_t operator ()(NSString *value) const {
857 return CFStringHashNSString((CFStringRef) value);
858 }
859};
860
861struct NSStringMapLess :
862 std::binary_function<NSString *, NSString *, bool>
863{
864 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
865 return [lhs compare:rhs] == NSOrderedAscending;
866 }
867};
868
869struct NSStringMapEqual :
870 std::binary_function<NSString *, NSString *, bool>
871{
872 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
873 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
874 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
875 //[lhs isEqualToString:rhs];
876 }
877};
878
686e302f
JF
879/* Perl-Compatible RegEx {{{ */
880class Pcre {
881 private:
882 pcre *code_;
883 pcre_extra *study_;
884 int capture_;
885 int *matches_;
886 const char *data_;
887
888 public:
889 Pcre(const char *regex) :
890 study_(NULL)
891 {
892 const char *error;
893 int offset;
894 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
895
896 if (code_ == NULL) {
cb9c2100 897 lprintf("%d:%s\n", offset, error);
686e302f
JF
898 _assert(false);
899 }
900
901 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
902 matches_ = new int[(capture_ + 1) * 3];
903 }
904
905 ~Pcre() {
906 pcre_free(code_);
907 delete matches_;
908 }
909
910 NSString *operator [](size_t match) {
2a987aa5 911 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
686e302f
JF
912 }
913
7600bd69
JF
914 bool operator ()(NSString *data) {
915 // XXX: length is for characters, not for bytes
916 return operator ()([data UTF8String], [data length]);
917 }
918
686e302f
JF
919 bool operator ()(const char *data, size_t size) {
920 data_ = data;
921 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
922 }
923};
924/* }}} */
e057ec05 925/* Mime Addresses {{{ */
e057ec05
JF
926@interface Address : NSObject {
927 NSString *name_;
ad554f10 928 NSString *address_;
e057ec05
JF
929}
930
931- (NSString *) name;
ad554f10 932- (NSString *) address;
e057ec05 933
3ff1504e
JF
934- (void) setAddress:(NSString *)address;
935
e057ec05
JF
936+ (Address *) addressWithString:(NSString *)string;
937- (Address *) initWithString:(NSString *)string;
938@end
939
940@implementation Address
941
942- (void) dealloc {
943 [name_ release];
ad554f10
JF
944 if (address_ != nil)
945 [address_ release];
e057ec05
JF
946 [super dealloc];
947}
948
949- (NSString *) name {
950 return name_;
951}
952
ad554f10
JF
953- (NSString *) address {
954 return address_;
e057ec05
JF
955}
956
3ff1504e
JF
957- (void) setAddress:(NSString *)address {
958 if (address_ != nil)
959 [address_ autorelease];
960 if (address == nil)
961 address_ = nil;
962 else
963 address_ = [address retain];
964}
965
e057ec05
JF
966+ (Address *) addressWithString:(NSString *)string {
967 return [[[Address alloc] initWithString:string] autorelease];
968}
969
ad554f10
JF
970+ (NSArray *) _attributeKeys {
971 return [NSArray arrayWithObjects:@"address", @"name", nil];
972}
973
974- (NSArray *) attributeKeys {
975 return [[self class] _attributeKeys];
976}
977
978+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
979 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
980}
981
e057ec05
JF
982- (Address *) initWithString:(NSString *)string {
983 if ((self = [super init]) != nil) {
984 const char *data = [string UTF8String];
985 size_t size = [string length];
986
ad554f10 987 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
faf4eb4f 988
ad554f10
JF
989 if (address_r(data, size)) {
990 name_ = [address_r[1] retain];
991 address_ = [address_r[2] retain];
e057ec05 992 } else {
f464053e 993 name_ = [string retain];
ad554f10 994 address_ = nil;
e057ec05
JF
995 }
996 } return self;
997}
998
999@end
1000/* }}} */
b0d03ade 1001/* CoreGraphics Primitives {{{ */
686e302f
JF
1002class CGColor {
1003 private:
1004 CGColorRef color_;
1005
1006 public:
e057ec05
JF
1007 CGColor() :
1008 color_(NULL)
1009 {
1010 }
1011
1012 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1013 color_(NULL)
1014 {
1015 Set(space, red, green, blue, alpha);
1016 }
1017
1018 void Clear() {
1019 if (color_ != NULL)
1020 CGColorRelease(color_);
686e302f
JF
1021 }
1022
1023 ~CGColor() {
e057ec05
JF
1024 Clear();
1025 }
1026
1027 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1028 Clear();
1029 float color[] = {red, green, blue, alpha};
1030 color_ = CGColorCreate(space, color);
686e302f
JF
1031 }
1032
1033 operator CGColorRef() {
1034 return color_;
1035 }
1036};
686e302f
JF
1037/* }}} */
1038
5e563e79
JF
1039extern "C" void UISetColor(CGColorRef color);
1040
e057ec05 1041/* Random Global Variables {{{ */
2d28b35a 1042static const int PulseInterval_ = 50000;
2a987aa5 1043static const int ButtonBarHeight_ = 48;
fa7bb92f 1044static const float KeyboardTime_ = 0.3f;
f464053e
JF
1045
1046#define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1047#define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
bde2d79b 1048#define NotifyConfig_ "/etc/notify.conf"
fc675b93 1049
3ff1504e
JF
1050static bool Queuing_;
1051
5e563e79 1052static CGColor Blue_;
d72d91aa 1053static CGColor Blueish_;
e057ec05 1054static CGColor Black_;
87c76914 1055static CGColor Off_;
e057ec05 1056static CGColor White_;
faf4eb4f 1057static CGColor Gray_;
d8d9a65c
JF
1058static CGColor Green_;
1059static CGColor Purple_;
1060static CGColor Purplish_;
1061
3ff1504e
JF
1062static UIColor *InstallingColor_;
1063static UIColor *RemovingColor_;
e057ec05 1064
853d14d3 1065static NSString *App_;
0039464f
JF
1066static NSString *Home_;
1067static BOOL Sounds_Keyboard_;
1068
2a987aa5 1069static BOOL Advanced_;
ad554f10 1070static BOOL Loaded_;
9e07091a 1071static BOOL Ignored_;
2a987aa5 1072
5e563e79
JF
1073static UIFont *Font12_;
1074static UIFont *Font12Bold_;
1075static UIFont *Font14_;
1076static UIFont *Font18Bold_;
1077static UIFont *Font22Bold_;
1078
2cb68ddf 1079static const char *Machine_ = NULL;
68c05606
JF
1080static const NSString *UniqueID_ = nil;
1081static const NSString *Build_ = nil;
7b00c562
JF
1082static const NSString *Product_ = nil;
1083static const NSString *Safari_ = nil;
fc675b93 1084
b27f0a94 1085CFLocaleRef Locale_;
bb9edf8b 1086NSArray *Languages_;
e057ec05
JF
1087CGColorSpaceRef space_;
1088
e057ec05 1089bool bootstrap_;
d72d91aa 1090bool reload_;
df5a7529 1091
d1494d2c 1092static NSDictionary *SectionMap_;
686e302f 1093static NSMutableDictionary *Metadata_;
faf4eb4f
JF
1094static _transient NSMutableDictionary *Settings_;
1095static _transient NSString *Role_;
1096static _transient NSMutableDictionary *Packages_;
1097static _transient NSMutableDictionary *Sections_;
1098static _transient NSMutableDictionary *Sources_;
3d37fc0d 1099static bool Changed_;
686e302f 1100static NSDate *now_;
20dd7407 1101
f464053e
JF
1102#if RecycleWebViews
1103static NSMutableArray *Documents_;
1104#endif
1105
3a83ebf7
JF
1106NSString *GetLastUpdate() {
1107 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1108
1109 if (update == nil)
6932575e 1110 return CYLocalize("NEVER_OR_UNKNOWN");
3a83ebf7 1111
b27f0a94 1112 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
3a83ebf7
JF
1113 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1114
1115 CFRelease(formatter);
3a83ebf7
JF
1116
1117 return [(NSString *) formatted autorelease];
1118}
e057ec05
JF
1119/* }}} */
1120/* Display Helpers {{{ */
1121inline float Interpolate(float begin, float end, float fraction) {
1122 return (end - begin) * fraction + begin;
1123}
4941f41d 1124
6932575e 1125/* XXX: localize this! */
b6ffa083 1126NSString *SizeString(double size) {
f464053e
JF
1127 bool negative = size < 0;
1128 if (negative)
1129 size = -size;
1130
b6ffa083
JF
1131 unsigned power = 0;
1132 while (size > 1024) {
1133 size /= 1024;
1134 ++power;
1135 }
1136
1137 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1138
56e10908 1139 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
b6ffa083
JF
1140}
1141
fbe40361
JF
1142static _finline CFStringRef CFCString(const char *value) {
1143 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1144}
1145
98fb9119 1146CFStringRef StripVersion(const char *version) {
f7ee98cb
JF
1147 const char *colon(strchr(version, ':'));
1148 if (colon != NULL)
1149 version = colon + 1;
fbe40361 1150 return CFCString(version);
f7ee98cb
JF
1151}
1152
6932575e 1153NSString *LocalizeSection(NSString *section) {
bb9edf8b 1154 static Pcre title_r("^(.*?) \\((.*)\\)$");
9ee296df
JF
1155 if (title_r(section)) {
1156 NSString *parent(title_r[1]);
1157 NSString *child(title_r[2]);
1158
bb9edf8b 1159 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
9ee296df
JF
1160 LocalizeSection(parent),
1161 LocalizeSection(child)
bb9edf8b 1162 ];
9ee296df 1163 }
bb9edf8b
JF
1164
1165 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
6932575e
JF
1166}
1167
49525fb2
JF
1168NSString *Simplify(NSString *title) {
1169 const char *data = [title UTF8String];
1170 size_t size = [title length];
1171
faf4eb4f
JF
1172 static Pcre square_r("^\\[(.*)\\]$");
1173 if (square_r(data, size))
1174 return Simplify(square_r[1]);
1175
1176 static Pcre paren_r("^\\((.*)\\)$");
1177 if (paren_r(data, size))
1178 return Simplify(paren_r[1]);
1179
bb9edf8b 1180 static Pcre title_r("^(.*?) \\((.*)\\)$");
49525fb2 1181 if (title_r(data, size))
faf4eb4f
JF
1182 return Simplify(title_r[1]);
1183
1184 return title;
49525fb2 1185}
e057ec05
JF
1186/* }}} */
1187
fa7bb92f 1188bool isSectionVisible(NSString *section) {
43b742af
JF
1189 NSDictionary *metadata([Sections_ objectForKey:section]);
1190 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
fa7bb92f
JF
1191 return hidden == nil || ![hidden boolValue];
1192}
1193
a0e1b888 1194/* Delegate Prototypes {{{ */
e057ec05
JF
1195@class Package;
1196@class Source;
1197
238b07ce
JF
1198@interface NSObject (ProgressDelegate)
1199@end
1200
1201@implementation NSObject(ProgressDelegate)
1202
1203- (void) _setProgressError:(NSArray *)args {
1204 [self performSelector:@selector(setProgressError:forPackage:)
1205 withObject:[args objectAtIndex:0]
1206 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1207 ];
1208}
1209
1210@end
1211
e057ec05 1212@protocol ProgressDelegate
238b07ce 1213- (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
e057ec05
JF
1214- (void) setProgressTitle:(NSString *)title;
1215- (void) setProgressPercent:(float)percent;
87c76914 1216- (void) startProgress;
e057ec05 1217- (void) addProgressOutput:(NSString *)output;
87c76914 1218- (bool) isCancelling:(size_t)received;
e057ec05
JF
1219@end
1220
7600bd69 1221@protocol ConfigurationDelegate
965edd52 1222- (void) repairWithSelector:(SEL)selector;
7600bd69
JF
1223- (void) setConfigurationData:(NSString *)data;
1224@end
1225
6932575e
JF
1226@class PackageView;
1227
e057ec05 1228@protocol CydiaDelegate
6932575e 1229- (void) setPackageView:(PackageView *)view;
3ff1504e 1230- (void) clearPackage:(Package *)package;
e057ec05
JF
1231- (void) installPackage:(Package *)package;
1232- (void) removePackage:(Package *)package;
d210b85d 1233- (void) slideUp:(UIActionSheet *)alert;
e057ec05 1234- (void) distUpgrade;
fa7bb92f 1235- (void) updateData;
faf4eb4f
JF
1236- (void) syncData;
1237- (void) askForSettings;
1238- (UIProgressHUD *) addProgressHUD;
7398a389 1239- (void) removeProgressHUD:(UIProgressHUD *)hud;
cb9c2100
JF
1240- (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1241- (RVPage *) pageForPackage:(NSString *)name;
1242- (void) openMailToURL:(NSURL *)url;
ec32cb10 1243- (void) clearFirstResponder;
6932575e 1244- (PackageView *) packageView;
e057ec05 1245@end
a0e1b888 1246/* }}} */
686e302f 1247
a75f53e7
JF
1248/* Status Delegation {{{ */
1249class Status :
1250 public pkgAcquireStatus
1251{
1252 private:
238b07ce 1253 _transient NSObject<ProgressDelegate> *delegate_;
a75f53e7
JF
1254
1255 public:
1256 Status() :
1257 delegate_(nil)
1258 {
1259 }
1260
1261 void setDelegate(id delegate) {
1262 delegate_ = delegate;
1263 }
1264
1265 virtual bool MediaChange(std::string media, std::string drive) {
1266 return false;
1267 }
1268
1269 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
a75f53e7
JF
1270 }
1271
1272 virtual void Fetch(pkgAcquire::ItemDesc &item) {
907a35d6 1273 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
2a987aa5 1274 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
a75f53e7
JF
1275 }
1276
1277 virtual void Done(pkgAcquire::ItemDesc &item) {
a75f53e7
JF
1278 }
1279
1280 virtual void Fail(pkgAcquire::ItemDesc &item) {
3325a005
JF
1281 if (
1282 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1283 item.Owner->Status == pkgAcquire::Item::StatDone
1284 )
1285 return;
1286
f464053e
JF
1287 std::string &error(item.Owner->ErrorText);
1288 if (error.empty())
1289 return;
1290
1291 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1292 NSArray *fields([description componentsSeparatedByString:@" "]);
1293 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1294
238b07ce 1295 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
f464053e
JF
1296 withObject:[NSArray arrayWithObjects:
1297 [NSString stringWithUTF8String:error.c_str()],
1298 source,
1299 nil]
238b07ce
JF
1300 waitUntilDone:YES
1301 ];
a75f53e7
JF
1302 }
1303
1304 virtual bool Pulse(pkgAcquire *Owner) {
4941f41d
JF
1305 bool value = pkgAcquireStatus::Pulse(Owner);
1306
1307 float percent(
1308 double(CurrentBytes + CurrentItems) /
1309 double(TotalBytes + TotalItems)
1310 );
1311
e057ec05 1312 [delegate_ setProgressPercent:percent];
87c76914 1313 return [delegate_ isCancelling:CurrentBytes] ? false : value;
a75f53e7
JF
1314 }
1315
1316 virtual void Start() {
87c76914 1317 [delegate_ startProgress];
a75f53e7
JF
1318 }
1319
1320 virtual void Stop() {
a75f53e7
JF
1321 }
1322};
1323/* }}} */
1324/* Progress Delegation {{{ */
1325class Progress :
1326 public OpProgress
1327{
1328 private:
e057ec05 1329 _transient id<ProgressDelegate> delegate_;
a75f53e7
JF
1330
1331 protected:
1332 virtual void Update() {
b7ad9c68
JF
1333 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1334 [delegate_ setProgressPercent:(Percent / 100)];*/
a75f53e7
JF
1335 }
1336
1337 public:
1338 Progress() :
1339 delegate_(nil)
1340 {
1341 }
1342
1343 void setDelegate(id delegate) {
1344 delegate_ = delegate;
1345 }
1346
1347 virtual void Done() {
b7ad9c68 1348 //[delegate_ setProgressPercent:1];
a75f53e7
JF
1349 }
1350};
1351/* }}} */
1352
e057ec05 1353/* Database Interface {{{ */
631a0a1e
JF
1354typedef std::map< unsigned long, _H<Source> > SourceMap;
1355
e057ec05 1356@interface Database : NSObject {
6932575e
JF
1357 NSZone *zone_;
1358 apr_pool_t *pool_;
1359
a70cf746
JF
1360 unsigned era_;
1361
e057ec05 1362 pkgCacheFile cache_;
965edd52 1363 pkgDepCache::Policy *policy_;
e057ec05
JF
1364 pkgRecords *records_;
1365 pkgProblemResolver *resolver_;
1366 pkgAcquire *fetcher_;
1367 FileFd *lock_;
1368 SPtr<pkgPackageManager> manager_;
1369 pkgSourceList *list_;
b0d03ade 1370
631a0a1e 1371 SourceMap sources_;
9ee296df 1372 NSMutableArray *packages_;
686e302f 1373
238b07ce 1374 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
e057ec05
JF
1375 Status status_;
1376 Progress progress_;
7600bd69 1377
d72d91aa 1378 int cydiafd_;
e057ec05 1379 int statusfd_;
7600bd69 1380 FILE *input_;
a75f53e7
JF
1381}
1382
dbe0f181 1383+ (Database *) sharedInstance;
a70cf746 1384- (unsigned) era;
dbe0f181 1385
d72d91aa 1386- (void) _readCydia:(NSNumber *)fd;
e057ec05
JF
1387- (void) _readStatus:(NSNumber *)fd;
1388- (void) _readOutput:(NSNumber *)fd;
4941f41d 1389
7600bd69
JF
1390- (FILE *) input;
1391
e057ec05 1392- (Package *) packageWithName:(NSString *)name;
a75f53e7 1393
e057ec05 1394- (pkgCacheFile &) cache;
965edd52 1395- (pkgDepCache::Policy *) policy;
e057ec05
JF
1396- (pkgRecords *) records;
1397- (pkgProblemResolver *) resolver;
1398- (pkgAcquire &) fetcher;
ce09fc27 1399- (pkgSourceList &) list;
e057ec05 1400- (NSArray *) packages;
faf4eb4f 1401- (NSArray *) sources;
e057ec05
JF
1402- (void) reloadData;
1403
965edd52 1404- (void) configure;
e057ec05
JF
1405- (void) prepare;
1406- (void) perform;
1407- (void) upgrade;
1408- (void) update;
1409
1410- (void) updateWithStatus:(Status &)status;
1411
1412- (void) setDelegate:(id)delegate;
3e3977a2 1413- (Source *) getSource:(pkgCache::PkgFileIterator)file;
a75f53e7 1414@end
e057ec05 1415/* }}} */
a75f53e7 1416
e057ec05
JF
1417/* Source Class {{{ */
1418@interface Source : NSObject {
b8b1cfd0
JF
1419 CYString description_;
1420 CYString label_;
1421 CYString origin_;
1422 CYString support_;
a75f53e7 1423
b8b1cfd0
JF
1424 CYString uri_;
1425 CYString distribution_;
1426 CYString type_;
1427 CYString version_;
4941f41d 1428
b8b1cfd0
JF
1429 NSString *host_;
1430
1431 CYString defaultIcon_;
a75f53e7 1432
faf4eb4f 1433 NSDictionary *record_;
e057ec05 1434 BOOL trusted_;
a75f53e7
JF
1435}
1436
b8b1cfd0 1437- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
a75f53e7 1438
faf4eb4f
JF
1439- (NSComparisonResult) compareByNameAndType:(Source *)source;
1440
3ff1504e
JF
1441- (NSString *) supportForPackage:(NSString *)package;
1442
faf4eb4f 1443- (NSDictionary *) record;
e057ec05 1444- (BOOL) trusted;
a75f53e7 1445
e057ec05
JF
1446- (NSString *) uri;
1447- (NSString *) distribution;
1448- (NSString *) type;
faf4eb4f
JF
1449- (NSString *) key;
1450- (NSString *) host;
e057ec05 1451
faf4eb4f 1452- (NSString *) name;
e057ec05
JF
1453- (NSString *) description;
1454- (NSString *) label;
1455- (NSString *) origin;
1456- (NSString *) version;
a75f53e7 1457
e057ec05 1458- (NSString *) defaultIcon;
faf4eb4f 1459
a75f53e7 1460@end
a75f53e7 1461
e057ec05 1462@implementation Source
a75f53e7 1463
ce09fc27 1464- (void) _clear {
b8b1cfd0
JF
1465 uri_.clear();
1466 distribution_.clear();
1467 type_.clear();
ce09fc27 1468
b8b1cfd0
JF
1469 description_.clear();
1470 label_.clear();
1471 origin_.clear();
1472 support_.clear();
1473 version_.clear();
1474 defaultIcon_.clear();
1475
1476 if (record_ != nil) {
1477 [record_ release];
1478 record_ = nil;
1479 }
1480
1481 if (host_ != nil) {
1482 [host_ release];
1483 host_ = nil;
1484 }
ce09fc27 1485}
a75f53e7 1486
ce09fc27
JF
1487- (void) dealloc {
1488 [self _clear];
e057ec05 1489 [super dealloc];
a75f53e7
JF
1490}
1491
ad554f10
JF
1492+ (NSArray *) _attributeKeys {
1493 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1494}
1495
1496- (NSArray *) attributeKeys {
1497 return [[self class] _attributeKeys];
1498}
1499
1500+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1501 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1502}
1503
b8b1cfd0 1504- (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
ce09fc27 1505 [self _clear];
a75f53e7 1506
ce09fc27
JF
1507 trusted_ = index->IsTrusted();
1508
b8b1cfd0
JF
1509 uri_.set(pool, index->GetURI());
1510 distribution_.set(pool, index->GetDist());
1511 type_.set(pool, index->GetType());
ce09fc27
JF
1512
1513 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1514 if (dindex != NULL) {
b8b1cfd0
JF
1515 FileFd fd(dindex->MetaIndexFile("Release"), FileFd::ReadOnly);
1516 pkgTagFile tags(&fd);
1517
1518 pkgTagSection section;
1519 tags.Step(section);
ce09fc27 1520
b8b1cfd0
JF
1521 struct {
1522 const char *name_;
1523 CYString *value_;
1524 } names[] = {
1525 {"default-icon", &defaultIcon_},
1526 {"description", &description_},
1527 {"label", &label_},
1528 {"origin", &origin_},
1529 {"support", &support_},
1530 {"version", &version_},
1531 };
1532
1533 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1534 const char *start, *end;
1535
1536 if (section.Find(names[i].name_, start, end)) {
1537 CYString &value(*names[i].value_);
1538 value.set(pool, start, end - start);
1539 }
e057ec05 1540 }
ce09fc27 1541 }
faf4eb4f 1542
ce09fc27
JF
1543 record_ = [Sources_ objectForKey:[self key]];
1544 if (record_ != nil)
1545 record_ = [record_ retain];
b8b1cfd0
JF
1546
1547 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
ce09fc27
JF
1548}
1549
b8b1cfd0 1550- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
ce09fc27 1551 if ((self = [super init]) != nil) {
b8b1cfd0 1552 [self setMetaIndex:index inPool:pool];
e057ec05 1553 } return self;
4941f41d 1554}
a75f53e7 1555
faf4eb4f
JF
1556- (NSComparisonResult) compareByNameAndType:(Source *)source {
1557 NSDictionary *lhr = [self record];
1558 NSDictionary *rhr = [source record];
1559
1560 if (lhr != rhr)
1561 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1562
1563 NSString *lhs = [self name];
1564 NSString *rhs = [source name];
1565
1566 if ([lhs length] != 0 && [rhs length] != 0) {
1567 unichar lhc = [lhs characterAtIndex:0];
1568 unichar rhc = [rhs characterAtIndex:0];
1569
1570 if (isalpha(lhc) && !isalpha(rhc))
1571 return NSOrderedAscending;
1572 else if (!isalpha(lhc) && isalpha(rhc))
1573 return NSOrderedDescending;
1574 }
1575
9c4e0cbe 1576 return [lhs compare:rhs options:LaxCompareOptions_];
faf4eb4f
JF
1577}
1578
3ff1504e 1579- (NSString *) supportForPackage:(NSString *)package {
b8b1cfd0 1580 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
3ff1504e
JF
1581}
1582
faf4eb4f
JF
1583- (NSDictionary *) record {
1584 return record_;
1585}
1586
e057ec05
JF
1587- (BOOL) trusted {
1588 return trusted_;
1589}
2d28b35a 1590
e057ec05
JF
1591- (NSString *) uri {
1592 return uri_;
1593}
1cb11c5f 1594
e057ec05
JF
1595- (NSString *) distribution {
1596 return distribution_;
1597}
a75f53e7 1598
e057ec05
JF
1599- (NSString *) type {
1600 return type_;
a75f53e7
JF
1601}
1602
faf4eb4f 1603- (NSString *) key {
b8b1cfd0 1604 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
faf4eb4f
JF
1605}
1606
1607- (NSString *) host {
b8b1cfd0 1608 return host_;
faf4eb4f
JF
1609}
1610
1611- (NSString *) name {
b8b1cfd0 1612 return origin_.empty() ? host_ : origin_;
faf4eb4f
JF
1613}
1614
e057ec05
JF
1615- (NSString *) description {
1616 return description_;
1617}
686e302f 1618
e057ec05 1619- (NSString *) label {
b8b1cfd0 1620 return label_.empty() ? host_ : label_;
e057ec05 1621}
2d28b35a 1622
e057ec05
JF
1623- (NSString *) origin {
1624 return origin_;
1625}
2d28b35a 1626
e057ec05
JF
1627- (NSString *) version {
1628 return version_;
1629}
4941f41d 1630
e057ec05
JF
1631- (NSString *) defaultIcon {
1632 return defaultIcon_;
1633}
4941f41d 1634
2a987aa5
JF
1635@end
1636/* }}} */
1637/* Relationship Class {{{ */
1638@interface Relationship : NSObject {
1639 NSString *type_;
1640 NSString *id_;
1641}
1642
1643- (NSString *) type;
1644- (NSString *) id;
1645- (NSString *) name;
1646
1647@end
1648
1649@implementation Relationship
1650
1651- (void) dealloc {
1652 [type_ release];
1653 [id_ release];
1654 [super dealloc];
1655}
1656
1657- (NSString *) type {
1658 return type_;
1659}
1660
1661- (NSString *) id {
1662 return id_;
1663}
1664
1665- (NSString *) name {
1666 _assert(false);
1667 return nil;
1668}
1669
a75f53e7 1670@end
686e302f 1671/* }}} */
e057ec05 1672/* Package Class {{{ */
e057ec05 1673@interface Package : NSObject {
a70cf746 1674 unsigned era_;
631a0a1e 1675 apr_pool_t *pool_;
a70cf746 1676
3e3977a2 1677 pkgCache::VerIterator version_;
e057ec05
JF
1678 pkgCache::PkgIterator iterator_;
1679 _transient Database *database_;
e057ec05 1680 pkgCache::VerFileIterator file_;
3d37fc0d 1681
e057ec05 1682 Source *source_;
3d37fc0d 1683 bool cached_;
631a0a1e 1684 bool parsed_;
a75f53e7 1685
6932575e
JF
1686 CYString section_;
1687 NSString *section$_;
a70cf746 1688 bool essential_;
43b742af 1689 bool visible_;
f159ecd4 1690
e057ec05
JF
1691 NSString *latest_;
1692 NSString *installed_;
a75f53e7 1693
9ee296df 1694 CYString id_;
6932575e
JF
1695 CYString name_;
1696 CYString tagline_;
1697 CYString icon_;
1698 CYString depiction_;
1699 CYString homepage_;
1700
1701 CYString sponsor_;
1702 Address *sponsor$_;
1703
1704 CYString author_;
1705 Address *author$_;
1706
1707 CYString support_;
fbe40361 1708 NSMutableArray *tags_;
faf4eb4f 1709 NSString *role_;
2a987aa5
JF
1710
1711 NSArray *relationships_;
43b742af 1712
6932575e 1713 NSMutableDictionary *metadata_;
43b742af
JF
1714 _transient NSDate *firstSeen_;
1715 _transient NSDate *lastSeen_;
1716 bool subscribed_;
686e302f
JF
1717}
1718
3e3977a2 1719- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
6932575e 1720+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
686e302f 1721
2a987aa5 1722- (pkgCache::PkgIterator) iterator;
631a0a1e 1723- (void) parse;
2a987aa5 1724
e057ec05 1725- (NSString *) section;
6b4b3bee
JF
1726- (NSString *) simpleSection;
1727
6932575e
JF
1728- (NSString *) longSection;
1729- (NSString *) shortSection;
1730
ce09fc27
JF
1731- (NSString *) uri;
1732
e057ec05
JF
1733- (Address *) maintainer;
1734- (size_t) size;
66abcbb0
JF
1735- (NSString *) longDescription;
1736- (NSString *) shortDescription;
3bddda52 1737- (unichar) index;
a75f53e7 1738
f159ecd4 1739- (NSMutableDictionary *) metadata;
e057ec05 1740- (NSDate *) seen;
f159ecd4
JF
1741- (BOOL) subscribed;
1742- (BOOL) ignored;
63a1e4b8 1743
e057ec05
JF
1744- (NSString *) latest;
1745- (NSString *) installed;
965edd52
JF
1746
1747- (BOOL) valid;
238b07ce 1748- (BOOL) upgradableAndEssential:(BOOL)essential;
e057ec05
JF
1749- (BOOL) essential;
1750- (BOOL) broken;
853d14d3 1751- (BOOL) unfiltered;
fa7bb92f 1752- (BOOL) visible;
686e302f 1753
3319715b
JF
1754- (BOOL) half;
1755- (BOOL) halfConfigured;
1756- (BOOL) halfInstalled;
1757- (BOOL) hasMode;
1758- (NSString *) mode;
1759
e057ec05
JF
1760- (NSString *) id;
1761- (NSString *) name;
dbe0f181 1762- (UIImage *) icon;
ad554f10 1763- (NSString *) homepage;
0235116c 1764- (NSString *) depiction;
d72d91aa 1765- (Address *) author;
686e302f 1766
3ff1504e
JF
1767- (NSString *) support;
1768
f464053e 1769- (NSArray *) files;
2a987aa5 1770- (NSArray *) relationships;
f464053e
JF
1771- (NSArray *) warnings;
1772- (NSArray *) applications;
2a987aa5 1773
e057ec05 1774- (Source *) source;
faf4eb4f 1775- (NSString *) role;
686e302f 1776
e057ec05 1777- (BOOL) matches:(NSString *)text;
686e302f 1778
faf4eb4f 1779- (bool) hasSupportingRole;
fa7bb92f 1780- (BOOL) hasTag:(NSString *)tag;
cb9c2100 1781- (NSString *) primaryPurpose;
dbe0f181 1782- (NSArray *) purposes;
d8d9a65c 1783- (bool) isCommercial;
fa7bb92f 1784
dd9390c5
JF
1785- (CYString &) cyname;
1786
6932575e 1787- (uint32_t) compareBySection:(NSArray *)sections;
f159ecd4
JF
1788
1789- (uint32_t) compareForChanges;
686e302f 1790
e057ec05
JF
1791- (void) install;
1792- (void) remove;
7e986211 1793
7cf54836
JF
1794- (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1795- (bool) isInstalledAndVisible:(NSNumber *)number;
1796- (bool) isVisiblyUninstalledInSection:(NSString *)section;
1797- (bool) isVisibleInSource:(Source *)source;
686e302f 1798
e057ec05 1799@end
686e302f 1800
6932575e
JF
1801uint32_t PackageChangesRadix(Package *self, void *) {
1802 union {
1803 uint32_t key;
1804
1805 struct {
1806 uint32_t timestamp : 30;
1807 uint32_t ignored : 1;
1808 uint32_t upgradable : 1;
1809 } bits;
1810 } value;
1811
1812 bool upgradable([self upgradableAndEssential:YES]);
1813 value.bits.upgradable = upgradable ? 1 : 0;
1814
1815 if (upgradable) {
1816 value.bits.timestamp = 0;
1817 value.bits.ignored = [self ignored] ? 0 : 1;
1818 value.bits.upgradable = 1;
1819 } else {
1820 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1821 value.bits.ignored = 0;
1822 value.bits.upgradable = 0;
1823 }
1824
1825 return _not(uint32_t) - value.key;
1826}
1827
dd9390c5
JF
1828_finline static void Stifle(uint8_t &value) {
1829}
43b742af 1830
dd9390c5
JF
1831uint32_t PackagePrefixRadix(Package *self, void *context) {
1832 size_t offset(reinterpret_cast<size_t>(context));
1833 CYString &name([self cyname]);
43b742af 1834
dd9390c5
JF
1835 size_t size(name.size());
1836 if (size == 0)
1837 return 0;
1838 char *text(name.data());
43b742af 1839
dd9390c5
JF
1840 size_t zeros;
1841 if (!isdigit(text[0]))
1842 zeros = 0;
1843 else {
1844 size_t digits(1);
1845 while (size != digits && isdigit(text[digits]))
1846 if (++digits == 4)
1847 break;
1848 zeros = 4 - digits;
1849 }
43b742af 1850
dd9390c5
JF
1851 uint8_t data[4];
1852
1853 // 0.607997
1854
1855 if (offset == 0 && zeros != 0) {
1856 memset(data, '0', zeros);
1857 memcpy(data + zeros, text, 4 - zeros);
1858 } else {
1859 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1860 if (size <= offset - zeros)
1861 return 0;
1862
1863 text += offset - zeros;
1864 size -= offset - zeros;
1865
1866 if (size >= 4)
1867 memcpy(data, text, 4);
1868 else {
1869 memcpy(data, text, size);
1870 memset(data + size, 0, 4 - size);
1871 }
1872
1873 for (size_t i(0); i != 4; ++i)
1874 if (isalpha(data[i]))
1875 data[i] &= 0xdf;
1876 }
1877
1878 if (offset == 0)
1879 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1880
1881 /* XXX: ntohl may be more honest */
1882 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1883}
1884
1885CYString &(*PackageName)(Package *self, SEL sel);
1886
1887CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1888 _profile(PackageNameCompare)
1889 CYString &lhi(PackageName(lhs, @selector(cyname)));
1890 CYString &rhi(PackageName(rhs, @selector(cyname)));
1891 CFStringRef lhn(lhi), rhn(rhi);
43b742af
JF
1892
1893 _profile(PackageNameCompare$NumbersLast)
dd9390c5 1894 if (!lhi.empty() && !rhi.empty()) {
43b742af
JF
1895 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1896 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1897 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1898 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1899 return lha ? NSOrderedAscending : NSOrderedDescending;
1900 }
1901 _end
1902
dd9390c5
JF
1903 CFIndex length = CFStringGetLength(lhn);
1904
43b742af
JF
1905 _profile(PackageNameCompare$Compare)
1906 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1907 _end
1908 _end
1909}
1910
66abcbb0
JF
1911CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1912 return PackageNameCompare(*lhs, *rhs, context);
43b742af
JF
1913}
1914
1915struct PackageNameOrdering :
1916 std::binary_function<Package *, Package *, bool>
1917{
1918 _finline bool operator ()(Package *lhs, Package *rhs) const {
1919 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1920 }
1921};
1922
e057ec05 1923@implementation Package
686e302f 1924
dd9390c5
JF
1925- (NSString *) description {
1926 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1927}
1928
e057ec05 1929- (void) dealloc {
3d37fc0d
JF
1930 if (source_ != nil)
1931 [source_ release];
6932575e
JF
1932 if (section$_ != nil)
1933 [section$_ release];
f159ecd4 1934
3e3977a2
JF
1935 if (latest_ != nil)
1936 [latest_ release];
e057ec05
JF
1937 if (installed_ != nil)
1938 [installed_ release];
686e302f 1939
6932575e
JF
1940 if (sponsor$_ != nil)
1941 [sponsor$_ release];
1942 if (author$_ != nil)
1943 [author$_ release];
fa7bb92f
JF
1944 if (tags_ != nil)
1945 [tags_ release];
faf4eb4f
JF
1946 if (role_ != nil)
1947 [role_ release];
63a1e4b8 1948
2a987aa5
JF
1949 if (relationships_ != nil)
1950 [relationships_ release];
6932575e
JF
1951 if (metadata_ != nil)
1952 [metadata_ release];
2a987aa5 1953
e057ec05 1954 [super dealloc];
686e302f
JF
1955}
1956
d8d9a65c
JF
1957+ (NSString *) webScriptNameForSelector:(SEL)selector {
1958 if (selector == @selector(hasTag:))
1959 return @"hasTag";
1960 else
1961 return nil;
1962}
1963
1964+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1965 return [self webScriptNameForSelector:selector] == nil;
1966}
1967
ad554f10 1968+ (NSArray *) _attributeKeys {
66abcbb0 1969 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
ad554f10
JF
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
631a0a1e
JF
1980- (void) parse {
1981 if (parsed_)
1982 return;
1983 parsed_ = true;
1984 if (file_.end())
1985 return;
1986
1987 _profile(Package$parse)
1988 pkgRecords::Parser *parser;
1989
1990 _profile(Package$parse$Lookup)
1991 parser = &[database_ records]->Lookup(file_);
1992 _end
1993
1994 CYString website;
1995
1996 _profile(Package$parse$Find)
1997 struct {
1998 const char *name_;
1999 CYString *value_;
2000 } names[] = {
2001 {"icon", &icon_},
2002 {"depiction", &depiction_},
2003 {"homepage", &homepage_},
2004 {"website", &website},
2005 {"support", &support_},
2006 {"sponsor", &sponsor_},
2007 {"author", &author_},
2008 };
2009
2010 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2011 const char *start, *end;
2012
2013 if (parser->Find(names[i].name_, start, end)) {
2014 CYString &value(*names[i].value_);
2015 _profile(Package$parse$Value)
2016 value.set(pool_, start, end - start);
2017 _end
2018 }
2019 }
2020 _end
2021
2022 _profile(Package$parse$Tagline)
2023 const char *start, *end;
fbe40361 2024 if (parser->ShortDesc(start, end)) {
631a0a1e
JF
2025 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2026 if (stop == NULL)
2027 stop = end;
2028 while (stop != start && stop[-1] == '\r')
2029 --stop;
2030 tagline_.set(pool_, start, stop - start);
2031 }
2032 _end
2033
2034 _profile(Package$parse$Retain)
2035 if (!homepage_.empty())
2036 homepage_ = website;
2037 if (homepage_ == depiction_)
2038 homepage_.clear();
2039 _end
2040 _end
2041}
2042
3e3977a2 2043- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
a70cf746 2044 if ((self = [super init]) != nil) {
3e3977a2 2045 _profile(Package$initWithVersion)
a70cf746
JF
2046 @synchronized (database) {
2047 era_ = [database era];
631a0a1e 2048 pool_ = pool;
a70cf746 2049
3e3977a2
JF
2050 version_ = version;
2051 iterator_ = version.ParentPkg();
e057ec05 2052 database_ = database;
686e302f 2053
3e3977a2 2054 _profile(Package$initWithVersion$Latest)
98fb9119 2055 latest_ = (NSString *) StripVersion(version_.VerStr());
3bddda52 2056 _end
e2a207dd 2057
631a0a1e
JF
2058 pkgCache::VerIterator current;
2059 _profile(Package$initWithVersion$Versions)
2060 current = iterator_.CurrentVer();
2061 if (!current.end())
98fb9119 2062 installed_ = (NSString *) StripVersion(current.VerStr());
7e986211 2063
631a0a1e
JF
2064 if (!version_.end())
2065 file_ = version_.FileList();
2066 else {
2067 pkgCache &cache([database_ cache]);
2068 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2069 }
2070 _end
3bddda52 2071
3e3977a2 2072 _profile(Package$initWithVersion$Name)
631a0a1e 2073 id_.set(pool_, iterator_.Name());
fbe40361 2074 name_.set(pool, iterator_.Display());
3bddda52
JF
2075 _end
2076
631a0a1e
JF
2077 if (!file_.end()) {
2078 _profile(Package$initWithVersion$Source)
2079 source_ = [database_ getSource:file_.File()];
2080 if (source_ != nil)
2081 [source_ retain];
2082 cached_ = true;
3bddda52 2083 _end
631a0a1e
JF
2084 }
2085
3e3977a2 2086 _profile(Package$initWithVersion$Tags)
fbe40361
JF
2087 pkgCache::TagIterator tag(iterator_.TagList());
2088 if (!tag.end()) {
2089 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2090 do {
2091 const char *name(tag.Name());
2092 [tags_ addObject:(NSString *)CFCString(name)];
2093 if (role_ == nil && strncmp(name, "role::", 6) == 0)
2094 role_ = (NSString *) CFCString(name + 6);
2095 ++tag;
2096 } while (!tag.end());
2097 }
3bddda52 2098 _end
faf4eb4f 2099
6b92acab 2100 bool changed(false);
56e10908
JF
2101 NSString *key([id_ lowercaseString]);
2102
3e3977a2 2103 _profile(Package$initWithVersion$Metadata)
6932575e 2104 metadata_ = [Packages_ objectForKey:key];
43b742af 2105
6932575e 2106 if (metadata_ == nil) {
98fb9119 2107 firstSeen_ = now_;
43b742af 2108
6932575e 2109 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
43b742af
JF
2110 firstSeen_, @"FirstSeen",
2111 latest_, @"LastVersion",
3bddda52 2112 nil] mutableCopy];
6b92acab 2113
3bddda52
JF
2114 changed = true;
2115 } else {
43b742af
JF
2116 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2117 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2118
2119 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2120 subscribed_ = [subscribed boolValue];
2121
6932575e 2122 NSString *version([metadata_ objectForKey:@"LastVersion"]);
3bddda52 2123
43b742af
JF
2124 if (firstSeen_ == nil) {
2125 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2126 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
6b92acab
JF
2127 changed = true;
2128 }
6b92acab 2129
3e3977a2
JF
2130 if (version == nil) {
2131 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2132 changed = true;
2133 } else if (![version isEqualToString:latest_]) {
2134 [metadata_ setObject:latest_ forKey:@"LastVersion"];
43b742af
JF
2135 lastSeen_ = now_;
2136 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
3e3977a2
JF
2137 changed = true;
2138 }
3bddda52
JF
2139 }
2140
6932575e
JF
2141 metadata_ = [metadata_ retain];
2142
3bddda52 2143 if (changed) {
6932575e 2144 [Packages_ setObject:metadata_ forKey:key];
3bddda52
JF
2145 Changed_ = true;
2146 }
2147 _end
a70cf746 2148
3e3977a2 2149 _profile(Package$initWithVersion$Section)
631a0a1e 2150 section_.set(pool_, iterator_.Section());
6932575e 2151 _end
a70cf746 2152
6932575e 2153 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
43b742af 2154 visible_ = [self hasSupportingRole] && [self unfiltered];
a70cf746 2155 } _end } return self;
a75f53e7
JF
2156}
2157
6932575e 2158+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
bb9edf8b
JF
2159 pkgCache::VerIterator version;
2160
2161 _profile(Package$packageWithIterator$GetCandidateVer)
2162 version = [database policy]->GetCandidateVer(iterator);
2163 _end
2164
3e3977a2
JF
2165 if (version.end())
2166 return nil;
bb9edf8b 2167
965edd52 2168 return [[[Package alloc]
3e3977a2 2169 initWithVersion:version
6932575e
JF
2170 withZone:zone
2171 inPool:pool
965edd52
JF
2172 database:database
2173 ] autorelease];
a75f53e7
JF
2174}
2175
2a987aa5
JF
2176- (pkgCache::PkgIterator) iterator {
2177 return iterator_;
2178}
2179
e057ec05 2180- (NSString *) section {
6932575e
JF
2181 if (section$_ == nil) {
2182 if (section_.empty())
2183 return nil;
2184
2185 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2186 NSString *name(section_);
2187
2188 lookup:
2189 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2190 if (NSString *rename = [value objectForKey:@"Rename"]) {
2191 name = rename;
2192 goto lookup;
2193 }
2194
2195 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2196 } return section$_;
a75f53e7
JF
2197}
2198
6b4b3bee
JF
2199- (NSString *) simpleSection {
2200 if (NSString *section = [self section])
2201 return Simplify(section);
2202 else
2203 return nil;
ce09fc27 2204}
6b4b3bee 2205
6932575e
JF
2206- (NSString *) longSection {
2207 return LocalizeSection(section_);
2208}
2209
2210- (NSString *) shortSection {
2211 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2212}
2213
ce09fc27
JF
2214- (NSString *) uri {
2215 return nil;
2216#if 0
2217 pkgIndexFile *index;
2218 pkgCache::PkgFileIterator file(file_.File());
2219 if (![database_ list].FindIndex(file, index))
2220 return nil;
2221 return [NSString stringWithUTF8String:iterator_->Path];
2222 //return [NSString stringWithUTF8String:file.Site()];
2223 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2224#endif
6b4b3bee
JF
2225}
2226
e057ec05 2227- (Address *) maintainer {
965edd52
JF
2228 if (file_.end())
2229 return nil;
e057ec05 2230 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
0a7e5478
JF
2231 const std::string &maintainer(parser->Maintainer());
2232 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
b6ffa083
JF
2233}
2234
e057ec05 2235- (size_t) size {
965edd52 2236 return version_.end() ? 0 : version_->InstalledSize;
a75f53e7
JF
2237}
2238
66abcbb0 2239- (NSString *) longDescription {
965edd52
JF
2240 if (file_.end())
2241 return nil;
e057ec05 2242 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2a987aa5 2243 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
b6ffa083 2244
e057ec05
JF
2245 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2246 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2247 if ([lines count] < 2)
2248 return nil;
2d28b35a 2249
e057ec05 2250 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
9fdd37d0 2251 for (size_t i(1), e([lines count]); i != e; ++i) {
e057ec05
JF
2252 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2253 [trimmed addObject:trim];
2254 }
2d28b35a 2255
e057ec05
JF
2256 return [trimmed componentsJoinedByString:@"\n"];
2257}
a75f53e7 2258
66abcbb0
JF
2259- (NSString *) shortDescription {
2260 return tagline_;
2261}
2262
3bddda52
JF
2263- (unichar) index {
2264 _profile(Package$index)
43b742af
JF
2265 CFStringRef name((CFStringRef) [self name]);
2266 if (CFStringGetLength(name) == 0)
3bddda52 2267 return '#';
43b742af
JF
2268 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2269 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
3bddda52 2270 return '#';
c46df204 2271 return toupper(character);
3bddda52 2272 _end
e057ec05 2273}
2d28b35a 2274
f159ecd4 2275- (NSMutableDictionary *) metadata {
6932575e 2276 return metadata_;
f159ecd4
JF
2277}
2278
e057ec05 2279- (NSDate *) seen {
43b742af
JF
2280 if (subscribed_ && lastSeen_ != nil)
2281 return lastSeen_;
2282 return firstSeen_;
2d28b35a
JF
2283}
2284
f159ecd4 2285- (BOOL) subscribed {
43b742af 2286 return subscribed_;
f159ecd4
JF
2287}
2288
2289- (BOOL) ignored {
2290 NSDictionary *metadata([self metadata]);
2291 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2292 return [ignored boolValue];
2293 else
2294 return false;
2295}
2296
e057ec05
JF
2297- (NSString *) latest {
2298 return latest_;
b6ffa083
JF
2299}
2300
e057ec05
JF
2301- (NSString *) installed {
2302 return installed_;
2d28b35a
JF
2303}
2304
965edd52
JF
2305- (BOOL) valid {
2306 return !version_.end();
2307}
2308
238b07ce 2309- (BOOL) upgradableAndEssential:(BOOL)essential {
43b742af
JF
2310 _profile(Package$upgradableAndEssential)
2311 pkgCache::VerIterator current(iterator_.CurrentVer());
2312 if (current.end())
2313 return essential && essential_ && visible_;
2314 else
2315 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2316 _end
e057ec05 2317}
2d28b35a 2318
e057ec05 2319- (BOOL) essential {
a70cf746 2320 return essential_;
2d28b35a
JF
2321}
2322
e057ec05 2323- (BOOL) broken {
3319715b
JF
2324 return [database_ cache][iterator_].InstBroken();
2325}
2326
853d14d3 2327- (BOOL) unfiltered {
43b742af 2328 NSString *section([self section]);
853d14d3
JF
2329 return section == nil || isSectionVisible(section);
2330}
2331
2332- (BOOL) visible {
43b742af 2333 return visible_;
fa7bb92f
JF
2334}
2335
3319715b 2336- (BOOL) half {
43b742af 2337 unsigned char current(iterator_->CurrentState);
3319715b
JF
2338 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2339}
2340
2341- (BOOL) halfConfigured {
2342 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2343}
2344
2345- (BOOL) halfInstalled {
2346 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2347}
2348
2349- (BOOL) hasMode {
2350 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2351 return state.Mode != pkgDepCache::ModeKeep;
2352}
2353
2354- (NSString *) mode {
2355 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2356
2357 switch (state.Mode) {
2358 case pkgDepCache::ModeDelete:
2359 if ((state.iFlags & pkgDepCache::Purge) != 0)
6932575e 2360 return @"PURGE";
3319715b 2361 else
6932575e 2362 return @"REMOVE";
3319715b 2363 case pkgDepCache::ModeKeep:
3ff1504e 2364 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
6932575e 2365 return @"REINSTALL";
3ff1504e
JF
2366 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2367 return nil;*/
3319715b
JF
2368 else
2369 return nil;
3319715b 2370 case pkgDepCache::ModeInstall:
3ff1504e 2371 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
6932575e 2372 return @"REINSTALL";
3ff1504e 2373 else*/ switch (state.Status) {
3319715b 2374 case -1:
6932575e 2375 return @"DOWNGRADE";
3319715b 2376 case 0:
6932575e 2377 return @"INSTALL";
3319715b 2378 case 1:
6932575e 2379 return @"UPGRADE";
3319715b 2380 case 2:
6932575e 2381 return @"NEW_INSTALL";
3319715b
JF
2382 default:
2383 _assert(false);
2384 }
2385 default:
2386 _assert(false);
2387 }
b6ffa083
JF
2388}
2389
e057ec05
JF
2390- (NSString *) id {
2391 return id_;
b6ffa083
JF
2392}
2393
e057ec05 2394- (NSString *) name {
9ee296df 2395 return name_.empty() ? id_ : name_;
e057ec05 2396}
b6ffa083 2397
dbe0f181 2398- (UIImage *) icon {
6b4b3bee 2399 NSString *section = [self simpleSection];
dbe0f181
JF
2400
2401 UIImage *icon(nil);
dd9390c5 2402 if (!icon_.empty())
6e673d99
JF
2403 if ([icon_ hasPrefix:@"file:///"])
2404 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
dbe0f181
JF
2405 if (icon == nil) if (section != nil)
2406 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
6e673d99
JF
2407 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2408 if ([dicon hasPrefix:@"file:///"])
2409 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
dbe0f181
JF
2410 if (icon == nil)
2411 icon = [UIImage applicationImageNamed:@"unknown.png"];
2412 return icon;
e057ec05 2413}
b6ffa083 2414
ad554f10 2415- (NSString *) homepage {
ff47b800 2416 return homepage_;
b6ffa083
JF
2417}
2418
0235116c
JF
2419- (NSString *) depiction {
2420 return depiction_;
2421}
2422
81ab76dc 2423- (Address *) sponsor {
6932575e
JF
2424 if (sponsor$_ == nil) {
2425 if (sponsor_.empty())
2426 return nil;
2427 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2428 } return sponsor$_;
81ab76dc
JF
2429}
2430
d72d91aa 2431- (Address *) author {
6932575e
JF
2432 if (author$_ == nil) {
2433 if (author_.empty())
2434 return nil;
2435 author$_ = [[Address addressWithString:author_] retain];
2436 } return author$_;
d72d91aa
JF
2437}
2438
3ff1504e 2439- (NSString *) support {
dd9390c5 2440 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
3ff1504e
JF
2441}
2442
f464053e 2443- (NSArray *) files {
9ee296df 2444 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
f464053e
JF
2445 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2446
2447 std::ifstream fin;
2448 fin.open([path UTF8String]);
2449 if (!fin.is_open())
2450 return nil;
2451
2452 std::string line;
2453 while (std::getline(fin, line))
2454 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2455
2456 return files;
2457}
2458
2a987aa5
JF
2459- (NSArray *) relationships {
2460 return relationships_;
2461}
2462
f464053e
JF
2463- (NSArray *) warnings {
2464 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2465 const char *name(iterator_.Name());
2466
2467 size_t length(strlen(name));
2468 if (length < 2) invalid:
6932575e 2469 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
f464053e
JF
2470 else for (size_t i(0); i != length; ++i)
2471 if (
8944281a
JF
2472 /* XXX: technically this is not allowed */
2473 (name[i] < 'A' || name[i] > 'Z') &&
f464053e
JF
2474 (name[i] < 'a' || name[i] > 'z') &&
2475 (name[i] < '0' || name[i] > '9') &&
2476 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2477 ) goto invalid;
2478
2479 if (strcmp(name, "cydia") != 0) {
2480 bool cydia = false;
8944281a 2481 bool _private = false;
f464053e
JF
2482 bool stash = false;
2483
8944281a
JF
2484 bool repository = [[self section] isEqualToString:@"Repositories"];
2485
f464053e
JF
2486 if (NSArray *files = [self files])
2487 for (NSString *file in files)
2488 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2489 cydia = true;
8944281a
JF
2490 else if (!_private && [file isEqualToString:@"/private"])
2491 _private = true;
f464053e
JF
2492 else if (!stash && [file isEqualToString:@"/var/stash"])
2493 stash = true;
2494
8944281a
JF
2495 /* XXX: this is not sensitive enough. only some folders are valid. */
2496 if (cydia && !repository)
6932575e 2497 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
8944281a 2498 if (_private)
6932575e 2499 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
f464053e 2500 if (stash)
6932575e 2501 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
f464053e
JF
2502 }
2503
2504 return [warnings count] == 0 ? nil : warnings;
2505}
2506
2507- (NSArray *) applications {
2508 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2509
2510 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2511
2512 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2513 if (NSArray *files = [self files])
2514 for (NSString *file in files)
2515 if (application_r(file)) {
2516 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2517 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2518 if ([id isEqualToString:me])
2519 continue;
2520
2521 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2522 if (display == nil)
2523 display = application_r[1];
2524
2525 NSString *bundle([file stringByDeletingLastPathComponent]);
2526 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2527 if (icon == nil || [icon length] == 0)
2528 icon = @"icon.png";
2529 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2530
2531 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2532 [applications addObject:application];
2533
2534 [application addObject:id];
2535 [application addObject:display];
2536 [application addObject:url];
2537 }
2538
2539 return [applications count] == 0 ? nil : applications;
2540}
2541
e057ec05 2542- (Source *) source {
3d37fc0d 2543 if (!cached_) {
a70cf746
JF
2544 @synchronized (database_) {
2545 if ([database_ era] != era_ || file_.end())
2546 source_ = nil;
2547 else {
2548 source_ = [database_ getSource:file_.File()];
2549 if (source_ != nil)
2550 [source_ retain];
2551 }
2552
2553 cached_ = true;
2554 }
3d37fc0d
JF
2555 }
2556
e057ec05 2557 return source_;
b6ffa083
JF
2558}
2559
faf4eb4f
JF
2560- (NSString *) role {
2561 return role_;
2562}
2563
e057ec05
JF
2564- (BOOL) matches:(NSString *)text {
2565 if (text == nil)
2566 return NO;
b6ffa083 2567
e057ec05 2568 NSRange range;
b6ffa083 2569
3bddda52 2570 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
e057ec05
JF
2571 if (range.location != NSNotFound)
2572 return YES;
b6ffa083 2573
3bddda52 2574 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
e057ec05
JF
2575 if (range.location != NSNotFound)
2576 return YES;
b6ffa083 2577
66abcbb0 2578 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
e057ec05
JF
2579 if (range.location != NSNotFound)
2580 return YES;
b6ffa083 2581
e057ec05
JF
2582 return NO;
2583}
b6ffa083 2584
faf4eb4f
JF
2585- (bool) hasSupportingRole {
2586 if (role_ == nil)
fa7bb92f 2587 return true;
faf4eb4f
JF
2588 if ([role_ isEqualToString:@"enduser"])
2589 return true;
2590 if ([Role_ isEqualToString:@"User"])
2591 return false;
2592 if ([role_ isEqualToString:@"hacker"])
2593 return true;
2594 if ([Role_ isEqualToString:@"Hacker"])
2595 return false;
2596 if ([role_ isEqualToString:@"developer"])
2597 return true;
2598 if ([Role_ isEqualToString:@"Developer"])
2599 return false;
2600 _assert(false);
fa7bb92f
JF
2601}
2602
2603- (BOOL) hasTag:(NSString *)tag {
2604 return tags_ == nil ? NO : [tags_ containsObject:tag];
2605}
2606
cb9c2100
JF
2607- (NSString *) primaryPurpose {
2608 for (NSString *tag in tags_)
2609 if ([tag hasPrefix:@"purpose::"])
2610 return [tag substringFromIndex:9];
2611 return nil;
2612}
2613
dbe0f181
JF
2614- (NSArray *) purposes {
2615 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2616 for (NSString *tag in tags_)
2617 if ([tag hasPrefix:@"purpose::"])
2618 [purposes addObject:[tag substringFromIndex:9]];
2619 return [purposes count] == 0 ? nil : purposes;
2620}
2621
d8d9a65c
JF
2622- (bool) isCommercial {
2623 return [self hasTag:@"cydia::commercial"];
2624}
2625
dd9390c5
JF
2626- (CYString &) cyname {
2627 return name_.empty() ? id_ : name_;
6932575e
JF
2628}
2629
6932575e
JF
2630- (uint32_t) compareBySection:(NSArray *)sections {
2631 NSString *section([self section]);
2632 for (size_t i(0), e([sections count]); i != e; ++i) {
2633 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2634 return i;
e057ec05 2635 }
2d28b35a 2636
6932575e 2637 return _not(uint32_t);
e057ec05 2638}
2d28b35a 2639
f159ecd4
JF
2640- (uint32_t) compareForChanges {
2641 union {
2642 uint32_t key;
2d28b35a 2643
f159ecd4
JF
2644 struct {
2645 uint32_t timestamp : 30;
2646 uint32_t ignored : 1;
2647 uint32_t upgradable : 1;
2648 } bits;
2649 } value;
2d28b35a 2650
5c87d61b
JF
2651 bool upgradable([self upgradableAndEssential:YES]);
2652 value.bits.upgradable = upgradable ? 1 : 0;
b6ffa083 2653
5c87d61b 2654 if (upgradable) {
f159ecd4
JF
2655 value.bits.timestamp = 0;
2656 value.bits.ignored = [self ignored] ? 0 : 1;
2657 value.bits.upgradable = 1;
2658 } else {
2659 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2660 value.bits.ignored = 0;
2661 value.bits.upgradable = 0;
e057ec05 2662 }
b6ffa083 2663
f159ecd4 2664 return _not(uint32_t) - value.key;
e057ec05 2665}
b6ffa083 2666
3ff1504e
JF
2667- (void) clear {
2668 pkgProblemResolver *resolver = [database_ resolver];
2669 resolver->Clear(iterator_);
2670 resolver->Protect(iterator_);
2671}
2672
e057ec05
JF
2673- (void) install {
2674 pkgProblemResolver *resolver = [database_ resolver];
2675 resolver->Clear(iterator_);
2676 resolver->Protect(iterator_);
2677 pkgCacheFile &cache([database_ cache]);
2678 cache->MarkInstall(iterator_, false);
2679 pkgDepCache::StateCache &state((*cache)[iterator_]);
2680 if (!state.Install())
2681 cache->SetReInstall(iterator_, true);
2682}
0f25fa58 2683
e057ec05
JF
2684- (void) remove {
2685 pkgProblemResolver *resolver = [database_ resolver];
2686 resolver->Clear(iterator_);
2687 resolver->Protect(iterator_);
2688 resolver->Remove(iterator_);
2689 [database_ cache]->MarkDelete(iterator_, true);
2690}
b6ffa083 2691
7cf54836 2692- (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3bddda52
JF
2693 _profile(Package$isUnfilteredAndSearchedForBy)
2694 bool value(true);
2695
2696 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2697 value &= [self unfiltered];
2698 _end
2699
2700 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2701 value &= [self matches:search];
2702 _end
2703
7cf54836 2704 return value;
3bddda52 2705 _end
e057ec05 2706}
b6ffa083 2707
7cf54836
JF
2708- (bool) isInstalledAndVisible:(NSNumber *)number {
2709 return (![number boolValue] || [self visible]) && [self installed] != nil;
e057ec05 2710}
b6ffa083 2711
7cf54836 2712- (bool) isVisiblyUninstalledInSection:(NSString *)name {
965edd52
JF
2713 NSString *section = [self section];
2714
7cf54836 2715 return
853d14d3 2716 [self visible] &&
faf4eb4f
JF
2717 [self installed] == nil && (
2718 name == nil ||
2719 section == nil && [name length] == 0 ||
2720 [name isEqualToString:section]
7cf54836 2721 );
faf4eb4f
JF
2722}
2723
7cf54836
JF
2724- (bool) isVisibleInSource:(Source *)source {
2725 return [self source] == source && [self visible];
e057ec05 2726}
b6ffa083 2727
e057ec05
JF
2728@end
2729/* }}} */
2730/* Section Class {{{ */
2731@interface Section : NSObject {
2732 NSString *name_;
3bddda52 2733 unichar index_;
e057ec05
JF
2734 size_t row_;
2735 size_t count_;
6932575e 2736 NSString *localized_;
e057ec05 2737}
2d28b35a 2738
43b742af 2739- (NSComparisonResult) compareByLocalized:(Section *)section;
9ee296df
JF
2740- (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2741- (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2742- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3bddda52 2743- (Section *) initWithIndex:(unichar)index row:(size_t)row;
e057ec05 2744- (NSString *) name;
3bddda52 2745- (unichar) index;
6932575e 2746
e057ec05
JF
2747- (size_t) row;
2748- (size_t) count;
6932575e
JF
2749
2750- (void) addToRow;
e057ec05 2751- (void) addToCount;
a933cee2 2752
6932575e 2753- (void) setCount:(size_t)count;
43b742af 2754- (NSString *) localized;
6932575e 2755
e057ec05 2756@end
a933cee2 2757
e057ec05 2758@implementation Section
a933cee2 2759
e057ec05
JF
2760- (void) dealloc {
2761 [name_ release];
6932575e
JF
2762 if (localized_ != nil)
2763 [localized_ release];
e057ec05
JF
2764 [super dealloc];
2765}
a933cee2 2766
43b742af 2767- (NSComparisonResult) compareByLocalized:(Section *)section {
9ee296df
JF
2768 NSString *lhs(localized_);
2769 NSString *rhs([section localized]);
fa7bb92f 2770
9ee296df 2771 /*if ([lhs length] != 0 && [rhs length] != 0) {
fa7bb92f
JF
2772 unichar lhc = [lhs characterAtIndex:0];
2773 unichar rhc = [rhs characterAtIndex:0];
2774
2775 if (isalpha(lhc) && !isalpha(rhc))
2776 return NSOrderedAscending;
2777 else if (!isalpha(lhc) && isalpha(rhc))
2778 return NSOrderedDescending;
9ee296df 2779 }*/
fa7bb92f 2780
9c4e0cbe 2781 return [lhs compare:rhs options:LaxCompareOptions_];
fa7bb92f
JF
2782}
2783
9ee296df
JF
2784- (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2785 if ((self = [self initWithName:name localize:NO]) != nil) {
2786 if (localized != nil)
2787 localized_ = [localized retain];
2788 } return self;
2789}
2790
2791- (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2792 return [self initWithName:name row:0 localize:localize];
fa7bb92f
JF
2793}
2794
9ee296df 2795- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
e057ec05
JF
2796 if ((self = [super init]) != nil) {
2797 name_ = [name retain];
3bddda52
JF
2798 index_ = '\0';
2799 row_ = row;
9ee296df
JF
2800 if (localize)
2801 localized_ = [LocalizeSection(name_) retain];
3bddda52
JF
2802 } return self;
2803}
2804
6932575e 2805/* XXX: localize the index thingees */
3bddda52
JF
2806- (Section *) initWithIndex:(unichar)index row:(size_t)row {
2807 if ((self = [super init]) != nil) {
7f96382b 2808 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
3bddda52 2809 index_ = index;
e057ec05 2810 row_ = row;
a933cee2
JF
2811 } return self;
2812}
2813
e057ec05
JF
2814- (NSString *) name {
2815 return name_;
2816}
2817
3bddda52
JF
2818- (unichar) index {
2819 return index_;
2820}
2821
e057ec05
JF
2822- (size_t) row {
2823 return row_;
2824}
2825
2826- (size_t) count {
2827 return count_;
2828}
2829
6932575e
JF
2830- (void) addToRow {
2831 ++row_;
2832}
2833
e057ec05
JF
2834- (void) addToCount {
2835 ++count_;
2836}
2837
6932575e
JF
2838- (void) setCount:(size_t)count {
2839 count_ = count;
2840}
2841
2842- (NSString *) localized {
2843 return localized_;
2844}
2845
a933cee2
JF
2846@end
2847/* }}} */
2848
f464053e
JF
2849static int Finish_;
2850static NSArray *Finishes_;
03d01f0e 2851
e057ec05
JF
2852/* Database Implementation {{{ */
2853@implementation Database
1cb11c5f 2854
dbe0f181
JF
2855+ (Database *) sharedInstance {
2856 static Database *instance;
2857 if (instance == nil)
2858 instance = [[Database alloc] init];
2859 return instance;
2860}
2861
a70cf746
JF
2862- (unsigned) era {
2863 return era_;
2864}
2865
e057ec05
JF
2866- (void) dealloc {
2867 _assert(false);
6932575e
JF
2868 NSRecycleZone(zone_);
2869 // XXX: malloc_destroy_zone(zone_);
2870 apr_pool_destroy(pool_);
e057ec05
JF
2871 [super dealloc];
2872}
1cb11c5f 2873
f464053e 2874- (void) _readCydia:(NSNumber *)fd { _pooled
d72d91aa
JF
2875 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2876 std::istream is(&ib);
2877 std::string line;
2878
03d01f0e
JF
2879 static Pcre finish_r("^finish:([^:]*)$");
2880
d72d91aa
JF
2881 while (std::getline(is, line)) {
2882 const char *data(line.c_str());
03d01f0e 2883 size_t size = line.size();
cb9c2100 2884 lprintf("C:%s\n", data);
03d01f0e
JF
2885
2886 if (finish_r(data, size)) {
2887 NSString *finish = finish_r[1];
2888 int index = [Finishes_ indexOfObject:finish];
2889 if (index != INT_MAX && index > Finish_)
2890 Finish_ = index;
2891 }
d72d91aa
JF
2892 }
2893
d72d91aa
JF
2894 _assert(false);
2895}
2896
f464053e 2897- (void) _readStatus:(NSNumber *)fd { _pooled
e057ec05
JF
2898 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2899 std::istream is(&ib);
2900 std::string line;
1cb11c5f 2901
faf4eb4f
JF
2902 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2903 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
1cb11c5f 2904
e057ec05
JF
2905 while (std::getline(is, line)) {
2906 const char *data(line.c_str());
965edd52 2907 size_t size = line.size();
cb9c2100 2908 lprintf("S:%s\n", data);
1cb11c5f 2909
965edd52
JF
2910 if (conffile_r(data, size)) {
2911 [delegate_ setConfigurationData:conffile_r[1]];
2912 } else if (strncmp(data, "status: ", 8) == 0) {
2913 NSString *string = [NSString stringWithUTF8String:(data + 8)];
e057ec05 2914 [delegate_ setProgressTitle:string];
965edd52 2915 } else if (pmstatus_r(data, size)) {
238b07ce
JF
2916 std::string type([pmstatus_r[1] UTF8String]);
2917 NSString *id = pmstatus_r[2];
2918
965edd52
JF
2919 float percent([pmstatus_r[3] floatValue]);
2920 [delegate_ setProgressPercent:(percent / 100)];
2921
2922 NSString *string = pmstatus_r[4];
965edd52
JF
2923
2924 if (type == "pmerror")
238b07ce
JF
2925 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2926 withObject:[NSArray arrayWithObjects:string, id, nil]
2927 waitUntilDone:YES
2928 ];
907a35d6 2929 else if (type == "pmstatus") {
965edd52 2930 [delegate_ setProgressTitle:string];
907a35d6 2931 } else if (type == "pmconffile")
965edd52
JF
2932 [delegate_ setConfigurationData:string];
2933 else _assert(false);
2934 } else _assert(false);
e057ec05 2935 }
1cb11c5f 2936
e057ec05
JF
2937 _assert(false);
2938}
1cb11c5f 2939
f464053e 2940- (void) _readOutput:(NSNumber *)fd { _pooled
e057ec05
JF
2941 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2942 std::istream is(&ib);
2943 std::string line;
2944
965edd52 2945 while (std::getline(is, line)) {
cb9c2100 2946 lprintf("O:%s\n", line.c_str());
2a987aa5 2947 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
965edd52 2948 }
e057ec05 2949
e057ec05 2950 _assert(false);
1cb11c5f
JF
2951}
2952
7600bd69
JF
2953- (FILE *) input {
2954 return input_;
2955}
2956
e057ec05 2957- (Package *) packageWithName:(NSString *)name {
965edd52
JF
2958 if (static_cast<pkgDepCache *>(cache_) == NULL)
2959 return nil;
e057ec05 2960 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
6932575e 2961 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
e057ec05
JF
2962}
2963
2964- (Database *) init {
1cb11c5f 2965 if ((self = [super init]) != nil) {
965edd52 2966 policy_ = NULL;
e057ec05
JF
2967 records_ = NULL;
2968 resolver_ = NULL;
2969 fetcher_ = NULL;
2970 lock_ = NULL;
1cb11c5f 2971
6932575e
JF
2972 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2973 apr_pool_create(&pool_, NULL);
2974
9ee296df 2975 packages_ = [[NSMutableArray alloc] init];
1cb11c5f 2976
e057ec05 2977 int fds[2];
1cb11c5f 2978
d72d91aa
JF
2979 _assert(pipe(fds) != -1);
2980 cydiafd_ = fds[1];
2981
2982 _config->Set("APT::Keep-Fds::", cydiafd_);
03d01f0e 2983 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
d72d91aa
JF
2984
2985 [NSThread
2986 detachNewThreadSelector:@selector(_readCydia:)
2987 toTarget:self
2988 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2989 ];
2990
e057ec05
JF
2991 _assert(pipe(fds) != -1);
2992 statusfd_ = fds[1];
1cb11c5f 2993
e057ec05
JF
2994 [NSThread
2995 detachNewThreadSelector:@selector(_readStatus:)
2996 toTarget:self
2997 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2998 ];
1cb11c5f 2999
7600bd69
JF
3000 _assert(pipe(fds) != -1);
3001 _assert(dup2(fds[0], 0) != -1);
3002 _assert(close(fds[0]) != -1);
3003
3004 input_ = fdopen(fds[1], "a");
3005
e057ec05
JF
3006 _assert(pipe(fds) != -1);
3007 _assert(dup2(fds[1], 1) != -1);
3008 _assert(close(fds[1]) != -1);
3009
3010 [NSThread
3011 detachNewThreadSelector:@selector(_readOutput:)
3012 toTarget:self
3013 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3014 ];
1cb11c5f
JF
3015 } return self;
3016}
3017
e057ec05
JF
3018- (pkgCacheFile &) cache {
3019 return cache_;
1cb11c5f
JF
3020}
3021
965edd52
JF
3022- (pkgDepCache::Policy *) policy {
3023 return policy_;
3024}
3025
e057ec05
JF
3026- (pkgRecords *) records {
3027 return records_;
1cb11c5f
JF
3028}
3029
e057ec05
JF
3030- (pkgProblemResolver *) resolver {
3031 return resolver_;
1cb11c5f
JF
3032}
3033
e057ec05
JF
3034- (pkgAcquire &) fetcher {
3035 return *fetcher_;
1cb11c5f
JF
3036}
3037
ce09fc27
JF
3038- (pkgSourceList &) list {
3039 return *list_;
3040}
3041
e057ec05
JF
3042- (NSArray *) packages {
3043 return packages_;
1cb11c5f
JF
3044}
3045
faf4eb4f 3046- (NSArray *) sources {
631a0a1e
JF
3047 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3048 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3049 [sources addObject:i->second];
3050 return sources;
faf4eb4f
JF
3051}
3052
f464053e
JF
3053- (NSArray *) issues {
3054 if (cache_->BrokenCount() == 0)
3055 return nil;
3056
3057 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3058
3059 for (Package *package in packages_) {
3060 if (![package broken])
3061 continue;
3062 pkgCache::PkgIterator pkg([package iterator]);
3063
3064 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3065 [entry addObject:[package name]];
3066 [issues addObject:entry];
3067
3068 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3069 if (ver.end())
3070 continue;
3071
3072 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3073 pkgCache::DepIterator start;
3074 pkgCache::DepIterator end;
3075 dep.GlobOr(start, end); // ++dep
3076
3077 if (!cache_->IsImportantDep(end))
3078 continue;
3079 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3080 continue;
3081
3082 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3083 [entry addObject:failure];
3084 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3085
3086 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3087 [failure addObject:[package name]];
3088
3089 pkgCache::PkgIterator target(start.TargetPkg());
3090 if (target->ProvidesList != 0)
3091 [failure addObject:@"?"];
3092 else {
3093 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3094 if (!ver.end())
3095 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3096 else if (!cache_[target].CandidateVerIter(cache_).end())
3097 [failure addObject:@"-"];
3098 else if (target->ProvidesList == 0)
3099 [failure addObject:@"!"];
3100 else
3101 [failure addObject:@"%"];
3102 }
3103
3104 _forever {
3105 if (start.TargetVer() != 0)
3106 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3107 if (start == end)
3108 break;
3109 ++start;
3110 }
3111 }
3112 }
3113
3114 return issues;
3115}
3116
7398a389 3117- (void) reloadData { _pooled
a70cf746
JF
3118 @synchronized (self) {
3119 ++era_;
3120 }
3121
98fb9119
JF
3122 [packages_ removeAllObjects];
3123 sources_.clear();
3124
e057ec05 3125 _error->Discard();
965edd52 3126
e057ec05 3127 delete list_;
965edd52 3128 list_ = NULL;
e057ec05
JF
3129 manager_ = NULL;
3130 delete lock_;
965edd52 3131 lock_ = NULL;
e057ec05 3132 delete fetcher_;
965edd52 3133 fetcher_ = NULL;
e057ec05 3134 delete resolver_;
965edd52 3135 resolver_ = NULL;
e057ec05 3136 delete records_;
965edd52
JF
3137 records_ = NULL;
3138 delete policy_;
3139 policy_ = NULL;
e057ec05 3140
98fb9119
JF
3141 if (now_ != nil) {
3142 [now_ release];
3143 now_ = nil;
3144 }
3145
965edd52 3146 cache_.Close();
7600bd69 3147
6932575e
JF
3148 apr_pool_clear(pool_);
3149 NSRecycleZone(zone_);
3150
3e3977a2
JF
3151 int chk(creat("/tmp/cydia.chk", 0644));
3152 if (chk != -1)
3153 close(chk);
3154
907a35d6 3155 _trace();
965edd52 3156 if (!cache_.Open(progress_, true)) {
7600bd69
JF
3157 std::string error;
3158 if (!_error->PopMessage(error))
3159 _assert(false);
965edd52 3160 _error->Discard();
cb9c2100 3161 lprintf("cache_.Open():[%s]\n", error.c_str());
965edd52
JF
3162
3163 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3164 [delegate_ repairWithSelector:@selector(configure)];
3165 else if (error == "The package lists or status file could not be parsed or opened.")
3166 [delegate_ repairWithSelector:@selector(update)];
fc19e583
JF
3167 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3168 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3169 // else if (error == "The list of sources could not be read.")
965edd52
JF
3170 else _assert(false);
3171
3172 return;
e057ec05 3173 }
907a35d6 3174 _trace();
e057ec05 3175
3e3977a2
JF
3176 unlink("/tmp/cydia.chk");
3177
e057ec05
JF
3178 now_ = [[NSDate date] retain];
3179
965edd52 3180 policy_ = new pkgDepCache::Policy();
e057ec05
JF
3181 records_ = new pkgRecords(cache_);
3182 resolver_ = new pkgProblemResolver(cache_);
3183 fetcher_ = new pkgAcquire(&status_);
3184 lock_ = NULL;
3185
3186 list_ = new pkgSourceList();
3187 _assert(list_->ReadMainList());
3188
3319715b
JF
3189 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3190 _assert(pkgApplyStatus(cache_));
3191
3192 if (cache_->BrokenCount() != 0) {
3193 _assert(pkgFixBroken(cache_));
3194 _assert(cache_->BrokenCount() == 0);
3195 _assert(pkgMinimizeUpgrade(cache_));
3196 }
3197
3e3977a2 3198 _trace();
631a0a1e 3199
631a0a1e
JF
3200 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3201 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3202 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3203 // XXX: this could be more intelligent
3204 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3205 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3206 if (!cached.end())
b8b1cfd0 3207 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
631a0a1e 3208 }
e057ec05 3209 }
631a0a1e 3210
3e3977a2 3211 _trace();
e057ec05 3212
43b742af 3213 {
9ee296df 3214 /*std::vector<Package *> packages;
43b742af 3215 packages.reserve(std::max(10000U, [packages_ count] + 1000));
43b742af 3216 [packages_ release];
9ee296df
JF
3217 packages_ = nil;*/
3218
43b742af
JF
3219 _trace();
3220
3221 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3222 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
9ee296df
JF
3223 //packages.push_back(package);
3224 [packages_ addObject:package];
43b742af
JF
3225
3226 _trace();
3227
9ee296df 3228 /*if (packages.empty())
43b742af
JF
3229 packages_ = [[NSArray alloc] init];
3230 else
3231 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
9ee296df
JF
3232 _trace();*/
3233
dd9390c5
JF
3234 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3235 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3236 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
9ee296df
JF
3237
3238 /*_trace();
3239 PrintTimes();
3240 _trace();*/
3241
3242 _trace();
3243
3244 /*if (!packages.empty())
3245 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3246 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3247
66abcbb0
JF
3248 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3249
dd9390c5 3250 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
9ee296df
JF
3251
3252 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
43b742af
JF
3253
3254 _trace();
3255 }
1cb11c5f
JF
3256}
3257
965edd52
JF
3258- (void) configure {
3259 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3260 system([dpkg UTF8String]);
3261}
3262
d72d91aa
JF
3263- (void) clean {
3264 if (lock_ != NULL)
3265 return;
3266
3267 FileFd Lock;
3268 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3269 _assert(!_error->PendingError());
3270
3271 pkgAcquire fetcher;
3272 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3273
3319715b
JF
3274 class LogCleaner :
3275 public pkgArchiveCleaner
3276 {
d72d91aa
JF
3277 protected:
3278 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3319715b 3279 unlink(File);
d72d91aa
JF
3280 }
3281 } cleaner;
3282
3283 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3284 std::string error;
3285 while (_error->PopMessage(error))
cb9c2100 3286 lprintf("ArchiveCleaner: %s\n", error.c_str());
d72d91aa
JF
3287 }
3288}
3289
e057ec05
JF
3290- (void) prepare {
3291 pkgRecords records(cache_);
3292
3293 lock_ = new FileFd();
3294 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3295 _assert(!_error->PendingError());
3296
3297 pkgSourceList list;
3298 // XXX: explain this with an error message
3299 _assert(list.ReadMainList());
3300
3301 manager_ = (_system->CreatePM(cache_));
3302 _assert(manager_->GetArchives(fetcher_, &list, &records));
3303 _assert(!_error->PendingError());
1cb11c5f
JF
3304}
3305
e057ec05 3306- (void) perform {
113c9b62
JF
3307 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3308 pkgSourceList list;
3309 _assert(list.ReadMainList());
3310 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3311 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3312 }
8993ad57 3313
2d7f7dea
JF
3314 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3315 _trace();
e057ec05 3316 return;
2d7f7dea
JF
3317 }
3318
3319 bool failed = false;
3320 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3321 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3322 continue;
3323
3324 std::string uri = (*item)->DescURI();
3325 std::string error = (*item)->ErrorText;
3326
cb9c2100 3327 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
2d7f7dea
JF
3328 failed = true;
3329
3330 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
ce09fc27
JF
3331 withObject:[NSArray arrayWithObjects:
3332 [NSString stringWithUTF8String:error.c_str()],
3333 nil]
2d7f7dea
JF
3334 waitUntilDone:YES
3335 ];
3336 }
3337
3338 if (failed) {
3339 _trace();
3340 return;
3341 }
e057ec05
JF
3342
3343 _system->UnLock();
3344 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3345
2d7f7dea
JF
3346 if (_error->PendingError()) {
3347 _trace();
e057ec05 3348 return;
2d7f7dea
JF
3349 }
3350
3351 if (result == pkgPackageManager::Failed) {
3352 _trace();
e057ec05 3353 return;
2d7f7dea
JF
3354 }
3355
3356 if (result != pkgPackageManager::Completed) {
3357 _trace();
e057ec05 3358 return;
2d7f7dea 3359 }
8993ad57 3360
113c9b62
JF
3361 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3362 pkgSourceList list;
3363 _assert(list.ReadMainList());
3364 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3365 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3366 }
3367
3368 if (![before isEqualToArray:after])
3369 [self update];
1cb11c5f
JF
3370}
3371
e057ec05 3372- (void) upgrade {
e057ec05 3373 _assert(pkgDistUpgrade(cache_));
1951a333
JF
3374}
3375
e057ec05
JF
3376- (void) update {
3377 [self updateWithStatus:status_];
3378}
686e302f 3379
e057ec05
JF
3380- (void) updateWithStatus:(Status &)status {
3381 pkgSourceList list;
3382 _assert(list.ReadMainList());
686e302f 3383
e057ec05
JF
3384 FileFd lock;
3385 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3386 _assert(!_error->PendingError());
3387
3388 pkgAcquire fetcher(&status);
3389 _assert(list.GetIndexes(&fetcher));
3390
3391 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3392 bool failed = false;
3393 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3394 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3395 (*item)->Finished();
3396 failed = true;
3397 }
3398
3399 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3400 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3401 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
686e302f 3402 }
e057ec05
JF
3403
3404 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3d37fc0d 3405 Changed_ = true;
686e302f
JF
3406 }
3407}
3408
e057ec05
JF
3409- (void) setDelegate:(id)delegate {
3410 delegate_ = delegate;
3411 status_.setDelegate(delegate);
3412 progress_.setDelegate(delegate);
3413}
686e302f 3414
3e3977a2 3415- (Source *) getSource:(pkgCache::PkgFileIterator)file {
631a0a1e 3416 return sources_[file->ID];
a933cee2
JF
3417}
3418
e057ec05
JF
3419@end
3420/* }}} */
686e302f 3421
f464053e 3422/* PopUp Windows {{{ */
cb9c2100
JF
3423@interface PopUpView : UIView {
3424 _transient id delegate_;
3425 UITransitionView *transition_;
3426 UIView *overlay_;
3427}
3428
3429- (void) cancel;
3430- (id) initWithView:(UIView *)view delegate:(id)delegate;
3431
3432@end
3433
3434@implementation PopUpView
3435
3436- (void) dealloc {
3437 [transition_ setDelegate:nil];
3438 [transition_ release];
3439 [overlay_ release];
3440 [super dealloc];
3441}
3442
3443- (void) cancel {
3444 [transition_ transition:UITransitionPushFromTop toView:nil];
3445}
3446
3447- (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3448 if (from != nil && to == nil)
3449 [self removeFromSuperview];
3450}
3451
3452- (id) initWithView:(UIView *)view delegate:(id)delegate {
3453 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3454 delegate_ = delegate;
3455
3456 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3457 [self addSubview:transition_];
3458
3459 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3460
3461 [view addSubview:self];
3462
3463 [transition_ setDelegate:self];
3464
3465 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3466 [transition_ transition:UITransitionNone toView:blank];
3467 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3468 } return self;
3469}
3470
3471@end
3472/* }}} */
3473
6932575e 3474#if 0
cb9c2100
JF
3475/* Mail Composition {{{ */
3476@interface MailToView : PopUpView {
3477 MailComposeController *controller_;
3478}
3479
3480- (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3481
3482@end
3483
3484@implementation MailToView
3485
3486- (void) dealloc {
3487 [controller_ release];
3488 [super dealloc];
3489}
3490
cb9c2100
JF
3491- (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3492 NSLog(@"will");
3493}
3494
3495- (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3496 NSLog(@"did:%@", delivery);
3497// [UIApp setStatusBarShowsProgress:NO];
3498if ([controller error]){
6932575e
JF
3499NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3500UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
cb9c2100
JF
3501[mailAlertSheet setBodyText:[controller error]];
3502[mailAlertSheet popupAlertAnimated:YES];
3503}
3504}
3505
f464053e
JF
3506- (void) showError {
3507 NSLog(@"%@", [controller_ error]);
6932575e
JF
3508 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3509 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
f464053e
JF
3510 [mailAlertSheet setBodyText:[controller_ error]];
3511 [mailAlertSheet popupAlertAnimated:YES];
3512}
3513
3514- (void) deliverMessage { _pooled
56e10908
JF
3515 setuid(501);
3516 setgid(501);
3517
f464053e
JF
3518 if (![controller_ deliverMessage])
3519 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3520}
3521
cb9c2100 3522- (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
f464053e
JF
3523 if ([controller_ needsDelivery])
3524 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
cb9c2100
JF
3525 else
3526 [self cancel];
3527}
3528
3529- (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3530 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3531 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3532 [controller_ setDelegate:self];
3533 [controller_ initializeUI];
3534 [controller_ setupForURL:url];
3535
3536 UIView *view([controller_ view]);
3537 [overlay_ addSubview:view];
3538 } return self;
3539}
3540
3541@end
3542/* }}} */
6932575e
JF
3543#endif
3544
e057ec05 3545/* Confirmation View {{{ */
e00439f7
JF
3546bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3547 if (!iterator.end())
3548 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3549 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3550 continue;
3551 pkgCache::PkgIterator package(dep.TargetPkg());
3552 if (package.end())
3553 continue;
3554 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3555 return true;
3556 }
3557
3558 return false;
3559}
3560
e057ec05
JF
3561@protocol ConfirmationViewDelegate
3562- (void) cancel;
3563- (void) confirm;
3ff1504e 3564- (void) queue;
e057ec05 3565@end
4941f41d 3566
f464053e 3567@interface ConfirmationView : BrowserView {
dbe0f181 3568 _transient Database *database_;
d210b85d 3569 UIActionSheet *essential_;
f464053e
JF
3570 NSArray *changes_;
3571 NSArray *issues_;
3572 NSArray *sizes_;
e00439f7 3573 BOOL substrate_;
e057ec05 3574}
a75f53e7 3575
f464053e 3576- (id) initWithBook:(RVBook *)book database:(Database *)database;
686e302f 3577
a75f53e7
JF
3578@end
3579
e057ec05 3580@implementation ConfirmationView
a75f53e7 3581
4941f41d 3582- (void) dealloc {
f464053e
JF
3583 [changes_ release];
3584 if (issues_ != nil)
3585 [issues_ release];
3586 [sizes_ release];
e057ec05
JF
3587 if (essential_ != nil)
3588 [essential_ release];
4941f41d
JF
3589 [super dealloc];
3590}
3591
e057ec05 3592- (void) cancel {
e057ec05 3593 [delegate_ cancel];
f464053e 3594 [book_ popFromSuperviewAnimated:YES];
e057ec05
JF
3595}
3596
d210b85d 3597- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
a5dd312c 3598 NSString *context([sheet context]);
3319715b 3599
a5dd312c 3600 if ([context isEqualToString:@"remove"]) {
3319715b
JF
3601 switch (button) {
3602 case 1:
238b07ce 3603 [self cancel];
3319715b
JF
3604 break;
3605 case 2:
e00439f7
JF
3606 if (substrate_)
3607 Finish_ = 2;
238b07ce 3608 [delegate_ confirm];
3319715b
JF
3609 break;
3610 default:
3611 _assert(false);
3612 }
3319715b 3613
a5dd312c
JF
3614 [sheet dismiss];
3615 } else if ([context isEqualToString:@"unable"]) {
3616 [self cancel];
3617 [sheet dismiss];
3618 } else
3619 [super alertSheet:sheet buttonClicked:button];
e057ec05
JF
3620}
3621
f464053e 3622- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6932575e 3623 [super webView:sender didClearWindowObject:window forFrame:frame];
f464053e
JF
3624 [window setValue:changes_ forKey:@"changes"];
3625 [window setValue:issues_ forKey:@"issues"];
3626 [window setValue:sizes_ forKey:@"sizes"];
e057ec05
JF
3627}
3628
f464053e 3629- (id) initWithBook:(RVBook *)book database:(Database *)database {
dbe0f181
JF
3630 if ((self = [super initWithBook:book]) != nil) {
3631 database_ = database;
3632
e057ec05
JF
3633 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3634 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3635 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3636 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3637 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
a75f53e7 3638
e057ec05 3639 bool remove(false);
a75f53e7 3640
e00439f7
JF
3641 pkgDepCache::Policy *policy([database_ policy]);
3642
e057ec05 3643 pkgCacheFile &cache([database_ cache]);
2a987aa5 3644 NSArray *packages = [database_ packages];
9fdd37d0 3645 for (Package *package in packages) {
2a987aa5 3646 pkgCache::PkgIterator iterator = [package iterator];
e057ec05 3647 pkgDepCache::StateCache &state(cache[iterator]);
a75f53e7 3648
2a987aa5
JF
3649 NSString *name([package name]);
3650
e057ec05
JF
3651 if (state.NewInstall())
3652 [installing addObject:name];
3653 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3654 [reinstalling addObject:name];
3655 else if (state.Upgrade())
3656 [upgrading addObject:name];
3657 else if (state.Downgrade())
3658 [downgrading addObject:name];
3659 else if (state.Delete()) {
2a987aa5 3660 if ([package essential])
e057ec05
JF
3661 remove = true;
3662 [removing addObject:name];
e00439f7
JF
3663 } else continue;
3664
3665 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3666 substrate_ |= DepSubstrate(iterator.CurrentVer());
e057ec05 3667 }
1cb11c5f 3668
e057ec05
JF
3669 if (!remove)
3670 essential_ = nil;
3319715b 3671 else if (Advanced_ || true) {
6932575e
JF
3672 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3673
d210b85d 3674 essential_ = [[UIActionSheet alloc]
6932575e 3675 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3319715b 3676 buttons:[NSArray arrayWithObjects:
6932575e
JF
3677 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3678 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3319715b 3679 nil]
238b07ce 3680 defaultButtonIndex:0
3319715b
JF
3681 delegate:self
3682 context:@"remove"
3683 ];
3684
b27f0a94 3685#ifndef __OBJC2__
3319715b 3686 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
b27f0a94 3687#endif
6932575e 3688 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3319715b 3689 } else {
d210b85d 3690 essential_ = [[UIActionSheet alloc]
6932575e
JF
3691 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3692 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
e057ec05
JF
3693 defaultButtonIndex:0
3694 delegate:self
3319715b 3695 context:@"unable"
e057ec05 3696 ];
1cb11c5f 3697
6932575e 3698 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
e057ec05 3699 }
1cb11c5f 3700
f464053e
JF
3701 changes_ = [[NSArray alloc] initWithObjects:
3702 installing,
3703 reinstalling,
3704 upgrading,
3705 downgrading,
3706 removing,
3707 nil];
a75f53e7 3708
f464053e
JF
3709 issues_ = [database_ issues];
3710 if (issues_ != nil)
3711 issues_ = [issues_ retain];
a75f53e7 3712
f464053e
JF
3713 sizes_ = [[NSArray alloc] initWithObjects:
3714 SizeString([database_ fetcher].FetchNeeded()),
3715 SizeString([database_ fetcher].PartialPresent()),
3716 SizeString([database_ cache]->UsrSize()),
3717 nil];
a75f53e7 3718
f464053e 3719 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
e057ec05 3720 } return self;
686e302f 3721}
20dd7407 3722
f464053e 3723- (NSString *) backButtonTitle {
6932575e 3724 return CYLocalize("CONFIRM");
f464053e
JF
3725}
3726
3727- (NSString *) leftButtonTitle {
6932575e 3728 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
f464053e
JF
3729}
3730
b456f1c9
JF
3731- (id) rightButtonTitle {
3732 return issues_ != nil ? nil : [super rightButtonTitle];
3733}
3734
2bfeaf6f 3735- (id) _rightButtonTitle {
83105e6e 3736#if AlwaysReload || IgnoreInstall
b456f1c9 3737 return [super _rightButtonTitle];
83105e6e 3738#else
6932575e 3739 return CYLocalize("CONFIRM");
83105e6e 3740#endif
f464053e
JF
3741}
3742
3743- (void) _leftButtonClicked {
3744 [self cancel];
3745}
3746
907a35d6 3747#if !AlwaysReload
f464053e 3748- (void) _rightButtonClicked {
83105e6e
JF
3749#if IgnoreInstall
3750 return [super _rightButtonClicked];
3751#endif
f464053e
JF
3752 if (essential_ != nil)
3753 [essential_ popupAlertAnimated:YES];
3754 else {
3755 if (substrate_)
3756 Finish_ = 2;
3757 [delegate_ confirm];
3758 }
3759}
907a35d6 3760#endif
f464053e 3761
e057ec05
JF
3762@end
3763/* }}} */
20dd7407 3764
e057ec05
JF
3765/* Progress Data {{{ */
3766@interface ProgressData : NSObject {
3767 SEL selector_;
3768 id target_;
3769 id object_;
a75f53e7
JF
3770}
3771
e057ec05 3772- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
686e302f 3773
e057ec05
JF
3774- (SEL) selector;
3775- (id) target;
3776- (id) object;
3777@end
686e302f 3778
e057ec05 3779@implementation ProgressData
686e302f 3780
e057ec05
JF
3781- (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3782 if ((self = [super init]) != nil) {
3783 selector_ = selector;
3784 target_ = target;
3785 object_ = object;
3786 } return self;
3787}
686e302f 3788
e057ec05
JF
3789- (SEL) selector {
3790 return selector_;
3791}
686e302f 3792
e057ec05
JF
3793- (id) target {
3794 return target_;
20dd7407
JF
3795}
3796
e057ec05
JF
3797- (id) object {
3798 return object_;
a75f53e7
JF
3799}
3800
4941f41d
JF
3801@end
3802/* }}} */
e057ec05
JF
3803/* Progress View {{{ */
3804@interface ProgressView : UIView <
7600bd69 3805 ConfigurationDelegate,
e057ec05
JF
3806 ProgressDelegate
3807> {
7600bd69 3808 _transient Database *database_;
e057ec05
JF
3809 UIView *view_;
3810 UIView *background_;
3811 UITransitionView *transition_;
3812 UIView *overlay_;
3813 UINavigationBar *navbar_;
3814 UIProgressBar *progress_;
3815 UITextView *output_;
3816 UITextLabel *status_;
238b07ce 3817 UIPushButton *close_;
e057ec05 3818 id delegate_;
b26eb97d 3819 BOOL running_;
1eb0c554 3820 SHA1SumValue springlist_;
bde2d79b 3821 SHA1SumValue notifyconf_;
f464053e 3822 SHA1SumValue sandplate_;
4941f41d
JF
3823}
3824
e057ec05 3825- (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
4941f41d 3826
7600bd69 3827- (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
e057ec05
JF
3828- (void) setContentView:(UIView *)view;
3829- (void) resetView;
4941f41d 3830
e057ec05
JF
3831- (void) _retachThread;
3832- (void) _detachNewThreadData:(ProgressData *)data;
3833- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4941f41d 3834
b26eb97d
JF
3835- (BOOL) isRunning;
3836
4941f41d
JF
3837@end
3838
e057ec05
JF
3839@protocol ProgressViewDelegate
3840- (void) progressViewIsComplete:(ProgressView *)sender;
3841@end
3842
3843@implementation ProgressView
4941f41d
JF
3844
3845- (void) dealloc {
e057ec05
JF
3846 [transition_ setDelegate:nil];
3847 [navbar_ setDelegate:nil];
3848
3849 [view_ release];
3850 if (background_ != nil)
3851 [background_ release];
3852 [transition_ release];
3853 [overlay_ release];
3854 [navbar_ release];
3855 [progress_ release];
3856 [output_ release];
3857 [status_ release];
238b07ce 3858 [close_ release];
4941f41d
JF
3859 [super dealloc];
3860}
3861
e057ec05
JF
3862- (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3863 if (bootstrap_ && from == overlay_ && to == view_)
3864 exit(0);
3865}
4941f41d 3866
7600bd69 3867- (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
e057ec05 3868 if ((self = [super initWithFrame:frame]) != nil) {
7600bd69 3869 database_ = database;
e057ec05 3870 delegate_ = delegate;
1cb11c5f 3871
e057ec05
JF
3872 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3873 [transition_ setDelegate:self];
4941f41d 3874
e057ec05 3875 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
1cb11c5f 3876
e057ec05 3877 if (bootstrap_)
87c76914 3878 [overlay_ setBackgroundColor:[UIColor blackColor]];
e057ec05
JF
3879 else {
3880 background_ = [[UIView alloc] initWithFrame:[self bounds]];
87c76914 3881 [background_ setBackgroundColor:[UIColor blackColor]];
e057ec05
JF
3882 [self addSubview:background_];
3883 }
1cb11c5f 3884
e057ec05 3885 [self addSubview:transition_];
4941f41d 3886
e057ec05
JF
3887 CGSize navsize = [UINavigationBar defaultSize];
3888 CGRect navrect = {{0, 0}, navsize};
4941f41d 3889
e057ec05
JF
3890 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3891 [overlay_ addSubview:navbar_];
686e302f 3892
e057ec05
JF
3893 [navbar_ setBarStyle:1];
3894 [navbar_ setDelegate:self];
4941f41d 3895
e057ec05
JF
3896 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3897 [navbar_ pushNavigationItem:navitem];
1951a333 3898
e057ec05
JF
3899 CGRect bounds = [overlay_ bounds];
3900 CGSize prgsize = [UIProgressBar defaultSize];
1cb11c5f 3901
e057ec05
JF
3902 CGRect prgrect = {{
3903 (bounds.size.width - prgsize.width) / 2,
3904 bounds.size.height - prgsize.height - 20
3905 }, prgsize};
1cb11c5f 3906
e057ec05 3907 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
238b07ce 3908 [progress_ setStyle:0];
1cb11c5f 3909
e057ec05
JF
3910 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3911 10,
3912 bounds.size.height - prgsize.height - 50,
3913 bounds.size.width - 20,
3914 24
3915 )];
1cb11c5f 3916
87c76914
JF
3917 [status_ setColor:[UIColor whiteColor]];
3918 [status_ setBackgroundColor:[UIColor clearColor]];
1cb11c5f 3919
e057ec05
JF
3920 [status_ setCentersHorizontally:YES];
3921 //[status_ setFont:font];
b7ad9c68 3922 _trace();
1cb11c5f 3923
e057ec05
JF
3924 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3925 10,
3926 navrect.size.height + 20,
3927 bounds.size.width - 20,
3928 bounds.size.height - navsize.height - 62 - navrect.size.height
3929 )];
b7ad9c68 3930 _trace();
3325a005 3931
e057ec05
JF
3932 //[output_ setTextFont:@"Courier New"];
3933 [output_ setTextSize:12];
4941f41d 3934
87c76914
JF
3935 [output_ setTextColor:[UIColor whiteColor]];
3936 [output_ setBackgroundColor:[UIColor clearColor]];
4941f41d 3937
e057ec05
JF
3938 [output_ setMarginTop:0];
3939 [output_ setAllowsRubberBanding:YES];
81ab76dc 3940 [output_ setEditable:NO];
686e302f 3941
e057ec05 3942 [overlay_ addSubview:output_];
4941f41d 3943
238b07ce
JF
3944 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3945 10,
3946 bounds.size.height - prgsize.height - 50,
3947 bounds.size.width - 20,
81ab76dc 3948 32 + prgsize.height
238b07ce
JF
3949 )];
3950
3951 [close_ setAutosizesToFit:NO];
3952 [close_ setDrawsShadow:YES];
3953 [close_ setStretchBackground:YES];
238b07ce
JF
3954 [close_ setEnabled:YES];
3955
d210b85d 3956 UIFont *bold = [UIFont boldSystemFontOfSize:22];
238b07ce 3957 [close_ setTitleFont:bold];
238b07ce
JF
3958
3959 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3960 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3961 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
e057ec05 3962 } return self;
4941f41d
JF
3963}
3964
e057ec05
JF
3965- (void) setContentView:(UIView *)view {
3966 view_ = [view retain];
4941f41d
JF
3967}
3968
e057ec05
JF
3969- (void) resetView {
3970 [transition_ transition:6 toView:view_];
4941f41d
JF
3971}
3972
d210b85d 3973- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
a5dd312c
JF
3974 NSString *context([sheet context]);
3975
ce09fc27
JF
3976 if ([context isEqualToString:@"error"])
3977 [sheet dismiss];
3978 else if ([context isEqualToString:@"conffile"]) {
7600bd69
JF
3979 FILE *input = [database_ input];
3980
3981 switch (button) {
3982 case 1:
3983 fprintf(input, "N\n");
3984 fflush(input);
3319715b 3985 break;
7600bd69
JF
3986 case 2:
3987 fprintf(input, "Y\n");
3988 fflush(input);
3319715b
JF
3989 break;
3990 default:
3991 _assert(false);
7600bd69 3992 }
7600bd69 3993
a5dd312c
JF
3994 [sheet dismiss];
3995 }
4941f41d
JF
3996}
3997
238b07ce 3998- (void) closeButtonPushed {
f464053e
JF
3999 running_ = NO;
4000
03d01f0e
JF
4001 switch (Finish_) {
4002 case 0:
e00439f7 4003 [self resetView];
03d01f0e
JF
4004 break;
4005
4006 case 1:
4007 [delegate_ suspendWithAnimation:YES];
4008 break;
4009
4010 case 2:
e00439f7 4011 system("launchctl stop com.apple.SpringBoard");
03d01f0e
JF
4012 break;
4013
4014 case 3:
f464053e 4015 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
03d01f0e
JF
4016 break;
4017
4018 case 4:
4019 system("reboot");
4020 break;
4021 }
a933cee2
JF
4022}
4023
238b07ce 4024- (void) _retachThread {
81ab76dc 4025 UINavigationItem *item = [navbar_ topItem];
6932575e 4026 [item setTitle:CYLocalize("COMPLETE")];
81ab76dc 4027
238b07ce
JF
4028 [overlay_ addSubview:close_];
4029 [progress_ removeFromSuperview];
4030 [status_ removeFromSuperview];
b26eb97d 4031
cb9c2100
JF
4032 [delegate_ progressViewIsComplete:self];
4033
f464053e
JF
4034 if (Finish_ < 4) {
4035 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4036 MMap mmap(file, MMap::ReadOnly);
4037 SHA1Summation sha1;
4038 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4039 if (!(sandplate_ == sha1.Result()))
4040 Finish_ = 4;
4041 }
4042
bde2d79b
JF
4043 if (Finish_ < 4) {
4044 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4045 MMap mmap(file, MMap::ReadOnly);
4046 SHA1Summation sha1;
4047 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4048 if (!(notifyconf_ == sha1.Result()))
4049 Finish_ = 4;
4050 }
4051
f464053e
JF
4052 if (Finish_ < 3) {
4053 FileFd file(SpringBoard_, FileFd::ReadOnly);
1eb0c554
JF
4054 MMap mmap(file, MMap::ReadOnly);
4055 SHA1Summation sha1;
4056 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4057 if (!(springlist_ == sha1.Result()))
4058 Finish_ = 3;
4059 }
4060
03d01f0e 4061 switch (Finish_) {
6932575e
JF
4062 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4063 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4064 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4065 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4066 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
03d01f0e
JF
4067 }
4068
2cb68ddf
JF
4069#define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4070
405eb8a3 4071 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
2cb68ddf
JF
4072 [cache autorelease];
4073
4074 NSFileManager *manager = [NSFileManager defaultManager];
7f9c29fa 4075 NSError *error = nil;
2cb68ddf 4076
7f9c29fa 4077 id system = [cache objectForKey:@"System"];
2cb68ddf
JF
4078 if (system == nil)
4079 goto error;
4080
4081 struct stat info;
4082 if (stat(Cache_, &info) == -1)
4083 goto error;
4084
4085 [system removeAllObjects];
4086
7f9c29fa 4087 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
2cb68ddf
JF
4088 for (NSString *app in apps)
4089 if ([app hasSuffix:@".app"]) {
4090 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4091 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4092 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4093 [info autorelease];
e69d449d
JF
4094 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4095 [info setObject:path forKey:@"Path"];
4096 [info setObject:@"System" forKey:@"ApplicationType"];
4097 [system addInfoDictionary:info];
4098 }
2cb68ddf
JF
4099 }
4100 }
7f9c29fa 4101 } else goto error;
2cb68ddf
JF
4102
4103 [cache writeToFile:@Cache_ atomically:YES];
4104
4105 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4106 goto error;
4107 if (chmod(Cache_, info.st_mode) == -1)
4108 goto error;
4109
4110 if (false) error:
cb9c2100 4111 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
2cb68ddf
JF
4112 }
4113
5f54c108 4114 notify_post("com.apple.mobile.application_installed");
5f54c108 4115
b26eb97d 4116 [delegate_ setStatusBarShowsProgress:NO];
238b07ce
JF
4117}
4118
f464053e 4119- (void) _detachNewThreadData:(ProgressData *)data { _pooled
e057ec05
JF
4120 [[data target] performSelector:[data selector] withObject:[data object]];
4121 [data release];
a933cee2 4122
e057ec05 4123 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
a933cee2
JF
4124}
4125
e057ec05 4126- (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
965edd52
JF
4127 UINavigationItem *item = [navbar_ topItem];
4128 [item setTitle:title];
686e302f 4129
e057ec05
JF
4130 [status_ setText:nil];
4131 [output_ setText:@""];
4132 [progress_ setProgress:0];
a933cee2 4133
238b07ce
JF
4134 [close_ removeFromSuperview];
4135 [overlay_ addSubview:progress_];
4136 [overlay_ addSubview:status_];
4137
b26eb97d
JF
4138 [delegate_ setStatusBarShowsProgress:YES];
4139 running_ = YES;
4140
1eb0c554 4141 {
f464053e
JF
4142 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4143 MMap mmap(file, MMap::ReadOnly);
4144 SHA1Summation sha1;
4145 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4146 sandplate_ = sha1.Result();
4147 }
4148
bde2d79b
JF
4149 {
4150 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4151 MMap mmap(file, MMap::ReadOnly);
4152 SHA1Summation sha1;
4153 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4154 notifyconf_ = sha1.Result();
4155 }
4156
f464053e
JF
4157 {
4158 FileFd file(SpringBoard_, FileFd::ReadOnly);
1eb0c554
JF
4159 MMap mmap(file, MMap::ReadOnly);
4160 SHA1Summation sha1;
4161 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4162 springlist_ = sha1.Result();
4163 }
4164
e057ec05 4165 [transition_ transition:6 toView:overlay_];
a933cee2 4166
e057ec05
JF
4167 [NSThread
4168 detachNewThreadSelector:@selector(_detachNewThreadData:)
4169 toTarget:self
4170 withObject:[[ProgressData alloc]
4171 initWithSelector:selector
4172 target:target
4173 object:object
4174 ]
4175 ];
a933cee2
JF
4176}
4177
965edd52
JF
4178- (void) repairWithSelector:(SEL)selector {
4179 [self
4180 detachNewThreadSelector:selector
4181 toTarget:database_
4182 withObject:nil
6932575e 4183 title:CYLocalize("REPAIRING")
965edd52
JF
4184 ];
4185}
4186
7600bd69
JF
4187- (void) setConfigurationData:(NSString *)data {
4188 [self
4189 performSelectorOnMainThread:@selector(_setConfigurationData:)
4190 withObject:data
4191 waitUntilDone:YES
4192 ];
4193}
4194
238b07ce
JF
4195- (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4196 Package *package = id == nil ? nil : [database_ packageWithName:id];
4197
d210b85d 4198 UIActionSheet *sheet = [[[UIActionSheet alloc]
f464053e 4199 initWithTitle:(package == nil ? id : [package name])
6932575e 4200 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
238b07ce
JF
4201 defaultButtonIndex:0
4202 delegate:self
4203 context:@"error"
4204 ] autorelease];
4205
4206 [sheet setBodyText:error];
4207 [sheet popupAlertAnimated:YES];
a933cee2
JF
4208}
4209
e057ec05
JF
4210- (void) setProgressTitle:(NSString *)title {
4211 [self
4212 performSelectorOnMainThread:@selector(_setProgressTitle:)
4213 withObject:title
4214 waitUntilDone:YES
4215 ];
a933cee2
JF
4216}
4217
e057ec05
JF
4218- (void) setProgressPercent:(float)percent {
4219 [self
4220 performSelectorOnMainThread:@selector(_setProgressPercent:)
4221 withObject:[NSNumber numberWithFloat:percent]
4222 waitUntilDone:YES
4223 ];
a933cee2
JF
4224}
4225
87c76914 4226- (void) startProgress {
87c76914
JF
4227}
4228
e057ec05
JF
4229- (void) addProgressOutput:(NSString *)output {
4230 [self
4231 performSelectorOnMainThread:@selector(_addProgressOutput:)
4232 withObject:output
4233 waitUntilDone:YES
4234 ];
a933cee2
JF
4235}
4236
87c76914 4237- (bool) isCancelling:(size_t)received {
87c76914
JF
4238 return false;
4239}
4240
7600bd69 4241- (void) _setConfigurationData:(NSString *)data {
faf4eb4f
JF
4242 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4243
7600bd69
JF
4244 _assert(conffile_r(data));
4245
4246 NSString *ofile = conffile_r[1];
4247 //NSString *nfile = conffile_r[2];
4248
d210b85d 4249 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e 4250 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
7600bd69 4251 buttons:[NSArray arrayWithObjects:
6932575e
JF
4252 CYLocalize("KEEP_OLD_COPY"),
4253 CYLocalize("ACCEPT_NEW_COPY"),
4254 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
7600bd69
JF
4255 nil]
4256 defaultButtonIndex:0
4257 delegate:self
4258 context:@"conffile"
4259 ] autorelease];
4260
6932575e 4261 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
7600bd69
JF
4262 [sheet popupAlertAnimated:YES];
4263}
4264
e057ec05 4265- (void) _setProgressTitle:(NSString *)title {
907a35d6
JF
4266 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4267 for (size_t i(0), e([words count]); i != e; ++i) {
4268 NSString *word([words objectAtIndex:i]);
4269 if (Package *package = [database_ packageWithName:word])
4270 [words replaceObjectAtIndex:i withObject:[package name]];
4271 }
4272
4273 [status_ setText:[words componentsJoinedByString:@" "]];
686e302f 4274}
a933cee2 4275
e057ec05
JF
4276- (void) _setProgressPercent:(NSNumber *)percent {
4277 [progress_ setProgress:[percent floatValue]];
242bcc6d
JF
4278}
4279
e057ec05
JF
4280- (void) _addProgressOutput:(NSString *)output {
4281 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4282 CGSize size = [output_ contentSize];
4283 CGRect rect = {{0, size.height}, {size.width, 0}};
4284 [output_ scrollRectToVisible:rect animated:YES];
4285}
3957dd75 4286
b26eb97d 4287- (BOOL) isRunning {
5f54c108 4288 return running_;
b26eb97d
JF
4289}
4290
e057ec05
JF
4291@end
4292/* }}} */
3957dd75 4293
e057ec05 4294/* Package Cell {{{ */
d8d9a65c 4295@interface PackageCell : UITableCell {
5e563e79
JF
4296 UIImage *icon_;
4297 NSString *name_;
4298 NSString *description_;
d8d9a65c 4299 bool commercial_;
5e563e79 4300 NSString *source_;
cb9c2100 4301 UIImage *badge_;
d8d9a65c 4302 bool cached_;
3ff1504e 4303 Package *package_;
238b07ce 4304#ifdef USE_BADGES
3319715b 4305 UITextLabel *status_;
238b07ce 4306#endif
e057ec05 4307}
138ae18d 4308
e057ec05
JF
4309- (PackageCell *) init;
4310- (void) setPackage:(Package *)package;
1cb11c5f 4311
3319715b
JF
4312+ (int) heightForPackage:(Package *)package;
4313
e057ec05 4314@end
242bcc6d 4315
e057ec05
JF
4316@implementation PackageCell
4317
5e563e79
JF
4318- (void) clearPackage {
4319 if (icon_ != nil) {
4320 [icon_ release];
4321 icon_ = nil;
4322 }
4323
4324 if (name_ != nil) {
4325 [name_ release];
4326 name_ = nil;
4327 }
4328
4329 if (description_ != nil) {
4330 [description_ release];
4331 description_ = nil;
4332 }
4333
4334 if (source_ != nil) {
4335 [source_ release];
4336 source_ = nil;
4337 }
cb9c2100
JF
4338
4339 if (badge_ != nil) {
4340 [badge_ release];
4341 badge_ = nil;
4342 }
3ff1504e
JF
4343
4344 [package_ release];
4345 package_ = nil;
5e563e79
JF
4346}
4347
e057ec05 4348- (void) dealloc {
5e563e79 4349 [self clearPackage];
238b07ce 4350#ifdef USE_BADGES
3319715b 4351 [status_ release];
238b07ce 4352#endif
e057ec05 4353 [super dealloc];
686e302f 4354}
a933cee2 4355
e057ec05
JF
4356- (PackageCell *) init {
4357 if ((self = [super init]) != nil) {
238b07ce 4358#ifdef USE_BADGES
3319715b 4359 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
87c76914 4360 [status_ setBackgroundColor:[UIColor clearColor]];
3319715b 4361 [status_ setFont:small];
238b07ce 4362#endif
e057ec05 4363 } return self;
686e302f 4364}
a933cee2 4365
e057ec05 4366- (void) setPackage:(Package *)package {
d1494d2c 4367 [self clearPackage];
631a0a1e 4368 [package parse];
238b07ce 4369
e057ec05 4370 Source *source = [package source];
a933cee2 4371
dbe0f181 4372 icon_ = [[package icon] retain];
5e563e79 4373 name_ = [[package name] retain];
66abcbb0 4374 description_ = [[package shortDescription] retain];
d8d9a65c 4375 commercial_ = [package isCommercial];
e057ec05 4376
3ff1504e
JF
4377 package_ = [package retain];
4378
9e07091a
JF
4379 NSString *label = nil;
4380 bool trusted = false;
a933cee2 4381
e057ec05
JF
4382 if (source != nil) {
4383 label = [source label];
4384 trusted = [source trusted];
9e07091a 4385 } else if ([[package id] isEqualToString:@"firmware"])
6932575e 4386 label = CYLocalize("APPLE");
faf4eb4f 4387 else
6932575e 4388 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
a933cee2 4389
6932575e 4390 NSString *from(label);
9e07091a 4391
6932575e
JF
4392 NSString *section = [package simpleSection];
4393 if (section != nil && ![section isEqualToString:label]) {
4394 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4395 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4396 }
9e07091a 4397
3e3977a2 4398 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
5e563e79 4399 source_ = [from retain];
e057ec05 4400
cb9c2100
JF
4401 if (NSString *purpose = [package primaryPurpose])
4402 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4403 badge_ = [badge_ retain];
4404
238b07ce 4405#ifdef USE_BADGES
3319715b
JF
4406 if (NSString *mode = [package mode]) {
4407 [badge_ setImage:[UIImage applicationImageNamed:
6932575e 4408 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
3319715b
JF
4409 ]];
4410
6932575e 4411 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
f464053e 4412 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
3319715b
JF
4413 } else if ([package half]) {
4414 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
6932575e 4415 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
87c76914 4416 [status_ setColor:[UIColor redColor]];
3319715b
JF
4417 } else {
4418 [badge_ setImage:nil];
4419 [status_ setText:nil];
4420 }
238b07ce 4421#endif
d8d9a65c
JF
4422
4423 cached_ = false;
4424}
4425
4426- (void) drawRect:(CGRect)rect {
4427 if (!cached_) {
3ff1504e
JF
4428 UIColor *color;
4429
4430 if (NSString *mode = [package_ mode]) {
6932575e 4431 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
3ff1504e
JF
4432 color = remove ? RemovingColor_ : InstallingColor_;
4433 } else
4434 color = [UIColor whiteColor];
4435
4436 [self setBackgroundColor:color];
d8d9a65c
JF
4437 cached_ = true;
4438 }
4439
4440 [super drawRect:rect];
4441}
4442
4443- (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
3ff1504e 4444 if (fade == 0) {
d8d9a65c
JF
4445 CGContextRef context(UIGraphicsGetCurrentContext());
4446 [[self backgroundColor] set];
4447 CGRect back(rect);
4448 back.size.height -= 1;
4449 CGContextFillRect(context, back);
4450 }
4451
4452 [super drawBackgroundInRect:rect withFade:fade];
a933cee2
JF
4453}
4454
5e563e79 4455- (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
87c76914
JF
4456 if (icon_ != nil) {
4457 CGRect rect;
4458 rect.size = [icon_ size];
4459
4460 rect.size.width /= 2;
4461 rect.size.height /= 2;
4462
4463 rect.origin.x = 25 - rect.size.width / 2;
4464 rect.origin.y = 25 - rect.size.height / 2;
4465
4466 [icon_ drawInRect:rect];
4467 }
a933cee2 4468
cb9c2100
JF
4469 if (badge_ != nil) {
4470 CGSize size = [badge_ size];
4471
4472 [badge_ drawAtPoint:CGPointMake(
4473 36 - size.width / 2,
4474 36 - size.height / 2
4475 )];
4476 }
4477
5e563e79
JF
4478 if (selected)
4479 UISetColor(White_);
a933cee2 4480
5e563e79 4481 if (!selected)
d8d9a65c 4482 UISetColor(commercial_ ? Purple_ : Black_);
5e563e79
JF
4483 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4484 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
a933cee2 4485
5e563e79 4486 if (!selected)
d8d9a65c 4487 UISetColor(commercial_ ? Purplish_ : Gray_);
5e563e79 4488 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
a933cee2 4489
5e563e79 4490 [super drawContentInRect:rect selected:selected];
1cb11c5f
JF
4491}
4492
3ff1504e
JF
4493- (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4494 cached_ = false;
4495 [super setSelected:selected withFade:fade];
4496}
4497
3319715b 4498+ (int) heightForPackage:(Package *)package {
631a0a1e 4499 return 73;
3319715b
JF
4500}
4501
20dd7407
JF
4502@end
4503/* }}} */
e057ec05 4504/* Section Cell {{{ */
5e563e79 4505@interface SectionCell : UISimpleTableCell {
fa7bb92f 4506 NSString *section_;
5e563e79
JF
4507 NSString *name_;
4508 NSString *count_;
4509 UIImage *icon_;
d210b85d 4510 _UISwitchSlider *switch_;
fa7bb92f 4511 BOOL editing_;
686e302f 4512}
a933cee2 4513
e057ec05 4514- (id) init;
fa7bb92f 4515- (void) setSection:(Section *)section editing:(BOOL)editing;
e057ec05 4516
20dd7407
JF
4517@end
4518
e057ec05 4519@implementation SectionCell
20dd7407 4520
5e563e79
JF
4521- (void) clearSection {
4522 if (section_ != nil) {
fa7bb92f 4523 [section_ release];
5e563e79
JF
4524 section_ = nil;
4525 }
faf4eb4f 4526
5e563e79
JF
4527 if (name_ != nil) {
4528 [name_ release];
4529 name_ = nil;
4530 }
faf4eb4f 4531
5e563e79
JF
4532 if (count_ != nil) {
4533 [count_ release];
4534 count_ = nil;
4535 }
faf4eb4f
JF
4536}
4537
5e563e79
JF
4538- (void) dealloc {
4539 [self clearSection];
4540 [icon_ release];
4541 [switch_ release];
4542 [super dealloc];
faf4eb4f
JF
4543}
4544
e057ec05 4545- (id) init {
686e302f 4546 if ((self = [super init]) != nil) {
5e563e79 4547 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
e057ec05 4548
d210b85d 4549 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
fa7bb92f 4550 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
686e302f 4551 } return self;
a933cee2
JF
4552}
4553
fa7bb92f
JF
4554- (void) onSwitch:(id)sender {
4555 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4556 if (metadata == nil) {
4557 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4558 [Sections_ setObject:metadata forKey:section_];
4559 }
4560
4561 Changed_ = true;
4562 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4563}
4564
4565- (void) setSection:(Section *)section editing:(BOOL)editing {
4566 if (editing != editing_) {
4567 if (editing_)
4568 [switch_ removeFromSuperview];
4569 else
4570 [self addSubview:switch_];
4571 editing_ = editing;
4572 }
4573
5e563e79 4574 [self clearSection];
fa7bb92f 4575
e057ec05 4576 if (section == nil) {
6932575e 4577 name_ = [CYLocalize("ALL_PACKAGES") retain];
5e563e79 4578 count_ = nil;
e057ec05 4579 } else {
43b742af 4580 section_ = [section localized];
fa7bb92f
JF
4581 if (section_ != nil)
4582 section_ = [section_ retain];
6932575e 4583 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
5e563e79 4584 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
fa7bb92f
JF
4585
4586 if (editing_)
f159ecd4 4587 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
e057ec05 4588 }
5e563e79
JF
4589}
4590
4591- (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4592 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4593
4594 if (selected)
4595 UISetColor(White_);
4596
4597 if (!selected)
4598 UISetColor(Black_);
4599 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
fa7bb92f 4600
5e563e79
JF
4601 CGSize size = [count_ sizeWithFont:Font14_];
4602
4603 UISetColor(White_);
4604 if (count_ != nil)
cb9c2100 4605 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5e563e79
JF
4606
4607 [super drawContentInRect:rect selected:selected];
a933cee2
JF
4608}
4609
e057ec05
JF
4610@end
4611/* }}} */
a933cee2 4612
59efd93a
JF
4613/* File Table {{{ */
4614@interface FileTable : RVPage {
e057ec05 4615 _transient Database *database_;
59efd93a
JF
4616 Package *package_;
4617 NSString *name_;
4618 NSMutableArray *files_;
4619 UITable *list_;
4620}
a933cee2 4621
59efd93a
JF
4622- (id) initWithBook:(RVBook *)book database:(Database *)database;
4623- (void) setPackage:(Package *)package;
4624
4625@end
4626
4627@implementation FileTable
4628
4629- (void) dealloc {
4630 if (package_ != nil)
4631 [package_ release];
4632 if (name_ != nil)
4633 [name_ release];
4634 [files_ release];
4635 [list_ release];
4636 [super dealloc];
4637}
4638
4639- (int) numberOfRowsInTable:(UITable *)table {
4640 return files_ == nil ? 0 : [files_ count];
4641}
4642
4643- (float) table:(UITable *)table heightForRow:(int)row {
4644 return 24;
4645}
4646
4647- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4648 if (reusing == nil) {
4649 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
d210b85d 4650 UIFont *font = [UIFont systemFontOfSize:16];
59efd93a 4651 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
59efd93a
JF
4652 }
4653 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4654 return reusing;
e057ec05 4655}
a933cee2 4656
30edf48c 4657- (BOOL) table:(UITable *)table canSelectRow:(int)row {
59efd93a
JF
4658 return NO;
4659}
a933cee2 4660
59efd93a
JF
4661- (id) initWithBook:(RVBook *)book database:(Database *)database {
4662 if ((self = [super initWithBook:book]) != nil) {
4663 database_ = database;
a933cee2 4664
59efd93a 4665 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
20dd7407 4666
59efd93a
JF
4667 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4668 [self addSubview:list_];
4669
4670 UITableColumn *column = [[[UITableColumn alloc]
6932575e 4671 initWithTitle:CYLocalize("NAME")
59efd93a
JF
4672 identifier:@"name"
4673 width:[self frame].size.width
4674 ] autorelease];
4675
4676 [list_ setDataSource:self];
4677 [list_ setSeparatorStyle:1];
4678 [list_ addTableColumn:column];
4679 [list_ setDelegate:self];
4680 [list_ setReusesTableCells:YES];
4681 } return self;
4682}
4683
4684- (void) setPackage:(Package *)package {
4685 if (package_ != nil) {
4686 [package_ autorelease];
4687 package_ = nil;
4688 }
4689
4690 if (name_ != nil) {
4691 [name_ release];
4692 name_ = nil;
4693 }
4694
4695 [files_ removeAllObjects];
4696
4697 if (package != nil) {
4698 package_ = [package retain];
4699 name_ = [[package id] retain];
4700
f464053e
JF
4701 if (NSArray *files = [package files])
4702 [files_ addObjectsFromArray:files];
59efd93a 4703
fc19e583
JF
4704 if ([files_ count] != 0) {
4705 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4706 [files_ removeObjectAtIndex:0];
9e07091a 4707 [files_ sortUsingSelector:@selector(compareByPath:)];
2a987aa5
JF
4708
4709 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4710 [stack addObject:@"/"];
4711
4712 for (int i(0), e([files_ count]); i != e; ++i) {
4713 NSString *file = [files_ objectAtIndex:i];
4714 while (![file hasPrefix:[stack lastObject]])
4715 [stack removeLastObject];
4716 NSString *directory = [stack lastObject];
4717 [stack addObject:[file stringByAppendingString:@"/"]];
4718 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
9e07091a 4719 ([stack count] - 2) * 3, "",
2a987aa5
JF
4720 [file substringFromIndex:[directory length]]
4721 ]];
4722 }
59efd93a
JF
4723 }
4724 }
4725
4726 [list_ reloadData];
4727}
4728
4729- (void) resetViewAnimated:(BOOL)animated {
4730 [list_ resetViewAnimated:animated];
4731}
4732
4733- (void) reloadData {
4734 [self setPackage:[database_ packageWithName:name_]];
4735 [self reloadButtons];
4736}
4737
4738- (NSString *) title {
6932575e 4739 return CYLocalize("INSTALLED_FILES");
2a987aa5
JF
4740}
4741
4742- (NSString *) backButtonTitle {
6932575e 4743 return CYLocalize("FILES");
59efd93a 4744}
686e302f 4745
686e302f 4746@end
e057ec05 4747/* }}} */
e057ec05 4748/* Package View {{{ */
ad554f10 4749@interface PackageView : BrowserView {
dbe0f181 4750 _transient Database *database_;
e057ec05
JF
4751 Package *package_;
4752 NSString *name_;
d8d9a65c 4753 bool commercial_;
965edd52 4754 NSMutableArray *buttons_;
df5a7529
JF
4755}
4756
e057ec05
JF
4757- (id) initWithBook:(RVBook *)book database:(Database *)database;
4758- (void) setPackage:(Package *)package;
686e302f 4759
e057ec05 4760@end
686e302f 4761
e057ec05 4762@implementation PackageView
686e302f 4763
e057ec05 4764- (void) dealloc {
e057ec05
JF
4765 if (package_ != nil)
4766 [package_ release];
4767 if (name_ != nil)
4768 [name_ release];
965edd52 4769 [buttons_ release];
e057ec05
JF
4770 [super dealloc];
4771}
20dd7407 4772
d287ae9a 4773- (void) release {
6932575e
JF
4774 if ([self retainCount] == 1)
4775 [delegate_ setPackageView:self];
4776 [super release];
d287ae9a 4777}
6932575e
JF
4778
4779/* XXX: this is not safe at all... localization of /fail/ */
965edd52 4780- (void) _clickButtonWithName:(NSString *)name {
6932575e 4781 if ([name isEqualToString:CYLocalize("CLEAR")])
3ff1504e 4782 [delegate_ clearPackage:package_];
6932575e 4783 else if ([name isEqualToString:CYLocalize("INSTALL")])
965edd52 4784 [delegate_ installPackage:package_];
6932575e 4785 else if ([name isEqualToString:CYLocalize("REINSTALL")])
965edd52 4786 [delegate_ installPackage:package_];
6932575e 4787 else if ([name isEqualToString:CYLocalize("REMOVE")])
965edd52 4788 [delegate_ removePackage:package_];
6932575e 4789 else if ([name isEqualToString:CYLocalize("UPGRADE")])
965edd52
JF
4790 [delegate_ installPackage:package_];
4791 else _assert(false);
4792}
4793
d210b85d 4794- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
a5dd312c 4795 NSString *context([sheet context]);
965edd52 4796
a5dd312c
JF
4797 if ([context isEqualToString:@"modify"]) {
4798 int count = [buttons_ count];
4799 _assert(count != 0);
4800 _assert(button <= count + 1);
e057ec05 4801
a5dd312c
JF
4802 if (count != button - 1)
4803 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4804
4805 [sheet dismiss];
4806 } else
4807 [super alertSheet:sheet buttonClicked:button];
686e302f 4808}
4941f41d 4809
853d14d3 4810- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
853d14d3
JF
4811 return [super webView:sender didFinishLoadForFrame:frame];
4812}
4813
ad554f10 4814- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
cb9c2100 4815 [super webView:sender didClearWindowObject:window forFrame:frame];
6932575e 4816 [window setValue:package_ forKey:@"package"];
ad554f10
JF
4817}
4818
7b00c562 4819- (bool) _allowJavaScriptPanel {
d8d9a65c 4820 return commercial_;
7b00c562
JF
4821}
4822
907a35d6 4823#if !AlwaysReload
1ce016d4 4824- (void) __rightButtonClicked {
965edd52
JF
4825 int count = [buttons_ count];
4826 _assert(count != 0);
4941f41d 4827
965edd52
JF
4828 if (count == 1)
4829 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4830 else {
4831 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4832 [buttons addObjectsFromArray:buttons_];
6932575e 4833 [buttons addObject:CYLocalize("CANCEL")];
e057ec05 4834
d210b85d 4835 [delegate_ slideUp:[[[UIActionSheet alloc]
fc19e583 4836 initWithTitle:nil
e057ec05 4837 buttons:buttons
3ff1504e 4838 defaultButtonIndex:([buttons count] - 1)
e057ec05 4839 delegate:self
a5dd312c 4840 context:@"modify"
e057ec05
JF
4841 ] autorelease]];
4842 }
686e302f 4843}
1ce016d4
JF
4844
4845- (void) _rightButtonClicked {
4846 if (commercial_)
4847 [super _rightButtonClicked];
4848 else
4849 [self __rightButtonClicked];
4850}
907a35d6 4851#endif
4941f41d 4852
2bfeaf6f 4853- (id) _rightButtonTitle {
965edd52 4854 int count = [buttons_ count];
6932575e 4855 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
686e302f 4856}
4941f41d 4857
f464053e 4858- (NSString *) backButtonTitle {
e057ec05 4859 return @"Details";
a75f53e7
JF
4860}
4861
e057ec05 4862- (id) initWithBook:(RVBook *)book database:(Database *)database {
dbe0f181 4863 if ((self = [super initWithBook:book]) != nil) {
e057ec05 4864 database_ = database;
965edd52 4865 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
6932575e 4866 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
e057ec05 4867 } return self;
a75f53e7
JF
4868}
4869
e057ec05
JF
4870- (void) setPackage:(Package *)package {
4871 if (package_ != nil) {
4872 [package_ autorelease];
4873 package_ = nil;
4874 }
4875
4876 if (name_ != nil) {
4877 [name_ release];
4878 name_ = nil;
4879 }
4880
965edd52
JF
4881 [buttons_ removeAllObjects];
4882
e057ec05 4883 if (package != nil) {
631a0a1e
JF
4884 [package parse];
4885
e057ec05
JF
4886 package_ = [package retain];
4887 name_ = [[package id] retain];
d8d9a65c 4888 commercial_ = [package isCommercial];
e057ec05 4889
3ff1504e 4890 if ([package_ mode] != nil)
6932575e 4891 [buttons_ addObject:CYLocalize("CLEAR")];
965edd52 4892 if ([package_ source] == nil);
238b07ce 4893 else if ([package_ upgradableAndEssential:NO])
6932575e 4894 [buttons_ addObject:CYLocalize("UPGRADE")];
965edd52 4895 else if ([package_ installed] == nil)
6932575e 4896 [buttons_ addObject:CYLocalize("INSTALL")];
965edd52 4897 else
6932575e 4898 [buttons_ addObject:CYLocalize("REINSTALL")];
965edd52 4899 if ([package_ installed] != nil)
6932575e
JF
4900 [buttons_ addObject:CYLocalize("REMOVE")];
4901
4902 if (special_ != NULL) {
4903 CGRect frame([webview_ frame]);
4904 frame.size.width = 320;
4905 frame.size.height = 0;
4906 [webview_ setFrame:frame];
4907
4908 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4909
4910 WebThreadLock();
4911 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4912
4913 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4914
4915 [self setFinishHook:nil];
4916 [self setPopupHook:nil];
4917 WebThreadUnlock();
4918
bb9edf8b 4919 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
6932575e
JF
4920 [super callFunction:special_];
4921 }
e057ec05 4922 }
6932575e
JF
4923
4924 [self reloadButtons];
a75f53e7
JF
4925}
4926
d8d9a65c
JF
4927- (bool) isLoading {
4928 return commercial_ ? [super isLoading] : false;
a99d2808
JF
4929}
4930
e057ec05
JF
4931- (void) reloadData {
4932 [self setPackage:[database_ packageWithName:name_]];
b6ffa083
JF
4933}
4934
686e302f
JF
4935@end
4936/* }}} */
686e302f 4937/* Package Table {{{ */
e057ec05
JF
4938@interface PackageTable : RVPage {
4939 _transient Database *database_;
4940 NSString *title_;
e057ec05 4941 NSMutableArray *packages_;
686e302f 4942 NSMutableArray *sections_;
e057ec05 4943 UISectionList *list_;
a75f53e7
JF
4944}
4945
ce09fc27 4946- (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
686e302f
JF
4947
4948- (void) setDelegate:(id)delegate;
8993ad57 4949
e057ec05 4950- (void) reloadData;
8993ad57 4951- (void) resetCursor;
686e302f 4952
2a987aa5
JF
4953- (UISectionList *) list;
4954
59efd93a
JF
4955- (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4956
686e302f
JF
4957@end
4958
4959@implementation PackageTable
4960
4961- (void) dealloc {
e057ec05
JF
4962 [list_ setDataSource:nil];
4963
4964 [title_ release];
e057ec05 4965 [packages_ release];
686e302f 4966 [sections_ release];
e057ec05 4967 [list_ release];
686e302f 4968 [super dealloc];
b6ffa083
JF
4969}
4970
686e302f
JF
4971- (int) numberOfSectionsInSectionList:(UISectionList *)list {
4972 return [sections_ count];
4973}
4941f41d 4974
686e302f
JF
4975- (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4976 return [[sections_ objectAtIndex:section] name];
4977}
a75f53e7 4978
686e302f
JF
4979- (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4980 return [[sections_ objectAtIndex:section] row];
4941f41d
JF
4981}
4982
686e302f
JF
4983- (int) numberOfRowsInTable:(UITable *)table {
4984 return [packages_ count];
4985}
a75f53e7 4986
686e302f 4987- (float) table:(UITable *)table heightForRow:(int)row {
3319715b 4988 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
686e302f 4989}
a75f53e7 4990
686e302f
JF
4991- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4992 if (reusing == nil)
e057ec05 4993 reusing = [[[PackageCell alloc] init] autorelease];
686e302f
JF
4994 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4995 return reusing;
4996}
a75f53e7 4997
686e302f
JF
4998- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4999 return NO;
5000}
a75f53e7 5001
686e302f
JF
5002- (void) tableRowSelected:(NSNotification *)notification {
5003 int row = [[notification object] selectedRow];
e057ec05
JF
5004 if (row == INT_MAX)
5005 return;
5006
5007 Package *package = [packages_ objectAtIndex:row];
c3f582af 5008 package = [database_ packageWithName:[package id]];
6932575e 5009 PackageView *view([delegate_ packageView]);
e057ec05 5010 [view setPackage:package];
c3f582af 5011 [view setDelegate:delegate_];
e057ec05 5012 [book_ pushPage:view];
a75f53e7
JF
5013}
5014
ce09fc27 5015- (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
e057ec05
JF
5016 if ((self = [super initWithBook:book]) != nil) {
5017 database_ = database;
5018 title_ = [title retain];
e057ec05
JF
5019
5020 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
686e302f 5021 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
a75f53e7 5022
686e302f
JF
5023 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5024 [list_ setDataSource:self];
a75f53e7 5025
686e302f 5026 UITableColumn *column = [[[UITableColumn alloc]
6932575e 5027 initWithTitle:CYLocalize("NAME")
686e302f 5028 identifier:@"name"
e057ec05 5029 width:[self frame].size.width
686e302f
JF
5030 ] autorelease];
5031
5032 UITable *table = [list_ table];
5033 [table setSeparatorStyle:1];
5034 [table addTableColumn:column];
5035 [table setDelegate:self];
5036 [table setReusesTableCells:YES];
5037
5038 [self addSubview:list_];
87c76914
JF
5039
5040 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5041 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
686e302f 5042 } return self;
a75f53e7
JF
5043}
5044
5045- (void) setDelegate:(id)delegate {
4941f41d 5046 delegate_ = delegate;
686e302f
JF
5047}
5048
ce09fc27
JF
5049- (bool) hasPackage:(Package *)package {
5050 return true;
8993ad57
JF
5051}
5052
e057ec05
JF
5053- (void) reloadData {
5054 NSArray *packages = [database_ packages];
686e302f 5055
e057ec05 5056 [packages_ removeAllObjects];
686e302f
JF
5057 [sections_ removeAllObjects];
5058
3bddda52 5059 _profile(PackageTable$reloadData$Filter)
9fdd37d0 5060 for (Package *package in packages)
3bddda52
JF
5061 if ([self hasPackage:package])
5062 [packages_ addObject:package];
3bddda52 5063 _end
e057ec05 5064
686e302f
JF
5065 Section *section = nil;
5066
3bddda52 5067 _profile(PackageTable$reloadData$Section)
9fdd37d0
JF
5068 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5069 Package *package;
5070 unichar index;
5071
5072 _profile(PackageTable$reloadData$Section$Package)
5073 package = [packages_ objectAtIndex:offset];
5074 index = [package index];
5075 _end
686e302f 5076
3bddda52
JF
5077 if (section == nil || [section index] != index) {
5078 _profile(PackageTable$reloadData$Section$Allocate)
5079 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5080 _end
686e302f 5081
9fdd37d0
JF
5082 _profile(PackageTable$reloadData$Section$Add)
5083 [sections_ addObject:section];
5084 _end
3bddda52
JF
5085 }
5086
5087 [section addToCount];
5088 }
5089 _end
686e302f 5090
9fdd37d0
JF
5091 _profile(PackageTable$reloadData$List)
5092 [list_ reloadData];
5093 _end
686e302f
JF
5094}
5095
e057ec05
JF
5096- (NSString *) title {
5097 return title_;
686e302f
JF
5098}
5099
e057ec05
JF
5100- (void) resetViewAnimated:(BOOL)animated {
5101 [list_ resetViewAnimated:animated];
a75f53e7
JF
5102}
5103
8993ad57
JF
5104- (void) resetCursor {
5105 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5106}
5107
2a987aa5
JF
5108- (UISectionList *) list {
5109 return list_;
5110}
5111
59efd93a
JF
5112- (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5113 [list_ setShouldHideHeaderInShortLists:hide];
5114}
5115
ce09fc27
JF
5116@end
5117/* }}} */
5118/* Filtered Package Table {{{ */
5119@interface FilteredPackageTable : PackageTable {
5120 SEL filter_;
142bd2db 5121 IMP imp_;
ce09fc27
JF
5122 id object_;
5123}
5124
5125- (void) setObject:(id)object;
5126
5127- (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5128
5129@end
5130
5131@implementation FilteredPackageTable
5132
5133- (void) dealloc {
5134 if (object_ != nil)
5135 [object_ release];
5136 [super dealloc];
5137}
5138
5139- (void) setObject:(id)object {
5140 if (object_ != nil)
5141 [object_ release];
5142 if (object == nil)
5143 object_ = nil;
5144 else
5145 object_ = [object retain];
5146}
5147
5148- (bool) hasPackage:(Package *)package {
142bd2db
JF
5149 _profile(FilteredPackageTable$hasPackage)
5150 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5151 _end
ce09fc27
JF
5152}
5153
5154- (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5155 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5156 filter_ = filter;
5157 object_ = object == nil ? nil : [object retain];
6e673d99 5158
142bd2db
JF
5159 /* XXX: this is an unsafe optimization of doomy hell */
5160 Method method = class_getInstanceMethod([Package class], filter);
66abcbb0 5161 _assert(method != NULL);
142bd2db
JF
5162 imp_ = method_getImplementation(method);
5163 _assert(imp_ != NULL);
5164
6e673d99 5165 [self reloadData];
ce09fc27
JF
5166 } return self;
5167}
5168
a75f53e7 5169@end
686e302f 5170/* }}} */
a75f53e7 5171
faf4eb4f
JF
5172/* Add Source View {{{ */
5173@interface AddSourceView : RVPage {
5174 _transient Database *database_;
a75f53e7
JF
5175}
5176
faf4eb4f 5177- (id) initWithBook:(RVBook *)book database:(Database *)database;
686e302f 5178
faf4eb4f 5179@end
a75f53e7 5180
faf4eb4f 5181@implementation AddSourceView
a75f53e7 5182
faf4eb4f
JF
5183- (id) initWithBook:(RVBook *)book database:(Database *)database {
5184 if ((self = [super initWithBook:book]) != nil) {
5185 database_ = database;
5186 } return self;
e057ec05 5187}
a75f53e7 5188
faf4eb4f
JF
5189@end
5190/* }}} */
5191/* Source Cell {{{ */
5192@interface SourceCell : UITableCell {
5e563e79
JF
5193 UIImage *icon_;
5194 NSString *origin_;
5195 NSString *description_;
5196 NSString *label_;
686e302f
JF
5197}
5198
faf4eb4f 5199- (void) dealloc;
686e302f 5200
faf4eb4f 5201- (SourceCell *) initWithSource:(Source *)source;
686e302f 5202
faf4eb4f 5203@end
686e302f 5204
faf4eb4f 5205@implementation SourceCell
686e302f 5206
faf4eb4f 5207- (void) dealloc {
5e563e79 5208 [icon_ release];
faf4eb4f
JF
5209 [origin_ release];
5210 [description_ release];
5211 [label_ release];
5212 [super dealloc];
e057ec05 5213}
686e302f 5214
faf4eb4f
JF
5215- (SourceCell *) initWithSource:(Source *)source {
5216 if ((self = [super init]) != nil) {
5e563e79
JF
5217 if (icon_ == nil)
5218 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5219 if (icon_ == nil)
5220 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5221 icon_ = [icon_ retain];
5222
5223 origin_ = [[source name] retain];
5224 label_ = [[source uri] retain];
5225 description_ = [[source description] retain];
faf4eb4f 5226 } return self;
48c0461e
JF
5227}
5228
5e563e79
JF
5229- (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5230 if (icon_ != nil)
5231 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
faf4eb4f 5232
5e563e79
JF
5233 if (selected)
5234 UISetColor(White_);
faf4eb4f 5235
5e563e79
JF
5236 if (!selected)
5237 UISetColor(Black_);
5238 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
faf4eb4f 5239
5e563e79
JF
5240 if (!selected)
5241 UISetColor(Blue_);
5242 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
faf4eb4f 5243
5e563e79
JF
5244 if (!selected)
5245 UISetColor(Gray_);
5246 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
faf4eb4f 5247
5e563e79 5248 [super drawContentInRect:rect selected:selected];
faf4eb4f
JF
5249}
5250
5251@end
5252/* }}} */
5253/* Source Table {{{ */
5254@interface SourceTable : RVPage {
5255 _transient Database *database_;
5256 UISectionList *list_;
5257 NSMutableArray *sources_;
d210b85d 5258 UIActionSheet *alert_;
faf4eb4f
JF
5259 int offset_;
5260
5261 NSString *href_;
5262 UIProgressHUD *hud_;
5263 NSError *error_;
5264
5265 //NSURLConnection *installer_;
5266 NSURLConnection *trivial_bz2_;
5267 NSURLConnection *trivial_gz_;
5268 //NSURLConnection *automatic_;
5269
5270 BOOL trivial_;
5271}
5272
5273- (id) initWithBook:(RVBook *)book database:(Database *)database;
5274
5275@end
5276
5277@implementation SourceTable
5278
5279- (void) _deallocConnection:(NSURLConnection *)connection {
5280 if (connection != nil) {
5281 [connection cancel];
5282 //[connection setDelegate:nil];
5283 [connection release];
5284 }
5285}
5286
5287- (void) dealloc {
5288 [[list_ table] setDelegate:nil];
5289 [list_ setDataSource:nil];
5290
5291 if (href_ != nil)
5292 [href_ release];
5293 if (hud_ != nil)
5294 [hud_ release];
5295 if (error_ != nil)
5296 [error_ release];
5297
5298 //[self _deallocConnection:installer_];
5299 [self _deallocConnection:trivial_gz_];
5300 [self _deallocConnection:trivial_bz2_];
5301 //[self _deallocConnection:automatic_];
5302
5303 [sources_ release];
5304 [list_ release];
5305 [super dealloc];
5306}
5307
5308- (int) numberOfSectionsInSectionList:(UISectionList *)list {
5309 return offset_ == 0 ? 1 : 2;
5310}
5311
5312- (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5313 switch (section + (offset_ == 0 ? 1 : 0)) {
6932575e
JF
5314 case 0: return CYLocalize("ENTERED_BY_USER");
5315 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
faf4eb4f
JF
5316
5317 default:
5318 _assert(false);
5319 return nil;
5320 }
5321}
5322
5323- (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5324 switch (section + (offset_ == 0 ? 1 : 0)) {
5325 case 0: return 0;
5326 case 1: return offset_;
5327
5328 default:
5329 _assert(false);
5330 return -1;
5331 }
5332}
5333
5334- (int) numberOfRowsInTable:(UITable *)table {
5335 return [sources_ count];
5336}
5337
5338- (float) table:(UITable *)table heightForRow:(int)row {
5339 Source *source = [sources_ objectAtIndex:row];
5e563e79 5340 return [source description] == nil ? 56 : 73;
faf4eb4f
JF
5341}
5342
5343- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5344 Source *source = [sources_ objectAtIndex:row];
5345 // XXX: weird warning, stupid selectors ;P
5346 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5347}
5348
5349- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5350 return YES;
5351}
5352
5353- (BOOL) table:(UITable *)table canSelectRow:(int)row {
5354 return YES;
5355}
5356
5357- (void) tableRowSelected:(NSNotification*)notification {
5358 UITable *table([list_ table]);
5359 int row([table selectedRow]);
5360 if (row == INT_MAX)
5361 return;
5362
5363 Source *source = [sources_ objectAtIndex:row];
5364
ce09fc27 5365 PackageTable *packages = [[[FilteredPackageTable alloc]
faf4eb4f
JF
5366 initWithBook:book_
5367 database:database_
5368 title:[source label]
5369 filter:@selector(isVisibleInSource:)
5370 with:source
5371 ] autorelease];
5372
5373 [packages setDelegate:delegate_];
5374
5375 [book_ pushPage:packages];
5376}
5377
5378- (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5379 Source *source = [sources_ objectAtIndex:row];
5380 return [source record] != nil;
5381}
5382
5383- (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5384 [[list_ table] setDeleteConfirmationRow:row];
5385}
5386
5387- (void) table:(UITable *)table deleteRow:(int)row {
5388 Source *source = [sources_ objectAtIndex:row];
5389 [Sources_ removeObjectForKey:[source key]];
5390 [delegate_ syncData];
5391}
5392
b4dff19a
JF
5393- (void) complete {
5394 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5395 @"deb", @"Type",
5396 href_, @"URI",
5397 @"./", @"Distribution",
5398 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5399
5400 [delegate_ syncData];
5401}
5402
5403- (NSString *) getWarning {
7b00c562
JF
5404 NSString *href(href_);
5405 NSRange colon([href rangeOfString:@"://"]);
5406 if (colon.location != NSNotFound)
5407 href = [href substringFromIndex:(colon.location + 3)];
5408 href = [href stringByAddingPercentEscapes];
b4dff19a
JF
5409 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5410 href = [href stringByCachingURLWithCurrentCDN];
5411
5412 NSURL *url([NSURL URLWithString:href]);
5413
5414 NSStringEncoding encoding;
5415 NSError *error(nil);
5416
5417 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5418 return [warning length] == 0 ? nil : warning;
5419 return nil;
5420}
5421
faf4eb4f
JF
5422- (void) _endConnection:(NSURLConnection *)connection {
5423 NSURLConnection **field = NULL;
5424 if (connection == trivial_bz2_)
5425 field = &trivial_bz2_;
5426 else if (connection == trivial_gz_)
5427 field = &trivial_gz_;
5428 _assert(field != NULL);
5429 [connection release];
5430 *field = nil;
5431
5432 if (
5433 trivial_bz2_ == nil &&
5434 trivial_gz_ == nil
5435 ) {
7b00c562 5436 bool defer(false);
faf4eb4f
JF
5437
5438 if (trivial_) {
b4dff19a 5439 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7b00c562
JF
5440 defer = true;
5441
b4dff19a 5442 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e
JF
5443 initWithTitle:CYLocalize("SOURCE_WARNING")
5444 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
b4dff19a
JF
5445 defaultButtonIndex:0
5446 delegate:self
5447 context:@"warning"
5448 ] autorelease];
5449
5450 [sheet setNumberOfRows:1];
5451
5452 [sheet setBodyText:warning];
5453 [sheet popupAlertAnimated:YES];
5454 } else
5455 [self complete];
faf4eb4f 5456 } else if (error_ != nil) {
d210b85d 5457 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e
JF
5458 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5459 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
faf4eb4f
JF
5460 defaultButtonIndex:0
5461 delegate:self
5462 context:@"urlerror"
5463 ] autorelease];
5464
5465 [sheet setBodyText:[error_ localizedDescription]];
5466 [sheet popupAlertAnimated:YES];
5467 } else {
d210b85d 5468 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e
JF
5469 initWithTitle:CYLocalize("NOT_REPOSITORY")
5470 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
faf4eb4f
JF
5471 defaultButtonIndex:0
5472 delegate:self
5473 context:@"trivial"
5474 ] autorelease];
5475
6932575e 5476 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
faf4eb4f
JF
5477 [sheet popupAlertAnimated:YES];
5478 }
5479
7b00c562
JF
5480 [delegate_ setStatusBarShowsProgress:NO];
5481 [delegate_ removeProgressHUD:hud_];
5482
5483 [hud_ autorelease];
5484 hud_ = nil;
5485
5486 if (!defer) {
5487 [href_ release];
5488 href_ = nil;
5489 }
faf4eb4f
JF
5490
5491 if (error_ != nil) {
5492 [error_ release];
5493 error_ = nil;
5494 }
5495 }
5496}
5497
5498- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5499 switch ([response statusCode]) {
5500 case 200:
5501 trivial_ = YES;
5502 }
5503}
5504
5505- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
cb9c2100 5506 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
faf4eb4f
JF
5507 if (error_ != nil)
5508 error_ = [error retain];
5509 [self _endConnection:connection];
5510}
5511
5512- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5513 [self _endConnection:connection];
5514}
5515
5516- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5517 NSMutableURLRequest *request = [NSMutableURLRequest
5518 requestWithURL:[NSURL URLWithString:href]
5519 cachePolicy:NSURLRequestUseProtocolCachePolicy
5520 timeoutInterval:20.0
5521 ];
5522
5523 [request setHTTPMethod:method];
5524
6932575e
JF
5525 if (Machine_ != NULL)
5526 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5527 if (UniqueID_ != nil)
5528 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5529
5530 if (Role_ != nil)
5531 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5532
faf4eb4f
JF
5533 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5534}
5535
d210b85d 5536- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
a5dd312c
JF
5537 NSString *context([sheet context]);
5538
5539 if ([context isEqualToString:@"source"]) {
faf4eb4f
JF
5540 switch (button) {
5541 case 1: {
5542 NSString *href = [[sheet textField] text];
5543
5544 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5545
5546 if (![href hasSuffix:@"/"])
5547 href_ = [href stringByAppendingString:@"/"];
5548 else
5549 href_ = href;
5550 href_ = [href_ retain];
5551
5552 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5553 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5554 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5555
5556 trivial_ = false;
5557
7398a389 5558 hud_ = [[delegate_ addProgressHUD] retain];
6932575e 5559 [hud_ setText:CYLocalize("VERIFYING_URL")];
faf4eb4f
JF
5560 } break;
5561
5562 case 2:
5563 break;
5564
5565 default:
5566 _assert(false);
5567 }
5568
a5dd312c 5569 [sheet dismiss];
b7adefda
JF
5570 } else if ([context isEqualToString:@"trivial"])
5571 [sheet dismiss];
5572 else if ([context isEqualToString:@"urlerror"])
5573 [sheet dismiss];
b4dff19a
JF
5574 else if ([context isEqualToString:@"warning"]) {
5575 switch (button) {
5576 case 1:
5577 [self complete];
5578 break;
5579
5580 case 2:
5581 break;
5582
5583 default:
5584 _assert(false);
5585 }
5586
7b00c562
JF
5587 [href_ release];
5588 href_ = nil;
5589
b4dff19a
JF
5590 [sheet dismiss];
5591 }
faf4eb4f
JF
5592}
5593
5594- (id) initWithBook:(RVBook *)book database:(Database *)database {
5595 if ((self = [super initWithBook:book]) != nil) {
5596 database_ = database;
5597 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5598
5599 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5600 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5601 [list_ setShouldHideHeaderInShortLists:NO];
5602
5603 [self addSubview:list_];
5604 [list_ setDataSource:self];
5605
5606 UITableColumn *column = [[UITableColumn alloc]
6932575e 5607 initWithTitle:CYLocalize("NAME")
faf4eb4f
JF
5608 identifier:@"name"
5609 width:[self frame].size.width
5610 ];
5611
5612 UITable *table = [list_ table];
5613 [table setSeparatorStyle:1];
5614 [table addTableColumn:column];
5615 [table setDelegate:self];
5616
5617 [self reloadData];
87c76914
JF
5618
5619 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5620 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
faf4eb4f
JF
5621 } return self;
5622}
5623
5624- (void) reloadData {
5625 pkgSourceList list;
5626 _assert(list.ReadMainList());
5627
5628 [sources_ removeAllObjects];
5629 [sources_ addObjectsFromArray:[database_ sources]];
f159ecd4 5630 _trace();
faf4eb4f 5631 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
f159ecd4 5632 _trace();
faf4eb4f
JF
5633
5634 int count = [sources_ count];
5635 for (offset_ = 0; offset_ != count; ++offset_) {
5636 Source *source = [sources_ objectAtIndex:offset_];
5637 if ([source record] == nil)
5638 break;
5639 }
5640
5641 [list_ reloadData];
5642}
5643
5644- (void) resetViewAnimated:(BOOL)animated {
5645 [list_ resetViewAnimated:animated];
5646}
5647
5648- (void) _leftButtonClicked {
5649 /*[book_ pushPage:[[[AddSourceView alloc]
5650 initWithBook:book_
5651 database:database_
5652 ] autorelease]];*/
5653
d210b85d 5654 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e
JF
5655 initWithTitle:CYLocalize("ENTER_APT_URL")
5656 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
faf4eb4f
JF
5657 defaultButtonIndex:0
5658 delegate:self
5659 context:@"source"
5660 ] autorelease];
5661
a5dd312c
JF
5662 [sheet setNumberOfRows:1];
5663
faf4eb4f
JF
5664 [sheet addTextFieldWithValue:@"http://" label:@""];
5665
d210b85d 5666 UITextInputTraits *traits = [[sheet textField] textInputTraits];
b7adefda
JF
5667 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5668 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
a5dd312c 5669 [traits setKeyboardType:UIKeyboardTypeURL];
b7adefda
JF
5670 // XXX: UIReturnKeyDone
5671 [traits setReturnKeyType:UIReturnKeyNext];
faf4eb4f
JF
5672
5673 [sheet popupAlertAnimated:YES];
5674}
5675
5676- (void) _rightButtonClicked {
5677 UITable *table = [list_ table];
5678 BOOL editing = [table isRowDeletionEnabled];
5679 [table enableRowDeletion:!editing animated:YES];
5680 [book_ reloadButtonsForPage:self];
5681}
5682
5683- (NSString *) title {
6932575e 5684 return CYLocalize("SOURCES");
faf4eb4f
JF
5685}
5686
faf4eb4f 5687- (NSString *) leftButtonTitle {
6932575e 5688 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
faf4eb4f
JF
5689}
5690
2bfeaf6f 5691- (id) rightButtonTitle {
6932575e 5692 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
faf4eb4f
JF
5693}
5694
87c76914
JF
5695- (UINavigationButtonStyle) rightButtonStyle {
5696 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
faf4eb4f
JF
5697}
5698
5699@end
5700/* }}} */
5701
5702/* Installed View {{{ */
5703@interface InstalledView : RVPage {
5704 _transient Database *database_;
ce09fc27 5705 FilteredPackageTable *packages_;
5e563e79 5706 BOOL expert_;
faf4eb4f
JF
5707}
5708
5709- (id) initWithBook:(RVBook *)book database:(Database *)database;
5710
5711@end
5712
5713@implementation InstalledView
5714
5715- (void) dealloc {
5716 [packages_ release];
5717 [super dealloc];
5718}
5719
5720- (id) initWithBook:(RVBook *)book database:(Database *)database {
5721 if ((self = [super initWithBook:book]) != nil) {
5722 database_ = database;
5723
ce09fc27 5724 packages_ = [[FilteredPackageTable alloc]
faf4eb4f
JF
5725 initWithBook:book
5726 database:database
5727 title:nil
4fdee079 5728 filter:@selector(isInstalledAndVisible:)
5e563e79 5729 with:[NSNumber numberWithBool:YES]
faf4eb4f
JF
5730 ];
5731
5732 [self addSubview:packages_];
87c76914
JF
5733
5734 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5735 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
faf4eb4f
JF
5736 } return self;
5737}
5738
5739- (void) resetViewAnimated:(BOOL)animated {
5740 [packages_ resetViewAnimated:animated];
5741}
5742
5743- (void) reloadData {
5744 [packages_ reloadData];
5745}
5746
5e563e79
JF
5747- (void) _rightButtonClicked {
5748 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5749 [packages_ reloadData];
5750 expert_ = !expert_;
5751 [book_ reloadButtonsForPage:self];
5752}
5753
faf4eb4f 5754- (NSString *) title {
6932575e 5755 return CYLocalize("INSTALLED");
faf4eb4f
JF
5756}
5757
5758- (NSString *) backButtonTitle {
6932575e 5759 return CYLocalize("PACKAGES");
faf4eb4f
JF
5760}
5761
2bfeaf6f 5762- (id) rightButtonTitle {
6932575e 5763 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5e563e79
JF
5764}
5765
87c76914
JF
5766- (UINavigationButtonStyle) rightButtonStyle {
5767 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5e563e79
JF
5768}
5769
faf4eb4f
JF
5770- (void) setDelegate:(id)delegate {
5771 [super setDelegate:delegate];
5772 [packages_ setDelegate:delegate];
5773}
5774
5775@end
5776/* }}} */
5777
1bb0d66c 5778/* Home View {{{ */
faf4eb4f
JF
5779@interface HomeView : BrowserView {
5780}
5781
5782@end
5783
5784@implementation HomeView
5785
d210b85d 5786- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
a5dd312c
JF
5787 NSString *context([sheet context]);
5788
5789 if ([context isEqualToString:@"about"])
5790 [sheet dismiss];
5791 else
5792 [super alertSheet:sheet buttonClicked:button];
faf4eb4f
JF
5793}
5794
5795- (void) _leftButtonClicked {
d210b85d 5796 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e
JF
5797 initWithTitle:CYLocalize("ABOUT_CYDIA")
5798 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
faf4eb4f
JF
5799 defaultButtonIndex:0
5800 delegate:self
5801 context:@"about"
5802 ] autorelease];
5803
5804 [sheet setBodyText:
b456f1c9 5805 @"Copyright (C) 2008-2009\n"
faf4eb4f
JF
5806 "Jay Freeman (saurik)\n"
5807 "saurik@saurik.com\n"
5808 "http://www.saurik.com/\n"
5809 "\n"
5810 "The Okori Group\n"
5811 "http://www.theokorigroup.com/\n"
5812 "\n"
5813 "College of Creative Studies,\n"
5814 "University of California,\n"
5815 "Santa Barbara\n"
5816 "http://www.ccs.ucsb.edu/"
5817 ];
5818
5819 [sheet popupAlertAnimated:YES];
5820}
5821
5822- (NSString *) leftButtonTitle {
6932575e 5823 return CYLocalize("ABOUT");
faf4eb4f
JF
5824}
5825
5826@end
1bb0d66c
JF
5827/* }}} */
5828/* Manage View {{{ */
faf4eb4f
JF
5829@interface ManageView : BrowserView {
5830}
5831
5832@end
5833
5834@implementation ManageView
5835
5836- (NSString *) title {
6932575e 5837 return CYLocalize("MANAGE");
faf4eb4f
JF
5838}
5839
5840- (void) _leftButtonClicked {
5841 [delegate_ askForSettings];
5842}
5843
5844- (NSString *) leftButtonTitle {
6932575e 5845 return CYLocalize("SETTINGS");
faf4eb4f
JF
5846}
5847
541a556a 5848#if !AlwaysReload
2bfeaf6f 5849- (id) _rightButtonTitle {
6932575e 5850 return Queuing_ ? CYLocalize("QUEUE") : nil;
3ff1504e
JF
5851}
5852
5853- (UINavigationButtonStyle) rightButtonStyle {
5854 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5855}
5856
5857- (void) _rightButtonClicked {
5858 [delegate_ queue];
faf4eb4f 5859}
541a556a 5860#endif
faf4eb4f 5861
d8d9a65c 5862- (bool) isLoading {
a99d2808
JF
5863 return false;
5864}
5865
faf4eb4f 5866@end
1bb0d66c 5867/* }}} */
faf4eb4f 5868
bde2d79b 5869#include <BrowserView.m>
30d83bfe 5870
f159ecd4 5871/* Cydia Book {{{ */
faf4eb4f
JF
5872@interface CYBook : RVBook <
5873 ProgressDelegate
5874> {
5875 _transient Database *database_;
87c76914 5876 UINavigationBar *overlay_;
f464053e 5877 UINavigationBar *underlay_;
faf4eb4f
JF
5878 UIProgressIndicator *indicator_;
5879 UITextLabel *prompt_;
5880 UIProgressBar *progress_;
87c76914 5881 UINavigationButton *cancel_;
faf4eb4f 5882 bool updating_;
30d83bfe
JF
5883}
5884
faf4eb4f
JF
5885- (id) initWithFrame:(CGRect)frame database:(Database *)database;
5886- (void) update;
5887- (BOOL) updating;
30d83bfe
JF
5888
5889@end
30d83bfe 5890
f159ecd4 5891@implementation CYBook
a75f53e7 5892
4941f41d 5893- (void) dealloc {
f159ecd4
JF
5894 [overlay_ release];
5895 [indicator_ release];
5896 [prompt_ release];
5897 [progress_ release];
5898 [cancel_ release];
4941f41d
JF
5899 [super dealloc];
5900}
5901
f159ecd4 5902- (NSString *) getTitleForPage:(RVPage *)page {
6932575e 5903 return [super getTitleForPage:page];
686e302f 5904}
a75f53e7 5905
f159ecd4
JF
5906- (BOOL) updating {
5907 return updating_;
fa7bb92f
JF
5908}
5909
f159ecd4
JF
5910- (void) update {
5911 [UIView beginAnimations:nil context:NULL];
a75f53e7 5912
f159ecd4
JF
5913 CGRect ovrframe = [overlay_ frame];
5914 ovrframe.origin.y = 0;
5915 [overlay_ setFrame:ovrframe];
a75f53e7 5916
f159ecd4
JF
5917 CGRect barframe = [navbar_ frame];
5918 barframe.origin.y += ovrframe.size.height;
5919 [navbar_ setFrame:barframe];
a75f53e7 5920
f159ecd4
JF
5921 CGRect trnframe = [transition_ frame];
5922 trnframe.origin.y += ovrframe.size.height;
5923 trnframe.size.height -= ovrframe.size.height;
5924 [transition_ setFrame:trnframe];
965edd52 5925
f159ecd4 5926 [UIView endAnimations];
4941f41d 5927
f159ecd4 5928 [indicator_ startAnimation];
6932575e 5929 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
f159ecd4 5930 [progress_ setProgress:0];
4941f41d 5931
f159ecd4
JF
5932 updating_ = true;
5933 [overlay_ addSubview:cancel_];
4941f41d 5934
f159ecd4
JF
5935 [NSThread
5936 detachNewThreadSelector:@selector(_update)
5937 toTarget:self
5938 withObject:nil
5939 ];
686e302f 5940}
4941f41d 5941
f159ecd4
JF
5942- (void) _update_ {
5943 updating_ = false;
e057ec05 5944
f159ecd4 5945 [indicator_ stopAnimation];
4941f41d 5946
f159ecd4 5947 [UIView beginAnimations:nil context:NULL];
fa7bb92f 5948
f159ecd4
JF
5949 CGRect ovrframe = [overlay_ frame];
5950 ovrframe.origin.y = -ovrframe.size.height;
5951 [overlay_ setFrame:ovrframe];
a75f53e7 5952
f159ecd4
JF
5953 CGRect barframe = [navbar_ frame];
5954 barframe.origin.y -= ovrframe.size.height;
5955 [navbar_ setFrame:barframe];
a75f53e7 5956
f159ecd4
JF
5957 CGRect trnframe = [transition_ frame];
5958 trnframe.origin.y -= ovrframe.size.height;
5959 trnframe.size.height += ovrframe.size.height;
5960 [transition_ setFrame:trnframe];
4941f41d 5961
f159ecd4 5962 [UIView commitAnimations];
87c76914 5963
f159ecd4 5964 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
4941f41d
JF
5965}
5966
f159ecd4
JF
5967- (id) initWithFrame:(CGRect)frame database:(Database *)database {
5968 if ((self = [super initWithFrame:frame]) != nil) {
5969 database_ = database;
e057ec05 5970
f159ecd4
JF
5971 CGRect ovrrect = [navbar_ bounds];
5972 ovrrect.size.height = [UINavigationBar defaultSize].height;
5973 ovrrect.origin.y = -ovrrect.size.height;
fa7bb92f 5974
f159ecd4
JF
5975 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5976 [self addSubview:overlay_];
a75f53e7 5977
f159ecd4
JF
5978 ovrrect.origin.y = frame.size.height;
5979 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5980 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5981 [self addSubview:underlay_];
fa7bb92f 5982
f159ecd4
JF
5983 [overlay_ setBarStyle:1];
5984 [underlay_ setBarStyle:1];
5985
5986 int barstyle = [overlay_ _barStyle:NO];
5987 bool ugly = barstyle == 0;
5988
5989 UIProgressIndicatorStyle style = ugly ?
5990 UIProgressIndicatorStyleMediumBrown :
5991 UIProgressIndicatorStyleMediumWhite;
5992
5993 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5994 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5995 CGRect indrect = {{indoffset, indoffset}, indsize};
5996
5997 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5998 [indicator_ setStyle:style];
5999 [overlay_ addSubview:indicator_];
6000
6001 CGSize prmsize = {215, indsize.height + 4};
6002
6003 CGRect prmrect = {{
6004 indoffset * 2 + indsize.width,
6005#ifdef __OBJC2__
6006 -1 +
6007#endif
6008 unsigned(ovrrect.size.height - prmsize.height) / 2
6009 }, prmsize};
6010
6011 UIFont *font = [UIFont systemFontOfSize:15];
6012
6013 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6014
6015 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6016 [prompt_ setBackgroundColor:[UIColor clearColor]];
6017 [prompt_ setFont:font];
6018
6019 [overlay_ addSubview:prompt_];
6020
6021 CGSize prgsize = {75, 100};
6022
6023 CGRect prgrect = {{
6024 ovrrect.size.width - prgsize.width - 10,
6025 (ovrrect.size.height - prgsize.height) / 2
6026 } , prgsize};
6027
6028 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6029 [progress_ setStyle:0];
6030 [overlay_ addSubview:progress_];
6031
6932575e 6032 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
f159ecd4
JF
6033 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6034
6035 CGRect frame = [cancel_ frame];
f159ecd4
JF
6036 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6037 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6038 [cancel_ setFrame:frame];
6039
6040 [cancel_ setBarStyle:barstyle];
6041 } return self;
6042}
6043
6044- (void) _onCancel {
6045 updating_ = false;
6046 [cancel_ removeFromSuperview];
6047}
6048
6049- (void) _update { _pooled
6050 Status status;
6051 status.setDelegate(self);
6052
6053 [database_ updateWithStatus:status];
6054
6055 [self
6056 performSelectorOnMainThread:@selector(_update_)
6057 withObject:nil
6058 waitUntilDone:NO
6059 ];
6060}
6061
6062- (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
43b742af 6063 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
f159ecd4
JF
6064}
6065
6066- (void) setProgressTitle:(NSString *)title {
6067 [self
6068 performSelectorOnMainThread:@selector(_setProgressTitle:)
6069 withObject:title
6070 waitUntilDone:YES
6071 ];
6072}
6073
6074- (void) setProgressPercent:(float)percent {
6075 [self
6076 performSelectorOnMainThread:@selector(_setProgressPercent:)
6077 withObject:[NSNumber numberWithFloat:percent]
6078 waitUntilDone:YES
6079 ];
6080}
6081
6082- (void) startProgress {
6083}
6084
6085- (void) addProgressOutput:(NSString *)output {
6086 [self
6087 performSelectorOnMainThread:@selector(_addProgressOutput:)
6088 withObject:output
6089 waitUntilDone:YES
6090 ];
6091}
6092
6093- (bool) isCancelling:(size_t)received {
f159ecd4
JF
6094 return !updating_;
6095}
6096
6097- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6098 [sheet dismiss];
6099}
6100
6101- (void) _setProgressTitle:(NSString *)title {
6102 [prompt_ setText:title];
6103}
6104
6105- (void) _setProgressPercent:(NSNumber *)percent {
6106 [progress_ setProgress:[percent floatValue]];
6107}
6108
6109- (void) _addProgressOutput:(NSString *)output {
6110}
6111
6112@end
6113/* }}} */
6114/* Cydia:// Protocol {{{ */
6115@interface CydiaURLProtocol : NSURLProtocol {
6116}
6117
6118@end
6119
6120@implementation CydiaURLProtocol
6121
6122+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
6123 NSURL *url([request URL]);
6124 if (url == nil)
6125 return NO;
6126 NSString *scheme([[url scheme] lowercaseString]);
6127 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6128 return NO;
6129 return YES;
6130}
6131
6132+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6133 return request;
6134}
6135
a99d2808
JF
6136- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6137 id<NSURLProtocolClient> client([self client]);
6e673d99
JF
6138 if (icon == nil)
6139 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6140 else {
6141 NSData *data(UIImagePNGRepresentation(icon));
a99d2808 6142
6e673d99
JF
6143 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6144 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6145 [client URLProtocol:self didLoadData:data];
6146 [client URLProtocolDidFinishLoading:self];
6147 }
a99d2808
JF
6148}
6149
f159ecd4
JF
6150- (void) startLoading {
6151 id<NSURLProtocolClient> client([self client]);
6152 NSURLRequest *request([self request]);
6153
6154 NSURL *url([request URL]);
6155 NSString *href([url absoluteString]);
6156
6157 NSString *path([href substringFromIndex:8]);
6158 NSRange slash([path rangeOfString:@"/"]);
6159
6160 NSString *command;
6161 if (slash.location == NSNotFound) {
6162 command = path;
6163 path = nil;
6164 } else {
6165 command = [path substringToIndex:slash.location];
6166 path = [path substringFromIndex:(slash.location + 1)];
6167 }
6168
6169 Database *database([Database sharedInstance]);
6170
6171 if ([command isEqualToString:@"package-icon"]) {
6172 if (path == nil)
6173 goto fail;
6b4b3bee 6174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
f159ecd4
JF
6175 Package *package([database packageWithName:path]);
6176 if (package == nil)
6177 goto fail;
6b4b3bee 6178 UIImage *icon([package icon]);
a99d2808 6179 [self _returnPNGWithImage:icon forRequest:request];
18159e09
JF
6180 } else if ([command isEqualToString:@"source-icon"]) {
6181 if (path == nil)
6182 goto fail;
6183 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6184 NSString *source(Simplify(path));
18159e09
JF
6185 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6186 if (icon == nil)
6187 icon = [UIImage applicationImageNamed:@"unknown.png"];
a99d2808
JF
6188 [self _returnPNGWithImage:icon forRequest:request];
6189 } else if ([command isEqualToString:@"uikit-image"]) {
6190 if (path == nil)
6191 goto fail;
6192 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6193 UIImage *icon(_UIImageWithName(path));
6194 [self _returnPNGWithImage:icon forRequest:request];
6b4b3bee
JF
6195 } else if ([command isEqualToString:@"section-icon"]) {
6196 if (path == nil)
6197 goto fail;
6198 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6199 NSString *section(Simplify(path));
6b4b3bee
JF
6200 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6201 if (icon == nil)
6202 icon = [UIImage applicationImageNamed:@"unknown.png"];
a99d2808 6203 [self _returnPNGWithImage:icon forRequest:request];
f159ecd4
JF
6204 } else fail: {
6205 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6206 }
6207}
6208
6209- (void) stopLoading {
6210}
6211
6212@end
6213/* }}} */
6214
ce09fc27
JF
6215/* Sections View {{{ */
6216@interface SectionsView : RVPage {
f159ecd4
JF
6217 _transient Database *database_;
6218 NSMutableArray *sections_;
6219 NSMutableArray *filtered_;
6220 UITransitionView *transition_;
6221 UITable *list_;
6222 UIView *accessory_;
6223 BOOL editing_;
6224}
6225
6226- (id) initWithBook:(RVBook *)book database:(Database *)database;
6227- (void) reloadData;
6228- (void) resetView;
6229
6230@end
6231
ce09fc27 6232@implementation SectionsView
f159ecd4
JF
6233
6234- (void) dealloc {
6235 [list_ setDataSource:nil];
6236 [list_ setDelegate:nil];
6237
6238 [sections_ release];
6239 [filtered_ release];
6240 [transition_ release];
6241 [list_ release];
6242 [accessory_ release];
6243 [super dealloc];
6244}
6245
6246- (int) numberOfRowsInTable:(UITable *)table {
6247 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6248}
6249
6250- (float) table:(UITable *)table heightForRow:(int)row {
6251 return 45;
6252}
6253
6254- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6255 if (reusing == nil)
6256 reusing = [[[SectionCell alloc] init] autorelease];
6257 [(SectionCell *)reusing setSection:(editing_ ?
6258 [sections_ objectAtIndex:row] :
6259 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6260 ) editing:editing_];
6261 return reusing;
6262}
6263
6264- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6265 return !editing_;
6266}
6267
6268- (BOOL) table:(UITable *)table canSelectRow:(int)row {
6269 return !editing_;
6270}
6271
6272- (void) tableRowSelected:(NSNotification *)notification {
6273 int row = [[notification object] selectedRow];
6274 if (row == INT_MAX)
6275 return;
6276
6277 Section *section;
6278 NSString *name;
6279 NSString *title;
6280
6281 if (row == 0) {
6282 section = nil;
6283 name = nil;
6932575e 6284 title = CYLocalize("ALL_PACKAGES");
f159ecd4
JF
6285 } else {
6286 section = [filtered_ objectAtIndex:(row - 1)];
6287 name = [section name];
6288
6289 if (name != nil)
6932575e 6290 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
f159ecd4
JF
6291 else {
6292 name = @"";
6932575e 6293 title = CYLocalize("NO_SECTION");
f159ecd4
JF
6294 }
6295 }
6296
ce09fc27 6297 PackageTable *table = [[[FilteredPackageTable alloc]
f159ecd4
JF
6298 initWithBook:book_
6299 database:database_
6300 title:title
6301 filter:@selector(isVisiblyUninstalledInSection:)
6302 with:name
6303 ] autorelease];
6304
6305 [table setDelegate:delegate_];
6306
6307 [book_ pushPage:table];
6308}
6309
6310- (id) initWithBook:(RVBook *)book database:(Database *)database {
6311 if ((self = [super initWithBook:book]) != nil) {
6312 database_ = database;
6313
6314 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6315 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6316
6317 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6318 [self addSubview:transition_];
6319
6320 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6321 [transition_ transition:0 toView:list_];
6322
6323 UITableColumn *column = [[[UITableColumn alloc]
6932575e 6324 initWithTitle:CYLocalize("NAME")
f159ecd4
JF
6325 identifier:@"name"
6326 width:[self frame].size.width
6327 ] autorelease];
6328
6329 [list_ setDataSource:self];
6330 [list_ setSeparatorStyle:1];
6331 [list_ addTableColumn:column];
6332 [list_ setDelegate:self];
6333 [list_ setReusesTableCells:YES];
6334
6335 [self reloadData];
6336
6337 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6338 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6339 } return self;
6340}
6341
6342- (void) reloadData {
6343 NSArray *packages = [database_ packages];
6344
6345 [sections_ removeAllObjects];
6346 [filtered_ removeAllObjects];
6347
6932575e
JF
6348#if 0
6349 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6350 SectionMap sections;
6351 sections.resize(64);
6352#else
6353 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6354#endif
f159ecd4
JF
6355
6356 _trace();
9fdd37d0 6357 for (Package *package in packages) {
f159ecd4 6358 NSString *name([package section]);
6932575e 6359 NSString *key(name == nil ? @"" : name);
f159ecd4 6360
6932575e
JF
6361#if 0
6362 Section **section;
6363
6364 _profile(SectionsView$reloadData$Section)
6365 section = &sections[key];
6366 if (*section == nil) {
6367 _profile(SectionsView$reloadData$Section$Allocate)
9ee296df 6368 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6932575e
JF
6369 _end
6370 }
6371 _end
6372
6373 [*section addToCount];
6374
6375 _profile(SectionsView$reloadData$Filter)
6376 if (![package valid] || [package installed] != nil || ![package visible])
6377 continue;
6378 _end
6379
6380 [*section addToRow];
6381#else
6382 Section *section;
6383
6384 _profile(SectionsView$reloadData$Section)
6385 section = [sections objectForKey:key];
f159ecd4 6386 if (section == nil) {
6932575e 6387 _profile(SectionsView$reloadData$Section$Allocate)
9ee296df 6388 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6932575e
JF
6389 [sections setObject:section forKey:key];
6390 _end
f159ecd4 6391 }
6932575e
JF
6392 _end
6393
6394 [section addToCount];
fa7bb92f 6395
6932575e
JF
6396 _profile(SectionsView$reloadData$Filter)
6397 if (![package valid] || [package installed] != nil || ![package visible])
6398 continue;
6399 _end
6400
6401 [section addToRow];
6402#endif
686e302f 6403 }
f159ecd4 6404 _trace();
a75f53e7 6405
6932575e
JF
6406#if 0
6407 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6408 [sections_ addObject:i->second];
6409#else
fa7bb92f 6410 [sections_ addObjectsFromArray:[sections allValues]];
6932575e 6411#endif
fa7bb92f 6412
43b742af 6413 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
a75f53e7 6414
6932575e
JF
6415 for (Section *section in sections_) {
6416 size_t count([section row]);
43b742af 6417 if (count == 0)
6932575e 6418 continue;
a75f53e7 6419
9ee296df 6420 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6932575e
JF
6421 [section setCount:count];
6422 [filtered_ addObject:section];
686e302f 6423 }
4941f41d 6424
686e302f 6425 [list_ reloadData];
f159ecd4 6426 _trace();
e057ec05 6427}
4941f41d 6428
fa7bb92f
JF
6429- (void) resetView {
6430 if (editing_)
6431 [self _rightButtonClicked];
6432}
6433
e057ec05
JF
6434- (void) resetViewAnimated:(BOOL)animated {
6435 [list_ resetViewAnimated:animated];
6436}
4941f41d 6437
fa7bb92f
JF
6438- (void) _rightButtonClicked {
6439 if ((editing_ = !editing_))
6440 [list_ reloadData];
f159ecd4 6441 else
fa7bb92f 6442 [delegate_ updateData];
f464053e 6443 [book_ reloadTitleForPage:self];
fa7bb92f
JF
6444 [book_ reloadButtonsForPage:self];
6445}
6446
e057ec05 6447- (NSString *) title {
6932575e 6448 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
4941f41d
JF
6449}
6450
e057ec05 6451- (NSString *) backButtonTitle {
6932575e 6452 return CYLocalize("SECTIONS");
a75f53e7
JF
6453}
6454
2bfeaf6f 6455- (id) rightButtonTitle {
6932575e 6456 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
fa7bb92f
JF
6457}
6458
87c76914
JF
6459- (UINavigationButtonStyle) rightButtonStyle {
6460 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6461}
6462
9e07091a
JF
6463- (UIView *) accessoryView {
6464 return accessory_;
6465}
6466
a75f53e7 6467@end
4941f41d 6468/* }}} */
686e302f 6469/* Changes View {{{ */
e057ec05
JF
6470@interface ChangesView : RVPage {
6471 _transient Database *database_;
a75f53e7
JF
6472 NSMutableArray *packages_;
6473 NSMutableArray *sections_;
e057ec05
JF
6474 UISectionList *list_;
6475 unsigned upgrades_;
a75f53e7
JF
6476}
6477
e057ec05
JF
6478- (id) initWithBook:(RVBook *)book database:(Database *)database;
6479- (void) reloadData;
a75f53e7 6480
a75f53e7
JF
6481@end
6482
686e302f
JF
6483@implementation ChangesView
6484
6485- (void) dealloc {
e057ec05
JF
6486 [[list_ table] setDelegate:nil];
6487 [list_ setDataSource:nil];
6488
686e302f
JF
6489 [packages_ release];
6490 [sections_ release];
e057ec05 6491 [list_ release];
686e302f
JF
6492 [super dealloc];
6493}
a75f53e7
JF
6494
6495- (int) numberOfSectionsInSectionList:(UISectionList *)list {
6496 return [sections_ count];
6497}
6498
6499- (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6500 return [[sections_ objectAtIndex:section] name];
6501}
6502
6503- (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6504 return [[sections_ objectAtIndex:section] row];
6505}
6506
6507- (int) numberOfRowsInTable:(UITable *)table {
6508 return [packages_ count];
6509}
6510
6511- (float) table:(UITable *)table heightForRow:(int)row {
3319715b 6512 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
a75f53e7
JF
6513}
6514
3325a005
JF
6515- (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6516 if (reusing == nil)
e057ec05 6517 reusing = [[[PackageCell alloc] init] autorelease];
3325a005
JF
6518 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6519 return reusing;
a75f53e7
JF
6520}
6521
6522- (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
686e302f 6523 return NO;
a75f53e7
JF
6524}
6525
686e302f
JF
6526- (void) tableRowSelected:(NSNotification *)notification {
6527 int row = [[notification object] selectedRow];
e057ec05
JF
6528 if (row == INT_MAX)
6529 return;
6530 Package *package = [packages_ objectAtIndex:row];
6932575e 6531 PackageView *view([delegate_ packageView]);
e057ec05
JF
6532 [view setDelegate:delegate_];
6533 [view setPackage:package];
6534 [book_ pushPage:view];
a75f53e7
JF
6535}
6536
b7eb9e84
JF
6537- (void) _leftButtonClicked {
6538 [(CYBook *)book_ update];
6539 [self reloadButtons];
6540}
6541
e057ec05
JF
6542- (void) _rightButtonClicked {
6543 [delegate_ distUpgrade];
a75f53e7
JF
6544}
6545
e057ec05
JF
6546- (id) initWithBook:(RVBook *)book database:(Database *)database {
6547 if ((self = [super initWithBook:book]) != nil) {
6548 database_ = database;
a75f53e7 6549
686e302f
JF
6550 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6551 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
a75f53e7 6552
e057ec05
JF
6553 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6554 [self addSubview:list_];
6555
2d28b35a 6556 [list_ setShouldHideHeaderInShortLists:NO];
686e302f
JF
6557 [list_ setDataSource:self];
6558 //[list_ setSectionListStyle:1];
a75f53e7 6559
686e302f 6560 UITableColumn *column = [[[UITableColumn alloc]
6932575e 6561 initWithTitle:CYLocalize("NAME")
a75f53e7 6562 identifier:@"name"
e057ec05 6563 width:[self frame].size.width
686e302f 6564 ] autorelease];
a75f53e7
JF
6565
6566 UITable *table = [list_ table];
6567 [table setSeparatorStyle:1];
6568 [table addTableColumn:column];
6569 [table setDelegate:self];
3325a005 6570 [table setReusesTableCells:YES];
a75f53e7 6571
e057ec05 6572 [self reloadData];
87c76914
JF
6573
6574 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6575 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
a75f53e7
JF
6576 } return self;
6577}
6578
e057ec05
JF
6579- (void) reloadData {
6580 NSArray *packages = [database_ packages];
6581
686e302f 6582 [packages_ removeAllObjects];
e057ec05
JF
6583 [sections_ removeAllObjects];
6584
f159ecd4 6585 _trace();
9fdd37d0 6586 for (Package *package in packages)
fa7bb92f
JF
6587 if (
6588 [package installed] == nil && [package valid] && [package visible] ||
6e673d99 6589 [package upgradableAndEssential:YES]
fa7bb92f 6590 )
686e302f 6591 [packages_ addObject:package];
4941f41d 6592
f159ecd4 6593 _trace();
dd9390c5 6594 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
f159ecd4 6595 _trace();
a75f53e7 6596
9ee296df
JF
6597 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6598 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
a75f53e7 6599 Section *section = nil;
f159ecd4 6600 NSDate *last = nil;
686e302f 6601
e057ec05
JF
6602 upgrades_ = 0;
6603 bool unseens = false;
6604
43b742af 6605 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
e057ec05 6606
a75f53e7
JF
6607 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6608 Package *package = [packages_ objectAtIndex:offset];
a75f53e7 6609
43b742af 6610 BOOL uae = [package upgradableAndEssential:YES];
6932575e
JF
6611
6612 if (!uae) {
e057ec05 6613 unseens = true;
6932575e 6614 NSDate *seen;
a75f53e7 6615
6932575e
JF
6616 _profile(ChangesView$reloadData$Remember)
6617 seen = [package seen];
6618 _end
6619
43b742af 6620 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
f159ecd4 6621 last = seen;
138ae18d 6622
3ff1504e
JF
6623 NSString *name;
6624 if (seen == nil)
6932575e 6625 name = CYLocalize("UNKNOWN");
3ff1504e 6626 else {
43b742af 6627 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
3ff1504e
JF
6628 [name autorelease];
6629 }
6630
6932575e
JF
6631 _profile(ChangesView$reloadData$Allocate)
6632 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
9ee296df 6633 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6932575e
JF
6634 [sections_ addObject:section];
6635 _end
686e302f
JF
6636 }
6637
e057ec05 6638 [section addToCount];
f159ecd4
JF
6639 } else if ([package ignored])
6640 [ignored addToCount];
6641 else {
6642 ++upgrades_;
6643 [upgradable addToCount];
686e302f 6644 }
a75f53e7 6645 }
f159ecd4 6646 _trace();
a75f53e7 6647
e057ec05 6648 CFRelease(formatter);
686e302f 6649
e057ec05
JF
6650 if (unseens) {
6651 Section *last = [sections_ lastObject];
6652 size_t count = [last count];
6653 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6654 [sections_ removeLastObject];
6655 }
a75f53e7 6656
f159ecd4
JF
6657 if ([ignored count] != 0)
6658 [sections_ insertObject:ignored atIndex:0];
e057ec05
JF
6659 if (upgrades_ != 0)
6660 [sections_ insertObject:upgradable atIndex:0];
d12c6e70 6661
e057ec05
JF
6662 [list_ reloadData];
6663 [self reloadButtons];
2d28b35a
JF
6664}
6665
e057ec05
JF
6666- (void) resetViewAnimated:(BOOL)animated {
6667 [list_ resetViewAnimated:animated];
2d28b35a
JF
6668}
6669
b7eb9e84 6670- (NSString *) leftButtonTitle {
6932575e 6671 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
b7eb9e84
JF
6672}
6673
2bfeaf6f 6674- (id) rightButtonTitle {
6932575e 6675 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
2d28b35a
JF
6676}
6677
e057ec05 6678- (NSString *) title {
6932575e 6679 return CYLocalize("CHANGES");
b6ffa083
JF
6680}
6681
2d28b35a
JF
6682@end
6683/* }}} */
e057ec05
JF
6684/* Search View {{{ */
6685@protocol SearchViewDelegate
6686- (void) showKeyboard:(BOOL)show;
6687@end
686e302f 6688
8993ad57 6689@interface SearchView : RVPage {
e057ec05
JF
6690 UIView *accessory_;
6691 UISearchField *field_;
8993ad57 6692 UITransitionView *transition_;
ce09fc27 6693 FilteredPackageTable *table_;
8993ad57 6694 UIPreferencesTable *advanced_;
e25e221f 6695 UIView *dimmed_;
8993ad57 6696 bool flipped_;
59efd93a 6697 bool reload_;
e057ec05 6698}
686e302f 6699
e057ec05
JF
6700- (id) initWithBook:(RVBook *)book database:(Database *)database;
6701- (void) reloadData;
686e302f 6702
2d28b35a
JF
6703@end
6704
e057ec05 6705@implementation SearchView
2d28b35a 6706
686e302f 6707- (void) dealloc {
e057ec05 6708 [field_ setDelegate:nil];
2d28b35a 6709
e057ec05
JF
6710 [accessory_ release];
6711 [field_ release];
8993ad57
JF
6712 [transition_ release];
6713 [table_ release];
6714 [advanced_ release];
e25e221f 6715 [dimmed_ release];
e057ec05 6716 [super dealloc];
686e302f
JF
6717}
6718
59efd93a
JF
6719- (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6720 return 1;
6721}
6722
6723- (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6724 switch (group) {
6932575e 6725 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
59efd93a
JF
6726
6727 default: _assert(false);
6728 }
6729}
6730
6731- (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6732 switch (group) {
6733 case 0: return 0;
6734
6735 default: _assert(false);
6736 }
6737}
6738
2a987aa5
JF
6739- (void) _showKeyboard:(BOOL)show {
6740 CGSize keysize = [UIKeyboard defaultSize];
6741 CGRect keydown = [book_ pageBounds];
6742 CGRect keyup = keydown;
6743 keyup.size.height -= keysize.height - ButtonBarHeight_;
6744
6745 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6746
6747 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6748 [animation setSignificantRectFields:8];
6749
6750 if (show) {
6751 [animation setStartFrame:keydown];
6752 [animation setEndFrame:keyup];
6753 } else {
6754 [animation setStartFrame:keyup];
6755 [animation setEndFrame:keydown];
6756 }
6757
6758 UIAnimator *animator = [UIAnimator sharedAnimator];
6759
6760 [animator
6761 addAnimations:[NSArray arrayWithObjects:animation, nil]
6762 withDuration:(KeyboardTime_ - delay)
6763 start:!show
6764 ];
6765
6766 if (show)
6767 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6768
6769 [delegate_ showKeyboard:show];
6770}
6771
e057ec05 6772- (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
2a987aa5 6773 [self _showKeyboard:YES];
e057ec05 6774}
686e302f 6775
e057ec05 6776- (void) textFieldDidResignFirstResponder:(UITextField *)field {
2a987aa5 6777 [self _showKeyboard:NO];
e057ec05 6778}
686e302f 6779
e057ec05 6780- (void) keyboardInputChanged:(UIFieldEditor *)editor {
59efd93a
JF
6781 if (reload_) {
6782 NSString *text([field_ text]);
6783 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6784 [self reloadData];
6785 reload_ = false;
6786 }
6787}
6788
6789- (void) textFieldClearButtonPressed:(UITextField *)field {
6790 reload_ = true;
6791}
6792
6793- (void) keyboardInputShouldDelete:(id)input {
6794 reload_ = true;
e057ec05 6795}
686e302f 6796
e057ec05 6797- (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
59efd93a
JF
6798 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6799 reload_ = true;
e057ec05 6800 return YES;
59efd93a
JF
6801 } else {
6802 [field_ resignFirstResponder];
6803 return NO;
6804 }
686e302f
JF
6805}
6806
e057ec05 6807- (id) initWithBook:(RVBook *)book database:(Database *)database {
8993ad57
JF
6808 if ((self = [super initWithBook:book]) != nil) {
6809 CGRect pageBounds = [book_ pageBounds];
6810
8993ad57
JF
6811 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6812 [self addSubview:transition_];
6813
6814 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6815
59efd93a
JF
6816 [advanced_ setReusesTableCells:YES];
6817 [advanced_ setDataSource:self];
6818 [advanced_ reloadData];
6819
e25e221f
JF
6820 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6821 CGColor dimmed(space_, 0, 0, 0, 0.5);
d210b85d 6822 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
e25e221f 6823
ce09fc27 6824 table_ = [[FilteredPackageTable alloc]
8993ad57
JF
6825 initWithBook:book
6826 database:database
6827 title:nil
853d14d3 6828 filter:@selector(isUnfilteredAndSearchedForBy:)
8993ad57
JF
6829 with:nil
6830 ];
6831
59efd93a 6832 [table_ setShouldHideHeaderInShortLists:NO];
8993ad57
JF
6833 [transition_ transition:0 toView:table_];
6834
23bcd525
JF
6835 CGRect cnfrect = {{
6836#ifdef __OBJC2__
6837 6 +
6838#endif
6839 1, 38}, {17, 18}};
686e302f 6840
e057ec05 6841 CGRect area;
fa7bb92f 6842 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
87c76914 6843 area.origin.y = 1;
23bcd525
JF
6844
6845 area.size.width =
6846#ifdef __OBJC2__
6847 8 +
6848#endif
6849 [self bounds].size.width - area.origin.x - 18;
6850
e057ec05 6851 area.size.height = [UISearchField defaultHeight];
2d28b35a 6852
e057ec05 6853 field_ = [[UISearchField alloc] initWithFrame:area];
686e302f 6854
d210b85d 6855 UIFont *font = [UIFont systemFontOfSize:16];
e057ec05 6856 [field_ setFont:font];
686e302f 6857
6932575e 6858 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
e057ec05 6859 [field_ setDelegate:self];
686e302f 6860
2cb68ddf 6861 [field_ setPaddingTop:5];
23bcd525 6862
b7adefda
JF
6863 UITextInputTraits *traits([field_ textInputTraits]);
6864 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6865 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6866 [traits setReturnKeyType:UIReturnKeySearch];
fa7bb92f 6867
87c76914 6868 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
23bcd525
JF
6869
6870 accessory_ = [[UIView alloc] initWithFrame:accrect];
81ab76dc
JF
6871 [accessory_ addSubview:field_];
6872
fa7bb92f 6873 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
e057ec05 6874 [configure setShowPressFeedback:YES];
97959670 6875 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
e057ec05 6876 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
fa7bb92f 6877 [accessory_ addSubview:configure];*/
87c76914
JF
6878
6879 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6880 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
e057ec05 6881 } return self;
2d28b35a
JF
6882}
6883
8993ad57 6884- (void) flipPage {
b27f0a94 6885#ifndef __OBJC2__
8993ad57
JF
6886 LKAnimation *animation = [LKTransition animation];
6887 [animation setType:@"oglFlip"];
6888 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6889 [animation setFillMode:@"extended"];
6890 [animation setTransitionFlags:3];
6891 [animation setDuration:10];
6892 [animation setSpeed:0.35];
ecabc2b3
JF
6893 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6894 [[transition_ _layer] addAnimation:animation forKey:0];
8993ad57
JF
6895 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6896 flipped_ = !flipped_;
b27f0a94 6897#endif
8993ad57
JF
6898}
6899
e057ec05 6900- (void) configurePushed {
8993ad57
JF
6901 [field_ resignFirstResponder];
6902 [self flipPage];
6903}
6904
f159ecd4
JF
6905- (void) resetViewAnimated:(BOOL)animated {
6906 if (flipped_)
6907 [self flipPage];
6908 [table_ resetViewAnimated:animated];
6909}
2d28b35a 6910
f159ecd4
JF
6911- (void) _reloadData {
6912}
686e302f 6913
f159ecd4
JF
6914- (void) reloadData {
6915 if (flipped_)
6916 [self flipPage];
6917 [table_ setObject:[field_ text]];
3bddda52
JF
6918 _profile(SearchView$reloadData)
6919 [table_ reloadData];
6920 _end
6921 PrintTimes();
f159ecd4
JF
6922 [table_ resetCursor];
6923}
f464053e 6924
f159ecd4
JF
6925- (UIView *) accessoryView {
6926 return accessory_;
6927}
f464053e 6928
f159ecd4
JF
6929- (NSString *) title {
6930 return nil;
6931}
1eb0c554 6932
f159ecd4 6933- (NSString *) backButtonTitle {
6932575e 6934 return CYLocalize("SEARCH");
f159ecd4 6935}
81ab76dc 6936
f159ecd4
JF
6937- (void) setDelegate:(id)delegate {
6938 [table_ setDelegate:delegate];
6939 [super setDelegate:delegate];
6940}
b6ffa083 6941
f159ecd4
JF
6942@end
6943/* }}} */
686e302f 6944
f159ecd4
JF
6945@interface SettingsView : RVPage {
6946 _transient Database *database_;
6947 NSString *name_;
6948 Package *package_;
6949 UIPreferencesTable *table_;
6950 _UISwitchSlider *subscribedSwitch_;
6951 _UISwitchSlider *ignoredSwitch_;
6952 UIPreferencesControlTableCell *subscribedCell_;
6953 UIPreferencesControlTableCell *ignoredCell_;
6954}
686e302f 6955
f159ecd4 6956- (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
686e302f 6957
f159ecd4 6958@end
686e302f 6959
f159ecd4 6960@implementation SettingsView
686e302f 6961
f159ecd4
JF
6962- (void) dealloc {
6963 [table_ setDataSource:nil];
686e302f 6964
f159ecd4
JF
6965 [name_ release];
6966 if (package_ != nil)
6967 [package_ release];
6968 [table_ release];
6969 [subscribedSwitch_ release];
6970 [ignoredSwitch_ release];
6971 [subscribedCell_ release];
6972 [ignoredCell_ release];
6973 [super dealloc];
6974}
686e302f 6975
f159ecd4
JF
6976- (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6977 if (package_ == nil)
6978 return 0;
686e302f 6979
f159ecd4
JF
6980 return 2;
6981}
e057ec05 6982
f159ecd4
JF
6983- (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6984 if (package_ == nil)
6985 return nil;
87c76914 6986
f159ecd4
JF
6987 switch (group) {
6988 case 0: return nil;
6989 case 1: return nil;
87c76914 6990
f159ecd4
JF
6991 default: _assert(false);
6992 }
87c76914 6993
f159ecd4 6994 return nil;
2d28b35a
JF
6995}
6996
f159ecd4
JF
6997- (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6998 if (package_ == nil)
6999 return NO;
87c76914 7000
f159ecd4
JF
7001 switch (group) {
7002 case 0: return NO;
7003 case 1: return YES;
686e302f 7004
f159ecd4
JF
7005 default: _assert(false);
7006 }
2d28b35a 7007
f159ecd4 7008 return NO;
a75f53e7
JF
7009}
7010
f159ecd4
JF
7011- (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7012 if (package_ == nil)
7013 return 0;
a75f53e7 7014
f159ecd4
JF
7015 switch (group) {
7016 case 0: return 1;
7017 case 1: return 1;
2d28b35a 7018
f159ecd4
JF
7019 default: _assert(false);
7020 }
87c76914 7021
f159ecd4 7022 return 0;
e057ec05 7023}
686e302f 7024
f159ecd4
JF
7025- (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7026 if (package_ == nil)
7027 return;
686e302f 7028
f159ecd4 7029 _UISwitchSlider *slider([cell control]);
f159ecd4
JF
7030 BOOL value([slider value] != 0);
7031 NSMutableDictionary *metadata([package_ metadata]);
87c76914 7032
f159ecd4
JF
7033 BOOL before;
7034 if (NSNumber *number = [metadata objectForKey:key])
7035 before = [number boolValue];
7036 else
7037 before = NO;
e057ec05 7038
f159ecd4
JF
7039 if (value != before) {
7040 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7041 Changed_ = true;
f159ecd4
JF
7042 [delegate_ updateData];
7043 }
87c76914
JF
7044}
7045
f159ecd4
JF
7046- (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7047 [self onSomething:cell withKey:@"IsSubscribed"];
e057ec05 7048}
686e302f 7049
f159ecd4
JF
7050- (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7051 [self onSomething:cell withKey:@"IsIgnored"];
b6ffa083
JF
7052}
7053
f159ecd4
JF
7054- (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7055 if (package_ == nil)
7056 return nil;
dbe0f181 7057
f159ecd4
JF
7058 switch (group) {
7059 case 0: switch (row) {
7060 case 0:
7061 return subscribedCell_;
7062 case 1:
7063 return ignoredCell_;
7064 default: _assert(false);
7065 } break;
7066
7067 case 1: switch (row) {
7068 case 0: {
7069 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
907a35d6 7070 [cell setShowSelection:NO];
6932575e 7071 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
f159ecd4
JF
7072 return cell;
7073 }
dbe0f181 7074
f159ecd4
JF
7075 default: _assert(false);
7076 } break;
dbe0f181 7077
f159ecd4
JF
7078 default: _assert(false);
7079 }
dbe0f181 7080
f159ecd4 7081 return nil;
dbe0f181
JF
7082}
7083
f159ecd4
JF
7084- (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7085 if ((self = [super initWithBook:book])) {
7086 database_ = database;
7087 name_ = [package retain];
dbe0f181 7088
f159ecd4
JF
7089 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7090 [self addSubview:table_];
dbe0f181 7091
f159ecd4
JF
7092 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7093 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
dbe0f181 7094
f159ecd4
JF
7095 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7096 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
dbe0f181 7097
f159ecd4 7098 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
907a35d6 7099 [subscribedCell_ setShowSelection:NO];
6932575e 7100 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
f159ecd4 7101 [subscribedCell_ setControl:subscribedSwitch_];
dbe0f181 7102
f159ecd4 7103 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
907a35d6 7104 [ignoredCell_ setShowSelection:NO];
6932575e 7105 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
f159ecd4 7106 [ignoredCell_ setControl:ignoredSwitch_];
dbe0f181 7107
f159ecd4
JF
7108 [table_ setDataSource:self];
7109 [self reloadData];
7110 } return self;
7111}
dbe0f181 7112
f159ecd4
JF
7113- (void) resetViewAnimated:(BOOL)animated {
7114 [table_ resetViewAnimated:animated];
7115}
dbe0f181 7116
f159ecd4
JF
7117- (void) reloadData {
7118 if (package_ != nil)
7119 [package_ autorelease];
7120 package_ = [database_ packageWithName:name_];
7121 if (package_ != nil) {
7122 [package_ retain];
7123 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7124 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
dbe0f181 7125 }
f159ecd4
JF
7126
7127 [table_ reloadData];
dbe0f181
JF
7128}
7129
f159ecd4 7130- (NSString *) title {
6932575e 7131 return CYLocalize("SETTINGS");
dbe0f181
JF
7132}
7133
7134@end
7135
f159ecd4 7136/* Signature View {{{ */
dbe0f181
JF
7137@interface SignatureView : BrowserView {
7138 _transient Database *database_;
7139 NSString *package_;
7140}
7141
7142- (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7143
7144@end
7145
7146@implementation SignatureView
7147
7148- (void) dealloc {
7149 [package_ release];
7150 [super dealloc];
7151}
7152
7153- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7154 // XXX: dude!
7155 [super webView:sender didClearWindowObject:window forFrame:frame];
7156}
7157
7158- (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7159 if ((self = [super initWithBook:book]) != nil) {
7160 database_ = database;
7161 package_ = [package retain];
7162 [self reloadData];
7163 } return self;
7164}
7165
f159ecd4
JF
7166- (void) resetViewAnimated:(BOOL)animated {
7167}
7168
dbe0f181
JF
7169- (void) reloadData {
7170 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7171}
7172
7173@end
f159ecd4 7174/* }}} */
dbe0f181 7175
4941f41d 7176@interface Cydia : UIApplication <
2d28b35a 7177 ConfirmationViewDelegate,
686e302f 7178 ProgressViewDelegate,
b0d03ade
JF
7179 SearchViewDelegate,
7180 CydiaDelegate
4941f41d 7181> {
a75f53e7 7182 UIWindow *window_;
e057ec05 7183
2d28b35a
JF
7184 UIView *underlay_;
7185 UIView *overlay_;
e057ec05 7186 CYBook *book_;
d210b85d 7187 UIToolbar *buttonbar_;
2d28b35a 7188
f464053e 7189 RVBook *confirm_;
3319715b 7190
9e07091a 7191 NSMutableArray *essential_;
3319715b 7192 NSMutableArray *broken_;
a75f53e7
JF
7193
7194 Database *database_;
7195 ProgressView *progress_;
7196
7e986211 7197 unsigned tag_;
686e302f
JF
7198
7199 UIKeyboard *keyboard_;
b26eb97d 7200 UIProgressHUD *hud_;
e25e221f 7201
ce09fc27 7202 SectionsView *sections_;
e25e221f
JF
7203 ChangesView *changes_;
7204 ManageView *manage_;
7205 SearchView *search_;
6932575e 7206
b452841e 7207 NSMutableArray *details_;
a75f53e7
JF
7208}
7209
a75f53e7
JF
7210@end
7211
7212@implementation Cydia
7213
3319715b
JF
7214- (void) _loaded {
7215 if ([broken_ count] != 0) {
7216 int count = [broken_ count];
7217
d210b85d 7218 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e 7219 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
3319715b 7220 buttons:[NSArray arrayWithObjects:
6932575e
JF
7221 CYLocalize("FORCIBLY_CLEAR"),
7222 CYLocalize("TEMPORARY_IGNORE"),
3319715b
JF
7223 nil]
7224 defaultButtonIndex:0
7225 delegate:self
7226 context:@"fixhalf"
7227 ] autorelease];
7228
6932575e 7229 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
3319715b
JF
7230 [sheet popupAlertAnimated:YES];
7231 } else if (!Ignored_ && [essential_ count] != 0) {
7232 int count = [essential_ count];
7233
d210b85d 7234 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e 7235 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
f464053e 7236 buttons:[NSArray arrayWithObjects:
6932575e
JF
7237 CYLocalize("UPGRADE_ESSENTIAL"),
7238 CYLocalize("COMPLETE_UPGRADE"),
7239 CYLocalize("TEMPORARY_IGNORE"),
f464053e 7240 nil]
3319715b
JF
7241 defaultButtonIndex:0
7242 delegate:self
7243 context:@"upgrade"
7244 ] autorelease];
7245
6932575e 7246 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
3319715b
JF
7247 [sheet popupAlertAnimated:YES];
7248 }
7249}
7250
e057ec05 7251- (void) _reloadData {
7398a389
JF
7252 UIView *block();
7253
7b00c562 7254 static bool loaded(false);
7398a389 7255 UIProgressHUD *hud([self addProgressHUD]);
6932575e 7256 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7b00c562 7257 loaded = true;
a75f53e7 7258
7398a389
JF
7259 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7260 _trace();
7261
7262 [self removeProgressHUD:hud];
d12c6e70 7263
e057ec05 7264 size_t changes(0);
3319715b 7265
9e07091a 7266 [essential_ removeAllObjects];
3319715b 7267 [broken_ removeAllObjects];
686e302f 7268
e057ec05 7269 NSArray *packages = [database_ packages];
f464053e 7270 for (Package *package in packages) {
3319715b
JF
7271 if ([package half])
7272 [broken_ addObject:package];
238b07ce 7273 if ([package upgradableAndEssential:NO]) {
9e07091a
JF
7274 if ([package essential])
7275 [essential_ addObject:package];
e057ec05 7276 ++changes;
9e07091a 7277 }
e057ec05 7278 }
686e302f 7279
e057ec05
JF
7280 if (changes != 0) {
7281 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
d12c6e70 7282 [buttonbar_ setBadgeValue:badge forButton:3];
63a1e4b8 7283 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
3ff1504e 7284 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
6932575e
JF
7285 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7286 [self setApplicationBadge:badge];
7287 else
7288 [self setApplicationBadgeString:badge];
d12c6e70
JF
7289 } else {
7290 [buttonbar_ setBadgeValue:nil forButton:3];
63a1e4b8
JF
7291 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7292 [buttonbar_ setBadgeAnimated:NO forButton:3];
6932575e
JF
7293 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7294 [self removeApplicationBadge];
7295 else // XXX: maybe use setApplicationBadgeString also?
7296 [self setApplicationIconBadgeNumber:0];
d12c6e70 7297 }
686e302f 7298
3ff1504e
JF
7299 Queuing_ = false;
7300 [buttonbar_ setBadgeValue:nil forButton:4];
7301
fa7bb92f
JF
7302 [self updateData];
7303
04700693 7304 // XXX: what is this line of code for?
ad554f10 7305 if ([packages count] == 0);
d8d9a65c 7306 else if (Loaded_ || ManualRefresh) loaded:
fa7bb92f 7307 [self _loaded];
ad554f10 7308 else {
fa7bb92f 7309 Loaded_ = YES;
04700693
JF
7310
7311 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7312 NSTimeInterval interval([update timeIntervalSinceNow]);
7313 if (interval <= 0 && interval > -600)
7314 goto loaded;
7315 }
7316
fa7bb92f 7317 [book_ update];
ad554f10 7318 }
fa7bb92f
JF
7319}
7320
faf4eb4f 7321- (void) _saveConfig {
3d37fc0d 7322 if (Changed_) {
f159ecd4 7323 _trace();
6932575e
JF
7324 NSString *error(nil);
7325 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7326 _trace();
7327 NSError *error(nil);
7328 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7329 NSLog(@"failure to save metadata data: %@", error);
7330 _trace();
7331 } else {
7332 NSLog(@"failure to serialize metadata: %@", error);
7333 return;
7334 }
7335
3d37fc0d
JF
7336 Changed_ = false;
7337 }
faf4eb4f
JF
7338}
7339
7340- (void) updateData {
7341 [self _saveConfig];
e057ec05 7342
e25e221f 7343 /* XXX: this is just stupid */
ce09fc27
JF
7344 if (tag_ != 2 && sections_ != nil)
7345 [sections_ reloadData];
f159ecd4 7346 if (tag_ != 3 && changes_ != nil)
e25e221f 7347 [changes_ reloadData];
f159ecd4 7348 if (tag_ != 5 && search_ != nil)
e25e221f
JF
7349 [search_ reloadData];
7350
e057ec05 7351 [book_ reloadData];
686e302f
JF
7352}
7353
faf4eb4f
JF
7354- (void) update_ {
7355 [database_ update];
7356}
7357
7358- (void) syncData {
7359 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7360 _assert(file != NULL);
7361
7362 NSArray *keys = [Sources_ allKeys];
7363
9fdd37d0 7364 for (NSString *key in keys) {
faf4eb4f
JF
7365 NSDictionary *source = [Sources_ objectForKey:key];
7366
7367 fprintf(file, "%s %s %s\n",
7368 [[source objectForKey:@"Type"] UTF8String],
7369 [[source objectForKey:@"URI"] UTF8String],
7370 [[source objectForKey:@"Distribution"] UTF8String]
7371 );
7372 }
7373
7374 fclose(file);
7375
7376 [self _saveConfig];
7377
7378 [progress_
7379 detachNewThreadSelector:@selector(update_)
7380 toTarget:self
7381 withObject:nil
6932575e 7382 title:CYLocalize("UPDATING_SOURCES")
faf4eb4f
JF
7383 ];
7384}
7385
e057ec05
JF
7386- (void) reloadData {
7387 @synchronized (self) {
7388 if (confirm_ == nil)
7389 [self _reloadData];
7390 }
686e302f
JF
7391}
7392
7393- (void) resolve {
7394 pkgProblemResolver *resolver = [database_ resolver];
7395
7396 resolver->InstallProtect();
7397 if (!resolver->Resolve(true))
7398 _error->Discard();
4941f41d
JF
7399}
7400
04700693
JF
7401- (void) popUpBook:(RVBook *)book {
7402 [underlay_ popSubview:book];
7403}
7404
7405- (CGRect) popUpBounds {
7406 return [underlay_ bounds];
7407}
7408
4941f41d 7409- (void) perform {
b6ffa083 7410 [database_ prepare];
242bcc6d 7411
04700693 7412 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
f464053e 7413 [confirm_ setDelegate:self];
242bcc6d 7414
f464053e
JF
7415 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7416 [page setDelegate:self];
242bcc6d 7417
f464053e 7418 [confirm_ setPage:page];
04700693 7419 [self popUpBook:confirm_];
2d28b35a
JF
7420}
7421
3ff1504e
JF
7422- (void) queue {
7423 @synchronized (self) {
7424 [self perform];
7425 }
7426}
7427
7428- (void) clearPackage:(Package *)package {
7429 @synchronized (self) {
7430 [package clear];
7431 [self resolve];
7432 [self perform];
7433 }
7434}
7435
e057ec05
JF
7436- (void) installPackage:(Package *)package {
7437 @synchronized (self) {
7438 [package install];
7439 [self resolve];
7440 [self perform];
7441 }
7442}
7443
7444- (void) removePackage:(Package *)package {
7445 @synchronized (self) {
7446 [package remove];
7447 [self resolve];
7448 [self perform];
7449 }
7450}
7451
7452- (void) distUpgrade {
7453 @synchronized (self) {
7454 [database_ upgrade];
7455 [self perform];
7456 }
686e302f
JF
7457}
7458
2d28b35a 7459- (void) cancel {
3ff1504e
JF
7460 [self slideUp:[[[UIActionSheet alloc]
7461 initWithTitle:nil
6932575e 7462 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
3ff1504e
JF
7463 defaultButtonIndex:1
7464 delegate:self
7465 context:@"cancel"
7466 ] autorelease]];
7467}
7468
7469- (void) complete {
e057ec05 7470 @synchronized (self) {
e057ec05 7471 [self _reloadData];
3ff1504e 7472
cb9c2100
JF
7473 if (confirm_ != nil) {
7474 [confirm_ release];
7475 confirm_ = nil;
7476 }
e057ec05 7477 }
2d28b35a
JF
7478}
7479
7480- (void) confirm {
7481 [overlay_ removeFromSuperview];
d72d91aa 7482 reload_ = true;
2d28b35a 7483
4941f41d
JF
7484 [progress_
7485 detachNewThreadSelector:@selector(perform)
7486 toTarget:database_
7487 withObject:nil
6932575e 7488 title:CYLocalize("RUNNING")
4941f41d
JF
7489 ];
7490}
7491
df5a7529
JF
7492- (void) bootstrap_ {
7493 [database_ update];
7494 [database_ upgrade];
7495 [database_ prepare];
7496 [database_ perform];
7497}
7498
6932575e 7499/* XXX: replace and localize */
df5a7529
JF
7500- (void) bootstrap {
7501 [progress_
7502 detachNewThreadSelector:@selector(bootstrap_)
7503 toTarget:self
7504 withObject:nil
87c76914 7505 title:@"Bootstrap Install"
df5a7529
JF
7506 ];
7507}
7508
4941f41d 7509- (void) progressViewIsComplete:(ProgressView *)progress {
cb9c2100
JF
7510 if (confirm_ != nil) {
7511 [underlay_ addSubview:overlay_];
f464053e 7512 [confirm_ popFromSuperviewAnimated:NO];
2d28b35a 7513 }
cb9c2100 7514
3ff1504e 7515 [self complete];
a75f53e7
JF
7516}
7517
e057ec05 7518- (void) setPage:(RVPage *)page {
e25e221f 7519 [page resetViewAnimated:NO];
e057ec05
JF
7520 [page setDelegate:self];
7521 [book_ setPage:page];
a75f53e7
JF
7522}
7523
faf4eb4f 7524- (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
dbe0f181 7525 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
faf4eb4f 7526 [browser loadURL:url];
e057ec05 7527 return browser;
4941f41d
JF
7528}
7529
faf4eb4f
JF
7530- (void) _setHomePage {
7531 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7532}
7533
6932575e
JF
7534- (SectionsView *) sectionsView {
7535 if (sections_ == nil)
7536 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7537 return sections_;
7538}
7539
a75f53e7 7540- (void) buttonBarItemTapped:(id)sender {
7e986211 7541 unsigned tag = [sender tag];
97959670
JF
7542 if (tag == tag_) {
7543 [book_ resetViewAnimated:YES];
7544 return;
fa7bb92f 7545 } else if (tag_ == 2 && tag != 2)
6932575e 7546 [[self sectionsView] resetView];
a75f53e7 7547
7e986211 7548 switch (tag) {
7d07c4ff 7549 case 1: [self _setHomePage]; break;
e057ec05 7550
6932575e 7551 case 2: [self setPage:[self sectionsView]]; break;
7d07c4ff
JF
7552 case 3: [self setPage:changes_]; break;
7553 case 4: [self setPage:manage_]; break;
7554 case 5: [self setPage:search_]; break;
e057ec05 7555
7d07c4ff 7556 default: _assert(false);
a75f53e7
JF
7557 }
7558
7e986211 7559 tag_ = tag;
7e986211
JF
7560}
7561
686e302f 7562- (void) applicationWillSuspend {
d72d91aa 7563 [database_ clean];
2d7f7dea 7564 [super applicationWillSuspend];
686e302f
JF
7565}
7566
faf4eb4f 7567- (void) askForSettings {
6932575e
JF
7568 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7569
d210b85d 7570 UIActionSheet *role = [[[UIActionSheet alloc]
6932575e 7571 initWithTitle:CYLocalize("WHO_ARE_YOU")
faf4eb4f 7572 buttons:[NSArray arrayWithObjects:
6932575e
JF
7573 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7574 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7575 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
faf4eb4f
JF
7576 nil]
7577 defaultButtonIndex:-1
7578 delegate:self
7579 context:@"role"
7580 ] autorelease];
7581
6932575e 7582 [role setBodyText:CYLocalize("ROLE_EX")];
faf4eb4f
JF
7583 [role popupAlertAnimated:YES];
7584}
7585
6932575e 7586- (void) setPackageView:(PackageView *)view {
b452841e
JF
7587 WebThreadLock();
7588 [view setPackage:nil];
7589 if ([details_ count] < 3)
7590 [details_ addObject:view];
7591 WebThreadUnlock();
7592}
7593
7594- (PackageView *) _packageView {
7595 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
6932575e
JF
7596}
7597
7598- (PackageView *) packageView {
7599 PackageView *view;
b452841e 7600 size_t count([details_ count]);
6932575e 7601
b452841e
JF
7602 if (count == 0) {
7603 view = [self _packageView];
7604 renew:
7605 [details_ addObject:[self _packageView]];
7606 } else {
7607 view = [[[details_ lastObject] retain] autorelease];
7608 [details_ removeLastObject];
7609 if (count == 1)
7610 goto renew;
6932575e
JF
7611 }
7612
7613 return view;
7614}
7615
b26eb97d
JF
7616- (void) finish {
7617 if (hud_ != nil) {
7618 [self setStatusBarShowsProgress:NO];
7398a389 7619 [self removeProgressHUD:hud_];
9e07091a 7620
b26eb97d
JF
7621 [hud_ autorelease];
7622 hud_ = nil;
a2ef756d 7623
81a66bfc
JF
7624 pid_t pid = ExecFork();
7625 if (pid == 0) {
7626 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7627 perror("launchctl stop");
7628 }
7629
a2ef756d 7630 return;
b26eb97d 7631 }
2d28b35a 7632
faf4eb4f
JF
7633 if (Role_ == nil) {
7634 [self askForSettings];
7635 return;
7636 }
7637
b7ad9c68 7638 _trace();
2d28b35a 7639 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
df5a7529 7640
b26eb97d 7641 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
e057ec05
JF
7642 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7643 0, 0, screenrect.size.width, screenrect.size.height - 48
7644 ) database:database_];
a75f53e7 7645
e057ec05 7646 [book_ setDelegate:self];
a75f53e7 7647
e057ec05 7648 [overlay_ addSubview:book_];
a933cee2 7649
a75f53e7
JF
7650 NSArray *buttonitems = [NSArray arrayWithObjects:
7651 [NSDictionary dictionaryWithObjectsAndKeys:
7652 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
e25e221f
JF
7653 @"home-up.png", kUIButtonBarButtonInfo,
7654 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
a75f53e7
JF
7655 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7656 self, kUIButtonBarButtonTarget,
bb9edf8b 7657 @"Cydia", kUIButtonBarButtonTitle,
a75f53e7
JF
7658 @"0", kUIButtonBarButtonType,
7659 nil],
7660
7661 [NSDictionary dictionaryWithObjectsAndKeys:
7662 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7663 @"install-up.png", kUIButtonBarButtonInfo,
7664 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7665 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7666 self, kUIButtonBarButtonTarget,
6932575e 7667 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
a75f53e7
JF
7668 @"0", kUIButtonBarButtonType,
7669 nil],
7670
7671 [NSDictionary dictionaryWithObjectsAndKeys:
7672 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
686e302f
JF
7673 @"changes-up.png", kUIButtonBarButtonInfo,
7674 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
a75f53e7
JF
7675 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7676 self, kUIButtonBarButtonTarget,
6932575e 7677 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
a75f53e7
JF
7678 @"0", kUIButtonBarButtonType,
7679 nil],
7680
7681 [NSDictionary dictionaryWithObjectsAndKeys:
7682 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
686e302f
JF
7683 @"manage-up.png", kUIButtonBarButtonInfo,
7684 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
a75f53e7
JF
7685 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7686 self, kUIButtonBarButtonTarget,
6932575e 7687 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
a75f53e7
JF
7688 @"0", kUIButtonBarButtonType,
7689 nil],
7690
7691 [NSDictionary dictionaryWithObjectsAndKeys:
7692 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
686e302f
JF
7693 @"search-up.png", kUIButtonBarButtonInfo,
7694 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
a75f53e7
JF
7695 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7696 self, kUIButtonBarButtonTarget,
6932575e 7697 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
a75f53e7
JF
7698 @"0", kUIButtonBarButtonType,
7699 nil],
7700 nil];
7701
d210b85d 7702 buttonbar_ = [[UIToolbar alloc]
2d28b35a 7703 initInView:overlay_
a75f53e7 7704 withFrame:CGRectMake(
2a987aa5
JF
7705 0, screenrect.size.height - ButtonBarHeight_,
7706 screenrect.size.width, ButtonBarHeight_
a75f53e7
JF
7707 )
7708 withItemList:buttonitems
7709 ];
7710
4941f41d
JF
7711 [buttonbar_ setDelegate:self];
7712 [buttonbar_ setBarStyle:1];
7713 [buttonbar_ setButtonBarTrackingMode:2];
a75f53e7
JF
7714
7715 int buttons[5] = {1, 2, 3, 4, 5};
4941f41d
JF
7716 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7717 [buttonbar_ showButtonGroup:0 withDuration:0];
a75f53e7
JF
7718
7719 for (int i = 0; i != 5; ++i)
4941f41d 7720 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
2a987aa5 7721 i * 64 + 2, 1, 60, ButtonBarHeight_
a75f53e7
JF
7722 )];
7723
4941f41d 7724 [buttonbar_ showSelectionForButton:1];
2d28b35a 7725 [overlay_ addSubview:buttonbar_];
a75f53e7 7726
686e302f 7727 [UIKeyboard initImplementationNow];
686e302f 7728 CGSize keysize = [UIKeyboard defaultSize];
59efd93a 7729 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
686e302f 7730 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
e69d449d 7731 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
59efd93a 7732 [overlay_ addSubview:keyboard_];
686e302f 7733
f159ecd4
JF
7734 if (!bootstrap_)
7735 [underlay_ addSubview:overlay_];
7736
7737 [self reloadData];
7738
6932575e 7739 [self sectionsView];
e25e221f 7740 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
e25e221f
JF
7741 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7742
faf4eb4f
JF
7743 manage_ = (ManageView *) [[self
7744 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7745 withClass:[ManageView class]
7746 ] retain];
7747
b452841e
JF
7748 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7749 [details_ addObject:[self _packageView]];
7750 [details_ addObject:[self _packageView]];
6932575e 7751
3bddda52
JF
7752 PrintTimes();
7753
df5a7529
JF
7754 if (bootstrap_)
7755 [self bootstrap];
e057ec05 7756 else
e25e221f 7757 [self _setHomePage];
686e302f
JF
7758}
7759
d210b85d 7760- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
a5dd312c
JF
7761 NSString *context([sheet context]);
7762
775699a7
JF
7763 if ([context isEqualToString:@"missing"])
7764 [sheet dismiss];
3ff1504e
JF
7765 else if ([context isEqualToString:@"cancel"]) {
7766 bool clear;
7767
7768 switch (button) {
7769 case 1:
7770 clear = false;
7771 break;
7772
7773 case 2:
7774 clear = true;
7775 break;
7776
7777 default:
7778 _assert(false);
7779 }
7780
7781 [sheet dismiss];
7782
7783 @synchronized (self) {
7784 if (clear)
7785 [self _reloadData];
7786 else {
7787 Queuing_ = true;
6932575e 7788 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
3ff1504e
JF
7789 [book_ reloadData];
7790 }
7791
7792 if (confirm_ != nil) {
7793 [confirm_ release];
7794 confirm_ = nil;
7795 }
7796 }
7797 } else if ([context isEqualToString:@"fixhalf"]) {
faf4eb4f
JF
7798 switch (button) {
7799 case 1:
7800 @synchronized (self) {
9fdd37d0 7801 for (Package *broken in broken_) {
faf4eb4f
JF
7802 [broken remove];
7803
7804 NSString *id = [broken id];
7805 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7806 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7807 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7808 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7809 }
7810
7811 [self resolve];
7812 [self perform];
7813 }
7814 break;
7815
7816 case 2:
7817 [broken_ removeAllObjects];
7818 [self _loaded];
7819 break;
7820
7821 default:
7822 _assert(false);
7823 }
a5dd312c
JF
7824
7825 [sheet dismiss];
7826 } else if ([context isEqualToString:@"role"]) {
faf4eb4f
JF
7827 switch (button) {
7828 case 1: Role_ = @"User"; break;
7829 case 2: Role_ = @"Hacker"; break;
7830 case 3: Role_ = @"Developer"; break;
7831
7832 default:
7833 Role_ = nil;
7834 _assert(false);
7835 }
7836
7837 bool reset = Settings_ != nil;
7838
7839 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7840 Role_, @"Role",
7841 nil];
7842
7843 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7844
7845 Changed_ = true;
7846
7847 if (reset)
7848 [self updateData];
7849 else
7850 [self finish];
a5dd312c
JF
7851
7852 [sheet dismiss];
7853 } else if ([context isEqualToString:@"upgrade"]) {
faf4eb4f
JF
7854 switch (button) {
7855 case 1:
7856 @synchronized (self) {
9fdd37d0 7857 for (Package *essential in essential_)
faf4eb4f 7858 [essential install];
faf4eb4f
JF
7859
7860 [self resolve];
7861 [self perform];
7862 }
7863 break;
7864
7865 case 2:
f464053e
JF
7866 [self distUpgrade];
7867 break;
7868
7869 case 3:
faf4eb4f
JF
7870 Ignored_ = YES;
7871 break;
7872
7873 default:
7874 _assert(false);
7875 }
7876
a5dd312c
JF
7877 [sheet dismiss];
7878 }
faf4eb4f
JF
7879}
7880
f464053e 7881- (void) reorganize { _pooled
56fd24ea
JF
7882 system("/usr/libexec/cydia/free.sh");
7883 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
b26eb97d
JF
7884}
7885
7886- (void) applicationSuspend:(__GSEvent *)event {
7887 if (hud_ == nil && ![progress_ isRunning])
7888 [super applicationSuspend:event];
b26eb97d
JF
7889}
7890
fa7bb92f
JF
7891- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7892 if (hud_ == nil)
7893 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7894}
7895
7896- (void) _setSuspended:(BOOL)value {
7897 if (hud_ == nil)
7898 [super _setSuspended:value];
7899}
7900
faf4eb4f 7901- (UIProgressHUD *) addProgressHUD {
7398a389
JF
7902 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7903 [window_ setUserInteractionEnabled:NO];
faf4eb4f 7904 [hud show:YES];
7398a389 7905 [progress_ addSubview:hud];
faf4eb4f
JF
7906 return hud;
7907}
7908
7398a389
JF
7909- (void) removeProgressHUD:(UIProgressHUD *)hud {
7910 [hud show:NO];
7911 [hud removeFromSuperview];
7912 [window_ setUserInteractionEnabled:YES];
7913}
7914
cb9c2100 7915- (void) openMailToURL:(NSURL *)url {
56e10908
JF
7916// XXX: this makes me sad
7917#if 0
cb9c2100 7918 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
56e10908 7919#else
a99d2808 7920 [UIApp openURL:url];// asPanel:YES];
56e10908 7921#endif
cb9c2100
JF
7922}
7923
ec32cb10
JF
7924- (void) clearFirstResponder {
7925 if (id responder = [window_ firstResponder])
7926 [responder resignFirstResponder];
7927}
7928
cb9c2100
JF
7929- (RVPage *) pageForPackage:(NSString *)name {
7930 if (Package *package = [database_ packageWithName:name]) {
6932575e 7931 PackageView *view([self packageView]);
cb9c2100
JF
7932 [view setPackage:package];
7933 return view;
7934 } else {
7935 UIActionSheet *sheet = [[[UIActionSheet alloc]
6932575e
JF
7936 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7937 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
cb9c2100
JF
7938 defaultButtonIndex:0
7939 delegate:self
7940 context:@"missing"
7941 ] autorelease];
7942
6932575e 7943 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
cb9c2100
JF
7944
7945 [sheet popupAlertAnimated:YES];
7946 return nil;
7947 }
7948}
7949
7950- (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
cb9c2100
JF
7951 if (tag != NULL)
7952 tag = 0;
7953
2dfc46f7
JF
7954 NSString *scheme([[url scheme] lowercaseString]);
7955 if (![scheme isEqualToString:@"cydia"])
7956 return nil;
7957 NSString *path([url absoluteString]);
7958 if ([path length] < 8)
7959 return nil;
7960 path = [path substringFromIndex:8];
7961 if (![path hasPrefix:@"/"])
7962 path = [@"/" stringByAppendingString:path];
7963
7964 if ([path isEqualToString:@"/add-source"])
cb9c2100 7965 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
2dfc46f7 7966 else if ([path isEqualToString:@"/storage"])
cc6c8601 7967 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
2dfc46f7 7968 else if ([path isEqualToString:@"/sources"])
cb9c2100 7969 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
2dfc46f7 7970 else if ([path isEqualToString:@"/packages"])
cb9c2100 7971 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
2dfc46f7
JF
7972 else if ([path hasPrefix:@"/url/"])
7973 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7974 else if ([path hasPrefix:@"/launch/"])
7975 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7976 else if ([path hasPrefix:@"/package-settings/"])
7977 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7978 else if ([path hasPrefix:@"/package-signature/"])
7979 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7980 else if ([path hasPrefix:@"/package/"])
7981 return [self pageForPackage:[path substringFromIndex:9]];
7982 else if ([path hasPrefix:@"/files/"]) {
7983 NSString *name = [path substringFromIndex:7];
cb9c2100
JF
7984
7985 if (Package *package = [database_ packageWithName:name]) {
7986 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7987 [files setPackage:package];
7988 return files;
7989 }
7990 }
7991
7992 return nil;
7993}
7994
7995- (void) applicationOpenURL:(NSURL *)url {
7996 [super applicationOpenURL:url];
7997 int tag;
7998 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7999 [self setPage:page];
8000 [buttonbar_ showSelectionForButton:tag];
8001 tag_ = tag;
8002 }
8003}
8004
b26eb97d 8005- (void) applicationDidFinishLaunching:(id)unused {
b7ad9c68 8006 _trace();
5e563e79
JF
8007 Font12_ = [[UIFont systemFontOfSize:12] retain];
8008 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8009 Font14_ = [[UIFont systemFontOfSize:14] retain];
8010 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8011 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8012
b26eb97d
JF
8013 tag_ = 1;
8014
8015 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8016 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8017
dbe0f181
JF
8018 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8019
b26eb97d
JF
8020 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8021 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8022
5e563e79
JF
8023 [window_ orderFront:self];
8024 [window_ makeKey:self];
cb9c2100 8025 [window_ setHidden:NO];
b26eb97d 8026
dbe0f181 8027 database_ = [Database sharedInstance];
b26eb97d
JF
8028 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8029 [database_ setDelegate:progress_];
8030 [window_ setContentView:progress_];
8031
8032 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8033 [progress_ setContentView:underlay_];
8034
8035 [progress_ resetView];
8036
fa7bb92f 8037 if (
b26eb97d 8038 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
b26eb97d 8039 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
fa7bb92f
JF
8040 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8041 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8042 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
4d2ac731
JF
8043 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8044 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
b26eb97d 8045 ) {
03a2893d
JF
8046 [self setIdleTimerDisabled:YES];
8047
7398a389 8048 hud_ = [[self addProgressHUD] retain];
a5dd312c 8049 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
b26eb97d
JF
8050
8051 [self setStatusBarShowsProgress:YES];
8052
8053 [NSThread
8054 detachNewThreadSelector:@selector(reorganize)
8055 toTarget:self
8056 withObject:nil
8057 ];
fa7bb92f 8058 } else
b26eb97d
JF
8059 [self finish];
8060}
8061
686e302f 8062- (void) showKeyboard:(BOOL)show {
59efd93a
JF
8063 CGSize keysize = [UIKeyboard defaultSize];
8064 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8065 CGRect keyup = keydown;
8066 keyup.origin.y -= keysize.height;
8067
8068 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8069 [animation setSignificantRectFields:2];
8070
8071 if (show) {
8072 [animation setStartFrame:keydown];
8073 [animation setEndFrame:keyup];
8074 [keyboard_ activate];
8075 } else {
8076 [animation setStartFrame:keyup];
8077 [animation setEndFrame:keydown];
8078 [keyboard_ deactivate];
8079 }
8080
8081 [[UIAnimator sharedAnimator]
8082 addAnimations:[NSArray arrayWithObjects:animation, nil]
2a987aa5 8083 withDuration:KeyboardTime_
59efd93a
JF
8084 start:YES
8085 ];
a75f53e7
JF
8086}
8087
d210b85d 8088- (void) slideUp:(UIActionSheet *)alert {
d72d91aa
JF
8089 if (Advanced_)
8090 [alert presentSheetFromButtonBar:buttonbar_];
8091 else
8092 [alert presentSheetInView:overlay_];
e057ec05
JF
8093}
8094
a75f53e7
JF
8095@end
8096
f464053e 8097void AddPreferences(NSString *plist) { _pooled
686e302f
JF
8098 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8099 _assert(settings != NULL);
8100 NSMutableArray *items = [settings objectForKey:@"items"];
8101
8102 bool cydia(false);
8103
9fdd37d0 8104 for (NSMutableDictionary *item in items) {
686e302f
JF
8105 NSString *label = [item objectForKey:@"label"];
8106 if (label != nil && [label isEqualToString:@"Cydia"]) {
8107 cydia = true;
8108 break;
8109 }
8110 }
8111
8112 if (!cydia) {
8113 for (size_t i(0); i != [items count]; ++i) {
8114 NSDictionary *item([items objectAtIndex:i]);
8115 NSString *label = [item objectForKey:@"label"];
8116 if (label != nil && [label isEqualToString:@"General"]) {
8117 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8118 @"CydiaSettings", @"bundle",
8119 @"PSLinkCell", @"cell",
8120 [NSNumber numberWithBool:YES], @"hasIcon",
8121 [NSNumber numberWithBool:YES], @"isController",
8122 @"Cydia", @"label",
8123 nil] atIndex:(i + 1)];
8124
8125 break;
8126 }
8127 }
8128
8129 _assert([settings writeToFile:plist atomically:YES] == YES);
8130 }
686e302f
JF
8131}
8132
8133/*IMP alloc_;
8134id Alloc_(id self, SEL selector) {
8135 id object = alloc_(self, selector);
cb9c2100 8136 lprintf("[%s]A-%p\n", self->isa->name, object);
686e302f
JF
8137 return object;
8138}*/
8139
e057ec05
JF
8140/*IMP dealloc_;
8141id Dealloc_(id self, SEL selector) {
8142 id object = dealloc_(self, selector);
cb9c2100 8143 lprintf("[%s]D-%p\n", self->isa->name, object);
e057ec05
JF
8144 return object;
8145}*/
686e302f 8146
6932575e
JF
8147Class $WebDefaultUIKitDelegate;
8148
8149void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8150
8151void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8152 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8153 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8154 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8155}
8156
f464053e 8157int main(int argc, char *argv[]) { _pooled
7ec29c77 8158 _trace();
6932575e 8159
dd9390c5 8160 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
43b742af 8161
3e3977a2
JF
8162 /* Library Hacks {{{ */
8163 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8164
8165 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8166 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8167 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8168 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8169 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8170 }
8171 /* }}} */
8172 /* Set Locale {{{ */
6932575e 8173 Locale_ = CFLocaleCopyCurrent();
bb9edf8b
JF
8174 Languages_ = [NSLocale preferredLanguages];
8175 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
f7ee98cb 8176 //NSLog(@"%@", [Languages_ description]);
bb9edf8b
JF
8177 const char *lang;
8178 if (Languages_ == nil || [Languages_ count] == 0)
8179 lang = NULL;
8180 else
8181 lang = [[Languages_ objectAtIndex:0] UTF8String];
8182 setenv("LANG", lang, true);
8183 //std::setlocale(LC_ALL, lang);
8184 NSLog(@"Setting Language: %s", lang);
3e3977a2 8185 /* }}} */
6932575e
JF
8186
8187 // XXX: apr_app_initialize?
8188 apr_initialize();
8189
3e3977a2 8190 /* Parse Arguments {{{ */
64da7a2f
JF
8191 bool substrate(false);
8192
8193 if (argc != 0) {
8194 char **args(argv);
8195 int arge(1);
8196
8197 for (int argi(1); argi != argc; ++argi)
8198 if (strcmp(argv[argi], "--") == 0) {
8199 arge = argi;
8200 argv[argi] = argv[0];
8201 argv += argi;
8202 argc -= argi;
8203 break;
8204 }
8205
8206 for (int argi(1); argi != arge; ++argi)
8207 if (strcmp(args[argi], "--bootstrap") == 0)
8208 bootstrap_ = true;
8209 else if (strcmp(args[argi], "--substrate") == 0)
8210 substrate = true;
8211 else
8212 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8213 }
3e3977a2 8214 /* }}} */
0039464f
JF
8215
8216 {
8217 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8218 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8219 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8220 Sounds_Keyboard_ = [keyboard boolValue];
8221 }
8222
3e3977a2
JF
8223 App_ = [[NSBundle mainBundle] bundlePath];
8224 Home_ = NSHomeDirectory();
8225
686e302f
JF
8226 setuid(0);
8227 setgid(0);
8228
8229 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8230 alloc_ = alloc->method_imp;
8231 alloc->method_imp = (IMP) &Alloc_;*/
8232
e057ec05
JF
8233 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8234 dealloc_ = dealloc->method_imp;
8235 dealloc->method_imp = (IMP) &Dealloc_;*/
8236
2d28b35a 8237 size_t size;
cb9c2100
JF
8238
8239 int maxproc;
8240 size = sizeof(maxproc);
8241 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8242 perror("sysctlbyname(\"kern.maxproc\", ?)");
8243 else if (maxproc < 64) {
8244 maxproc = 64;
8245 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8246 perror("sysctlbyname(\"kern.maxproc\", #)");
8247 }
8248
2d28b35a
JF
8249 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8250 char *machine = new char[size];
cb9c2100
JF
8251 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8252 perror("sysctlbyname(\"hw.machine\", ?)");
8253 else
8254 Machine_ = machine;
2d28b35a 8255
2cb68ddf 8256 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
2d28b35a 8257
68c05606
JF
8258 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8259 Build_ = [system objectForKey:@"ProductBuildVersion"];
7b00c562
JF
8260 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8261 Product_ = [info objectForKey:@"SafariProductVersion"];
8262 Safari_ = [info objectForKey:@"CFBundleVersion"];
8263 }
68c05606 8264
ec5624fe
JF
8265 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8266 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
686e302f 8267
3e3977a2 8268 /* Load Database {{{ */
7ec29c77 8269 _trace();
6932575e
JF
8270 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8271 _trace();
8272 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
7ec29c77
JF
8273 _trace();
8274
8275 if (Metadata_ == NULL)
6932575e 8276 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
fa7bb92f 8277 else {
faf4eb4f
JF
8278 Settings_ = [Metadata_ objectForKey:@"Settings"];
8279
686e302f 8280 Packages_ = [Metadata_ objectForKey:@"Packages"];
fa7bb92f 8281 Sections_ = [Metadata_ objectForKey:@"Sections"];
faf4eb4f
JF
8282 Sources_ = [Metadata_ objectForKey:@"Sources"];
8283 }
8284
8285 if (Settings_ != nil)
8286 Role_ = [Settings_ objectForKey:@"Role"];
8287
8288 if (Packages_ == nil) {
8289 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8290 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8291 }
8292
8293 if (Sections_ == nil) {
8294 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8295 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8296 }
8297
8298 if (Sources_ == nil) {
8299 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8300 [Metadata_ setObject:Sources_ forKey:@"Sources"];
fa7bb92f 8301 }
3e3977a2 8302 /* }}} */
686e302f 8303
f464053e 8304#if RecycleWebViews
87c76914 8305 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
f464053e 8306#endif
87c76914 8307
8944281a
JF
8308 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8309 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8310 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8311 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
1eb0c554 8312
7ec29c77
JF
8313 if (access("/User", F_OK) != 0) {
8314 _trace();
6a0db335 8315 system("/usr/libexec/cydia/firmware.sh");
7ec29c77
JF
8316 _trace();
8317 }
63a1e4b8 8318
2cb68ddf
JF
8319 _assert([[NSFileManager defaultManager]
8320 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8321 withIntermediateDirectories:YES
8322 attributes:nil
8323 error:NULL
8324 ]);
8325
3e3977a2
JF
8326 if (access("/tmp/cydia.chk", F_OK) == 0) {
8327 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8328 _assert(errno == ENOENT);
8329 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8330 _assert(errno == ENOENT);
8331 }
8332
bb9edf8b
JF
8333 _assert(pkgInitConfig(*_config));
8334 _assert(pkgInitSystem(*_config, _system));
8335
8336 if (lang != NULL)
8337 _config->Set("APT::Acquire::Translation", lang);
43b742af
JF
8338 _config->Set("Acquire::http::Timeout", 15);
8339 _config->Set("Acquire::http::MaxParallel", 4);
bb9edf8b 8340
3e3977a2 8341 /* Color Choices {{{ */
e057ec05
JF
8342 space_ = CGColorSpaceCreateDeviceRGB();
8343
5e563e79 8344 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
d72d91aa 8345 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
e057ec05 8346 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
87c76914 8347 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
e057ec05 8348 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
faf4eb4f 8349 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
d8d9a65c
JF
8350 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8351 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8352 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8353 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8354 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8355 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8356 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8357 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8358 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8359
3ff1504e
JF
8360//.93
8361 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8362 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
3e3977a2 8363 /* }}}*/
faf4eb4f 8364
03d01f0e
JF
8365 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8366
3e3977a2 8367 /* UIKit Configuration {{{ */
6932575e
JF
8368 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8369 if ($GSFontSetUseLegacyFontMetrics != NULL)
8370 $GSFontSetUseLegacyFontMetrics(YES);
faf4eb4f 8371
2cb68ddf 8372 UIKeyboardDisableAutomaticAppearance();
3e3977a2 8373 /* }}} */
2cb68ddf 8374
7ec29c77 8375 _trace();
d210b85d 8376 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
e057ec05
JF
8377
8378 CGColorSpaceRelease(space_);
b27f0a94 8379 CFRelease(Locale_);
e057ec05 8380
e057ec05 8381 return value;
a75f53e7 8382}