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