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