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