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