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