]> git.saurik.com Git - cydia.git/blob - Cydia.mm
Minor tweaks.
[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 CFStringRef StripVersion(const char *version) {
1142 const char *colon(strchr(version, ':'));
1143 if (colon != NULL)
1144 version = colon + 1;
1145 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
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_ = (NSString *) StripVersion(version_.VerStr());
2042 _end
2043
2044 pkgCache::VerIterator current;
2045 _profile(Package$initWithVersion$Versions)
2046 current = iterator_.CurrentVer();
2047 if (!current.end())
2048 installed_ = (NSString *) StripVersion(current.VerStr());
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_;
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 [packages_ removeAllObjects];
3105 sources_.clear();
3106
3107 _error->Discard();
3108
3109 delete list_;
3110 list_ = NULL;
3111 manager_ = NULL;
3112 delete lock_;
3113 lock_ = NULL;
3114 delete fetcher_;
3115 fetcher_ = NULL;
3116 delete resolver_;
3117 resolver_ = NULL;
3118 delete records_;
3119 records_ = NULL;
3120 delete policy_;
3121 policy_ = NULL;
3122
3123 if (now_ != nil) {
3124 [now_ release];
3125 now_ = nil;
3126 }
3127
3128 cache_.Close();
3129
3130 apr_pool_clear(pool_);
3131 NSRecycleZone(zone_);
3132
3133 int chk(creat("/tmp/cydia.chk", 0644));
3134 if (chk != -1)
3135 close(chk);
3136
3137 _trace();
3138 if (!cache_.Open(progress_, true)) {
3139 std::string error;
3140 if (!_error->PopMessage(error))
3141 _assert(false);
3142 _error->Discard();
3143 lprintf("cache_.Open():[%s]\n", error.c_str());
3144
3145 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3146 [delegate_ repairWithSelector:@selector(configure)];
3147 else if (error == "The package lists or status file could not be parsed or opened.")
3148 [delegate_ repairWithSelector:@selector(update)];
3149 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3150 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3151 // else if (error == "The list of sources could not be read.")
3152 else _assert(false);
3153
3154 return;
3155 }
3156 _trace();
3157
3158 unlink("/tmp/cydia.chk");
3159
3160 now_ = [[NSDate date] retain];
3161
3162 policy_ = new pkgDepCache::Policy();
3163 records_ = new pkgRecords(cache_);
3164 resolver_ = new pkgProblemResolver(cache_);
3165 fetcher_ = new pkgAcquire(&status_);
3166 lock_ = NULL;
3167
3168 list_ = new pkgSourceList();
3169 _assert(list_->ReadMainList());
3170
3171 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3172 _assert(pkgApplyStatus(cache_));
3173
3174 if (cache_->BrokenCount() != 0) {
3175 _assert(pkgFixBroken(cache_));
3176 _assert(cache_->BrokenCount() == 0);
3177 _assert(pkgMinimizeUpgrade(cache_));
3178 }
3179
3180 _trace();
3181
3182 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3183 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3184 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3185 // XXX: this could be more intelligent
3186 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3187 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3188 if (!cached.end())
3189 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source] autorelease];
3190 }
3191 }
3192
3193 _trace();
3194
3195 {
3196 /*std::vector<Package *> packages;
3197 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3198 [packages_ release];
3199 packages_ = nil;*/
3200
3201 _trace();
3202
3203 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3204 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3205 //packages.push_back(package);
3206 [packages_ addObject:package];
3207
3208 _trace();
3209
3210 /*if (packages.empty())
3211 packages_ = [[NSArray alloc] init];
3212 else
3213 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3214 _trace();*/
3215
3216 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3217 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3218 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3219
3220 /*_trace();
3221 PrintTimes();
3222 _trace();*/
3223
3224 _trace();
3225
3226 /*if (!packages.empty())
3227 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3228 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3229
3230 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3231
3232 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3233
3234 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3235
3236 _trace();
3237 }
3238 }
3239
3240 - (void) configure {
3241 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3242 system([dpkg UTF8String]);
3243 }
3244
3245 - (void) clean {
3246 if (lock_ != NULL)
3247 return;
3248
3249 FileFd Lock;
3250 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3251 _assert(!_error->PendingError());
3252
3253 pkgAcquire fetcher;
3254 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3255
3256 class LogCleaner :
3257 public pkgArchiveCleaner
3258 {
3259 protected:
3260 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3261 unlink(File);
3262 }
3263 } cleaner;
3264
3265 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3266 std::string error;
3267 while (_error->PopMessage(error))
3268 lprintf("ArchiveCleaner: %s\n", error.c_str());
3269 }
3270 }
3271
3272 - (void) prepare {
3273 pkgRecords records(cache_);
3274
3275 lock_ = new FileFd();
3276 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3277 _assert(!_error->PendingError());
3278
3279 pkgSourceList list;
3280 // XXX: explain this with an error message
3281 _assert(list.ReadMainList());
3282
3283 manager_ = (_system->CreatePM(cache_));
3284 _assert(manager_->GetArchives(fetcher_, &list, &records));
3285 _assert(!_error->PendingError());
3286 }
3287
3288 - (void) perform {
3289 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3290 pkgSourceList list;
3291 _assert(list.ReadMainList());
3292 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3293 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3294 }
3295
3296 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3297 _trace();
3298 return;
3299 }
3300
3301 bool failed = false;
3302 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3303 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3304 continue;
3305
3306 std::string uri = (*item)->DescURI();
3307 std::string error = (*item)->ErrorText;
3308
3309 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3310 failed = true;
3311
3312 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3313 withObject:[NSArray arrayWithObjects:
3314 [NSString stringWithUTF8String:error.c_str()],
3315 nil]
3316 waitUntilDone:YES
3317 ];
3318 }
3319
3320 if (failed) {
3321 _trace();
3322 return;
3323 }
3324
3325 _system->UnLock();
3326 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3327
3328 if (_error->PendingError()) {
3329 _trace();
3330 return;
3331 }
3332
3333 if (result == pkgPackageManager::Failed) {
3334 _trace();
3335 return;
3336 }
3337
3338 if (result != pkgPackageManager::Completed) {
3339 _trace();
3340 return;
3341 }
3342
3343 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3344 pkgSourceList list;
3345 _assert(list.ReadMainList());
3346 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3347 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3348 }
3349
3350 if (![before isEqualToArray:after])
3351 [self update];
3352 }
3353
3354 - (void) upgrade {
3355 _assert(pkgDistUpgrade(cache_));
3356 }
3357
3358 - (void) update {
3359 [self updateWithStatus:status_];
3360 }
3361
3362 - (void) updateWithStatus:(Status &)status {
3363 pkgSourceList list;
3364 _assert(list.ReadMainList());
3365
3366 FileFd lock;
3367 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3368 _assert(!_error->PendingError());
3369
3370 pkgAcquire fetcher(&status);
3371 _assert(list.GetIndexes(&fetcher));
3372
3373 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3374 bool failed = false;
3375 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3376 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3377 (*item)->Finished();
3378 failed = true;
3379 }
3380
3381 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3382 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3383 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3384 }
3385
3386 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3387 Changed_ = true;
3388 }
3389 }
3390
3391 - (void) setDelegate:(id)delegate {
3392 delegate_ = delegate;
3393 status_.setDelegate(delegate);
3394 progress_.setDelegate(delegate);
3395 }
3396
3397 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3398 return sources_[file->ID];
3399 }
3400
3401 @end
3402 /* }}} */
3403
3404 /* PopUp Windows {{{ */
3405 @interface PopUpView : UIView {
3406 _transient id delegate_;
3407 UITransitionView *transition_;
3408 UIView *overlay_;
3409 }
3410
3411 - (void) cancel;
3412 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3413
3414 @end
3415
3416 @implementation PopUpView
3417
3418 - (void) dealloc {
3419 [transition_ setDelegate:nil];
3420 [transition_ release];
3421 [overlay_ release];
3422 [super dealloc];
3423 }
3424
3425 - (void) cancel {
3426 [transition_ transition:UITransitionPushFromTop toView:nil];
3427 }
3428
3429 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3430 if (from != nil && to == nil)
3431 [self removeFromSuperview];
3432 }
3433
3434 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3435 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3436 delegate_ = delegate;
3437
3438 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3439 [self addSubview:transition_];
3440
3441 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3442
3443 [view addSubview:self];
3444
3445 [transition_ setDelegate:self];
3446
3447 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3448 [transition_ transition:UITransitionNone toView:blank];
3449 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3450 } return self;
3451 }
3452
3453 @end
3454 /* }}} */
3455
3456 #if 0
3457 /* Mail Composition {{{ */
3458 @interface MailToView : PopUpView {
3459 MailComposeController *controller_;
3460 }
3461
3462 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3463
3464 @end
3465
3466 @implementation MailToView
3467
3468 - (void) dealloc {
3469 [controller_ release];
3470 [super dealloc];
3471 }
3472
3473 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3474 NSLog(@"will");
3475 }
3476
3477 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3478 NSLog(@"did:%@", delivery);
3479 // [UIApp setStatusBarShowsProgress:NO];
3480 if ([controller error]){
3481 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3482 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3483 [mailAlertSheet setBodyText:[controller error]];
3484 [mailAlertSheet popupAlertAnimated:YES];
3485 }
3486 }
3487
3488 - (void) showError {
3489 NSLog(@"%@", [controller_ error]);
3490 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3491 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3492 [mailAlertSheet setBodyText:[controller_ error]];
3493 [mailAlertSheet popupAlertAnimated:YES];
3494 }
3495
3496 - (void) deliverMessage { _pooled
3497 setuid(501);
3498 setgid(501);
3499
3500 if (![controller_ deliverMessage])
3501 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3502 }
3503
3504 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3505 if ([controller_ needsDelivery])
3506 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3507 else
3508 [self cancel];
3509 }
3510
3511 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3512 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3513 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3514 [controller_ setDelegate:self];
3515 [controller_ initializeUI];
3516 [controller_ setupForURL:url];
3517
3518 UIView *view([controller_ view]);
3519 [overlay_ addSubview:view];
3520 } return self;
3521 }
3522
3523 @end
3524 /* }}} */
3525 #endif
3526
3527 /* Confirmation View {{{ */
3528 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3529 if (!iterator.end())
3530 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3531 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3532 continue;
3533 pkgCache::PkgIterator package(dep.TargetPkg());
3534 if (package.end())
3535 continue;
3536 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3537 return true;
3538 }
3539
3540 return false;
3541 }
3542
3543 @protocol ConfirmationViewDelegate
3544 - (void) cancel;
3545 - (void) confirm;
3546 - (void) queue;
3547 @end
3548
3549 @interface ConfirmationView : BrowserView {
3550 _transient Database *database_;
3551 UIActionSheet *essential_;
3552 NSArray *changes_;
3553 NSArray *issues_;
3554 NSArray *sizes_;
3555 BOOL substrate_;
3556 }
3557
3558 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3559
3560 @end
3561
3562 @implementation ConfirmationView
3563
3564 - (void) dealloc {
3565 [changes_ release];
3566 if (issues_ != nil)
3567 [issues_ release];
3568 [sizes_ release];
3569 if (essential_ != nil)
3570 [essential_ release];
3571 [super dealloc];
3572 }
3573
3574 - (void) cancel {
3575 [delegate_ cancel];
3576 [book_ popFromSuperviewAnimated:YES];
3577 }
3578
3579 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3580 NSString *context([sheet context]);
3581
3582 if ([context isEqualToString:@"remove"]) {
3583 switch (button) {
3584 case 1:
3585 [self cancel];
3586 break;
3587 case 2:
3588 if (substrate_)
3589 Finish_ = 2;
3590 [delegate_ confirm];
3591 break;
3592 default:
3593 _assert(false);
3594 }
3595
3596 [sheet dismiss];
3597 } else if ([context isEqualToString:@"unable"]) {
3598 [self cancel];
3599 [sheet dismiss];
3600 } else
3601 [super alertSheet:sheet buttonClicked:button];
3602 }
3603
3604 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3605 [super webView:sender didClearWindowObject:window forFrame:frame];
3606 [window setValue:changes_ forKey:@"changes"];
3607 [window setValue:issues_ forKey:@"issues"];
3608 [window setValue:sizes_ forKey:@"sizes"];
3609 }
3610
3611 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3612 if ((self = [super initWithBook:book]) != nil) {
3613 database_ = database;
3614
3615 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3616 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3617 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3618 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3619 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3620
3621 bool remove(false);
3622
3623 pkgDepCache::Policy *policy([database_ policy]);
3624
3625 pkgCacheFile &cache([database_ cache]);
3626 NSArray *packages = [database_ packages];
3627 for (Package *package in packages) {
3628 pkgCache::PkgIterator iterator = [package iterator];
3629 pkgDepCache::StateCache &state(cache[iterator]);
3630
3631 NSString *name([package name]);
3632
3633 if (state.NewInstall())
3634 [installing addObject:name];
3635 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3636 [reinstalling addObject:name];
3637 else if (state.Upgrade())
3638 [upgrading addObject:name];
3639 else if (state.Downgrade())
3640 [downgrading addObject:name];
3641 else if (state.Delete()) {
3642 if ([package essential])
3643 remove = true;
3644 [removing addObject:name];
3645 } else continue;
3646
3647 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3648 substrate_ |= DepSubstrate(iterator.CurrentVer());
3649 }
3650
3651 if (!remove)
3652 essential_ = nil;
3653 else if (Advanced_ || true) {
3654 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3655
3656 essential_ = [[UIActionSheet alloc]
3657 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3658 buttons:[NSArray arrayWithObjects:
3659 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3660 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3661 nil]
3662 defaultButtonIndex:0
3663 delegate:self
3664 context:@"remove"
3665 ];
3666
3667 #ifndef __OBJC2__
3668 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3669 #endif
3670 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3671 } else {
3672 essential_ = [[UIActionSheet alloc]
3673 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3674 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3675 defaultButtonIndex:0
3676 delegate:self
3677 context:@"unable"
3678 ];
3679
3680 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3681 }
3682
3683 changes_ = [[NSArray alloc] initWithObjects:
3684 installing,
3685 reinstalling,
3686 upgrading,
3687 downgrading,
3688 removing,
3689 nil];
3690
3691 issues_ = [database_ issues];
3692 if (issues_ != nil)
3693 issues_ = [issues_ retain];
3694
3695 sizes_ = [[NSArray alloc] initWithObjects:
3696 SizeString([database_ fetcher].FetchNeeded()),
3697 SizeString([database_ fetcher].PartialPresent()),
3698 SizeString([database_ cache]->UsrSize()),
3699 nil];
3700
3701 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3702 } return self;
3703 }
3704
3705 - (NSString *) backButtonTitle {
3706 return CYLocalize("CONFIRM");
3707 }
3708
3709 - (NSString *) leftButtonTitle {
3710 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3711 }
3712
3713 - (id) rightButtonTitle {
3714 return issues_ != nil ? nil : [super rightButtonTitle];
3715 }
3716
3717 - (id) _rightButtonTitle {
3718 #if AlwaysReload || IgnoreInstall
3719 return [super _rightButtonTitle];
3720 #else
3721 return CYLocalize("CONFIRM");
3722 #endif
3723 }
3724
3725 - (void) _leftButtonClicked {
3726 [self cancel];
3727 }
3728
3729 #if !AlwaysReload
3730 - (void) _rightButtonClicked {
3731 #if IgnoreInstall
3732 return [super _rightButtonClicked];
3733 #endif
3734 if (essential_ != nil)
3735 [essential_ popupAlertAnimated:YES];
3736 else {
3737 if (substrate_)
3738 Finish_ = 2;
3739 [delegate_ confirm];
3740 }
3741 }
3742 #endif
3743
3744 @end
3745 /* }}} */
3746
3747 /* Progress Data {{{ */
3748 @interface ProgressData : NSObject {
3749 SEL selector_;
3750 id target_;
3751 id object_;
3752 }
3753
3754 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3755
3756 - (SEL) selector;
3757 - (id) target;
3758 - (id) object;
3759 @end
3760
3761 @implementation ProgressData
3762
3763 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3764 if ((self = [super init]) != nil) {
3765 selector_ = selector;
3766 target_ = target;
3767 object_ = object;
3768 } return self;
3769 }
3770
3771 - (SEL) selector {
3772 return selector_;
3773 }
3774
3775 - (id) target {
3776 return target_;
3777 }
3778
3779 - (id) object {
3780 return object_;
3781 }
3782
3783 @end
3784 /* }}} */
3785 /* Progress View {{{ */
3786 @interface ProgressView : UIView <
3787 ConfigurationDelegate,
3788 ProgressDelegate
3789 > {
3790 _transient Database *database_;
3791 UIView *view_;
3792 UIView *background_;
3793 UITransitionView *transition_;
3794 UIView *overlay_;
3795 UINavigationBar *navbar_;
3796 UIProgressBar *progress_;
3797 UITextView *output_;
3798 UITextLabel *status_;
3799 UIPushButton *close_;
3800 id delegate_;
3801 BOOL running_;
3802 SHA1SumValue springlist_;
3803 SHA1SumValue notifyconf_;
3804 SHA1SumValue sandplate_;
3805 }
3806
3807 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3808
3809 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3810 - (void) setContentView:(UIView *)view;
3811 - (void) resetView;
3812
3813 - (void) _retachThread;
3814 - (void) _detachNewThreadData:(ProgressData *)data;
3815 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3816
3817 - (BOOL) isRunning;
3818
3819 @end
3820
3821 @protocol ProgressViewDelegate
3822 - (void) progressViewIsComplete:(ProgressView *)sender;
3823 @end
3824
3825 @implementation ProgressView
3826
3827 - (void) dealloc {
3828 [transition_ setDelegate:nil];
3829 [navbar_ setDelegate:nil];
3830
3831 [view_ release];
3832 if (background_ != nil)
3833 [background_ release];
3834 [transition_ release];
3835 [overlay_ release];
3836 [navbar_ release];
3837 [progress_ release];
3838 [output_ release];
3839 [status_ release];
3840 [close_ release];
3841 [super dealloc];
3842 }
3843
3844 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3845 if (bootstrap_ && from == overlay_ && to == view_)
3846 exit(0);
3847 }
3848
3849 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3850 if ((self = [super initWithFrame:frame]) != nil) {
3851 database_ = database;
3852 delegate_ = delegate;
3853
3854 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3855 [transition_ setDelegate:self];
3856
3857 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3858
3859 if (bootstrap_)
3860 [overlay_ setBackgroundColor:[UIColor blackColor]];
3861 else {
3862 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3863 [background_ setBackgroundColor:[UIColor blackColor]];
3864 [self addSubview:background_];
3865 }
3866
3867 [self addSubview:transition_];
3868
3869 CGSize navsize = [UINavigationBar defaultSize];
3870 CGRect navrect = {{0, 0}, navsize};
3871
3872 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3873 [overlay_ addSubview:navbar_];
3874
3875 [navbar_ setBarStyle:1];
3876 [navbar_ setDelegate:self];
3877
3878 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3879 [navbar_ pushNavigationItem:navitem];
3880
3881 CGRect bounds = [overlay_ bounds];
3882 CGSize prgsize = [UIProgressBar defaultSize];
3883
3884 CGRect prgrect = {{
3885 (bounds.size.width - prgsize.width) / 2,
3886 bounds.size.height - prgsize.height - 20
3887 }, prgsize};
3888
3889 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3890 [progress_ setStyle:0];
3891
3892 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3893 10,
3894 bounds.size.height - prgsize.height - 50,
3895 bounds.size.width - 20,
3896 24
3897 )];
3898
3899 [status_ setColor:[UIColor whiteColor]];
3900 [status_ setBackgroundColor:[UIColor clearColor]];
3901
3902 [status_ setCentersHorizontally:YES];
3903 //[status_ setFont:font];
3904 _trace();
3905
3906 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3907 10,
3908 navrect.size.height + 20,
3909 bounds.size.width - 20,
3910 bounds.size.height - navsize.height - 62 - navrect.size.height
3911 )];
3912 _trace();
3913
3914 //[output_ setTextFont:@"Courier New"];
3915 [output_ setTextSize:12];
3916
3917 [output_ setTextColor:[UIColor whiteColor]];
3918 [output_ setBackgroundColor:[UIColor clearColor]];
3919
3920 [output_ setMarginTop:0];
3921 [output_ setAllowsRubberBanding:YES];
3922 [output_ setEditable:NO];
3923
3924 [overlay_ addSubview:output_];
3925
3926 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3927 10,
3928 bounds.size.height - prgsize.height - 50,
3929 bounds.size.width - 20,
3930 32 + prgsize.height
3931 )];
3932
3933 [close_ setAutosizesToFit:NO];
3934 [close_ setDrawsShadow:YES];
3935 [close_ setStretchBackground:YES];
3936 [close_ setEnabled:YES];
3937
3938 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3939 [close_ setTitleFont:bold];
3940
3941 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3942 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3943 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3944 } return self;
3945 }
3946
3947 - (void) setContentView:(UIView *)view {
3948 view_ = [view retain];
3949 }
3950
3951 - (void) resetView {
3952 [transition_ transition:6 toView:view_];
3953 }
3954
3955 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3956 NSString *context([sheet context]);
3957
3958 if ([context isEqualToString:@"error"])
3959 [sheet dismiss];
3960 else if ([context isEqualToString:@"conffile"]) {
3961 FILE *input = [database_ input];
3962
3963 switch (button) {
3964 case 1:
3965 fprintf(input, "N\n");
3966 fflush(input);
3967 break;
3968 case 2:
3969 fprintf(input, "Y\n");
3970 fflush(input);
3971 break;
3972 default:
3973 _assert(false);
3974 }
3975
3976 [sheet dismiss];
3977 }
3978 }
3979
3980 - (void) closeButtonPushed {
3981 running_ = NO;
3982
3983 switch (Finish_) {
3984 case 0:
3985 [self resetView];
3986 break;
3987
3988 case 1:
3989 [delegate_ suspendWithAnimation:YES];
3990 break;
3991
3992 case 2:
3993 system("launchctl stop com.apple.SpringBoard");
3994 break;
3995
3996 case 3:
3997 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3998 break;
3999
4000 case 4:
4001 system("reboot");
4002 break;
4003 }
4004 }
4005
4006 - (void) _retachThread {
4007 UINavigationItem *item = [navbar_ topItem];
4008 [item setTitle:CYLocalize("COMPLETE")];
4009
4010 [overlay_ addSubview:close_];
4011 [progress_ removeFromSuperview];
4012 [status_ removeFromSuperview];
4013
4014 [delegate_ progressViewIsComplete:self];
4015
4016 if (Finish_ < 4) {
4017 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4018 MMap mmap(file, MMap::ReadOnly);
4019 SHA1Summation sha1;
4020 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4021 if (!(sandplate_ == sha1.Result()))
4022 Finish_ = 4;
4023 }
4024
4025 if (Finish_ < 4) {
4026 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4027 MMap mmap(file, MMap::ReadOnly);
4028 SHA1Summation sha1;
4029 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4030 if (!(notifyconf_ == sha1.Result()))
4031 Finish_ = 4;
4032 }
4033
4034 if (Finish_ < 3) {
4035 FileFd file(SpringBoard_, FileFd::ReadOnly);
4036 MMap mmap(file, MMap::ReadOnly);
4037 SHA1Summation sha1;
4038 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4039 if (!(springlist_ == sha1.Result()))
4040 Finish_ = 3;
4041 }
4042
4043 switch (Finish_) {
4044 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4045 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4046 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4047 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4048 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4049 }
4050
4051 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4052
4053 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4054 [cache autorelease];
4055
4056 NSFileManager *manager = [NSFileManager defaultManager];
4057 NSError *error = nil;
4058
4059 id system = [cache objectForKey:@"System"];
4060 if (system == nil)
4061 goto error;
4062
4063 struct stat info;
4064 if (stat(Cache_, &info) == -1)
4065 goto error;
4066
4067 [system removeAllObjects];
4068
4069 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4070 for (NSString *app in apps)
4071 if ([app hasSuffix:@".app"]) {
4072 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4073 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4074 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4075 [info autorelease];
4076 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4077 [info setObject:path forKey:@"Path"];
4078 [info setObject:@"System" forKey:@"ApplicationType"];
4079 [system addInfoDictionary:info];
4080 }
4081 }
4082 }
4083 } else goto error;
4084
4085 [cache writeToFile:@Cache_ atomically:YES];
4086
4087 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4088 goto error;
4089 if (chmod(Cache_, info.st_mode) == -1)
4090 goto error;
4091
4092 if (false) error:
4093 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4094 }
4095
4096 notify_post("com.apple.mobile.application_installed");
4097
4098 [delegate_ setStatusBarShowsProgress:NO];
4099 }
4100
4101 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4102 [[data target] performSelector:[data selector] withObject:[data object]];
4103 [data release];
4104
4105 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4106 }
4107
4108 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4109 UINavigationItem *item = [navbar_ topItem];
4110 [item setTitle:title];
4111
4112 [status_ setText:nil];
4113 [output_ setText:@""];
4114 [progress_ setProgress:0];
4115
4116 [close_ removeFromSuperview];
4117 [overlay_ addSubview:progress_];
4118 [overlay_ addSubview:status_];
4119
4120 [delegate_ setStatusBarShowsProgress:YES];
4121 running_ = YES;
4122
4123 {
4124 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4125 MMap mmap(file, MMap::ReadOnly);
4126 SHA1Summation sha1;
4127 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4128 sandplate_ = sha1.Result();
4129 }
4130
4131 {
4132 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4133 MMap mmap(file, MMap::ReadOnly);
4134 SHA1Summation sha1;
4135 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4136 notifyconf_ = sha1.Result();
4137 }
4138
4139 {
4140 FileFd file(SpringBoard_, FileFd::ReadOnly);
4141 MMap mmap(file, MMap::ReadOnly);
4142 SHA1Summation sha1;
4143 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4144 springlist_ = sha1.Result();
4145 }
4146
4147 [transition_ transition:6 toView:overlay_];
4148
4149 [NSThread
4150 detachNewThreadSelector:@selector(_detachNewThreadData:)
4151 toTarget:self
4152 withObject:[[ProgressData alloc]
4153 initWithSelector:selector
4154 target:target
4155 object:object
4156 ]
4157 ];
4158 }
4159
4160 - (void) repairWithSelector:(SEL)selector {
4161 [self
4162 detachNewThreadSelector:selector
4163 toTarget:database_
4164 withObject:nil
4165 title:CYLocalize("REPAIRING")
4166 ];
4167 }
4168
4169 - (void) setConfigurationData:(NSString *)data {
4170 [self
4171 performSelectorOnMainThread:@selector(_setConfigurationData:)
4172 withObject:data
4173 waitUntilDone:YES
4174 ];
4175 }
4176
4177 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4178 Package *package = id == nil ? nil : [database_ packageWithName:id];
4179
4180 UIActionSheet *sheet = [[[UIActionSheet alloc]
4181 initWithTitle:(package == nil ? id : [package name])
4182 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4183 defaultButtonIndex:0
4184 delegate:self
4185 context:@"error"
4186 ] autorelease];
4187
4188 [sheet setBodyText:error];
4189 [sheet popupAlertAnimated:YES];
4190 }
4191
4192 - (void) setProgressTitle:(NSString *)title {
4193 [self
4194 performSelectorOnMainThread:@selector(_setProgressTitle:)
4195 withObject:title
4196 waitUntilDone:YES
4197 ];
4198 }
4199
4200 - (void) setProgressPercent:(float)percent {
4201 [self
4202 performSelectorOnMainThread:@selector(_setProgressPercent:)
4203 withObject:[NSNumber numberWithFloat:percent]
4204 waitUntilDone:YES
4205 ];
4206 }
4207
4208 - (void) startProgress {
4209 }
4210
4211 - (void) addProgressOutput:(NSString *)output {
4212 [self
4213 performSelectorOnMainThread:@selector(_addProgressOutput:)
4214 withObject:output
4215 waitUntilDone:YES
4216 ];
4217 }
4218
4219 - (bool) isCancelling:(size_t)received {
4220 return false;
4221 }
4222
4223 - (void) _setConfigurationData:(NSString *)data {
4224 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4225
4226 _assert(conffile_r(data));
4227
4228 NSString *ofile = conffile_r[1];
4229 //NSString *nfile = conffile_r[2];
4230
4231 UIActionSheet *sheet = [[[UIActionSheet alloc]
4232 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4233 buttons:[NSArray arrayWithObjects:
4234 CYLocalize("KEEP_OLD_COPY"),
4235 CYLocalize("ACCEPT_NEW_COPY"),
4236 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4237 nil]
4238 defaultButtonIndex:0
4239 delegate:self
4240 context:@"conffile"
4241 ] autorelease];
4242
4243 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4244 [sheet popupAlertAnimated:YES];
4245 }
4246
4247 - (void) _setProgressTitle:(NSString *)title {
4248 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4249 for (size_t i(0), e([words count]); i != e; ++i) {
4250 NSString *word([words objectAtIndex:i]);
4251 if (Package *package = [database_ packageWithName:word])
4252 [words replaceObjectAtIndex:i withObject:[package name]];
4253 }
4254
4255 [status_ setText:[words componentsJoinedByString:@" "]];
4256 }
4257
4258 - (void) _setProgressPercent:(NSNumber *)percent {
4259 [progress_ setProgress:[percent floatValue]];
4260 }
4261
4262 - (void) _addProgressOutput:(NSString *)output {
4263 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4264 CGSize size = [output_ contentSize];
4265 CGRect rect = {{0, size.height}, {size.width, 0}};
4266 [output_ scrollRectToVisible:rect animated:YES];
4267 }
4268
4269 - (BOOL) isRunning {
4270 return running_;
4271 }
4272
4273 @end
4274 /* }}} */
4275
4276 /* Package Cell {{{ */
4277 @interface PackageCell : UITableCell {
4278 UIImage *icon_;
4279 NSString *name_;
4280 NSString *description_;
4281 bool commercial_;
4282 NSString *source_;
4283 UIImage *badge_;
4284 bool cached_;
4285 Package *package_;
4286 #ifdef USE_BADGES
4287 UITextLabel *status_;
4288 #endif
4289 }
4290
4291 - (PackageCell *) init;
4292 - (void) setPackage:(Package *)package;
4293
4294 + (int) heightForPackage:(Package *)package;
4295
4296 @end
4297
4298 @implementation PackageCell
4299
4300 - (void) clearPackage {
4301 if (icon_ != nil) {
4302 [icon_ release];
4303 icon_ = nil;
4304 }
4305
4306 if (name_ != nil) {
4307 [name_ release];
4308 name_ = nil;
4309 }
4310
4311 if (description_ != nil) {
4312 [description_ release];
4313 description_ = nil;
4314 }
4315
4316 if (source_ != nil) {
4317 [source_ release];
4318 source_ = nil;
4319 }
4320
4321 if (badge_ != nil) {
4322 [badge_ release];
4323 badge_ = nil;
4324 }
4325
4326 [package_ release];
4327 package_ = nil;
4328 }
4329
4330 - (void) dealloc {
4331 [self clearPackage];
4332 #ifdef USE_BADGES
4333 [status_ release];
4334 #endif
4335 [super dealloc];
4336 }
4337
4338 - (PackageCell *) init {
4339 if ((self = [super init]) != nil) {
4340 #ifdef USE_BADGES
4341 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4342 [status_ setBackgroundColor:[UIColor clearColor]];
4343 [status_ setFont:small];
4344 #endif
4345 } return self;
4346 }
4347
4348 - (void) setPackage:(Package *)package {
4349 [self clearPackage];
4350 [package parse];
4351
4352 Source *source = [package source];
4353
4354 icon_ = [[package icon] retain];
4355 name_ = [[package name] retain];
4356 description_ = [[package shortDescription] retain];
4357 commercial_ = [package isCommercial];
4358
4359 package_ = [package retain];
4360
4361 NSString *label = nil;
4362 bool trusted = false;
4363
4364 if (source != nil) {
4365 label = [source label];
4366 trusted = [source trusted];
4367 } else if ([[package id] isEqualToString:@"firmware"])
4368 label = CYLocalize("APPLE");
4369 else
4370 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4371
4372 NSString *from(label);
4373
4374 NSString *section = [package simpleSection];
4375 if (section != nil && ![section isEqualToString:label]) {
4376 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4377 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4378 }
4379
4380 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4381 source_ = [from retain];
4382
4383 if (NSString *purpose = [package primaryPurpose])
4384 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4385 badge_ = [badge_ retain];
4386
4387 #ifdef USE_BADGES
4388 if (NSString *mode = [package mode]) {
4389 [badge_ setImage:[UIImage applicationImageNamed:
4390 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4391 ]];
4392
4393 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4394 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4395 } else if ([package half]) {
4396 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4397 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4398 [status_ setColor:[UIColor redColor]];
4399 } else {
4400 [badge_ setImage:nil];
4401 [status_ setText:nil];
4402 }
4403 #endif
4404
4405 cached_ = false;
4406 }
4407
4408 - (void) drawRect:(CGRect)rect {
4409 if (!cached_) {
4410 UIColor *color;
4411
4412 if (NSString *mode = [package_ mode]) {
4413 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4414 color = remove ? RemovingColor_ : InstallingColor_;
4415 } else
4416 color = [UIColor whiteColor];
4417
4418 [self setBackgroundColor:color];
4419 cached_ = true;
4420 }
4421
4422 [super drawRect:rect];
4423 }
4424
4425 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4426 if (fade == 0) {
4427 CGContextRef context(UIGraphicsGetCurrentContext());
4428 [[self backgroundColor] set];
4429 CGRect back(rect);
4430 back.size.height -= 1;
4431 CGContextFillRect(context, back);
4432 }
4433
4434 [super drawBackgroundInRect:rect withFade:fade];
4435 }
4436
4437 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4438 if (icon_ != nil) {
4439 CGRect rect;
4440 rect.size = [icon_ size];
4441
4442 rect.size.width /= 2;
4443 rect.size.height /= 2;
4444
4445 rect.origin.x = 25 - rect.size.width / 2;
4446 rect.origin.y = 25 - rect.size.height / 2;
4447
4448 [icon_ drawInRect:rect];
4449 }
4450
4451 if (badge_ != nil) {
4452 CGSize size = [badge_ size];
4453
4454 [badge_ drawAtPoint:CGPointMake(
4455 36 - size.width / 2,
4456 36 - size.height / 2
4457 )];
4458 }
4459
4460 if (selected)
4461 UISetColor(White_);
4462
4463 if (!selected)
4464 UISetColor(commercial_ ? Purple_ : Black_);
4465 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4466 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4467
4468 if (!selected)
4469 UISetColor(commercial_ ? Purplish_ : Gray_);
4470 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4471
4472 [super drawContentInRect:rect selected:selected];
4473 }
4474
4475 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4476 cached_ = false;
4477 [super setSelected:selected withFade:fade];
4478 }
4479
4480 + (int) heightForPackage:(Package *)package {
4481 return 73;
4482 }
4483
4484 @end
4485 /* }}} */
4486 /* Section Cell {{{ */
4487 @interface SectionCell : UISimpleTableCell {
4488 NSString *section_;
4489 NSString *name_;
4490 NSString *count_;
4491 UIImage *icon_;
4492 _UISwitchSlider *switch_;
4493 BOOL editing_;
4494 }
4495
4496 - (id) init;
4497 - (void) setSection:(Section *)section editing:(BOOL)editing;
4498
4499 @end
4500
4501 @implementation SectionCell
4502
4503 - (void) clearSection {
4504 if (section_ != nil) {
4505 [section_ release];
4506 section_ = nil;
4507 }
4508
4509 if (name_ != nil) {
4510 [name_ release];
4511 name_ = nil;
4512 }
4513
4514 if (count_ != nil) {
4515 [count_ release];
4516 count_ = nil;
4517 }
4518 }
4519
4520 - (void) dealloc {
4521 [self clearSection];
4522 [icon_ release];
4523 [switch_ release];
4524 [super dealloc];
4525 }
4526
4527 - (id) init {
4528 if ((self = [super init]) != nil) {
4529 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4530
4531 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4532 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4533 } return self;
4534 }
4535
4536 - (void) onSwitch:(id)sender {
4537 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4538 if (metadata == nil) {
4539 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4540 [Sections_ setObject:metadata forKey:section_];
4541 }
4542
4543 Changed_ = true;
4544 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4545 }
4546
4547 - (void) setSection:(Section *)section editing:(BOOL)editing {
4548 if (editing != editing_) {
4549 if (editing_)
4550 [switch_ removeFromSuperview];
4551 else
4552 [self addSubview:switch_];
4553 editing_ = editing;
4554 }
4555
4556 [self clearSection];
4557
4558 if (section == nil) {
4559 name_ = [CYLocalize("ALL_PACKAGES") retain];
4560 count_ = nil;
4561 } else {
4562 section_ = [section localized];
4563 if (section_ != nil)
4564 section_ = [section_ retain];
4565 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4566 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4567
4568 if (editing_)
4569 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4570 }
4571 }
4572
4573 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4574 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4575
4576 if (selected)
4577 UISetColor(White_);
4578
4579 if (!selected)
4580 UISetColor(Black_);
4581 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4582
4583 CGSize size = [count_ sizeWithFont:Font14_];
4584
4585 UISetColor(White_);
4586 if (count_ != nil)
4587 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4588
4589 [super drawContentInRect:rect selected:selected];
4590 }
4591
4592 @end
4593 /* }}} */
4594
4595 /* File Table {{{ */
4596 @interface FileTable : RVPage {
4597 _transient Database *database_;
4598 Package *package_;
4599 NSString *name_;
4600 NSMutableArray *files_;
4601 UITable *list_;
4602 }
4603
4604 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4605 - (void) setPackage:(Package *)package;
4606
4607 @end
4608
4609 @implementation FileTable
4610
4611 - (void) dealloc {
4612 if (package_ != nil)
4613 [package_ release];
4614 if (name_ != nil)
4615 [name_ release];
4616 [files_ release];
4617 [list_ release];
4618 [super dealloc];
4619 }
4620
4621 - (int) numberOfRowsInTable:(UITable *)table {
4622 return files_ == nil ? 0 : [files_ count];
4623 }
4624
4625 - (float) table:(UITable *)table heightForRow:(int)row {
4626 return 24;
4627 }
4628
4629 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4630 if (reusing == nil) {
4631 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4632 UIFont *font = [UIFont systemFontOfSize:16];
4633 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4634 }
4635 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4636 return reusing;
4637 }
4638
4639 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4640 return NO;
4641 }
4642
4643 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4644 if ((self = [super initWithBook:book]) != nil) {
4645 database_ = database;
4646
4647 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4648
4649 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4650 [self addSubview:list_];
4651
4652 UITableColumn *column = [[[UITableColumn alloc]
4653 initWithTitle:CYLocalize("NAME")
4654 identifier:@"name"
4655 width:[self frame].size.width
4656 ] autorelease];
4657
4658 [list_ setDataSource:self];
4659 [list_ setSeparatorStyle:1];
4660 [list_ addTableColumn:column];
4661 [list_ setDelegate:self];
4662 [list_ setReusesTableCells:YES];
4663 } return self;
4664 }
4665
4666 - (void) setPackage:(Package *)package {
4667 if (package_ != nil) {
4668 [package_ autorelease];
4669 package_ = nil;
4670 }
4671
4672 if (name_ != nil) {
4673 [name_ release];
4674 name_ = nil;
4675 }
4676
4677 [files_ removeAllObjects];
4678
4679 if (package != nil) {
4680 package_ = [package retain];
4681 name_ = [[package id] retain];
4682
4683 if (NSArray *files = [package files])
4684 [files_ addObjectsFromArray:files];
4685
4686 if ([files_ count] != 0) {
4687 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4688 [files_ removeObjectAtIndex:0];
4689 [files_ sortUsingSelector:@selector(compareByPath:)];
4690
4691 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4692 [stack addObject:@"/"];
4693
4694 for (int i(0), e([files_ count]); i != e; ++i) {
4695 NSString *file = [files_ objectAtIndex:i];
4696 while (![file hasPrefix:[stack lastObject]])
4697 [stack removeLastObject];
4698 NSString *directory = [stack lastObject];
4699 [stack addObject:[file stringByAppendingString:@"/"]];
4700 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4701 ([stack count] - 2) * 3, "",
4702 [file substringFromIndex:[directory length]]
4703 ]];
4704 }
4705 }
4706 }
4707
4708 [list_ reloadData];
4709 }
4710
4711 - (void) resetViewAnimated:(BOOL)animated {
4712 [list_ resetViewAnimated:animated];
4713 }
4714
4715 - (void) reloadData {
4716 [self setPackage:[database_ packageWithName:name_]];
4717 [self reloadButtons];
4718 }
4719
4720 - (NSString *) title {
4721 return CYLocalize("INSTALLED_FILES");
4722 }
4723
4724 - (NSString *) backButtonTitle {
4725 return CYLocalize("FILES");
4726 }
4727
4728 @end
4729 /* }}} */
4730 /* Package View {{{ */
4731 @interface PackageView : BrowserView {
4732 _transient Database *database_;
4733 Package *package_;
4734 NSString *name_;
4735 bool commercial_;
4736 NSMutableArray *buttons_;
4737 }
4738
4739 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4740 - (void) setPackage:(Package *)package;
4741
4742 @end
4743
4744 @implementation PackageView
4745
4746 - (void) dealloc {
4747 if (package_ != nil)
4748 [package_ release];
4749 if (name_ != nil)
4750 [name_ release];
4751 [buttons_ release];
4752 [super dealloc];
4753 }
4754
4755 - (void) release {
4756 if ([self retainCount] == 1)
4757 [delegate_ setPackageView:self];
4758 [super release];
4759 }
4760
4761 /* XXX: this is not safe at all... localization of /fail/ */
4762 - (void) _clickButtonWithName:(NSString *)name {
4763 if ([name isEqualToString:CYLocalize("CLEAR")])
4764 [delegate_ clearPackage:package_];
4765 else if ([name isEqualToString:CYLocalize("INSTALL")])
4766 [delegate_ installPackage:package_];
4767 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4768 [delegate_ installPackage:package_];
4769 else if ([name isEqualToString:CYLocalize("REMOVE")])
4770 [delegate_ removePackage:package_];
4771 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4772 [delegate_ installPackage:package_];
4773 else _assert(false);
4774 }
4775
4776 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4777 NSString *context([sheet context]);
4778
4779 if ([context isEqualToString:@"modify"]) {
4780 int count = [buttons_ count];
4781 _assert(count != 0);
4782 _assert(button <= count + 1);
4783
4784 if (count != button - 1)
4785 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4786
4787 [sheet dismiss];
4788 } else
4789 [super alertSheet:sheet buttonClicked:button];
4790 }
4791
4792 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4793 return [super webView:sender didFinishLoadForFrame:frame];
4794 }
4795
4796 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4797 [super webView:sender didClearWindowObject:window forFrame:frame];
4798 [window setValue:package_ forKey:@"package"];
4799 }
4800
4801 - (bool) _allowJavaScriptPanel {
4802 return commercial_;
4803 }
4804
4805 #if !AlwaysReload
4806 - (void) __rightButtonClicked {
4807 int count = [buttons_ count];
4808 _assert(count != 0);
4809
4810 if (count == 1)
4811 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4812 else {
4813 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4814 [buttons addObjectsFromArray:buttons_];
4815 [buttons addObject:CYLocalize("CANCEL")];
4816
4817 [delegate_ slideUp:[[[UIActionSheet alloc]
4818 initWithTitle:nil
4819 buttons:buttons
4820 defaultButtonIndex:([buttons count] - 1)
4821 delegate:self
4822 context:@"modify"
4823 ] autorelease]];
4824 }
4825 }
4826
4827 - (void) _rightButtonClicked {
4828 if (commercial_)
4829 [super _rightButtonClicked];
4830 else
4831 [self __rightButtonClicked];
4832 }
4833 #endif
4834
4835 - (id) _rightButtonTitle {
4836 int count = [buttons_ count];
4837 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4838 }
4839
4840 - (NSString *) backButtonTitle {
4841 return @"Details";
4842 }
4843
4844 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4845 if ((self = [super initWithBook:book]) != nil) {
4846 database_ = database;
4847 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4848 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4849 } return self;
4850 }
4851
4852 - (void) setPackage:(Package *)package {
4853 if (package_ != nil) {
4854 [package_ autorelease];
4855 package_ = nil;
4856 }
4857
4858 if (name_ != nil) {
4859 [name_ release];
4860 name_ = nil;
4861 }
4862
4863 [buttons_ removeAllObjects];
4864
4865 if (package != nil) {
4866 [package parse];
4867
4868 package_ = [package retain];
4869 name_ = [[package id] retain];
4870 commercial_ = [package isCommercial];
4871
4872 if ([package_ mode] != nil)
4873 [buttons_ addObject:CYLocalize("CLEAR")];
4874 if ([package_ source] == nil);
4875 else if ([package_ upgradableAndEssential:NO])
4876 [buttons_ addObject:CYLocalize("UPGRADE")];
4877 else if ([package_ installed] == nil)
4878 [buttons_ addObject:CYLocalize("INSTALL")];
4879 else
4880 [buttons_ addObject:CYLocalize("REINSTALL")];
4881 if ([package_ installed] != nil)
4882 [buttons_ addObject:CYLocalize("REMOVE")];
4883
4884 if (special_ != NULL) {
4885 CGRect frame([webview_ frame]);
4886 frame.size.width = 320;
4887 frame.size.height = 0;
4888 [webview_ setFrame:frame];
4889
4890 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4891
4892 WebThreadLock();
4893 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4894
4895 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4896
4897 [self setFinishHook:nil];
4898 [self setPopupHook:nil];
4899 WebThreadUnlock();
4900
4901 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4902 [super callFunction:special_];
4903 }
4904 }
4905
4906 [self reloadButtons];
4907 }
4908
4909 - (bool) isLoading {
4910 return commercial_ ? [super isLoading] : false;
4911 }
4912
4913 - (void) reloadData {
4914 [self setPackage:[database_ packageWithName:name_]];
4915 }
4916
4917 @end
4918 /* }}} */
4919 /* Package Table {{{ */
4920 @interface PackageTable : RVPage {
4921 _transient Database *database_;
4922 NSString *title_;
4923 NSMutableArray *packages_;
4924 NSMutableArray *sections_;
4925 UISectionList *list_;
4926 }
4927
4928 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4929
4930 - (void) setDelegate:(id)delegate;
4931
4932 - (void) reloadData;
4933 - (void) resetCursor;
4934
4935 - (UISectionList *) list;
4936
4937 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4938
4939 @end
4940
4941 @implementation PackageTable
4942
4943 - (void) dealloc {
4944 [list_ setDataSource:nil];
4945
4946 [title_ release];
4947 [packages_ release];
4948 [sections_ release];
4949 [list_ release];
4950 [super dealloc];
4951 }
4952
4953 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4954 return [sections_ count];
4955 }
4956
4957 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4958 return [[sections_ objectAtIndex:section] name];
4959 }
4960
4961 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4962 return [[sections_ objectAtIndex:section] row];
4963 }
4964
4965 - (int) numberOfRowsInTable:(UITable *)table {
4966 return [packages_ count];
4967 }
4968
4969 - (float) table:(UITable *)table heightForRow:(int)row {
4970 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4971 }
4972
4973 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4974 if (reusing == nil)
4975 reusing = [[[PackageCell alloc] init] autorelease];
4976 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4977 return reusing;
4978 }
4979
4980 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4981 return NO;
4982 }
4983
4984 - (void) tableRowSelected:(NSNotification *)notification {
4985 int row = [[notification object] selectedRow];
4986 if (row == INT_MAX)
4987 return;
4988
4989 Package *package = [packages_ objectAtIndex:row];
4990 package = [database_ packageWithName:[package id]];
4991 PackageView *view([delegate_ packageView]);
4992 [view setPackage:package];
4993 [view setDelegate:delegate_];
4994 [book_ pushPage:view];
4995 }
4996
4997 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4998 if ((self = [super initWithBook:book]) != nil) {
4999 database_ = database;
5000 title_ = [title retain];
5001
5002 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5003 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5004
5005 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5006 [list_ setDataSource:self];
5007
5008 UITableColumn *column = [[[UITableColumn alloc]
5009 initWithTitle:CYLocalize("NAME")
5010 identifier:@"name"
5011 width:[self frame].size.width
5012 ] autorelease];
5013
5014 UITable *table = [list_ table];
5015 [table setSeparatorStyle:1];
5016 [table addTableColumn:column];
5017 [table setDelegate:self];
5018 [table setReusesTableCells:YES];
5019
5020 [self addSubview:list_];
5021
5022 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5023 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5024 } return self;
5025 }
5026
5027 - (void) setDelegate:(id)delegate {
5028 delegate_ = delegate;
5029 }
5030
5031 - (bool) hasPackage:(Package *)package {
5032 return true;
5033 }
5034
5035 - (void) reloadData {
5036 NSArray *packages = [database_ packages];
5037
5038 [packages_ removeAllObjects];
5039 [sections_ removeAllObjects];
5040
5041 _profile(PackageTable$reloadData$Filter)
5042 for (Package *package in packages)
5043 if ([self hasPackage:package])
5044 [packages_ addObject:package];
5045 _end
5046
5047 Section *section = nil;
5048
5049 _profile(PackageTable$reloadData$Section)
5050 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5051 Package *package;
5052 unichar index;
5053
5054 _profile(PackageTable$reloadData$Section$Package)
5055 package = [packages_ objectAtIndex:offset];
5056 index = [package index];
5057 _end
5058
5059 if (section == nil || [section index] != index) {
5060 _profile(PackageTable$reloadData$Section$Allocate)
5061 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5062 _end
5063
5064 _profile(PackageTable$reloadData$Section$Add)
5065 [sections_ addObject:section];
5066 _end
5067 }
5068
5069 [section addToCount];
5070 }
5071 _end
5072
5073 _profile(PackageTable$reloadData$List)
5074 [list_ reloadData];
5075 _end
5076 }
5077
5078 - (NSString *) title {
5079 return title_;
5080 }
5081
5082 - (void) resetViewAnimated:(BOOL)animated {
5083 [list_ resetViewAnimated:animated];
5084 }
5085
5086 - (void) resetCursor {
5087 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5088 }
5089
5090 - (UISectionList *) list {
5091 return list_;
5092 }
5093
5094 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5095 [list_ setShouldHideHeaderInShortLists:hide];
5096 }
5097
5098 @end
5099 /* }}} */
5100 /* Filtered Package Table {{{ */
5101 @interface FilteredPackageTable : PackageTable {
5102 SEL filter_;
5103 IMP imp_;
5104 id object_;
5105 }
5106
5107 - (void) setObject:(id)object;
5108
5109 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5110
5111 @end
5112
5113 @implementation FilteredPackageTable
5114
5115 - (void) dealloc {
5116 if (object_ != nil)
5117 [object_ release];
5118 [super dealloc];
5119 }
5120
5121 - (void) setObject:(id)object {
5122 if (object_ != nil)
5123 [object_ release];
5124 if (object == nil)
5125 object_ = nil;
5126 else
5127 object_ = [object retain];
5128 }
5129
5130 - (bool) hasPackage:(Package *)package {
5131 _profile(FilteredPackageTable$hasPackage)
5132 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5133 _end
5134 }
5135
5136 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5137 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5138 filter_ = filter;
5139 object_ = object == nil ? nil : [object retain];
5140
5141 /* XXX: this is an unsafe optimization of doomy hell */
5142 Method method = class_getInstanceMethod([Package class], filter);
5143 _assert(method != NULL);
5144 imp_ = method_getImplementation(method);
5145 _assert(imp_ != NULL);
5146
5147 [self reloadData];
5148 } return self;
5149 }
5150
5151 @end
5152 /* }}} */
5153
5154 /* Add Source View {{{ */
5155 @interface AddSourceView : RVPage {
5156 _transient Database *database_;
5157 }
5158
5159 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5160
5161 @end
5162
5163 @implementation AddSourceView
5164
5165 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5166 if ((self = [super initWithBook:book]) != nil) {
5167 database_ = database;
5168 } return self;
5169 }
5170
5171 @end
5172 /* }}} */
5173 /* Source Cell {{{ */
5174 @interface SourceCell : UITableCell {
5175 UIImage *icon_;
5176 NSString *origin_;
5177 NSString *description_;
5178 NSString *label_;
5179 }
5180
5181 - (void) dealloc;
5182
5183 - (SourceCell *) initWithSource:(Source *)source;
5184
5185 @end
5186
5187 @implementation SourceCell
5188
5189 - (void) dealloc {
5190 [icon_ release];
5191 [origin_ release];
5192 [description_ release];
5193 [label_ release];
5194 [super dealloc];
5195 }
5196
5197 - (SourceCell *) initWithSource:(Source *)source {
5198 if ((self = [super init]) != nil) {
5199 if (icon_ == nil)
5200 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5201 if (icon_ == nil)
5202 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5203 icon_ = [icon_ retain];
5204
5205 origin_ = [[source name] retain];
5206 label_ = [[source uri] retain];
5207 description_ = [[source description] retain];
5208 } return self;
5209 }
5210
5211 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5212 if (icon_ != nil)
5213 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5214
5215 if (selected)
5216 UISetColor(White_);
5217
5218 if (!selected)
5219 UISetColor(Black_);
5220 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5221
5222 if (!selected)
5223 UISetColor(Blue_);
5224 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5225
5226 if (!selected)
5227 UISetColor(Gray_);
5228 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5229
5230 [super drawContentInRect:rect selected:selected];
5231 }
5232
5233 @end
5234 /* }}} */
5235 /* Source Table {{{ */
5236 @interface SourceTable : RVPage {
5237 _transient Database *database_;
5238 UISectionList *list_;
5239 NSMutableArray *sources_;
5240 UIActionSheet *alert_;
5241 int offset_;
5242
5243 NSString *href_;
5244 UIProgressHUD *hud_;
5245 NSError *error_;
5246
5247 //NSURLConnection *installer_;
5248 NSURLConnection *trivial_bz2_;
5249 NSURLConnection *trivial_gz_;
5250 //NSURLConnection *automatic_;
5251
5252 BOOL trivial_;
5253 }
5254
5255 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5256
5257 @end
5258
5259 @implementation SourceTable
5260
5261 - (void) _deallocConnection:(NSURLConnection *)connection {
5262 if (connection != nil) {
5263 [connection cancel];
5264 //[connection setDelegate:nil];
5265 [connection release];
5266 }
5267 }
5268
5269 - (void) dealloc {
5270 [[list_ table] setDelegate:nil];
5271 [list_ setDataSource:nil];
5272
5273 if (href_ != nil)
5274 [href_ release];
5275 if (hud_ != nil)
5276 [hud_ release];
5277 if (error_ != nil)
5278 [error_ release];
5279
5280 //[self _deallocConnection:installer_];
5281 [self _deallocConnection:trivial_gz_];
5282 [self _deallocConnection:trivial_bz2_];
5283 //[self _deallocConnection:automatic_];
5284
5285 [sources_ release];
5286 [list_ release];
5287 [super dealloc];
5288 }
5289
5290 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5291 return offset_ == 0 ? 1 : 2;
5292 }
5293
5294 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5295 switch (section + (offset_ == 0 ? 1 : 0)) {
5296 case 0: return CYLocalize("ENTERED_BY_USER");
5297 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5298
5299 default:
5300 _assert(false);
5301 return nil;
5302 }
5303 }
5304
5305 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5306 switch (section + (offset_ == 0 ? 1 : 0)) {
5307 case 0: return 0;
5308 case 1: return offset_;
5309
5310 default:
5311 _assert(false);
5312 return -1;
5313 }
5314 }
5315
5316 - (int) numberOfRowsInTable:(UITable *)table {
5317 return [sources_ count];
5318 }
5319
5320 - (float) table:(UITable *)table heightForRow:(int)row {
5321 Source *source = [sources_ objectAtIndex:row];
5322 return [source description] == nil ? 56 : 73;
5323 }
5324
5325 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5326 Source *source = [sources_ objectAtIndex:row];
5327 // XXX: weird warning, stupid selectors ;P
5328 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5329 }
5330
5331 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5332 return YES;
5333 }
5334
5335 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5336 return YES;
5337 }
5338
5339 - (void) tableRowSelected:(NSNotification*)notification {
5340 UITable *table([list_ table]);
5341 int row([table selectedRow]);
5342 if (row == INT_MAX)
5343 return;
5344
5345 Source *source = [sources_ objectAtIndex:row];
5346
5347 PackageTable *packages = [[[FilteredPackageTable alloc]
5348 initWithBook:book_
5349 database:database_
5350 title:[source label]
5351 filter:@selector(isVisibleInSource:)
5352 with:source
5353 ] autorelease];
5354
5355 [packages setDelegate:delegate_];
5356
5357 [book_ pushPage:packages];
5358 }
5359
5360 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5361 Source *source = [sources_ objectAtIndex:row];
5362 return [source record] != nil;
5363 }
5364
5365 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5366 [[list_ table] setDeleteConfirmationRow:row];
5367 }
5368
5369 - (void) table:(UITable *)table deleteRow:(int)row {
5370 Source *source = [sources_ objectAtIndex:row];
5371 [Sources_ removeObjectForKey:[source key]];
5372 [delegate_ syncData];
5373 }
5374
5375 - (void) complete {
5376 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5377 @"deb", @"Type",
5378 href_, @"URI",
5379 @"./", @"Distribution",
5380 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5381
5382 [delegate_ syncData];
5383 }
5384
5385 - (NSString *) getWarning {
5386 NSString *href(href_);
5387 NSRange colon([href rangeOfString:@"://"]);
5388 if (colon.location != NSNotFound)
5389 href = [href substringFromIndex:(colon.location + 3)];
5390 href = [href stringByAddingPercentEscapes];
5391 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5392 href = [href stringByCachingURLWithCurrentCDN];
5393
5394 NSURL *url([NSURL URLWithString:href]);
5395
5396 NSStringEncoding encoding;
5397 NSError *error(nil);
5398
5399 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5400 return [warning length] == 0 ? nil : warning;
5401 return nil;
5402 }
5403
5404 - (void) _endConnection:(NSURLConnection *)connection {
5405 NSURLConnection **field = NULL;
5406 if (connection == trivial_bz2_)
5407 field = &trivial_bz2_;
5408 else if (connection == trivial_gz_)
5409 field = &trivial_gz_;
5410 _assert(field != NULL);
5411 [connection release];
5412 *field = nil;
5413
5414 if (
5415 trivial_bz2_ == nil &&
5416 trivial_gz_ == nil
5417 ) {
5418 bool defer(false);
5419
5420 if (trivial_) {
5421 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5422 defer = true;
5423
5424 UIActionSheet *sheet = [[[UIActionSheet alloc]
5425 initWithTitle:CYLocalize("SOURCE_WARNING")
5426 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5427 defaultButtonIndex:0
5428 delegate:self
5429 context:@"warning"
5430 ] autorelease];
5431
5432 [sheet setNumberOfRows:1];
5433
5434 [sheet setBodyText:warning];
5435 [sheet popupAlertAnimated:YES];
5436 } else
5437 [self complete];
5438 } else if (error_ != nil) {
5439 UIActionSheet *sheet = [[[UIActionSheet alloc]
5440 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5441 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5442 defaultButtonIndex:0
5443 delegate:self
5444 context:@"urlerror"
5445 ] autorelease];
5446
5447 [sheet setBodyText:[error_ localizedDescription]];
5448 [sheet popupAlertAnimated:YES];
5449 } else {
5450 UIActionSheet *sheet = [[[UIActionSheet alloc]
5451 initWithTitle:CYLocalize("NOT_REPOSITORY")
5452 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5453 defaultButtonIndex:0
5454 delegate:self
5455 context:@"trivial"
5456 ] autorelease];
5457
5458 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5459 [sheet popupAlertAnimated:YES];
5460 }
5461
5462 [delegate_ setStatusBarShowsProgress:NO];
5463 [delegate_ removeProgressHUD:hud_];
5464
5465 [hud_ autorelease];
5466 hud_ = nil;
5467
5468 if (!defer) {
5469 [href_ release];
5470 href_ = nil;
5471 }
5472
5473 if (error_ != nil) {
5474 [error_ release];
5475 error_ = nil;
5476 }
5477 }
5478 }
5479
5480 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5481 switch ([response statusCode]) {
5482 case 200:
5483 trivial_ = YES;
5484 }
5485 }
5486
5487 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5488 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5489 if (error_ != nil)
5490 error_ = [error retain];
5491 [self _endConnection:connection];
5492 }
5493
5494 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5495 [self _endConnection:connection];
5496 }
5497
5498 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5499 NSMutableURLRequest *request = [NSMutableURLRequest
5500 requestWithURL:[NSURL URLWithString:href]
5501 cachePolicy:NSURLRequestUseProtocolCachePolicy
5502 timeoutInterval:20.0
5503 ];
5504
5505 [request setHTTPMethod:method];
5506
5507 if (Machine_ != NULL)
5508 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5509 if (UniqueID_ != nil)
5510 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5511
5512 if (Role_ != nil)
5513 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5514
5515 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5516 }
5517
5518 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5519 NSString *context([sheet context]);
5520
5521 if ([context isEqualToString:@"source"]) {
5522 switch (button) {
5523 case 1: {
5524 NSString *href = [[sheet textField] text];
5525
5526 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5527
5528 if (![href hasSuffix:@"/"])
5529 href_ = [href stringByAppendingString:@"/"];
5530 else
5531 href_ = href;
5532 href_ = [href_ retain];
5533
5534 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5535 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5536 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5537
5538 trivial_ = false;
5539
5540 hud_ = [[delegate_ addProgressHUD] retain];
5541 [hud_ setText:CYLocalize("VERIFYING_URL")];
5542 } break;
5543
5544 case 2:
5545 break;
5546
5547 default:
5548 _assert(false);
5549 }
5550
5551 [sheet dismiss];
5552 } else if ([context isEqualToString:@"trivial"])
5553 [sheet dismiss];
5554 else if ([context isEqualToString:@"urlerror"])
5555 [sheet dismiss];
5556 else if ([context isEqualToString:@"warning"]) {
5557 switch (button) {
5558 case 1:
5559 [self complete];
5560 break;
5561
5562 case 2:
5563 break;
5564
5565 default:
5566 _assert(false);
5567 }
5568
5569 [href_ release];
5570 href_ = nil;
5571
5572 [sheet dismiss];
5573 }
5574 }
5575
5576 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5577 if ((self = [super initWithBook:book]) != nil) {
5578 database_ = database;
5579 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5580
5581 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5582 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5583 [list_ setShouldHideHeaderInShortLists:NO];
5584
5585 [self addSubview:list_];
5586 [list_ setDataSource:self];
5587
5588 UITableColumn *column = [[UITableColumn alloc]
5589 initWithTitle:CYLocalize("NAME")
5590 identifier:@"name"
5591 width:[self frame].size.width
5592 ];
5593
5594 UITable *table = [list_ table];
5595 [table setSeparatorStyle:1];
5596 [table addTableColumn:column];
5597 [table setDelegate:self];
5598
5599 [self reloadData];
5600
5601 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5602 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5603 } return self;
5604 }
5605
5606 - (void) reloadData {
5607 pkgSourceList list;
5608 _assert(list.ReadMainList());
5609
5610 [sources_ removeAllObjects];
5611 [sources_ addObjectsFromArray:[database_ sources]];
5612 _trace();
5613 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5614 _trace();
5615
5616 int count = [sources_ count];
5617 for (offset_ = 0; offset_ != count; ++offset_) {
5618 Source *source = [sources_ objectAtIndex:offset_];
5619 if ([source record] == nil)
5620 break;
5621 }
5622
5623 [list_ reloadData];
5624 }
5625
5626 - (void) resetViewAnimated:(BOOL)animated {
5627 [list_ resetViewAnimated:animated];
5628 }
5629
5630 - (void) _leftButtonClicked {
5631 /*[book_ pushPage:[[[AddSourceView alloc]
5632 initWithBook:book_
5633 database:database_
5634 ] autorelease]];*/
5635
5636 UIActionSheet *sheet = [[[UIActionSheet alloc]
5637 initWithTitle:CYLocalize("ENTER_APT_URL")
5638 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5639 defaultButtonIndex:0
5640 delegate:self
5641 context:@"source"
5642 ] autorelease];
5643
5644 [sheet setNumberOfRows:1];
5645
5646 [sheet addTextFieldWithValue:@"http://" label:@""];
5647
5648 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5649 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5650 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5651 [traits setKeyboardType:UIKeyboardTypeURL];
5652 // XXX: UIReturnKeyDone
5653 [traits setReturnKeyType:UIReturnKeyNext];
5654
5655 [sheet popupAlertAnimated:YES];
5656 }
5657
5658 - (void) _rightButtonClicked {
5659 UITable *table = [list_ table];
5660 BOOL editing = [table isRowDeletionEnabled];
5661 [table enableRowDeletion:!editing animated:YES];
5662 [book_ reloadButtonsForPage:self];
5663 }
5664
5665 - (NSString *) title {
5666 return CYLocalize("SOURCES");
5667 }
5668
5669 - (NSString *) leftButtonTitle {
5670 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5671 }
5672
5673 - (id) rightButtonTitle {
5674 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5675 }
5676
5677 - (UINavigationButtonStyle) rightButtonStyle {
5678 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5679 }
5680
5681 @end
5682 /* }}} */
5683
5684 /* Installed View {{{ */
5685 @interface InstalledView : RVPage {
5686 _transient Database *database_;
5687 FilteredPackageTable *packages_;
5688 BOOL expert_;
5689 }
5690
5691 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5692
5693 @end
5694
5695 @implementation InstalledView
5696
5697 - (void) dealloc {
5698 [packages_ release];
5699 [super dealloc];
5700 }
5701
5702 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5703 if ((self = [super initWithBook:book]) != nil) {
5704 database_ = database;
5705
5706 packages_ = [[FilteredPackageTable alloc]
5707 initWithBook:book
5708 database:database
5709 title:nil
5710 filter:@selector(isInstalledAndVisible:)
5711 with:[NSNumber numberWithBool:YES]
5712 ];
5713
5714 [self addSubview:packages_];
5715
5716 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5717 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5718 } return self;
5719 }
5720
5721 - (void) resetViewAnimated:(BOOL)animated {
5722 [packages_ resetViewAnimated:animated];
5723 }
5724
5725 - (void) reloadData {
5726 [packages_ reloadData];
5727 }
5728
5729 - (void) _rightButtonClicked {
5730 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5731 [packages_ reloadData];
5732 expert_ = !expert_;
5733 [book_ reloadButtonsForPage:self];
5734 }
5735
5736 - (NSString *) title {
5737 return CYLocalize("INSTALLED");
5738 }
5739
5740 - (NSString *) backButtonTitle {
5741 return CYLocalize("PACKAGES");
5742 }
5743
5744 - (id) rightButtonTitle {
5745 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5746 }
5747
5748 - (UINavigationButtonStyle) rightButtonStyle {
5749 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5750 }
5751
5752 - (void) setDelegate:(id)delegate {
5753 [super setDelegate:delegate];
5754 [packages_ setDelegate:delegate];
5755 }
5756
5757 @end
5758 /* }}} */
5759
5760 /* Home View {{{ */
5761 @interface HomeView : BrowserView {
5762 }
5763
5764 @end
5765
5766 @implementation HomeView
5767
5768 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5769 NSString *context([sheet context]);
5770
5771 if ([context isEqualToString:@"about"])
5772 [sheet dismiss];
5773 else
5774 [super alertSheet:sheet buttonClicked:button];
5775 }
5776
5777 - (void) _leftButtonClicked {
5778 UIActionSheet *sheet = [[[UIActionSheet alloc]
5779 initWithTitle:CYLocalize("ABOUT_CYDIA")
5780 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5781 defaultButtonIndex:0
5782 delegate:self
5783 context:@"about"
5784 ] autorelease];
5785
5786 [sheet setBodyText:
5787 @"Copyright (C) 2008-2009\n"
5788 "Jay Freeman (saurik)\n"
5789 "saurik@saurik.com\n"
5790 "http://www.saurik.com/\n"
5791 "\n"
5792 "The Okori Group\n"
5793 "http://www.theokorigroup.com/\n"
5794 "\n"
5795 "College of Creative Studies,\n"
5796 "University of California,\n"
5797 "Santa Barbara\n"
5798 "http://www.ccs.ucsb.edu/"
5799 ];
5800
5801 [sheet popupAlertAnimated:YES];
5802 }
5803
5804 - (NSString *) leftButtonTitle {
5805 return CYLocalize("ABOUT");
5806 }
5807
5808 @end
5809 /* }}} */
5810 /* Manage View {{{ */
5811 @interface ManageView : BrowserView {
5812 }
5813
5814 @end
5815
5816 @implementation ManageView
5817
5818 - (NSString *) title {
5819 return CYLocalize("MANAGE");
5820 }
5821
5822 - (void) _leftButtonClicked {
5823 [delegate_ askForSettings];
5824 }
5825
5826 - (NSString *) leftButtonTitle {
5827 return CYLocalize("SETTINGS");
5828 }
5829
5830 #if !AlwaysReload
5831 - (id) _rightButtonTitle {
5832 return Queuing_ ? CYLocalize("QUEUE") : nil;
5833 }
5834
5835 - (UINavigationButtonStyle) rightButtonStyle {
5836 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5837 }
5838
5839 - (void) _rightButtonClicked {
5840 [delegate_ queue];
5841 }
5842 #endif
5843
5844 - (bool) isLoading {
5845 return false;
5846 }
5847
5848 @end
5849 /* }}} */
5850
5851 #include <BrowserView.m>
5852
5853 /* Cydia Book {{{ */
5854 @interface CYBook : RVBook <
5855 ProgressDelegate
5856 > {
5857 _transient Database *database_;
5858 UINavigationBar *overlay_;
5859 UINavigationBar *underlay_;
5860 UIProgressIndicator *indicator_;
5861 UITextLabel *prompt_;
5862 UIProgressBar *progress_;
5863 UINavigationButton *cancel_;
5864 bool updating_;
5865 }
5866
5867 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5868 - (void) update;
5869 - (BOOL) updating;
5870
5871 @end
5872
5873 @implementation CYBook
5874
5875 - (void) dealloc {
5876 [overlay_ release];
5877 [indicator_ release];
5878 [prompt_ release];
5879 [progress_ release];
5880 [cancel_ release];
5881 [super dealloc];
5882 }
5883
5884 - (NSString *) getTitleForPage:(RVPage *)page {
5885 return [super getTitleForPage:page];
5886 }
5887
5888 - (BOOL) updating {
5889 return updating_;
5890 }
5891
5892 - (void) update {
5893 [UIView beginAnimations:nil context:NULL];
5894
5895 CGRect ovrframe = [overlay_ frame];
5896 ovrframe.origin.y = 0;
5897 [overlay_ setFrame:ovrframe];
5898
5899 CGRect barframe = [navbar_ frame];
5900 barframe.origin.y += ovrframe.size.height;
5901 [navbar_ setFrame:barframe];
5902
5903 CGRect trnframe = [transition_ frame];
5904 trnframe.origin.y += ovrframe.size.height;
5905 trnframe.size.height -= ovrframe.size.height;
5906 [transition_ setFrame:trnframe];
5907
5908 [UIView endAnimations];
5909
5910 [indicator_ startAnimation];
5911 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5912 [progress_ setProgress:0];
5913
5914 updating_ = true;
5915 [overlay_ addSubview:cancel_];
5916
5917 [NSThread
5918 detachNewThreadSelector:@selector(_update)
5919 toTarget:self
5920 withObject:nil
5921 ];
5922 }
5923
5924 - (void) _update_ {
5925 updating_ = false;
5926
5927 [indicator_ stopAnimation];
5928
5929 [UIView beginAnimations:nil context:NULL];
5930
5931 CGRect ovrframe = [overlay_ frame];
5932 ovrframe.origin.y = -ovrframe.size.height;
5933 [overlay_ setFrame:ovrframe];
5934
5935 CGRect barframe = [navbar_ frame];
5936 barframe.origin.y -= ovrframe.size.height;
5937 [navbar_ setFrame:barframe];
5938
5939 CGRect trnframe = [transition_ frame];
5940 trnframe.origin.y -= ovrframe.size.height;
5941 trnframe.size.height += ovrframe.size.height;
5942 [transition_ setFrame:trnframe];
5943
5944 [UIView commitAnimations];
5945
5946 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5947 }
5948
5949 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5950 if ((self = [super initWithFrame:frame]) != nil) {
5951 database_ = database;
5952
5953 CGRect ovrrect = [navbar_ bounds];
5954 ovrrect.size.height = [UINavigationBar defaultSize].height;
5955 ovrrect.origin.y = -ovrrect.size.height;
5956
5957 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5958 [self addSubview:overlay_];
5959
5960 ovrrect.origin.y = frame.size.height;
5961 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5962 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5963 [self addSubview:underlay_];
5964
5965 [overlay_ setBarStyle:1];
5966 [underlay_ setBarStyle:1];
5967
5968 int barstyle = [overlay_ _barStyle:NO];
5969 bool ugly = barstyle == 0;
5970
5971 UIProgressIndicatorStyle style = ugly ?
5972 UIProgressIndicatorStyleMediumBrown :
5973 UIProgressIndicatorStyleMediumWhite;
5974
5975 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5976 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5977 CGRect indrect = {{indoffset, indoffset}, indsize};
5978
5979 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5980 [indicator_ setStyle:style];
5981 [overlay_ addSubview:indicator_];
5982
5983 CGSize prmsize = {215, indsize.height + 4};
5984
5985 CGRect prmrect = {{
5986 indoffset * 2 + indsize.width,
5987 #ifdef __OBJC2__
5988 -1 +
5989 #endif
5990 unsigned(ovrrect.size.height - prmsize.height) / 2
5991 }, prmsize};
5992
5993 UIFont *font = [UIFont systemFontOfSize:15];
5994
5995 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5996
5997 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5998 [prompt_ setBackgroundColor:[UIColor clearColor]];
5999 [prompt_ setFont:font];
6000
6001 [overlay_ addSubview:prompt_];
6002
6003 CGSize prgsize = {75, 100};
6004
6005 CGRect prgrect = {{
6006 ovrrect.size.width - prgsize.width - 10,
6007 (ovrrect.size.height - prgsize.height) / 2
6008 } , prgsize};
6009
6010 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6011 [progress_ setStyle:0];
6012 [overlay_ addSubview:progress_];
6013
6014 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6015 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6016
6017 CGRect frame = [cancel_ frame];
6018 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6019 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6020 [cancel_ setFrame:frame];
6021
6022 [cancel_ setBarStyle:barstyle];
6023 } return self;
6024 }
6025
6026 - (void) _onCancel {
6027 updating_ = false;
6028 [cancel_ removeFromSuperview];
6029 }
6030
6031 - (void) _update { _pooled
6032 Status status;
6033 status.setDelegate(self);
6034
6035 [database_ updateWithStatus:status];
6036
6037 [self
6038 performSelectorOnMainThread:@selector(_update_)
6039 withObject:nil
6040 waitUntilDone:NO
6041 ];
6042 }
6043
6044 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6045 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6046 }
6047
6048 - (void) setProgressTitle:(NSString *)title {
6049 [self
6050 performSelectorOnMainThread:@selector(_setProgressTitle:)
6051 withObject:title
6052 waitUntilDone:YES
6053 ];
6054 }
6055
6056 - (void) setProgressPercent:(float)percent {
6057 [self
6058 performSelectorOnMainThread:@selector(_setProgressPercent:)
6059 withObject:[NSNumber numberWithFloat:percent]
6060 waitUntilDone:YES
6061 ];
6062 }
6063
6064 - (void) startProgress {
6065 }
6066
6067 - (void) addProgressOutput:(NSString *)output {
6068 [self
6069 performSelectorOnMainThread:@selector(_addProgressOutput:)
6070 withObject:output
6071 waitUntilDone:YES
6072 ];
6073 }
6074
6075 - (bool) isCancelling:(size_t)received {
6076 return !updating_;
6077 }
6078
6079 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6080 [sheet dismiss];
6081 }
6082
6083 - (void) _setProgressTitle:(NSString *)title {
6084 [prompt_ setText:title];
6085 }
6086
6087 - (void) _setProgressPercent:(NSNumber *)percent {
6088 [progress_ setProgress:[percent floatValue]];
6089 }
6090
6091 - (void) _addProgressOutput:(NSString *)output {
6092 }
6093
6094 @end
6095 /* }}} */
6096 /* Cydia:// Protocol {{{ */
6097 @interface CydiaURLProtocol : NSURLProtocol {
6098 }
6099
6100 @end
6101
6102 @implementation CydiaURLProtocol
6103
6104 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6105 NSURL *url([request URL]);
6106 if (url == nil)
6107 return NO;
6108 NSString *scheme([[url scheme] lowercaseString]);
6109 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6110 return NO;
6111 return YES;
6112 }
6113
6114 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6115 return request;
6116 }
6117
6118 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6119 id<NSURLProtocolClient> client([self client]);
6120 if (icon == nil)
6121 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6122 else {
6123 NSData *data(UIImagePNGRepresentation(icon));
6124
6125 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6126 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6127 [client URLProtocol:self didLoadData:data];
6128 [client URLProtocolDidFinishLoading:self];
6129 }
6130 }
6131
6132 - (void) startLoading {
6133 id<NSURLProtocolClient> client([self client]);
6134 NSURLRequest *request([self request]);
6135
6136 NSURL *url([request URL]);
6137 NSString *href([url absoluteString]);
6138
6139 NSString *path([href substringFromIndex:8]);
6140 NSRange slash([path rangeOfString:@"/"]);
6141
6142 NSString *command;
6143 if (slash.location == NSNotFound) {
6144 command = path;
6145 path = nil;
6146 } else {
6147 command = [path substringToIndex:slash.location];
6148 path = [path substringFromIndex:(slash.location + 1)];
6149 }
6150
6151 Database *database([Database sharedInstance]);
6152
6153 if ([command isEqualToString:@"package-icon"]) {
6154 if (path == nil)
6155 goto fail;
6156 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6157 Package *package([database packageWithName:path]);
6158 if (package == nil)
6159 goto fail;
6160 UIImage *icon([package icon]);
6161 [self _returnPNGWithImage:icon forRequest:request];
6162 } else if ([command isEqualToString:@"source-icon"]) {
6163 if (path == nil)
6164 goto fail;
6165 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6166 NSString *source(Simplify(path));
6167 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6168 if (icon == nil)
6169 icon = [UIImage applicationImageNamed:@"unknown.png"];
6170 [self _returnPNGWithImage:icon forRequest:request];
6171 } else if ([command isEqualToString:@"uikit-image"]) {
6172 if (path == nil)
6173 goto fail;
6174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6175 UIImage *icon(_UIImageWithName(path));
6176 [self _returnPNGWithImage:icon forRequest:request];
6177 } else if ([command isEqualToString:@"section-icon"]) {
6178 if (path == nil)
6179 goto fail;
6180 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6181 NSString *section(Simplify(path));
6182 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6183 if (icon == nil)
6184 icon = [UIImage applicationImageNamed:@"unknown.png"];
6185 [self _returnPNGWithImage:icon forRequest:request];
6186 } else fail: {
6187 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6188 }
6189 }
6190
6191 - (void) stopLoading {
6192 }
6193
6194 @end
6195 /* }}} */
6196
6197 /* Sections View {{{ */
6198 @interface SectionsView : RVPage {
6199 _transient Database *database_;
6200 NSMutableArray *sections_;
6201 NSMutableArray *filtered_;
6202 UITransitionView *transition_;
6203 UITable *list_;
6204 UIView *accessory_;
6205 BOOL editing_;
6206 }
6207
6208 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6209 - (void) reloadData;
6210 - (void) resetView;
6211
6212 @end
6213
6214 @implementation SectionsView
6215
6216 - (void) dealloc {
6217 [list_ setDataSource:nil];
6218 [list_ setDelegate:nil];
6219
6220 [sections_ release];
6221 [filtered_ release];
6222 [transition_ release];
6223 [list_ release];
6224 [accessory_ release];
6225 [super dealloc];
6226 }
6227
6228 - (int) numberOfRowsInTable:(UITable *)table {
6229 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6230 }
6231
6232 - (float) table:(UITable *)table heightForRow:(int)row {
6233 return 45;
6234 }
6235
6236 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6237 if (reusing == nil)
6238 reusing = [[[SectionCell alloc] init] autorelease];
6239 [(SectionCell *)reusing setSection:(editing_ ?
6240 [sections_ objectAtIndex:row] :
6241 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6242 ) editing:editing_];
6243 return reusing;
6244 }
6245
6246 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6247 return !editing_;
6248 }
6249
6250 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6251 return !editing_;
6252 }
6253
6254 - (void) tableRowSelected:(NSNotification *)notification {
6255 int row = [[notification object] selectedRow];
6256 if (row == INT_MAX)
6257 return;
6258
6259 Section *section;
6260 NSString *name;
6261 NSString *title;
6262
6263 if (row == 0) {
6264 section = nil;
6265 name = nil;
6266 title = CYLocalize("ALL_PACKAGES");
6267 } else {
6268 section = [filtered_ objectAtIndex:(row - 1)];
6269 name = [section name];
6270
6271 if (name != nil)
6272 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6273 else {
6274 name = @"";
6275 title = CYLocalize("NO_SECTION");
6276 }
6277 }
6278
6279 PackageTable *table = [[[FilteredPackageTable alloc]
6280 initWithBook:book_
6281 database:database_
6282 title:title
6283 filter:@selector(isVisiblyUninstalledInSection:)
6284 with:name
6285 ] autorelease];
6286
6287 [table setDelegate:delegate_];
6288
6289 [book_ pushPage:table];
6290 }
6291
6292 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6293 if ((self = [super initWithBook:book]) != nil) {
6294 database_ = database;
6295
6296 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6297 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6298
6299 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6300 [self addSubview:transition_];
6301
6302 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6303 [transition_ transition:0 toView:list_];
6304
6305 UITableColumn *column = [[[UITableColumn alloc]
6306 initWithTitle:CYLocalize("NAME")
6307 identifier:@"name"
6308 width:[self frame].size.width
6309 ] autorelease];
6310
6311 [list_ setDataSource:self];
6312 [list_ setSeparatorStyle:1];
6313 [list_ addTableColumn:column];
6314 [list_ setDelegate:self];
6315 [list_ setReusesTableCells:YES];
6316
6317 [self reloadData];
6318
6319 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6320 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6321 } return self;
6322 }
6323
6324 - (void) reloadData {
6325 NSArray *packages = [database_ packages];
6326
6327 [sections_ removeAllObjects];
6328 [filtered_ removeAllObjects];
6329
6330 #if 0
6331 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6332 SectionMap sections;
6333 sections.resize(64);
6334 #else
6335 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6336 #endif
6337
6338 _trace();
6339 for (Package *package in packages) {
6340 NSString *name([package section]);
6341 NSString *key(name == nil ? @"" : name);
6342
6343 #if 0
6344 Section **section;
6345
6346 _profile(SectionsView$reloadData$Section)
6347 section = &sections[key];
6348 if (*section == nil) {
6349 _profile(SectionsView$reloadData$Section$Allocate)
6350 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6351 _end
6352 }
6353 _end
6354
6355 [*section addToCount];
6356
6357 _profile(SectionsView$reloadData$Filter)
6358 if (![package valid] || [package installed] != nil || ![package visible])
6359 continue;
6360 _end
6361
6362 [*section addToRow];
6363 #else
6364 Section *section;
6365
6366 _profile(SectionsView$reloadData$Section)
6367 section = [sections objectForKey:key];
6368 if (section == nil) {
6369 _profile(SectionsView$reloadData$Section$Allocate)
6370 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6371 [sections setObject:section forKey:key];
6372 _end
6373 }
6374 _end
6375
6376 [section addToCount];
6377
6378 _profile(SectionsView$reloadData$Filter)
6379 if (![package valid] || [package installed] != nil || ![package visible])
6380 continue;
6381 _end
6382
6383 [section addToRow];
6384 #endif
6385 }
6386 _trace();
6387
6388 #if 0
6389 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6390 [sections_ addObject:i->second];
6391 #else
6392 [sections_ addObjectsFromArray:[sections allValues]];
6393 #endif
6394
6395 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6396
6397 for (Section *section in sections_) {
6398 size_t count([section row]);
6399 if (count == 0)
6400 continue;
6401
6402 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6403 [section setCount:count];
6404 [filtered_ addObject:section];
6405 }
6406
6407 [list_ reloadData];
6408 _trace();
6409 }
6410
6411 - (void) resetView {
6412 if (editing_)
6413 [self _rightButtonClicked];
6414 }
6415
6416 - (void) resetViewAnimated:(BOOL)animated {
6417 [list_ resetViewAnimated:animated];
6418 }
6419
6420 - (void) _rightButtonClicked {
6421 if ((editing_ = !editing_))
6422 [list_ reloadData];
6423 else
6424 [delegate_ updateData];
6425 [book_ reloadTitleForPage:self];
6426 [book_ reloadButtonsForPage:self];
6427 }
6428
6429 - (NSString *) title {
6430 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6431 }
6432
6433 - (NSString *) backButtonTitle {
6434 return CYLocalize("SECTIONS");
6435 }
6436
6437 - (id) rightButtonTitle {
6438 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6439 }
6440
6441 - (UINavigationButtonStyle) rightButtonStyle {
6442 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6443 }
6444
6445 - (UIView *) accessoryView {
6446 return accessory_;
6447 }
6448
6449 @end
6450 /* }}} */
6451 /* Changes View {{{ */
6452 @interface ChangesView : RVPage {
6453 _transient Database *database_;
6454 NSMutableArray *packages_;
6455 NSMutableArray *sections_;
6456 UISectionList *list_;
6457 unsigned upgrades_;
6458 }
6459
6460 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6461 - (void) reloadData;
6462
6463 @end
6464
6465 @implementation ChangesView
6466
6467 - (void) dealloc {
6468 [[list_ table] setDelegate:nil];
6469 [list_ setDataSource:nil];
6470
6471 [packages_ release];
6472 [sections_ release];
6473 [list_ release];
6474 [super dealloc];
6475 }
6476
6477 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6478 return [sections_ count];
6479 }
6480
6481 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6482 return [[sections_ objectAtIndex:section] name];
6483 }
6484
6485 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6486 return [[sections_ objectAtIndex:section] row];
6487 }
6488
6489 - (int) numberOfRowsInTable:(UITable *)table {
6490 return [packages_ count];
6491 }
6492
6493 - (float) table:(UITable *)table heightForRow:(int)row {
6494 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6495 }
6496
6497 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6498 if (reusing == nil)
6499 reusing = [[[PackageCell alloc] init] autorelease];
6500 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6501 return reusing;
6502 }
6503
6504 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6505 return NO;
6506 }
6507
6508 - (void) tableRowSelected:(NSNotification *)notification {
6509 int row = [[notification object] selectedRow];
6510 if (row == INT_MAX)
6511 return;
6512 Package *package = [packages_ objectAtIndex:row];
6513 PackageView *view([delegate_ packageView]);
6514 [view setDelegate:delegate_];
6515 [view setPackage:package];
6516 [book_ pushPage:view];
6517 }
6518
6519 - (void) _leftButtonClicked {
6520 [(CYBook *)book_ update];
6521 [self reloadButtons];
6522 }
6523
6524 - (void) _rightButtonClicked {
6525 [delegate_ distUpgrade];
6526 }
6527
6528 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6529 if ((self = [super initWithBook:book]) != nil) {
6530 database_ = database;
6531
6532 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6533 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6534
6535 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6536 [self addSubview:list_];
6537
6538 [list_ setShouldHideHeaderInShortLists:NO];
6539 [list_ setDataSource:self];
6540 //[list_ setSectionListStyle:1];
6541
6542 UITableColumn *column = [[[UITableColumn alloc]
6543 initWithTitle:CYLocalize("NAME")
6544 identifier:@"name"
6545 width:[self frame].size.width
6546 ] autorelease];
6547
6548 UITable *table = [list_ table];
6549 [table setSeparatorStyle:1];
6550 [table addTableColumn:column];
6551 [table setDelegate:self];
6552 [table setReusesTableCells:YES];
6553
6554 [self reloadData];
6555
6556 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6557 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6558 } return self;
6559 }
6560
6561 - (void) reloadData {
6562 NSArray *packages = [database_ packages];
6563
6564 [packages_ removeAllObjects];
6565 [sections_ removeAllObjects];
6566
6567 _trace();
6568 for (Package *package in packages)
6569 if (
6570 [package installed] == nil && [package valid] && [package visible] ||
6571 [package upgradableAndEssential:YES]
6572 )
6573 [packages_ addObject:package];
6574
6575 _trace();
6576 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6577 _trace();
6578
6579 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6580 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6581 Section *section = nil;
6582 NSDate *last = nil;
6583
6584 upgrades_ = 0;
6585 bool unseens = false;
6586
6587 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6588
6589 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6590 Package *package = [packages_ objectAtIndex:offset];
6591
6592 BOOL uae = [package upgradableAndEssential:YES];
6593
6594 if (!uae) {
6595 unseens = true;
6596 NSDate *seen;
6597
6598 _profile(ChangesView$reloadData$Remember)
6599 seen = [package seen];
6600 _end
6601
6602 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6603 last = seen;
6604
6605 NSString *name;
6606 if (seen == nil)
6607 name = CYLocalize("UNKNOWN");
6608 else {
6609 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6610 [name autorelease];
6611 }
6612
6613 _profile(ChangesView$reloadData$Allocate)
6614 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6615 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6616 [sections_ addObject:section];
6617 _end
6618 }
6619
6620 [section addToCount];
6621 } else if ([package ignored])
6622 [ignored addToCount];
6623 else {
6624 ++upgrades_;
6625 [upgradable addToCount];
6626 }
6627 }
6628 _trace();
6629
6630 CFRelease(formatter);
6631
6632 if (unseens) {
6633 Section *last = [sections_ lastObject];
6634 size_t count = [last count];
6635 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6636 [sections_ removeLastObject];
6637 }
6638
6639 if ([ignored count] != 0)
6640 [sections_ insertObject:ignored atIndex:0];
6641 if (upgrades_ != 0)
6642 [sections_ insertObject:upgradable atIndex:0];
6643
6644 [list_ reloadData];
6645 [self reloadButtons];
6646 }
6647
6648 - (void) resetViewAnimated:(BOOL)animated {
6649 [list_ resetViewAnimated:animated];
6650 }
6651
6652 - (NSString *) leftButtonTitle {
6653 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6654 }
6655
6656 - (id) rightButtonTitle {
6657 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6658 }
6659
6660 - (NSString *) title {
6661 return CYLocalize("CHANGES");
6662 }
6663
6664 @end
6665 /* }}} */
6666 /* Search View {{{ */
6667 @protocol SearchViewDelegate
6668 - (void) showKeyboard:(BOOL)show;
6669 @end
6670
6671 @interface SearchView : RVPage {
6672 UIView *accessory_;
6673 UISearchField *field_;
6674 UITransitionView *transition_;
6675 FilteredPackageTable *table_;
6676 UIPreferencesTable *advanced_;
6677 UIView *dimmed_;
6678 bool flipped_;
6679 bool reload_;
6680 }
6681
6682 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6683 - (void) reloadData;
6684
6685 @end
6686
6687 @implementation SearchView
6688
6689 - (void) dealloc {
6690 [field_ setDelegate:nil];
6691
6692 [accessory_ release];
6693 [field_ release];
6694 [transition_ release];
6695 [table_ release];
6696 [advanced_ release];
6697 [dimmed_ release];
6698 [super dealloc];
6699 }
6700
6701 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6702 return 1;
6703 }
6704
6705 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6706 switch (group) {
6707 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6708
6709 default: _assert(false);
6710 }
6711 }
6712
6713 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6714 switch (group) {
6715 case 0: return 0;
6716
6717 default: _assert(false);
6718 }
6719 }
6720
6721 - (void) _showKeyboard:(BOOL)show {
6722 CGSize keysize = [UIKeyboard defaultSize];
6723 CGRect keydown = [book_ pageBounds];
6724 CGRect keyup = keydown;
6725 keyup.size.height -= keysize.height - ButtonBarHeight_;
6726
6727 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6728
6729 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6730 [animation setSignificantRectFields:8];
6731
6732 if (show) {
6733 [animation setStartFrame:keydown];
6734 [animation setEndFrame:keyup];
6735 } else {
6736 [animation setStartFrame:keyup];
6737 [animation setEndFrame:keydown];
6738 }
6739
6740 UIAnimator *animator = [UIAnimator sharedAnimator];
6741
6742 [animator
6743 addAnimations:[NSArray arrayWithObjects:animation, nil]
6744 withDuration:(KeyboardTime_ - delay)
6745 start:!show
6746 ];
6747
6748 if (show)
6749 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6750
6751 [delegate_ showKeyboard:show];
6752 }
6753
6754 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6755 [self _showKeyboard:YES];
6756 }
6757
6758 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6759 [self _showKeyboard:NO];
6760 }
6761
6762 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6763 if (reload_) {
6764 NSString *text([field_ text]);
6765 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6766 [self reloadData];
6767 reload_ = false;
6768 }
6769 }
6770
6771 - (void) textFieldClearButtonPressed:(UITextField *)field {
6772 reload_ = true;
6773 }
6774
6775 - (void) keyboardInputShouldDelete:(id)input {
6776 reload_ = true;
6777 }
6778
6779 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6780 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6781 reload_ = true;
6782 return YES;
6783 } else {
6784 [field_ resignFirstResponder];
6785 return NO;
6786 }
6787 }
6788
6789 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6790 if ((self = [super initWithBook:book]) != nil) {
6791 CGRect pageBounds = [book_ pageBounds];
6792
6793 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6794 [self addSubview:transition_];
6795
6796 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6797
6798 [advanced_ setReusesTableCells:YES];
6799 [advanced_ setDataSource:self];
6800 [advanced_ reloadData];
6801
6802 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6803 CGColor dimmed(space_, 0, 0, 0, 0.5);
6804 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6805
6806 table_ = [[FilteredPackageTable alloc]
6807 initWithBook:book
6808 database:database
6809 title:nil
6810 filter:@selector(isUnfilteredAndSearchedForBy:)
6811 with:nil
6812 ];
6813
6814 [table_ setShouldHideHeaderInShortLists:NO];
6815 [transition_ transition:0 toView:table_];
6816
6817 CGRect cnfrect = {{
6818 #ifdef __OBJC2__
6819 6 +
6820 #endif
6821 1, 38}, {17, 18}};
6822
6823 CGRect area;
6824 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6825 area.origin.y = 1;
6826
6827 area.size.width =
6828 #ifdef __OBJC2__
6829 8 +
6830 #endif
6831 [self bounds].size.width - area.origin.x - 18;
6832
6833 area.size.height = [UISearchField defaultHeight];
6834
6835 field_ = [[UISearchField alloc] initWithFrame:area];
6836
6837 UIFont *font = [UIFont systemFontOfSize:16];
6838 [field_ setFont:font];
6839
6840 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6841 [field_ setDelegate:self];
6842
6843 [field_ setPaddingTop:5];
6844
6845 UITextInputTraits *traits([field_ textInputTraits]);
6846 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6847 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6848 [traits setReturnKeyType:UIReturnKeySearch];
6849
6850 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6851
6852 accessory_ = [[UIView alloc] initWithFrame:accrect];
6853 [accessory_ addSubview:field_];
6854
6855 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6856 [configure setShowPressFeedback:YES];
6857 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6858 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6859 [accessory_ addSubview:configure];*/
6860
6861 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6862 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6863 } return self;
6864 }
6865
6866 - (void) flipPage {
6867 #ifndef __OBJC2__
6868 LKAnimation *animation = [LKTransition animation];
6869 [animation setType:@"oglFlip"];
6870 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6871 [animation setFillMode:@"extended"];
6872 [animation setTransitionFlags:3];
6873 [animation setDuration:10];
6874 [animation setSpeed:0.35];
6875 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6876 [[transition_ _layer] addAnimation:animation forKey:0];
6877 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6878 flipped_ = !flipped_;
6879 #endif
6880 }
6881
6882 - (void) configurePushed {
6883 [field_ resignFirstResponder];
6884 [self flipPage];
6885 }
6886
6887 - (void) resetViewAnimated:(BOOL)animated {
6888 if (flipped_)
6889 [self flipPage];
6890 [table_ resetViewAnimated:animated];
6891 }
6892
6893 - (void) _reloadData {
6894 }
6895
6896 - (void) reloadData {
6897 if (flipped_)
6898 [self flipPage];
6899 [table_ setObject:[field_ text]];
6900 _profile(SearchView$reloadData)
6901 [table_ reloadData];
6902 _end
6903 PrintTimes();
6904 [table_ resetCursor];
6905 }
6906
6907 - (UIView *) accessoryView {
6908 return accessory_;
6909 }
6910
6911 - (NSString *) title {
6912 return nil;
6913 }
6914
6915 - (NSString *) backButtonTitle {
6916 return CYLocalize("SEARCH");
6917 }
6918
6919 - (void) setDelegate:(id)delegate {
6920 [table_ setDelegate:delegate];
6921 [super setDelegate:delegate];
6922 }
6923
6924 @end
6925 /* }}} */
6926
6927 @interface SettingsView : RVPage {
6928 _transient Database *database_;
6929 NSString *name_;
6930 Package *package_;
6931 UIPreferencesTable *table_;
6932 _UISwitchSlider *subscribedSwitch_;
6933 _UISwitchSlider *ignoredSwitch_;
6934 UIPreferencesControlTableCell *subscribedCell_;
6935 UIPreferencesControlTableCell *ignoredCell_;
6936 }
6937
6938 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6939
6940 @end
6941
6942 @implementation SettingsView
6943
6944 - (void) dealloc {
6945 [table_ setDataSource:nil];
6946
6947 [name_ release];
6948 if (package_ != nil)
6949 [package_ release];
6950 [table_ release];
6951 [subscribedSwitch_ release];
6952 [ignoredSwitch_ release];
6953 [subscribedCell_ release];
6954 [ignoredCell_ release];
6955 [super dealloc];
6956 }
6957
6958 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6959 if (package_ == nil)
6960 return 0;
6961
6962 return 2;
6963 }
6964
6965 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6966 if (package_ == nil)
6967 return nil;
6968
6969 switch (group) {
6970 case 0: return nil;
6971 case 1: return nil;
6972
6973 default: _assert(false);
6974 }
6975
6976 return nil;
6977 }
6978
6979 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6980 if (package_ == nil)
6981 return NO;
6982
6983 switch (group) {
6984 case 0: return NO;
6985 case 1: return YES;
6986
6987 default: _assert(false);
6988 }
6989
6990 return NO;
6991 }
6992
6993 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6994 if (package_ == nil)
6995 return 0;
6996
6997 switch (group) {
6998 case 0: return 1;
6999 case 1: return 1;
7000
7001 default: _assert(false);
7002 }
7003
7004 return 0;
7005 }
7006
7007 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7008 if (package_ == nil)
7009 return;
7010
7011 _UISwitchSlider *slider([cell control]);
7012 BOOL value([slider value] != 0);
7013 NSMutableDictionary *metadata([package_ metadata]);
7014
7015 BOOL before;
7016 if (NSNumber *number = [metadata objectForKey:key])
7017 before = [number boolValue];
7018 else
7019 before = NO;
7020
7021 if (value != before) {
7022 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7023 Changed_ = true;
7024 [delegate_ updateData];
7025 }
7026 }
7027
7028 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7029 [self onSomething:cell withKey:@"IsSubscribed"];
7030 }
7031
7032 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7033 [self onSomething:cell withKey:@"IsIgnored"];
7034 }
7035
7036 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7037 if (package_ == nil)
7038 return nil;
7039
7040 switch (group) {
7041 case 0: switch (row) {
7042 case 0:
7043 return subscribedCell_;
7044 case 1:
7045 return ignoredCell_;
7046 default: _assert(false);
7047 } break;
7048
7049 case 1: switch (row) {
7050 case 0: {
7051 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7052 [cell setShowSelection:NO];
7053 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7054 return cell;
7055 }
7056
7057 default: _assert(false);
7058 } break;
7059
7060 default: _assert(false);
7061 }
7062
7063 return nil;
7064 }
7065
7066 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7067 if ((self = [super initWithBook:book])) {
7068 database_ = database;
7069 name_ = [package retain];
7070
7071 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7072 [self addSubview:table_];
7073
7074 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7075 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7076
7077 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7078 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7079
7080 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7081 [subscribedCell_ setShowSelection:NO];
7082 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7083 [subscribedCell_ setControl:subscribedSwitch_];
7084
7085 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7086 [ignoredCell_ setShowSelection:NO];
7087 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7088 [ignoredCell_ setControl:ignoredSwitch_];
7089
7090 [table_ setDataSource:self];
7091 [self reloadData];
7092 } return self;
7093 }
7094
7095 - (void) resetViewAnimated:(BOOL)animated {
7096 [table_ resetViewAnimated:animated];
7097 }
7098
7099 - (void) reloadData {
7100 if (package_ != nil)
7101 [package_ autorelease];
7102 package_ = [database_ packageWithName:name_];
7103 if (package_ != nil) {
7104 [package_ retain];
7105 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7106 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7107 }
7108
7109 [table_ reloadData];
7110 }
7111
7112 - (NSString *) title {
7113 return CYLocalize("SETTINGS");
7114 }
7115
7116 @end
7117
7118 /* Signature View {{{ */
7119 @interface SignatureView : BrowserView {
7120 _transient Database *database_;
7121 NSString *package_;
7122 }
7123
7124 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7125
7126 @end
7127
7128 @implementation SignatureView
7129
7130 - (void) dealloc {
7131 [package_ release];
7132 [super dealloc];
7133 }
7134
7135 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7136 // XXX: dude!
7137 [super webView:sender didClearWindowObject:window forFrame:frame];
7138 }
7139
7140 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7141 if ((self = [super initWithBook:book]) != nil) {
7142 database_ = database;
7143 package_ = [package retain];
7144 [self reloadData];
7145 } return self;
7146 }
7147
7148 - (void) resetViewAnimated:(BOOL)animated {
7149 }
7150
7151 - (void) reloadData {
7152 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7153 }
7154
7155 @end
7156 /* }}} */
7157
7158 @interface Cydia : UIApplication <
7159 ConfirmationViewDelegate,
7160 ProgressViewDelegate,
7161 SearchViewDelegate,
7162 CydiaDelegate
7163 > {
7164 UIWindow *window_;
7165
7166 UIView *underlay_;
7167 UIView *overlay_;
7168 CYBook *book_;
7169 UIToolbar *buttonbar_;
7170
7171 RVBook *confirm_;
7172
7173 NSMutableArray *essential_;
7174 NSMutableArray *broken_;
7175
7176 Database *database_;
7177 ProgressView *progress_;
7178
7179 unsigned tag_;
7180
7181 UIKeyboard *keyboard_;
7182 UIProgressHUD *hud_;
7183
7184 SectionsView *sections_;
7185 ChangesView *changes_;
7186 ManageView *manage_;
7187 SearchView *search_;
7188
7189 PackageView *package_;
7190 }
7191
7192 @end
7193
7194 @implementation Cydia
7195
7196 - (void) _loaded {
7197 if ([broken_ count] != 0) {
7198 int count = [broken_ count];
7199
7200 UIActionSheet *sheet = [[[UIActionSheet alloc]
7201 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7202 buttons:[NSArray arrayWithObjects:
7203 CYLocalize("FORCIBLY_CLEAR"),
7204 CYLocalize("TEMPORARY_IGNORE"),
7205 nil]
7206 defaultButtonIndex:0
7207 delegate:self
7208 context:@"fixhalf"
7209 ] autorelease];
7210
7211 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7212 [sheet popupAlertAnimated:YES];
7213 } else if (!Ignored_ && [essential_ count] != 0) {
7214 int count = [essential_ count];
7215
7216 UIActionSheet *sheet = [[[UIActionSheet alloc]
7217 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7218 buttons:[NSArray arrayWithObjects:
7219 CYLocalize("UPGRADE_ESSENTIAL"),
7220 CYLocalize("COMPLETE_UPGRADE"),
7221 CYLocalize("TEMPORARY_IGNORE"),
7222 nil]
7223 defaultButtonIndex:0
7224 delegate:self
7225 context:@"upgrade"
7226 ] autorelease];
7227
7228 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7229 [sheet popupAlertAnimated:YES];
7230 }
7231 }
7232
7233 - (void) _reloadData {
7234 UIView *block();
7235
7236 static bool loaded(false);
7237 UIProgressHUD *hud([self addProgressHUD]);
7238 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7239 loaded = true;
7240
7241 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7242 _trace();
7243
7244 [self removeProgressHUD:hud];
7245
7246 size_t changes(0);
7247
7248 [essential_ removeAllObjects];
7249 [broken_ removeAllObjects];
7250
7251 NSArray *packages = [database_ packages];
7252 for (Package *package in packages) {
7253 if ([package half])
7254 [broken_ addObject:package];
7255 if ([package upgradableAndEssential:NO]) {
7256 if ([package essential])
7257 [essential_ addObject:package];
7258 ++changes;
7259 }
7260 }
7261
7262 if (changes != 0) {
7263 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7264 [buttonbar_ setBadgeValue:badge forButton:3];
7265 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7266 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7267 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7268 [self setApplicationBadge:badge];
7269 else
7270 [self setApplicationBadgeString:badge];
7271 } else {
7272 [buttonbar_ setBadgeValue:nil forButton:3];
7273 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7274 [buttonbar_ setBadgeAnimated:NO forButton:3];
7275 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7276 [self removeApplicationBadge];
7277 else // XXX: maybe use setApplicationBadgeString also?
7278 [self setApplicationIconBadgeNumber:0];
7279 }
7280
7281 Queuing_ = false;
7282 [buttonbar_ setBadgeValue:nil forButton:4];
7283
7284 [self updateData];
7285
7286 // XXX: what is this line of code for?
7287 if ([packages count] == 0);
7288 else if (Loaded_ || ManualRefresh) loaded:
7289 [self _loaded];
7290 else {
7291 Loaded_ = YES;
7292
7293 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7294 NSTimeInterval interval([update timeIntervalSinceNow]);
7295 if (interval <= 0 && interval > -600)
7296 goto loaded;
7297 }
7298
7299 [book_ update];
7300 }
7301 }
7302
7303 - (void) _saveConfig {
7304 if (Changed_) {
7305 _trace();
7306 NSString *error(nil);
7307 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7308 _trace();
7309 NSError *error(nil);
7310 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7311 NSLog(@"failure to save metadata data: %@", error);
7312 _trace();
7313 } else {
7314 NSLog(@"failure to serialize metadata: %@", error);
7315 return;
7316 }
7317
7318 Changed_ = false;
7319 }
7320 }
7321
7322 - (void) updateData {
7323 [self _saveConfig];
7324
7325 /* XXX: this is just stupid */
7326 if (tag_ != 2 && sections_ != nil)
7327 [sections_ reloadData];
7328 if (tag_ != 3 && changes_ != nil)
7329 [changes_ reloadData];
7330 if (tag_ != 5 && search_ != nil)
7331 [search_ reloadData];
7332
7333 [book_ reloadData];
7334 }
7335
7336 - (void) update_ {
7337 [database_ update];
7338 }
7339
7340 - (void) syncData {
7341 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7342 _assert(file != NULL);
7343
7344 NSArray *keys = [Sources_ allKeys];
7345
7346 for (NSString *key in keys) {
7347 NSDictionary *source = [Sources_ objectForKey:key];
7348
7349 fprintf(file, "%s %s %s\n",
7350 [[source objectForKey:@"Type"] UTF8String],
7351 [[source objectForKey:@"URI"] UTF8String],
7352 [[source objectForKey:@"Distribution"] UTF8String]
7353 );
7354 }
7355
7356 fclose(file);
7357
7358 [self _saveConfig];
7359
7360 [progress_
7361 detachNewThreadSelector:@selector(update_)
7362 toTarget:self
7363 withObject:nil
7364 title:CYLocalize("UPDATING_SOURCES")
7365 ];
7366 }
7367
7368 - (void) reloadData {
7369 @synchronized (self) {
7370 if (confirm_ == nil)
7371 [self _reloadData];
7372 }
7373 }
7374
7375 - (void) resolve {
7376 pkgProblemResolver *resolver = [database_ resolver];
7377
7378 resolver->InstallProtect();
7379 if (!resolver->Resolve(true))
7380 _error->Discard();
7381 }
7382
7383 - (void) popUpBook:(RVBook *)book {
7384 [underlay_ popSubview:book];
7385 }
7386
7387 - (CGRect) popUpBounds {
7388 return [underlay_ bounds];
7389 }
7390
7391 - (void) perform {
7392 [database_ prepare];
7393
7394 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7395 [confirm_ setDelegate:self];
7396
7397 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7398 [page setDelegate:self];
7399
7400 [confirm_ setPage:page];
7401 [self popUpBook:confirm_];
7402 }
7403
7404 - (void) queue {
7405 @synchronized (self) {
7406 [self perform];
7407 }
7408 }
7409
7410 - (void) clearPackage:(Package *)package {
7411 @synchronized (self) {
7412 [package clear];
7413 [self resolve];
7414 [self perform];
7415 }
7416 }
7417
7418 - (void) installPackage:(Package *)package {
7419 @synchronized (self) {
7420 [package install];
7421 [self resolve];
7422 [self perform];
7423 }
7424 }
7425
7426 - (void) removePackage:(Package *)package {
7427 @synchronized (self) {
7428 [package remove];
7429 [self resolve];
7430 [self perform];
7431 }
7432 }
7433
7434 - (void) distUpgrade {
7435 @synchronized (self) {
7436 [database_ upgrade];
7437 [self perform];
7438 }
7439 }
7440
7441 - (void) cancel {
7442 [self slideUp:[[[UIActionSheet alloc]
7443 initWithTitle:nil
7444 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7445 defaultButtonIndex:1
7446 delegate:self
7447 context:@"cancel"
7448 ] autorelease]];
7449 }
7450
7451 - (void) complete {
7452 @synchronized (self) {
7453 [self _reloadData];
7454
7455 if (confirm_ != nil) {
7456 [confirm_ release];
7457 confirm_ = nil;
7458 }
7459 }
7460 }
7461
7462 - (void) confirm {
7463 [overlay_ removeFromSuperview];
7464 reload_ = true;
7465
7466 [progress_
7467 detachNewThreadSelector:@selector(perform)
7468 toTarget:database_
7469 withObject:nil
7470 title:CYLocalize("RUNNING")
7471 ];
7472 }
7473
7474 - (void) bootstrap_ {
7475 [database_ update];
7476 [database_ upgrade];
7477 [database_ prepare];
7478 [database_ perform];
7479 }
7480
7481 /* XXX: replace and localize */
7482 - (void) bootstrap {
7483 [progress_
7484 detachNewThreadSelector:@selector(bootstrap_)
7485 toTarget:self
7486 withObject:nil
7487 title:@"Bootstrap Install"
7488 ];
7489 }
7490
7491 - (void) progressViewIsComplete:(ProgressView *)progress {
7492 if (confirm_ != nil) {
7493 [underlay_ addSubview:overlay_];
7494 [confirm_ popFromSuperviewAnimated:NO];
7495 }
7496
7497 [self complete];
7498 }
7499
7500 - (void) setPage:(RVPage *)page {
7501 [page resetViewAnimated:NO];
7502 [page setDelegate:self];
7503 [book_ setPage:page];
7504 }
7505
7506 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7507 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7508 [browser loadURL:url];
7509 return browser;
7510 }
7511
7512 - (void) _setHomePage {
7513 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7514 }
7515
7516 - (SectionsView *) sectionsView {
7517 if (sections_ == nil)
7518 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7519 return sections_;
7520 }
7521
7522 - (void) buttonBarItemTapped:(id)sender {
7523 unsigned tag = [sender tag];
7524 if (tag == tag_) {
7525 [book_ resetViewAnimated:YES];
7526 return;
7527 } else if (tag_ == 2 && tag != 2)
7528 [[self sectionsView] resetView];
7529
7530 switch (tag) {
7531 case 1: [self _setHomePage]; break;
7532
7533 case 2: [self setPage:[self sectionsView]]; break;
7534 case 3: [self setPage:changes_]; break;
7535 case 4: [self setPage:manage_]; break;
7536 case 5: [self setPage:search_]; break;
7537
7538 default: _assert(false);
7539 }
7540
7541 tag_ = tag;
7542 }
7543
7544 - (void) applicationWillSuspend {
7545 [database_ clean];
7546 [super applicationWillSuspend];
7547 }
7548
7549 - (void) askForSettings {
7550 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7551
7552 UIActionSheet *role = [[[UIActionSheet alloc]
7553 initWithTitle:CYLocalize("WHO_ARE_YOU")
7554 buttons:[NSArray arrayWithObjects:
7555 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7556 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7557 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7558 nil]
7559 defaultButtonIndex:-1
7560 delegate:self
7561 context:@"role"
7562 ] autorelease];
7563
7564 [role setBodyText:CYLocalize("ROLE_EX")];
7565 [role popupAlertAnimated:YES];
7566 }
7567
7568 - (void) setPackageView:(PackageView *)view {
7569 if (package_ == nil)
7570 package_ = [view retain];
7571 }
7572
7573 - (PackageView *) packageView {
7574 PackageView *view;
7575
7576 if (package_ == nil)
7577 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7578 else {
7579 return package_;
7580 view = [package_ autorelease];
7581 package_ = nil;
7582 }
7583
7584 return view;
7585 }
7586
7587 - (void) finish {
7588 if (hud_ != nil) {
7589 [self setStatusBarShowsProgress:NO];
7590 [self removeProgressHUD:hud_];
7591
7592 [hud_ autorelease];
7593 hud_ = nil;
7594
7595 pid_t pid = ExecFork();
7596 if (pid == 0) {
7597 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7598 perror("launchctl stop");
7599 }
7600
7601 return;
7602 }
7603
7604 if (Role_ == nil) {
7605 [self askForSettings];
7606 return;
7607 }
7608
7609 _trace();
7610 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7611
7612 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7613 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7614 0, 0, screenrect.size.width, screenrect.size.height - 48
7615 ) database:database_];
7616
7617 [book_ setDelegate:self];
7618
7619 [overlay_ addSubview:book_];
7620
7621 NSArray *buttonitems = [NSArray arrayWithObjects:
7622 [NSDictionary dictionaryWithObjectsAndKeys:
7623 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7624 @"home-up.png", kUIButtonBarButtonInfo,
7625 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7626 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7627 self, kUIButtonBarButtonTarget,
7628 @"Cydia", kUIButtonBarButtonTitle,
7629 @"0", kUIButtonBarButtonType,
7630 nil],
7631
7632 [NSDictionary dictionaryWithObjectsAndKeys:
7633 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7634 @"install-up.png", kUIButtonBarButtonInfo,
7635 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7636 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7637 self, kUIButtonBarButtonTarget,
7638 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7639 @"0", kUIButtonBarButtonType,
7640 nil],
7641
7642 [NSDictionary dictionaryWithObjectsAndKeys:
7643 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7644 @"changes-up.png", kUIButtonBarButtonInfo,
7645 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7646 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7647 self, kUIButtonBarButtonTarget,
7648 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7649 @"0", kUIButtonBarButtonType,
7650 nil],
7651
7652 [NSDictionary dictionaryWithObjectsAndKeys:
7653 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7654 @"manage-up.png", kUIButtonBarButtonInfo,
7655 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7656 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7657 self, kUIButtonBarButtonTarget,
7658 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7659 @"0", kUIButtonBarButtonType,
7660 nil],
7661
7662 [NSDictionary dictionaryWithObjectsAndKeys:
7663 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7664 @"search-up.png", kUIButtonBarButtonInfo,
7665 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7666 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7667 self, kUIButtonBarButtonTarget,
7668 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7669 @"0", kUIButtonBarButtonType,
7670 nil],
7671 nil];
7672
7673 buttonbar_ = [[UIToolbar alloc]
7674 initInView:overlay_
7675 withFrame:CGRectMake(
7676 0, screenrect.size.height - ButtonBarHeight_,
7677 screenrect.size.width, ButtonBarHeight_
7678 )
7679 withItemList:buttonitems
7680 ];
7681
7682 [buttonbar_ setDelegate:self];
7683 [buttonbar_ setBarStyle:1];
7684 [buttonbar_ setButtonBarTrackingMode:2];
7685
7686 int buttons[5] = {1, 2, 3, 4, 5};
7687 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7688 [buttonbar_ showButtonGroup:0 withDuration:0];
7689
7690 for (int i = 0; i != 5; ++i)
7691 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7692 i * 64 + 2, 1, 60, ButtonBarHeight_
7693 )];
7694
7695 [buttonbar_ showSelectionForButton:1];
7696 [overlay_ addSubview:buttonbar_];
7697
7698 [UIKeyboard initImplementationNow];
7699 CGSize keysize = [UIKeyboard defaultSize];
7700 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7701 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7702 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7703 [overlay_ addSubview:keyboard_];
7704
7705 if (!bootstrap_)
7706 [underlay_ addSubview:overlay_];
7707
7708 [self reloadData];
7709
7710 [self sectionsView];
7711 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7712 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7713
7714 manage_ = (ManageView *) [[self
7715 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7716 withClass:[ManageView class]
7717 ] retain];
7718
7719 [self setPackageView:[self packageView]];
7720
7721 PrintTimes();
7722
7723 if (bootstrap_)
7724 [self bootstrap];
7725 else
7726 [self _setHomePage];
7727 }
7728
7729 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7730 NSString *context([sheet context]);
7731
7732 if ([context isEqualToString:@"missing"])
7733 [sheet dismiss];
7734 else if ([context isEqualToString:@"cancel"]) {
7735 bool clear;
7736
7737 switch (button) {
7738 case 1:
7739 clear = false;
7740 break;
7741
7742 case 2:
7743 clear = true;
7744 break;
7745
7746 default:
7747 _assert(false);
7748 }
7749
7750 [sheet dismiss];
7751
7752 @synchronized (self) {
7753 if (clear)
7754 [self _reloadData];
7755 else {
7756 Queuing_ = true;
7757 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7758 [book_ reloadData];
7759 }
7760
7761 if (confirm_ != nil) {
7762 [confirm_ release];
7763 confirm_ = nil;
7764 }
7765 }
7766 } else if ([context isEqualToString:@"fixhalf"]) {
7767 switch (button) {
7768 case 1:
7769 @synchronized (self) {
7770 for (Package *broken in broken_) {
7771 [broken remove];
7772
7773 NSString *id = [broken id];
7774 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7775 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7776 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7777 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7778 }
7779
7780 [self resolve];
7781 [self perform];
7782 }
7783 break;
7784
7785 case 2:
7786 [broken_ removeAllObjects];
7787 [self _loaded];
7788 break;
7789
7790 default:
7791 _assert(false);
7792 }
7793
7794 [sheet dismiss];
7795 } else if ([context isEqualToString:@"role"]) {
7796 switch (button) {
7797 case 1: Role_ = @"User"; break;
7798 case 2: Role_ = @"Hacker"; break;
7799 case 3: Role_ = @"Developer"; break;
7800
7801 default:
7802 Role_ = nil;
7803 _assert(false);
7804 }
7805
7806 bool reset = Settings_ != nil;
7807
7808 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7809 Role_, @"Role",
7810 nil];
7811
7812 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7813
7814 Changed_ = true;
7815
7816 if (reset)
7817 [self updateData];
7818 else
7819 [self finish];
7820
7821 [sheet dismiss];
7822 } else if ([context isEqualToString:@"upgrade"]) {
7823 switch (button) {
7824 case 1:
7825 @synchronized (self) {
7826 for (Package *essential in essential_)
7827 [essential install];
7828
7829 [self resolve];
7830 [self perform];
7831 }
7832 break;
7833
7834 case 2:
7835 [self distUpgrade];
7836 break;
7837
7838 case 3:
7839 Ignored_ = YES;
7840 break;
7841
7842 default:
7843 _assert(false);
7844 }
7845
7846 [sheet dismiss];
7847 }
7848 }
7849
7850 - (void) reorganize { _pooled
7851 system("/usr/libexec/cydia/free.sh");
7852 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7853 }
7854
7855 - (void) applicationSuspend:(__GSEvent *)event {
7856 if (hud_ == nil && ![progress_ isRunning])
7857 [super applicationSuspend:event];
7858 }
7859
7860 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7861 if (hud_ == nil)
7862 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7863 }
7864
7865 - (void) _setSuspended:(BOOL)value {
7866 if (hud_ == nil)
7867 [super _setSuspended:value];
7868 }
7869
7870 - (UIProgressHUD *) addProgressHUD {
7871 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7872 [window_ setUserInteractionEnabled:NO];
7873 [hud show:YES];
7874 [progress_ addSubview:hud];
7875 return hud;
7876 }
7877
7878 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7879 [hud show:NO];
7880 [hud removeFromSuperview];
7881 [window_ setUserInteractionEnabled:YES];
7882 }
7883
7884 - (void) openMailToURL:(NSURL *)url {
7885 // XXX: this makes me sad
7886 #if 0
7887 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7888 #else
7889 [UIApp openURL:url];// asPanel:YES];
7890 #endif
7891 }
7892
7893 - (void) clearFirstResponder {
7894 if (id responder = [window_ firstResponder])
7895 [responder resignFirstResponder];
7896 }
7897
7898 - (RVPage *) pageForPackage:(NSString *)name {
7899 if (Package *package = [database_ packageWithName:name]) {
7900 PackageView *view([self packageView]);
7901 [view setPackage:package];
7902 return view;
7903 } else {
7904 UIActionSheet *sheet = [[[UIActionSheet alloc]
7905 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7906 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7907 defaultButtonIndex:0
7908 delegate:self
7909 context:@"missing"
7910 ] autorelease];
7911
7912 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7913
7914 [sheet popupAlertAnimated:YES];
7915 return nil;
7916 }
7917 }
7918
7919 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7920 if (tag != NULL)
7921 tag = 0;
7922
7923 NSString *scheme([[url scheme] lowercaseString]);
7924 if (![scheme isEqualToString:@"cydia"])
7925 return nil;
7926 NSString *path([url absoluteString]);
7927 if ([path length] < 8)
7928 return nil;
7929 path = [path substringFromIndex:8];
7930 if (![path hasPrefix:@"/"])
7931 path = [@"/" stringByAppendingString:path];
7932
7933 if ([path isEqualToString:@"/add-source"])
7934 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7935 else if ([path isEqualToString:@"/storage"])
7936 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7937 else if ([path isEqualToString:@"/sources"])
7938 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7939 else if ([path isEqualToString:@"/packages"])
7940 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7941 else if ([path hasPrefix:@"/url/"])
7942 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7943 else if ([path hasPrefix:@"/launch/"])
7944 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7945 else if ([path hasPrefix:@"/package-settings/"])
7946 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7947 else if ([path hasPrefix:@"/package-signature/"])
7948 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7949 else if ([path hasPrefix:@"/package/"])
7950 return [self pageForPackage:[path substringFromIndex:9]];
7951 else if ([path hasPrefix:@"/files/"]) {
7952 NSString *name = [path substringFromIndex:7];
7953
7954 if (Package *package = [database_ packageWithName:name]) {
7955 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7956 [files setPackage:package];
7957 return files;
7958 }
7959 }
7960
7961 return nil;
7962 }
7963
7964 - (void) applicationOpenURL:(NSURL *)url {
7965 [super applicationOpenURL:url];
7966 int tag;
7967 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7968 [self setPage:page];
7969 [buttonbar_ showSelectionForButton:tag];
7970 tag_ = tag;
7971 }
7972 }
7973
7974 - (void) applicationDidFinishLaunching:(id)unused {
7975 _trace();
7976 Font12_ = [[UIFont systemFontOfSize:12] retain];
7977 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7978 Font14_ = [[UIFont systemFontOfSize:14] retain];
7979 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7980 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7981
7982 tag_ = 1;
7983
7984 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7985 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7986
7987 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7988
7989 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7990 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7991
7992 [window_ orderFront:self];
7993 [window_ makeKey:self];
7994 [window_ setHidden:NO];
7995
7996 database_ = [Database sharedInstance];
7997 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7998 [database_ setDelegate:progress_];
7999 [window_ setContentView:progress_];
8000
8001 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8002 [progress_ setContentView:underlay_];
8003
8004 [progress_ resetView];
8005
8006 if (
8007 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8008 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8009 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8010 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8011 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8012 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8013 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8014 ) {
8015 [self setIdleTimerDisabled:YES];
8016
8017 hud_ = [[self addProgressHUD] retain];
8018 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8019
8020 [self setStatusBarShowsProgress:YES];
8021
8022 [NSThread
8023 detachNewThreadSelector:@selector(reorganize)
8024 toTarget:self
8025 withObject:nil
8026 ];
8027 } else
8028 [self finish];
8029 }
8030
8031 - (void) showKeyboard:(BOOL)show {
8032 CGSize keysize = [UIKeyboard defaultSize];
8033 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8034 CGRect keyup = keydown;
8035 keyup.origin.y -= keysize.height;
8036
8037 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8038 [animation setSignificantRectFields:2];
8039
8040 if (show) {
8041 [animation setStartFrame:keydown];
8042 [animation setEndFrame:keyup];
8043 [keyboard_ activate];
8044 } else {
8045 [animation setStartFrame:keyup];
8046 [animation setEndFrame:keydown];
8047 [keyboard_ deactivate];
8048 }
8049
8050 [[UIAnimator sharedAnimator]
8051 addAnimations:[NSArray arrayWithObjects:animation, nil]
8052 withDuration:KeyboardTime_
8053 start:YES
8054 ];
8055 }
8056
8057 - (void) slideUp:(UIActionSheet *)alert {
8058 if (Advanced_)
8059 [alert presentSheetFromButtonBar:buttonbar_];
8060 else
8061 [alert presentSheetInView:overlay_];
8062 }
8063
8064 @end
8065
8066 void AddPreferences(NSString *plist) { _pooled
8067 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8068 _assert(settings != NULL);
8069 NSMutableArray *items = [settings objectForKey:@"items"];
8070
8071 bool cydia(false);
8072
8073 for (NSMutableDictionary *item in items) {
8074 NSString *label = [item objectForKey:@"label"];
8075 if (label != nil && [label isEqualToString:@"Cydia"]) {
8076 cydia = true;
8077 break;
8078 }
8079 }
8080
8081 if (!cydia) {
8082 for (size_t i(0); i != [items count]; ++i) {
8083 NSDictionary *item([items objectAtIndex:i]);
8084 NSString *label = [item objectForKey:@"label"];
8085 if (label != nil && [label isEqualToString:@"General"]) {
8086 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8087 @"CydiaSettings", @"bundle",
8088 @"PSLinkCell", @"cell",
8089 [NSNumber numberWithBool:YES], @"hasIcon",
8090 [NSNumber numberWithBool:YES], @"isController",
8091 @"Cydia", @"label",
8092 nil] atIndex:(i + 1)];
8093
8094 break;
8095 }
8096 }
8097
8098 _assert([settings writeToFile:plist atomically:YES] == YES);
8099 }
8100 }
8101
8102 /*IMP alloc_;
8103 id Alloc_(id self, SEL selector) {
8104 id object = alloc_(self, selector);
8105 lprintf("[%s]A-%p\n", self->isa->name, object);
8106 return object;
8107 }*/
8108
8109 /*IMP dealloc_;
8110 id Dealloc_(id self, SEL selector) {
8111 id object = dealloc_(self, selector);
8112 lprintf("[%s]D-%p\n", self->isa->name, object);
8113 return object;
8114 }*/
8115
8116 Class $WebDefaultUIKitDelegate;
8117
8118 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8119
8120 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8121 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8122 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8123 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8124 }
8125
8126 int main(int argc, char *argv[]) { _pooled
8127 _trace();
8128
8129 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8130
8131 /* Library Hacks {{{ */
8132 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8133
8134 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8135 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8136 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8137 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8138 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8139 }
8140 /* }}} */
8141 /* Set Locale {{{ */
8142 Locale_ = CFLocaleCopyCurrent();
8143 Languages_ = [NSLocale preferredLanguages];
8144 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8145 //NSLog(@"%@", [Languages_ description]);
8146 const char *lang;
8147 if (Languages_ == nil || [Languages_ count] == 0)
8148 lang = NULL;
8149 else
8150 lang = [[Languages_ objectAtIndex:0] UTF8String];
8151 setenv("LANG", lang, true);
8152 //std::setlocale(LC_ALL, lang);
8153 NSLog(@"Setting Language: %s", lang);
8154 /* }}} */
8155
8156 // XXX: apr_app_initialize?
8157 apr_initialize();
8158
8159 /* Parse Arguments {{{ */
8160 bool substrate(false);
8161
8162 if (argc != 0) {
8163 char **args(argv);
8164 int arge(1);
8165
8166 for (int argi(1); argi != argc; ++argi)
8167 if (strcmp(argv[argi], "--") == 0) {
8168 arge = argi;
8169 argv[argi] = argv[0];
8170 argv += argi;
8171 argc -= argi;
8172 break;
8173 }
8174
8175 for (int argi(1); argi != arge; ++argi)
8176 if (strcmp(args[argi], "--bootstrap") == 0)
8177 bootstrap_ = true;
8178 else if (strcmp(args[argi], "--substrate") == 0)
8179 substrate = true;
8180 else
8181 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8182 }
8183 /* }}} */
8184
8185 {
8186 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8187 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8188 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8189 Sounds_Keyboard_ = [keyboard boolValue];
8190 }
8191
8192 App_ = [[NSBundle mainBundle] bundlePath];
8193 Home_ = NSHomeDirectory();
8194
8195 setuid(0);
8196 setgid(0);
8197
8198 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8199 alloc_ = alloc->method_imp;
8200 alloc->method_imp = (IMP) &Alloc_;*/
8201
8202 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8203 dealloc_ = dealloc->method_imp;
8204 dealloc->method_imp = (IMP) &Dealloc_;*/
8205
8206 size_t size;
8207
8208 int maxproc;
8209 size = sizeof(maxproc);
8210 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8211 perror("sysctlbyname(\"kern.maxproc\", ?)");
8212 else if (maxproc < 64) {
8213 maxproc = 64;
8214 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8215 perror("sysctlbyname(\"kern.maxproc\", #)");
8216 }
8217
8218 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8219 char *machine = new char[size];
8220 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8221 perror("sysctlbyname(\"hw.machine\", ?)");
8222 else
8223 Machine_ = machine;
8224
8225 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8226
8227 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8228 Build_ = [system objectForKey:@"ProductBuildVersion"];
8229 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8230 Product_ = [info objectForKey:@"SafariProductVersion"];
8231 Safari_ = [info objectForKey:@"CFBundleVersion"];
8232 }
8233
8234 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8235 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8236
8237 /* Load Database {{{ */
8238 _trace();
8239 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8240 _trace();
8241 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8242 _trace();
8243
8244 if (Metadata_ == NULL)
8245 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8246 else {
8247 Settings_ = [Metadata_ objectForKey:@"Settings"];
8248
8249 Packages_ = [Metadata_ objectForKey:@"Packages"];
8250 Sections_ = [Metadata_ objectForKey:@"Sections"];
8251 Sources_ = [Metadata_ objectForKey:@"Sources"];
8252 }
8253
8254 if (Settings_ != nil)
8255 Role_ = [Settings_ objectForKey:@"Role"];
8256
8257 if (Packages_ == nil) {
8258 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8259 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8260 }
8261
8262 if (Sections_ == nil) {
8263 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8264 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8265 }
8266
8267 if (Sources_ == nil) {
8268 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8269 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8270 }
8271 /* }}} */
8272
8273 #if RecycleWebViews
8274 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8275 #endif
8276
8277 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8278 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8279 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8280 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8281
8282 if (access("/User", F_OK) != 0) {
8283 _trace();
8284 system("/usr/libexec/cydia/firmware.sh");
8285 _trace();
8286 }
8287
8288 _assert([[NSFileManager defaultManager]
8289 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8290 withIntermediateDirectories:YES
8291 attributes:nil
8292 error:NULL
8293 ]);
8294
8295 if (access("/tmp/cydia.chk", F_OK) == 0) {
8296 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8297 _assert(errno == ENOENT);
8298 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8299 _assert(errno == ENOENT);
8300 }
8301
8302 _assert(pkgInitConfig(*_config));
8303 _assert(pkgInitSystem(*_config, _system));
8304
8305 if (lang != NULL)
8306 _config->Set("APT::Acquire::Translation", lang);
8307 _config->Set("Acquire::http::Timeout", 15);
8308 _config->Set("Acquire::http::MaxParallel", 4);
8309
8310 /* Color Choices {{{ */
8311 space_ = CGColorSpaceCreateDeviceRGB();
8312
8313 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8314 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8315 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8316 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8317 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8318 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8319 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8320 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8321 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8322 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8323 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8324 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8325 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8326 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8327 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8328
8329 //.93
8330 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8331 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8332 /* }}}*/
8333
8334 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8335
8336 /* UIKit Configuration {{{ */
8337 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8338 if ($GSFontSetUseLegacyFontMetrics != NULL)
8339 $GSFontSetUseLegacyFontMetrics(YES);
8340
8341 UIKeyboardDisableAutomaticAppearance();
8342 /* }}} */
8343
8344 _trace();
8345 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8346
8347 CGColorSpaceRelease(space_);
8348 CFRelease(Locale_);
8349
8350 return value;
8351 }