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