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