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