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