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