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