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