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