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