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