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