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