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