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