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