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