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