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