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