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