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