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