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