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