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