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