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