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