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