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