]> git.saurik.com Git - cydia.git/blob - Cydia.mm
Final fix to something stupid.
[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 1
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 (fatal && !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 /* XXX: ignore this because users suck and don't understand why refreshing is important: 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_ terminateWithSuccess];
4324 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4325 [delegate_ suspendWithAnimation:YES];
4326 else
4327 [delegate_ suspend];*/
4328 break;
4329
4330 case 2:
4331 system("launchctl stop com.apple.SpringBoard");
4332 break;
4333
4334 case 3:
4335 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4336 break;
4337
4338 case 4:
4339 system("reboot");
4340 break;
4341 }
4342 }
4343
4344 - (void) _retachThread {
4345 UINavigationItem *item([navbar_ topItem]);
4346 [item setTitle:UCLocalize("COMPLETE")];
4347
4348 [overlay_ addSubview:close_];
4349 [progress_ removeFromSuperview];
4350 [status_ removeFromSuperview];
4351
4352 [database_ popErrorWithTitle:title_];
4353 [delegate_ progressViewIsComplete:self];
4354
4355 if (Finish_ < 4) {
4356 FileFd file;
4357 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4358 _error->Discard();
4359 else {
4360 MMap mmap(file, MMap::ReadOnly);
4361 SHA1Summation sha1;
4362 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4363 if (!(notifyconf_ == sha1.Result()))
4364 Finish_ = 4;
4365 }
4366 }
4367
4368 if (Finish_ < 3) {
4369 FileFd file;
4370 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4371 _error->Discard();
4372 else {
4373 MMap mmap(file, MMap::ReadOnly);
4374 SHA1Summation sha1;
4375 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4376 if (!(springlist_ == sha1.Result()))
4377 Finish_ = 3;
4378 }
4379 }
4380
4381 switch (Finish_) {
4382 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4383 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4384 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4385 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4386 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4387 }
4388
4389 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4390 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4391
4392 unlink(IconCache_);
4393
4394 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4395 [cache autorelease];
4396
4397 NSFileManager *manager([NSFileManager defaultManager]);
4398 NSError *error(nil);
4399
4400 id system([cache objectForKey:@"System"]);
4401 if (system == nil)
4402 goto error;
4403
4404 struct stat info;
4405 if (stat(ListCache_, &info) == -1)
4406 goto error;
4407
4408 [system removeAllObjects];
4409
4410 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4411 for (NSString *app in apps)
4412 if ([app hasSuffix:@".app"]) {
4413 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4414 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4415 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4416 [info autorelease];
4417 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4418 [info setObject:path forKey:@"Path"];
4419 [info setObject:@"System" forKey:@"ApplicationType"];
4420 [system addInfoDictionary:info];
4421 }
4422 }
4423 }
4424 } else goto error;
4425
4426 [cache writeToFile:@ListCache_ atomically:YES];
4427
4428 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4429 goto error;
4430 if (chmod(ListCache_, info.st_mode) == -1)
4431 goto error;
4432
4433 if (false) error:
4434 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4435 }
4436
4437 notify_post("com.apple.mobile.application_installed");
4438
4439 [delegate_ setStatusBarShowsProgress:NO];
4440 }
4441
4442 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4443 [[data target] performSelector:[data selector] withObject:[data object]];
4444 [data release];
4445
4446 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4447 }
4448
4449 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4450 if (title_ != nil)
4451 [title_ release];
4452 if (title == nil)
4453 title_ = nil;
4454 else
4455 title_ = [title retain];
4456
4457 UINavigationItem *item([navbar_ topItem]);
4458 [item setTitle:title_];
4459
4460 [status_ setText:nil];
4461 [output_ setText:@""];
4462 [progress_ setProgress:0];
4463
4464 [close_ removeFromSuperview];
4465 [overlay_ addSubview:progress_];
4466 [overlay_ addSubview:status_];
4467
4468 [delegate_ setStatusBarShowsProgress:YES];
4469 running_ = YES;
4470
4471 {
4472 FileFd file;
4473 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4474 _error->Discard();
4475 else {
4476 MMap mmap(file, MMap::ReadOnly);
4477 SHA1Summation sha1;
4478 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4479 notifyconf_ = sha1.Result();
4480 }
4481 }
4482
4483 {
4484 FileFd file;
4485 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4486 _error->Discard();
4487 else {
4488 MMap mmap(file, MMap::ReadOnly);
4489 SHA1Summation sha1;
4490 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4491 springlist_ = sha1.Result();
4492 }
4493 }
4494
4495 [transition_ transition:6 toView:overlay_];
4496
4497 [NSThread
4498 detachNewThreadSelector:@selector(_detachNewThreadData:)
4499 toTarget:self
4500 withObject:[[ProgressData alloc]
4501 initWithSelector:selector
4502 target:target
4503 object:object
4504 ]
4505 ];
4506 }
4507
4508 - (void) repairWithSelector:(SEL)selector {
4509 [self
4510 detachNewThreadSelector:selector
4511 toTarget:database_
4512 withObject:nil
4513 title:UCLocalize("REPAIRING")
4514 ];
4515 }
4516
4517 - (void) setConfigurationData:(NSString *)data {
4518 [self
4519 performSelectorOnMainThread:@selector(_setConfigurationData:)
4520 withObject:data
4521 waitUntilDone:YES
4522 ];
4523 }
4524
4525 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4526 CYActionSheet *sheet([[[CYActionSheet alloc]
4527 initWithTitle:title
4528 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4529 defaultButtonIndex:0
4530 ] autorelease]);
4531
4532 [sheet setBodyText:error];
4533 [sheet yieldToPopupAlertAnimated:YES];
4534 [sheet dismiss];
4535 }
4536
4537 - (void) setProgressTitle:(NSString *)title {
4538 [self
4539 performSelectorOnMainThread:@selector(_setProgressTitle:)
4540 withObject:title
4541 waitUntilDone:YES
4542 ];
4543 }
4544
4545 - (void) setProgressPercent:(float)percent {
4546 [self
4547 performSelectorOnMainThread:@selector(_setProgressPercent:)
4548 withObject:[NSNumber numberWithFloat:percent]
4549 waitUntilDone:YES
4550 ];
4551 }
4552
4553 - (void) startProgress {
4554 }
4555
4556 - (void) addProgressOutput:(NSString *)output {
4557 [self
4558 performSelectorOnMainThread:@selector(_addProgressOutput:)
4559 withObject:output
4560 waitUntilDone:YES
4561 ];
4562 }
4563
4564 - (bool) isCancelling:(size_t)received {
4565 return false;
4566 }
4567
4568 - (void) _setConfigurationData:(NSString *)data {
4569 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4570
4571 if (!conffile_r(data)) {
4572 lprintf("E:invalid conffile\n");
4573 return;
4574 }
4575
4576 NSString *ofile = conffile_r[1];
4577 //NSString *nfile = conffile_r[2];
4578
4579 UIActionSheet *sheet = [[[UIActionSheet alloc]
4580 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4581 buttons:[NSArray arrayWithObjects:
4582 UCLocalize("KEEP_OLD_COPY"),
4583 UCLocalize("ACCEPT_NEW_COPY"),
4584 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4585 nil]
4586 defaultButtonIndex:0
4587 delegate:self
4588 context:@"conffile"
4589 ] autorelease];
4590
4591 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4592 [sheet popupAlertAnimated:YES];
4593 }
4594
4595 - (void) _setProgressTitle:(NSString *)title {
4596 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4597 for (size_t i(0), e([words count]); i != e; ++i) {
4598 NSString *word([words objectAtIndex:i]);
4599 if (Package *package = [database_ packageWithName:word])
4600 [words replaceObjectAtIndex:i withObject:[package name]];
4601 }
4602
4603 [status_ setText:[words componentsJoinedByString:@" "]];
4604 }
4605
4606 - (void) _setProgressPercent:(NSNumber *)percent {
4607 [progress_ setProgress:[percent floatValue]];
4608 }
4609
4610 - (void) _addProgressOutput:(NSString *)output {
4611 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4612 CGSize size = [output_ contentSize];
4613 CGRect rect = {{0, size.height}, {size.width, 0}};
4614 [output_ scrollRectToVisible:rect animated:YES];
4615 }
4616
4617 - (BOOL) isRunning {
4618 return running_;
4619 }
4620
4621 @end
4622 /* }}} */
4623
4624 /* Package Cell {{{ */
4625 @interface ContentView : UIView {
4626 _transient id delegate_;
4627 }
4628
4629 @end
4630
4631 @interface PackageCell : UITableViewCell {
4632 UIImage *icon_;
4633 NSString *name_;
4634 NSString *description_;
4635 bool commercial_;
4636 NSString *source_;
4637 UIImage *badge_;
4638 Package *package_;
4639 UIColor *color_;
4640 ContentView *content_;
4641 BOOL faded_;
4642 float fade_;
4643 UIImage *placard_;
4644 }
4645
4646 - (PackageCell *) init;
4647 - (void) setPackage:(Package *)package;
4648
4649 + (int) heightForPackage:(Package *)package;
4650 - (void) drawContentRect:(CGRect)rect;
4651
4652 @end
4653
4654 @implementation ContentView
4655
4656 - (id) initWithFrame:(CGRect)frame {
4657 if ((self = [super initWithFrame:frame]) != nil) {
4658 } return self;
4659 }
4660
4661 - (void) setDelegate:(id)delegate {
4662 delegate_ = delegate;
4663 }
4664
4665 - (void) drawRect:(CGRect)rect {
4666 [super drawRect:rect];
4667 [delegate_ drawContentRect:rect];
4668 }
4669
4670 @end
4671
4672 @implementation PackageCell
4673
4674 - (void) clearPackage {
4675 if (icon_ != nil) {
4676 [icon_ release];
4677 icon_ = nil;
4678 }
4679
4680 if (name_ != nil) {
4681 [name_ release];
4682 name_ = nil;
4683 }
4684
4685 if (description_ != nil) {
4686 [description_ release];
4687 description_ = nil;
4688 }
4689
4690 if (source_ != nil) {
4691 [source_ release];
4692 source_ = nil;
4693 }
4694
4695 if (badge_ != nil) {
4696 [badge_ release];
4697 badge_ = nil;
4698 }
4699
4700 if (placard_ != nil) {
4701 [placard_ release];
4702 placard_ = nil;
4703 }
4704
4705 [package_ release];
4706 package_ = nil;
4707 }
4708
4709 - (void) dealloc {
4710 [self clearPackage];
4711 [content_ release];
4712 [color_ release];
4713 [super dealloc];
4714 }
4715
4716 - (float) fade {
4717 return faded_ ? [self selectionPercent] : fade_;
4718 }
4719
4720 - (PackageCell *) init {
4721 CGRect frame(CGRectMake(0, 0, 320, 74));
4722 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4723 UIView *content([self contentView]);
4724 CGRect bounds([content bounds]);
4725 content_ = [[ContentView alloc] initWithFrame:bounds];
4726 [content_ setDelegate:self];
4727 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4728 [content_ setOpaque:YES];
4729 [content addSubview:content_];
4730 if ([self respondsToSelector:@selector(selectionPercent)])
4731 faded_ = YES;
4732 } return self;
4733 }
4734
4735 - (void) _setBackgroundColor {
4736 UIColor *color;
4737 if (NSString *mode = [package_ mode]) {
4738 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4739 color = remove ? RemovingColor_ : InstallingColor_;
4740 } else
4741 color = [UIColor whiteColor];
4742
4743 [content_ setBackgroundColor:color];
4744 [self setNeedsDisplay];
4745 }
4746
4747 - (void) setPackage:(Package *)package {
4748 [self clearPackage];
4749 [package parse];
4750
4751 Source *source = [package source];
4752
4753 icon_ = [[package icon] retain];
4754 name_ = [[package name] retain];
4755 description_ = [[package shortDescription] retain];
4756 commercial_ = [package isCommercial];
4757
4758 package_ = [package retain];
4759
4760 NSString *label = nil;
4761 bool trusted = false;
4762
4763 if (source != nil) {
4764 label = [source label];
4765 trusted = [source trusted];
4766 } else if ([[package id] isEqualToString:@"firmware"])
4767 label = UCLocalize("APPLE");
4768 else
4769 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4770
4771 NSString *from(label);
4772
4773 NSString *section = [package simpleSection];
4774 if (section != nil && ![section isEqualToString:label]) {
4775 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4776 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4777 }
4778
4779 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4780 source_ = [from retain];
4781
4782 if (NSString *purpose = [package primaryPurpose])
4783 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4784 badge_ = [badge_ retain];
4785
4786 if ([package installed] != nil)
4787 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4788 placard_ = [placard_ retain];
4789
4790 [self _setBackgroundColor];
4791 [content_ setNeedsDisplay];
4792 }
4793
4794 - (void) drawContentRect:(CGRect)rect {
4795 bool selected([self isSelected]);
4796
4797 #if 0
4798 CGContextRef context(UIGraphicsGetCurrentContext());
4799 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4800 CGContextFillRect(context, rect);
4801 #endif
4802
4803 if (icon_ != nil) {
4804 CGRect rect;
4805 rect.size = [icon_ size];
4806
4807 rect.size.width /= 2;
4808 rect.size.height /= 2;
4809
4810 rect.origin.x = 25 - rect.size.width / 2;
4811 rect.origin.y = 25 - rect.size.height / 2;
4812
4813 [icon_ drawInRect:rect];
4814 }
4815
4816 if (badge_ != nil) {
4817 CGSize size = [badge_ size];
4818
4819 [badge_ drawAtPoint:CGPointMake(
4820 36 - size.width / 2,
4821 36 - size.height / 2
4822 )];
4823 }
4824
4825 if (selected)
4826 UISetColor(White_);
4827
4828 if (!selected)
4829 UISetColor(commercial_ ? Purple_ : Black_);
4830 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(placard_ == nil ? 240 : 214) withFont:Font18Bold_ ellipsis:2];
4831 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4832
4833 if (!selected)
4834 UISetColor(commercial_ ? Purplish_ : Gray_);
4835 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:274 withFont:Font14_ ellipsis:2];
4836
4837 if (placard_ != nil)
4838 [placard_ drawAtPoint:CGPointMake(268, 9)];
4839 }
4840
4841 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4842 //[self _setBackgroundColor];
4843 [super setSelected:selected animated:fade];
4844 [content_ setNeedsDisplay];
4845 }
4846
4847 + (int) heightForPackage:(Package *)package {
4848 return 73;
4849 }
4850
4851 @end
4852 /* }}} */
4853 /* Section Cell {{{ */
4854 @interface SectionCell : UISimpleTableCell {
4855 NSString *section_;
4856 NSString *name_;
4857 NSString *count_;
4858 UIImage *icon_;
4859 _UISwitchSlider *switch_;
4860 BOOL editing_;
4861 }
4862
4863 - (id) init;
4864 - (void) setSection:(Section *)section editing:(BOOL)editing;
4865
4866 @end
4867
4868 @implementation SectionCell
4869
4870 - (void) clearSection {
4871 if (section_ != nil) {
4872 [section_ release];
4873 section_ = nil;
4874 }
4875
4876 if (name_ != nil) {
4877 [name_ release];
4878 name_ = nil;
4879 }
4880
4881 if (count_ != nil) {
4882 [count_ release];
4883 count_ = nil;
4884 }
4885 }
4886
4887 - (void) dealloc {
4888 [self clearSection];
4889 [icon_ release];
4890 [switch_ release];
4891 [super dealloc];
4892 }
4893
4894 - (id) init {
4895 if ((self = [super init]) != nil) {
4896 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4897
4898 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4899 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4900 } return self;
4901 }
4902
4903 - (void) onSwitch:(id)sender {
4904 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4905 if (metadata == nil) {
4906 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4907 [Sections_ setObject:metadata forKey:section_];
4908 }
4909
4910 Changed_ = true;
4911 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4912 }
4913
4914 - (void) setSection:(Section *)section editing:(BOOL)editing {
4915 if (editing != editing_) {
4916 if (editing_)
4917 [switch_ removeFromSuperview];
4918 else
4919 [self addSubview:switch_];
4920 editing_ = editing;
4921 }
4922
4923 [self clearSection];
4924
4925 if (section == nil) {
4926 name_ = [UCLocalize("ALL_PACKAGES") retain];
4927 count_ = nil;
4928 } else {
4929 section_ = [section localized];
4930 if (section_ != nil)
4931 section_ = [section_ retain];
4932 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4933 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4934
4935 if (editing_)
4936 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4937 }
4938 }
4939
4940 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4941 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4942
4943 if (selected)
4944 UISetColor(White_);
4945
4946 if (!selected)
4947 UISetColor(Black_);
4948 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4949
4950 CGSize size = [count_ sizeWithFont:Font14_];
4951
4952 UISetColor(White_);
4953 if (count_ != nil)
4954 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4955
4956 [super drawContentInRect:rect selected:selected];
4957 }
4958
4959 @end
4960 /* }}} */
4961
4962 /* File Table {{{ */
4963 @interface FileTable : RVPage {
4964 _transient Database *database_;
4965 Package *package_;
4966 NSString *name_;
4967 NSMutableArray *files_;
4968 UITable *list_;
4969 }
4970
4971 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4972 - (void) setPackage:(Package *)package;
4973
4974 @end
4975
4976 @implementation FileTable
4977
4978 - (void) dealloc {
4979 if (package_ != nil)
4980 [package_ release];
4981 if (name_ != nil)
4982 [name_ release];
4983 [files_ release];
4984 [list_ release];
4985 [super dealloc];
4986 }
4987
4988 - (int) numberOfRowsInTable:(UITable *)table {
4989 return files_ == nil ? 0 : [files_ count];
4990 }
4991
4992 - (float) table:(UITable *)table heightForRow:(int)row {
4993 return 24;
4994 }
4995
4996 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4997 if (reusing == nil) {
4998 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4999 UIFont *font = [UIFont systemFontOfSize:16];
5000 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
5001 }
5002 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
5003 return reusing;
5004 }
5005
5006 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5007 return NO;
5008 }
5009
5010 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5011 if ((self = [super initWithBook:book]) != nil) {
5012 database_ = database;
5013
5014 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5015
5016 list_ = [[UITable alloc] initWithFrame:[self bounds]];
5017 [self addSubview:list_];
5018
5019 UITableColumn *column = [[[UITableColumn alloc]
5020 initWithTitle:UCLocalize("NAME")
5021 identifier:@"name"
5022 width:[self frame].size.width
5023 ] autorelease];
5024
5025 [list_ setDataSource:self];
5026 [list_ setSeparatorStyle:1];
5027 [list_ addTableColumn:column];
5028 [list_ setDelegate:self];
5029 [list_ setReusesTableCells:YES];
5030 } return self;
5031 }
5032
5033 - (void) setPackage:(Package *)package {
5034 if (package_ != nil) {
5035 [package_ autorelease];
5036 package_ = nil;
5037 }
5038
5039 if (name_ != nil) {
5040 [name_ release];
5041 name_ = nil;
5042 }
5043
5044 [files_ removeAllObjects];
5045
5046 if (package != nil) {
5047 package_ = [package retain];
5048 name_ = [[package id] retain];
5049
5050 if (NSArray *files = [package files])
5051 [files_ addObjectsFromArray:files];
5052
5053 if ([files_ count] != 0) {
5054 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5055 [files_ removeObjectAtIndex:0];
5056 [files_ sortUsingSelector:@selector(compareByPath:)];
5057
5058 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5059 [stack addObject:@"/"];
5060
5061 for (int i(0), e([files_ count]); i != e; ++i) {
5062 NSString *file = [files_ objectAtIndex:i];
5063 while (![file hasPrefix:[stack lastObject]])
5064 [stack removeLastObject];
5065 NSString *directory = [stack lastObject];
5066 [stack addObject:[file stringByAppendingString:@"/"]];
5067 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5068 ([stack count] - 2) * 3, "",
5069 [file substringFromIndex:[directory length]]
5070 ]];
5071 }
5072 }
5073 }
5074
5075 [list_ reloadData];
5076 }
5077
5078 - (void) resetViewAnimated:(BOOL)animated {
5079 [list_ resetViewAnimated:animated];
5080 }
5081
5082 - (void) reloadData {
5083 [self setPackage:[database_ packageWithName:name_]];
5084 [self reloadButtons];
5085 }
5086
5087 - (NSString *) title {
5088 return UCLocalize("INSTALLED_FILES");
5089 }
5090
5091 - (NSString *) backButtonTitle {
5092 return UCLocalize("FILES");
5093 }
5094
5095 @end
5096 /* }}} */
5097 /* Package View {{{ */
5098 @interface PackageView : CydiaBrowserView {
5099 _transient Database *database_;
5100 Package *package_;
5101 NSString *name_;
5102 bool commercial_;
5103 NSMutableArray *buttons_;
5104 }
5105
5106 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5107 - (void) setPackage:(Package *)package;
5108
5109 @end
5110
5111 @implementation PackageView
5112
5113 - (void) dealloc {
5114 if (package_ != nil)
5115 [package_ release];
5116 if (name_ != nil)
5117 [name_ release];
5118 [buttons_ release];
5119 [super dealloc];
5120 }
5121
5122 - (void) release {
5123 if ([self retainCount] == 1)
5124 [delegate_ setPackageView:self];
5125 [super release];
5126 }
5127
5128 /* XXX: this is not safe at all... localization of /fail/ */
5129 - (void) _clickButtonWithName:(NSString *)name {
5130 if ([name isEqualToString:UCLocalize("CLEAR")])
5131 [delegate_ clearPackage:package_];
5132 else if ([name isEqualToString:UCLocalize("INSTALL")])
5133 [delegate_ installPackage:package_];
5134 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5135 [delegate_ installPackage:package_];
5136 else if ([name isEqualToString:UCLocalize("REMOVE")])
5137 [delegate_ removePackage:package_];
5138 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5139 [delegate_ installPackage:package_];
5140 else _assert(false);
5141 }
5142
5143 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5144 NSString *context([sheet context]);
5145
5146 if ([context isEqualToString:@"modify"]) {
5147 int count = [buttons_ count];
5148 _assert(count != 0);
5149 _assert(button <= count + 1);
5150
5151 if (count != button - 1)
5152 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5153
5154 [sheet dismiss];
5155 } else
5156 [super alertSheet:sheet buttonClicked:button];
5157 }
5158
5159 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5160 return [super webView:sender didFinishLoadForFrame:frame];
5161 }
5162
5163 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5164 [super webView:sender didClearWindowObject:window forFrame:frame];
5165 [window setValue:package_ forKey:@"package"];
5166 }
5167
5168 - (bool) _allowJavaScriptPanel {
5169 return commercial_;
5170 }
5171
5172 #if !AlwaysReload
5173 - (void) __rightButtonClicked {
5174 int count([buttons_ count]);
5175 if (count == 0)
5176 return;
5177
5178 if (count == 1)
5179 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5180 else {
5181 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5182 [buttons addObjectsFromArray:buttons_];
5183 [buttons addObject:UCLocalize("CANCEL")];
5184
5185 [delegate_ slideUp:[[[UIActionSheet alloc]
5186 initWithTitle:nil
5187 buttons:buttons
5188 defaultButtonIndex:([buttons count] - 1)
5189 delegate:self
5190 context:@"modify"
5191 ] autorelease]];
5192 }
5193 }
5194
5195 - (void) _rightButtonClicked {
5196 if (commercial_)
5197 [super _rightButtonClicked];
5198 else
5199 [self __rightButtonClicked];
5200 }
5201 #endif
5202
5203 - (id) _rightButtonTitle {
5204 int count = [buttons_ count];
5205 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5206 }
5207
5208 - (NSString *) backButtonTitle {
5209 return @"Details";
5210 }
5211
5212 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5213 if ((self = [super initWithBook:book]) != nil) {
5214 database_ = database;
5215 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5216 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5217 } return self;
5218 }
5219
5220 - (void) setPackage:(Package *)package {
5221 if (package_ != nil) {
5222 [package_ autorelease];
5223 package_ = nil;
5224 }
5225
5226 if (name_ != nil) {
5227 [name_ release];
5228 name_ = nil;
5229 }
5230
5231 [buttons_ removeAllObjects];
5232
5233 if (package != nil) {
5234 [package parse];
5235
5236 package_ = [package retain];
5237 name_ = [[package id] retain];
5238 commercial_ = [package isCommercial];
5239
5240 if ([package_ mode] != nil)
5241 [buttons_ addObject:UCLocalize("CLEAR")];
5242 if ([package_ source] == nil);
5243 else if ([package_ upgradableAndEssential:NO])
5244 [buttons_ addObject:UCLocalize("UPGRADE")];
5245 else if ([package_ uninstalled])
5246 [buttons_ addObject:UCLocalize("INSTALL")];
5247 else
5248 [buttons_ addObject:UCLocalize("REINSTALL")];
5249 if (![package_ uninstalled])
5250 [buttons_ addObject:UCLocalize("REMOVE")];
5251
5252 if (special_ != NULL) {
5253 CGRect frame([webview_ frame]);
5254 frame.size.width = 320;
5255 frame.size.height = 0;
5256 [webview_ setFrame:frame];
5257
5258 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5259
5260 WebThreadLock();
5261 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5262
5263 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5264
5265 [self setFinishHook:nil];
5266 [self setPopupHook:nil];
5267 WebThreadUnlock();
5268
5269 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5270 [super callFunction:special_];
5271 }
5272 }
5273
5274 [self reloadButtons];
5275 }
5276
5277 - (bool) isLoading {
5278 return commercial_ ? [super isLoading] : false;
5279 }
5280
5281 - (void) reloadData {
5282 [self setPackage:[database_ packageWithName:name_]];
5283 }
5284
5285 @end
5286 /* }}} */
5287 /* Package Table {{{ */
5288 @interface PackageTable : RVPage {
5289 _transient Database *database_;
5290 NSString *title_;
5291 NSMutableArray *packages_;
5292 NSMutableArray *sections_;
5293 UITableView *list_;
5294 NSMutableArray *index_;
5295 NSMutableDictionary *indices_;
5296 }
5297
5298 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5299
5300 - (void) setDelegate:(id)delegate;
5301
5302 - (void) reloadData;
5303 - (void) resetCursor;
5304
5305 - (UITableView *) list;
5306
5307 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5308
5309 @end
5310
5311 @implementation PackageTable
5312
5313 - (void) dealloc {
5314 [list_ setDataSource:nil];
5315
5316 [title_ release];
5317 [packages_ release];
5318 [sections_ release];
5319 [list_ release];
5320 [index_ release];
5321 [indices_ release];
5322 [super dealloc];
5323 }
5324
5325 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5326 NSInteger count([sections_ count]);
5327 return count == 0 ? 1 : count;
5328 }
5329
5330 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5331 if ([sections_ count] == 0)
5332 return nil;
5333 return [[sections_ objectAtIndex:section] name];
5334 }
5335
5336 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5337 if ([sections_ count] == 0)
5338 return 0;
5339 return [[sections_ objectAtIndex:section] count];
5340 }
5341
5342 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5343 Section *section([sections_ objectAtIndex:[path section]]);
5344 NSInteger row([path row]);
5345 Package *package([packages_ objectAtIndex:([section row] + row)]);
5346 return package;
5347 }
5348
5349 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5350 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5351 if (cell == nil)
5352 cell = [[[PackageCell alloc] init] autorelease];
5353 [cell setPackage:[self packageAtIndexPath:path]];
5354 return cell;
5355 }
5356
5357 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5358 return 73;
5359 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5360 }
5361
5362 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5363 Package *package([self packageAtIndexPath:path]);
5364 package = [database_ packageWithName:[package id]];
5365 PackageView *view([delegate_ packageView]);
5366 [view setPackage:package];
5367 [view setDelegate:delegate_];
5368 [book_ pushPage:view];
5369 return path;
5370 }
5371
5372 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5373 return [packages_ count] > 20 ? index_ : nil;
5374 }
5375
5376 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5377 return index;
5378 }
5379
5380 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5381 if ((self = [super initWithBook:book]) != nil) {
5382 database_ = database;
5383 title_ = [title retain];
5384
5385 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5386 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5387
5388 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5389 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5390
5391 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5392 [list_ setDataSource:self];
5393 [list_ setDelegate:self];
5394
5395 [self addSubview:list_];
5396
5397 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5398 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5399 } return self;
5400 }
5401
5402 - (void) setDelegate:(id)delegate {
5403 delegate_ = delegate;
5404 }
5405
5406 - (bool) hasPackage:(Package *)package {
5407 return true;
5408 }
5409
5410 - (void) reloadData {
5411 NSArray *packages = [database_ packages];
5412
5413 [packages_ removeAllObjects];
5414 [sections_ removeAllObjects];
5415
5416 _profile(PackageTable$reloadData$Filter)
5417 for (Package *package in packages)
5418 if ([self hasPackage:package])
5419 [packages_ addObject:package];
5420 _end
5421
5422 [index_ removeAllObjects];
5423 [indices_ removeAllObjects];
5424
5425 Section *section = nil;
5426
5427 _profile(PackageTable$reloadData$Section)
5428 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5429 Package *package;
5430 unichar index;
5431
5432 _profile(PackageTable$reloadData$Section$Package)
5433 package = [packages_ objectAtIndex:offset];
5434 index = [package index];
5435 _end
5436
5437 if (section == nil || [section index] != index) {
5438 _profile(PackageTable$reloadData$Section$Allocate)
5439 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5440 _end
5441
5442 [index_ addObject:[section name]];
5443 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5444
5445 _profile(PackageTable$reloadData$Section$Add)
5446 [sections_ addObject:section];
5447 _end
5448 }
5449
5450 [section addToCount];
5451 }
5452 _end
5453
5454 _profile(PackageTable$reloadData$List)
5455 [list_ reloadData];
5456 _end
5457 }
5458
5459 - (NSString *) title {
5460 return title_;
5461 }
5462
5463 - (void) resetViewAnimated:(BOOL)animated {
5464 [list_ resetViewAnimated:animated];
5465 }
5466
5467 - (void) resetCursor {
5468 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5469 }
5470
5471 - (UITableView *) list {
5472 return list_;
5473 }
5474
5475 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5476 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5477 }
5478
5479 @end
5480 /* }}} */
5481 /* Filtered Package Table {{{ */
5482 @interface FilteredPackageTable : PackageTable {
5483 SEL filter_;
5484 IMP imp_;
5485 id object_;
5486 }
5487
5488 - (void) setObject:(id)object;
5489
5490 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5491
5492 @end
5493
5494 @implementation FilteredPackageTable
5495
5496 - (void) dealloc {
5497 if (object_ != nil)
5498 [object_ release];
5499 [super dealloc];
5500 }
5501
5502 - (void) setObject:(id)object {
5503 if (object_ != nil)
5504 [object_ release];
5505 if (object == nil)
5506 object_ = nil;
5507 else
5508 object_ = [object retain];
5509 }
5510
5511 - (bool) hasPackage:(Package *)package {
5512 _profile(FilteredPackageTable$hasPackage)
5513 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5514 _end
5515 }
5516
5517 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5518 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5519 filter_ = filter;
5520 object_ = object == nil ? nil : [object retain];
5521
5522 /* XXX: this is an unsafe optimization of doomy hell */
5523 Method method(class_getInstanceMethod([Package class], filter));
5524 _assert(method != NULL);
5525 imp_ = method_getImplementation(method);
5526 _assert(imp_ != NULL);
5527
5528 [self reloadData];
5529 } return self;
5530 }
5531
5532 @end
5533 /* }}} */
5534
5535 /* Add Source View {{{ */
5536 @interface AddSourceView : RVPage {
5537 _transient Database *database_;
5538 }
5539
5540 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5541
5542 @end
5543
5544 @implementation AddSourceView
5545
5546 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5547 if ((self = [super initWithBook:book]) != nil) {
5548 database_ = database;
5549 } return self;
5550 }
5551
5552 @end
5553 /* }}} */
5554 /* Source Cell {{{ */
5555 @interface SourceCell : UITableCell {
5556 UIImage *icon_;
5557 NSString *origin_;
5558 NSString *description_;
5559 NSString *label_;
5560 }
5561
5562 - (void) dealloc;
5563
5564 - (SourceCell *) initWithSource:(Source *)source;
5565
5566 @end
5567
5568 @implementation SourceCell
5569
5570 - (void) dealloc {
5571 [icon_ release];
5572 [origin_ release];
5573 [description_ release];
5574 [label_ release];
5575 [super dealloc];
5576 }
5577
5578 - (SourceCell *) initWithSource:(Source *)source {
5579 if ((self = [super init]) != nil) {
5580 if (icon_ == nil)
5581 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5582 if (icon_ == nil)
5583 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5584 icon_ = [icon_ retain];
5585
5586 origin_ = [[source name] retain];
5587 label_ = [[source uri] retain];
5588 description_ = [[source description] retain];
5589 } return self;
5590 }
5591
5592 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5593 if (icon_ != nil)
5594 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5595
5596 if (selected)
5597 UISetColor(White_);
5598
5599 if (!selected)
5600 UISetColor(Black_);
5601 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5602
5603 if (!selected)
5604 UISetColor(Blue_);
5605 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5606
5607 if (!selected)
5608 UISetColor(Gray_);
5609 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5610
5611 [super drawContentInRect:rect selected:selected];
5612 }
5613
5614 @end
5615 /* }}} */
5616 /* Source Table {{{ */
5617 @interface SourceTable : RVPage {
5618 _transient Database *database_;
5619 UISectionList *list_;
5620 NSMutableArray *sources_;
5621 UIActionSheet *alert_;
5622 int offset_;
5623
5624 NSString *href_;
5625 UIProgressHUD *hud_;
5626 NSError *error_;
5627
5628 //NSURLConnection *installer_;
5629 NSURLConnection *trivial_bz2_;
5630 NSURLConnection *trivial_gz_;
5631 //NSURLConnection *automatic_;
5632
5633 BOOL trivial_;
5634 }
5635
5636 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5637
5638 @end
5639
5640 @implementation SourceTable
5641
5642 - (void) _deallocConnection:(NSURLConnection *)connection {
5643 if (connection != nil) {
5644 [connection cancel];
5645 //[connection setDelegate:nil];
5646 [connection release];
5647 }
5648 }
5649
5650 - (void) dealloc {
5651 [[list_ table] setDelegate:nil];
5652 [list_ setDataSource:nil];
5653
5654 if (href_ != nil)
5655 [href_ release];
5656 if (hud_ != nil)
5657 [hud_ release];
5658 if (error_ != nil)
5659 [error_ release];
5660
5661 //[self _deallocConnection:installer_];
5662 [self _deallocConnection:trivial_gz_];
5663 [self _deallocConnection:trivial_bz2_];
5664 //[self _deallocConnection:automatic_];
5665
5666 [sources_ release];
5667 [list_ release];
5668 [super dealloc];
5669 }
5670
5671 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5672 return offset_ == 0 ? 1 : 2;
5673 }
5674
5675 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5676 switch (section + (offset_ == 0 ? 1 : 0)) {
5677 case 0: return UCLocalize("ENTERED_BY_USER");
5678 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5679
5680 _nodefault
5681 }
5682 }
5683
5684 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5685 switch (section + (offset_ == 0 ? 1 : 0)) {
5686 case 0: return 0;
5687 case 1: return offset_;
5688
5689 _nodefault
5690 }
5691 }
5692
5693 - (int) numberOfRowsInTable:(UITable *)table {
5694 return [sources_ count];
5695 }
5696
5697 - (float) table:(UITable *)table heightForRow:(int)row {
5698 Source *source = [sources_ objectAtIndex:row];
5699 return [source description] == nil ? 56 : 73;
5700 }
5701
5702 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5703 Source *source = [sources_ objectAtIndex:row];
5704 // XXX: weird warning, stupid selectors ;P
5705 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5706 }
5707
5708 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5709 return YES;
5710 }
5711
5712 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5713 return YES;
5714 }
5715
5716 - (void) tableRowSelected:(NSNotification*)notification {
5717 UITable *table([list_ table]);
5718 int row([table selectedRow]);
5719 if (row == INT_MAX)
5720 return;
5721
5722 Source *source = [sources_ objectAtIndex:row];
5723
5724 PackageTable *packages = [[[FilteredPackageTable alloc]
5725 initWithBook:book_
5726 database:database_
5727 title:[source label]
5728 filter:@selector(isVisibleInSource:)
5729 with:source
5730 ] autorelease];
5731
5732 [packages setDelegate:delegate_];
5733
5734 [book_ pushPage:packages];
5735 }
5736
5737 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5738 Source *source = [sources_ objectAtIndex:row];
5739 return [source record] != nil;
5740 }
5741
5742 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5743 [[list_ table] setDeleteConfirmationRow:row];
5744 }
5745
5746 - (void) table:(UITable *)table deleteRow:(int)row {
5747 Source *source = [sources_ objectAtIndex:row];
5748 [Sources_ removeObjectForKey:[source key]];
5749 [delegate_ syncData];
5750 }
5751
5752 - (void) complete {
5753 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5754 @"deb", @"Type",
5755 href_, @"URI",
5756 @"./", @"Distribution",
5757 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5758
5759 [delegate_ syncData];
5760 }
5761
5762 - (NSString *) getWarning {
5763 NSString *href(href_);
5764 NSRange colon([href rangeOfString:@"://"]);
5765 if (colon.location != NSNotFound)
5766 href = [href substringFromIndex:(colon.location + 3)];
5767 href = [href stringByAddingPercentEscapes];
5768 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5769 href = [href stringByCachingURLWithCurrentCDN];
5770
5771 NSURL *url([NSURL URLWithString:href]);
5772
5773 NSStringEncoding encoding;
5774 NSError *error(nil);
5775
5776 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5777 return [warning length] == 0 ? nil : warning;
5778 return nil;
5779 }
5780
5781 - (void) _endConnection:(NSURLConnection *)connection {
5782 NSURLConnection **field = NULL;
5783 if (connection == trivial_bz2_)
5784 field = &trivial_bz2_;
5785 else if (connection == trivial_gz_)
5786 field = &trivial_gz_;
5787 _assert(field != NULL);
5788 [connection release];
5789 *field = nil;
5790
5791 if (
5792 trivial_bz2_ == nil &&
5793 trivial_gz_ == nil
5794 ) {
5795 bool defer(false);
5796
5797 if (trivial_) {
5798 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5799 defer = true;
5800
5801 UIActionSheet *sheet = [[[UIActionSheet alloc]
5802 initWithTitle:UCLocalize("SOURCE_WARNING")
5803 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5804 defaultButtonIndex:0
5805 delegate:self
5806 context:@"warning"
5807 ] autorelease];
5808
5809 [sheet setNumberOfRows:1];
5810
5811 [sheet setBodyText:warning];
5812 [sheet popupAlertAnimated:YES];
5813 } else
5814 [self complete];
5815 } else if (error_ != nil) {
5816 UIActionSheet *sheet = [[[UIActionSheet alloc]
5817 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5818 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5819 defaultButtonIndex:0
5820 delegate:self
5821 context:@"urlerror"
5822 ] autorelease];
5823
5824 [sheet setBodyText:[error_ localizedDescription]];
5825 [sheet popupAlertAnimated:YES];
5826 } else {
5827 UIActionSheet *sheet = [[[UIActionSheet alloc]
5828 initWithTitle:UCLocalize("NOT_REPOSITORY")
5829 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5830 defaultButtonIndex:0
5831 delegate:self
5832 context:@"trivial"
5833 ] autorelease];
5834
5835 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5836 [sheet popupAlertAnimated:YES];
5837 }
5838
5839 [delegate_ setStatusBarShowsProgress:NO];
5840 [delegate_ removeProgressHUD:hud_];
5841
5842 [hud_ autorelease];
5843 hud_ = nil;
5844
5845 if (!defer) {
5846 [href_ release];
5847 href_ = nil;
5848 }
5849
5850 if (error_ != nil) {
5851 [error_ release];
5852 error_ = nil;
5853 }
5854 }
5855 }
5856
5857 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5858 switch ([response statusCode]) {
5859 case 200:
5860 trivial_ = YES;
5861 }
5862 }
5863
5864 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5865 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5866 if (error_ != nil)
5867 error_ = [error retain];
5868 [self _endConnection:connection];
5869 }
5870
5871 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5872 [self _endConnection:connection];
5873 }
5874
5875 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5876 NSMutableURLRequest *request = [NSMutableURLRequest
5877 requestWithURL:[NSURL URLWithString:href]
5878 cachePolicy:NSURLRequestUseProtocolCachePolicy
5879 timeoutInterval:20.0
5880 ];
5881
5882 [request setHTTPMethod:method];
5883
5884 if (Machine_ != NULL)
5885 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5886 if (UniqueID_ != nil)
5887 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5888
5889 if (Role_ != nil)
5890 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5891
5892 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5893 }
5894
5895 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5896 NSString *context([sheet context]);
5897
5898 if ([context isEqualToString:@"source"]) {
5899 switch (button) {
5900 case 1: {
5901 NSString *href = [[sheet textField] text];
5902
5903 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5904
5905 if (![href hasSuffix:@"/"])
5906 href_ = [href stringByAppendingString:@"/"];
5907 else
5908 href_ = href;
5909 href_ = [href_ retain];
5910
5911 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5912 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5913 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5914 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5915
5916 trivial_ = false;
5917
5918 hud_ = [[delegate_ addProgressHUD] retain];
5919 [hud_ setText:UCLocalize("VERIFYING_URL")];
5920 } break;
5921
5922 case 2:
5923 break;
5924
5925 _nodefault
5926 }
5927
5928 [sheet dismiss];
5929 } else if ([context isEqualToString:@"trivial"])
5930 [sheet dismiss];
5931 else if ([context isEqualToString:@"urlerror"])
5932 [sheet dismiss];
5933 else if ([context isEqualToString:@"warning"]) {
5934 switch (button) {
5935 case 1:
5936 [self complete];
5937 break;
5938
5939 case 2:
5940 break;
5941
5942 _nodefault
5943 }
5944
5945 [href_ release];
5946 href_ = nil;
5947
5948 [sheet dismiss];
5949 }
5950 }
5951
5952 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5953 if ((self = [super initWithBook:book]) != nil) {
5954 database_ = database;
5955 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5956
5957 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5958 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5959 [list_ setShouldHideHeaderInShortLists:NO];
5960
5961 [self addSubview:list_];
5962 [list_ setDataSource:self];
5963
5964 UITableColumn *column = [[UITableColumn alloc]
5965 initWithTitle:UCLocalize("NAME")
5966 identifier:@"name"
5967 width:[self frame].size.width
5968 ];
5969
5970 UITable *table = [list_ table];
5971 [table setSeparatorStyle:1];
5972 [table addTableColumn:column];
5973 [table setDelegate:self];
5974
5975 [self reloadData];
5976
5977 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5978 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5979 } return self;
5980 }
5981
5982 - (void) reloadData {
5983 pkgSourceList list;
5984 if (!list.ReadMainList())
5985 return;
5986
5987 [sources_ removeAllObjects];
5988 [sources_ addObjectsFromArray:[database_ sources]];
5989 _trace();
5990 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5991 _trace();
5992
5993 int count([sources_ count]);
5994 for (offset_ = 0; offset_ != count; ++offset_) {
5995 Source *source = [sources_ objectAtIndex:offset_];
5996 if ([source record] == nil)
5997 break;
5998 }
5999
6000 [list_ reloadData];
6001 }
6002
6003 - (void) resetViewAnimated:(BOOL)animated {
6004 [list_ resetViewAnimated:animated];
6005 }
6006
6007 - (void) _leftButtonClicked {
6008 /*[book_ pushPage:[[[AddSourceView alloc]
6009 initWithBook:book_
6010 database:database_
6011 ] autorelease]];*/
6012
6013 UIActionSheet *sheet = [[[UIActionSheet alloc]
6014 initWithTitle:UCLocalize("ENTER_APT_URL")
6015 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6016 defaultButtonIndex:0
6017 delegate:self
6018 context:@"source"
6019 ] autorelease];
6020
6021 [sheet setNumberOfRows:1];
6022
6023 [sheet addTextFieldWithValue:@"http://" label:@""];
6024
6025 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6026 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6027 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6028 [traits setKeyboardType:UIKeyboardTypeURL];
6029 // XXX: UIReturnKeyDone
6030 [traits setReturnKeyType:UIReturnKeyNext];
6031
6032 [sheet popupAlertAnimated:YES];
6033 }
6034
6035 - (void) _rightButtonClicked {
6036 UITable *table = [list_ table];
6037 BOOL editing = [table isRowDeletionEnabled];
6038 [table enableRowDeletion:!editing animated:YES];
6039 [book_ reloadButtonsForPage:self];
6040 }
6041
6042 - (NSString *) title {
6043 return UCLocalize("SOURCES");
6044 }
6045
6046 - (NSString *) leftButtonTitle {
6047 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6048 }
6049
6050 - (id) rightButtonTitle {
6051 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6052 }
6053
6054 - (UINavigationButtonStyle) rightButtonStyle {
6055 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6056 }
6057
6058 @end
6059 /* }}} */
6060
6061 /* Installed View {{{ */
6062 @interface InstalledView : RVPage {
6063 _transient Database *database_;
6064 FilteredPackageTable *packages_;
6065 BOOL expert_;
6066 }
6067
6068 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6069
6070 @end
6071
6072 @implementation InstalledView
6073
6074 - (void) dealloc {
6075 [packages_ release];
6076 [super dealloc];
6077 }
6078
6079 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6080 if ((self = [super initWithBook:book]) != nil) {
6081 database_ = database;
6082
6083 packages_ = [[FilteredPackageTable alloc]
6084 initWithBook:book
6085 database:database
6086 title:nil
6087 filter:@selector(isInstalledAndVisible:)
6088 with:[NSNumber numberWithBool:YES]
6089 ];
6090
6091 [self addSubview:packages_];
6092
6093 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6094 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6095 } return self;
6096 }
6097
6098 - (void) resetViewAnimated:(BOOL)animated {
6099 [packages_ resetViewAnimated:animated];
6100 }
6101
6102 - (void) reloadData {
6103 [packages_ reloadData];
6104 }
6105
6106 - (void) _rightButtonClicked {
6107 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6108 [packages_ reloadData];
6109 expert_ = !expert_;
6110 [book_ reloadButtonsForPage:self];
6111 }
6112
6113 - (NSString *) title {
6114 return UCLocalize("INSTALLED");
6115 }
6116
6117 - (NSString *) backButtonTitle {
6118 return UCLocalize("PACKAGES");
6119 }
6120
6121 - (id) rightButtonTitle {
6122 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6123 }
6124
6125 - (UINavigationButtonStyle) rightButtonStyle {
6126 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6127 }
6128
6129 - (void) setDelegate:(id)delegate {
6130 [super setDelegate:delegate];
6131 [packages_ setDelegate:delegate];
6132 }
6133
6134 @end
6135 /* }}} */
6136
6137 /* Home View {{{ */
6138 @interface HomeView : CydiaBrowserView {
6139 }
6140
6141 @end
6142
6143 @implementation HomeView
6144
6145 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6146 NSString *context([sheet context]);
6147
6148 if ([context isEqualToString:@"about"])
6149 [sheet dismiss];
6150 else
6151 [super alertSheet:sheet buttonClicked:button];
6152 }
6153
6154 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6155 [super _setMoreHeaders:request];
6156 if (ChipID_ != nil)
6157 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6158 }
6159
6160 - (void) _leftButtonClicked {
6161 UIActionSheet *sheet = [[[UIActionSheet alloc]
6162 initWithTitle:UCLocalize("ABOUT_CYDIA")
6163 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6164 defaultButtonIndex:0
6165 delegate:self
6166 context:@"about"
6167 ] autorelease];
6168
6169 [sheet setBodyText:
6170 @"Copyright (C) 2008-2009\n"
6171 "Jay Freeman (saurik)\n"
6172 "saurik@saurik.com\n"
6173 "http://www.saurik.com/\n"
6174 "\n"
6175 "The Okori Group\n"
6176 "http://www.theokorigroup.com/\n"
6177 "\n"
6178 "College of Creative Studies,\n"
6179 "University of California,\n"
6180 "Santa Barbara\n"
6181 "http://www.ccs.ucsb.edu/"
6182 ];
6183
6184 [sheet popupAlertAnimated:YES];
6185 }
6186
6187 - (NSString *) leftButtonTitle {
6188 return UCLocalize("ABOUT");
6189 }
6190
6191 @end
6192 /* }}} */
6193 /* Manage View {{{ */
6194 @interface ManageView : CydiaBrowserView {
6195 }
6196
6197 @end
6198
6199 @implementation ManageView
6200
6201 - (NSString *) title {
6202 return UCLocalize("MANAGE");
6203 }
6204
6205 - (void) _leftButtonClicked {
6206 [delegate_ askForSettings];
6207 [delegate_ updateData];
6208 }
6209
6210 - (NSString *) leftButtonTitle {
6211 return UCLocalize("SETTINGS");
6212 }
6213
6214 #if !AlwaysReload
6215 - (id) _rightButtonTitle {
6216 return Queuing_ ? UCLocalize("QUEUE") : nil;
6217 }
6218
6219 - (UINavigationButtonStyle) rightButtonStyle {
6220 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6221 }
6222
6223 - (void) _rightButtonClicked {
6224 [delegate_ queue];
6225 }
6226 #endif
6227
6228 - (bool) isLoading {
6229 return false;
6230 }
6231
6232 @end
6233 /* }}} */
6234
6235 /* Cydia Book {{{ */
6236 @interface CYBook : RVBook <
6237 ProgressDelegate
6238 > {
6239 _transient Database *database_;
6240 UINavigationBar *overlay_;
6241 UINavigationBar *underlay_;
6242 UIProgressIndicator *indicator_;
6243 UITextLabel *prompt_;
6244 UIProgressBar *progress_;
6245 UINavigationButton *cancel_;
6246 bool updating_;
6247 }
6248
6249 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6250 - (void) update;
6251 - (BOOL) updating;
6252
6253 @end
6254
6255 @implementation CYBook
6256
6257 - (void) dealloc {
6258 [overlay_ release];
6259 [indicator_ release];
6260 [prompt_ release];
6261 [progress_ release];
6262 [cancel_ release];
6263 [super dealloc];
6264 }
6265
6266 - (NSString *) getTitleForPage:(RVPage *)page {
6267 return [super getTitleForPage:page];
6268 }
6269
6270 - (BOOL) updating {
6271 return updating_;
6272 }
6273
6274 - (void) update {
6275 [UIView beginAnimations:nil context:NULL];
6276
6277 CGRect ovrframe = [overlay_ frame];
6278 ovrframe.origin.y = 0;
6279 [overlay_ setFrame:ovrframe];
6280
6281 CGRect barframe = [navbar_ frame];
6282 barframe.origin.y += ovrframe.size.height;
6283 [navbar_ setFrame:barframe];
6284
6285 CGRect trnframe = [transition_ frame];
6286 trnframe.origin.y += ovrframe.size.height;
6287 trnframe.size.height -= ovrframe.size.height;
6288 [transition_ setFrame:trnframe];
6289
6290 [UIView endAnimations];
6291
6292 [indicator_ startAnimation];
6293 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6294 [progress_ setProgress:0];
6295
6296 updating_ = true;
6297 [overlay_ addSubview:cancel_];
6298
6299 [NSThread
6300 detachNewThreadSelector:@selector(_update)
6301 toTarget:self
6302 withObject:nil
6303 ];
6304 }
6305
6306 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6307 NSString *context([sheet context]);
6308
6309 if ([context isEqualToString:@"refresh"])
6310 [sheet dismiss];
6311 }
6312
6313 - (void) _update_ {
6314 updating_ = false;
6315
6316 [indicator_ stopAnimation];
6317
6318 [UIView beginAnimations:nil context:NULL];
6319
6320 CGRect ovrframe = [overlay_ frame];
6321 ovrframe.origin.y = -ovrframe.size.height;
6322 [overlay_ setFrame:ovrframe];
6323
6324 CGRect barframe = [navbar_ frame];
6325 barframe.origin.y -= ovrframe.size.height;
6326 [navbar_ setFrame:barframe];
6327
6328 CGRect trnframe = [transition_ frame];
6329 trnframe.origin.y -= ovrframe.size.height;
6330 trnframe.size.height += ovrframe.size.height;
6331 [transition_ setFrame:trnframe];
6332
6333 [UIView commitAnimations];
6334
6335 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6336 }
6337
6338 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6339 if ((self = [super initWithFrame:frame]) != nil) {
6340 database_ = database;
6341
6342 CGRect ovrrect([navbar_ bounds]);
6343 ovrrect.size.height = [UINavigationBar defaultSize].height;
6344 ovrrect.origin.y = -ovrrect.size.height;
6345
6346 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6347 [self addSubview:overlay_];
6348
6349 ovrrect.origin.y = frame.size.height;
6350 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6351 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6352 [self addSubview:underlay_];
6353
6354 [overlay_ setBarStyle:1];
6355 [underlay_ setBarStyle:1];
6356
6357 int barstyle([overlay_ _barStyle:NO]);
6358 bool ugly(barstyle == 0);
6359
6360 UIProgressIndicatorStyle style = ugly ?
6361 UIProgressIndicatorStyleMediumBrown :
6362 UIProgressIndicatorStyleMediumWhite;
6363
6364 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6365 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6366 CGRect indrect = {{indoffset, indoffset}, indsize};
6367
6368 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6369 [indicator_ setStyle:style];
6370 [overlay_ addSubview:indicator_];
6371
6372 CGSize prmsize = {215, indsize.height + 4};
6373
6374 CGRect prmrect = {{
6375 indoffset * 2 + indsize.width,
6376 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6377 }, prmsize};
6378
6379 UIFont *font([UIFont systemFontOfSize:15]);
6380
6381 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6382
6383 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6384 [prompt_ setBackgroundColor:[UIColor clearColor]];
6385 [prompt_ setFont:font];
6386
6387 [overlay_ addSubview:prompt_];
6388
6389 CGSize prgsize = {75, 100};
6390
6391 CGRect prgrect = {{
6392 ovrrect.size.width - prgsize.width - 10,
6393 (ovrrect.size.height - prgsize.height) / 2
6394 } , prgsize};
6395
6396 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6397 [progress_ setStyle:0];
6398 [overlay_ addSubview:progress_];
6399
6400 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6401 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6402
6403 CGRect frame = [cancel_ frame];
6404 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6405 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6406 [cancel_ setFrame:frame];
6407
6408 [cancel_ setBarStyle:barstyle];
6409 } return self;
6410 }
6411
6412 - (void) _onCancel {
6413 updating_ = false;
6414 [cancel_ removeFromSuperview];
6415 }
6416
6417 - (void) _update { _pooled
6418 Status status;
6419 status.setDelegate(self);
6420 [database_ updateWithStatus:status];
6421
6422 [self
6423 performSelectorOnMainThread:@selector(_update_)
6424 withObject:nil
6425 waitUntilDone:NO
6426 ];
6427 }
6428
6429 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6430 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6431 }
6432
6433 /*
6434 UIActionSheet *sheet = [[[UIActionSheet alloc]
6435 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6436 buttons:[NSArray arrayWithObjects:
6437 UCLocalize("OK"),
6438 nil]
6439 defaultButtonIndex:0
6440 delegate:self
6441 context:@"refresh"
6442 ] autorelease];
6443
6444 [sheet setBodyText:error];
6445 [sheet popupAlertAnimated:YES];
6446
6447 [self reloadButtons];
6448 */
6449
6450 - (void) setProgressTitle:(NSString *)title {
6451 [self
6452 performSelectorOnMainThread:@selector(_setProgressTitle:)
6453 withObject:title
6454 waitUntilDone:YES
6455 ];
6456 }
6457
6458 - (void) setProgressPercent:(float)percent {
6459 [self
6460 performSelectorOnMainThread:@selector(_setProgressPercent:)
6461 withObject:[NSNumber numberWithFloat:percent]
6462 waitUntilDone:YES
6463 ];
6464 }
6465
6466 - (void) startProgress {
6467 }
6468
6469 - (void) addProgressOutput:(NSString *)output {
6470 [self
6471 performSelectorOnMainThread:@selector(_addProgressOutput:)
6472 withObject:output
6473 waitUntilDone:YES
6474 ];
6475 }
6476
6477 - (bool) isCancelling:(size_t)received {
6478 return !updating_;
6479 }
6480
6481 - (void) _setProgressTitle:(NSString *)title {
6482 [prompt_ setText:title];
6483 }
6484
6485 - (void) _setProgressPercent:(NSNumber *)percent {
6486 [progress_ setProgress:[percent floatValue]];
6487 }
6488
6489 - (void) _addProgressOutput:(NSString *)output {
6490 }
6491
6492 @end
6493 /* }}} */
6494 /* Cydia:// Protocol {{{ */
6495 @interface CydiaURLProtocol : NSURLProtocol {
6496 }
6497
6498 @end
6499
6500 @implementation CydiaURLProtocol
6501
6502 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6503 NSURL *url([request URL]);
6504 if (url == nil)
6505 return NO;
6506 NSString *scheme([[url scheme] lowercaseString]);
6507 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6508 return NO;
6509 return YES;
6510 }
6511
6512 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6513 return request;
6514 }
6515
6516 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6517 id<NSURLProtocolClient> client([self client]);
6518 if (icon == nil)
6519 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6520 else {
6521 NSData *data(UIImagePNGRepresentation(icon));
6522
6523 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6524 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6525 [client URLProtocol:self didLoadData:data];
6526 [client URLProtocolDidFinishLoading:self];
6527 }
6528 }
6529
6530 - (void) startLoading {
6531 id<NSURLProtocolClient> client([self client]);
6532 NSURLRequest *request([self request]);
6533
6534 NSURL *url([request URL]);
6535 NSString *href([url absoluteString]);
6536
6537 NSString *path([href substringFromIndex:8]);
6538 NSRange slash([path rangeOfString:@"/"]);
6539
6540 NSString *command;
6541 if (slash.location == NSNotFound) {
6542 command = path;
6543 path = nil;
6544 } else {
6545 command = [path substringToIndex:slash.location];
6546 path = [path substringFromIndex:(slash.location + 1)];
6547 }
6548
6549 Database *database([Database sharedInstance]);
6550
6551 if ([command isEqualToString:@"package-icon"]) {
6552 if (path == nil)
6553 goto fail;
6554 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6555 Package *package([database packageWithName:path]);
6556 if (package == nil)
6557 goto fail;
6558 UIImage *icon([package icon]);
6559 [self _returnPNGWithImage:icon forRequest:request];
6560 } else if ([command isEqualToString:@"source-icon"]) {
6561 if (path == nil)
6562 goto fail;
6563 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6564 NSString *source(Simplify(path));
6565 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6566 if (icon == nil)
6567 icon = [UIImage applicationImageNamed:@"unknown.png"];
6568 [self _returnPNGWithImage:icon forRequest:request];
6569 } else if ([command isEqualToString:@"uikit-image"]) {
6570 if (path == nil)
6571 goto fail;
6572 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6573 UIImage *icon(_UIImageWithName(path));
6574 [self _returnPNGWithImage:icon forRequest:request];
6575 } else if ([command isEqualToString:@"section-icon"]) {
6576 if (path == nil)
6577 goto fail;
6578 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6579 NSString *section(Simplify(path));
6580 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6581 if (icon == nil)
6582 icon = [UIImage applicationImageNamed:@"unknown.png"];
6583 [self _returnPNGWithImage:icon forRequest:request];
6584 } else fail: {
6585 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6586 }
6587 }
6588
6589 - (void) stopLoading {
6590 }
6591
6592 @end
6593 /* }}} */
6594
6595 /* Sections View {{{ */
6596 @interface SectionsView : RVPage {
6597 _transient Database *database_;
6598 NSMutableArray *sections_;
6599 NSMutableArray *filtered_;
6600 UITransitionView *transition_;
6601 UITable *list_;
6602 UIView *accessory_;
6603 BOOL editing_;
6604 }
6605
6606 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6607 - (void) reloadData;
6608 - (void) resetView;
6609
6610 @end
6611
6612 @implementation SectionsView
6613
6614 - (void) dealloc {
6615 [list_ setDataSource:nil];
6616 [list_ setDelegate:nil];
6617
6618 [sections_ release];
6619 [filtered_ release];
6620 [transition_ release];
6621 [list_ release];
6622 [accessory_ release];
6623 [super dealloc];
6624 }
6625
6626 - (int) numberOfRowsInTable:(UITable *)table {
6627 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6628 }
6629
6630 - (float) table:(UITable *)table heightForRow:(int)row {
6631 return 45;
6632 }
6633
6634 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6635 if (reusing == nil)
6636 reusing = [[[SectionCell alloc] init] autorelease];
6637 [(SectionCell *)reusing setSection:(editing_ ?
6638 [sections_ objectAtIndex:row] :
6639 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6640 ) editing:editing_];
6641 return reusing;
6642 }
6643
6644 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6645 return !editing_;
6646 }
6647
6648 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6649 return !editing_;
6650 }
6651
6652 - (void) tableRowSelected:(NSNotification *)notification {
6653 int row = [[notification object] selectedRow];
6654 if (row == INT_MAX)
6655 return;
6656
6657 Section *section;
6658 NSString *name;
6659 NSString *title;
6660
6661 if (row == 0) {
6662 section = nil;
6663 name = nil;
6664 title = UCLocalize("ALL_PACKAGES");
6665 } else {
6666 section = [filtered_ objectAtIndex:(row - 1)];
6667 name = [section name];
6668
6669 if (name != nil) {
6670 name = [NSString stringWithString:name];
6671 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6672 } else {
6673 name = @"";
6674 title = UCLocalize("NO_SECTION");
6675 }
6676 }
6677
6678 PackageTable *table = [[[FilteredPackageTable alloc]
6679 initWithBook:book_
6680 database:database_
6681 title:title
6682 filter:@selector(isVisibleInSection:)
6683 with:name
6684 ] autorelease];
6685
6686 [table setDelegate:delegate_];
6687
6688 [book_ pushPage:table];
6689 }
6690
6691 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6692 if ((self = [super initWithBook:book]) != nil) {
6693 database_ = database;
6694
6695 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6696 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6697
6698 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6699 [self addSubview:transition_];
6700
6701 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6702 [transition_ transition:0 toView:list_];
6703
6704 UITableColumn *column = [[[UITableColumn alloc]
6705 initWithTitle:UCLocalize("NAME")
6706 identifier:@"name"
6707 width:[self frame].size.width
6708 ] autorelease];
6709
6710 [list_ setDataSource:self];
6711 [list_ setSeparatorStyle:1];
6712 [list_ addTableColumn:column];
6713 [list_ setDelegate:self];
6714 [list_ setReusesTableCells:YES];
6715
6716 [self reloadData];
6717
6718 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6719 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6720 } return self;
6721 }
6722
6723 - (void) reloadData {
6724 NSArray *packages = [database_ packages];
6725
6726 [sections_ removeAllObjects];
6727 [filtered_ removeAllObjects];
6728
6729 #if 0
6730 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6731 SectionMap sections;
6732 sections.resize(64);
6733 #else
6734 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6735 #endif
6736
6737 _trace();
6738 for (Package *package in packages) {
6739 NSString *name([package section]);
6740 NSString *key(name == nil ? @"" : name);
6741
6742 #if 0
6743 Section **section;
6744
6745 _profile(SectionsView$reloadData$Section)
6746 section = &sections[key];
6747 if (*section == nil) {
6748 _profile(SectionsView$reloadData$Section$Allocate)
6749 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6750 _end
6751 }
6752 _end
6753
6754 [*section addToCount];
6755
6756 _profile(SectionsView$reloadData$Filter)
6757 if (![package valid] || ![package visible])
6758 continue;
6759 _end
6760
6761 [*section addToRow];
6762 #else
6763 Section *section;
6764
6765 _profile(SectionsView$reloadData$Section)
6766 section = [sections objectForKey:key];
6767 if (section == nil) {
6768 _profile(SectionsView$reloadData$Section$Allocate)
6769 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6770 [sections setObject:section forKey:key];
6771 _end
6772 }
6773 _end
6774
6775 [section addToCount];
6776
6777 _profile(SectionsView$reloadData$Filter)
6778 if (![package valid] || ![package visible])
6779 continue;
6780 _end
6781
6782 [section addToRow];
6783 #endif
6784 }
6785 _trace();
6786
6787 #if 0
6788 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6789 [sections_ addObject:i->second];
6790 #else
6791 [sections_ addObjectsFromArray:[sections allValues]];
6792 #endif
6793
6794 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6795
6796 for (Section *section in sections_) {
6797 size_t count([section row]);
6798 if (count == 0)
6799 continue;
6800
6801 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6802 [section setCount:count];
6803 [filtered_ addObject:section];
6804 }
6805
6806 [list_ reloadData];
6807 _trace();
6808 }
6809
6810 - (void) resetView {
6811 if (editing_)
6812 [self _rightButtonClicked];
6813 }
6814
6815 - (void) resetViewAnimated:(BOOL)animated {
6816 [list_ resetViewAnimated:animated];
6817 }
6818
6819 - (void) _rightButtonClicked {
6820 if ((editing_ = !editing_))
6821 [list_ reloadData];
6822 else
6823 [delegate_ updateData];
6824 [book_ reloadTitleForPage:self];
6825 [book_ reloadButtonsForPage:self];
6826 }
6827
6828 - (NSString *) title {
6829 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6830 }
6831
6832 - (NSString *) backButtonTitle {
6833 return UCLocalize("SECTIONS");
6834 }
6835
6836 - (id) rightButtonTitle {
6837 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6838 }
6839
6840 - (UINavigationButtonStyle) rightButtonStyle {
6841 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6842 }
6843
6844 - (UIView *) accessoryView {
6845 return accessory_;
6846 }
6847
6848 @end
6849 /* }}} */
6850 /* Changes View {{{ */
6851 @interface ChangesView : RVPage {
6852 _transient Database *database_;
6853 NSMutableArray *packages_;
6854 NSMutableArray *sections_;
6855 UITableView *list_;
6856 unsigned upgrades_;
6857 }
6858
6859 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6860 - (void) reloadData;
6861
6862 @end
6863
6864 @implementation ChangesView
6865
6866 - (void) dealloc {
6867 [list_ setDelegate:nil];
6868 [list_ setDataSource:nil];
6869
6870 [packages_ release];
6871 [sections_ release];
6872 [list_ release];
6873 [super dealloc];
6874 }
6875
6876 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6877 NSInteger count([sections_ count]);
6878 return count == 0 ? 1 : count;
6879 }
6880
6881 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6882 if ([sections_ count] == 0)
6883 return nil;
6884 return [[sections_ objectAtIndex:section] name];
6885 }
6886
6887 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6888 if ([sections_ count] == 0)
6889 return 0;
6890 return [[sections_ objectAtIndex:section] count];
6891 }
6892
6893 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6894 Section *section([sections_ objectAtIndex:[path section]]);
6895 NSInteger row([path row]);
6896 return [packages_ objectAtIndex:([section row] + row)];
6897 }
6898
6899 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6900 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6901 if (cell == nil)
6902 cell = [[[PackageCell alloc] init] autorelease];
6903 [cell setPackage:[self packageAtIndexPath:path]];
6904 return cell;
6905 }
6906
6907 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6908 return 73;
6909 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6910 }
6911
6912 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6913 Package *package([self packageAtIndexPath:path]);
6914 PackageView *view([delegate_ packageView]);
6915 [view setDelegate:delegate_];
6916 [view setPackage:package];
6917 [book_ pushPage:view];
6918 return path;
6919 }
6920
6921 - (void) _leftButtonClicked {
6922 [(CYBook *)book_ update];
6923 [self reloadButtons];
6924 }
6925
6926 - (void) _rightButtonClicked {
6927 [delegate_ distUpgrade];
6928 }
6929
6930 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6931 if ((self = [super initWithBook:book]) != nil) {
6932 database_ = database;
6933
6934 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6935 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6936
6937 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6938 [self addSubview:list_];
6939
6940 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6941 [list_ setDataSource:self];
6942 [list_ setDelegate:self];
6943 //[list_ setSectionListStyle:1];
6944
6945 [self reloadData];
6946
6947 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6948 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6949 } return self;
6950 }
6951
6952 - (void) reloadData {
6953 NSArray *packages = [database_ packages];
6954
6955 [packages_ removeAllObjects];
6956 [sections_ removeAllObjects];
6957
6958 _trace();
6959 for (Package *package in packages)
6960 if (
6961 [package uninstalled] && [package valid] && [package visible] ||
6962 [package upgradableAndEssential:YES]
6963 )
6964 [packages_ addObject:package];
6965
6966 _trace();
6967 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6968 _trace();
6969
6970 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6971 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6972 Section *section = nil;
6973 NSDate *last = nil;
6974
6975 upgrades_ = 0;
6976 bool unseens = false;
6977
6978 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6979
6980 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6981 Package *package = [packages_ objectAtIndex:offset];
6982
6983 BOOL uae = [package upgradableAndEssential:YES];
6984
6985 if (!uae) {
6986 unseens = true;
6987 NSDate *seen;
6988
6989 _profile(ChangesView$reloadData$Remember)
6990 seen = [package seen];
6991 _end
6992
6993 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6994 last = seen;
6995
6996 NSString *name;
6997 if (seen == nil)
6998 name = UCLocalize("UNKNOWN");
6999 else {
7000 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7001 [name autorelease];
7002 }
7003
7004 _profile(ChangesView$reloadData$Allocate)
7005 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7006 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7007 [sections_ addObject:section];
7008 _end
7009 }
7010
7011 [section addToCount];
7012 } else if ([package ignored])
7013 [ignored addToCount];
7014 else {
7015 ++upgrades_;
7016 [upgradable addToCount];
7017 }
7018 }
7019 _trace();
7020
7021 CFRelease(formatter);
7022
7023 if (unseens) {
7024 Section *last = [sections_ lastObject];
7025 size_t count = [last count];
7026 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7027 [sections_ removeLastObject];
7028 }
7029
7030 if ([ignored count] != 0)
7031 [sections_ insertObject:ignored atIndex:0];
7032 if (upgrades_ != 0)
7033 [sections_ insertObject:upgradable atIndex:0];
7034
7035 [list_ reloadData];
7036 [self reloadButtons];
7037 }
7038
7039 - (void) resetViewAnimated:(BOOL)animated {
7040 [list_ resetViewAnimated:animated];
7041 }
7042
7043 - (NSString *) leftButtonTitle {
7044 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7045 }
7046
7047 - (id) rightButtonTitle {
7048 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7049 }
7050
7051 - (NSString *) title {
7052 return UCLocalize("CHANGES");
7053 }
7054
7055 @end
7056 /* }}} */
7057 /* Search View {{{ */
7058 @protocol SearchViewDelegate
7059 - (void) showKeyboard:(BOOL)show;
7060 @end
7061
7062 @interface SearchView : RVPage {
7063 UIView *accessory_;
7064 UISearchField *field_;
7065 FilteredPackageTable *table_;
7066 UIView *dimmed_;
7067 bool reload_;
7068 }
7069
7070 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7071 - (void) reloadData;
7072
7073 @end
7074
7075 @implementation SearchView
7076
7077 - (void) dealloc {
7078 [field_ setDelegate:nil];
7079
7080 [accessory_ release];
7081 [field_ release];
7082 [table_ release];
7083 [dimmed_ release];
7084 [super dealloc];
7085 }
7086
7087 - (void) _showKeyboard:(BOOL)show {
7088 CGSize keysize = [UIKeyboard defaultSize];
7089 CGRect keydown = [book_ pageBounds];
7090 CGRect keyup = keydown;
7091 keyup.size.height -= keysize.height - ButtonBarHeight_;
7092
7093 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7094
7095 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7096 [animation setSignificantRectFields:8];
7097
7098 if (show) {
7099 [animation setStartFrame:keydown];
7100 [animation setEndFrame:keyup];
7101 } else {
7102 [animation setStartFrame:keyup];
7103 [animation setEndFrame:keydown];
7104 }
7105
7106 UIAnimator *animator = [UIAnimator sharedAnimator];
7107
7108 [animator
7109 addAnimations:[NSArray arrayWithObjects:animation, nil]
7110 withDuration:(KeyboardTime_ - delay)
7111 start:!show
7112 ];
7113
7114 if (show)
7115 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7116
7117 [delegate_ showKeyboard:show];
7118 }
7119
7120 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7121 [self _showKeyboard:YES];
7122 }
7123
7124 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7125 [self _showKeyboard:NO];
7126 }
7127
7128 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7129 if (reload_) {
7130 NSString *text([field_ text]);
7131 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7132 [self reloadData];
7133 reload_ = false;
7134 }
7135 }
7136
7137 - (void) textFieldClearButtonPressed:(UITextField *)field {
7138 reload_ = true;
7139 }
7140
7141 - (void) keyboardInputShouldDelete:(id)input {
7142 reload_ = true;
7143 }
7144
7145 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7146 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7147 reload_ = true;
7148 return YES;
7149 } else {
7150 [field_ resignFirstResponder];
7151 return NO;
7152 }
7153 }
7154
7155 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7156 if ((self = [super initWithBook:book]) != nil) {
7157 CGRect pageBounds = [book_ pageBounds];
7158
7159 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7160 CGColor dimmed(space_, 0, 0, 0, 0.5);
7161 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7162
7163 table_ = [[FilteredPackageTable alloc]
7164 initWithBook:book
7165 database:database
7166 title:nil
7167 filter:@selector(isUnfilteredAndSearchedForBy:)
7168 with:nil
7169 ];
7170
7171 [table_ setShouldHideHeaderInShortLists:NO];
7172 [self addSubview:table_];
7173
7174 CGRect cnfrect = {{7, 38}, {17, 18}};
7175
7176 CGRect area;
7177
7178 area.origin.x = 10;
7179 area.origin.y = 1;
7180
7181 area.size.width = [self bounds].size.width - area.origin.x * 2;
7182 area.size.height = [UISearchField defaultHeight];
7183
7184 field_ = [[UISearchField alloc] initWithFrame:area];
7185
7186 UIFont *font = [UIFont systemFontOfSize:16];
7187 [field_ setFont:font];
7188
7189 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7190 [field_ setDelegate:self];
7191
7192 [field_ setPaddingTop:5];
7193
7194 UITextInputTraits *traits([field_ textInputTraits]);
7195 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7196 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7197 [traits setReturnKeyType:UIReturnKeySearch];
7198
7199 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7200
7201 accessory_ = [[UIView alloc] initWithFrame:accrect];
7202 [accessory_ addSubview:field_];
7203
7204 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7205 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7206 } return self;
7207 }
7208
7209 - (void) resetViewAnimated:(BOOL)animated {
7210 [table_ resetViewAnimated:animated];
7211 }
7212
7213 - (void) _reloadData {
7214 }
7215
7216 - (void) reloadData {
7217 [table_ setObject:[field_ text]];
7218 _profile(SearchView$reloadData)
7219 [table_ reloadData];
7220 _end
7221 PrintTimes();
7222 [table_ resetCursor];
7223 }
7224
7225 - (UIView *) accessoryView {
7226 return accessory_;
7227 }
7228
7229 - (NSString *) title {
7230 return nil;
7231 }
7232
7233 - (NSString *) backButtonTitle {
7234 return UCLocalize("SEARCH");
7235 }
7236
7237 - (void) setDelegate:(id)delegate {
7238 [table_ setDelegate:delegate];
7239 [super setDelegate:delegate];
7240 }
7241
7242 @end
7243 /* }}} */
7244 /* Settings View {{{ */
7245 @interface SettingsView : RVPage {
7246 _transient Database *database_;
7247 NSString *name_;
7248 Package *package_;
7249 UIPreferencesTable *table_;
7250 _UISwitchSlider *subscribedSwitch_;
7251 _UISwitchSlider *ignoredSwitch_;
7252 UIPreferencesControlTableCell *subscribedCell_;
7253 UIPreferencesControlTableCell *ignoredCell_;
7254 }
7255
7256 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7257
7258 @end
7259
7260 @implementation SettingsView
7261
7262 - (void) dealloc {
7263 [table_ setDataSource:nil];
7264
7265 [name_ release];
7266 if (package_ != nil)
7267 [package_ release];
7268 [table_ release];
7269 [subscribedSwitch_ release];
7270 [ignoredSwitch_ release];
7271 [subscribedCell_ release];
7272 [ignoredCell_ release];
7273 [super dealloc];
7274 }
7275
7276 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7277 if (package_ == nil)
7278 return 0;
7279
7280 return 2;
7281 }
7282
7283 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7284 if (package_ == nil)
7285 return nil;
7286
7287 switch (group) {
7288 case 0: return nil;
7289 case 1: return nil;
7290
7291 _nodefault
7292 }
7293
7294 return nil;
7295 }
7296
7297 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7298 if (package_ == nil)
7299 return NO;
7300
7301 switch (group) {
7302 case 0: return NO;
7303 case 1: return YES;
7304
7305 _nodefault
7306 }
7307
7308 return NO;
7309 }
7310
7311 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7312 if (package_ == nil)
7313 return 0;
7314
7315 switch (group) {
7316 case 0: return 1;
7317 case 1: return 1;
7318
7319 _nodefault
7320 }
7321
7322 return 0;
7323 }
7324
7325 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7326 if (package_ == nil)
7327 return;
7328
7329 _UISwitchSlider *slider([cell control]);
7330 BOOL value([slider value] != 0);
7331 NSMutableDictionary *metadata([package_ metadata]);
7332
7333 BOOL before;
7334 if (NSNumber *number = [metadata objectForKey:key])
7335 before = [number boolValue];
7336 else
7337 before = NO;
7338
7339 if (value != before) {
7340 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7341 Changed_ = true;
7342 [delegate_ updateData];
7343 }
7344 }
7345
7346 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7347 [self onSomething:cell withKey:@"IsSubscribed"];
7348 }
7349
7350 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7351 [self onSomething:cell withKey:@"IsIgnored"];
7352 }
7353
7354 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7355 if (package_ == nil)
7356 return nil;
7357
7358 switch (group) {
7359 case 0: switch (row) {
7360 case 0:
7361 return subscribedCell_;
7362 case 1:
7363 return ignoredCell_;
7364 _nodefault
7365 } break;
7366
7367 case 1: switch (row) {
7368 case 0: {
7369 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7370 [cell setShowSelection:NO];
7371 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7372 return cell;
7373 }
7374
7375 _nodefault
7376 } break;
7377
7378 _nodefault
7379 }
7380
7381 return nil;
7382 }
7383
7384 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7385 if ((self = [super initWithBook:book])) {
7386 database_ = database;
7387 name_ = [package retain];
7388
7389 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7390 [self addSubview:table_];
7391
7392 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7393 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7394
7395 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7396 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7397
7398 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7399 [subscribedCell_ setShowSelection:NO];
7400 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7401 [subscribedCell_ setControl:subscribedSwitch_];
7402
7403 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7404 [ignoredCell_ setShowSelection:NO];
7405 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7406 [ignoredCell_ setControl:ignoredSwitch_];
7407
7408 [table_ setDataSource:self];
7409 [self reloadData];
7410 } return self;
7411 }
7412
7413 - (void) resetViewAnimated:(BOOL)animated {
7414 [table_ resetViewAnimated:animated];
7415 }
7416
7417 - (void) reloadData {
7418 if (package_ != nil)
7419 [package_ autorelease];
7420 package_ = [database_ packageWithName:name_];
7421 if (package_ != nil) {
7422 [package_ retain];
7423 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7424 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7425 }
7426
7427 [table_ reloadData];
7428 }
7429
7430 - (NSString *) title {
7431 return UCLocalize("SETTINGS");
7432 }
7433
7434 @end
7435 /* }}} */
7436
7437 /* Signature View {{{ */
7438 @interface SignatureView : CydiaBrowserView {
7439 _transient Database *database_;
7440 NSString *package_;
7441 }
7442
7443 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7444
7445 @end
7446
7447 @implementation SignatureView
7448
7449 - (void) dealloc {
7450 [package_ release];
7451 [super dealloc];
7452 }
7453
7454 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7455 // XXX: dude!
7456 [super webView:sender didClearWindowObject:window forFrame:frame];
7457 }
7458
7459 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7460 if ((self = [super initWithBook:book]) != nil) {
7461 database_ = database;
7462 package_ = [package retain];
7463 [self reloadData];
7464 } return self;
7465 }
7466
7467 - (void) resetViewAnimated:(BOOL)animated {
7468 }
7469
7470 - (void) reloadData {
7471 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7472 }
7473
7474 @end
7475 /* }}} */
7476
7477 @interface Cydia : UIApplication <
7478 ConfirmationViewDelegate,
7479 ProgressViewDelegate,
7480 SearchViewDelegate,
7481 CydiaDelegate
7482 > {
7483 UIWindow *window_;
7484
7485 UIView *underlay_;
7486 UIView *overlay_;
7487 CYBook *book_;
7488 UIToolbar *toolbar_;
7489
7490 RVBook *confirm_;
7491
7492 NSMutableArray *essential_;
7493 NSMutableArray *broken_;
7494
7495 Database *database_;
7496 ProgressView *progress_;
7497
7498 unsigned tag_;
7499
7500 UIKeyboard *keyboard_;
7501 UIProgressHUD *hud_;
7502
7503 SectionsView *sections_;
7504 ChangesView *changes_;
7505 ManageView *manage_;
7506 SearchView *search_;
7507
7508 #if RecyclePackageViews
7509 NSMutableArray *details_;
7510 #endif
7511 }
7512
7513 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7514 - (void) setPage:(RVPage *)page;
7515
7516 @end
7517
7518 static _finline void _setHomePage(Cydia *self) {
7519 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7520 }
7521
7522 @implementation Cydia
7523
7524 - (void) _loaded {
7525 if ([broken_ count] != 0) {
7526 int count = [broken_ count];
7527
7528 UIActionSheet *sheet = [[[UIActionSheet alloc]
7529 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7530 buttons:[NSArray arrayWithObjects:
7531 UCLocalize("FORCIBLY_CLEAR"),
7532 UCLocalize("TEMPORARY_IGNORE"),
7533 nil]
7534 defaultButtonIndex:0
7535 delegate:self
7536 context:@"fixhalf"
7537 ] autorelease];
7538
7539 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7540 [sheet popupAlertAnimated:YES];
7541 } else if (!Ignored_ && [essential_ count] != 0) {
7542 int count = [essential_ count];
7543
7544 UIActionSheet *sheet = [[[UIActionSheet alloc]
7545 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7546 buttons:[NSArray arrayWithObjects:
7547 UCLocalize("UPGRADE_ESSENTIAL"),
7548 UCLocalize("COMPLETE_UPGRADE"),
7549 UCLocalize("TEMPORARY_IGNORE"),
7550 nil]
7551 defaultButtonIndex:0
7552 delegate:self
7553 context:@"upgrade"
7554 ] autorelease];
7555
7556 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7557 [sheet popupAlertAnimated:YES];
7558 }
7559 }
7560
7561 - (void) _saveConfig {
7562 if (Changed_) {
7563 _trace();
7564 NSString *error(nil);
7565 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7566 _trace();
7567 NSError *error(nil);
7568 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7569 NSLog(@"failure to save metadata data: %@", error);
7570 _trace();
7571 } else {
7572 NSLog(@"failure to serialize metadata: %@", error);
7573 return;
7574 }
7575
7576 Changed_ = false;
7577 }
7578 }
7579
7580 - (void) _updateData {
7581 [self _saveConfig];
7582
7583 /* XXX: this is just stupid */
7584 if (tag_ != 2 && sections_ != nil)
7585 [sections_ reloadData];
7586 if (tag_ != 3 && changes_ != nil)
7587 [changes_ reloadData];
7588 if (tag_ != 5 && search_ != nil)
7589 [search_ reloadData];
7590
7591 [book_ reloadData];
7592 }
7593
7594 - (void) _reloadData {
7595 UIView *block();
7596
7597 static bool loaded(false);
7598 UIProgressHUD *hud([self addProgressHUD]);
7599 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7600
7601 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7602 _trace();
7603
7604 [self removeProgressHUD:hud];
7605
7606 size_t changes(0);
7607
7608 [essential_ removeAllObjects];
7609 [broken_ removeAllObjects];
7610
7611 NSArray *packages([database_ packages]);
7612 for (Package *package in packages) {
7613 if ([package half])
7614 [broken_ addObject:package];
7615 if ([package upgradableAndEssential:NO]) {
7616 if ([package essential])
7617 [essential_ addObject:package];
7618 ++changes;
7619 }
7620 }
7621
7622 if (changes != 0) {
7623 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7624 [toolbar_ setBadgeValue:badge forButton:3];
7625 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7626 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7627 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7628 [self setApplicationBadge:badge];
7629 else
7630 [self setApplicationBadgeString:badge];
7631 } else {
7632 [toolbar_ setBadgeValue:nil forButton:3];
7633 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7634 [toolbar_ setBadgeAnimated:NO forButton:3];
7635 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7636 [self removeApplicationBadge];
7637 else // XXX: maybe use setApplicationBadgeString also?
7638 [self setApplicationIconBadgeNumber:0];
7639 }
7640
7641 Queuing_ = false;
7642 [toolbar_ setBadgeValue:nil forButton:4];
7643
7644 [self _updateData];
7645
7646 if (loaded || ManualRefresh) loaded:
7647 [self _loaded];
7648 else {
7649 loaded = true;
7650
7651 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7652 NSTimeInterval interval([update timeIntervalSinceNow]);
7653 if (interval <= 0 && interval > -(15*60))
7654 goto loaded;
7655 }
7656
7657 [book_ update];
7658 }
7659 }
7660
7661 - (void) updateData {
7662 [database_ setVisible];
7663 [self _updateData];
7664 }
7665
7666 - (void) update_ {
7667 [database_ update];
7668 }
7669
7670 - (void) syncData {
7671 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7672 _assert(file != NULL);
7673
7674 for (NSString *key in [Sources_ allKeys]) {
7675 NSDictionary *source([Sources_ objectForKey:key]);
7676
7677 fprintf(file, "%s %s %s\n",
7678 [[source objectForKey:@"Type"] UTF8String],
7679 [[source objectForKey:@"URI"] UTF8String],
7680 [[source objectForKey:@"Distribution"] UTF8String]
7681 );
7682 }
7683
7684 fclose(file);
7685
7686 [self _saveConfig];
7687
7688 [progress_
7689 detachNewThreadSelector:@selector(update_)
7690 toTarget:self
7691 withObject:nil
7692 title:UCLocalize("UPDATING_SOURCES")
7693 ];
7694 }
7695
7696 - (void) reloadData {
7697 @synchronized (self) {
7698 if (confirm_ == nil)
7699 [self _reloadData];
7700 }
7701 }
7702
7703 - (void) resolve {
7704 pkgProblemResolver *resolver = [database_ resolver];
7705
7706 resolver->InstallProtect();
7707 if (!resolver->Resolve(true))
7708 _error->Discard();
7709 }
7710
7711 - (void) popUpBook:(RVBook *)book {
7712 [underlay_ popSubview:book];
7713 }
7714
7715 - (CGRect) popUpBounds {
7716 return [underlay_ bounds];
7717 }
7718
7719 - (bool) perform {
7720 if (![database_ prepare])
7721 return false;
7722
7723 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7724 [confirm_ setDelegate:self];
7725
7726 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7727 [page setDelegate:self];
7728
7729 [confirm_ setPage:page];
7730 [self popUpBook:confirm_];
7731
7732 return true;
7733 }
7734
7735 - (void) queue {
7736 @synchronized (self) {
7737 [self perform];
7738 }
7739 }
7740
7741 - (void) clearPackage:(Package *)package {
7742 @synchronized (self) {
7743 [package clear];
7744 [self resolve];
7745 [self perform];
7746 }
7747 }
7748
7749 - (void) installPackage:(Package *)package {
7750 @synchronized (self) {
7751 [package install];
7752 [self resolve];
7753 [self perform];
7754 }
7755 }
7756
7757 - (void) removePackage:(Package *)package {
7758 @synchronized (self) {
7759 [package remove];
7760 [self resolve];
7761 [self perform];
7762 }
7763 }
7764
7765 - (void) distUpgrade {
7766 @synchronized (self) {
7767 if (![database_ upgrade])
7768 return;
7769 [self perform];
7770 }
7771 }
7772
7773 - (void) cancel {
7774 [self slideUp:[[[UIActionSheet alloc]
7775 initWithTitle:nil
7776 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7777 defaultButtonIndex:1
7778 delegate:self
7779 context:@"cancel"
7780 ] autorelease]];
7781 }
7782
7783 - (void) complete {
7784 @synchronized (self) {
7785 [self _reloadData];
7786
7787 if (confirm_ != nil) {
7788 [confirm_ release];
7789 confirm_ = nil;
7790 }
7791 }
7792 }
7793
7794 - (void) confirm {
7795 [overlay_ removeFromSuperview];
7796 reload_ = true;
7797
7798 [progress_
7799 detachNewThreadSelector:@selector(perform)
7800 toTarget:database_
7801 withObject:nil
7802 title:UCLocalize("RUNNING")
7803 ];
7804 }
7805
7806 - (void) progressViewIsComplete:(ProgressView *)progress {
7807 if (confirm_ != nil) {
7808 [underlay_ addSubview:overlay_];
7809 [confirm_ popFromSuperviewAnimated:NO];
7810 }
7811
7812 [self complete];
7813 }
7814
7815 - (void) setPage:(RVPage *)page {
7816 [page resetViewAnimated:NO];
7817 [page setDelegate:self];
7818 [book_ setPage:page];
7819 }
7820
7821 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7822 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7823 [browser loadURL:url];
7824 return browser;
7825 }
7826
7827 - (SectionsView *) sectionsView {
7828 if (sections_ == nil)
7829 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7830 return sections_;
7831 }
7832
7833 - (void) buttonBarItemTapped:(id)sender {
7834 unsigned tag = [sender tag];
7835 if (tag == tag_) {
7836 [book_ resetViewAnimated:YES];
7837 return;
7838 } else if (tag_ == 2)
7839 [[self sectionsView] resetView];
7840
7841 switch (tag) {
7842 case 1: _setHomePage(self); break;
7843
7844 case 2: [self setPage:[self sectionsView]]; break;
7845 case 3: [self setPage:changes_]; break;
7846 case 4: [self setPage:manage_]; break;
7847 case 5: [self setPage:search_]; break;
7848
7849 _nodefault
7850 }
7851
7852 tag_ = tag;
7853 }
7854
7855 - (void) askForSettings {
7856 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7857
7858 CYActionSheet *role([[[CYActionSheet alloc]
7859 initWithTitle:UCLocalize("WHO_ARE_YOU")
7860 buttons:[NSArray arrayWithObjects:
7861 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7862 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7863 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7864 nil]
7865 defaultButtonIndex:-1
7866 ] autorelease]);
7867
7868 [role setBodyText:UCLocalize("ROLE_EX")];
7869
7870 int button([role yieldToPopupAlertAnimated:YES]);
7871
7872 switch (button) {
7873 case 1: Role_ = @"User"; break;
7874 case 2: Role_ = @"Hacker"; break;
7875 case 3: Role_ = @"Developer"; break;
7876
7877 _nodefault
7878 }
7879
7880 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7881 Role_, @"Role",
7882 nil];
7883
7884 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7885
7886 Changed_ = true;
7887
7888 [role dismiss];
7889 }
7890
7891 - (void) setPackageView:(PackageView *)view {
7892 WebThreadLock();
7893 [view setPackage:nil];
7894 #if RecyclePackageViews
7895 if ([details_ count] < 3)
7896 [details_ addObject:view];
7897 #endif
7898 WebThreadUnlock();
7899 }
7900
7901 - (PackageView *) _packageView {
7902 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7903 }
7904
7905 - (PackageView *) packageView {
7906 #if RecyclePackageViews
7907 PackageView *view;
7908 size_t count([details_ count]);
7909
7910 if (count == 0) {
7911 view = [self _packageView];
7912 renew:
7913 [details_ addObject:[self _packageView]];
7914 } else {
7915 view = [[[details_ lastObject] retain] autorelease];
7916 [details_ removeLastObject];
7917 if (count == 1)
7918 goto renew;
7919 }
7920
7921 return view;
7922 #else
7923 return [self _packageView];
7924 #endif
7925 }
7926
7927 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7928 NSString *context([sheet context]);
7929
7930 if ([context isEqualToString:@"missing"])
7931 [sheet dismiss];
7932 else if ([context isEqualToString:@"cancel"]) {
7933 bool clear;
7934
7935 switch (button) {
7936 case 1:
7937 clear = false;
7938 break;
7939
7940 case 2:
7941 clear = true;
7942 break;
7943
7944 _nodefault
7945 }
7946
7947 [sheet dismiss];
7948
7949 @synchronized (self) {
7950 if (clear)
7951 [self _reloadData];
7952 else {
7953 Queuing_ = true;
7954 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7955 [book_ reloadData];
7956 }
7957
7958 if (confirm_ != nil) {
7959 [confirm_ release];
7960 confirm_ = nil;
7961 }
7962 }
7963 } else if ([context isEqualToString:@"fixhalf"]) {
7964 switch (button) {
7965 case 1:
7966 @synchronized (self) {
7967 for (Package *broken in broken_) {
7968 [broken remove];
7969
7970 NSString *id = [broken id];
7971 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7972 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7973 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7974 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7975 }
7976
7977 [self resolve];
7978 [self perform];
7979 }
7980 break;
7981
7982 case 2:
7983 [broken_ removeAllObjects];
7984 [self _loaded];
7985 break;
7986
7987 _nodefault
7988 }
7989
7990 [sheet dismiss];
7991 } else if ([context isEqualToString:@"upgrade"]) {
7992 switch (button) {
7993 case 1:
7994 @synchronized (self) {
7995 for (Package *essential in essential_)
7996 [essential install];
7997
7998 [self resolve];
7999 [self perform];
8000 }
8001 break;
8002
8003 case 2:
8004 [self distUpgrade];
8005 break;
8006
8007 case 3:
8008 Ignored_ = YES;
8009 break;
8010
8011 _nodefault
8012 }
8013
8014 [sheet dismiss];
8015 }
8016 }
8017
8018 - (void) system:(NSString *)command { _pooled
8019 system([command UTF8String]);
8020 }
8021
8022 - (void) applicationWillSuspend {
8023 [database_ clean];
8024 [super applicationWillSuspend];
8025 }
8026
8027 - (void) applicationSuspend:(__GSEvent *)event {
8028 if (hud_ == nil && ![progress_ isRunning])
8029 [super applicationSuspend:event];
8030 }
8031
8032 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8033 if (hud_ == nil)
8034 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8035 }
8036
8037 - (void) _setSuspended:(BOOL)value {
8038 if (hud_ == nil)
8039 [super _setSuspended:value];
8040 }
8041
8042 - (UIProgressHUD *) addProgressHUD {
8043 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8044 [window_ setUserInteractionEnabled:NO];
8045 [hud show:YES];
8046 [progress_ addSubview:hud];
8047 return hud;
8048 }
8049
8050 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8051 [hud show:NO];
8052 [hud removeFromSuperview];
8053 [window_ setUserInteractionEnabled:YES];
8054 }
8055
8056 - (RVPage *) pageForPackage:(NSString *)name {
8057 if (Package *package = [database_ packageWithName:name]) {
8058 PackageView *view([self packageView]);
8059 [view setPackage:package];
8060 return view;
8061 } else {
8062 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8063 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8064 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8065 }
8066 }
8067
8068 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8069 if (tag != NULL)
8070 tag = 0;
8071
8072 NSString *href([url absoluteString]);
8073 if ([href hasPrefix:@"apptapp://package/"])
8074 return [self pageForPackage:[href substringFromIndex:18]];
8075
8076 NSString *scheme([[url scheme] lowercaseString]);
8077 if (![scheme isEqualToString:@"cydia"])
8078 return nil;
8079 NSString *path([url absoluteString]);
8080 if ([path length] < 8)
8081 return nil;
8082 path = [path substringFromIndex:8];
8083 if (![path hasPrefix:@"/"])
8084 path = [@"/" stringByAppendingString:path];
8085
8086 if ([path isEqualToString:@"/add-source"])
8087 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8088 else if ([path isEqualToString:@"/storage"])
8089 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8090 else if ([path isEqualToString:@"/sources"])
8091 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8092 else if ([path isEqualToString:@"/packages"])
8093 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8094 else if ([path hasPrefix:@"/url/"])
8095 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8096 else if ([path hasPrefix:@"/launch/"])
8097 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8098 else if ([path hasPrefix:@"/package-settings/"])
8099 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8100 else if ([path hasPrefix:@"/package-signature/"])
8101 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8102 else if ([path hasPrefix:@"/package/"])
8103 return [self pageForPackage:[path substringFromIndex:9]];
8104 else if ([path hasPrefix:@"/files/"]) {
8105 NSString *name = [path substringFromIndex:7];
8106
8107 if (Package *package = [database_ packageWithName:name]) {
8108 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8109 [files setPackage:package];
8110 return files;
8111 }
8112 }
8113
8114 return nil;
8115 }
8116
8117 - (void) applicationOpenURL:(NSURL *)url {
8118 [super applicationOpenURL:url];
8119 int tag;
8120 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8121 [self setPage:page];
8122 [toolbar_ showSelectionForButton:tag];
8123 tag_ = tag;
8124 }
8125 }
8126
8127 - (void) applicationDidFinishLaunching:(id)unused {
8128 [BrowserView _initialize];
8129
8130 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8131
8132 Font12_ = [[UIFont systemFontOfSize:12] retain];
8133 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8134 Font14_ = [[UIFont systemFontOfSize:14] retain];
8135 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8136 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8137
8138 tag_ = 1;
8139
8140 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8141 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8142
8143 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8144 [window_ orderFront:self];
8145 [window_ makeKey:self];
8146 [window_ setHidden:NO];
8147
8148 database_ = [Database sharedInstance];
8149
8150 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8151 [database_ setDelegate:progress_];
8152 [window_ setContentView:progress_];
8153
8154 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8155 [progress_ setContentView:underlay_];
8156
8157 [progress_ resetView];
8158
8159 if (
8160 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8161 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8162 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8163 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8164 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8165 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8166 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8167 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8168 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8169 false
8170 ) {
8171 [self setIdleTimerDisabled:YES];
8172
8173 hud_ = [self addProgressHUD];
8174 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8175 [self setStatusBarShowsProgress:YES];
8176
8177 [self yieldToSelector:@selector(system) withObject:@"http://www.hipsterwave.com/tag/cydia/"];
8178
8179 [self setStatusBarShowsProgress:NO];
8180 [self removeProgressHUD:hud_];
8181 hud_ = nil;
8182
8183 if (ExecFork() == 0) {
8184 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8185 perror("launchctl stop");
8186 }
8187
8188 return;
8189 }
8190
8191 if (Role_ == nil)
8192 [self askForSettings];
8193
8194 _trace();
8195 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8196
8197 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8198 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8199 0, 0, screenrect.size.width, screenrect.size.height - 48
8200 ) database:database_];
8201
8202 [book_ setDelegate:self];
8203
8204 [overlay_ addSubview:book_];
8205
8206 NSArray *buttonitems = [NSArray arrayWithObjects:
8207 [NSDictionary dictionaryWithObjectsAndKeys:
8208 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8209 @"home-up.png", kUIButtonBarButtonInfo,
8210 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8211 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8212 self, kUIButtonBarButtonTarget,
8213 @"Cydia", kUIButtonBarButtonTitle,
8214 @"0", kUIButtonBarButtonType,
8215 nil],
8216
8217 [NSDictionary dictionaryWithObjectsAndKeys:
8218 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8219 @"install-up.png", kUIButtonBarButtonInfo,
8220 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8221 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8222 self, kUIButtonBarButtonTarget,
8223 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8224 @"0", kUIButtonBarButtonType,
8225 nil],
8226
8227 [NSDictionary dictionaryWithObjectsAndKeys:
8228 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8229 @"changes-up.png", kUIButtonBarButtonInfo,
8230 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8231 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8232 self, kUIButtonBarButtonTarget,
8233 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8234 @"0", kUIButtonBarButtonType,
8235 nil],
8236
8237 [NSDictionary dictionaryWithObjectsAndKeys:
8238 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8239 @"manage-up.png", kUIButtonBarButtonInfo,
8240 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8241 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8242 self, kUIButtonBarButtonTarget,
8243 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8244 @"0", kUIButtonBarButtonType,
8245 nil],
8246
8247 [NSDictionary dictionaryWithObjectsAndKeys:
8248 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8249 @"search-up.png", kUIButtonBarButtonInfo,
8250 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8251 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8252 self, kUIButtonBarButtonTarget,
8253 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8254 @"0", kUIButtonBarButtonType,
8255 nil],
8256 nil];
8257
8258 toolbar_ = [[UIToolbar alloc]
8259 initInView:overlay_
8260 withFrame:CGRectMake(
8261 0, screenrect.size.height - ButtonBarHeight_,
8262 screenrect.size.width, ButtonBarHeight_
8263 )
8264 withItemList:buttonitems
8265 ];
8266
8267 [toolbar_ setDelegate:self];
8268 [toolbar_ setBarStyle:1];
8269 [toolbar_ setButtonBarTrackingMode:2];
8270
8271 int buttons[5] = {1, 2, 3, 4, 5};
8272 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8273 [toolbar_ showButtonGroup:0 withDuration:0];
8274
8275 for (int i = 0; i != 5; ++i)
8276 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8277 i * 64 + 2, 1, 60, ButtonBarHeight_
8278 )];
8279
8280 [toolbar_ showSelectionForButton:1];
8281 [overlay_ addSubview:toolbar_];
8282
8283 [UIKeyboard initImplementationNow];
8284 CGSize keysize = [UIKeyboard defaultSize];
8285 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8286 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8287 [overlay_ addSubview:keyboard_];
8288
8289 [underlay_ addSubview:overlay_];
8290
8291 [self reloadData];
8292
8293 [self sectionsView];
8294 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8295 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8296
8297 manage_ = (ManageView *) [[self
8298 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8299 withClass:[ManageView class]
8300 ] retain];
8301
8302 #if RecyclePackageViews
8303 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8304 [details_ addObject:[self _packageView]];
8305 [details_ addObject:[self _packageView]];
8306 #endif
8307
8308 PrintTimes();
8309
8310 _setHomePage(self);
8311 }
8312
8313 - (void) showKeyboard:(BOOL)show {
8314 CGSize keysize([UIKeyboard defaultSize]);
8315 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8316 CGRect keyup(keydown);
8317 keyup.origin.y -= keysize.height;
8318
8319 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8320 [animation setSignificantRectFields:2];
8321
8322 if (show) {
8323 [animation setStartFrame:keydown];
8324 [animation setEndFrame:keyup];
8325 [keyboard_ activate];
8326 } else {
8327 [animation setStartFrame:keyup];
8328 [animation setEndFrame:keydown];
8329 [keyboard_ deactivate];
8330 }
8331
8332 [[UIAnimator sharedAnimator]
8333 addAnimations:[NSArray arrayWithObjects:animation, nil]
8334 withDuration:KeyboardTime_
8335 start:YES
8336 ];
8337 }
8338
8339 - (void) slideUp:(UIActionSheet *)alert {
8340 [alert presentSheetInView:overlay_];
8341 }
8342
8343 @end
8344
8345 /*IMP alloc_;
8346 id Alloc_(id self, SEL selector) {
8347 id object = alloc_(self, selector);
8348 lprintf("[%s]A-%p\n", self->isa->name, object);
8349 return object;
8350 }*/
8351
8352 /*IMP dealloc_;
8353 id Dealloc_(id self, SEL selector) {
8354 id object = dealloc_(self, selector);
8355 lprintf("[%s]D-%p\n", self->isa->name, object);
8356 return object;
8357 }*/
8358
8359 Class $WebDefaultUIKitDelegate;
8360
8361 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8362 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8363 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8364 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8365 }
8366
8367 int main(int argc, char *argv[]) { _pooled
8368 _trace();
8369
8370 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8371
8372 /* Library Hacks {{{ */
8373 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8374
8375 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8376 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8377 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8378 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8379 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8380 }
8381 /* }}} */
8382 /* Set Locale {{{ */
8383 Locale_ = CFLocaleCopyCurrent();
8384 Languages_ = [NSLocale preferredLanguages];
8385 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8386 //NSLog(@"%@", [Languages_ description]);
8387 const char *lang;
8388 if (Languages_ == nil || [Languages_ count] == 0)
8389 lang = NULL;
8390 else
8391 lang = [[Languages_ objectAtIndex:0] UTF8String];
8392 setenv("LANG", lang, true);
8393 //std::setlocale(LC_ALL, lang);
8394 NSLog(@"Setting Language: %s", lang);
8395 /* }}} */
8396
8397 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8398
8399 /* Parse Arguments {{{ */
8400 bool substrate(false);
8401
8402 if (argc != 0) {
8403 char **args(argv);
8404 int arge(1);
8405
8406 for (int argi(1); argi != argc; ++argi)
8407 if (strcmp(argv[argi], "--") == 0) {
8408 arge = argi;
8409 argv[argi] = argv[0];
8410 argv += argi;
8411 argc -= argi;
8412 break;
8413 }
8414
8415 for (int argi(1); argi != arge; ++argi)
8416 if (strcmp(args[argi], "--substrate") == 0)
8417 substrate = true;
8418 else
8419 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8420 }
8421 /* }}} */
8422
8423 App_ = [[NSBundle mainBundle] bundlePath];
8424 Home_ = NSHomeDirectory();
8425 Advanced_ = YES;
8426
8427 setuid(0);
8428 setgid(0);
8429
8430 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8431 alloc_ = alloc->method_imp;
8432 alloc->method_imp = (IMP) &Alloc_;*/
8433
8434 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8435 dealloc_ = dealloc->method_imp;
8436 dealloc->method_imp = (IMP) &Dealloc_;*/
8437
8438 /* System Information {{{ */
8439 size_t size;
8440
8441 int maxproc;
8442 size = sizeof(maxproc);
8443 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8444 perror("sysctlbyname(\"kern.maxproc\", ?)");
8445 else if (maxproc < 64) {
8446 maxproc = 64;
8447 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8448 perror("sysctlbyname(\"kern.maxproc\", #)");
8449 }
8450
8451 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8452 char *osversion = new char[size];
8453 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8454 perror("sysctlbyname(\"kern.osversion\", ?)");
8455 else
8456 System_ = [NSString stringWithUTF8String:osversion];
8457
8458 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8459 char *machine = new char[size];
8460 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8461 perror("sysctlbyname(\"hw.machine\", ?)");
8462 else
8463 Machine_ = machine;
8464
8465 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8466 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8467 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8468 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8469 CFRelease(serial);
8470 }
8471
8472 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8473 NSData *data((NSData *) ecid);
8474 size_t length([data length]);
8475 uint8_t bytes[length];
8476 [data getBytes:bytes];
8477 char string[length * 2 + 1];
8478 for (size_t i(0); i != length; ++i)
8479 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8480 ChipID_ = [NSString stringWithUTF8String:string];
8481 CFRelease(ecid);
8482 }
8483
8484 IOObjectRelease(service);
8485 }
8486 }
8487
8488 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8489
8490 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8491 Build_ = [system objectForKey:@"ProductBuildVersion"];
8492 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8493 Product_ = [info objectForKey:@"SafariProductVersion"];
8494 Safari_ = [info objectForKey:@"CFBundleVersion"];
8495 }
8496 /* }}} */
8497 /* Load Database {{{ */
8498 _trace();
8499 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8500 _trace();
8501 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8502 _trace();
8503
8504 if (Metadata_ == NULL)
8505 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8506 else {
8507 Settings_ = [Metadata_ objectForKey:@"Settings"];
8508
8509 Packages_ = [Metadata_ objectForKey:@"Packages"];
8510 Sections_ = [Metadata_ objectForKey:@"Sections"];
8511 Sources_ = [Metadata_ objectForKey:@"Sources"];
8512 }
8513
8514 if (Settings_ != nil)
8515 Role_ = [Settings_ objectForKey:@"Role"];
8516
8517 if (Packages_ == nil) {
8518 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8519 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8520 }
8521
8522 if (Sections_ == nil) {
8523 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8524 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8525 }
8526
8527 if (Sources_ == nil) {
8528 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8529 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8530 }
8531 /* }}} */
8532
8533 #if RecycleWebViews
8534 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8535 #endif
8536
8537 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8538
8539 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8540 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8541 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8542 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8543
8544 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8545 unlink("/tmp/.cydia.fw");
8546 goto firmware;
8547 } else if (access("/User", F_OK) != 0) {
8548 firmware:
8549 _trace();
8550 system("/usr/libexec/cydia/firmware.sh");
8551 _trace();
8552 }
8553
8554 _assert([[NSFileManager defaultManager]
8555 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8556 withIntermediateDirectories:YES
8557 attributes:nil
8558 error:NULL
8559 ]);
8560
8561 if (access("/tmp/cydia.chk", F_OK) == 0) {
8562 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8563 _assert(errno == ENOENT);
8564 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8565 _assert(errno == ENOENT);
8566 }
8567
8568 /* APT Initialization {{{ */
8569 _assert(pkgInitConfig(*_config));
8570 _assert(pkgInitSystem(*_config, _system));
8571
8572 if (lang != NULL)
8573 _config->Set("APT::Acquire::Translation", lang);
8574 _config->Set("Acquire::http::Timeout", 15);
8575 _config->Set("Acquire::http::MaxParallel", 3);
8576 /* }}} */
8577 /* Color Choices {{{ */
8578 space_ = CGColorSpaceCreateDeviceRGB();
8579
8580 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8581 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8582 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8583 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8584 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8585 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8586 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8587 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8588 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8589
8590 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8591 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8592 /* }}}*/
8593 /* UIKit Configuration {{{ */
8594 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8595 if ($GSFontSetUseLegacyFontMetrics != NULL)
8596 $GSFontSetUseLegacyFontMetrics(YES);
8597
8598 UIKeyboardDisableAutomaticAppearance();
8599 /* }}} */
8600
8601 Colon_ = UCLocalize("COLON_DELIMITED");
8602 Error_ = UCLocalize("ERROR");
8603 Warning_ = UCLocalize("WARNING");
8604
8605 _trace();
8606 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8607
8608 CGColorSpaceRelease(space_);
8609 CFRelease(Locale_);
8610
8611 return value;
8612 }