]> git.saurik.com Git - cydia.git/blob - Cydia.mm
Fixed a stupid bug with trivial repo addition.
[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_;
5630 NSURLConnection *trivial_bz2_;
5631 NSURLConnection *trivial_gz_;
5632 //NSURLConnection *automatic_;
5633
5634 BOOL cydia_;
5635 }
5636
5637 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5638
5639 @end
5640
5641 @implementation SourceTable
5642
5643 - (void) _deallocConnection:(NSURLConnection *)connection {
5644 if (connection != nil) {
5645 [connection cancel];
5646 //[connection setDelegate:nil];
5647 [connection release];
5648 }
5649 }
5650
5651 - (void) dealloc {
5652 [[list_ table] setDelegate:nil];
5653 [list_ setDataSource:nil];
5654
5655 if (href_ != nil)
5656 [href_ release];
5657 if (hud_ != nil)
5658 [hud_ release];
5659 if (error_ != nil)
5660 [error_ release];
5661
5662 //[self _deallocConnection:installer_];
5663 [self _deallocConnection:trivial_];
5664 [self _deallocConnection:trivial_gz_];
5665 [self _deallocConnection:trivial_bz2_];
5666 //[self _deallocConnection:automatic_];
5667
5668 [sources_ release];
5669 [list_ release];
5670 [super dealloc];
5671 }
5672
5673 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5674 return offset_ == 0 ? 1 : 2;
5675 }
5676
5677 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5678 switch (section + (offset_ == 0 ? 1 : 0)) {
5679 case 0: return UCLocalize("ENTERED_BY_USER");
5680 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5681
5682 _nodefault
5683 }
5684 }
5685
5686 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5687 switch (section + (offset_ == 0 ? 1 : 0)) {
5688 case 0: return 0;
5689 case 1: return offset_;
5690
5691 _nodefault
5692 }
5693 }
5694
5695 - (int) numberOfRowsInTable:(UITable *)table {
5696 return [sources_ count];
5697 }
5698
5699 - (float) table:(UITable *)table heightForRow:(int)row {
5700 Source *source = [sources_ objectAtIndex:row];
5701 return [source description] == nil ? 56 : 73;
5702 }
5703
5704 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5705 Source *source = [sources_ objectAtIndex:row];
5706 // XXX: weird warning, stupid selectors ;P
5707 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5708 }
5709
5710 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5711 return YES;
5712 }
5713
5714 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5715 return YES;
5716 }
5717
5718 - (void) tableRowSelected:(NSNotification*)notification {
5719 UITable *table([list_ table]);
5720 int row([table selectedRow]);
5721 if (row == INT_MAX)
5722 return;
5723
5724 Source *source = [sources_ objectAtIndex:row];
5725
5726 PackageTable *packages = [[[FilteredPackageTable alloc]
5727 initWithBook:book_
5728 database:database_
5729 title:[source label]
5730 filter:@selector(isVisibleInSource:)
5731 with:source
5732 ] autorelease];
5733
5734 [packages setDelegate:delegate_];
5735
5736 [book_ pushPage:packages];
5737 }
5738
5739 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5740 Source *source = [sources_ objectAtIndex:row];
5741 return [source record] != nil;
5742 }
5743
5744 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5745 [[list_ table] setDeleteConfirmationRow:row];
5746 }
5747
5748 - (void) table:(UITable *)table deleteRow:(int)row {
5749 Source *source = [sources_ objectAtIndex:row];
5750 [Sources_ removeObjectForKey:[source key]];
5751 [delegate_ syncData];
5752 }
5753
5754 - (void) complete {
5755 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5756 @"deb", @"Type",
5757 href_, @"URI",
5758 @"./", @"Distribution",
5759 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5760
5761 [delegate_ syncData];
5762 }
5763
5764 - (NSString *) getWarning {
5765 NSString *href(href_);
5766 NSRange colon([href rangeOfString:@"://"]);
5767 if (colon.location != NSNotFound)
5768 href = [href substringFromIndex:(colon.location + 3)];
5769 href = [href stringByAddingPercentEscapes];
5770 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5771 href = [href stringByCachingURLWithCurrentCDN];
5772
5773 NSURL *url([NSURL URLWithString:href]);
5774
5775 NSStringEncoding encoding;
5776 NSError *error(nil);
5777
5778 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5779 return [warning length] == 0 ? nil : warning;
5780 return nil;
5781 }
5782
5783 - (void) _endConnection:(NSURLConnection *)connection {
5784 NSURLConnection **field = NULL;
5785 if (connection == trivial_)
5786 field = &trivial_;
5787 else if (connection == trivial_bz2_)
5788 field = &trivial_bz2_;
5789 else if (connection == trivial_gz_)
5790 field = &trivial_gz_;
5791 _assert(field != NULL);
5792 [connection release];
5793 *field = nil;
5794
5795 if (
5796 trivial_ == nil &&
5797 trivial_bz2_ == nil &&
5798 trivial_gz_ == nil
5799 ) {
5800 bool defer(false);
5801
5802 if (cydia_) {
5803 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5804 defer = true;
5805
5806 UIActionSheet *sheet = [[[UIActionSheet alloc]
5807 initWithTitle:UCLocalize("SOURCE_WARNING")
5808 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5809 defaultButtonIndex:0
5810 delegate:self
5811 context:@"warning"
5812 ] autorelease];
5813
5814 [sheet setNumberOfRows:1];
5815
5816 [sheet setBodyText:warning];
5817 [sheet popupAlertAnimated:YES];
5818 } else
5819 [self complete];
5820 } else if (error_ != nil) {
5821 UIActionSheet *sheet = [[[UIActionSheet alloc]
5822 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5823 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5824 defaultButtonIndex:0
5825 delegate:self
5826 context:@"urlerror"
5827 ] autorelease];
5828
5829 [sheet setBodyText:[error_ localizedDescription]];
5830 [sheet popupAlertAnimated:YES];
5831 } else {
5832 UIActionSheet *sheet = [[[UIActionSheet alloc]
5833 initWithTitle:UCLocalize("NOT_REPOSITORY")
5834 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5835 defaultButtonIndex:0
5836 delegate:self
5837 context:@"trivial"
5838 ] autorelease];
5839
5840 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5841 [sheet popupAlertAnimated:YES];
5842 }
5843
5844 [delegate_ setStatusBarShowsProgress:NO];
5845 [delegate_ removeProgressHUD:hud_];
5846
5847 [hud_ autorelease];
5848 hud_ = nil;
5849
5850 if (!defer) {
5851 [href_ release];
5852 href_ = nil;
5853 }
5854
5855 if (error_ != nil) {
5856 [error_ release];
5857 error_ = nil;
5858 }
5859 }
5860 }
5861
5862 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5863 switch ([response statusCode]) {
5864 case 200:
5865 cydia_ = YES;
5866 }
5867 }
5868
5869 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5870 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5871 if (error_ != nil)
5872 error_ = [error retain];
5873 [self _endConnection:connection];
5874 }
5875
5876 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5877 [self _endConnection:connection];
5878 }
5879
5880 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5881 NSMutableURLRequest *request = [NSMutableURLRequest
5882 requestWithURL:[NSURL URLWithString:href]
5883 cachePolicy:NSURLRequestUseProtocolCachePolicy
5884 timeoutInterval:20.0
5885 ];
5886
5887 [request setHTTPMethod:method];
5888
5889 if (Machine_ != NULL)
5890 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5891 if (UniqueID_ != nil)
5892 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5893
5894 if (Role_ != nil)
5895 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5896
5897 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5898 }
5899
5900 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5901 NSString *context([sheet context]);
5902
5903 if ([context isEqualToString:@"source"]) {
5904 switch (button) {
5905 case 1: {
5906 NSString *href = [[sheet textField] text];
5907
5908 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5909
5910 if (![href hasSuffix:@"/"])
5911 href_ = [href stringByAppendingString:@"/"];
5912 else
5913 href_ = href;
5914 href_ = [href_ retain];
5915
5916 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5917 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5918 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5919 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5920
5921 cydia_ = false;
5922
5923 hud_ = [[delegate_ addProgressHUD] retain];
5924 [hud_ setText:UCLocalize("VERIFYING_URL")];
5925 } break;
5926
5927 case 2:
5928 break;
5929
5930 _nodefault
5931 }
5932
5933 [sheet dismiss];
5934 } else if ([context isEqualToString:@"trivial"])
5935 [sheet dismiss];
5936 else if ([context isEqualToString:@"urlerror"])
5937 [sheet dismiss];
5938 else if ([context isEqualToString:@"warning"]) {
5939 switch (button) {
5940 case 1:
5941 [self complete];
5942 break;
5943
5944 case 2:
5945 break;
5946
5947 _nodefault
5948 }
5949
5950 [href_ release];
5951 href_ = nil;
5952
5953 [sheet dismiss];
5954 }
5955 }
5956
5957 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5958 if ((self = [super initWithBook:book]) != nil) {
5959 database_ = database;
5960 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5961
5962 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5963 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5964 [list_ setShouldHideHeaderInShortLists:NO];
5965
5966 [self addSubview:list_];
5967 [list_ setDataSource:self];
5968
5969 UITableColumn *column = [[UITableColumn alloc]
5970 initWithTitle:UCLocalize("NAME")
5971 identifier:@"name"
5972 width:[self frame].size.width
5973 ];
5974
5975 UITable *table = [list_ table];
5976 [table setSeparatorStyle:1];
5977 [table addTableColumn:column];
5978 [table setDelegate:self];
5979
5980 [self reloadData];
5981
5982 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5983 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5984 } return self;
5985 }
5986
5987 - (void) reloadData {
5988 pkgSourceList list;
5989 if (!list.ReadMainList())
5990 return;
5991
5992 [sources_ removeAllObjects];
5993 [sources_ addObjectsFromArray:[database_ sources]];
5994 _trace();
5995 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5996 _trace();
5997
5998 int count([sources_ count]);
5999 for (offset_ = 0; offset_ != count; ++offset_) {
6000 Source *source = [sources_ objectAtIndex:offset_];
6001 if ([source record] == nil)
6002 break;
6003 }
6004
6005 [list_ reloadData];
6006 }
6007
6008 - (void) resetViewAnimated:(BOOL)animated {
6009 [list_ resetViewAnimated:animated];
6010 }
6011
6012 - (void) _leftButtonClicked {
6013 /*[book_ pushPage:[[[AddSourceView alloc]
6014 initWithBook:book_
6015 database:database_
6016 ] autorelease]];*/
6017
6018 UIActionSheet *sheet = [[[UIActionSheet alloc]
6019 initWithTitle:UCLocalize("ENTER_APT_URL")
6020 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6021 defaultButtonIndex:0
6022 delegate:self
6023 context:@"source"
6024 ] autorelease];
6025
6026 [sheet setNumberOfRows:1];
6027
6028 [sheet addTextFieldWithValue:@"http://" label:@""];
6029
6030 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6031 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6032 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6033 [traits setKeyboardType:UIKeyboardTypeURL];
6034 // XXX: UIReturnKeyDone
6035 [traits setReturnKeyType:UIReturnKeyNext];
6036
6037 [sheet popupAlertAnimated:YES];
6038 }
6039
6040 - (void) _rightButtonClicked {
6041 UITable *table = [list_ table];
6042 BOOL editing = [table isRowDeletionEnabled];
6043 [table enableRowDeletion:!editing animated:YES];
6044 [book_ reloadButtonsForPage:self];
6045 }
6046
6047 - (NSString *) title {
6048 return UCLocalize("SOURCES");
6049 }
6050
6051 - (NSString *) leftButtonTitle {
6052 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6053 }
6054
6055 - (id) rightButtonTitle {
6056 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6057 }
6058
6059 - (UINavigationButtonStyle) rightButtonStyle {
6060 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6061 }
6062
6063 @end
6064 /* }}} */
6065
6066 /* Installed View {{{ */
6067 @interface InstalledView : RVPage {
6068 _transient Database *database_;
6069 FilteredPackageTable *packages_;
6070 BOOL expert_;
6071 }
6072
6073 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6074
6075 @end
6076
6077 @implementation InstalledView
6078
6079 - (void) dealloc {
6080 [packages_ release];
6081 [super dealloc];
6082 }
6083
6084 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6085 if ((self = [super initWithBook:book]) != nil) {
6086 database_ = database;
6087
6088 packages_ = [[FilteredPackageTable alloc]
6089 initWithBook:book
6090 database:database
6091 title:nil
6092 filter:@selector(isInstalledAndVisible:)
6093 with:[NSNumber numberWithBool:YES]
6094 ];
6095
6096 [self addSubview:packages_];
6097
6098 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6099 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6100 } return self;
6101 }
6102
6103 - (void) resetViewAnimated:(BOOL)animated {
6104 [packages_ resetViewAnimated:animated];
6105 }
6106
6107 - (void) reloadData {
6108 [packages_ reloadData];
6109 }
6110
6111 - (void) _rightButtonClicked {
6112 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6113 [packages_ reloadData];
6114 expert_ = !expert_;
6115 [book_ reloadButtonsForPage:self];
6116 }
6117
6118 - (NSString *) title {
6119 return UCLocalize("INSTALLED");
6120 }
6121
6122 - (NSString *) backButtonTitle {
6123 return UCLocalize("PACKAGES");
6124 }
6125
6126 - (id) rightButtonTitle {
6127 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6128 }
6129
6130 - (UINavigationButtonStyle) rightButtonStyle {
6131 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6132 }
6133
6134 - (void) setDelegate:(id)delegate {
6135 [super setDelegate:delegate];
6136 [packages_ setDelegate:delegate];
6137 }
6138
6139 @end
6140 /* }}} */
6141
6142 /* Home View {{{ */
6143 @interface HomeView : CydiaBrowserView {
6144 }
6145
6146 @end
6147
6148 @implementation HomeView
6149
6150 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6151 NSString *context([sheet context]);
6152
6153 if ([context isEqualToString:@"about"])
6154 [sheet dismiss];
6155 else
6156 [super alertSheet:sheet buttonClicked:button];
6157 }
6158
6159 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6160 [super _setMoreHeaders:request];
6161 if (ChipID_ != nil)
6162 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6163 }
6164
6165 - (void) _leftButtonClicked {
6166 UIActionSheet *sheet = [[[UIActionSheet alloc]
6167 initWithTitle:UCLocalize("ABOUT_CYDIA")
6168 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6169 defaultButtonIndex:0
6170 delegate:self
6171 context:@"about"
6172 ] autorelease];
6173
6174 [sheet setBodyText:
6175 @"Copyright (C) 2008-2009\n"
6176 "Jay Freeman (saurik)\n"
6177 "saurik@saurik.com\n"
6178 "http://www.saurik.com/\n"
6179 "\n"
6180 "The Okori Group\n"
6181 "http://www.theokorigroup.com/\n"
6182 "\n"
6183 "College of Creative Studies,\n"
6184 "University of California,\n"
6185 "Santa Barbara\n"
6186 "http://www.ccs.ucsb.edu/"
6187 ];
6188
6189 [sheet popupAlertAnimated:YES];
6190 }
6191
6192 - (NSString *) leftButtonTitle {
6193 return UCLocalize("ABOUT");
6194 }
6195
6196 @end
6197 /* }}} */
6198 /* Manage View {{{ */
6199 @interface ManageView : CydiaBrowserView {
6200 }
6201
6202 @end
6203
6204 @implementation ManageView
6205
6206 - (NSString *) title {
6207 return UCLocalize("MANAGE");
6208 }
6209
6210 - (void) _leftButtonClicked {
6211 [delegate_ askForSettings];
6212 [delegate_ updateData];
6213 }
6214
6215 - (NSString *) leftButtonTitle {
6216 return UCLocalize("SETTINGS");
6217 }
6218
6219 #if !AlwaysReload
6220 - (id) _rightButtonTitle {
6221 return Queuing_ ? UCLocalize("QUEUE") : nil;
6222 }
6223
6224 - (UINavigationButtonStyle) rightButtonStyle {
6225 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6226 }
6227
6228 - (void) _rightButtonClicked {
6229 [delegate_ queue];
6230 }
6231 #endif
6232
6233 - (bool) isLoading {
6234 return false;
6235 }
6236
6237 @end
6238 /* }}} */
6239
6240 /* Cydia Book {{{ */
6241 @interface CYBook : RVBook <
6242 ProgressDelegate
6243 > {
6244 _transient Database *database_;
6245 UINavigationBar *overlay_;
6246 UINavigationBar *underlay_;
6247 UIProgressIndicator *indicator_;
6248 UITextLabel *prompt_;
6249 UIProgressBar *progress_;
6250 UINavigationButton *cancel_;
6251 bool updating_;
6252 }
6253
6254 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6255 - (void) update;
6256 - (BOOL) updating;
6257
6258 @end
6259
6260 @implementation CYBook
6261
6262 - (void) dealloc {
6263 [overlay_ release];
6264 [indicator_ release];
6265 [prompt_ release];
6266 [progress_ release];
6267 [cancel_ release];
6268 [super dealloc];
6269 }
6270
6271 - (NSString *) getTitleForPage:(RVPage *)page {
6272 return [super getTitleForPage:page];
6273 }
6274
6275 - (BOOL) updating {
6276 return updating_;
6277 }
6278
6279 - (void) update {
6280 [UIView beginAnimations:nil context:NULL];
6281
6282 CGRect ovrframe = [overlay_ frame];
6283 ovrframe.origin.y = 0;
6284 [overlay_ setFrame:ovrframe];
6285
6286 CGRect barframe = [navbar_ frame];
6287 barframe.origin.y += ovrframe.size.height;
6288 [navbar_ setFrame:barframe];
6289
6290 CGRect trnframe = [transition_ frame];
6291 trnframe.origin.y += ovrframe.size.height;
6292 trnframe.size.height -= ovrframe.size.height;
6293 [transition_ setFrame:trnframe];
6294
6295 [UIView endAnimations];
6296
6297 [indicator_ startAnimation];
6298 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6299 [progress_ setProgress:0];
6300
6301 updating_ = true;
6302 [overlay_ addSubview:cancel_];
6303
6304 [NSThread
6305 detachNewThreadSelector:@selector(_update)
6306 toTarget:self
6307 withObject:nil
6308 ];
6309 }
6310
6311 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6312 NSString *context([sheet context]);
6313
6314 if ([context isEqualToString:@"refresh"])
6315 [sheet dismiss];
6316 }
6317
6318 - (void) _update_ {
6319 updating_ = false;
6320
6321 [indicator_ stopAnimation];
6322
6323 [UIView beginAnimations:nil context:NULL];
6324
6325 CGRect ovrframe = [overlay_ frame];
6326 ovrframe.origin.y = -ovrframe.size.height;
6327 [overlay_ setFrame:ovrframe];
6328
6329 CGRect barframe = [navbar_ frame];
6330 barframe.origin.y -= ovrframe.size.height;
6331 [navbar_ setFrame:barframe];
6332
6333 CGRect trnframe = [transition_ frame];
6334 trnframe.origin.y -= ovrframe.size.height;
6335 trnframe.size.height += ovrframe.size.height;
6336 [transition_ setFrame:trnframe];
6337
6338 [UIView commitAnimations];
6339
6340 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6341 }
6342
6343 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6344 if ((self = [super initWithFrame:frame]) != nil) {
6345 database_ = database;
6346
6347 CGRect ovrrect([navbar_ bounds]);
6348 ovrrect.size.height = [UINavigationBar defaultSize].height;
6349 ovrrect.origin.y = -ovrrect.size.height;
6350
6351 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6352 [self addSubview:overlay_];
6353
6354 ovrrect.origin.y = frame.size.height;
6355 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6356 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6357 [self addSubview:underlay_];
6358
6359 [overlay_ setBarStyle:1];
6360 [underlay_ setBarStyle:1];
6361
6362 int barstyle([overlay_ _barStyle:NO]);
6363 bool ugly(barstyle == 0);
6364
6365 UIProgressIndicatorStyle style = ugly ?
6366 UIProgressIndicatorStyleMediumBrown :
6367 UIProgressIndicatorStyleMediumWhite;
6368
6369 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6370 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6371 CGRect indrect = {{indoffset, indoffset}, indsize};
6372
6373 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6374 [indicator_ setStyle:style];
6375 [overlay_ addSubview:indicator_];
6376
6377 CGSize prmsize = {215, indsize.height + 4};
6378
6379 CGRect prmrect = {{
6380 indoffset * 2 + indsize.width,
6381 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6382 }, prmsize};
6383
6384 UIFont *font([UIFont systemFontOfSize:15]);
6385
6386 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6387
6388 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6389 [prompt_ setBackgroundColor:[UIColor clearColor]];
6390 [prompt_ setFont:font];
6391
6392 [overlay_ addSubview:prompt_];
6393
6394 CGSize prgsize = {75, 100};
6395
6396 CGRect prgrect = {{
6397 ovrrect.size.width - prgsize.width - 10,
6398 (ovrrect.size.height - prgsize.height) / 2
6399 } , prgsize};
6400
6401 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6402 [progress_ setStyle:0];
6403 [overlay_ addSubview:progress_];
6404
6405 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6406 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6407
6408 CGRect frame = [cancel_ frame];
6409 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6410 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6411 [cancel_ setFrame:frame];
6412
6413 [cancel_ setBarStyle:barstyle];
6414 } return self;
6415 }
6416
6417 - (void) _onCancel {
6418 updating_ = false;
6419 [cancel_ removeFromSuperview];
6420 }
6421
6422 - (void) _update { _pooled
6423 Status status;
6424 status.setDelegate(self);
6425 [database_ updateWithStatus:status];
6426
6427 [self
6428 performSelectorOnMainThread:@selector(_update_)
6429 withObject:nil
6430 waitUntilDone:NO
6431 ];
6432 }
6433
6434 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6435 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6436 }
6437
6438 /*
6439 UIActionSheet *sheet = [[[UIActionSheet alloc]
6440 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6441 buttons:[NSArray arrayWithObjects:
6442 UCLocalize("OK"),
6443 nil]
6444 defaultButtonIndex:0
6445 delegate:self
6446 context:@"refresh"
6447 ] autorelease];
6448
6449 [sheet setBodyText:error];
6450 [sheet popupAlertAnimated:YES];
6451
6452 [self reloadButtons];
6453 */
6454
6455 - (void) setProgressTitle:(NSString *)title {
6456 [self
6457 performSelectorOnMainThread:@selector(_setProgressTitle:)
6458 withObject:title
6459 waitUntilDone:YES
6460 ];
6461 }
6462
6463 - (void) setProgressPercent:(float)percent {
6464 [self
6465 performSelectorOnMainThread:@selector(_setProgressPercent:)
6466 withObject:[NSNumber numberWithFloat:percent]
6467 waitUntilDone:YES
6468 ];
6469 }
6470
6471 - (void) startProgress {
6472 }
6473
6474 - (void) addProgressOutput:(NSString *)output {
6475 [self
6476 performSelectorOnMainThread:@selector(_addProgressOutput:)
6477 withObject:output
6478 waitUntilDone:YES
6479 ];
6480 }
6481
6482 - (bool) isCancelling:(size_t)received {
6483 return !updating_;
6484 }
6485
6486 - (void) _setProgressTitle:(NSString *)title {
6487 [prompt_ setText:title];
6488 }
6489
6490 - (void) _setProgressPercent:(NSNumber *)percent {
6491 [progress_ setProgress:[percent floatValue]];
6492 }
6493
6494 - (void) _addProgressOutput:(NSString *)output {
6495 }
6496
6497 @end
6498 /* }}} */
6499 /* Cydia:// Protocol {{{ */
6500 @interface CydiaURLProtocol : NSURLProtocol {
6501 }
6502
6503 @end
6504
6505 @implementation CydiaURLProtocol
6506
6507 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6508 NSURL *url([request URL]);
6509 if (url == nil)
6510 return NO;
6511 NSString *scheme([[url scheme] lowercaseString]);
6512 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6513 return NO;
6514 return YES;
6515 }
6516
6517 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6518 return request;
6519 }
6520
6521 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6522 id<NSURLProtocolClient> client([self client]);
6523 if (icon == nil)
6524 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6525 else {
6526 NSData *data(UIImagePNGRepresentation(icon));
6527
6528 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6529 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6530 [client URLProtocol:self didLoadData:data];
6531 [client URLProtocolDidFinishLoading:self];
6532 }
6533 }
6534
6535 - (void) startLoading {
6536 id<NSURLProtocolClient> client([self client]);
6537 NSURLRequest *request([self request]);
6538
6539 NSURL *url([request URL]);
6540 NSString *href([url absoluteString]);
6541
6542 NSString *path([href substringFromIndex:8]);
6543 NSRange slash([path rangeOfString:@"/"]);
6544
6545 NSString *command;
6546 if (slash.location == NSNotFound) {
6547 command = path;
6548 path = nil;
6549 } else {
6550 command = [path substringToIndex:slash.location];
6551 path = [path substringFromIndex:(slash.location + 1)];
6552 }
6553
6554 Database *database([Database sharedInstance]);
6555
6556 if ([command isEqualToString:@"package-icon"]) {
6557 if (path == nil)
6558 goto fail;
6559 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6560 Package *package([database packageWithName:path]);
6561 if (package == nil)
6562 goto fail;
6563 UIImage *icon([package icon]);
6564 [self _returnPNGWithImage:icon forRequest:request];
6565 } else if ([command isEqualToString:@"source-icon"]) {
6566 if (path == nil)
6567 goto fail;
6568 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6569 NSString *source(Simplify(path));
6570 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6571 if (icon == nil)
6572 icon = [UIImage applicationImageNamed:@"unknown.png"];
6573 [self _returnPNGWithImage:icon forRequest:request];
6574 } else if ([command isEqualToString:@"uikit-image"]) {
6575 if (path == nil)
6576 goto fail;
6577 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6578 UIImage *icon(_UIImageWithName(path));
6579 [self _returnPNGWithImage:icon forRequest:request];
6580 } else if ([command isEqualToString:@"section-icon"]) {
6581 if (path == nil)
6582 goto fail;
6583 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6584 NSString *section(Simplify(path));
6585 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6586 if (icon == nil)
6587 icon = [UIImage applicationImageNamed:@"unknown.png"];
6588 [self _returnPNGWithImage:icon forRequest:request];
6589 } else fail: {
6590 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6591 }
6592 }
6593
6594 - (void) stopLoading {
6595 }
6596
6597 @end
6598 /* }}} */
6599
6600 /* Sections View {{{ */
6601 @interface SectionsView : RVPage {
6602 _transient Database *database_;
6603 NSMutableArray *sections_;
6604 NSMutableArray *filtered_;
6605 UITransitionView *transition_;
6606 UITable *list_;
6607 UIView *accessory_;
6608 BOOL editing_;
6609 }
6610
6611 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6612 - (void) reloadData;
6613 - (void) resetView;
6614
6615 @end
6616
6617 @implementation SectionsView
6618
6619 - (void) dealloc {
6620 [list_ setDataSource:nil];
6621 [list_ setDelegate:nil];
6622
6623 [sections_ release];
6624 [filtered_ release];
6625 [transition_ release];
6626 [list_ release];
6627 [accessory_ release];
6628 [super dealloc];
6629 }
6630
6631 - (int) numberOfRowsInTable:(UITable *)table {
6632 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6633 }
6634
6635 - (float) table:(UITable *)table heightForRow:(int)row {
6636 return 45;
6637 }
6638
6639 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6640 if (reusing == nil)
6641 reusing = [[[SectionCell alloc] init] autorelease];
6642 [(SectionCell *)reusing setSection:(editing_ ?
6643 [sections_ objectAtIndex:row] :
6644 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6645 ) editing:editing_];
6646 return reusing;
6647 }
6648
6649 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6650 return !editing_;
6651 }
6652
6653 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6654 return !editing_;
6655 }
6656
6657 - (void) tableRowSelected:(NSNotification *)notification {
6658 int row = [[notification object] selectedRow];
6659 if (row == INT_MAX)
6660 return;
6661
6662 Section *section;
6663 NSString *name;
6664 NSString *title;
6665
6666 if (row == 0) {
6667 section = nil;
6668 name = nil;
6669 title = UCLocalize("ALL_PACKAGES");
6670 } else {
6671 section = [filtered_ objectAtIndex:(row - 1)];
6672 name = [section name];
6673
6674 if (name != nil) {
6675 name = [NSString stringWithString:name];
6676 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6677 } else {
6678 name = @"";
6679 title = UCLocalize("NO_SECTION");
6680 }
6681 }
6682
6683 PackageTable *table = [[[FilteredPackageTable alloc]
6684 initWithBook:book_
6685 database:database_
6686 title:title
6687 filter:@selector(isVisibleInSection:)
6688 with:name
6689 ] autorelease];
6690
6691 [table setDelegate:delegate_];
6692
6693 [book_ pushPage:table];
6694 }
6695
6696 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6697 if ((self = [super initWithBook:book]) != nil) {
6698 database_ = database;
6699
6700 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6701 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6702
6703 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6704 [self addSubview:transition_];
6705
6706 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6707 [transition_ transition:0 toView:list_];
6708
6709 UITableColumn *column = [[[UITableColumn alloc]
6710 initWithTitle:UCLocalize("NAME")
6711 identifier:@"name"
6712 width:[self frame].size.width
6713 ] autorelease];
6714
6715 [list_ setDataSource:self];
6716 [list_ setSeparatorStyle:1];
6717 [list_ addTableColumn:column];
6718 [list_ setDelegate:self];
6719 [list_ setReusesTableCells:YES];
6720
6721 [self reloadData];
6722
6723 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6724 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6725 } return self;
6726 }
6727
6728 - (void) reloadData {
6729 NSArray *packages = [database_ packages];
6730
6731 [sections_ removeAllObjects];
6732 [filtered_ removeAllObjects];
6733
6734 #if 0
6735 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6736 SectionMap sections;
6737 sections.resize(64);
6738 #else
6739 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6740 #endif
6741
6742 _trace();
6743 for (Package *package in packages) {
6744 NSString *name([package section]);
6745 NSString *key(name == nil ? @"" : name);
6746
6747 #if 0
6748 Section **section;
6749
6750 _profile(SectionsView$reloadData$Section)
6751 section = &sections[key];
6752 if (*section == nil) {
6753 _profile(SectionsView$reloadData$Section$Allocate)
6754 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6755 _end
6756 }
6757 _end
6758
6759 [*section addToCount];
6760
6761 _profile(SectionsView$reloadData$Filter)
6762 if (![package valid] || ![package visible])
6763 continue;
6764 _end
6765
6766 [*section addToRow];
6767 #else
6768 Section *section;
6769
6770 _profile(SectionsView$reloadData$Section)
6771 section = [sections objectForKey:key];
6772 if (section == nil) {
6773 _profile(SectionsView$reloadData$Section$Allocate)
6774 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6775 [sections setObject:section forKey:key];
6776 _end
6777 }
6778 _end
6779
6780 [section addToCount];
6781
6782 _profile(SectionsView$reloadData$Filter)
6783 if (![package valid] || ![package visible])
6784 continue;
6785 _end
6786
6787 [section addToRow];
6788 #endif
6789 }
6790 _trace();
6791
6792 #if 0
6793 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6794 [sections_ addObject:i->second];
6795 #else
6796 [sections_ addObjectsFromArray:[sections allValues]];
6797 #endif
6798
6799 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6800
6801 for (Section *section in sections_) {
6802 size_t count([section row]);
6803 if (count == 0)
6804 continue;
6805
6806 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6807 [section setCount:count];
6808 [filtered_ addObject:section];
6809 }
6810
6811 [list_ reloadData];
6812 _trace();
6813 }
6814
6815 - (void) resetView {
6816 if (editing_)
6817 [self _rightButtonClicked];
6818 }
6819
6820 - (void) resetViewAnimated:(BOOL)animated {
6821 [list_ resetViewAnimated:animated];
6822 }
6823
6824 - (void) _rightButtonClicked {
6825 if ((editing_ = !editing_))
6826 [list_ reloadData];
6827 else
6828 [delegate_ updateData];
6829 [book_ reloadTitleForPage:self];
6830 [book_ reloadButtonsForPage:self];
6831 }
6832
6833 - (NSString *) title {
6834 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6835 }
6836
6837 - (NSString *) backButtonTitle {
6838 return UCLocalize("SECTIONS");
6839 }
6840
6841 - (id) rightButtonTitle {
6842 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6843 }
6844
6845 - (UINavigationButtonStyle) rightButtonStyle {
6846 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6847 }
6848
6849 - (UIView *) accessoryView {
6850 return accessory_;
6851 }
6852
6853 @end
6854 /* }}} */
6855 /* Changes View {{{ */
6856 @interface ChangesView : RVPage {
6857 _transient Database *database_;
6858 NSMutableArray *packages_;
6859 NSMutableArray *sections_;
6860 UITableView *list_;
6861 unsigned upgrades_;
6862 }
6863
6864 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6865 - (void) reloadData;
6866
6867 @end
6868
6869 @implementation ChangesView
6870
6871 - (void) dealloc {
6872 [list_ setDelegate:nil];
6873 [list_ setDataSource:nil];
6874
6875 [packages_ release];
6876 [sections_ release];
6877 [list_ release];
6878 [super dealloc];
6879 }
6880
6881 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6882 NSInteger count([sections_ count]);
6883 return count == 0 ? 1 : count;
6884 }
6885
6886 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6887 if ([sections_ count] == 0)
6888 return nil;
6889 return [[sections_ objectAtIndex:section] name];
6890 }
6891
6892 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6893 if ([sections_ count] == 0)
6894 return 0;
6895 return [[sections_ objectAtIndex:section] count];
6896 }
6897
6898 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6899 Section *section([sections_ objectAtIndex:[path section]]);
6900 NSInteger row([path row]);
6901 return [packages_ objectAtIndex:([section row] + row)];
6902 }
6903
6904 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6905 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6906 if (cell == nil)
6907 cell = [[[PackageCell alloc] init] autorelease];
6908 [cell setPackage:[self packageAtIndexPath:path]];
6909 return cell;
6910 }
6911
6912 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6913 return 73;
6914 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6915 }
6916
6917 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6918 Package *package([self packageAtIndexPath:path]);
6919 PackageView *view([delegate_ packageView]);
6920 [view setDelegate:delegate_];
6921 [view setPackage:package];
6922 [book_ pushPage:view];
6923 return path;
6924 }
6925
6926 - (void) _leftButtonClicked {
6927 [(CYBook *)book_ update];
6928 [self reloadButtons];
6929 }
6930
6931 - (void) _rightButtonClicked {
6932 [delegate_ distUpgrade];
6933 }
6934
6935 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6936 if ((self = [super initWithBook:book]) != nil) {
6937 database_ = database;
6938
6939 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6940 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6941
6942 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6943 [self addSubview:list_];
6944
6945 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6946 [list_ setDataSource:self];
6947 [list_ setDelegate:self];
6948 //[list_ setSectionListStyle:1];
6949
6950 [self reloadData];
6951
6952 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6953 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6954 } return self;
6955 }
6956
6957 - (void) reloadData {
6958 NSArray *packages = [database_ packages];
6959
6960 [packages_ removeAllObjects];
6961 [sections_ removeAllObjects];
6962
6963 _trace();
6964 for (Package *package in packages)
6965 if (
6966 [package uninstalled] && [package valid] && [package visible] ||
6967 [package upgradableAndEssential:YES]
6968 )
6969 [packages_ addObject:package];
6970
6971 _trace();
6972 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6973 _trace();
6974
6975 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6976 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6977 Section *section = nil;
6978 NSDate *last = nil;
6979
6980 upgrades_ = 0;
6981 bool unseens = false;
6982
6983 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6984
6985 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6986 Package *package = [packages_ objectAtIndex:offset];
6987
6988 BOOL uae = [package upgradableAndEssential:YES];
6989
6990 if (!uae) {
6991 unseens = true;
6992 NSDate *seen;
6993
6994 _profile(ChangesView$reloadData$Remember)
6995 seen = [package seen];
6996 _end
6997
6998 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6999 last = seen;
7000
7001 NSString *name;
7002 if (seen == nil)
7003 name = UCLocalize("UNKNOWN");
7004 else {
7005 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7006 [name autorelease];
7007 }
7008
7009 _profile(ChangesView$reloadData$Allocate)
7010 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7011 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7012 [sections_ addObject:section];
7013 _end
7014 }
7015
7016 [section addToCount];
7017 } else if ([package ignored])
7018 [ignored addToCount];
7019 else {
7020 ++upgrades_;
7021 [upgradable addToCount];
7022 }
7023 }
7024 _trace();
7025
7026 CFRelease(formatter);
7027
7028 if (unseens) {
7029 Section *last = [sections_ lastObject];
7030 size_t count = [last count];
7031 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7032 [sections_ removeLastObject];
7033 }
7034
7035 if ([ignored count] != 0)
7036 [sections_ insertObject:ignored atIndex:0];
7037 if (upgrades_ != 0)
7038 [sections_ insertObject:upgradable atIndex:0];
7039
7040 [list_ reloadData];
7041 [self reloadButtons];
7042 }
7043
7044 - (void) resetViewAnimated:(BOOL)animated {
7045 [list_ resetViewAnimated:animated];
7046 }
7047
7048 - (NSString *) leftButtonTitle {
7049 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7050 }
7051
7052 - (id) rightButtonTitle {
7053 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7054 }
7055
7056 - (NSString *) title {
7057 return UCLocalize("CHANGES");
7058 }
7059
7060 @end
7061 /* }}} */
7062 /* Search View {{{ */
7063 @protocol SearchViewDelegate
7064 - (void) showKeyboard:(BOOL)show;
7065 @end
7066
7067 @interface SearchView : RVPage {
7068 UIView *accessory_;
7069 UISearchField *field_;
7070 FilteredPackageTable *table_;
7071 UIView *dimmed_;
7072 bool reload_;
7073 }
7074
7075 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7076 - (void) reloadData;
7077
7078 @end
7079
7080 @implementation SearchView
7081
7082 - (void) dealloc {
7083 [field_ setDelegate:nil];
7084
7085 [accessory_ release];
7086 [field_ release];
7087 [table_ release];
7088 [dimmed_ release];
7089 [super dealloc];
7090 }
7091
7092 - (void) _showKeyboard:(BOOL)show {
7093 CGSize keysize = [UIKeyboard defaultSize];
7094 CGRect keydown = [book_ pageBounds];
7095 CGRect keyup = keydown;
7096 keyup.size.height -= keysize.height - ButtonBarHeight_;
7097
7098 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7099
7100 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7101 [animation setSignificantRectFields:8];
7102
7103 if (show) {
7104 [animation setStartFrame:keydown];
7105 [animation setEndFrame:keyup];
7106 } else {
7107 [animation setStartFrame:keyup];
7108 [animation setEndFrame:keydown];
7109 }
7110
7111 UIAnimator *animator = [UIAnimator sharedAnimator];
7112
7113 [animator
7114 addAnimations:[NSArray arrayWithObjects:animation, nil]
7115 withDuration:(KeyboardTime_ - delay)
7116 start:!show
7117 ];
7118
7119 if (show)
7120 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7121
7122 [delegate_ showKeyboard:show];
7123 }
7124
7125 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7126 [self _showKeyboard:YES];
7127 }
7128
7129 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7130 [self _showKeyboard:NO];
7131 }
7132
7133 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7134 if (reload_) {
7135 NSString *text([field_ text]);
7136 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7137 [self reloadData];
7138 reload_ = false;
7139 }
7140 }
7141
7142 - (void) textFieldClearButtonPressed:(UITextField *)field {
7143 reload_ = true;
7144 }
7145
7146 - (void) keyboardInputShouldDelete:(id)input {
7147 reload_ = true;
7148 }
7149
7150 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7151 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7152 reload_ = true;
7153 return YES;
7154 } else {
7155 [field_ resignFirstResponder];
7156 return NO;
7157 }
7158 }
7159
7160 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7161 if ((self = [super initWithBook:book]) != nil) {
7162 CGRect pageBounds = [book_ pageBounds];
7163
7164 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7165 CGColor dimmed(space_, 0, 0, 0, 0.5);
7166 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7167
7168 table_ = [[FilteredPackageTable alloc]
7169 initWithBook:book
7170 database:database
7171 title:nil
7172 filter:@selector(isUnfilteredAndSearchedForBy:)
7173 with:nil
7174 ];
7175
7176 [table_ setShouldHideHeaderInShortLists:NO];
7177 [self addSubview:table_];
7178
7179 CGRect cnfrect = {{7, 38}, {17, 18}};
7180
7181 CGRect area;
7182
7183 area.origin.x = 10;
7184 area.origin.y = 1;
7185
7186 area.size.width = [self bounds].size.width - area.origin.x * 2;
7187 area.size.height = [UISearchField defaultHeight];
7188
7189 field_ = [[UISearchField alloc] initWithFrame:area];
7190
7191 UIFont *font = [UIFont systemFontOfSize:16];
7192 [field_ setFont:font];
7193
7194 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7195 [field_ setDelegate:self];
7196
7197 [field_ setPaddingTop:5];
7198
7199 UITextInputTraits *traits([field_ textInputTraits]);
7200 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7201 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7202 [traits setReturnKeyType:UIReturnKeySearch];
7203
7204 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7205
7206 accessory_ = [[UIView alloc] initWithFrame:accrect];
7207 [accessory_ addSubview:field_];
7208
7209 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7210 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7211 } return self;
7212 }
7213
7214 - (void) resetViewAnimated:(BOOL)animated {
7215 [table_ resetViewAnimated:animated];
7216 }
7217
7218 - (void) _reloadData {
7219 }
7220
7221 - (void) reloadData {
7222 [table_ setObject:[field_ text]];
7223 _profile(SearchView$reloadData)
7224 [table_ reloadData];
7225 _end
7226 PrintTimes();
7227 [table_ resetCursor];
7228 }
7229
7230 - (UIView *) accessoryView {
7231 return accessory_;
7232 }
7233
7234 - (NSString *) title {
7235 return nil;
7236 }
7237
7238 - (NSString *) backButtonTitle {
7239 return UCLocalize("SEARCH");
7240 }
7241
7242 - (void) setDelegate:(id)delegate {
7243 [table_ setDelegate:delegate];
7244 [super setDelegate:delegate];
7245 }
7246
7247 @end
7248 /* }}} */
7249 /* Settings View {{{ */
7250 @interface SettingsView : RVPage {
7251 _transient Database *database_;
7252 NSString *name_;
7253 Package *package_;
7254 UIPreferencesTable *table_;
7255 _UISwitchSlider *subscribedSwitch_;
7256 _UISwitchSlider *ignoredSwitch_;
7257 UIPreferencesControlTableCell *subscribedCell_;
7258 UIPreferencesControlTableCell *ignoredCell_;
7259 }
7260
7261 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7262
7263 @end
7264
7265 @implementation SettingsView
7266
7267 - (void) dealloc {
7268 [table_ setDataSource:nil];
7269
7270 [name_ release];
7271 if (package_ != nil)
7272 [package_ release];
7273 [table_ release];
7274 [subscribedSwitch_ release];
7275 [ignoredSwitch_ release];
7276 [subscribedCell_ release];
7277 [ignoredCell_ release];
7278 [super dealloc];
7279 }
7280
7281 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7282 if (package_ == nil)
7283 return 0;
7284
7285 return 2;
7286 }
7287
7288 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7289 if (package_ == nil)
7290 return nil;
7291
7292 switch (group) {
7293 case 0: return nil;
7294 case 1: return nil;
7295
7296 _nodefault
7297 }
7298
7299 return nil;
7300 }
7301
7302 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7303 if (package_ == nil)
7304 return NO;
7305
7306 switch (group) {
7307 case 0: return NO;
7308 case 1: return YES;
7309
7310 _nodefault
7311 }
7312
7313 return NO;
7314 }
7315
7316 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7317 if (package_ == nil)
7318 return 0;
7319
7320 switch (group) {
7321 case 0: return 1;
7322 case 1: return 1;
7323
7324 _nodefault
7325 }
7326
7327 return 0;
7328 }
7329
7330 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7331 if (package_ == nil)
7332 return;
7333
7334 _UISwitchSlider *slider([cell control]);
7335 BOOL value([slider value] != 0);
7336 NSMutableDictionary *metadata([package_ metadata]);
7337
7338 BOOL before;
7339 if (NSNumber *number = [metadata objectForKey:key])
7340 before = [number boolValue];
7341 else
7342 before = NO;
7343
7344 if (value != before) {
7345 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7346 Changed_ = true;
7347 [delegate_ updateData];
7348 }
7349 }
7350
7351 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7352 [self onSomething:cell withKey:@"IsSubscribed"];
7353 }
7354
7355 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7356 [self onSomething:cell withKey:@"IsIgnored"];
7357 }
7358
7359 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7360 if (package_ == nil)
7361 return nil;
7362
7363 switch (group) {
7364 case 0: switch (row) {
7365 case 0:
7366 return subscribedCell_;
7367 case 1:
7368 return ignoredCell_;
7369 _nodefault
7370 } break;
7371
7372 case 1: switch (row) {
7373 case 0: {
7374 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7375 [cell setShowSelection:NO];
7376 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7377 return cell;
7378 }
7379
7380 _nodefault
7381 } break;
7382
7383 _nodefault
7384 }
7385
7386 return nil;
7387 }
7388
7389 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7390 if ((self = [super initWithBook:book])) {
7391 database_ = database;
7392 name_ = [package retain];
7393
7394 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7395 [self addSubview:table_];
7396
7397 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7398 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7399
7400 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7401 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7402
7403 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7404 [subscribedCell_ setShowSelection:NO];
7405 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7406 [subscribedCell_ setControl:subscribedSwitch_];
7407
7408 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7409 [ignoredCell_ setShowSelection:NO];
7410 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7411 [ignoredCell_ setControl:ignoredSwitch_];
7412
7413 [table_ setDataSource:self];
7414 [self reloadData];
7415 } return self;
7416 }
7417
7418 - (void) resetViewAnimated:(BOOL)animated {
7419 [table_ resetViewAnimated:animated];
7420 }
7421
7422 - (void) reloadData {
7423 if (package_ != nil)
7424 [package_ autorelease];
7425 package_ = [database_ packageWithName:name_];
7426 if (package_ != nil) {
7427 [package_ retain];
7428 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7429 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7430 }
7431
7432 [table_ reloadData];
7433 }
7434
7435 - (NSString *) title {
7436 return UCLocalize("SETTINGS");
7437 }
7438
7439 @end
7440 /* }}} */
7441
7442 /* Signature View {{{ */
7443 @interface SignatureView : CydiaBrowserView {
7444 _transient Database *database_;
7445 NSString *package_;
7446 }
7447
7448 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7449
7450 @end
7451
7452 @implementation SignatureView
7453
7454 - (void) dealloc {
7455 [package_ release];
7456 [super dealloc];
7457 }
7458
7459 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7460 // XXX: dude!
7461 [super webView:sender didClearWindowObject:window forFrame:frame];
7462 }
7463
7464 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7465 if ((self = [super initWithBook:book]) != nil) {
7466 database_ = database;
7467 package_ = [package retain];
7468 [self reloadData];
7469 } return self;
7470 }
7471
7472 - (void) resetViewAnimated:(BOOL)animated {
7473 }
7474
7475 - (void) reloadData {
7476 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7477 }
7478
7479 @end
7480 /* }}} */
7481
7482 @interface Cydia : UIApplication <
7483 ConfirmationViewDelegate,
7484 ProgressViewDelegate,
7485 SearchViewDelegate,
7486 CydiaDelegate
7487 > {
7488 UIWindow *window_;
7489
7490 UIView *underlay_;
7491 UIView *overlay_;
7492 CYBook *book_;
7493 UIToolbar *toolbar_;
7494
7495 RVBook *confirm_;
7496
7497 NSMutableArray *essential_;
7498 NSMutableArray *broken_;
7499
7500 Database *database_;
7501 ProgressView *progress_;
7502
7503 unsigned tag_;
7504
7505 UIKeyboard *keyboard_;
7506 UIProgressHUD *hud_;
7507
7508 SectionsView *sections_;
7509 ChangesView *changes_;
7510 ManageView *manage_;
7511 SearchView *search_;
7512
7513 #if RecyclePackageViews
7514 NSMutableArray *details_;
7515 #endif
7516 }
7517
7518 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7519 - (void) setPage:(RVPage *)page;
7520
7521 @end
7522
7523 static _finline void _setHomePage(Cydia *self) {
7524 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7525 }
7526
7527 @implementation Cydia
7528
7529 - (void) _loaded {
7530 if ([broken_ count] != 0) {
7531 int count = [broken_ count];
7532
7533 UIActionSheet *sheet = [[[UIActionSheet alloc]
7534 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7535 buttons:[NSArray arrayWithObjects:
7536 UCLocalize("FORCIBLY_CLEAR"),
7537 UCLocalize("TEMPORARY_IGNORE"),
7538 nil]
7539 defaultButtonIndex:0
7540 delegate:self
7541 context:@"fixhalf"
7542 ] autorelease];
7543
7544 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7545 [sheet popupAlertAnimated:YES];
7546 } else if (!Ignored_ && [essential_ count] != 0) {
7547 int count = [essential_ count];
7548
7549 UIActionSheet *sheet = [[[UIActionSheet alloc]
7550 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7551 buttons:[NSArray arrayWithObjects:
7552 UCLocalize("UPGRADE_ESSENTIAL"),
7553 UCLocalize("COMPLETE_UPGRADE"),
7554 UCLocalize("TEMPORARY_IGNORE"),
7555 nil]
7556 defaultButtonIndex:0
7557 delegate:self
7558 context:@"upgrade"
7559 ] autorelease];
7560
7561 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7562 [sheet popupAlertAnimated:YES];
7563 }
7564 }
7565
7566 - (void) _saveConfig {
7567 if (Changed_) {
7568 _trace();
7569 NSString *error(nil);
7570 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7571 _trace();
7572 NSError *error(nil);
7573 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7574 NSLog(@"failure to save metadata data: %@", error);
7575 _trace();
7576 } else {
7577 NSLog(@"failure to serialize metadata: %@", error);
7578 return;
7579 }
7580
7581 Changed_ = false;
7582 }
7583 }
7584
7585 - (void) _updateData {
7586 [self _saveConfig];
7587
7588 /* XXX: this is just stupid */
7589 if (tag_ != 2 && sections_ != nil)
7590 [sections_ reloadData];
7591 if (tag_ != 3 && changes_ != nil)
7592 [changes_ reloadData];
7593 if (tag_ != 5 && search_ != nil)
7594 [search_ reloadData];
7595
7596 [book_ reloadData];
7597 }
7598
7599 - (void) _reloadData {
7600 UIView *block();
7601
7602 static bool loaded(false);
7603 UIProgressHUD *hud([self addProgressHUD]);
7604 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7605
7606 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7607 _trace();
7608
7609 [self removeProgressHUD:hud];
7610
7611 size_t changes(0);
7612
7613 [essential_ removeAllObjects];
7614 [broken_ removeAllObjects];
7615
7616 NSArray *packages([database_ packages]);
7617 for (Package *package in packages) {
7618 if ([package half])
7619 [broken_ addObject:package];
7620 if ([package upgradableAndEssential:NO]) {
7621 if ([package essential])
7622 [essential_ addObject:package];
7623 ++changes;
7624 }
7625 }
7626
7627 if (changes != 0) {
7628 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7629 [toolbar_ setBadgeValue:badge forButton:3];
7630 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7631 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7632 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7633 [self setApplicationBadge:badge];
7634 else
7635 [self setApplicationBadgeString:badge];
7636 } else {
7637 [toolbar_ setBadgeValue:nil forButton:3];
7638 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7639 [toolbar_ setBadgeAnimated:NO forButton:3];
7640 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7641 [self removeApplicationBadge];
7642 else // XXX: maybe use setApplicationBadgeString also?
7643 [self setApplicationIconBadgeNumber:0];
7644 }
7645
7646 Queuing_ = false;
7647 [toolbar_ setBadgeValue:nil forButton:4];
7648
7649 [self _updateData];
7650
7651 if (loaded || ManualRefresh) loaded:
7652 [self _loaded];
7653 else {
7654 loaded = true;
7655
7656 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7657 NSTimeInterval interval([update timeIntervalSinceNow]);
7658 if (interval <= 0 && interval > -(15*60))
7659 goto loaded;
7660 }
7661
7662 [book_ update];
7663 }
7664 }
7665
7666 - (void) updateData {
7667 [database_ setVisible];
7668 [self _updateData];
7669 }
7670
7671 - (void) update_ {
7672 [database_ update];
7673 }
7674
7675 - (void) syncData {
7676 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7677 _assert(file != NULL);
7678
7679 for (NSString *key in [Sources_ allKeys]) {
7680 NSDictionary *source([Sources_ objectForKey:key]);
7681
7682 fprintf(file, "%s %s %s\n",
7683 [[source objectForKey:@"Type"] UTF8String],
7684 [[source objectForKey:@"URI"] UTF8String],
7685 [[source objectForKey:@"Distribution"] UTF8String]
7686 );
7687 }
7688
7689 fclose(file);
7690
7691 [self _saveConfig];
7692
7693 [progress_
7694 detachNewThreadSelector:@selector(update_)
7695 toTarget:self
7696 withObject:nil
7697 title:UCLocalize("UPDATING_SOURCES")
7698 ];
7699 }
7700
7701 - (void) reloadData {
7702 @synchronized (self) {
7703 if (confirm_ == nil)
7704 [self _reloadData];
7705 }
7706 }
7707
7708 - (void) resolve {
7709 pkgProblemResolver *resolver = [database_ resolver];
7710
7711 resolver->InstallProtect();
7712 if (!resolver->Resolve(true))
7713 _error->Discard();
7714 }
7715
7716 - (void) popUpBook:(RVBook *)book {
7717 [underlay_ popSubview:book];
7718 }
7719
7720 - (CGRect) popUpBounds {
7721 return [underlay_ bounds];
7722 }
7723
7724 - (bool) perform {
7725 if (![database_ prepare])
7726 return false;
7727
7728 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7729 [confirm_ setDelegate:self];
7730
7731 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7732 [page setDelegate:self];
7733
7734 [confirm_ setPage:page];
7735 [self popUpBook:confirm_];
7736
7737 return true;
7738 }
7739
7740 - (void) queue {
7741 @synchronized (self) {
7742 [self perform];
7743 }
7744 }
7745
7746 - (void) clearPackage:(Package *)package {
7747 @synchronized (self) {
7748 [package clear];
7749 [self resolve];
7750 [self perform];
7751 }
7752 }
7753
7754 - (void) installPackage:(Package *)package {
7755 @synchronized (self) {
7756 [package install];
7757 [self resolve];
7758 [self perform];
7759 }
7760 }
7761
7762 - (void) removePackage:(Package *)package {
7763 @synchronized (self) {
7764 [package remove];
7765 [self resolve];
7766 [self perform];
7767 }
7768 }
7769
7770 - (void) distUpgrade {
7771 @synchronized (self) {
7772 if (![database_ upgrade])
7773 return;
7774 [self perform];
7775 }
7776 }
7777
7778 - (void) cancel {
7779 [self slideUp:[[[UIActionSheet alloc]
7780 initWithTitle:nil
7781 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7782 defaultButtonIndex:1
7783 delegate:self
7784 context:@"cancel"
7785 ] autorelease]];
7786 }
7787
7788 - (void) complete {
7789 @synchronized (self) {
7790 [self _reloadData];
7791
7792 if (confirm_ != nil) {
7793 [confirm_ release];
7794 confirm_ = nil;
7795 }
7796 }
7797 }
7798
7799 - (void) confirm {
7800 [overlay_ removeFromSuperview];
7801 reload_ = true;
7802
7803 [progress_
7804 detachNewThreadSelector:@selector(perform)
7805 toTarget:database_
7806 withObject:nil
7807 title:UCLocalize("RUNNING")
7808 ];
7809 }
7810
7811 - (void) progressViewIsComplete:(ProgressView *)progress {
7812 if (confirm_ != nil) {
7813 [underlay_ addSubview:overlay_];
7814 [confirm_ popFromSuperviewAnimated:NO];
7815 }
7816
7817 [self complete];
7818 }
7819
7820 - (void) setPage:(RVPage *)page {
7821 [page resetViewAnimated:NO];
7822 [page setDelegate:self];
7823 [book_ setPage:page];
7824 }
7825
7826 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7827 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7828 [browser loadURL:url];
7829 return browser;
7830 }
7831
7832 - (SectionsView *) sectionsView {
7833 if (sections_ == nil)
7834 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7835 return sections_;
7836 }
7837
7838 - (void) buttonBarItemTapped:(id)sender {
7839 unsigned tag = [sender tag];
7840 if (tag == tag_) {
7841 [book_ resetViewAnimated:YES];
7842 return;
7843 } else if (tag_ == 2)
7844 [[self sectionsView] resetView];
7845
7846 switch (tag) {
7847 case 1: _setHomePage(self); break;
7848
7849 case 2: [self setPage:[self sectionsView]]; break;
7850 case 3: [self setPage:changes_]; break;
7851 case 4: [self setPage:manage_]; break;
7852 case 5: [self setPage:search_]; break;
7853
7854 _nodefault
7855 }
7856
7857 tag_ = tag;
7858 }
7859
7860 - (void) askForSettings {
7861 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7862
7863 CYActionSheet *role([[[CYActionSheet alloc]
7864 initWithTitle:UCLocalize("WHO_ARE_YOU")
7865 buttons:[NSArray arrayWithObjects:
7866 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7867 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7868 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7869 nil]
7870 defaultButtonIndex:-1
7871 ] autorelease]);
7872
7873 [role setBodyText:UCLocalize("ROLE_EX")];
7874
7875 int button([role yieldToPopupAlertAnimated:YES]);
7876
7877 switch (button) {
7878 case 1: Role_ = @"User"; break;
7879 case 2: Role_ = @"Hacker"; break;
7880 case 3: Role_ = @"Developer"; break;
7881
7882 _nodefault
7883 }
7884
7885 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7886 Role_, @"Role",
7887 nil];
7888
7889 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7890
7891 Changed_ = true;
7892
7893 [role dismiss];
7894 }
7895
7896 - (void) setPackageView:(PackageView *)view {
7897 WebThreadLock();
7898 [view setPackage:nil];
7899 #if RecyclePackageViews
7900 if ([details_ count] < 3)
7901 [details_ addObject:view];
7902 #endif
7903 WebThreadUnlock();
7904 }
7905
7906 - (PackageView *) _packageView {
7907 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7908 }
7909
7910 - (PackageView *) packageView {
7911 #if RecyclePackageViews
7912 PackageView *view;
7913 size_t count([details_ count]);
7914
7915 if (count == 0) {
7916 view = [self _packageView];
7917 renew:
7918 [details_ addObject:[self _packageView]];
7919 } else {
7920 view = [[[details_ lastObject] retain] autorelease];
7921 [details_ removeLastObject];
7922 if (count == 1)
7923 goto renew;
7924 }
7925
7926 return view;
7927 #else
7928 return [self _packageView];
7929 #endif
7930 }
7931
7932 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7933 NSString *context([sheet context]);
7934
7935 if ([context isEqualToString:@"missing"])
7936 [sheet dismiss];
7937 else if ([context isEqualToString:@"cancel"]) {
7938 bool clear;
7939
7940 switch (button) {
7941 case 1:
7942 clear = false;
7943 break;
7944
7945 case 2:
7946 clear = true;
7947 break;
7948
7949 _nodefault
7950 }
7951
7952 [sheet dismiss];
7953
7954 @synchronized (self) {
7955 if (clear)
7956 [self _reloadData];
7957 else {
7958 Queuing_ = true;
7959 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7960 [book_ reloadData];
7961 }
7962
7963 if (confirm_ != nil) {
7964 [confirm_ release];
7965 confirm_ = nil;
7966 }
7967 }
7968 } else if ([context isEqualToString:@"fixhalf"]) {
7969 switch (button) {
7970 case 1:
7971 @synchronized (self) {
7972 for (Package *broken in broken_) {
7973 [broken remove];
7974
7975 NSString *id = [broken id];
7976 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7977 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7978 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7979 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7980 }
7981
7982 [self resolve];
7983 [self perform];
7984 }
7985 break;
7986
7987 case 2:
7988 [broken_ removeAllObjects];
7989 [self _loaded];
7990 break;
7991
7992 _nodefault
7993 }
7994
7995 [sheet dismiss];
7996 } else if ([context isEqualToString:@"upgrade"]) {
7997 switch (button) {
7998 case 1:
7999 @synchronized (self) {
8000 for (Package *essential in essential_)
8001 [essential install];
8002
8003 [self resolve];
8004 [self perform];
8005 }
8006 break;
8007
8008 case 2:
8009 [self distUpgrade];
8010 break;
8011
8012 case 3:
8013 Ignored_ = YES;
8014 break;
8015
8016 _nodefault
8017 }
8018
8019 [sheet dismiss];
8020 }
8021 }
8022
8023 - (void) system:(NSString *)command { _pooled
8024 system([command UTF8String]);
8025 }
8026
8027 - (void) applicationWillSuspend {
8028 [database_ clean];
8029 [super applicationWillSuspend];
8030 }
8031
8032 - (void) applicationSuspend:(__GSEvent *)event {
8033 if (hud_ == nil && ![progress_ isRunning])
8034 [super applicationSuspend:event];
8035 }
8036
8037 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8038 if (hud_ == nil)
8039 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8040 }
8041
8042 - (void) _setSuspended:(BOOL)value {
8043 if (hud_ == nil)
8044 [super _setSuspended:value];
8045 }
8046
8047 - (UIProgressHUD *) addProgressHUD {
8048 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8049 [window_ setUserInteractionEnabled:NO];
8050 [hud show:YES];
8051 [progress_ addSubview:hud];
8052 return hud;
8053 }
8054
8055 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8056 [hud show:NO];
8057 [hud removeFromSuperview];
8058 [window_ setUserInteractionEnabled:YES];
8059 }
8060
8061 - (RVPage *) pageForPackage:(NSString *)name {
8062 if (Package *package = [database_ packageWithName:name]) {
8063 PackageView *view([self packageView]);
8064 [view setPackage:package];
8065 return view;
8066 } else {
8067 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8068 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8069 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8070 }
8071 }
8072
8073 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8074 if (tag != NULL)
8075 tag = 0;
8076
8077 NSString *href([url absoluteString]);
8078 if ([href hasPrefix:@"apptapp://package/"])
8079 return [self pageForPackage:[href substringFromIndex:18]];
8080
8081 NSString *scheme([[url scheme] lowercaseString]);
8082 if (![scheme isEqualToString:@"cydia"])
8083 return nil;
8084 NSString *path([url absoluteString]);
8085 if ([path length] < 8)
8086 return nil;
8087 path = [path substringFromIndex:8];
8088 if (![path hasPrefix:@"/"])
8089 path = [@"/" stringByAppendingString:path];
8090
8091 if ([path isEqualToString:@"/add-source"])
8092 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8093 else if ([path isEqualToString:@"/storage"])
8094 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8095 else if ([path isEqualToString:@"/sources"])
8096 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8097 else if ([path isEqualToString:@"/packages"])
8098 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8099 else if ([path hasPrefix:@"/url/"])
8100 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8101 else if ([path hasPrefix:@"/launch/"])
8102 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8103 else if ([path hasPrefix:@"/package-settings/"])
8104 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8105 else if ([path hasPrefix:@"/package-signature/"])
8106 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8107 else if ([path hasPrefix:@"/package/"])
8108 return [self pageForPackage:[path substringFromIndex:9]];
8109 else if ([path hasPrefix:@"/files/"]) {
8110 NSString *name = [path substringFromIndex:7];
8111
8112 if (Package *package = [database_ packageWithName:name]) {
8113 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8114 [files setPackage:package];
8115 return files;
8116 }
8117 }
8118
8119 return nil;
8120 }
8121
8122 - (void) applicationOpenURL:(NSURL *)url {
8123 [super applicationOpenURL:url];
8124 int tag;
8125 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8126 [self setPage:page];
8127 [toolbar_ showSelectionForButton:tag];
8128 tag_ = tag;
8129 }
8130 }
8131
8132 - (void) applicationDidFinishLaunching:(id)unused {
8133 [BrowserView _initialize];
8134
8135 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8136
8137 Font12_ = [[UIFont systemFontOfSize:12] retain];
8138 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8139 Font14_ = [[UIFont systemFontOfSize:14] retain];
8140 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8141 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8142
8143 tag_ = 1;
8144
8145 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8146 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8147
8148 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8149 [window_ orderFront:self];
8150 [window_ makeKey:self];
8151 [window_ setHidden:NO];
8152
8153 database_ = [Database sharedInstance];
8154
8155 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8156 [database_ setDelegate:progress_];
8157 [window_ setContentView:progress_];
8158
8159 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8160 [progress_ setContentView:underlay_];
8161
8162 [progress_ resetView];
8163
8164 if (
8165 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8166 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8167 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8168 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8169 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8170 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8171 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8172 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8173 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8174 false
8175 ) {
8176 [self setIdleTimerDisabled:YES];
8177
8178 hud_ = [self addProgressHUD];
8179 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8180 [self setStatusBarShowsProgress:YES];
8181
8182 [self yieldToSelector:@selector(system) withObject:@"http://www.hipsterwave.com/tag/cydia/"];
8183
8184 [self setStatusBarShowsProgress:NO];
8185 [self removeProgressHUD:hud_];
8186 hud_ = nil;
8187
8188 if (ExecFork() == 0) {
8189 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8190 perror("launchctl stop");
8191 }
8192
8193 return;
8194 }
8195
8196 if (Role_ == nil)
8197 [self askForSettings];
8198
8199 _trace();
8200 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8201
8202 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8203 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8204 0, 0, screenrect.size.width, screenrect.size.height - 48
8205 ) database:database_];
8206
8207 [book_ setDelegate:self];
8208
8209 [overlay_ addSubview:book_];
8210
8211 NSArray *buttonitems = [NSArray arrayWithObjects:
8212 [NSDictionary dictionaryWithObjectsAndKeys:
8213 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8214 @"home-up.png", kUIButtonBarButtonInfo,
8215 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8216 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8217 self, kUIButtonBarButtonTarget,
8218 @"Cydia", kUIButtonBarButtonTitle,
8219 @"0", kUIButtonBarButtonType,
8220 nil],
8221
8222 [NSDictionary dictionaryWithObjectsAndKeys:
8223 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8224 @"install-up.png", kUIButtonBarButtonInfo,
8225 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8226 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8227 self, kUIButtonBarButtonTarget,
8228 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8229 @"0", kUIButtonBarButtonType,
8230 nil],
8231
8232 [NSDictionary dictionaryWithObjectsAndKeys:
8233 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8234 @"changes-up.png", kUIButtonBarButtonInfo,
8235 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8236 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8237 self, kUIButtonBarButtonTarget,
8238 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8239 @"0", kUIButtonBarButtonType,
8240 nil],
8241
8242 [NSDictionary dictionaryWithObjectsAndKeys:
8243 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8244 @"manage-up.png", kUIButtonBarButtonInfo,
8245 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8246 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8247 self, kUIButtonBarButtonTarget,
8248 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8249 @"0", kUIButtonBarButtonType,
8250 nil],
8251
8252 [NSDictionary dictionaryWithObjectsAndKeys:
8253 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8254 @"search-up.png", kUIButtonBarButtonInfo,
8255 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8256 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8257 self, kUIButtonBarButtonTarget,
8258 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8259 @"0", kUIButtonBarButtonType,
8260 nil],
8261 nil];
8262
8263 toolbar_ = [[UIToolbar alloc]
8264 initInView:overlay_
8265 withFrame:CGRectMake(
8266 0, screenrect.size.height - ButtonBarHeight_,
8267 screenrect.size.width, ButtonBarHeight_
8268 )
8269 withItemList:buttonitems
8270 ];
8271
8272 [toolbar_ setDelegate:self];
8273 [toolbar_ setBarStyle:1];
8274 [toolbar_ setButtonBarTrackingMode:2];
8275
8276 int buttons[5] = {1, 2, 3, 4, 5};
8277 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8278 [toolbar_ showButtonGroup:0 withDuration:0];
8279
8280 for (int i = 0; i != 5; ++i)
8281 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8282 i * 64 + 2, 1, 60, ButtonBarHeight_
8283 )];
8284
8285 [toolbar_ showSelectionForButton:1];
8286 [overlay_ addSubview:toolbar_];
8287
8288 [UIKeyboard initImplementationNow];
8289 CGSize keysize = [UIKeyboard defaultSize];
8290 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8291 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8292 [overlay_ addSubview:keyboard_];
8293
8294 [underlay_ addSubview:overlay_];
8295
8296 [self reloadData];
8297
8298 [self sectionsView];
8299 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8300 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8301
8302 manage_ = (ManageView *) [[self
8303 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8304 withClass:[ManageView class]
8305 ] retain];
8306
8307 #if RecyclePackageViews
8308 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8309 [details_ addObject:[self _packageView]];
8310 [details_ addObject:[self _packageView]];
8311 #endif
8312
8313 PrintTimes();
8314
8315 _setHomePage(self);
8316 }
8317
8318 - (void) showKeyboard:(BOOL)show {
8319 CGSize keysize([UIKeyboard defaultSize]);
8320 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8321 CGRect keyup(keydown);
8322 keyup.origin.y -= keysize.height;
8323
8324 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8325 [animation setSignificantRectFields:2];
8326
8327 if (show) {
8328 [animation setStartFrame:keydown];
8329 [animation setEndFrame:keyup];
8330 [keyboard_ activate];
8331 } else {
8332 [animation setStartFrame:keyup];
8333 [animation setEndFrame:keydown];
8334 [keyboard_ deactivate];
8335 }
8336
8337 [[UIAnimator sharedAnimator]
8338 addAnimations:[NSArray arrayWithObjects:animation, nil]
8339 withDuration:KeyboardTime_
8340 start:YES
8341 ];
8342 }
8343
8344 - (void) slideUp:(UIActionSheet *)alert {
8345 [alert presentSheetInView:overlay_];
8346 }
8347
8348 @end
8349
8350 /*IMP alloc_;
8351 id Alloc_(id self, SEL selector) {
8352 id object = alloc_(self, selector);
8353 lprintf("[%s]A-%p\n", self->isa->name, object);
8354 return object;
8355 }*/
8356
8357 /*IMP dealloc_;
8358 id Dealloc_(id self, SEL selector) {
8359 id object = dealloc_(self, selector);
8360 lprintf("[%s]D-%p\n", self->isa->name, object);
8361 return object;
8362 }*/
8363
8364 Class $WebDefaultUIKitDelegate;
8365
8366 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8367 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8368 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8369 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8370 }
8371
8372 int main(int argc, char *argv[]) { _pooled
8373 _trace();
8374
8375 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8376
8377 /* Library Hacks {{{ */
8378 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8379
8380 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8381 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8382 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8383 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8384 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8385 }
8386 /* }}} */
8387 /* Set Locale {{{ */
8388 Locale_ = CFLocaleCopyCurrent();
8389 Languages_ = [NSLocale preferredLanguages];
8390 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8391 //NSLog(@"%@", [Languages_ description]);
8392 const char *lang;
8393 if (Languages_ == nil || [Languages_ count] == 0)
8394 lang = NULL;
8395 else
8396 lang = [[Languages_ objectAtIndex:0] UTF8String];
8397 setenv("LANG", lang, true);
8398 //std::setlocale(LC_ALL, lang);
8399 NSLog(@"Setting Language: %s", lang);
8400 /* }}} */
8401
8402 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8403
8404 /* Parse Arguments {{{ */
8405 bool substrate(false);
8406
8407 if (argc != 0) {
8408 char **args(argv);
8409 int arge(1);
8410
8411 for (int argi(1); argi != argc; ++argi)
8412 if (strcmp(argv[argi], "--") == 0) {
8413 arge = argi;
8414 argv[argi] = argv[0];
8415 argv += argi;
8416 argc -= argi;
8417 break;
8418 }
8419
8420 for (int argi(1); argi != arge; ++argi)
8421 if (strcmp(args[argi], "--substrate") == 0)
8422 substrate = true;
8423 else
8424 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8425 }
8426 /* }}} */
8427
8428 App_ = [[NSBundle mainBundle] bundlePath];
8429 Home_ = NSHomeDirectory();
8430 Advanced_ = YES;
8431
8432 setuid(0);
8433 setgid(0);
8434
8435 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8436 alloc_ = alloc->method_imp;
8437 alloc->method_imp = (IMP) &Alloc_;*/
8438
8439 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8440 dealloc_ = dealloc->method_imp;
8441 dealloc->method_imp = (IMP) &Dealloc_;*/
8442
8443 /* System Information {{{ */
8444 size_t size;
8445
8446 int maxproc;
8447 size = sizeof(maxproc);
8448 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8449 perror("sysctlbyname(\"kern.maxproc\", ?)");
8450 else if (maxproc < 64) {
8451 maxproc = 64;
8452 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8453 perror("sysctlbyname(\"kern.maxproc\", #)");
8454 }
8455
8456 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8457 char *osversion = new char[size];
8458 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8459 perror("sysctlbyname(\"kern.osversion\", ?)");
8460 else
8461 System_ = [NSString stringWithUTF8String:osversion];
8462
8463 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8464 char *machine = new char[size];
8465 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8466 perror("sysctlbyname(\"hw.machine\", ?)");
8467 else
8468 Machine_ = machine;
8469
8470 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8471 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8472 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8473 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8474 CFRelease(serial);
8475 }
8476
8477 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8478 NSData *data((NSData *) ecid);
8479 size_t length([data length]);
8480 uint8_t bytes[length];
8481 [data getBytes:bytes];
8482 char string[length * 2 + 1];
8483 for (size_t i(0); i != length; ++i)
8484 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8485 ChipID_ = [NSString stringWithUTF8String:string];
8486 CFRelease(ecid);
8487 }
8488
8489 IOObjectRelease(service);
8490 }
8491 }
8492
8493 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8494
8495 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8496 Build_ = [system objectForKey:@"ProductBuildVersion"];
8497 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8498 Product_ = [info objectForKey:@"SafariProductVersion"];
8499 Safari_ = [info objectForKey:@"CFBundleVersion"];
8500 }
8501 /* }}} */
8502 /* Load Database {{{ */
8503 _trace();
8504 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8505 _trace();
8506 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8507 _trace();
8508
8509 if (Metadata_ == NULL)
8510 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8511 else {
8512 Settings_ = [Metadata_ objectForKey:@"Settings"];
8513
8514 Packages_ = [Metadata_ objectForKey:@"Packages"];
8515 Sections_ = [Metadata_ objectForKey:@"Sections"];
8516 Sources_ = [Metadata_ objectForKey:@"Sources"];
8517 }
8518
8519 if (Settings_ != nil)
8520 Role_ = [Settings_ objectForKey:@"Role"];
8521
8522 if (Packages_ == nil) {
8523 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8524 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8525 }
8526
8527 if (Sections_ == nil) {
8528 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8529 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8530 }
8531
8532 if (Sources_ == nil) {
8533 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8534 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8535 }
8536 /* }}} */
8537
8538 #if RecycleWebViews
8539 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8540 #endif
8541
8542 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8543
8544 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8545 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8546 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8547 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8548
8549 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8550 unlink("/tmp/.cydia.fw");
8551 goto firmware;
8552 } else if (access("/User", F_OK) != 0) {
8553 firmware:
8554 _trace();
8555 system("/usr/libexec/cydia/firmware.sh");
8556 _trace();
8557 }
8558
8559 _assert([[NSFileManager defaultManager]
8560 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8561 withIntermediateDirectories:YES
8562 attributes:nil
8563 error:NULL
8564 ]);
8565
8566 if (access("/tmp/cydia.chk", F_OK) == 0) {
8567 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8568 _assert(errno == ENOENT);
8569 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8570 _assert(errno == ENOENT);
8571 }
8572
8573 /* APT Initialization {{{ */
8574 _assert(pkgInitConfig(*_config));
8575 _assert(pkgInitSystem(*_config, _system));
8576
8577 if (lang != NULL)
8578 _config->Set("APT::Acquire::Translation", lang);
8579 _config->Set("Acquire::http::Timeout", 15);
8580 _config->Set("Acquire::http::MaxParallel", 3);
8581 /* }}} */
8582 /* Color Choices {{{ */
8583 space_ = CGColorSpaceCreateDeviceRGB();
8584
8585 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8586 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8587 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8588 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8589 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8590 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8591 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8592 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8593 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8594
8595 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8596 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8597 /* }}}*/
8598 /* UIKit Configuration {{{ */
8599 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8600 if ($GSFontSetUseLegacyFontMetrics != NULL)
8601 $GSFontSetUseLegacyFontMetrics(YES);
8602
8603 UIKeyboardDisableAutomaticAppearance();
8604 /* }}} */
8605
8606 Colon_ = UCLocalize("COLON_DELIMITED");
8607 Error_ = UCLocalize("ERROR");
8608 Warning_ = UCLocalize("WARNING");
8609
8610 _trace();
8611 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8612
8613 CGColorSpaceRelease(space_);
8614 CFRelease(Locale_);
8615
8616 return value;
8617 }