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