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