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