]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Expose sysctl read access to JavaScript.
[cydia.git] / MobileCydia.mm
1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
42
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
46
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
49
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
52
53 #if 0
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
57 #endif
58
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
61
62 #include <SystemConfiguration/SystemConfiguration.h>
63
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
66
67 #include <IOKit/IOKitLib.h>
68
69 #include <WebCore/WebCoreThread.h>
70
71 #include <algorithm>
72 #include <iomanip>
73 #include <sstream>
74 #include <string>
75
76 #include <ext/stdio_filebuf.h>
77
78 #undef ABS
79
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
97
98 #include <apr-1/apr_pools.h>
99
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
106
107 #include <fcntl.h>
108 #include <notify.h>
109 #include <dlfcn.h>
110
111 extern "C" {
112 #include <mach-o/nlist.h>
113 }
114
115 #include <cstdio>
116 #include <cstdlib>
117 #include <cstring>
118
119 #include <errno.h>
120 #include <pcre.h>
121
122 #include <Cytore.hpp>
123
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
126
127 #include "substrate.h"
128 /* }}} */
129
130 /* Profiler {{{ */
131 struct timeval _ltv;
132 bool _itv;
133
134 #define _timestamp ({ \
135 struct timeval tv; \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
138 })
139
140 typedef std::vector<class ProfileTime *> TimeList;
141 TimeList times_;
142
143 class ProfileTime {
144 private:
145 const char *name_;
146 uint64_t total_;
147 uint64_t count_;
148
149 public:
150 ProfileTime(const char *name) :
151 name_(name),
152 total_(0)
153 {
154 times_.push_back(this);
155 }
156
157 void AddTime(uint64_t time) {
158 total_ += time;
159 ++count_;
160 }
161
162 void Print() {
163 if (total_ != 0)
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
165 total_ = 0;
166 count_ = 0;
167 }
168 };
169
170 class ProfileTimer {
171 private:
172 ProfileTime &time_;
173 uint64_t start_;
174
175 public:
176 ProfileTimer(ProfileTime &time) :
177 time_(time),
178 start_(_timestamp)
179 {
180 }
181
182 ~ProfileTimer() {
183 time_.AddTime(_timestamp - start_);
184 }
185 };
186
187 void PrintTimes() {
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
189 (*i)->Print();
190 std::cerr << "========" << std::endl;
191 }
192
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
196
197 #define _end }
198 /* }}} */
199
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
201
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
204 do
205 #define CYPoolEnd() \
206 while (false); \
207 [_pool release];
208
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
211
212 union SplitHash {
213 uint32_t u32;
214 uint16_t u16[2];
215 };
216 // }}}
217
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
219
220 static _finline NSString *CydiaURL(NSString *path) {
221 char page[25];
222 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
223 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
224 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
225 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
226 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
227 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
228 }
229
230 static _finline void UpdateExternalStatus(uint64_t newStatus) {
231 int notify_token;
232 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
233 notify_set_state(notify_token, newStatus);
234 notify_cancel(notify_token);
235 }
236 notify_post("com.saurik.Cydia.status");
237 }
238
239 /* [NSObject yieldToSelector:(withObject:)] {{{*/
240 @interface NSObject (Cydia)
241 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
242 - (id) yieldToSelector:(SEL)selector;
243 @end
244
245 @implementation NSObject (Cydia)
246
247 - (void) doNothing {
248 }
249
250 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
251 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
252 id object([[context objectAtIndex:1] nonretainedObjectValue]);
253 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
254
255 /* XXX: deal with exceptions */
256 id value([self performSelector:selector withObject:object]);
257
258 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
259 [context removeAllObjects];
260 if ([signature methodReturnLength] != 0 && value != nil)
261 [context addObject:value];
262
263 stopped = true;
264
265 [self
266 performSelectorOnMainThread:@selector(doNothing)
267 withObject:nil
268 waitUntilDone:NO
269 ];
270 }
271
272 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
273 volatile bool stopped(false);
274
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
279 nil]);
280
281 NSThread *thread([[[NSThread alloc]
282 initWithTarget:self
283 selector:@selector(_yieldToContext:)
284 object:context
285 ] autorelease]);
286
287 [thread start];
288
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
291
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
293
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
295 }
296
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
299 }
300
301 @end
302 /* }}} */
303
304 /* Cydia Alert View {{{ */
305 @interface CYAlertView : UIAlertView {
306 unsigned button_;
307 }
308
309 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
310
311 @end
312
313 @implementation CYAlertView
314
315 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
316 if ((self = [super init]) != nil) {
317 [self setTitle:title];
318 [self setDelegate:self];
319 for (NSString *button in buttons) [self addButtonWithTitle:button];
320 [self setCancelButtonIndex:index];
321 } return self;
322 }
323
324 - (void) _updateFrameForDisplay {
325 [super _updateFrameForDisplay];
326 if ([self cancelButtonIndex] == -1) {
327 NSArray *buttons = [self buttons];
328 if ([buttons count]) {
329 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
330 for (UIThreePartButton *button in buttons)
331 [button setBackground:background forState:0];
332 }
333 }
334 }
335
336 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
337 button_ = buttonIndex + 1;
338 }
339
340 - (void) dismiss {
341 [self dismissWithClickedButtonIndex:-1 animated:YES];
342 }
343
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
345 [self setRunsModal:YES];
346 button_ = 0;
347 [self show];
348 return button_;
349 }
350
351 @end
352 /* }}} */
353
354 /* NSForcedOrderingSearch doesn't work on the iPhone */
355 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
356 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
357 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
358
359 #define lprintf(args...) fprintf(stderr, args)
360
361 #define ForRelease 1
362 #define TraceLogging (1 && !ForRelease)
363 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
364 #define ProfileTimes (0 && !ForRelease)
365 #define ForSaurik (0 && !ForRelease)
366 #define LogBrowser (0 && !ForRelease)
367 #define TrackResize (0 && !ForRelease)
368 #define ManualRefresh (1 && !ForRelease)
369 #define ShowInternals (0 && !ForRelease)
370 #define AlwaysReload (0 && !ForRelease)
371 #define TryIndexedCollation (0 && !ForRelease)
372
373 #if !TraceLogging
374 #undef _trace
375 #define _trace(args...)
376 #endif
377
378 #if !ProfileTimes
379 #undef _profile
380 #define _profile(name) {
381 #undef _end
382 #define _end }
383 #define PrintTimes() do {} while (false)
384 #endif
385
386 /* Radix Sort {{{ */
387 typedef uint32_t (*SKRadixFunction)(id, void *);
388
389 @interface NSMutableArray (Radix)
390 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
391 @end
392
393 struct RadixItem_ {
394 size_t index;
395 uint32_t key;
396 };
397
398 @implementation NSMutableArray (Radix)
399
400 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
401 size_t count([self count]);
402 struct RadixItem_ *swap(new RadixItem_[count * 2]);
403
404 for (size_t i(0); i != count; ++i) {
405 RadixItem_ &item(swap[i]);
406 item.index = i;
407
408 id object([self objectAtIndex:i]);
409 item.key = function(object, argument);
410 }
411
412 struct RadixItem_ *lhs(swap), *rhs(swap + count);
413
414 static const size_t width = 32;
415 static const size_t bits = 11;
416 static const size_t slots = 1 << bits;
417 static const size_t passes = (width + (bits - 1)) / bits;
418
419 size_t *hist(new size_t[slots]);
420
421 for (size_t pass(0); pass != passes; ++pass) {
422 memset(hist, 0, sizeof(size_t) * slots);
423
424 for (size_t i(0); i != count; ++i) {
425 uint32_t key(lhs[i].key);
426 key >>= pass * bits;
427 key &= _not(uint32_t) >> width - bits;
428 ++hist[key];
429 }
430
431 size_t offset(0);
432 for (size_t i(0); i != slots; ++i) {
433 size_t local(offset);
434 offset += hist[i];
435 hist[i] = local;
436 }
437
438 for (size_t i(0); i != count; ++i) {
439 uint32_t key(lhs[i].key);
440 key >>= pass * bits;
441 key &= _not(uint32_t) >> width - bits;
442 rhs[hist[key]++] = lhs[i];
443 }
444
445 RadixItem_ *tmp(lhs);
446 lhs = rhs;
447 rhs = tmp;
448 }
449
450 delete [] hist;
451
452 const void **values(new const void *[count]);
453 for (size_t i(0); i != count; ++i)
454 values[i] = [self objectAtIndex:lhs[i].index];
455 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
456 delete [] values;
457
458 delete [] swap;
459 }
460
461 @end
462 /* }}} */
463 /* Insertion Sort {{{ */
464
465 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
466 const char *ptr = (const char *)list;
467 while (0 < count) {
468 CFIndex half = count / 2;
469 const char *probe = ptr + elementSize * half;
470 CFComparisonResult cr = comparator(element, probe, context);
471 if (0 == cr) return (probe - (const char *)list) / elementSize;
472 ptr = (cr < 0) ? ptr : probe + elementSize;
473 count = (cr < 0) ? half : (half + (count & 1) - 1);
474 }
475 return (ptr - (const char *)list) / elementSize;
476 }
477
478 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
479 const char *ptr = (const char *)list;
480 while (0 < count) {
481 CFIndex half = count / 2;
482 const char *probe = ptr + elementSize * half;
483 CFComparisonResult cr = comparator(element, probe, context);
484 if (0 == cr) return (probe - (const char *)list) / elementSize;
485 ptr = (cr < 0) ? ptr : probe + elementSize;
486 count = (cr < 0) ? half : (half + (count & 1) - 1);
487 }
488 return (ptr - (const char *)list) / elementSize;
489 }
490
491 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
492 if (range.length == 0)
493 return;
494 const void **values(new const void *[range.length]);
495 CFArrayGetValues(array, range, values);
496
497 #if HistogramInsertionSort > 0
498 uint32_t total(0), *offsets(new uint32_t[range.length]);
499 #endif
500
501 for (CFIndex index(1); index != range.length; ++index) {
502 const void *value(values[index]);
503 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
504 CFIndex correct(index);
505 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
506 #if HistogramInsertionSort > 1
507 NSLog(@"%@ < %@", value, values[correct - 1]);
508 #endif
509 if (--correct == 0)
510 break;
511 }
512 if (correct != index) {
513 size_t offset(index - correct);
514 #if HistogramInsertionSort
515 total += offset;
516 ++offsets[offset];
517 if (offset > 10)
518 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
519 #endif
520 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
521 values[correct] = value;
522 }
523 }
524
525 CFArrayReplaceValues(array, range, values, range.length);
526 delete [] values;
527
528 #if HistogramInsertionSort > 0
529 for (CFIndex index(0); index != range.length; ++index)
530 if (offsets[index] != 0)
531 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
532 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
533 delete [] offsets;
534 #endif
535 }
536
537 /* }}} */
538
539 /* Apple Bug Fixes {{{ */
540 @implementation UIWebDocumentView (Cydia)
541
542 - (void) _setScrollerOffset:(CGPoint)offset {
543 UIScroller *scroller([self _scroller]);
544
545 CGSize size([scroller contentSize]);
546 CGSize bounds([scroller bounds].size);
547
548 CGPoint max;
549 max.x = size.width - bounds.width;
550 max.y = size.height - bounds.height;
551
552 // wtf Apple?!
553 if (max.x < 0)
554 max.x = 0;
555 if (max.y < 0)
556 max.y = 0;
557
558 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
559 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
560
561 [scroller setOffset:offset];
562 }
563
564 @end
565 /* }}} */
566
567 @implementation WebScriptObject (NSFastEnumeration)
568
569 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
570 size_t length([self count] - state->state);
571 if (length <= 0)
572 return 0;
573 else if (length > count)
574 length = count;
575 for (size_t i(0); i != length; ++i)
576 objects[i] = [self objectAtIndex:state->state++];
577 state->itemsPtr = objects;
578 state->mutationsPtr = (unsigned long *) self;
579 return length;
580 }
581
582 @end
583
584 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
585 size_t length([self length] - state->state);
586 if (length <= 0)
587 return 0;
588 else if (length > count)
589 length = count;
590 for (size_t i(0); i != length; ++i)
591 objects[i] = [self item:state->state++];
592 state->itemsPtr = objects;
593 state->mutationsPtr = (unsigned long *) self;
594 return length;
595 }
596
597 /* Cydia NSString Additions {{{ */
598 @interface NSString (Cydia)
599 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
600 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
601 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
602 - (NSComparisonResult) compareByPath:(NSString *)other;
603 - (NSString *) stringByCachingURLWithCurrentCDN;
604 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
605 @end
606
607 @implementation NSString (Cydia)
608
609 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
610 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
611 }
612
613 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
614 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
615 memcpy(data, bytes, length);
616 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
617 }
618
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
620 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
621 }
622
623 - (NSComparisonResult) compareByPath:(NSString *)other {
624 NSString *prefix = [self commonPrefixWithString:other options:0];
625 size_t length = [prefix length];
626
627 NSRange lrange = NSMakeRange(length, [self length] - length);
628 NSRange rrange = NSMakeRange(length, [other length] - length);
629
630 lrange = [self rangeOfString:@"/" options:0 range:lrange];
631 rrange = [other rangeOfString:@"/" options:0 range:rrange];
632
633 NSComparisonResult value;
634
635 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
636 value = NSOrderedSame;
637 else if (lrange.location == NSNotFound)
638 value = NSOrderedAscending;
639 else if (rrange.location == NSNotFound)
640 value = NSOrderedDescending;
641 else
642 value = NSOrderedSame;
643
644 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
645 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
646 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
647 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
648
649 NSComparisonResult result = [lpath compare:rpath];
650 return result == NSOrderedSame ? value : result;
651 }
652
653 - (NSString *) stringByCachingURLWithCurrentCDN {
654 return [self
655 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
656 withString:@"://cache.cydia.saurik.com/"
657 ];
658 }
659
660 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
661 return [(id)CFURLCreateStringByAddingPercentEscapes(
662 kCFAllocatorDefault,
663 (CFStringRef) self,
664 NULL,
665 CFSTR(";/?:@&=+$,"),
666 kCFStringEncodingUTF8
667 ) autorelease];
668 }
669
670 @end
671 /* }}} */
672
673 /* C++ NSString Wrapper Cache {{{ */
674 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
675 return size == 0 ? NULL :
676 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
677 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
678 }
679
680 static _finline CFStringRef CYStringCreate(const char *data) {
681 return CYStringCreate(data, strlen(data));
682 }
683
684 class CYString {
685 private:
686 char *data_;
687 size_t size_;
688 CFStringRef cache_;
689
690 _finline void clear_() {
691 if (cache_ != NULL) {
692 CFRelease(cache_);
693 cache_ = NULL;
694 }
695 }
696
697 public:
698 _finline bool empty() const {
699 return size_ == 0;
700 }
701
702 _finline size_t size() const {
703 return size_;
704 }
705
706 _finline char *data() const {
707 return data_;
708 }
709
710 _finline void clear() {
711 size_ = 0;
712 clear_();
713 }
714
715 _finline CYString() :
716 data_(0),
717 size_(0),
718 cache_(NULL)
719 {
720 }
721
722 _finline ~CYString() {
723 clear_();
724 }
725
726 void operator =(const CYString &rhs) {
727 data_ = rhs.data_;
728 size_ = rhs.size_;
729
730 if (rhs.cache_ == nil)
731 cache_ = NULL;
732 else
733 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
734 }
735
736 void copy(apr_pool_t *pool) {
737 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
738 memcpy(temp, data_, size_);
739 temp[size_] = '\0';
740 data_ = temp;
741 }
742
743 void set(apr_pool_t *pool, const char *data, size_t size) {
744 if (size == 0)
745 clear();
746 else {
747 clear_();
748
749 data_ = const_cast<char *>(data);
750 size_ = size;
751
752 if (pool != NULL)
753 copy(pool);
754 }
755 }
756
757 _finline void set(apr_pool_t *pool, const char *data) {
758 set(pool, data, data == NULL ? 0 : strlen(data));
759 }
760
761 _finline void set(apr_pool_t *pool, const std::string &rhs) {
762 set(pool, rhs.data(), rhs.size());
763 }
764
765 bool operator ==(const CYString &rhs) const {
766 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
767 }
768
769 _finline operator CFStringRef() {
770 if (cache_ == NULL)
771 cache_ = CYStringCreate(data_, size_);
772 return cache_;
773 }
774
775 _finline operator id() {
776 return (NSString *) static_cast<CFStringRef>(*this);
777 }
778
779 _finline operator const char *() {
780 return reinterpret_cast<const char *>(data_);
781 }
782 };
783 /* }}} */
784 /* C++ NSString Algorithm Adapters {{{ */
785 extern "C" {
786 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
787 }
788
789 struct NSStringMapHash :
790 std::unary_function<NSString *, size_t>
791 {
792 _finline size_t operator ()(NSString *value) const {
793 return CFStringHashNSString((CFStringRef) value);
794 }
795 };
796
797 struct NSStringMapLess :
798 std::binary_function<NSString *, NSString *, bool>
799 {
800 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
801 return [lhs compare:rhs] == NSOrderedAscending;
802 }
803 };
804
805 struct NSStringMapEqual :
806 std::binary_function<NSString *, NSString *, bool>
807 {
808 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
809 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
810 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
811 //[lhs isEqualToString:rhs];
812 }
813 };
814 /* }}} */
815
816 /* Perl-Compatible RegEx {{{ */
817 class Pcre {
818 private:
819 pcre *code_;
820 pcre_extra *study_;
821 int capture_;
822 int *matches_;
823 const char *data_;
824
825 public:
826 Pcre(const char *regex) :
827 study_(NULL)
828 {
829 const char *error;
830 int offset;
831 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
832
833 if (code_ == NULL) {
834 lprintf("%d:%s\n", offset, error);
835 _assert(false);
836 }
837
838 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
839 matches_ = new int[(capture_ + 1) * 3];
840 }
841
842 ~Pcre() {
843 pcre_free(code_);
844 delete matches_;
845 }
846
847 NSString *operator [](size_t match) {
848 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
849 }
850
851 bool operator ()(NSString *data) {
852 // XXX: length is for characters, not for bytes
853 return operator ()([data UTF8String], [data length]);
854 }
855
856 bool operator ()(const char *data, size_t size) {
857 data_ = data;
858 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
859 }
860 };
861 /* }}} */
862 /* Mime Addresses {{{ */
863 @interface Address : NSObject {
864 NSString *name_;
865 NSString *address_;
866 }
867
868 - (NSString *) name;
869 - (NSString *) address;
870
871 - (void) setAddress:(NSString *)address;
872
873 + (Address *) addressWithString:(NSString *)string;
874 - (Address *) initWithString:(NSString *)string;
875
876 @end
877
878 @implementation Address
879
880 - (void) dealloc {
881 [name_ release];
882 if (address_ != nil)
883 [address_ release];
884 [super dealloc];
885 }
886
887 - (NSString *) name {
888 return name_;
889 }
890
891 - (NSString *) address {
892 return address_;
893 }
894
895 - (void) setAddress:(NSString *)address {
896 if (address_ != nil)
897 [address_ autorelease];
898 if (address == nil)
899 address_ = nil;
900 else
901 address_ = [address retain];
902 }
903
904 + (Address *) addressWithString:(NSString *)string {
905 return [[[Address alloc] initWithString:string] autorelease];
906 }
907
908 + (NSArray *) _attributeKeys {
909 return [NSArray arrayWithObjects:
910 @"address",
911 @"name",
912 nil];
913 }
914
915 - (NSArray *) attributeKeys {
916 return [[self class] _attributeKeys];
917 }
918
919 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
920 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
921 }
922
923 - (Address *) initWithString:(NSString *)string {
924 if ((self = [super init]) != nil) {
925 const char *data = [string UTF8String];
926 size_t size = [string length];
927
928 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
929
930 if (address_r(data, size)) {
931 name_ = [address_r[1] retain];
932 address_ = [address_r[2] retain];
933 } else {
934 name_ = [string retain];
935 address_ = nil;
936 }
937 } return self;
938 }
939
940 @end
941 /* }}} */
942 /* CoreGraphics Primitives {{{ */
943 class CYColor {
944 private:
945 CGColorRef color_;
946
947 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
948 CGFloat color[] = {red, green, blue, alpha};
949 return CGColorCreate(space, color);
950 }
951
952 public:
953 CYColor() :
954 color_(NULL)
955 {
956 }
957
958 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
959 color_(Create_(space, red, green, blue, alpha))
960 {
961 Set(space, red, green, blue, alpha);
962 }
963
964 void Clear() {
965 if (color_ != NULL)
966 CGColorRelease(color_);
967 }
968
969 ~CYColor() {
970 Clear();
971 }
972
973 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
974 Clear();
975 color_ = Create_(space, red, green, blue, alpha);
976 }
977
978 operator CGColorRef() {
979 return color_;
980 }
981 };
982 /* }}} */
983
984 /* Random Global Variables {{{ */
985 static const int PulseInterval_ = 50000;
986
987 static const NSString *UI_;
988
989 static int Finish_;
990 static NSArray *Finishes_;
991
992 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
993 #define NotifyConfig_ "/etc/notify.conf"
994
995 static bool Queuing_;
996
997 static CYColor Blue_;
998 static CYColor Blueish_;
999 static CYColor Black_;
1000 static CYColor Off_;
1001 static CYColor White_;
1002 static CYColor Gray_;
1003 static CYColor Green_;
1004 static CYColor Purple_;
1005 static CYColor Purplish_;
1006
1007 static UIColor *InstallingColor_;
1008 static UIColor *RemovingColor_;
1009
1010 static NSString *App_;
1011 static NSString *Home_;
1012
1013 static BOOL Advanced_;
1014 static BOOL Ignored_;
1015
1016 static UIFont *Font12_;
1017 static UIFont *Font12Bold_;
1018 static UIFont *Font14_;
1019 static UIFont *Font18Bold_;
1020 static UIFont *Font22Bold_;
1021
1022 static const char *Machine_ = NULL;
1023 static NSString *System_ = nil;
1024 static NSString *SerialNumber_ = nil;
1025 static NSString *ChipID_ = nil;
1026 static NSString *Token_ = nil;
1027 static NSString *UniqueID_ = nil;
1028 static NSString *PLMN_ = nil;
1029 static NSString *Build_ = nil;
1030 static NSString *Product_ = nil;
1031 static NSString *Safari_ = nil;
1032
1033 static CFLocaleRef Locale_;
1034 static NSArray *Languages_;
1035 static CGColorSpaceRef space_;
1036
1037 static NSDictionary *SectionMap_;
1038 static NSMutableDictionary *Metadata_;
1039 static _transient NSMutableDictionary *Settings_;
1040 static _transient NSString *Role_;
1041 static _transient NSMutableDictionary *Packages_;
1042 static _transient NSMutableDictionary *Sections_;
1043 static _transient NSMutableDictionary *Sources_;
1044 static bool Changed_;
1045 static time_t now_;
1046
1047 bool IsWildcat_;
1048 static CGFloat ScreenScale_;
1049 /* }}} */
1050
1051 /* Display Helpers {{{ */
1052 inline float Interpolate(float begin, float end, float fraction) {
1053 return (end - begin) * fraction + begin;
1054 }
1055
1056 static _finline const char *StripVersion_(const char *version) {
1057 const char *colon(strchr(version, ':'));
1058 return colon == NULL ? version : colon + 1;
1059 }
1060
1061 NSString *LocalizeSection(NSString *section) {
1062 static Pcre title_r("^(.*?) \\((.*)\\)$");
1063 if (title_r(section)) {
1064 NSString *parent(title_r[1]);
1065 NSString *child(title_r[2]);
1066
1067 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1068 LocalizeSection(parent),
1069 LocalizeSection(child)
1070 ];
1071 }
1072
1073 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1074 }
1075
1076 NSString *Simplify(NSString *title) {
1077 const char *data = [title UTF8String];
1078 size_t size = [title length];
1079
1080 static Pcre square_r("^\\[(.*)\\]$");
1081 if (square_r(data, size))
1082 return Simplify(square_r[1]);
1083
1084 static Pcre paren_r("^\\((.*)\\)$");
1085 if (paren_r(data, size))
1086 return Simplify(paren_r[1]);
1087
1088 static Pcre title_r("^(.*?) \\((.*)\\)$");
1089 if (title_r(data, size))
1090 return Simplify(title_r[1]);
1091
1092 return title;
1093 }
1094 /* }}} */
1095
1096 NSString *GetLastUpdate() {
1097 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1098
1099 if (update == nil)
1100 return UCLocalize("NEVER_OR_UNKNOWN");
1101
1102 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1103 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1104
1105 CFRelease(formatter);
1106
1107 return [(NSString *) formatted autorelease];
1108 }
1109
1110 bool isSectionVisible(NSString *section) {
1111 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1112 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1113 return hidden == nil || ![hidden boolValue];
1114 }
1115
1116 @class Cydia;
1117
1118 /* Delegate Prototypes {{{ */
1119 @class Package;
1120 @class Source;
1121
1122 @interface NSObject (ProgressDelegate)
1123 @end
1124
1125 @protocol ProgressDelegate
1126 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1127 - (void) setProgressTitle:(NSString *)title;
1128 - (void) setProgressPercent:(float)percent;
1129 - (void) startProgress;
1130 - (void) addProgressOutput:(NSString *)output;
1131 - (bool) isCancelling:(size_t)received;
1132 @end
1133
1134 @protocol ConfigurationDelegate
1135 - (void) repairWithSelector:(SEL)selector;
1136 - (void) setConfigurationData:(NSString *)data;
1137 @end
1138
1139 @class CYPackageController;
1140
1141 @protocol CydiaDelegate
1142 - (void) retainNetworkActivityIndicator;
1143 - (void) releaseNetworkActivityIndicator;
1144 - (void) clearPackage:(Package *)package;
1145 - (void) installPackage:(Package *)package;
1146 - (void) installPackages:(NSArray *)packages;
1147 - (void) removePackage:(Package *)package;
1148 - (void) beginUpdate;
1149 - (BOOL) updating;
1150 - (void) distUpgrade;
1151 - (void) loadData;
1152 - (void) updateData;
1153 - (void) syncData;
1154 - (void) 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: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_ setProgressPercent:(Percent / 100)];*/
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_ setProgressPercent:1];
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_ setProgressPercent:(percent / 100)];
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(setSpecial:))
3937 return @"setSpecial";
3938 else if (selector == @selector(setToken:))
3939 return @"setToken";
3940 else if (selector == @selector(setViewportWidth:))
3941 return @"setViewportWidth";
3942 else if (selector == @selector(statfs:))
3943 return @"statfs";
3944 else if (selector == @selector(supports:))
3945 return @"supports";
3946 else
3947 return nil;
3948 }
3949
3950 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3951 return [self webScriptNameForSelector:selector] == nil;
3952 }
3953
3954 - (BOOL) supports:(NSString *)feature {
3955 return [feature isEqualToString:@"window.open"];
3956 }
3957
3958 - (NSNumber *) getKernelNumber:(NSString *)name {
3959 const char *string([name UTF8String]);
3960
3961 size_t size;
3962 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3963 return (id) [NSNull null];
3964
3965 if (size != sizeof(int))
3966 return (id) [NSNull null];
3967
3968 int value;
3969 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3970 return (id) [NSNull null];
3971
3972 return [NSNumber numberWithInt:value];
3973 }
3974
3975 - (NSString *) getKernelString:(NSString *)name {
3976 const char *string([name UTF8String]);
3977
3978 size_t size;
3979 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3980 return (id) [NSNull null];
3981
3982 char value[size + 1];
3983 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3984 return (id) [NSNull null];
3985
3986 // XXX: just in case you request something ludicrous
3987 value[size] = '\0';
3988
3989 return [NSString stringWithCString:value];
3990 }
3991
3992 - (void) addTrivialSource:(NSString *)href {
3993 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3994 }
3995
3996 - (void) refreshSources {
3997 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3998 }
3999
4000 - (NSArray *) getAllSources {
4001 return [[Database sharedInstance] sources];
4002 }
4003
4004 - (NSArray *) getInstalledPackages {
4005 NSArray *packages([[Database sharedInstance] packages]);
4006 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4007 for (Package *package in packages)
4008 if ([package installed] != nil)
4009 [installed addObject:package];
4010 return installed;
4011 }
4012
4013 - (Package *) getPackageById:(NSString *)id {
4014 Package *package([[Database sharedInstance] packageWithName:id]);
4015 [package parse];
4016 return package;
4017 }
4018
4019 - (NSArray *) statfs:(NSString *)path {
4020 struct statfs stat;
4021
4022 if (path == nil || statfs([path UTF8String], &stat) == -1)
4023 return nil;
4024
4025 return [NSArray arrayWithObjects:
4026 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4027 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4028 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4029 nil];
4030 }
4031
4032 - (NSNumber *) du:(NSString *)path {
4033 NSNumber *value(nil);
4034
4035 int fds[2];
4036 _assert(pipe(fds) != -1);
4037
4038 pid_t pid(ExecFork());
4039 if (pid == 0) {
4040 _assert(dup2(fds[1], 1) != -1);
4041 _assert(close(fds[0]) != -1);
4042 _assert(close(fds[1]) != -1);
4043 /* XXX: this should probably not use du */
4044 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4045 exit(1);
4046 _assert(false);
4047 }
4048
4049 _assert(close(fds[1]) != -1);
4050
4051 if (FILE *du = fdopen(fds[0], "r")) {
4052 char line[1024];
4053 while (fgets(line, sizeof(line), du) != NULL) {
4054 size_t length(strlen(line));
4055 while (length != 0 && line[length - 1] == '\n')
4056 line[--length] = '\0';
4057 if (char *tab = strchr(line, '\t')) {
4058 *tab = '\0';
4059 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4060 }
4061 }
4062
4063 fclose(du);
4064 } else _assert(close(fds[0]));
4065
4066 int status;
4067 wait:
4068 if (waitpid(pid, &status, 0) == -1)
4069 if (errno == EINTR)
4070 goto wait;
4071 else _assert(false);
4072
4073 return value;
4074 }
4075
4076 - (void) close {
4077 [indirect_ close];
4078 }
4079
4080 - (void) installPackages:(NSArray *)packages {
4081 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4082 }
4083
4084 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4085 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4086 }
4087
4088 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4089 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4090 }
4091
4092 - (void) setSpecial:(id)function {
4093 [indirect_ setSpecial:function];
4094 }
4095
4096 - (void) setToken:(NSString *)token {
4097 if (Token_ != nil)
4098 [Token_ release];
4099 Token_ = [token retain];
4100
4101 [Metadata_ setObject:Token_ forKey:@"Token"];
4102 Changed_ = true;
4103 }
4104
4105 - (void) setPopupHook:(id)function {
4106 [indirect_ setPopupHook:function];
4107 }
4108
4109 - (void) setViewportWidth:(float)width {
4110 [indirect_ setViewportWidth:width];
4111 }
4112
4113 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4114 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4115 unsigned count([arguments count]);
4116 id values[count];
4117 for (unsigned i(0); i != count; ++i)
4118 values[i] = [arguments objectAtIndex:i];
4119 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4120 }
4121
4122 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4123 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4124 value = nil;
4125 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4126 table = nil;
4127 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4128 }
4129
4130 @end
4131 /* }}} */
4132
4133 /* @ Loading... Indicator {{{ */
4134 @interface CYLoadingIndicator : UIView {
4135 UIActivityIndicatorView *spinner_;
4136 UILabel *label_;
4137 UIView *container_;
4138 }
4139
4140 @property (readonly, nonatomic) UILabel *label;
4141 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4142
4143 @end
4144
4145 @implementation CYLoadingIndicator
4146
4147 - (id) initWithFrame:(CGRect)frame {
4148 if ((self = [super initWithFrame:frame]) != nil) {
4149 container_ = [[[UIView alloc] init] autorelease];
4150 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4151
4152 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4153 [spinner_ startAnimating];
4154 [container_ addSubview:spinner_];
4155
4156 label_ = [[[UILabel alloc] init] autorelease];
4157 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4158 [label_ setBackgroundColor:[UIColor clearColor]];
4159 [label_ setTextColor:[UIColor blackColor]];
4160 [label_ setShadowColor:[UIColor whiteColor]];
4161 [label_ setShadowOffset:CGSizeMake(0, 1)];
4162 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4163 [container_ addSubview:label_];
4164
4165 CGSize viewsize = frame.size;
4166 CGSize spinnersize = [spinner_ bounds].size;
4167 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4168 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4169
4170 CGRect containrect = {
4171 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4172 CGSizeMake(bothwidth, spinnersize.height)
4173 };
4174 CGRect textrect = {
4175 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4176 textsize
4177 };
4178 CGRect spinrect = {
4179 CGPointZero,
4180 spinnersize
4181 };
4182
4183 [container_ setFrame:containrect];
4184 [spinner_ setFrame:spinrect];
4185 [label_ setFrame:textrect];
4186 [self addSubview:container_];
4187 } return self;
4188 }
4189
4190 - (UILabel *) label {
4191 return label_;
4192 }
4193
4194 - (UIActivityIndicatorView *) activityIndicatorView {
4195 return spinner_;
4196 }
4197
4198 @end
4199 /* }}} */
4200 /* Emulated Loading Controller {{{ */
4201 @interface CYEmulatedLoadingController : CYViewController <
4202 ProgressDelegate,
4203 ConfigurationDelegate
4204 > {
4205 _transient Database *database_;
4206 CYLoadingIndicator *indicator_;
4207 UITabBar *tabbar_;
4208 UINavigationBar *navbar_;
4209 }
4210
4211 @end
4212
4213 @implementation CYEmulatedLoadingController
4214
4215 - (void) dealloc {
4216 [self releaseSubviews];
4217 [database_ setDelegate:nil];
4218
4219 [super dealloc];
4220 }
4221
4222 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4223 CYAlertView *sheet([[[CYAlertView alloc]
4224 initWithTitle:title
4225 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4226 defaultButtonIndex:0
4227 ] autorelease]);
4228
4229 [sheet setMessage:error];
4230 [sheet yieldToPopupAlertAnimated:YES];
4231 [sheet dismiss];
4232 }
4233
4234 - (void) setProgressTitle:(NSString *)title { }
4235 - (void) setProgressPercent:(float)percent { }
4236 - (void) startProgress { }
4237 - (void) addProgressOutput:(NSString *)output { }
4238 - (bool) isCancelling:(size_t)received { return NO; }
4239 - (void) setConfigurationData:(NSString *)data { }
4240
4241 - (void) repairWithSelector:(SEL)selector {
4242 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4243 [database_ performSelector:selector];
4244 sleep(10);
4245 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4246 }
4247
4248 - (id) initWithDatabase:(Database *)database {
4249 if ((self = [super init]) != nil) {
4250 database_ = database;
4251 [database_ setDelegate:self];
4252 } return self;
4253 }
4254
4255 - (void) loadView {
4256 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4257 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4258
4259 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4260 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4261 [[self view] addSubview:indicator_];
4262
4263 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4264 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4265 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4266 [[self view] addSubview:tabbar_];
4267
4268 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4269 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4270 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4271 [[self view] addSubview:navbar_];
4272 }
4273
4274 - (void) releaseSubviews {
4275 [indicator_ release];
4276 indicator_ = nil;
4277
4278 [tabbar_ release];
4279 tabbar_ = nil;
4280
4281 [navbar_ release];
4282 navbar_ = nil;
4283 }
4284
4285 @end
4286 /* }}} */
4287
4288 /* Cydia Browser Controller {{{ */
4289 @interface CYBrowserController : BrowserController {
4290 CydiaObject *cydia_;
4291 }
4292
4293 @end
4294
4295 @implementation CYBrowserController
4296
4297 - (void) dealloc {
4298 [cydia_ release];
4299 [super dealloc];
4300 }
4301
4302 - (NSURL *) navigationURL {
4303 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4304 }
4305
4306 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4307 }
4308
4309 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4310 [super webView:view didClearWindowObject:window forFrame:frame];
4311
4312 WebDataSource *source([frame dataSource]);
4313 NSURLResponse *response([source response]);
4314
4315 NSURL *url([response URL]);
4316 NSString *scheme([url scheme]);
4317 NSString *host([url host]);
4318
4319 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4320 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4321 NSDictionary *headers([http allHeaderFields]);
4322 [self setHeaders:headers forHost:host];
4323 }
4324
4325 if (
4326 [host isEqualToString:@"cydia.saurik.com"] ||
4327 [host hasSuffix:@".cydia.saurik.com"] ||
4328 [scheme isEqualToString:@"file"]
4329 )
4330 [window setValue:cydia_ forKey:@"cydia"];
4331 }
4332
4333 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4334 if (System_ != NULL)
4335 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4336 if (Machine_ != NULL)
4337 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4338 if (Token_ != nil)
4339 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4340 if (Role_ != nil)
4341 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4342 }
4343
4344 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4345 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4346 [self _setMoreHeaders:copy];
4347 return copy;
4348 }
4349
4350 - (void) setDelegate:(id)delegate {
4351 [super setDelegate:delegate];
4352 [cydia_ setDelegate:delegate];
4353 }
4354
4355 - (id) init {
4356 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4357 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4358
4359 WebView *webview([[webview_ _documentView] webView]);
4360
4361 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4362
4363 NSString *application = package == nil ? @"Cydia" : [NSString
4364 stringWithFormat:@"Cydia/%@",
4365 [package installed]
4366 ];
4367
4368 if (Safari_ != nil)
4369 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4370 if (Build_ != nil)
4371 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4372 if (Product_ != nil)
4373 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4374
4375 [webview setApplicationNameForUserAgent:application];
4376 } return self;
4377 }
4378
4379 @end
4380 /* }}} */
4381
4382 // CydiaScript {{{
4383 @interface NSObject (CydiaScript)
4384 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4385 @end
4386
4387 @implementation NSObject (CydiaScript)
4388
4389 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4390 return self;
4391 }
4392
4393 @end
4394
4395 @implementation NSArray (CydiaScript)
4396
4397 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4398 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4399 for (size_t i(0), e([self count]); i != e; ++i)
4400 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4401 return object;
4402 }
4403
4404 @end
4405
4406 @implementation NSDictionary (CydiaScript)
4407
4408 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4409 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4410 for (id i in self)
4411 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4412 return object;
4413 }
4414
4415 @end
4416 // }}}
4417
4418 /* Confirmation Controller {{{ */
4419 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4420 if (!iterator.end())
4421 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4422 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4423 continue;
4424 pkgCache::PkgIterator package(dep.TargetPkg());
4425 if (package.end())
4426 continue;
4427 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4428 return true;
4429 }
4430
4431 return false;
4432 }
4433
4434 @protocol ConfirmationControllerDelegate
4435 - (void) cancelAndClear:(bool)clear;
4436 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4437 - (void) queue;
4438 @end
4439
4440 @interface ConfirmationController : CYBrowserController {
4441 _transient Database *database_;
4442
4443 UIAlertView *essential_;
4444
4445 NSDictionary *changes_;
4446 NSMutableArray *issues_;
4447 NSDictionary *sizes_;
4448
4449 BOOL substrate_;
4450 }
4451
4452 - (id) initWithDatabase:(Database *)database;
4453
4454 @end
4455
4456 @implementation ConfirmationController
4457
4458 - (void) dealloc {
4459 [changes_ release];
4460 [issues_ release];
4461 [sizes_ release];
4462
4463 if (essential_ != nil)
4464 [essential_ release];
4465
4466 [super dealloc];
4467 }
4468
4469 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4470 NSString *context([alert context]);
4471
4472 if ([context isEqualToString:@"remove"]) {
4473 if (button == [alert cancelButtonIndex]) {
4474 [self dismissModalViewControllerAnimated:YES];
4475 } else if (button == [alert firstOtherButtonIndex]) {
4476 if (substrate_)
4477 Finish_ = 2;
4478 [delegate_ confirmWithNavigationController:[self navigationController]];
4479 }
4480
4481 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4482 } else if ([context isEqualToString:@"unable"]) {
4483 [self dismissModalViewControllerAnimated:YES];
4484 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4485 } else {
4486 [super alertView:alert clickedButtonAtIndex:button];
4487 }
4488 }
4489
4490 - (void) _doContinue {
4491 [self dismissModalViewControllerAnimated:YES];
4492 [delegate_ cancelAndClear:NO];
4493 }
4494
4495 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4496 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4497 return nil;
4498 }
4499
4500 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4501 [super webView:view didClearWindowObject:window forFrame:frame];
4502
4503 [window setValue:[changes_ Cydia$webScriptObjectInContext:window] forKey:@"changes"];
4504 [window setValue:[issues_ Cydia$webScriptObjectInContext:window] forKey:@"issues"];
4505 [window setValue:[sizes_ Cydia$webScriptObjectInContext:window] forKey:@"sizes"];
4506
4507 [window setValue:self forKey:@"queue"];
4508 }
4509
4510 - (id) initWithDatabase:(Database *)database {
4511 if ((self = [super init]) != nil) {
4512 database_ = database;
4513
4514 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4515 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4516 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4517 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4518 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4519
4520 bool remove(false);
4521
4522 pkgCacheFile &cache([database_ cache]);
4523 NSArray *packages([database_ packages]);
4524 pkgDepCache::Policy *policy([database_ policy]);
4525
4526 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4527
4528 for (Package *package in packages) {
4529 pkgCache::PkgIterator iterator([package iterator]);
4530 NSString *name([package id]);
4531
4532 if ([package broken]) {
4533 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4534
4535 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4536 name, @"package",
4537 reasons, @"reasons",
4538 nil]];
4539
4540 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4541 if (ver.end())
4542 continue;
4543
4544 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4545 pkgCache::DepIterator start;
4546 pkgCache::DepIterator end;
4547 dep.GlobOr(start, end); // ++dep
4548
4549 if (!cache->IsImportantDep(end))
4550 continue;
4551 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4552 continue;
4553
4554 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4555
4556 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4557 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4558 clauses, @"clauses",
4559 nil]];
4560
4561 _forever {
4562 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4563
4564 pkgCache::PkgIterator target(start.TargetPkg());
4565 if (target->ProvidesList != 0)
4566 reason = @"missing";
4567 else {
4568 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4569 if (!ver.end()) {
4570 reason = @"installed";
4571 installed = [NSString stringWithUTF8String:ver.VerStr()];
4572 } else if (!cache[target].CandidateVerIter(cache).end())
4573 reason = @"uninstalled";
4574 else if (target->ProvidesList == 0)
4575 reason = @"uninstallable";
4576 else
4577 reason = @"virtual";
4578 }
4579
4580 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4581 [NSString stringWithUTF8String:start.CompType()], @"operator",
4582 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4583 nil]);
4584
4585 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4586 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4587 version, @"version",
4588 reason, @"reason",
4589 installed, @"installed",
4590 nil]];
4591
4592 // yes, seriously. (wtf?)
4593 if (start == end)
4594 break;
4595 ++start;
4596 }
4597 }
4598 }
4599
4600 pkgDepCache::StateCache &state(cache[iterator]);
4601
4602 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4603
4604 if (state.NewInstall())
4605 [installs addObject:name];
4606 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4607 [reinstalls addObject:name];
4608 else if (state.Upgrade())
4609 [upgrades addObject:name];
4610 else if (state.Downgrade())
4611 [downgrades addObject:name];
4612 else if (!state.Delete())
4613 continue;
4614 else if (special_r(name))
4615 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4616 [NSNull null], @"package",
4617 [NSArray arrayWithObjects:
4618 [NSDictionary dictionaryWithObjectsAndKeys:
4619 @"Conflicts", @"relationship",
4620 [NSArray arrayWithObjects:
4621 [NSDictionary dictionaryWithObjectsAndKeys:
4622 name, @"package",
4623 [NSNull null], @"version",
4624 @"installed", @"reason",
4625 nil],
4626 nil], @"clauses",
4627 nil],
4628 nil], @"reasons",
4629 nil]];
4630 else {
4631 if ([package essential])
4632 remove = true;
4633 [removes addObject:name];
4634 }
4635
4636 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4637 substrate_ |= DepSubstrate(iterator.CurrentVer());
4638 }
4639
4640 if (!remove)
4641 essential_ = nil;
4642 else if (Advanced_) {
4643 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4644
4645 essential_ = [[UIAlertView alloc]
4646 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4647 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4648 delegate:self
4649 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4650 otherButtonTitles:
4651 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4652 nil
4653 ];
4654
4655 [essential_ setContext:@"remove"];
4656 } else {
4657 essential_ = [[UIAlertView alloc]
4658 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4659 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4660 delegate:self
4661 cancelButtonTitle:UCLocalize("OKAY")
4662 otherButtonTitles:nil
4663 ];
4664
4665 [essential_ setContext:@"unable"];
4666 }
4667
4668 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4669 installs, @"installs",
4670 reinstalls, @"reinstalls",
4671 upgrades, @"upgrades",
4672 downgrades, @"downgrades",
4673 removes, @"removes",
4674 nil];
4675
4676 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4677 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4678 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4679 nil];
4680
4681 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4682
4683 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4684 initWithTitle:UCLocalize("CANCEL")
4685 style:UIBarButtonItemStylePlain
4686 target:self
4687 action:@selector(cancelButtonClicked)
4688 ] autorelease]];
4689 } return self;
4690 }
4691
4692 #if !AlwaysReload
4693 - (void) applyRightButton {
4694 if ([issues_ count] == 0 && ![self isLoading])
4695 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4696 initWithTitle:UCLocalize("CONFIRM")
4697 style:UIBarButtonItemStyleDone
4698 target:self
4699 action:@selector(confirmButtonClicked)
4700 ] autorelease]];
4701 else
4702 [[self navigationItem] setRightBarButtonItem:nil];
4703 }
4704 #endif
4705
4706 - (void) cancelButtonClicked {
4707 [self dismissModalViewControllerAnimated:YES];
4708 [delegate_ cancelAndClear:YES];
4709 }
4710
4711 #if !AlwaysReload
4712 - (void) confirmButtonClicked {
4713 if (essential_ != nil)
4714 [essential_ show];
4715 else {
4716 if (substrate_)
4717 Finish_ = 2;
4718 [delegate_ confirmWithNavigationController:[self navigationController]];
4719 }
4720 }
4721 #endif
4722
4723 @end
4724 /* }}} */
4725
4726 /* Progress Data {{{ */
4727 @interface ProgressData : NSObject {
4728 SEL selector_;
4729 // XXX: should these really both be _transient?
4730 _transient id target_;
4731 _transient id object_;
4732 }
4733
4734 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4735
4736 - (SEL) selector;
4737 - (id) target;
4738 - (id) object;
4739
4740 @end
4741
4742 @implementation ProgressData
4743
4744 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4745 if ((self = [super init]) != nil) {
4746 selector_ = selector;
4747 target_ = target;
4748 object_ = object;
4749 } return self;
4750 }
4751
4752 - (SEL) selector {
4753 return selector_;
4754 }
4755
4756 - (id) target {
4757 return target_;
4758 }
4759
4760 - (id) object {
4761 return object_;
4762 }
4763
4764 @end
4765 /* }}} */
4766 /* Progress Controller {{{ */
4767 @interface ProgressController : CYViewController <
4768 ConfigurationDelegate,
4769 ProgressDelegate
4770 > {
4771 _transient Database *database_;
4772 UIProgressBar *progress_;
4773 UITextView *output_;
4774 UITextLabel *status_;
4775 UIPushButton *close_;
4776 BOOL running_;
4777 SHA1SumValue springlist_;
4778 SHA1SumValue notifyconf_;
4779 NSString *title_;
4780 }
4781
4782 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4783
4784 - (void) _retachThread;
4785 - (void) _detachNewThreadData:(ProgressData *)data;
4786 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4787
4788 - (BOOL) isRunning;
4789
4790 @end
4791
4792 @protocol ProgressControllerDelegate
4793 - (void) progressControllerIsComplete:(ProgressController *)sender;
4794 @end
4795
4796 @implementation ProgressController
4797
4798 - (void) dealloc {
4799 [database_ setDelegate:nil];
4800 [progress_ release];
4801 [output_ release];
4802 [status_ release];
4803 [close_ release];
4804 if (title_ != nil)
4805 [title_ release];
4806 [super dealloc];
4807 }
4808
4809 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4810 if ((self = [super init]) != nil) {
4811 database_ = database;
4812 [database_ setDelegate:self];
4813 delegate_ = delegate;
4814
4815 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4816
4817 progress_ = [[UIProgressBar alloc] init];
4818 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4819 [progress_ setStyle:0];
4820
4821 status_ = [[UITextLabel alloc] init];
4822 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4823 [status_ setColor:[UIColor whiteColor]];
4824 [status_ setBackgroundColor:[UIColor clearColor]];
4825 [status_ setCentersHorizontally:YES];
4826 //[status_ setFont:font];
4827
4828 output_ = [[UITextView alloc] init];
4829 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4830 //[output_ setTextFont:@"Courier New"];
4831 [output_ setFont:[[output_ font] fontWithSize:12]];
4832 [output_ setTextColor:[UIColor whiteColor]];
4833 [output_ setBackgroundColor:[UIColor clearColor]];
4834 [output_ setMarginTop:0];
4835 [output_ setAllowsRubberBanding:YES];
4836 [output_ setEditable:NO];
4837 [[self view] addSubview:output_];
4838
4839 close_ = [[UIPushButton alloc] init];
4840 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4841 [close_ setAutosizesToFit:NO];
4842 [close_ setDrawsShadow:YES];
4843 [close_ setStretchBackground:YES];
4844 [close_ setEnabled:YES];
4845 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4846 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4847 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4848 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4849 } return self;
4850 }
4851
4852 - (void) positionViews {
4853 CGRect bounds = [[self view] bounds];
4854 CGSize prgsize = [UIProgressBar defaultSize];
4855
4856 CGRect prgrect = {{
4857 (bounds.size.width - prgsize.width) / 2,
4858 bounds.size.height - prgsize.height - 20
4859 }, prgsize};
4860
4861 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4862
4863 [progress_ setFrame:prgrect];
4864 [status_ setFrame:CGRectMake(
4865 10,
4866 bounds.size.height - prgsize.height - 50,
4867 bounds.size.width - 20,
4868 24
4869 )];
4870 [output_ setFrame:CGRectMake(
4871 10,
4872 20,
4873 bounds.size.width - 20,
4874 bounds.size.height - 96
4875 )];
4876 [close_ setFrame:CGRectMake(
4877 (bounds.size.width - closewidth) / 2,
4878 bounds.size.height - prgsize.height - 50,
4879 closewidth,
4880 32 + prgsize.height
4881 )];
4882 }
4883
4884 - (void) viewWillAppear:(BOOL)animated {
4885 [super viewDidAppear:animated];
4886 [[self navigationItem] setHidesBackButton:YES];
4887 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4888
4889 [self positionViews];
4890 }
4891
4892 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4893 [self positionViews];
4894 }
4895
4896 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4897 NSString *context([alert context]);
4898
4899 if ([context isEqualToString:@"conffile"]) {
4900 FILE *input = [database_ input];
4901 if (button == [alert cancelButtonIndex])
4902 fprintf(input, "N\n");
4903 else if (button == [alert firstOtherButtonIndex])
4904 fprintf(input, "Y\n");
4905 fflush(input);
4906 }
4907 }
4908
4909 - (void) closeButtonPushed {
4910 running_ = NO;
4911
4912 UpdateExternalStatus(0);
4913
4914 switch (Finish_) {
4915 case 0:
4916 [self dismissModalViewControllerAnimated:YES];
4917 break;
4918
4919 case 1:
4920 [delegate_ terminateWithSuccess];
4921 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4922 [delegate_ suspendWithAnimation:YES];
4923 else
4924 [delegate_ suspend];*/
4925 break;
4926
4927 case 2:
4928 _trace();
4929 goto reload;
4930
4931 case 3:
4932 _trace();
4933 goto reload;
4934
4935 reload:
4936 system("/usr/bin/sbreload");
4937 _trace();
4938 break;
4939
4940 case 4:
4941 _trace();
4942 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4943 SBReboot(SBSSpringBoardServerPort());
4944 else
4945 reboot2(RB_AUTOBOOT);
4946 break;
4947 }
4948 }
4949
4950 - (void) _retachThread {
4951 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4952
4953 [[self view] addSubview:close_];
4954 [progress_ removeFromSuperview];
4955 [status_ removeFromSuperview];
4956
4957 [database_ popErrorWithTitle:title_];
4958 [delegate_ progressControllerIsComplete:self];
4959
4960 if (Finish_ < 4) {
4961 FileFd file;
4962 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4963 _error->Discard();
4964 else {
4965 MMap mmap(file, MMap::ReadOnly);
4966 SHA1Summation sha1;
4967 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4968 if (!(notifyconf_ == sha1.Result()))
4969 Finish_ = 4;
4970 }
4971 }
4972
4973 if (Finish_ < 3) {
4974 FileFd file;
4975 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4976 _error->Discard();
4977 else {
4978 MMap mmap(file, MMap::ReadOnly);
4979 SHA1Summation sha1;
4980 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4981 if (!(springlist_ == sha1.Result()))
4982 Finish_ = 3;
4983 }
4984 }
4985
4986 switch (Finish_) {
4987 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4988 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4989 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4990 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4991 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4992 }
4993
4994 _trace();
4995 system("su -c /usr/bin/uicache mobile");
4996 _trace();
4997
4998 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4999
5000 [delegate_ setStatusBarShowsProgress:NO];
5001 }
5002
5003 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
5004 [[data target] performSelector:[data selector] withObject:[data object]];
5005 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
5006 }
5007
5008 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
5009 UpdateExternalStatus(1);
5010
5011 if (title_ != nil)
5012 [title_ release];
5013 if (title == nil)
5014 title_ = nil;
5015 else
5016 title_ = [title retain];
5017
5018 [[self navigationItem] setTitle:title_];
5019
5020 [status_ setText:nil];
5021 [output_ setText:@""];
5022 [progress_ setProgress:0];
5023
5024 [close_ removeFromSuperview];
5025 [[self view] addSubview:progress_];
5026 [[self view] addSubview:status_];
5027
5028 [delegate_ setStatusBarShowsProgress:YES];
5029 running_ = YES;
5030
5031 {
5032 FileFd file;
5033 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5034 _error->Discard();
5035 else {
5036 MMap mmap(file, MMap::ReadOnly);
5037 SHA1Summation sha1;
5038 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5039 notifyconf_ = sha1.Result();
5040 }
5041 }
5042
5043 {
5044 FileFd file;
5045 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5046 _error->Discard();
5047 else {
5048 MMap mmap(file, MMap::ReadOnly);
5049 SHA1Summation sha1;
5050 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5051 springlist_ = sha1.Result();
5052 }
5053 }
5054
5055 [NSThread
5056 detachNewThreadSelector:@selector(_detachNewThreadData:)
5057 toTarget:self
5058 withObject:[[[ProgressData alloc]
5059 initWithSelector:selector
5060 target:target
5061 object:object
5062 ] autorelease]
5063 ];
5064 }
5065
5066 - (void) repairWithSelector:(SEL)selector {
5067 [self
5068 detachNewThreadSelector:selector
5069 toTarget:database_
5070 withObject:nil
5071 title:UCLocalize("REPAIRING")
5072 ];
5073 }
5074
5075 - (void) setConfigurationData:(NSString *)data {
5076 [self
5077 performSelectorOnMainThread:@selector(_setConfigurationData:)
5078 withObject:data
5079 waitUntilDone:YES
5080 ];
5081 }
5082
5083 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5084 CYAlertView *sheet([[[CYAlertView alloc]
5085 initWithTitle:title
5086 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5087 defaultButtonIndex:0
5088 ] autorelease]);
5089
5090 [sheet setMessage:error];
5091 [sheet yieldToPopupAlertAnimated:YES];
5092 [sheet dismiss];
5093 }
5094
5095 - (void) setProgressTitle:(NSString *)title {
5096 [self
5097 performSelectorOnMainThread:@selector(_setProgressTitle:)
5098 withObject:title
5099 waitUntilDone:YES
5100 ];
5101 }
5102
5103 - (void) setProgressPercent:(float)percent {
5104 [self
5105 performSelectorOnMainThread:@selector(_setProgressPercent:)
5106 withObject:[NSNumber numberWithFloat:percent]
5107 waitUntilDone:YES
5108 ];
5109 }
5110
5111 - (void) startProgress {
5112 }
5113
5114 - (void) addProgressOutput:(NSString *)output {
5115 [self
5116 performSelectorOnMainThread:@selector(_addProgressOutput:)
5117 withObject:output
5118 waitUntilDone:YES
5119 ];
5120 }
5121
5122 - (bool) isCancelling:(size_t)received {
5123 return false;
5124 }
5125
5126 - (void) _setConfigurationData:(NSString *)data {
5127 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5128
5129 if (!conffile_r(data)) {
5130 lprintf("E:invalid conffile\n");
5131 return;
5132 }
5133
5134 NSString *ofile = conffile_r[1];
5135 //NSString *nfile = conffile_r[2];
5136
5137 UIAlertView *alert = [[[UIAlertView alloc]
5138 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5139 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5140 delegate:self
5141 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5142 otherButtonTitles:
5143 UCLocalize("ACCEPT_NEW_COPY"),
5144 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5145 nil
5146 ] autorelease];
5147
5148 [alert setContext:@"conffile"];
5149 [alert show];
5150 }
5151
5152 - (void) _setProgressTitle:(NSString *)title {
5153 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5154 for (size_t i(0), e([words count]); i != e; ++i) {
5155 NSString *word([words objectAtIndex:i]);
5156 if (Package *package = [database_ packageWithName:word])
5157 [words replaceObjectAtIndex:i withObject:[package name]];
5158 }
5159
5160 [status_ setText:[words componentsJoinedByString:@" "]];
5161 }
5162
5163 - (void) _setProgressPercent:(NSNumber *)percent {
5164 [progress_ setProgress:[percent floatValue]];
5165 }
5166
5167 - (void) _addProgressOutput:(NSString *)output {
5168 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5169 CGSize size = [output_ contentSize];
5170 CGPoint offset = [output_ contentOffset];
5171 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5172 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5173 [output_ scrollRectToVisible:rect animated:YES];
5174 }
5175 }
5176
5177 - (BOOL) isRunning {
5178 return running_;
5179 }
5180
5181 @end
5182 /* }}} */
5183
5184 /* Cell Content View {{{ */
5185 @protocol ContentDelegate
5186 - (void) drawContentRect:(CGRect)rect;
5187 @end
5188
5189 @interface ContentView : UIView {
5190 _transient id<ContentDelegate> delegate_;
5191 }
5192
5193 @end
5194
5195 @implementation ContentView
5196
5197 - (id) initWithFrame:(CGRect)frame {
5198 if ((self = [super initWithFrame:frame]) != nil) {
5199 [self setNeedsDisplayOnBoundsChange:YES];
5200 } return self;
5201 }
5202
5203 - (void) setDelegate:(id<ContentDelegate>)delegate {
5204 delegate_ = delegate;
5205 }
5206
5207 - (void) drawRect:(CGRect)rect {
5208 [super drawRect:rect];
5209 [delegate_ drawContentRect:rect];
5210 }
5211
5212 @end
5213 /* }}} */
5214 /* Cydia TableView Cell {{{ */
5215 @interface CYTableViewCell : UITableViewCell {
5216 ContentView *content_;
5217 bool highlighted_;
5218 }
5219
5220 @end
5221
5222 @implementation CYTableViewCell
5223
5224 - (void) dealloc {
5225 [content_ release];
5226 [super dealloc];
5227 }
5228
5229 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5230 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5231
5232 if (view == content_) {
5233 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5234 highlighted_ = highlighted;
5235 }
5236
5237 [super _updateHighlightColorsForView:view highlighted:highlighted];
5238 }
5239
5240 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5241 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5242 highlighted_ = selected;
5243
5244 [super setSelected:selected animated:animated];
5245 [content_ setNeedsDisplay];
5246 }
5247
5248 @end
5249 /* }}} */
5250
5251 /* Package Cell {{{ */
5252 @interface PackageCell : CYTableViewCell <
5253 ContentDelegate
5254 > {
5255 UIImage *icon_;
5256 NSString *name_;
5257 NSString *description_;
5258 bool commercial_;
5259 NSString *source_;
5260 UIImage *badge_;
5261 Package *package_;
5262 UIImage *placard_;
5263 }
5264
5265 - (PackageCell *) init;
5266 - (void) setPackage:(Package *)package;
5267
5268 - (void) drawContentRect:(CGRect)rect;
5269
5270 @end
5271
5272 @implementation PackageCell
5273
5274 - (void) clearPackage {
5275 if (icon_ != nil) {
5276 [icon_ release];
5277 icon_ = nil;
5278 }
5279
5280 if (name_ != nil) {
5281 [name_ release];
5282 name_ = nil;
5283 }
5284
5285 if (description_ != nil) {
5286 [description_ release];
5287 description_ = nil;
5288 }
5289
5290 if (source_ != nil) {
5291 [source_ release];
5292 source_ = nil;
5293 }
5294
5295 if (badge_ != nil) {
5296 [badge_ release];
5297 badge_ = nil;
5298 }
5299
5300 if (placard_ != nil) {
5301 [placard_ release];
5302 placard_ = nil;
5303 }
5304
5305 [package_ release];
5306 package_ = nil;
5307 }
5308
5309 - (void) dealloc {
5310 [self clearPackage];
5311 [super dealloc];
5312 }
5313
5314 - (PackageCell *) init {
5315 CGRect frame(CGRectMake(0, 0, 320, 74));
5316 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5317 UIView *content([self contentView]);
5318 CGRect bounds([content bounds]);
5319
5320 content_ = [[ContentView alloc] initWithFrame:bounds];
5321 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5322 [content addSubview:content_];
5323
5324 [content_ setDelegate:self];
5325 [content_ setOpaque:YES];
5326 } return self;
5327 }
5328
5329 - (NSString *) accessibilityLabel {
5330 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5331 }
5332
5333 - (void) setPackage:(Package *)package {
5334 [self clearPackage];
5335 [package parse];
5336
5337 Source *source = [package source];
5338
5339 icon_ = [[package icon] retain];
5340 name_ = [[package name] retain];
5341
5342 if (IsWildcat_)
5343 description_ = [package longDescription];
5344 if (description_ == nil)
5345 description_ = [package shortDescription];
5346 if (description_ != nil)
5347 description_ = [description_ retain];
5348
5349 commercial_ = [package isCommercial];
5350
5351 package_ = [package retain];
5352
5353 NSString *label = nil;
5354 bool trusted = false;
5355
5356 if (source != nil) {
5357 label = [source label];
5358 trusted = [source trusted];
5359 } else if ([[package id] isEqualToString:@"firmware"])
5360 label = UCLocalize("APPLE");
5361 else
5362 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5363
5364 NSString *from(label);
5365
5366 NSString *section = [package simpleSection];
5367 if (section != nil && ![section isEqualToString:label]) {
5368 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5369 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5370 }
5371
5372 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5373 source_ = [from retain];
5374
5375 if (NSString *purpose = [package primaryPurpose])
5376 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5377 badge_ = [badge_ retain];
5378
5379 UIColor *color;
5380 NSString *placard;
5381
5382 if (NSString *mode = [package_ mode]) {
5383 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5384 color = RemovingColor_;
5385 //placard = @"removing";
5386 } else {
5387 color = InstallingColor_;
5388 //placard = @"installing";
5389 }
5390
5391 // XXX: the removing/installing placards are not @2x
5392 placard = nil;
5393 } else {
5394 color = [UIColor whiteColor];
5395
5396 if ([package installed] != nil)
5397 placard = @"installed";
5398 else
5399 placard = nil;
5400 }
5401
5402 [content_ setBackgroundColor:color];
5403
5404 if (placard != nil)
5405 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5406 placard_ = [placard_ retain];
5407
5408 [self setNeedsDisplay];
5409 [content_ setNeedsDisplay];
5410 }
5411
5412 - (void) drawContentRect:(CGRect)rect {
5413 bool highlighted(highlighted_);
5414 float width([self bounds].size.width);
5415
5416 #if 0
5417 CGContextRef context(UIGraphicsGetCurrentContext());
5418 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5419 CGContextFillRect(context, rect);
5420 #endif
5421
5422 if (icon_ != nil) {
5423 CGRect rect;
5424 rect.size = [icon_ size];
5425
5426 rect.size.width /= 2;
5427 rect.size.height /= 2;
5428
5429 rect.origin.x = 25 - rect.size.width / 2;
5430 rect.origin.y = 25 - rect.size.height / 2;
5431
5432 [icon_ drawInRect:rect];
5433 }
5434
5435 if (badge_ != nil) {
5436 CGRect rect;
5437 rect.size = [badge_ size];
5438
5439 rect.size.width /= 2;
5440 rect.size.height /= 2;
5441
5442 rect.origin.x = 36 - rect.size.width / 2;
5443 rect.origin.y = 36 - rect.size.height / 2;
5444
5445 [badge_ drawInRect:rect];
5446 }
5447
5448 if (highlighted)
5449 UISetColor(White_);
5450
5451 if (!highlighted)
5452 UISetColor(commercial_ ? Purple_ : Black_);
5453 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5454 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5455
5456 if (!highlighted)
5457 UISetColor(commercial_ ? Purplish_ : Gray_);
5458 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5459
5460 if (placard_ != nil)
5461 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5462 }
5463
5464 @end
5465 /* }}} */
5466 /* Section Cell {{{ */
5467 @interface SectionCell : CYTableViewCell <
5468 ContentDelegate
5469 > {
5470 NSString *basic_;
5471 NSString *section_;
5472 NSString *name_;
5473 NSString *count_;
5474 UIImage *icon_;
5475 UISwitch *switch_;
5476 BOOL editing_;
5477 }
5478
5479 - (void) setSection:(Section *)section editing:(BOOL)editing;
5480
5481 @end
5482
5483 @implementation SectionCell
5484
5485 - (void) clearSection {
5486 if (basic_ != nil) {
5487 [basic_ release];
5488 basic_ = nil;
5489 }
5490
5491 if (section_ != nil) {
5492 [section_ release];
5493 section_ = nil;
5494 }
5495
5496 if (name_ != nil) {
5497 [name_ release];
5498 name_ = nil;
5499 }
5500
5501 if (count_ != nil) {
5502 [count_ release];
5503 count_ = nil;
5504 }
5505 }
5506
5507 - (void) dealloc {
5508 [self clearSection];
5509 [icon_ release];
5510 [switch_ release];
5511 [super dealloc];
5512 }
5513
5514 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5515 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5516 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5517 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5518 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5519
5520 UIView *content([self contentView]);
5521 CGRect bounds([content bounds]);
5522
5523 content_ = [[ContentView alloc] initWithFrame:bounds];
5524 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5525 [content addSubview:content_];
5526 [content_ setBackgroundColor:[UIColor whiteColor]];
5527
5528 [content_ setDelegate:self];
5529 } return self;
5530 }
5531
5532 - (void) onSwitch:(id)sender {
5533 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5534 if (metadata == nil) {
5535 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5536 [Sections_ setObject:metadata forKey:basic_];
5537 }
5538
5539 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5540 Changed_ = true;
5541 }
5542
5543 - (void) setSection:(Section *)section editing:(BOOL)editing {
5544 if (editing != editing_) {
5545 if (editing_)
5546 [switch_ removeFromSuperview];
5547 else
5548 [self addSubview:switch_];
5549 editing_ = editing;
5550 }
5551
5552 [self clearSection];
5553
5554 if (section == nil) {
5555 name_ = [UCLocalize("ALL_PACKAGES") retain];
5556 count_ = nil;
5557 } else {
5558 basic_ = [section name];
5559 if (basic_ != nil)
5560 basic_ = [basic_ retain];
5561
5562 section_ = [section localized];
5563 if (section_ != nil)
5564 section_ = [section_ retain];
5565
5566 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5567 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5568
5569 if (editing_)
5570 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5571 }
5572
5573 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5574 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5575
5576 [content_ setNeedsDisplay];
5577 }
5578
5579 - (void) setFrame:(CGRect)frame {
5580 [super setFrame:frame];
5581
5582 CGRect rect([switch_ frame]);
5583 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5584 }
5585
5586 - (NSString *) accessibilityLabel {
5587 return name_;
5588 }
5589
5590 - (void) drawContentRect:(CGRect)rect {
5591 bool highlighted(highlighted_ && !editing_);
5592
5593 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5594
5595 if (highlighted)
5596 UISetColor(White_);
5597
5598 float width(rect.size.width);
5599 if (editing_)
5600 width -= 87;
5601
5602 if (!highlighted)
5603 UISetColor(Black_);
5604 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5605
5606 CGSize size = [count_ sizeWithFont:Font14_];
5607
5608 UISetColor(White_);
5609 if (count_ != nil)
5610 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5611 }
5612
5613 @end
5614 /* }}} */
5615
5616 /* File Table {{{ */
5617 @interface FileTable : CYViewController <
5618 UITableViewDataSource,
5619 UITableViewDelegate
5620 > {
5621 _transient Database *database_;
5622 Package *package_;
5623 NSString *name_;
5624 NSMutableArray *files_;
5625 UITableView *list_;
5626 }
5627
5628 - (id) initWithDatabase:(Database *)database;
5629 - (void) setPackage:(Package *)package;
5630
5631 @end
5632
5633 @implementation FileTable
5634
5635 - (void) dealloc {
5636 [self releaseSubviews];
5637
5638 [package_ release];
5639 [name_ release];
5640 [files_ release];
5641
5642 [super dealloc];
5643 }
5644
5645 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5646 return files_ == nil ? 0 : [files_ count];
5647 }
5648
5649 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5650 return 24.0f;
5651 }*/
5652
5653 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5654 static NSString *reuseIdentifier = @"Cell";
5655
5656 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5657 if (cell == nil) {
5658 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5659 [cell setFont:[UIFont systemFontOfSize:16]];
5660 }
5661 [cell setText:[files_ objectAtIndex:indexPath.row]];
5662 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5663
5664 return cell;
5665 }
5666
5667 - (NSURL *) navigationURL {
5668 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5669 }
5670
5671 - (void) loadView {
5672 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5673
5674 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5675 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5676 [list_ setRowHeight:24.0f];
5677 [list_ setDataSource:self];
5678 [list_ setDelegate:self];
5679 [[self view] addSubview:list_];
5680 }
5681
5682 - (void) viewDidLoad {
5683 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5684 }
5685
5686 - (void) releaseSubviews {
5687 [list_ release];
5688 list_ = nil;
5689 }
5690
5691 - (id) initWithDatabase:(Database *)database {
5692 if ((self = [super init]) != nil) {
5693 database_ = database;
5694
5695 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5696 } return self;
5697 }
5698
5699 - (void) setPackage:(Package *)package {
5700 if (package_ != nil) {
5701 [package_ autorelease];
5702 package_ = nil;
5703 }
5704
5705 if (name_ != nil) {
5706 [name_ release];
5707 name_ = nil;
5708 }
5709
5710 [files_ removeAllObjects];
5711
5712 if (package != nil) {
5713 package_ = [package retain];
5714 name_ = [[package id] retain];
5715
5716 if (NSArray *files = [package files])
5717 [files_ addObjectsFromArray:files];
5718
5719 if ([files_ count] != 0) {
5720 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5721 [files_ removeObjectAtIndex:0];
5722 [files_ sortUsingSelector:@selector(compareByPath:)];
5723
5724 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5725 [stack addObject:@"/"];
5726
5727 for (int i(0), e([files_ count]); i != e; ++i) {
5728 NSString *file = [files_ objectAtIndex:i];
5729 while (![file hasPrefix:[stack lastObject]])
5730 [stack removeLastObject];
5731 NSString *directory = [stack lastObject];
5732 [stack addObject:[file stringByAppendingString:@"/"]];
5733 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5734 ([stack count] - 2) * 3, "",
5735 [file substringFromIndex:[directory length]]
5736 ]];
5737 }
5738 }
5739 }
5740
5741 [list_ reloadData];
5742 }
5743
5744 - (void) reloadData {
5745 [super reloadData];
5746
5747 [self setPackage:[database_ packageWithName:name_]];
5748 }
5749
5750 @end
5751 /* }}} */
5752 /* Package Controller {{{ */
5753 @interface CYPackageController : CYBrowserController <
5754 UIActionSheetDelegate
5755 > {
5756 _transient Database *database_;
5757 Package *package_;
5758 NSString *name_;
5759 bool commercial_;
5760 NSMutableArray *buttons_;
5761 UIBarButtonItem *button_;
5762 }
5763
5764 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5765
5766 @end
5767
5768 @implementation CYPackageController
5769
5770 - (void) dealloc {
5771 if (package_ != nil)
5772 [package_ release];
5773 if (name_ != nil)
5774 [name_ release];
5775
5776 [buttons_ release];
5777
5778 if (button_ != nil)
5779 [button_ release];
5780
5781 [super dealloc];
5782 }
5783
5784 - (NSURL *) navigationURL {
5785 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5786 }
5787
5788 /* XXX: this is not safe at all... localization of /fail/ */
5789 - (void) _clickButtonWithName:(NSString *)name {
5790 if ([name isEqualToString:UCLocalize("CLEAR")])
5791 [delegate_ clearPackage:package_];
5792 else if ([name isEqualToString:UCLocalize("INSTALL")])
5793 [delegate_ installPackage:package_];
5794 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5795 [delegate_ installPackage:package_];
5796 else if ([name isEqualToString:UCLocalize("REMOVE")])
5797 [delegate_ removePackage:package_];
5798 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5799 [delegate_ installPackage:package_];
5800 else _assert(false);
5801 }
5802
5803 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5804 NSString *context([sheet context]);
5805
5806 if ([context isEqualToString:@"modify"]) {
5807 if (button != [sheet cancelButtonIndex]) {
5808 NSString *buttonName = [buttons_ objectAtIndex:button];
5809 [self _clickButtonWithName:buttonName];
5810 }
5811
5812 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5813 }
5814 }
5815
5816 - (bool) _allowJavaScriptPanel {
5817 return commercial_;
5818 }
5819
5820 #if !AlwaysReload
5821 - (void) _customButtonClicked {
5822 int count([buttons_ count]);
5823 if (count == 0)
5824 return;
5825
5826 if (count == 1)
5827 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5828 else {
5829 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5830 [buttons addObjectsFromArray:buttons_];
5831
5832 UIActionSheet *sheet = [[[UIActionSheet alloc]
5833 initWithTitle:nil
5834 delegate:self
5835 cancelButtonTitle:nil
5836 destructiveButtonTitle:nil
5837 otherButtonTitles:nil
5838 ] autorelease];
5839
5840 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5841 if (!IsWildcat_) {
5842 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5843 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5844 }
5845 [sheet setContext:@"modify"];
5846
5847 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5848 }
5849 }
5850
5851 // We don't want to allow non-commercial packages to do custom things to the install button,
5852 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5853 - (void) customButtonClicked {
5854 if (commercial_)
5855 [super customButtonClicked];
5856 else
5857 [self _customButtonClicked];
5858 }
5859
5860 - (void) reloadButtonClicked {
5861 // Don't reload a commerical package by tapping the loading button,
5862 // but if it's not an Install button, we should forward it on.
5863 if (![package_ uninstalled])
5864 [self _customButtonClicked];
5865 }
5866
5867 - (void) applyLoadingTitle {
5868 // Don't show "Loading" as the title. Ever.
5869 }
5870
5871 - (UIBarButtonItem *) rightButton {
5872 return button_;
5873 }
5874 #endif
5875
5876 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5877 if ((self = [super init]) != nil) {
5878 database_ = database;
5879 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5880 name_ = [[NSString alloc] initWithString:name];
5881 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5882 } return self;
5883 }
5884
5885 - (void) reloadData {
5886 if (package_ != nil)
5887 [package_ autorelease];
5888 package_ = [database_ packageWithName:name_];
5889
5890 [buttons_ removeAllObjects];
5891
5892 if (package_ != nil) {
5893 [package_ parse];
5894
5895 package_ = [package_ retain];
5896 commercial_ = [package_ isCommercial];
5897
5898 if ([package_ mode] != nil)
5899 [buttons_ addObject:UCLocalize("CLEAR")];
5900 if ([package_ source] == nil);
5901 else if ([package_ upgradableAndEssential:NO])
5902 [buttons_ addObject:UCLocalize("UPGRADE")];
5903 else if ([package_ uninstalled])
5904 [buttons_ addObject:UCLocalize("INSTALL")];
5905 else
5906 [buttons_ addObject:UCLocalize("REINSTALL")];
5907 if (![package_ uninstalled])
5908 [buttons_ addObject:UCLocalize("REMOVE")];
5909 }
5910
5911 if (button_ != nil)
5912 [button_ release];
5913
5914 NSString *title;
5915 switch ([buttons_ count]) {
5916 case 0: title = nil; break;
5917 case 1: title = [buttons_ objectAtIndex:0]; break;
5918 default: title = UCLocalize("MODIFY"); break;
5919 }
5920
5921 button_ = [[UIBarButtonItem alloc]
5922 initWithTitle:title
5923 style:UIBarButtonItemStylePlain
5924 target:self
5925 action:@selector(customButtonClicked)
5926 ];
5927
5928 [super reloadData];
5929 }
5930
5931 - (bool) isLoading {
5932 return commercial_ ? [super isLoading] : false;
5933 }
5934
5935 @end
5936 /* }}} */
5937
5938 /* Package List Controller {{{ */
5939 @interface PackageListController : CYViewController <
5940 UITableViewDataSource,
5941 UITableViewDelegate
5942 > {
5943 _transient Database *database_;
5944 unsigned era_;
5945 NSMutableArray *packages_;
5946 NSMutableArray *sections_;
5947 UITableView *list_;
5948 NSMutableArray *index_;
5949 NSMutableDictionary *indices_;
5950 NSString *title_;
5951 }
5952
5953 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5954 - (void) setDelegate:(id)delegate;
5955 - (void) resetCursor;
5956
5957 @end
5958
5959 @implementation PackageListController
5960
5961 - (void) dealloc {
5962 [packages_ release];
5963 [sections_ release];
5964 [list_ release];
5965 [index_ release];
5966 [indices_ release];
5967 [title_ release];
5968
5969 [super dealloc];
5970 }
5971
5972 - (void) deselectWithAnimation:(BOOL)animated {
5973 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5974 }
5975
5976 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5977 CGRect base = [[self view] bounds];
5978 base.size.height -= bounds.size.height;
5979 base.origin = [list_ frame].origin;
5980
5981 [UIView beginAnimations:nil context:NULL];
5982 [UIView setAnimationBeginsFromCurrentState:YES];
5983 [UIView setAnimationCurve:curve];
5984 [UIView setAnimationDuration:duration];
5985 [list_ setFrame:base];
5986 [UIView commitAnimations];
5987 }
5988
5989 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5990 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5991 }
5992
5993 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5994 [self resizeForKeyboardBounds:bounds duration:0];
5995 }
5996
5997 - (void) keyboardWillShow:(NSNotification *)notification {
5998 CGRect bounds;
5999 CGPoint center;
6000 NSTimeInterval duration;
6001 UIViewAnimationCurve curve;
6002 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6003 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6004 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6005 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6006
6007 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);
6008 UIViewController *base = self;
6009 while ([base parentViewController] != nil)
6010 base = [base parentViewController];
6011 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6012 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6013
6014 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6015 }
6016
6017 - (void) keyboardWillHide:(NSNotification *)notification {
6018 NSTimeInterval duration;
6019 UIViewAnimationCurve curve;
6020 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6021 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6022
6023 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6024 }
6025
6026 - (void) viewWillAppear:(BOOL)animated {
6027 [super viewWillAppear:animated];
6028
6029 [self resizeForKeyboardBounds:CGRectZero];
6030 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6031 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6032 }
6033
6034 - (void) viewWillDisappear:(BOOL)animated {
6035 [super viewWillDisappear:animated];
6036
6037 [self resizeForKeyboardBounds:CGRectZero];
6038 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6039 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6040 }
6041
6042 - (void) viewDidAppear:(BOOL)animated {
6043 [super viewDidAppear:animated];
6044 [self deselectWithAnimation:animated];
6045 }
6046
6047 - (void) didSelectPackage:(Package *)package {
6048 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6049 [view setDelegate:delegate_];
6050 [[self navigationController] pushViewController:view animated:YES];
6051 }
6052
6053 #if TryIndexedCollation
6054 + (BOOL) hasIndexedCollation {
6055 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6056 }
6057 #endif
6058
6059 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6060 NSInteger count([sections_ count]);
6061 return count == 0 ? 1 : count;
6062 }
6063
6064 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6065 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6066 return nil;
6067 return [[sections_ objectAtIndex:section] name];
6068 }
6069
6070 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6071 if ([sections_ count] == 0)
6072 return 0;
6073 return [[sections_ objectAtIndex:section] count];
6074 }
6075
6076 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6077 @synchronized (database_) {
6078 if ([database_ era] != era_)
6079 return nil;
6080
6081 Section *section([sections_ objectAtIndex:[path section]]);
6082 NSInteger row([path row]);
6083 Package *package([packages_ objectAtIndex:([section row] + row)]);
6084 return [[package retain] autorelease];
6085 } }
6086
6087 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6088 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6089 if (cell == nil)
6090 cell = [[[PackageCell alloc] init] autorelease];
6091 [cell setPackage:[self packageAtIndexPath:path]];
6092 return cell;
6093 }
6094
6095 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6096 Package *package([self packageAtIndexPath:path]);
6097 package = [database_ packageWithName:[package id]];
6098 [self didSelectPackage:package];
6099 }
6100
6101 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6102 // XXX: is 20 the most optimal number here?
6103 return [packages_ count] > 20 ? index_ : nil;
6104 }
6105
6106 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6107 #if TryIndexedCollation
6108 if ([[self class] hasIndexedCollation]) {
6109 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6110 }
6111 #endif
6112
6113 return index;
6114 }
6115
6116 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6117 if ((self = [super init]) != nil) {
6118 database_ = database;
6119 title_ = [title copy];
6120 [[self navigationItem] setTitle:title_];
6121
6122 #if TryIndexedCollation
6123 if ([[self class] hasIndexedCollation])
6124 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6125 else
6126 #endif
6127 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6128
6129 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6130
6131 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6132 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6133
6134 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6135 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6136 [list_ setRowHeight:73];
6137 [[self view] addSubview:list_];
6138
6139 [list_ setDataSource:self];
6140 [list_ setDelegate:self];
6141 } return self;
6142 }
6143
6144 - (void) setDelegate:(id)delegate {
6145 delegate_ = delegate;
6146 }
6147
6148 - (bool) hasPackage:(Package *)package {
6149 return true;
6150 }
6151
6152 - (void) reloadData {
6153 [super reloadData];
6154
6155 era_ = [database_ era];
6156 NSArray *packages = [database_ packages];
6157
6158 [packages_ removeAllObjects];
6159 [sections_ removeAllObjects];
6160
6161 _profile(PackageTable$reloadData$Filter)
6162 for (Package *package in packages)
6163 if ([self hasPackage:package])
6164 [packages_ addObject:package];
6165 _end
6166
6167 [indices_ removeAllObjects];
6168
6169 Section *section = nil;
6170
6171 #if TryIndexedCollation
6172 if ([[self class] hasIndexedCollation]) {
6173 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6174 NSArray *titles = [collation sectionIndexTitles];
6175 int secidx = -1;
6176
6177 _profile(PackageTable$reloadData$Section)
6178 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6179 Package *package;
6180 int index;
6181
6182 _profile(PackageTable$reloadData$Section$Package)
6183 package = [packages_ objectAtIndex:offset];
6184 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6185 _end
6186
6187 while (secidx < index) {
6188 secidx += 1;
6189
6190 _profile(PackageTable$reloadData$Section$Allocate)
6191 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6192 _end
6193
6194 _profile(PackageTable$reloadData$Section$Add)
6195 [sections_ addObject:section];
6196 _end
6197 }
6198
6199 [section addToCount];
6200 }
6201 _end
6202 } else
6203 #endif
6204 {
6205 [index_ removeAllObjects];
6206
6207 _profile(PackageTable$reloadData$Section)
6208 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6209 Package *package;
6210 unichar index;
6211
6212 _profile(PackageTable$reloadData$Section$Package)
6213 package = [packages_ objectAtIndex:offset];
6214 index = [package index];
6215 _end
6216
6217 if (section == nil || [section index] != index) {
6218 _profile(PackageTable$reloadData$Section$Allocate)
6219 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6220 _end
6221
6222 [index_ addObject:[section name]];
6223 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6224
6225 _profile(PackageTable$reloadData$Section$Add)
6226 [sections_ addObject:section];
6227 _end
6228 }
6229
6230 [section addToCount];
6231 }
6232 _end
6233 }
6234
6235 _profile(PackageTable$reloadData$List)
6236 [list_ reloadData];
6237 _end
6238 }
6239
6240 - (void) resetCursor {
6241 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6242 }
6243
6244 @end
6245 /* }}} */
6246 /* Filtered Package List Controller {{{ */
6247 @interface FilteredPackageListController : PackageListController {
6248 SEL filter_;
6249 IMP imp_;
6250 id object_;
6251 }
6252
6253 - (void) setObject:(id)object;
6254 - (void) setObject:(id)object forFilter:(SEL)filter;
6255
6256 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6257
6258 @end
6259
6260 @implementation FilteredPackageListController
6261
6262 - (void) dealloc {
6263 if (object_ != nil)
6264 [object_ release];
6265 [super dealloc];
6266 }
6267
6268 - (void) setFilter:(SEL)filter {
6269 filter_ = filter;
6270
6271 /* XXX: this is an unsafe optimization of doomy hell */
6272 Method method(class_getInstanceMethod([Package class], filter));
6273 _assert(method != NULL);
6274 imp_ = method_getImplementation(method);
6275 _assert(imp_ != NULL);
6276 }
6277
6278 - (void) setObject:(id)object {
6279 if (object_ != nil)
6280 [object_ release];
6281 if (object == nil)
6282 object_ = nil;
6283 else
6284 object_ = [object retain];
6285 }
6286
6287 - (void) setObject:(id)object forFilter:(SEL)filter {
6288 [self setFilter:filter];
6289 [self setObject:object];
6290 }
6291
6292 - (bool) hasPackage:(Package *)package {
6293 _profile(FilteredPackageTable$hasPackage)
6294 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6295 _end
6296 }
6297
6298 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6299 if ((self = [super initWithDatabase:database title:title]) != nil) {
6300 [self setFilter:filter];
6301 [self setObject:object];
6302 } return self;
6303 }
6304
6305 @end
6306 /* }}} */
6307
6308 /* Home Controller {{{ */
6309 @interface HomeController : CYBrowserController {
6310 }
6311
6312 @end
6313
6314 @implementation HomeController
6315
6316 + (BOOL) shouldHideNavigationBar {
6317 return NO;
6318 }
6319
6320 - (NSURL *) navigationURL {
6321 return [NSURL URLWithString:@"cydia://home"];
6322 }
6323
6324 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6325 [super _setMoreHeaders:request];
6326
6327 if (ChipID_ != nil)
6328 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6329 if (UniqueID_ != nil)
6330 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6331 if (PLMN_ != nil)
6332 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6333 }
6334
6335 - (void) aboutButtonClicked {
6336 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6337
6338 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6339 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6340 [alert setCancelButtonIndex:0];
6341
6342 [alert setMessage:
6343 @"Copyright (C) 2008-2011\n"
6344 "Jay Freeman (saurik)\n"
6345 "saurik@saurik.com\n"
6346 "http://www.saurik.com/"
6347 ];
6348
6349 [alert show];
6350 }
6351
6352 - (void) viewWillDisappear:(BOOL)animated {
6353 [super viewWillDisappear:animated];
6354
6355 if ([[self class] shouldHideNavigationBar])
6356 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6357 }
6358
6359 - (void) viewWillAppear:(BOOL)animated {
6360 if (![self hasLoaded])
6361 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6362
6363 [super viewWillAppear:animated];
6364
6365 if ([[self class] shouldHideNavigationBar])
6366 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6367 }
6368
6369 - (void) viewDidLoad {
6370 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6371 initWithTitle:UCLocalize("ABOUT")
6372 style:UIBarButtonItemStylePlain
6373 target:self
6374 action:@selector(aboutButtonClicked)
6375 ] autorelease]];
6376 }
6377
6378 @end
6379 /* }}} */
6380 /* Manage Controller {{{ */
6381 @interface ManageController : CYBrowserController {
6382 }
6383
6384 - (void) queueStatusDidChange;
6385
6386 @end
6387
6388 @implementation ManageController
6389
6390 - (NSURL *) navigationURL {
6391 return [NSURL URLWithString:@"cydia://manage"];
6392 }
6393
6394 - (void) viewWillAppear:(BOOL)animated {
6395 if (![self hasLoaded])
6396 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6397
6398 [super viewWillAppear:animated];
6399 }
6400
6401 - (void) viewDidLoad {
6402 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6403 initWithTitle:UCLocalize("SETTINGS")
6404 style:UIBarButtonItemStylePlain
6405 target:self
6406 action:@selector(settingsButtonClicked)
6407 ] autorelease]];
6408
6409 [self queueStatusDidChange];
6410 }
6411
6412 - (void) settingsButtonClicked {
6413 [delegate_ showSettings];
6414 }
6415
6416 #if !AlwaysReload
6417 - (void) queueButtonClicked {
6418 [delegate_ queue];
6419 }
6420
6421 - (void) applyLoadingTitle {
6422 // Disable "Loading" title.
6423 }
6424
6425 - (void) applyRightButton {
6426 // Disable right button.
6427 }
6428 #endif
6429
6430 - (void) queueStatusDidChange {
6431 #if !AlwaysReload
6432 if (!IsWildcat_ && Queuing_) {
6433 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6434 initWithTitle:UCLocalize("QUEUE")
6435 style:UIBarButtonItemStyleDone
6436 target:self
6437 action:@selector(queueButtonClicked)
6438 ] autorelease]];
6439 } else {
6440 [[self navigationItem] setRightBarButtonItem:nil];
6441 }
6442 #endif
6443 }
6444
6445 - (bool) isLoading {
6446 // Never show as loading.
6447 return false;
6448 }
6449
6450 @end
6451 /* }}} */
6452
6453 /* Refresh Bar {{{ */
6454 @interface RefreshBar : UINavigationBar {
6455 UIProgressIndicator *indicator_;
6456 UITextLabel *prompt_;
6457 UIProgressBar *progress_;
6458 UINavigationButton *cancel_;
6459 }
6460
6461 @end
6462
6463 @implementation RefreshBar
6464
6465 - (void) dealloc {
6466 [indicator_ release];
6467 [prompt_ release];
6468 [progress_ release];
6469 [cancel_ release];
6470 [super dealloc];
6471 }
6472
6473 - (void) positionViews {
6474 CGRect frame = [cancel_ frame];
6475 frame.size = [cancel_ sizeThatFits:frame.size];
6476 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6477 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6478 [cancel_ setFrame:frame];
6479
6480 CGSize prgsize = {75, 100};
6481 CGRect prgrect = {{
6482 [self frame].size.width - prgsize.width - 10,
6483 ([self frame].size.height - prgsize.height) / 2
6484 } , prgsize};
6485 [progress_ setFrame:prgrect];
6486
6487 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6488 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6489 CGRect indrect = {{indoffset, indoffset}, indsize};
6490 [indicator_ setFrame:indrect];
6491
6492 CGSize prmsize = {215, indsize.height + 4};
6493 CGRect prmrect = {{
6494 indoffset * 2 + indsize.width,
6495 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6496 }, prmsize};
6497 [prompt_ setFrame:prmrect];
6498 }
6499
6500 - (void) setFrame:(CGRect)frame {
6501 [super setFrame:frame];
6502 [self positionViews];
6503 }
6504
6505 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6506 if ((self = [super initWithFrame:frame]) != nil) {
6507 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6508
6509 [self setBarStyle:UIBarStyleBlack];
6510
6511 UIBarStyle barstyle([self _barStyle:NO]);
6512 bool ugly(barstyle == UIBarStyleDefault);
6513
6514 UIProgressIndicatorStyle style = ugly ?
6515 UIProgressIndicatorStyleMediumBrown :
6516 UIProgressIndicatorStyleMediumWhite;
6517
6518 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6519 [indicator_ setStyle:style];
6520 [indicator_ startAnimation];
6521 [self addSubview:indicator_];
6522
6523 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6524 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6525 [prompt_ setBackgroundColor:[UIColor clearColor]];
6526 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6527 [self addSubview:prompt_];
6528
6529 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6530 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6531 [progress_ setStyle:0];
6532 [self addSubview:progress_];
6533
6534 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6535 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6536 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6537 [cancel_ setBarStyle:barstyle];
6538
6539 [self positionViews];
6540 } return self;
6541 }
6542
6543 - (void) cancel {
6544 [cancel_ removeFromSuperview];
6545 }
6546
6547 - (void) start {
6548 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6549 [progress_ setProgress:0];
6550 [self addSubview:cancel_];
6551 }
6552
6553 - (void) stop {
6554 [cancel_ removeFromSuperview];
6555 }
6556
6557 - (void) setPrompt:(NSString *)prompt {
6558 [prompt_ setText:prompt];
6559 }
6560
6561 - (void) setProgress:(float)progress {
6562 [progress_ setProgress:progress];
6563 }
6564
6565 @end
6566 /* }}} */
6567
6568 @class CYNavigationController;
6569
6570 /* Cydia Tab Bar Controller {{{ */
6571 @interface CYTabBarController : UITabBarController <
6572 UITabBarControllerDelegate,
6573 ProgressDelegate
6574 > {
6575 _transient Database *database_;
6576 RefreshBar *refreshbar_;
6577
6578 bool dropped_;
6579 bool updating_;
6580 // XXX: ok, "updatedelegate_"?...
6581 _transient NSObject<CydiaDelegate> *updatedelegate_;
6582
6583 id root_;
6584 UIViewController *remembered_;
6585 _transient UIViewController *transient_;
6586 }
6587
6588 - (NSArray *) navigationURLCollection;
6589 - (void) dropBar:(BOOL)animated;
6590 - (void) beginUpdate;
6591 - (void) raiseBar:(BOOL)animated;
6592 - (BOOL) updating;
6593
6594 @end
6595
6596 @implementation CYTabBarController
6597
6598 - (void) setUnselectedViewController:(UIViewController *)transient {
6599 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6600 if (transient != nil) {
6601 if (transient_ == nil)
6602 remembered_ = [[controllers objectAtIndex:0] retain];
6603 transient_ = transient;
6604 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6605 [controllers replaceObjectAtIndex:0 withObject:transient_];
6606 [self setSelectedIndex:0];
6607 [self setViewControllers:controllers];
6608 [self concealTabBarSelection];
6609 } else if (remembered_ != nil) {
6610 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6611 transient_ = transient;
6612 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6613 [remembered_ release];
6614 remembered_ = nil;
6615 [self setViewControllers:controllers];
6616 [self revealTabBarSelection];
6617 }
6618 }
6619
6620 - (UIViewController *) unselectedViewController {
6621 return transient_;
6622 }
6623
6624 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6625 if ([self unselectedViewController])
6626 [self setUnselectedViewController:nil];
6627 }
6628
6629 - (NSArray *) navigationURLCollection {
6630 NSMutableArray *items([NSMutableArray array]);
6631
6632 // XXX: Should this deal with transient view controllers?
6633 for (id navigation in [self viewControllers]) {
6634 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6635 if (stack != nil)
6636 [items addObject:stack];
6637 }
6638
6639 return items;
6640 }
6641
6642 - (void) reloadData {
6643 for (CYViewController *controller in [self viewControllers])
6644 [controller reloadData];
6645
6646 [(CYNavigationController *)[self unselectedViewController] reloadData];
6647 }
6648
6649 - (void) dealloc {
6650 [refreshbar_ release];
6651 [[NSNotificationCenter defaultCenter] removeObserver:self];
6652
6653 [super dealloc];
6654 }
6655
6656 - (id) initWithDatabase:(Database *)database {
6657 if ((self = [super init]) != nil) {
6658 database_ = database;
6659 [self setDelegate:self];
6660
6661 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6662 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6663
6664 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6665 } return self;
6666 }
6667
6668 - (void) setUpdate:(NSDate *)date {
6669 [self beginUpdate];
6670 }
6671
6672 - (void) beginUpdate {
6673 [refreshbar_ start];
6674 [self dropBar:YES];
6675
6676 [updatedelegate_ retainNetworkActivityIndicator];
6677 updating_ = true;
6678
6679 [NSThread
6680 detachNewThreadSelector:@selector(performUpdate)
6681 toTarget:self
6682 withObject:nil
6683 ];
6684 }
6685
6686 - (void) performUpdate { _pooled
6687 Status status;
6688 status.setDelegate(self);
6689 [database_ updateWithStatus:status];
6690
6691 [self
6692 performSelectorOnMainThread:@selector(completeUpdate)
6693 withObject:nil
6694 waitUntilDone:NO
6695 ];
6696 }
6697
6698 - (void) stopUpdateWithSelector:(SEL)selector {
6699 updating_ = false;
6700 [updatedelegate_ releaseNetworkActivityIndicator];
6701
6702 [self raiseBar:YES];
6703 [refreshbar_ stop];
6704
6705 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6706 }
6707
6708 - (void) completeUpdate {
6709 if (!updating_)
6710 return;
6711 [self stopUpdateWithSelector:@selector(reloadData)];
6712 }
6713
6714 - (void) cancelUpdate {
6715 [self stopUpdateWithSelector:@selector(updateData)];
6716 }
6717
6718 - (void) cancelPressed {
6719 [self cancelUpdate];
6720 }
6721
6722 - (BOOL) updating {
6723 return updating_;
6724 }
6725
6726 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6727 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6728 }
6729
6730 - (void) startProgress {
6731 }
6732
6733 - (void) setProgressTitle:(NSString *)title {
6734 [self
6735 performSelectorOnMainThread:@selector(_setProgressTitle:)
6736 withObject:title
6737 waitUntilDone:YES
6738 ];
6739 }
6740
6741 - (bool) isCancelling:(size_t)received {
6742 return !updating_;
6743 }
6744
6745 - (void) setProgressPercent:(float)percent {
6746 [self
6747 performSelectorOnMainThread:@selector(_setProgressPercent:)
6748 withObject:[NSNumber numberWithFloat:percent]
6749 waitUntilDone:YES
6750 ];
6751 }
6752
6753 - (void) addProgressOutput:(NSString *)output {
6754 [self
6755 performSelectorOnMainThread:@selector(_addProgressOutput:)
6756 withObject:output
6757 waitUntilDone:YES
6758 ];
6759 }
6760
6761 - (void) _setProgressTitle:(NSString *)title {
6762 [refreshbar_ setPrompt:title];
6763 }
6764
6765 - (void) _setProgressPercent:(NSNumber *)percent {
6766 [refreshbar_ setProgress:[percent floatValue]];
6767 }
6768
6769 - (void) _addProgressOutput:(NSString *)output {
6770 }
6771
6772 - (void) setUpdateDelegate:(id)delegate {
6773 updatedelegate_ = delegate;
6774 }
6775
6776 - (CGFloat) statusBarHeight {
6777 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6778 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6779 } else {
6780 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6781 }
6782 }
6783
6784 - (UIView *) transitionView {
6785 if ([self respondsToSelector:@selector(_transitionView)])
6786 return [self _transitionView];
6787 else
6788 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6789 }
6790
6791 - (void) dropBar:(BOOL)animated {
6792 if (dropped_)
6793 return;
6794 dropped_ = true;
6795
6796 UIView *transition([self transitionView]);
6797 [[self view] addSubview:refreshbar_];
6798
6799 CGRect barframe([refreshbar_ frame]);
6800
6801 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6802 barframe.origin.y = [self statusBarHeight];
6803 else
6804 barframe.origin.y = 0;
6805
6806 [refreshbar_ setFrame:barframe];
6807
6808 if (animated)
6809 [UIView beginAnimations:nil context:NULL];
6810
6811 CGRect viewframe = [transition frame];
6812 viewframe.origin.y += barframe.size.height;
6813 viewframe.size.height -= barframe.size.height;
6814 [transition setFrame:viewframe];
6815
6816 if (animated)
6817 [UIView commitAnimations];
6818
6819 // Ensure bar has the proper width for our view, it might have changed
6820 barframe.size.width = viewframe.size.width;
6821 [refreshbar_ setFrame:barframe];
6822
6823 // XXX: fix Apple's layout bug
6824 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6825 }
6826
6827 - (void) raiseBar:(BOOL)animated {
6828 if (!dropped_)
6829 return;
6830 dropped_ = false;
6831
6832 UIView *transition([self transitionView]);
6833 [refreshbar_ removeFromSuperview];
6834
6835 CGRect barframe([refreshbar_ frame]);
6836
6837 if (animated)
6838 [UIView beginAnimations:nil context:NULL];
6839
6840 CGRect viewframe = [transition frame];
6841 viewframe.origin.y -= barframe.size.height;
6842 viewframe.size.height += barframe.size.height;
6843 [transition setFrame:viewframe];
6844
6845 if (animated)
6846 [UIView commitAnimations];
6847
6848 // XXX: fix Apple's layout bug
6849 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6850 }
6851
6852 #if 0
6853 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6854 // XXX: fix Apple's layout bug
6855 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6856 }
6857 #endif
6858
6859 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6860 bool dropped(dropped_);
6861
6862 if (dropped)
6863 [self raiseBar:NO];
6864
6865 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6866
6867 if (dropped)
6868 [self dropBar:NO];
6869
6870 // XXX: fix Apple's layout bug
6871 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6872 }
6873
6874 - (void) statusBarFrameChanged:(NSNotification *)notification {
6875 if (dropped_) {
6876 [self raiseBar:NO];
6877 [self dropBar:NO];
6878 }
6879 }
6880
6881 @end
6882 /* }}} */
6883 /* Cydia Navigation Controller {{{ */
6884 @interface CYNavigationController : UINavigationController {
6885 _transient Database *database_;
6886 _transient id<UINavigationControllerDelegate> delegate_;
6887 }
6888
6889 - (NSArray *) navigationURLCollection;
6890 - (id) initWithDatabase:(Database *)database;
6891 - (void) reloadData;
6892
6893 @end
6894
6895
6896 @implementation CYNavigationController
6897
6898 - (NSArray *) navigationURLCollection {
6899 NSMutableArray *stack([NSMutableArray array]);
6900
6901 for (CYViewController *controller in [self viewControllers]) {
6902 NSString *url = [[controller navigationURL] absoluteString];
6903 if (url != nil)
6904 [stack addObject:url];
6905 }
6906
6907 return stack;
6908 }
6909
6910 - (void) reloadData {
6911 for (CYViewController *page in [self viewControllers]) {
6912 // Only reload controllers that have already loaded.
6913 // This prevents a page from accidentally loading too
6914 // early if it hasn't been shown on the screen yet.
6915 if ([page hasLoaded])
6916 [page reloadData];
6917 }
6918 }
6919
6920 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6921 delegate_ = delegate;
6922 }
6923
6924 - (id) initWithDatabase:(Database *)database {
6925 if ((self = [super init]) != nil) {
6926 database_ = database;
6927 } return self;
6928 }
6929
6930 @end
6931 /* }}} */
6932
6933 /* Cydia:// Protocol {{{ */
6934 @interface CydiaURLProtocol : NSURLProtocol {
6935 }
6936
6937 @end
6938
6939 @implementation CydiaURLProtocol
6940
6941 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6942 NSURL *url([request URL]);
6943 if (url == nil)
6944 return NO;
6945 NSString *scheme([[url scheme] lowercaseString]);
6946 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6947 return NO;
6948 return YES;
6949 }
6950
6951 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6952 return request;
6953 }
6954
6955 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6956 id<NSURLProtocolClient> client([self client]);
6957 if (icon == nil)
6958 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6959 else {
6960 NSData *data(UIImagePNGRepresentation(icon));
6961
6962 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6963 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6964 [client URLProtocol:self didLoadData:data];
6965 [client URLProtocolDidFinishLoading:self];
6966 }
6967 }
6968
6969 - (void) startLoading {
6970 id<NSURLProtocolClient> client([self client]);
6971 NSURLRequest *request([self request]);
6972
6973 NSURL *url([request URL]);
6974 NSString *href([url absoluteString]);
6975
6976 NSString *path([href substringFromIndex:8]);
6977 NSRange slash([path rangeOfString:@"/"]);
6978
6979 NSString *command;
6980 if (slash.location == NSNotFound) {
6981 command = path;
6982 path = nil;
6983 } else {
6984 command = [path substringToIndex:slash.location];
6985 path = [path substringFromIndex:(slash.location + 1)];
6986 }
6987
6988 Database *database([Database sharedInstance]);
6989
6990 if ([command isEqualToString:@"package-icon"]) {
6991 if (path == nil)
6992 goto fail;
6993 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6994 Package *package([database packageWithName:path]);
6995 if (package == nil)
6996 goto fail;
6997 UIImage *icon([package icon]);
6998 [self _returnPNGWithImage:icon forRequest:request];
6999 } else if ([command isEqualToString:@"source-icon"]) {
7000 if (path == nil)
7001 goto fail;
7002 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7003 NSString *source(Simplify(path));
7004 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7005 if (icon == nil)
7006 icon = [UIImage applicationImageNamed:@"unknown.png"];
7007 [self _returnPNGWithImage:icon forRequest:request];
7008 } else if ([command isEqualToString:@"uikit-image"]) {
7009 if (path == nil)
7010 goto fail;
7011 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7012 UIImage *icon(_UIImageWithName(path));
7013 [self _returnPNGWithImage:icon forRequest:request];
7014 } else if ([command isEqualToString:@"section-icon"]) {
7015 if (path == nil)
7016 goto fail;
7017 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7018 NSString *section(Simplify(path));
7019 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7020 if (icon == nil)
7021 icon = [UIImage applicationImageNamed:@"unknown.png"];
7022 [self _returnPNGWithImage:icon forRequest:request];
7023 } else fail: {
7024 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7025 }
7026 }
7027
7028 - (void) stopLoading {
7029 }
7030
7031 @end
7032 /* }}} */
7033
7034 /* Section Controller {{{ */
7035 @interface SectionController : FilteredPackageListController {
7036 NSString *section_;
7037 }
7038
7039 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7040
7041 @end
7042
7043 @implementation SectionController
7044
7045 - (NSURL *) navigationURL {
7046 NSString *name = section_;
7047 if (name == nil)
7048 name = @"all";
7049
7050 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7051 }
7052
7053 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7054 NSString *title;
7055 if (name == nil)
7056 title = UCLocalize("ALL_PACKAGES");
7057 else if (![name isEqual:@""])
7058 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7059 else
7060 title = UCLocalize("NO_SECTION");
7061
7062 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7063 section_ = name;
7064 } return self;
7065 }
7066
7067 @end
7068 /* }}} */
7069 /* Sections Controller {{{ */
7070 @interface SectionsController : CYViewController <
7071 UITableViewDataSource,
7072 UITableViewDelegate
7073 > {
7074 _transient Database *database_;
7075 NSMutableArray *sections_;
7076 NSMutableArray *filtered_;
7077 UITableView *list_;
7078 BOOL editing_;
7079 }
7080
7081 - (id) initWithDatabase:(Database *)database;
7082 - (void) editButtonClicked;
7083
7084 @end
7085
7086 @implementation SectionsController
7087
7088 - (void) dealloc {
7089 [self releaseSubviews];
7090 [sections_ release];
7091 [filtered_ release];
7092
7093 [super dealloc];
7094 }
7095
7096 - (NSURL *) navigationURL {
7097 return [NSURL URLWithString:@"cydia://sections"];
7098 }
7099
7100 - (void) updateNavigationItem {
7101 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7102 if ([sections_ count] == 0) {
7103 [[self navigationItem] setRightBarButtonItem:nil];
7104 } else {
7105 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7106 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7107 target:self
7108 action:@selector(editButtonClicked)
7109 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7110 }
7111 }
7112
7113 - (BOOL) isEditing {
7114 return editing_;
7115 }
7116
7117 - (void) setEditing:(BOOL)editing {
7118 if ((editing_ = editing))
7119 [list_ reloadData];
7120 else
7121 [delegate_ updateData];
7122
7123 [self updateNavigationItem];
7124 }
7125
7126 - (void) viewDidAppear:(BOOL)animated {
7127 [super viewDidAppear:animated];
7128 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7129 }
7130
7131 - (void) viewWillDisappear:(BOOL)animated {
7132 [super viewWillDisappear:animated];
7133 if (editing_) [self setEditing:NO];
7134 }
7135
7136 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7137 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7138 return section;
7139 }
7140
7141 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7142 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7143 }
7144
7145 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7146 return 45.0f;
7147 }*/
7148
7149 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7150 static NSString *reuseIdentifier = @"SectionCell";
7151
7152 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7153 if (cell == nil)
7154 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7155
7156 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7157
7158 return cell;
7159 }
7160
7161 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7162 if (editing_)
7163 return;
7164
7165 Section *section = [self sectionAtIndexPath:indexPath];
7166
7167 SectionController *controller = [[[SectionController alloc]
7168 initWithDatabase:database_
7169 section:[section name]
7170 ] autorelease];
7171 [controller setDelegate:delegate_];
7172
7173 [[self navigationController] pushViewController:controller animated:YES];
7174 }
7175
7176 - (void) loadView {
7177 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7178
7179 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7180 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7181 [list_ setRowHeight:45.0f];
7182 [list_ setDataSource:self];
7183 [list_ setDelegate:self];
7184 [[self view] addSubview:list_];
7185 }
7186
7187 - (void) viewDidLoad {
7188 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7189 }
7190
7191 - (void) releaseSubviews {
7192 [list_ release];
7193 list_ = nil;
7194 }
7195
7196 - (id) initWithDatabase:(Database *)database {
7197 if ((self = [super init]) != nil) {
7198 database_ = database;
7199
7200 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7201 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7202 } return self;
7203 }
7204
7205 - (void) reloadData {
7206 [super reloadData];
7207
7208 NSArray *packages = [database_ packages];
7209
7210 [sections_ removeAllObjects];
7211 [filtered_ removeAllObjects];
7212
7213 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7214
7215 _trace();
7216 for (Package *package in packages) {
7217 NSString *name([package section]);
7218 NSString *key(name == nil ? @"" : name);
7219
7220 Section *section;
7221
7222 _profile(SectionsView$reloadData$Section)
7223 section = [sections objectForKey:key];
7224 if (section == nil) {
7225 _profile(SectionsView$reloadData$Section$Allocate)
7226 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7227 [sections setObject:section forKey:key];
7228 _end
7229 }
7230 _end
7231
7232 [section addToCount];
7233
7234 _profile(SectionsView$reloadData$Filter)
7235 if (![package valid] || ![package visible])
7236 continue;
7237 _end
7238
7239 [section addToRow];
7240 }
7241 _trace();
7242
7243 [sections_ addObjectsFromArray:[sections allValues]];
7244
7245 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7246
7247 for (Section *section in sections_) {
7248 size_t count([section row]);
7249 if (count == 0)
7250 continue;
7251
7252 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7253 [section setCount:count];
7254 [filtered_ addObject:section];
7255 }
7256
7257 [self updateNavigationItem];
7258 [list_ reloadData];
7259 _trace();
7260 }
7261
7262 - (void) editButtonClicked {
7263 [self setEditing:(!editing_)];
7264 }
7265
7266 @end
7267 /* }}} */
7268
7269 /* Changes Controller {{{ */
7270 @interface ChangesController : CYViewController <
7271 UITableViewDataSource,
7272 UITableViewDelegate
7273 > {
7274 _transient Database *database_;
7275 unsigned era_;
7276 CFMutableArrayRef packages_;
7277 NSMutableArray *sections_;
7278 UITableView *list_;
7279 unsigned upgrades_;
7280 BOOL hasSentFirstLoad_;
7281 }
7282
7283 - (id) initWithDatabase:(Database *)database;
7284
7285 @end
7286
7287 @implementation ChangesController
7288
7289 - (void) dealloc {
7290 [self releaseSubviews];
7291 CFRelease(packages_);
7292 [sections_ release];
7293
7294 [super dealloc];
7295 }
7296
7297 - (NSURL *) navigationURL {
7298 return [NSURL URLWithString:@"cydia://changes"];
7299 }
7300
7301 - (void) viewWillAppear:(BOOL)animated {
7302 // Loads after it appears, so don't load beforehand.
7303 loaded_ = YES;
7304 [super viewWillAppear:animated];
7305 }
7306
7307 - (void) viewDidAppear:(BOOL)animated {
7308 [super viewDidAppear:animated];
7309
7310 if (!hasSentFirstLoad_) {
7311 hasSentFirstLoad_ = YES;
7312 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7313 } else {
7314 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7315 }
7316 }
7317
7318 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7319 NSInteger count([sections_ count]);
7320 return count == 0 ? 1 : count;
7321 }
7322
7323 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7324 if ([sections_ count] == 0)
7325 return nil;
7326 return [[sections_ objectAtIndex:section] name];
7327 }
7328
7329 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7330 if ([sections_ count] == 0)
7331 return 0;
7332 return [[sections_ objectAtIndex:section] count];
7333 }
7334
7335 - (Package *) packageAtIndex:(NSUInteger)index {
7336 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7337 }
7338
7339 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7340 @synchronized (database_) {
7341 if ([database_ era] != era_)
7342 return nil;
7343
7344 NSUInteger sectionIndex([path section]);
7345 if (sectionIndex >= [sections_ count])
7346 return nil;
7347 Section *section([sections_ objectAtIndex:sectionIndex]);
7348 NSInteger row([path row]);
7349 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7350 } }
7351
7352 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7353 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7354 if (cell == nil)
7355 cell = [[[PackageCell alloc] init] autorelease];
7356 [cell setPackage:[self packageAtIndexPath:path]];
7357 return cell;
7358 }
7359
7360 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7361 Package *package([self packageAtIndexPath:path]);
7362 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7363 [view setDelegate:delegate_];
7364 [[self navigationController] pushViewController:view animated:YES];
7365 return path;
7366 }
7367
7368 - (void) refreshButtonClicked {
7369 [delegate_ beginUpdate];
7370 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7371 }
7372
7373 - (void) upgradeButtonClicked {
7374 [delegate_ distUpgrade];
7375 }
7376
7377 - (void) loadView {
7378 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7379
7380 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7381 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7382 [list_ setRowHeight:73];
7383 [list_ setDataSource:self];
7384 [list_ setDelegate:self];
7385 [[self view] addSubview:list_];
7386 }
7387
7388 - (void) viewDidLoad {
7389 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7390 }
7391
7392 - (void) releaseSubviews {
7393 [list_ release];
7394 list_ = nil;
7395 }
7396
7397 - (id) initWithDatabase:(Database *)database {
7398 if ((self = [super init]) != nil) {
7399 database_ = database;
7400
7401 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7402 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7403 } return self;
7404 }
7405
7406 - (void) _reloadPackages:(NSArray *)packages {
7407 CFRelease(packages_);
7408 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7409
7410 _trace();
7411 _profile(ChangesController$_reloadPackages$Filter)
7412 for (Package *package in packages)
7413 if ([package upgradableAndEssential:YES] || [package visible])
7414 CFArrayAppendValue(packages_, package);
7415 _end
7416 _trace();
7417 _profile(ChangesController$_reloadPackages$radixSort)
7418 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7419 _end
7420 _trace();
7421 }
7422
7423 - (void) reloadData {
7424 @synchronized (database_) {
7425 era_ = [database_ era];
7426 NSArray *packages = [database_ packages];
7427
7428 [sections_ removeAllObjects];
7429
7430 #if 1
7431 UIProgressHUD *hud([delegate_ addProgressHUD]);
7432 [hud setText:UCLocalize("LOADING")];
7433 //NSLog(@"HUD:%@::%@", delegate_, hud);
7434 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7435 [delegate_ removeProgressHUD:hud];
7436 #else
7437 [self _reloadPackages:packages];
7438 #endif
7439
7440 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7441 Section *ignored = nil;
7442 Section *section = nil;
7443 time_t last = 0;
7444
7445 upgrades_ = 0;
7446 bool unseens = false;
7447
7448 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7449
7450 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7451 Package *package = [self packageAtIndex:offset];
7452
7453 BOOL uae = [package upgradableAndEssential:YES];
7454
7455 if (!uae) {
7456 unseens = true;
7457 time_t seen([package seen]);
7458
7459 if (section == nil || last != seen) {
7460 last = seen;
7461
7462 NSString *name;
7463 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7464 [name autorelease];
7465
7466 _profile(ChangesController$reloadData$Allocate)
7467 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7468 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7469 [sections_ addObject:section];
7470 _end
7471 }
7472
7473 [section addToCount];
7474 } else if ([package ignored]) {
7475 if (ignored == nil) {
7476 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7477 }
7478 [ignored addToCount];
7479 } else {
7480 ++upgrades_;
7481 [upgradable addToCount];
7482 }
7483 }
7484 _trace();
7485
7486 CFRelease(formatter);
7487
7488 if (unseens) {
7489 Section *last = [sections_ lastObject];
7490 size_t count = [last count];
7491 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7492 [sections_ removeLastObject];
7493 }
7494
7495 if ([ignored count] != 0)
7496 [sections_ insertObject:ignored atIndex:0];
7497 if (upgrades_ != 0)
7498 [sections_ insertObject:upgradable atIndex:0];
7499
7500 [list_ reloadData];
7501
7502 if (upgrades_ > 0)
7503 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7504 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7505 style:UIBarButtonItemStylePlain
7506 target:self
7507 action:@selector(upgradeButtonClicked)
7508 ] autorelease]];
7509
7510 if (![delegate_ updating])
7511 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7512 initWithTitle:UCLocalize("REFRESH")
7513 style:UIBarButtonItemStylePlain
7514 target:self
7515 action:@selector(refreshButtonClicked)
7516 ] autorelease]];
7517
7518 PrintTimes();
7519 } }
7520
7521 @end
7522 /* }}} */
7523 /* Search Controller {{{ */
7524 @interface SearchController : FilteredPackageListController <
7525 UISearchBarDelegate
7526 > {
7527 UISearchBar *search_;
7528 BOOL searchloaded_;
7529 }
7530
7531 - (id) initWithDatabase:(Database *)database;
7532 - (void) setSearchTerm:(NSString *)term;
7533 - (void) reloadData;
7534
7535 @end
7536
7537 @implementation SearchController
7538
7539 - (void) dealloc {
7540 [search_ release];
7541 [super dealloc];
7542 }
7543
7544 - (NSURL *) navigationURL {
7545 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7546 return [NSURL URLWithString:@"cydia://search"];
7547 else
7548 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7549 }
7550
7551 - (void) setSearchTerm:(NSString *)searchTerm {
7552 [search_ setText:searchTerm];
7553 [self reloadData];
7554 }
7555
7556 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7557 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7558 [search_ resignFirstResponder];
7559 [self reloadData];
7560 }
7561
7562 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7563 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7564 [self reloadData];
7565 }
7566
7567 - (id) initWithDatabase:(Database *)database {
7568 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7569 search_ = [[UISearchBar alloc] init];
7570 } return self;
7571 }
7572
7573 - (void) viewDidAppear:(BOOL)animated {
7574 [super viewDidAppear:animated];
7575
7576 if (!searchloaded_) {
7577 searchloaded_ = YES;
7578 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7579 [search_ layoutSubviews];
7580 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7581
7582 UITextField *textField;
7583 if ([search_ respondsToSelector:@selector(searchField)])
7584 textField = [search_ searchField];
7585 else
7586 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7587
7588 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7589 [search_ setDelegate:self];
7590 [textField setEnablesReturnKeyAutomatically:NO];
7591 [[self navigationItem] setTitleView:textField];
7592 }
7593 }
7594
7595 - (void) reloadData {
7596 [self setObject:[search_ text]];
7597 [super reloadData];
7598 [self resetCursor];
7599 }
7600
7601 - (void) didSelectPackage:(Package *)package {
7602 [search_ resignFirstResponder];
7603 [super didSelectPackage:package];
7604 }
7605
7606 @end
7607 /* }}} */
7608 /* Package Settings Controller {{{ */
7609 @interface PackageSettingsController : CYViewController <
7610 UITableViewDataSource,
7611 UITableViewDelegate
7612 > {
7613 _transient Database *database_;
7614 NSString *name_;
7615 Package *package_;
7616 UITableView *table_;
7617 UISwitch *subscribedSwitch_;
7618 UISwitch *ignoredSwitch_;
7619 UITableViewCell *subscribedCell_;
7620 UITableViewCell *ignoredCell_;
7621 }
7622
7623 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7624
7625 @end
7626
7627 @implementation PackageSettingsController
7628
7629 - (void) dealloc {
7630 [self releaseSubviews];
7631 [name_ release];
7632 [package_ release];
7633
7634 [super dealloc];
7635 }
7636
7637 - (NSURL *) navigationURL {
7638 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7639 }
7640
7641 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7642 if (package_ == nil)
7643 return 0;
7644
7645 if ([package_ installed] == nil)
7646 return 1;
7647 else
7648 return 2;
7649 }
7650
7651 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7652 if (package_ == nil)
7653 return 0;
7654
7655 // both sections contain just one item right now.
7656 return 1;
7657 }
7658
7659 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7660 return nil;
7661 }
7662
7663 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7664 if (section == 0)
7665 return UCLocalize("SHOW_ALL_CHANGES_EX");
7666 else
7667 return UCLocalize("IGNORE_UPGRADES_EX");
7668 }
7669
7670 - (void) onSubscribed:(id)control {
7671 bool value([control isOn]);
7672 if (package_ == nil)
7673 return;
7674 if ([package_ setSubscribed:value])
7675 [delegate_ updateData];
7676 }
7677
7678 - (void) _updateIgnored {
7679 const char *package([name_ UTF8String]);
7680 bool on([ignoredSwitch_ isOn]);
7681
7682 pid_t pid(ExecFork());
7683 if (pid == 0) {
7684 FILE *dpkg(popen("dpkg --set-selections", "w"));
7685 fwrite(package, strlen(package), 1, dpkg);
7686
7687 if (on)
7688 fwrite(" hold\n", 6, 1, dpkg);
7689 else
7690 fwrite(" install\n", 9, 1, dpkg);
7691
7692 pclose(dpkg);
7693
7694 exit(0);
7695 _assert(false);
7696 }
7697
7698 _forever {
7699 int status;
7700 int result(waitpid(pid, &status, 0));
7701
7702 if (result != -1) {
7703 _assert(result == pid);
7704 break;
7705 }
7706 }
7707 }
7708
7709 - (void) onIgnored:(id)control {
7710 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7711 [invocation setTarget:self];
7712 [invocation setSelector:@selector(_updateIgnored)];
7713
7714 [delegate_ reloadDataWithInvocation:invocation];
7715 }
7716
7717 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7718 if (package_ == nil)
7719 return nil;
7720
7721 switch ([indexPath section]) {
7722 case 0: return subscribedCell_;
7723 case 1: return ignoredCell_;
7724
7725 _nodefault
7726 }
7727
7728 return nil;
7729 }
7730
7731 - (void) loadView {
7732 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7733
7734 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7735 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7736 [table_ setDataSource:self];
7737 [table_ setDelegate:self];
7738 [[self view] addSubview:table_];
7739
7740 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7741 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7742 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7743
7744 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7745 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7746 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7747
7748 subscribedCell_ = [[UITableViewCell alloc] init];
7749 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7750 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7751 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7752
7753 ignoredCell_ = [[UITableViewCell alloc] init];
7754 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7755 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7756 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7757 }
7758
7759 - (void) viewDidLoad {
7760 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7761 }
7762
7763 - (void) releaseSubviews {
7764 [ignoredCell_ release];
7765 ignoredCell_ = nil;
7766
7767 [subscribedCell_ release];
7768 subscribedCell_ = nil;
7769
7770 [table_ release];
7771 table_ = nil;
7772
7773 [ignoredSwitch_ release];
7774 ignoredSwitch_ = nil;
7775
7776 [subscribedSwitch_ release];
7777 subscribedSwitch_ = nil;
7778 }
7779
7780 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7781 if ((self = [super init]) != nil) {
7782 database_ = database;
7783 name_ = [package retain];
7784 } return self;
7785 }
7786
7787 - (void) reloadData {
7788 [super reloadData];
7789
7790 if (package_ != nil)
7791 [package_ autorelease];
7792 package_ = [database_ packageWithName:name_];
7793
7794 if (package_ != nil) {
7795 package_ = [package_ retain];
7796 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7797 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7798 } // XXX: what now, G?
7799
7800 [table_ reloadData];
7801 }
7802
7803 @end
7804 /* }}} */
7805
7806 /* Installed Controller {{{ */
7807 @interface InstalledController : FilteredPackageListController {
7808 BOOL expert_;
7809 }
7810
7811 - (id) initWithDatabase:(Database *)database;
7812
7813 - (void) updateRoleButton;
7814 - (void) queueStatusDidChange;
7815
7816 @end
7817
7818 @implementation InstalledController
7819
7820 - (void) dealloc {
7821 [super dealloc];
7822 }
7823
7824 - (NSURL *) navigationURL {
7825 return [NSURL URLWithString:@"cydia://installed"];
7826 }
7827
7828 - (id) initWithDatabase:(Database *)database {
7829 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7830 [self updateRoleButton];
7831 [self queueStatusDidChange];
7832 } return self;
7833 }
7834
7835 #if !AlwaysReload
7836 - (void) queueButtonClicked {
7837 [delegate_ queue];
7838 }
7839 #endif
7840
7841 - (void) queueStatusDidChange {
7842 #if !AlwaysReload
7843 if (IsWildcat_) {
7844 if (Queuing_) {
7845 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7846 initWithTitle:UCLocalize("QUEUE")
7847 style:UIBarButtonItemStyleDone
7848 target:self
7849 action:@selector(queueButtonClicked)
7850 ] autorelease]];
7851 } else {
7852 [[self navigationItem] setLeftBarButtonItem:nil];
7853 }
7854 }
7855 #endif
7856 }
7857
7858 - (void) updateRoleButton {
7859 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7860 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7861 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7862 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7863 target:self
7864 action:@selector(roleButtonClicked)
7865 ] autorelease]];
7866 }
7867
7868 - (void) roleButtonClicked {
7869 [self setObject:[NSNumber numberWithBool:expert_]];
7870 [self reloadData];
7871 expert_ = !expert_;
7872
7873 [self updateRoleButton];
7874 }
7875
7876 @end
7877 /* }}} */
7878
7879 /* Source Cell {{{ */
7880 @interface SourceCell : CYTableViewCell <
7881 ContentDelegate
7882 > {
7883 UIImage *icon_;
7884 NSString *origin_;
7885 NSString *label_;
7886 }
7887
7888 - (void) setSource:(Source *)source;
7889
7890 @end
7891
7892 @implementation SourceCell
7893
7894 - (void) clearSource {
7895 [icon_ release];
7896 [origin_ release];
7897 [label_ release];
7898
7899 icon_ = nil;
7900 origin_ = nil;
7901 label_ = nil;
7902 }
7903
7904 - (void) setSource:(Source *)source {
7905 [self clearSource];
7906
7907 if (icon_ == nil)
7908 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7909 if (icon_ == nil)
7910 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7911 icon_ = [icon_ retain];
7912
7913 origin_ = [[source name] retain];
7914 label_ = [[source uri] retain];
7915
7916 [content_ setNeedsDisplay];
7917 }
7918
7919 - (void) dealloc {
7920 [self clearSource];
7921 [super dealloc];
7922 }
7923
7924 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7925 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7926 UIView *content([self contentView]);
7927 CGRect bounds([content bounds]);
7928
7929 content_ = [[ContentView alloc] initWithFrame:bounds];
7930 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7931 [content_ setBackgroundColor:[UIColor whiteColor]];
7932 [content addSubview:content_];
7933
7934 [content_ setDelegate:self];
7935 [content_ setOpaque:YES];
7936 } return self;
7937 }
7938
7939 - (NSString *) accessibilityLabel {
7940 return label_;
7941 }
7942
7943 - (void) drawContentRect:(CGRect)rect {
7944 bool highlighted(highlighted_);
7945 float width(rect.size.width);
7946
7947 if (icon_ != nil)
7948 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7949
7950 if (highlighted)
7951 UISetColor(White_);
7952
7953 if (!highlighted)
7954 UISetColor(Black_);
7955 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7956
7957 if (!highlighted)
7958 UISetColor(Blue_);
7959 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7960 }
7961
7962 @end
7963 /* }}} */
7964 /* Source Controller {{{ */
7965 @interface SourceController : FilteredPackageListController {
7966 _transient Source *source_;
7967 NSString *key_;
7968 }
7969
7970 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7971
7972 @end
7973
7974 @implementation SourceController
7975
7976 - (NSURL *) navigationURL {
7977 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7978 }
7979
7980 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7981 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7982 source_ = source;
7983 key_ = [[source key] retain];
7984 } return self;
7985 }
7986
7987 - (void) reloadData {
7988 source_ = [database_ sourceWithKey:key_];
7989 [key_ release];
7990 key_ = [[source_ key] retain];
7991 [self setObject:source_];
7992 [[self navigationItem] setTitle:[source_ label]];
7993
7994 [super reloadData];
7995 }
7996
7997 @end
7998 /* }}} */
7999 /* Sources Controller {{{ */
8000 @interface SourcesController : CYViewController <
8001 UITableViewDataSource,
8002 UITableViewDelegate
8003 > {
8004 _transient Database *database_;
8005 UITableView *list_;
8006 NSMutableArray *sources_;
8007 int offset_;
8008
8009 NSString *href_;
8010 UIProgressHUD *hud_;
8011 NSError *error_;
8012
8013 //NSURLConnection *installer_;
8014 NSURLConnection *trivial_;
8015 NSURLConnection *trivial_bz2_;
8016 NSURLConnection *trivial_gz_;
8017 //NSURLConnection *automatic_;
8018
8019 BOOL cydia_;
8020 }
8021
8022 - (id) initWithDatabase:(Database *)database;
8023 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8024
8025 @end
8026
8027 @implementation SourcesController
8028
8029 - (void) _releaseConnection:(NSURLConnection *)connection {
8030 if (connection != nil) {
8031 [connection cancel];
8032 //[connection setDelegate:nil];
8033 [connection release];
8034 }
8035 }
8036
8037 - (void) dealloc {
8038 [self releaseSubviews];
8039
8040 [href_ release];
8041 [hud_ release];
8042 [error_ release];
8043
8044 //[self _releaseConnection:installer_];
8045 [self _releaseConnection:trivial_];
8046 [self _releaseConnection:trivial_gz_];
8047 [self _releaseConnection:trivial_bz2_];
8048 //[self _releaseConnection:automatic_];
8049
8050 [sources_ release];
8051 [super dealloc];
8052 }
8053
8054 - (NSURL *) navigationURL {
8055 return [NSURL URLWithString:@"cydia://sources"];
8056 }
8057
8058 - (void) viewDidAppear:(BOOL)animated {
8059 [super viewDidAppear:animated];
8060 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8061 }
8062
8063 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8064 return offset_ == 0 ? 1 : 2;
8065 }
8066
8067 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8068 switch (section + (offset_ == 0 ? 1 : 0)) {
8069 case 0: return UCLocalize("ENTERED_BY_USER");
8070 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8071
8072 _nodefault
8073 }
8074 }
8075
8076 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8077 int count = [sources_ count];
8078 switch (section) {
8079 case 0: return (offset_ == 0 ? count : offset_);
8080 case 1: return count - offset_;
8081
8082 _nodefault
8083 }
8084 }
8085
8086 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8087 unsigned idx = 0;
8088 switch (indexPath.section) {
8089 case 0: idx = indexPath.row; break;
8090 case 1: idx = indexPath.row + offset_; break;
8091
8092 _nodefault
8093 }
8094 return [sources_ objectAtIndex:idx];
8095 }
8096
8097 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8098 static NSString *cellIdentifier = @"SourceCell";
8099
8100 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8101 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8102 [cell setSource:[self sourceAtIndexPath:indexPath]];
8103 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8104
8105 return cell;
8106 }
8107
8108 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8109 Source *source = [self sourceAtIndexPath:indexPath];
8110
8111 SourceController *controller = [[[SourceController alloc]
8112 initWithDatabase:database_
8113 source:source
8114 ] autorelease];
8115
8116 [controller setDelegate:delegate_];
8117
8118 [[self navigationController] pushViewController:controller animated:YES];
8119 }
8120
8121 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8122 Source *source = [self sourceAtIndexPath:indexPath];
8123 return [source record] != nil;
8124 }
8125
8126 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8127 Source *source = [self sourceAtIndexPath:indexPath];
8128 [Sources_ removeObjectForKey:[source key]];
8129 [delegate_ syncData];
8130 }
8131
8132 - (void) complete {
8133 [delegate_ addTrivialSource:href_];
8134 [delegate_ syncData];
8135 }
8136
8137 - (NSString *) getWarning {
8138 NSString *href(href_);
8139 NSRange colon([href rangeOfString:@"://"]);
8140 if (colon.location != NSNotFound)
8141 href = [href substringFromIndex:(colon.location + 3)];
8142 href = [href stringByAddingPercentEscapes];
8143 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8144 href = [href stringByCachingURLWithCurrentCDN];
8145
8146 NSURL *url([NSURL URLWithString:href]);
8147
8148 NSStringEncoding encoding;
8149 NSError *error(nil);
8150
8151 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8152 return [warning length] == 0 ? nil : warning;
8153 return nil;
8154 }
8155
8156 - (void) _endConnection:(NSURLConnection *)connection {
8157 // XXX: the memory management in this method is horribly awkward
8158
8159 NSURLConnection **field = NULL;
8160 if (connection == trivial_)
8161 field = &trivial_;
8162 else if (connection == trivial_bz2_)
8163 field = &trivial_bz2_;
8164 else if (connection == trivial_gz_)
8165 field = &trivial_gz_;
8166 _assert(field != NULL);
8167 [connection release];
8168 *field = nil;
8169
8170 if (
8171 trivial_ == nil &&
8172 trivial_bz2_ == nil &&
8173 trivial_gz_ == nil
8174 ) {
8175 bool defer(false);
8176
8177 if (cydia_) {
8178 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8179 defer = true;
8180
8181 UIAlertView *alert = [[[UIAlertView alloc]
8182 initWithTitle:UCLocalize("SOURCE_WARNING")
8183 message:warning
8184 delegate:self
8185 cancelButtonTitle:UCLocalize("CANCEL")
8186 otherButtonTitles:
8187 UCLocalize("ADD_ANYWAY"),
8188 nil
8189 ] autorelease];
8190
8191 [alert setContext:@"warning"];
8192 [alert setNumberOfRows:1];
8193 [alert show];
8194 } else
8195 [self complete];
8196 } else if (error_ != nil) {
8197 UIAlertView *alert = [[[UIAlertView alloc]
8198 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8199 message:[error_ localizedDescription]
8200 delegate:self
8201 cancelButtonTitle:UCLocalize("OK")
8202 otherButtonTitles:nil
8203 ] autorelease];
8204
8205 [alert setContext:@"urlerror"];
8206 [alert show];
8207 } else {
8208 UIAlertView *alert = [[[UIAlertView alloc]
8209 initWithTitle:UCLocalize("NOT_REPOSITORY")
8210 message:UCLocalize("NOT_REPOSITORY_EX")
8211 delegate:self
8212 cancelButtonTitle:UCLocalize("OK")
8213 otherButtonTitles:nil
8214 ] autorelease];
8215
8216 [alert setContext:@"trivial"];
8217 [alert show];
8218 }
8219
8220 [delegate_ setStatusBarShowsProgress:NO];
8221 [delegate_ removeProgressHUD:hud_];
8222
8223 [hud_ autorelease];
8224 hud_ = nil;
8225
8226 if (!defer) {
8227 [href_ release];
8228 href_ = nil;
8229 }
8230
8231 if (error_ != nil) {
8232 [error_ release];
8233 error_ = nil;
8234 }
8235 }
8236 }
8237
8238 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8239 switch ([response statusCode]) {
8240 case 200:
8241 cydia_ = YES;
8242 }
8243 }
8244
8245 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8246 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8247 if (error_ != nil)
8248 error_ = [error retain];
8249 [self _endConnection:connection];
8250 }
8251
8252 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8253 [self _endConnection:connection];
8254 }
8255
8256 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8257 NSMutableURLRequest *request = [NSMutableURLRequest
8258 requestWithURL:[NSURL URLWithString:href]
8259 cachePolicy:NSURLRequestUseProtocolCachePolicy
8260 timeoutInterval:120.0
8261 ];
8262
8263 [request setHTTPMethod:method];
8264
8265 if (Machine_ != NULL)
8266 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8267 if (UniqueID_ != nil)
8268 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8269 if (Role_ != nil)
8270 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8271
8272 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8273 }
8274
8275 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8276 NSString *context([alert context]);
8277
8278 if ([context isEqualToString:@"source"]) {
8279 switch (button) {
8280 case 1: {
8281 NSString *href = [[alert textField] text];
8282
8283 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8284
8285 if (![href hasSuffix:@"/"])
8286 href_ = [href stringByAppendingString:@"/"];
8287 else
8288 href_ = href;
8289 href_ = [href_ retain];
8290
8291 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8292 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8293 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8294 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8295
8296 cydia_ = false;
8297
8298 // XXX: this is stupid
8299 hud_ = [[delegate_ addProgressHUD] retain];
8300 [hud_ setText:UCLocalize("VERIFYING_URL")];
8301 } break;
8302
8303 case 0:
8304 break;
8305
8306 _nodefault
8307 }
8308
8309 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8310 } else if ([context isEqualToString:@"trivial"])
8311 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8312 else if ([context isEqualToString:@"urlerror"])
8313 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8314 else if ([context isEqualToString:@"warning"]) {
8315 switch (button) {
8316 case 1:
8317 [self complete];
8318 break;
8319
8320 case 0:
8321 break;
8322
8323 _nodefault
8324 }
8325
8326 [href_ release];
8327 href_ = nil;
8328
8329 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8330 }
8331 }
8332
8333 - (void) loadView {
8334 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8335
8336 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8337 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8338 [list_ setRowHeight:56];
8339 [list_ setDataSource:self];
8340 [list_ setDelegate:self];
8341 [[self view] addSubview:list_];
8342 }
8343
8344 - (void) viewDidLoad {
8345 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8346 [self updateButtonsForEditingStatus:NO animated:NO];
8347 }
8348
8349 - (void) releaseSubviews {
8350 [list_ release];
8351 list_ = nil;
8352 }
8353
8354 - (id) initWithDatabase:(Database *)database {
8355 if ((self = [super init]) != nil) {
8356 database_ = database;
8357 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8358 } return self;
8359 }
8360
8361 - (void) reloadData {
8362 [super reloadData];
8363
8364 pkgSourceList list;
8365 if (!list.ReadMainList())
8366 return;
8367
8368 [sources_ removeAllObjects];
8369 [sources_ addObjectsFromArray:[database_ sources]];
8370 _trace();
8371 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8372 _trace();
8373
8374 int count([sources_ count]);
8375 offset_ = 0;
8376 for (int i = 0; i != count; i++) {
8377 if ([[sources_ objectAtIndex:i] record] == nil)
8378 break;
8379 offset_++;
8380 }
8381
8382 [list_ setEditing:NO];
8383 [self updateButtonsForEditingStatus:NO animated:NO];
8384 [list_ reloadData];
8385 }
8386
8387 - (void) showAddSourcePrompt {
8388 UIAlertView *alert = [[[UIAlertView alloc]
8389 initWithTitle:UCLocalize("ENTER_APT_URL")
8390 message:nil
8391 delegate:self
8392 cancelButtonTitle:UCLocalize("CANCEL")
8393 otherButtonTitles:
8394 UCLocalize("ADD_SOURCE"),
8395 nil
8396 ] autorelease];
8397
8398 [alert setContext:@"source"];
8399 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8400
8401 [alert setNumberOfRows:1];
8402 [alert addTextFieldWithValue:@"http://" label:@""];
8403
8404 UITextInputTraits *traits = [[alert textField] textInputTraits];
8405 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8406 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8407 [traits setKeyboardType:UIKeyboardTypeURL];
8408 // XXX: UIReturnKeyDone
8409 [traits setReturnKeyType:UIReturnKeyNext];
8410
8411 [alert show];
8412 }
8413
8414 - (void) addButtonClicked {
8415 [self showAddSourcePrompt];
8416 }
8417
8418 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8419 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8420 initWithTitle:UCLocalize("ADD")
8421 style:UIBarButtonItemStylePlain
8422 target:self
8423 action:@selector(addButtonClicked)
8424 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8425
8426 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8427 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8428 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8429 target:self
8430 action:@selector(editButtonClicked)
8431 ] autorelease] animated:animated];
8432
8433 if (IsWildcat_ && !editing)
8434 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8435 initWithTitle:UCLocalize("SETTINGS")
8436 style:UIBarButtonItemStylePlain
8437 target:self
8438 action:@selector(settingsButtonClicked)
8439 ] autorelease]];
8440 }
8441
8442 - (void) settingsButtonClicked {
8443 [delegate_ showSettings];
8444 }
8445
8446 - (void) editButtonClicked {
8447 [list_ setEditing:![list_ isEditing] animated:YES];
8448
8449 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8450 }
8451
8452 @end
8453 /* }}} */
8454
8455 /* Settings Controller {{{ */
8456 @interface SettingsController : CYViewController <
8457 UITableViewDataSource,
8458 UITableViewDelegate
8459 > {
8460 _transient Database *database_;
8461 // XXX: ok, "roledelegate_"?...
8462 _transient id roledelegate_;
8463 UITableView *table_;
8464 UISegmentedControl *segment_;
8465 UIView *container_;
8466 }
8467
8468 - (void) showDoneButton;
8469 - (void) resizeSegmentedControl;
8470
8471 @end
8472
8473 @implementation SettingsController
8474
8475 - (void) dealloc {
8476 [self releaseSubviews];
8477
8478 [super dealloc];
8479 }
8480
8481 - (void) loadView {
8482 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8483
8484 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8485 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8486 [table_ setDelegate:self];
8487 [table_ setDataSource:self];
8488 [[self view] addSubview:table_];
8489
8490 NSArray *items = [NSArray arrayWithObjects:
8491 UCLocalize("USER"),
8492 UCLocalize("HACKER"),
8493 UCLocalize("DEVELOPER"),
8494 nil];
8495 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8496 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8497 [container_ addSubview:segment_];
8498 }
8499
8500 - (void) viewDidLoad {
8501 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8502
8503 int index = -1;
8504 if ([Role_ isEqualToString:@"User"]) index = 0;
8505 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8506 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8507 if (index != -1) {
8508 [segment_ setSelectedSegmentIndex:index];
8509 [self showDoneButton];
8510 }
8511
8512 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8513 [self resizeSegmentedControl];
8514 }
8515
8516 - (void) releaseSubviews {
8517 [table_ release];
8518 table_ = nil;
8519
8520 [segment_ release];
8521 segment_ = nil;
8522
8523 [container_ release];
8524 container_ = nil;
8525 }
8526
8527 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8528 if ((self = [super init]) != nil) {
8529 database_ = database;
8530 roledelegate_ = delegate;
8531 } return self;
8532 }
8533
8534 - (void) resizeSegmentedControl {
8535 CGFloat width = [[self view] frame].size.width;
8536 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8537 }
8538
8539 - (void) viewWillAppear:(BOOL)animated {
8540 [super viewWillAppear:animated];
8541
8542 [self resizeSegmentedControl];
8543 }
8544
8545 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8546 [self resizeSegmentedControl];
8547 }
8548
8549 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8550 [self resizeSegmentedControl];
8551 }
8552
8553 - (void) save {
8554 NSString *role(nil);
8555
8556 switch ([segment_ selectedSegmentIndex]) {
8557 case 0: role = @"User"; break;
8558 case 1: role = @"Hacker"; break;
8559 case 2: role = @"Developer"; break;
8560
8561 _nodefault
8562 }
8563
8564 if (![role isEqualToString:Role_]) {
8565 bool rolling(Role_ == nil);
8566 Role_ = role;
8567
8568 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8569 Role_, @"Role",
8570 nil];
8571
8572 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8573 Changed_ = true;
8574
8575 if (rolling)
8576 [roledelegate_ loadData];
8577 else
8578 [roledelegate_ updateData];
8579 }
8580 }
8581
8582 - (void) segmentChanged:(UISegmentedControl *)control {
8583 [self showDoneButton];
8584 }
8585
8586 - (void) saveAndClose {
8587 [self save];
8588
8589 [[self navigationItem] setRightBarButtonItem:nil];
8590 [[self navigationController] dismissModalViewControllerAnimated:YES];
8591 }
8592
8593 - (void) doneButtonClicked {
8594 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8595 [spinner startAnimating];
8596 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8597 [[self navigationItem] setRightBarButtonItem:spinItem];
8598
8599 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8600 }
8601
8602 - (void) showDoneButton {
8603 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8604 initWithTitle:UCLocalize("DONE")
8605 style:UIBarButtonItemStyleDone
8606 target:self
8607 action:@selector(doneButtonClicked)
8608 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8609 }
8610
8611 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8612 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8613 return 6;
8614 }
8615
8616 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8617 return 0; // :(
8618 }
8619
8620 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8621 return nil; // This method is required by the protocol.
8622 }
8623
8624 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8625 if (section == 1)
8626 return UCLocalize("ROLE_EX");
8627 if (section == 4)
8628 return [NSString stringWithFormat:
8629 @"%@: %@\n%@: %@\n%@: %@",
8630 UCLocalize("USER"), UCLocalize("USER_EX"),
8631 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8632 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8633 ];
8634 else return nil;
8635 }
8636
8637 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8638 return section == 3 ? 44.0f : 0;
8639 }
8640
8641 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8642 return section == 3 ? container_ : nil;
8643 }
8644
8645 - (void) reloadData {
8646 [super reloadData];
8647 [table_ reloadData];
8648 }
8649
8650 @end
8651 /* }}} */
8652 /* Stash Controller {{{ */
8653 @interface StashController : CYViewController {
8654 UIActivityIndicatorView *spinner_;
8655 UILabel *status_;
8656 UILabel *caption_;
8657 }
8658
8659 @end
8660
8661 @implementation StashController
8662
8663 - (void) dealloc {
8664 [self releaseSubviews];
8665
8666 [super dealloc];
8667 }
8668
8669 - (void) loadView {
8670 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8671 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8672
8673 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8674 CGRect spinrect = [spinner_ frame];
8675 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8676 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8677 [spinner_ setFrame:spinrect];
8678 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8679 [[self view] addSubview:spinner_];
8680 [spinner_ startAnimating];
8681
8682 CGRect captrect;
8683 captrect.size.width = [[self view] frame].size.width;
8684 captrect.size.height = 40.0f;
8685 captrect.origin.x = 0;
8686 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8687 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8688 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8689 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8690 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8691 [caption_ setTextColor:[UIColor whiteColor]];
8692 [caption_ setBackgroundColor:[UIColor clearColor]];
8693 [caption_ setShadowColor:[UIColor blackColor]];
8694 [caption_ setTextAlignment:UITextAlignmentCenter];
8695 [[self view] addSubview:caption_];
8696
8697 CGRect statusrect;
8698 statusrect.size.width = [[self view] frame].size.width;
8699 statusrect.size.height = 30.0f;
8700 statusrect.origin.x = 0;
8701 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8702 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8703 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8704 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8705 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8706 [status_ setTextColor:[UIColor whiteColor]];
8707 [status_ setBackgroundColor:[UIColor clearColor]];
8708 [status_ setShadowColor:[UIColor blackColor]];
8709 [status_ setTextAlignment:UITextAlignmentCenter];
8710 [[self view] addSubview:status_];
8711 }
8712
8713 - (void) releaseSubviews {
8714 [spinner_ release];
8715 spinner_ = nil;
8716
8717 [status_ release];
8718 status_ = nil;
8719
8720 [caption_ release];
8721 caption_ = nil;
8722 }
8723
8724 @end
8725 /* }}} */
8726
8727 @interface Cydia : UIApplication <
8728 ConfirmationControllerDelegate,
8729 ProgressControllerDelegate,
8730 CydiaDelegate,
8731 UINavigationControllerDelegate,
8732 UITabBarControllerDelegate
8733 > {
8734 // XXX: evaluate all fields for _transient
8735
8736 UIWindow *window_;
8737 CYTabBarController *tabbar_;
8738
8739 NSMutableArray *essential_;
8740 NSMutableArray *broken_;
8741
8742 Database *database_;
8743
8744 NSURL *starturl_;
8745
8746 unsigned locked_;
8747 unsigned activity_;
8748
8749 StashController *stash_;
8750
8751 bool loaded_;
8752 }
8753
8754 - (void) loadData;
8755
8756 @end
8757
8758 @implementation Cydia
8759
8760 - (void) beginUpdate {
8761 [tabbar_ beginUpdate];
8762 }
8763
8764 - (BOOL) updating {
8765 return [tabbar_ updating];
8766 }
8767
8768 - (void) _loaded {
8769 if ([broken_ count] != 0) {
8770 int count = [broken_ count];
8771
8772 UIAlertView *alert = [[[UIAlertView alloc]
8773 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8774 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8775 delegate:self
8776 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8777 otherButtonTitles:
8778 UCLocalize("TEMPORARY_IGNORE"),
8779 nil
8780 ] autorelease];
8781
8782 [alert setContext:@"fixhalf"];
8783 [alert show];
8784 } else if (!Ignored_ && [essential_ count] != 0) {
8785 int count = [essential_ count];
8786
8787 UIAlertView *alert = [[[UIAlertView alloc]
8788 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8789 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8790 delegate:self
8791 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8792 otherButtonTitles:
8793 UCLocalize("UPGRADE_ESSENTIAL"),
8794 UCLocalize("COMPLETE_UPGRADE"),
8795 nil
8796 ] autorelease];
8797
8798 [alert setContext:@"upgrade"];
8799 [alert show];
8800 }
8801 }
8802
8803 - (void) _saveConfig {
8804 _trace();
8805 MetaFile_.Sync();
8806 _trace();
8807
8808 if (Changed_) {
8809 NSString *error(nil);
8810
8811 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8812 _trace();
8813 NSError *error(nil);
8814 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8815 NSLog(@"failure to save metadata data: %@", error);
8816 _trace();
8817
8818 Changed_ = false;
8819 } else {
8820 NSLog(@"failure to serialize metadata: %@", error);
8821 }
8822 }
8823 }
8824
8825 // Navigation controller for the queuing badge.
8826 - (CYNavigationController *) queueNavigationController {
8827 NSArray *controllers = [tabbar_ viewControllers];
8828 return [controllers objectAtIndex:3];
8829 }
8830
8831 - (void) _updateData {
8832 [self _saveConfig];
8833
8834 [tabbar_ reloadData];
8835
8836 CYNavigationController *navigation = [self queueNavigationController];
8837
8838 id queuedelegate = nil;
8839 if ([[navigation viewControllers] count] > 0)
8840 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8841
8842 [queuedelegate queueStatusDidChange];
8843 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8844 }
8845
8846 - (void) _refreshIfPossible {
8847 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8848
8849 bool recently = false;
8850 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8851 if (update != nil) {
8852 NSTimeInterval interval([update timeIntervalSinceNow]);
8853 if (interval <= 0 && interval > -(15*60))
8854 recently = true;
8855 }
8856
8857 // Don't automatic refresh if:
8858 // - We already refreshed recently.
8859 // - We already auto-refreshed this launch.
8860 // - Auto-refresh is disabled.
8861 if (recently || loaded_ || ManualRefresh) {
8862 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8863
8864 // If we are cancelling, we need to make sure it knows it's already loaded.
8865 loaded_ = true;
8866 return;
8867 } else {
8868 // We are going to load, so remember that.
8869 loaded_ = true;
8870 }
8871
8872 SCNetworkReachabilityFlags flags; {
8873 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8874 SCNetworkReachabilityGetFlags(reachability, &flags);
8875 CFRelease(reachability);
8876 }
8877
8878 // XXX: this elaborate mess is what Apple is using to determine this? :(
8879 // XXX: do we care if the user has to intervene? maybe that's ok?
8880 bool reachable(
8881 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8882 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8883 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8884 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8885 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8886 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8887 )
8888 );
8889
8890 // If we can reach the server, auto-refresh!
8891 if (reachable)
8892 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8893
8894 [pool release];
8895 }
8896
8897 - (void) refreshIfPossible {
8898 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8899 }
8900
8901 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8902 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8903 [hud setText:UCLocalize("RELOADING_DATA")];
8904
8905 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8906
8907 if (hud != nil)
8908 [self removeProgressHUD:hud];
8909
8910 size_t changes(0);
8911
8912 [essential_ removeAllObjects];
8913 [broken_ removeAllObjects];
8914
8915 NSArray *packages([database_ packages]);
8916 for (Package *package in packages) {
8917 if ([package half])
8918 [broken_ addObject:package];
8919 if ([package upgradableAndEssential:NO]) {
8920 if ([package essential])
8921 [essential_ addObject:package];
8922 ++changes;
8923 }
8924 }
8925
8926 NSLog(@"changes:#%u", changes);
8927
8928 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8929 if (changes != 0) {
8930 _trace();
8931 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8932 [changesItem setBadgeValue:badge];
8933 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8934 [self setApplicationIconBadgeNumber:changes];
8935 } else {
8936 _trace();
8937 [changesItem setBadgeValue:nil];
8938 [changesItem setAnimatedBadge:NO];
8939 [self setApplicationIconBadgeNumber:0];
8940 }
8941
8942 [self _updateData];
8943
8944 [self refreshIfPossible];
8945 }
8946
8947 - (void) updateData {
8948 [self _updateData];
8949 }
8950
8951 - (void) update_ {
8952 [database_ update];
8953 }
8954
8955 - (void) syncData {
8956 [self _saveConfig];
8957
8958 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8959 _assert(file != NULL);
8960
8961 for (NSString *key in [Sources_ allKeys]) {
8962 NSDictionary *source([Sources_ objectForKey:key]);
8963
8964 fprintf(file, "%s %s %s\n",
8965 [[source objectForKey:@"Type"] UTF8String],
8966 [[source objectForKey:@"URI"] UTF8String],
8967 [[source objectForKey:@"Distribution"] UTF8String]
8968 );
8969 }
8970
8971 fclose(file);
8972
8973 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8974 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8975 if (IsWildcat_)
8976 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8977 [tabbar_ presentModalViewController:navigation animated:YES];
8978
8979 [progress
8980 detachNewThreadSelector:@selector(update_)
8981 toTarget:self
8982 withObject:nil
8983 title:UCLocalize("UPDATING_SOURCES")
8984 ];
8985 }
8986
8987 - (void) addTrivialSource:(NSString *)href {
8988 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8989 @"deb", @"Type",
8990 href, @"URI",
8991 @"./", @"Distribution",
8992 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8993
8994 Changed_ = true;
8995 }
8996
8997 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8998 @synchronized (self) {
8999 [self _reloadDataWithInvocation:invocation];
9000 }
9001 }
9002
9003 - (void) reloadData {
9004 [self reloadDataWithInvocation:nil];
9005 }
9006
9007 - (void) resolve {
9008 pkgProblemResolver *resolver = [database_ resolver];
9009
9010 resolver->InstallProtect();
9011 if (!resolver->Resolve(true))
9012 _error->Discard();
9013 }
9014
9015 - (bool) perform {
9016 // XXX: this is a really crappy way of doing this.
9017 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9018 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9019 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9020 if ([tabbar_ updating])
9021 [tabbar_ cancelUpdate];
9022
9023 if (![database_ prepare])
9024 return false;
9025
9026 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9027 [page setDelegate:self];
9028 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9029 [confirm_ setDelegate:self];
9030
9031 if (IsWildcat_)
9032 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9033 [tabbar_ presentModalViewController:confirm_ animated:YES];
9034
9035 return true;
9036 }
9037
9038 - (void) queue {
9039 @synchronized (self) {
9040 [self perform];
9041 }
9042 }
9043
9044 - (void) clearPackage:(Package *)package {
9045 @synchronized (self) {
9046 [package clear];
9047 [self resolve];
9048 [self perform];
9049 }
9050 }
9051
9052 - (void) installPackages:(NSArray *)packages {
9053 @synchronized (self) {
9054 for (Package *package in packages)
9055 [package install];
9056 [self resolve];
9057 [self perform];
9058 }
9059 }
9060
9061 - (void) installPackage:(Package *)package {
9062 @synchronized (self) {
9063 [package install];
9064 [self resolve];
9065 [self perform];
9066 }
9067 }
9068
9069 - (void) removePackage:(Package *)package {
9070 @synchronized (self) {
9071 [package remove];
9072 [self resolve];
9073 [self perform];
9074 }
9075 }
9076
9077 - (void) distUpgrade {
9078 @synchronized (self) {
9079 if (![database_ upgrade])
9080 return;
9081 [self perform];
9082 }
9083 }
9084
9085 - (void) complete {
9086 @synchronized (self) {
9087 [self _reloadDataWithInvocation:nil];
9088 }
9089 }
9090
9091 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9092 Queuing_ = false;
9093
9094 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9095
9096 if (navigation != nil) {
9097 [navigation pushViewController:progress animated:YES];
9098 } else {
9099 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9100 if (IsWildcat_)
9101 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9102 [tabbar_ presentModalViewController:navigation animated:YES];
9103 }
9104
9105 [progress
9106 detachNewThreadSelector:@selector(perform)
9107 toTarget:database_
9108 withObject:nil
9109 title:UCLocalize("RUNNING")
9110 ];
9111
9112 ++locked_;
9113 }
9114
9115 - (void) progressControllerIsComplete:(ProgressController *)progress {
9116 --locked_;
9117 [self complete];
9118 }
9119
9120 - (void) showSettings {
9121 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9122 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9123 if (IsWildcat_)
9124 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9125 [tabbar_ presentModalViewController:nav animated:YES];
9126 }
9127
9128 - (void) retainNetworkActivityIndicator {
9129 if (activity_++ == 0)
9130 [self setNetworkActivityIndicatorVisible:YES];
9131 }
9132
9133 - (void) releaseNetworkActivityIndicator {
9134 if (--activity_ == 0)
9135 [self setNetworkActivityIndicatorVisible:NO];
9136 }
9137
9138 - (void) cancelAndClear:(bool)clear {
9139 @synchronized (self) {
9140 if (clear) {
9141 [database_ clear];
9142 Queuing_ = false;
9143 } else {
9144 Queuing_ = true;
9145 }
9146
9147 [self _updateData];
9148 }
9149 }
9150
9151 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9152 NSString *context([alert context]);
9153
9154 if ([context isEqualToString:@"fixhalf"]) {
9155 if (button == [alert cancelButtonIndex]) {
9156 @synchronized (self) {
9157 for (Package *broken in broken_) {
9158 [broken remove];
9159
9160 NSString *id = [broken id];
9161 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9162 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9163 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9164 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9165 }
9166
9167 [self resolve];
9168 [self perform];
9169 }
9170 } else if (button == [alert firstOtherButtonIndex]) {
9171 [broken_ removeAllObjects];
9172 [self _loaded];
9173 }
9174
9175 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9176 } else if ([context isEqualToString:@"upgrade"]) {
9177 if (button == [alert firstOtherButtonIndex]) {
9178 @synchronized (self) {
9179 for (Package *essential in essential_)
9180 [essential install];
9181
9182 [self resolve];
9183 [self perform];
9184 }
9185 } else if (button == [alert firstOtherButtonIndex] + 1) {
9186 [self distUpgrade];
9187 } else if (button == [alert cancelButtonIndex]) {
9188 Ignored_ = YES;
9189 }
9190
9191 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9192 }
9193 }
9194
9195 - (void) system:(NSString *)command { _pooled
9196 _trace();
9197 system([command UTF8String]);
9198 _trace();
9199 }
9200
9201 - (void) applicationWillSuspend {
9202 [database_ clean];
9203 [super applicationWillSuspend];
9204 }
9205
9206 - (BOOL) isSafeToSuspend {
9207 // Use external process status API internally.
9208 // This is probably a really bad idea.
9209 // XXX: what is the point of this? does this solve anything at all?
9210 uint64_t status = 0;
9211 int notify_token;
9212 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9213 notify_get_state(notify_token, &status);
9214 notify_cancel(notify_token);
9215 }
9216
9217 return locked_ == 0 && status == 0;
9218 }
9219
9220 - (void) applicationSuspend:(__GSEvent *)event {
9221 if ([self isSafeToSuspend])
9222 [super applicationSuspend:event];
9223 }
9224
9225 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9226 if ([self isSafeToSuspend])
9227 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9228 }
9229
9230 - (void) _setSuspended:(BOOL)value {
9231 if ([self isSafeToSuspend])
9232 [super _setSuspended:value];
9233 }
9234
9235 - (UIProgressHUD *) addProgressHUD {
9236 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9237 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9238
9239 [window_ setUserInteractionEnabled:NO];
9240 [hud show:YES];
9241
9242 UIViewController *target = tabbar_;
9243 while ([target modalViewController] != nil) target = [target modalViewController];
9244 [[target view] addSubview:hud];
9245
9246 ++locked_;
9247 return hud;
9248 }
9249
9250 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9251 [hud show:NO];
9252 [hud removeFromSuperview];
9253 [window_ setUserInteractionEnabled:YES];
9254 --locked_;
9255 }
9256
9257 - (CYViewController *) pageForPackage:(NSString *)name {
9258 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9259 }
9260
9261 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9262 NSString *scheme([[url scheme] lowercaseString]);
9263 if ([[url absoluteString] length] <= [scheme length] + 3)
9264 return nil;
9265 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9266 NSArray *components([path pathComponents]);
9267
9268 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9269 return [self pageForPackage:[components objectAtIndex:1]];
9270
9271 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9272 return nil;
9273
9274 NSString *base([components objectAtIndex:0]);
9275
9276 CYViewController *controller = nil;
9277
9278 if ([base isEqualToString:@"url"]) {
9279 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9280 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9281 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9282 } else if (!external && [components count] == 1) {
9283 if ([base isEqualToString:@"manage"]) {
9284 controller = [[[ManageController alloc] init] autorelease];
9285 }
9286
9287 if ([base isEqualToString:@"sources"]) {
9288 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9289 }
9290
9291 if ([base isEqualToString:@"home"]) {
9292 controller = [[[HomeController alloc] init] autorelease];
9293 }
9294
9295 if ([base isEqualToString:@"sections"]) {
9296 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9297 }
9298
9299 if ([base isEqualToString:@"search"]) {
9300 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9301 }
9302
9303 if ([base isEqualToString:@"changes"]) {
9304 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9305 }
9306
9307 if ([base isEqualToString:@"installed"]) {
9308 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9309 }
9310 } else if ([components count] == 2) {
9311 NSString *argument = [components objectAtIndex:1];
9312
9313 if ([base isEqualToString:@"package"]) {
9314 controller = [self pageForPackage:argument];
9315 }
9316
9317 if (!external && [base isEqualToString:@"search"]) {
9318 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9319 [(SearchController *)controller setSearchTerm:argument];
9320 }
9321
9322 if (!external && [base isEqualToString:@"sections"]) {
9323 if ([argument isEqualToString:@"all"])
9324 argument = nil;
9325 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9326 }
9327
9328 if (!external && [base isEqualToString:@"sources"]) {
9329 if ([argument isEqualToString:@"add"]) {
9330 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9331 [(SourcesController *)controller showAddSourcePrompt];
9332 } else {
9333 Source *source = [database_ sourceWithKey:argument];
9334 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9335 }
9336 }
9337
9338 if (!external && [base isEqualToString:@"launch"]) {
9339 [self launchApplicationWithIdentifier:argument suspended:NO];
9340 return nil;
9341 }
9342 } else if (!external && [components count] == 3) {
9343 NSString *arg1 = [components objectAtIndex:1];
9344 NSString *arg2 = [components objectAtIndex:2];
9345
9346 if ([base isEqualToString:@"package"]) {
9347 if ([arg2 isEqualToString:@"settings"]) {
9348 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9349 } else if ([arg2 isEqualToString:@"files"]) {
9350 if (Package *package = [database_ packageWithName:arg1]) {
9351 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9352 [(FileTable *)controller setPackage:package];
9353 }
9354 }
9355 }
9356 }
9357
9358 [controller setDelegate:self];
9359 return controller;
9360 }
9361
9362 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9363 CYViewController *page([self pageForURL:url forExternal:external]);
9364
9365 if (page != nil) {
9366 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9367 [nav setViewControllers:[NSArray arrayWithObject:page]];
9368 [tabbar_ setUnselectedViewController:nav];
9369 }
9370
9371 return page != nil;
9372 }
9373
9374 - (void) applicationOpenURL:(NSURL *)url {
9375 [super applicationOpenURL:url];
9376
9377 if (!loaded_) starturl_ = [url retain];
9378 else [self openCydiaURL:url forExternal:YES];
9379 }
9380
9381 - (void) applicationWillResignActive:(UIApplication *)application {
9382 // Stop refreshing if you get a phone call or lock the device.
9383 if ([tabbar_ updating])
9384 [tabbar_ cancelUpdate];
9385
9386 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9387 [super applicationWillResignActive:application];
9388 }
9389
9390 - (void) applicationWillTerminate:(UIApplication *)application {
9391 Changed_ = true;
9392 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9393 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9394 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9395
9396 [self _saveConfig];
9397 }
9398
9399 - (void) addStashController {
9400 ++locked_;
9401 stash_ = [[StashController alloc] init];
9402 [window_ addSubview:[stash_ view]];
9403 }
9404
9405 - (void) removeStashController {
9406 [[stash_ view] removeFromSuperview];
9407 [stash_ release];
9408 --locked_;
9409 }
9410
9411 - (void) stash {
9412 [self setIdleTimerDisabled:YES];
9413
9414 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9415 [self setStatusBarShowsProgress:YES];
9416 UpdateExternalStatus(1);
9417
9418 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9419
9420 UpdateExternalStatus(0);
9421 [self setStatusBarShowsProgress:NO];
9422
9423 [self removeStashController];
9424
9425 if (ExecFork() == 0) {
9426 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9427 perror("launchctl stop");
9428 }
9429 }
9430
9431 - (void) setupViewControllers {
9432 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9433
9434 NSMutableArray *items([NSMutableArray arrayWithObjects:
9435 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9436 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9437 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9438 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9439 nil]);
9440
9441 if (IsWildcat_) {
9442 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9443 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9444 } else {
9445 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9446 }
9447
9448 NSMutableArray *controllers([NSMutableArray array]);
9449 for (UITabBarItem *item in items) {
9450 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9451 [controller setTabBarItem:item];
9452 [controllers addObject:controller];
9453 }
9454 [tabbar_ setViewControllers:controllers];
9455
9456 [tabbar_ setUpdateDelegate:self];
9457 }
9458
9459 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9460 static CYEmulatedLoadingController *fake = nil;
9461
9462 if (view != nil) {
9463 if (fake == nil)
9464 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9465 [view addSubview:[fake view]];
9466 } else {
9467 [[fake view] removeFromSuperview];
9468 [fake release];
9469 fake = nil;
9470 }
9471
9472 return fake;
9473 }
9474
9475 - (void) applicationDidFinishLaunching:(id)unused {
9476 _trace();
9477 CydiaApp = self;
9478
9479 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9480 [self setApplicationSupportsShakeToEdit:NO];
9481
9482 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9483 initWithMemoryCapacity:524288
9484 diskCapacity:10485760
9485 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9486 ] autorelease]];
9487
9488 [CYBrowserController _initialize];
9489
9490 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9491
9492 Font12_ = [[UIFont systemFontOfSize:12] retain];
9493 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9494 Font14_ = [[UIFont systemFontOfSize:14] retain];
9495 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9496 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9497
9498 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9499 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9500
9501 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9502 [window_ orderFront:self];
9503 [window_ makeKey:self];
9504 [window_ setHidden:NO];
9505
9506 if (
9507 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9508 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9509 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9510 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9511 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9512 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9513 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9514 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9515 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9516 false
9517 ) {
9518 [self addStashController];
9519 // XXX: this would be much cleaner as a yieldToSelector:
9520 // that way the removeStashController could happen right here inline
9521 // we also could no longer require the useless stash_ field anymore
9522 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9523 return;
9524 }
9525
9526 database_ = [Database sharedInstance];
9527
9528 [window_ setUserInteractionEnabled:NO];
9529 [self setupViewControllers];
9530 [self showEmulatedLoadingControllerInView:window_];
9531
9532 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9533 _trace();
9534 }
9535
9536 - (void) loadData {
9537 _trace();
9538 if (Role_ == nil) {
9539 [window_ setUserInteractionEnabled:YES];
9540
9541 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9542 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9543 if (IsWildcat_)
9544 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9545 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9546
9547 return;
9548 } else {
9549 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9550 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9551 [window_ setUserInteractionEnabled:NO];
9552 }
9553
9554 [self reloadData];
9555 PrintTimes();
9556
9557 [window_ addSubview:[tabbar_ view]];
9558 [self showEmulatedLoadingControllerInView:nil];
9559 [window_ setUserInteractionEnabled:YES];
9560
9561 int selectedIndex = 0;
9562 NSMutableArray *items = nil;
9563
9564 bool recently = false;
9565 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9566 if (closed != nil) {
9567 NSTimeInterval interval([closed timeIntervalSinceNow]);
9568 // XXX: Is 15 minutes the optimal time here?
9569 if (interval <= 0 && interval > -(15*60))
9570 recently = true;
9571 }
9572
9573 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9574 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9575
9576 BOOL enough = YES;
9577 for (NSArray *entry in items)
9578 if ([entry count] <= 0)
9579 enough = NO;
9580
9581 if (!recently || !items || !enough) {
9582 selectedIndex = 0;
9583 items = [NSMutableArray array];
9584 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9585 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9586 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9587 if (!IsWildcat_) {
9588 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9589 } else {
9590 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9591 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9592 }
9593 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9594 }
9595
9596 [tabbar_ setSelectedIndex:selectedIndex];
9597 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9598 NSArray *stack = [items objectAtIndex:tab];
9599 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9600 NSMutableArray *current = [NSMutableArray array];
9601
9602 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9603 NSString *addr = [stack objectAtIndex:nav];
9604 NSURL *url = [NSURL URLWithString:addr];
9605 CYViewController *page = [self pageForURL:url forExternal:NO];
9606 if (page != nil)
9607 [current addObject:page];
9608 }
9609
9610 [navigation setViewControllers:current];
9611 }
9612
9613 // (Try to) show the startup URL.
9614 if (starturl_ != nil) {
9615 [self openCydiaURL:starturl_ forExternal:NO];
9616 [starturl_ release];
9617 starturl_ = nil;
9618 }
9619 }
9620
9621 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9622 if (item != nil && IsWildcat_) {
9623 [sheet showFromBarButtonItem:item animated:YES];
9624 } else {
9625 [sheet showInView:window_];
9626 }
9627 }
9628
9629 @end
9630
9631 /*IMP alloc_;
9632 id Alloc_(id self, SEL selector) {
9633 id object = alloc_(self, selector);
9634 lprintf("[%s]A-%p\n", self->isa->name, object);
9635 return object;
9636 }*/
9637
9638 /*IMP dealloc_;
9639 id Dealloc_(id self, SEL selector) {
9640 id object = dealloc_(self, selector);
9641 lprintf("[%s]D-%p\n", self->isa->name, object);
9642 return object;
9643 }*/
9644
9645 Class $WebDefaultUIKitDelegate;
9646
9647 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9648 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9649 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9650 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9651 }
9652
9653 static NSNumber *shouldPlayKeyboardSounds;
9654
9655 Class $UIHardware;
9656
9657 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9658 switch (sound) {
9659 case 1104: // Keyboard Button Clicked
9660 case 1105: // Keyboard Delete Repeated
9661 if (shouldPlayKeyboardSounds == nil) {
9662 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9663 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9664 }
9665
9666 if (![shouldPlayKeyboardSounds boolValue])
9667 break;
9668
9669 default:
9670 _UIHardware$_playSystemSound$(self, _cmd, sound);
9671 }
9672 }
9673
9674 Class $UIApplication;
9675
9676 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9677 static BOOL initialized = NO;
9678 static BOOL started = NO;
9679
9680 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9681 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9682
9683 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9684 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9685 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9686 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9687
9688 if (initialized && !enabled) {
9689 initialized = NO;
9690 [bundle performSelector:@selector(_accessibilityStopServer)];
9691 } else if (enabled) {
9692 initialized = YES;
9693 if (!started) {
9694 started = YES;
9695 [bundle performSelector:@selector(_accessibilityStartServer)];
9696 }
9697 }
9698 }
9699 }
9700
9701 int main(int argc, char *argv[]) { _pooled
9702 _trace();
9703
9704 if (Class $UIDevice = objc_getClass("UIDevice")) {
9705 UIDevice *device([$UIDevice currentDevice]);
9706 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9707 } else
9708 IsWildcat_ = false;
9709
9710 UIScreen *screen([UIScreen mainScreen]);
9711 if ([screen respondsToSelector:@selector(scale)])
9712 ScreenScale_ = [screen scale];
9713 else
9714 ScreenScale_ = 1;
9715
9716 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9717 if (ScreenScale_ > 1)
9718 [parts addObject:@"@2x"];
9719 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9720 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9721
9722 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9723
9724 /* Library Hacks {{{ */
9725 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9726
9727 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9728 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9729 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9730 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9731 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9732 }
9733
9734 $UIHardware = objc_getClass("UIHardware");
9735 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9736 if (UIHardware$_playSystemSound$ != NULL) {
9737 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9738 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9739 }
9740
9741 $UIApplication = objc_getClass("UIApplication");
9742 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9743 if (UIApplication$_updateApplicationAccessibility != NULL) {
9744 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9745 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9746 }
9747 /* }}} */
9748 /* Set Locale {{{ */
9749 Locale_ = CFLocaleCopyCurrent();
9750 Languages_ = [NSLocale preferredLanguages];
9751 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9752 //NSLog(@"%@", [Languages_ description]);
9753
9754 const char *lang;
9755 if (Languages_ == nil || [Languages_ count] == 0)
9756 // XXX: consider just setting to C and then falling through?
9757 lang = NULL;
9758 else {
9759 lang = [[Languages_ objectAtIndex:0] UTF8String];
9760 setenv("LANG", lang, true);
9761 }
9762
9763 //std::setlocale(LC_ALL, lang);
9764 NSLog(@"Setting Language: %s", lang);
9765 /* }}} */
9766
9767 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9768
9769 /* Parse Arguments {{{ */
9770 bool substrate(false);
9771
9772 if (argc != 0) {
9773 char **args(argv);
9774 int arge(1);
9775
9776 for (int argi(1); argi != argc; ++argi)
9777 if (strcmp(argv[argi], "--") == 0) {
9778 arge = argi;
9779 argv[argi] = argv[0];
9780 argv += argi;
9781 argc -= argi;
9782 break;
9783 }
9784
9785 for (int argi(1); argi != arge; ++argi)
9786 if (strcmp(args[argi], "--substrate") == 0)
9787 substrate = true;
9788 else
9789 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9790 }
9791 /* }}} */
9792
9793 App_ = [[NSBundle mainBundle] bundlePath];
9794 Home_ = NSHomeDirectory();
9795 Advanced_ = YES;
9796
9797 setuid(0);
9798 setgid(0);
9799
9800 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9801 alloc_ = alloc->method_imp;
9802 alloc->method_imp = (IMP) &Alloc_;*/
9803
9804 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9805 dealloc_ = dealloc->method_imp;
9806 dealloc->method_imp = (IMP) &Dealloc_;*/
9807
9808 /* System Information {{{ */
9809 size_t size;
9810
9811 int maxproc;
9812 size = sizeof(maxproc);
9813 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9814 perror("sysctlbyname(\"kern.maxproc\", ?)");
9815 else if (maxproc < 64) {
9816 maxproc = 64;
9817 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9818 perror("sysctlbyname(\"kern.maxproc\", #)");
9819 }
9820
9821 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9822 char *osversion = new char[size];
9823 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9824 perror("sysctlbyname(\"kern.osversion\", ?)");
9825 else
9826 System_ = [NSString stringWithUTF8String:osversion];
9827
9828 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9829 char *machine = new char[size];
9830 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9831 perror("sysctlbyname(\"hw.machine\", ?)");
9832 else
9833 Machine_ = machine;
9834
9835 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9836 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9837 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9838 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9839 CFRelease(serial);
9840 }
9841
9842 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9843 NSData *data((NSData *) ecid);
9844 size_t length([data length]);
9845 uint8_t bytes[length];
9846 [data getBytes:bytes];
9847 char string[length * 2 + 1];
9848 for (size_t i(0); i != length; ++i)
9849 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9850 ChipID_ = [NSString stringWithUTF8String:string];
9851 CFRelease(ecid);
9852 }
9853
9854 IOObjectRelease(service);
9855 }
9856 }
9857
9858 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9859
9860 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9861 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9862 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9863
9864 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9865 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9866 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9867
9868 if (mcc != NULL && mnc != NULL)
9869 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9870
9871 if (mnc != NULL)
9872 CFRelease(mnc);
9873 if (mcc != NULL)
9874 CFRelease(mcc);
9875
9876 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9877 Build_ = [system objectForKey:@"ProductBuildVersion"];
9878 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9879 Product_ = [info objectForKey:@"SafariProductVersion"];
9880 Safari_ = [info objectForKey:@"CFBundleVersion"];
9881 }
9882 /* }}} */
9883 /* Load Database {{{ */
9884 _trace();
9885 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9886 _trace();
9887 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9888
9889 if (Metadata_ == NULL)
9890 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9891 else {
9892 Settings_ = [Metadata_ objectForKey:@"Settings"];
9893
9894 Packages_ = [Metadata_ objectForKey:@"Packages"];
9895 Sections_ = [Metadata_ objectForKey:@"Sections"];
9896 Sources_ = [Metadata_ objectForKey:@"Sources"];
9897
9898 Token_ = [Metadata_ objectForKey:@"Token"];
9899 }
9900
9901 if (Settings_ != nil)
9902 Role_ = [Settings_ objectForKey:@"Role"];
9903
9904 if (Sections_ == nil) {
9905 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9906 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9907 }
9908
9909 if (Sources_ == nil) {
9910 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9911 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9912 }
9913 /* }}} */
9914
9915 _trace();
9916 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9917 _trace();
9918
9919 if (Packages_ != nil) {
9920 bool fail(false);
9921 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9922 _trace();
9923
9924 if (!fail) {
9925 [Metadata_ removeObjectForKey:@"Packages"];
9926 Packages_ = nil;
9927 Changed_ = true;
9928 }
9929 }
9930
9931 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9932
9933 #define MobileSubstrate_(name) \
9934 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9935 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9936
9937 MobileSubstrate_(Activator)
9938 MobileSubstrate_(libstatusbar)
9939 MobileSubstrate_(SimulatedKeyEvents)
9940 MobileSubstrate_(WinterBoard)
9941
9942 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9943 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9944
9945 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9946
9947 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9948 unlink("/tmp/.cydia.fw");
9949 goto firmware;
9950 } else if (access("/User", F_OK) != 0 || version < 2) {
9951 firmware:
9952 _trace();
9953 system("/usr/libexec/cydia/firmware.sh");
9954 _trace();
9955 }
9956
9957 _assert([[NSFileManager defaultManager]
9958 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9959 withIntermediateDirectories:YES
9960 attributes:nil
9961 error:NULL
9962 ]);
9963
9964 if (access("/tmp/cydia.chk", F_OK) == 0) {
9965 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9966 _assert(errno == ENOENT);
9967 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9968 _assert(errno == ENOENT);
9969 }
9970
9971 /* APT Initialization {{{ */
9972 _assert(pkgInitConfig(*_config));
9973 _assert(pkgInitSystem(*_config, _system));
9974
9975 if (lang != NULL)
9976 _config->Set("APT::Acquire::Translation", lang);
9977
9978 // XXX: this timeout might be important :(
9979 //_config->Set("Acquire::http::Timeout", 15);
9980
9981 _config->Set("Acquire::http::MaxParallel", 3);
9982 /* }}} */
9983 /* Color Choices {{{ */
9984 space_ = CGColorSpaceCreateDeviceRGB();
9985
9986 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9987 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9988 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9989 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9990 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9991 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9992 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9993 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9994 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9995
9996 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9997 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9998 /* }}}*/
9999 /* UIKit Configuration {{{ */
10000 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10001 if ($GSFontSetUseLegacyFontMetrics != NULL)
10002 $GSFontSetUseLegacyFontMetrics(YES);
10003
10004 // XXX: I have a feeling this was important
10005 //UIKeyboardDisableAutomaticAppearance();
10006 /* }}} */
10007
10008 Colon_ = UCLocalize("COLON_DELIMITED");
10009 Elision_ = UCLocalize("ELISION");
10010 Error_ = UCLocalize("ERROR");
10011 Warning_ = UCLocalize("WARNING");
10012
10013 _trace();
10014 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10015
10016 CGColorSpaceRelease(space_);
10017 CFRelease(Locale_);
10018
10019 return value;
10020 }