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