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