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