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