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