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