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