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