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