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