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