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