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