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