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