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