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