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