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