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