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