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