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