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