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