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