]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Entirely theoretical getInstalledPackages() threading bug: I'm anal.
[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_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
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_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
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
3293 [delegate_ performSelectorOnMainThread:@selector(addProgressOutput:) withObject:[NSString stringWithUTF8String:line.c_str()] waitUntilDone:YES];
3294 }
3295
3296 _assume(false);
3297 }
3298
3299 - (FILE *) input {
3300 return input_;
3301 }
3302
3303 - (Package *) packageWithName:(NSString *)name {
3304 @synchronized (self) {
3305 if (static_cast<pkgDepCache *>(cache_) == NULL)
3306 return nil;
3307 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3308 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3309 } }
3310
3311 - (id) init {
3312 if ((self = [super init]) != nil) {
3313 policy_ = NULL;
3314 records_ = NULL;
3315 resolver_ = NULL;
3316 fetcher_ = NULL;
3317 lock_ = NULL;
3318
3319 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3320 apr_pool_create(&pool_, NULL);
3321
3322 size_t capacity(MetaFile_->active_);
3323 if (capacity == 0)
3324 capacity = 16384;
3325 else
3326 capacity += 1024;
3327
3328 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3329 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3330
3331 int fds[2];
3332
3333 _assert(pipe(fds) != -1);
3334 cydiafd_ = fds[1];
3335
3336 _config->Set("APT::Keep-Fds::", cydiafd_);
3337 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3338
3339 [NSThread
3340 detachNewThreadSelector:@selector(_readCydia:)
3341 toTarget:self
3342 withObject:[NSNumber numberWithInt:fds[0]]
3343 ];
3344
3345 _assert(pipe(fds) != -1);
3346 statusfd_ = fds[1];
3347
3348 [NSThread
3349 detachNewThreadSelector:@selector(_readStatus:)
3350 toTarget:self
3351 withObject:[NSNumber numberWithInt:fds[0]]
3352 ];
3353
3354 _assert(pipe(fds) != -1);
3355 _assert(dup2(fds[0], 0) != -1);
3356 _assert(close(fds[0]) != -1);
3357
3358 input_ = fdopen(fds[1], "a");
3359
3360 _assert(pipe(fds) != -1);
3361 _assert(dup2(fds[1], 1) != -1);
3362 _assert(close(fds[1]) != -1);
3363
3364 [NSThread
3365 detachNewThreadSelector:@selector(_readOutput:)
3366 toTarget:self
3367 withObject:[NSNumber numberWithInt:fds[0]]
3368 ];
3369 } return self;
3370 }
3371
3372 - (pkgCacheFile &) cache {
3373 return cache_;
3374 }
3375
3376 - (pkgDepCache::Policy *) policy {
3377 return policy_;
3378 }
3379
3380 - (pkgRecords *) records {
3381 return records_;
3382 }
3383
3384 - (pkgProblemResolver *) resolver {
3385 return resolver_;
3386 }
3387
3388 - (pkgAcquire &) fetcher {
3389 return *fetcher_;
3390 }
3391
3392 - (pkgSourceList &) list {
3393 return *list_;
3394 }
3395
3396 - (NSArray *) packages {
3397 return (NSArray *) packages_;
3398 }
3399
3400 - (NSArray *) sources {
3401 return sourceList_;
3402 }
3403
3404 - (Source *) sourceWithKey:(NSString *)key {
3405 for (Source *source in [self sources]) {
3406 if ([[source key] isEqualToString:key])
3407 return source;
3408 } return nil;
3409 }
3410
3411 - (bool) popErrorWithTitle:(NSString *)title {
3412 bool fatal(false);
3413 std::string message;
3414
3415 while (!_error->empty()) {
3416 std::string error;
3417 bool warning(!_error->PopMessage(error));
3418 if (!warning)
3419 fatal = true;
3420 for (;;) {
3421 size_t size(error.size());
3422 if (size == 0 || error[size - 1] != '\n')
3423 break;
3424 error.resize(size - 1);
3425 }
3426 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3427
3428 if (!message.empty())
3429 message += "\n\n";
3430 message += error;
3431 }
3432
3433 if (fatal && !message.empty())
3434 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3435
3436 return fatal;
3437 }
3438
3439 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3440 return [self popErrorWithTitle:title] || !success;
3441 }
3442
3443 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3444 @synchronized (self) {
3445 ++era_;
3446
3447 [self releasePackages];
3448
3449 sourceMap_.clear();
3450 [sourceList_ removeAllObjects];
3451
3452 _error->Discard();
3453
3454 delete list_;
3455 list_ = NULL;
3456 manager_ = NULL;
3457 delete lock_;
3458 lock_ = NULL;
3459 delete fetcher_;
3460 fetcher_ = NULL;
3461 delete resolver_;
3462 resolver_ = NULL;
3463 delete records_;
3464 records_ = NULL;
3465 delete policy_;
3466 policy_ = NULL;
3467
3468 cache_.Close();
3469
3470 apr_pool_clear(pool_);
3471
3472 NSRecycleZone(zone_);
3473 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3474
3475 int chk(creat("/tmp/cydia.chk", 0644));
3476 if (chk != -1)
3477 close(chk);
3478
3479 if (invocation != nil)
3480 [invocation invoke];
3481
3482 NSString *title(UCLocalize("DATABASE"));
3483
3484 _trace();
3485 while (!cache_.Open(progress_, true)) { pop:
3486 std::string error;
3487 bool warning(!_error->PopMessage(error));
3488 lprintf("cache_.Open():[%s]\n", error.c_str());
3489
3490 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3491 [delegate_ repairWithSelector:@selector(configure)];
3492 else if (error == "The package lists or status file could not be parsed or opened.")
3493 [delegate_ repairWithSelector:@selector(update)];
3494 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3495 else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3496 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, Error_, title]];
3497 // else if (error == "The list of sources could not be read.")
3498 else {
3499 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3500 return;
3501 }
3502
3503 if (warning)
3504 goto pop;
3505 _error->Discard();
3506 }
3507 _trace();
3508
3509 unlink("/tmp/cydia.chk");
3510
3511 now_ = [[NSDate date] timeIntervalSince1970];
3512
3513 policy_ = new pkgDepCache::Policy();
3514 records_ = new pkgRecords(cache_);
3515 resolver_ = new pkgProblemResolver(cache_);
3516 fetcher_ = new pkgAcquire(&status_);
3517 lock_ = NULL;
3518
3519 list_ = new pkgSourceList();
3520 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3521 return;
3522
3523 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3524 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3525 return;
3526 }
3527
3528 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3529 return;
3530
3531 if (cache_->BrokenCount() != 0) {
3532 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3533 return;
3534
3535 if (cache_->BrokenCount() != 0) {
3536 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3537 return;
3538 }
3539
3540 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3541 return;
3542 }
3543
3544 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3545 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3546 [sourceList_ addObject:object];
3547
3548 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3549 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3550 // XXX: this could be more intelligent
3551 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3552 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3553 if (!cached.end())
3554 sourceMap_[cached->ID] = object;
3555 }
3556 }
3557
3558 {
3559 /*std::vector<Package *> packages;
3560 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3561 [packages_ release];
3562 packages_ = nil;*/
3563
3564 _trace();
3565
3566 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3567 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3568 //packages.push_back(package);
3569 CFArrayAppendValue(packages_, [package retain]);
3570
3571 _trace();
3572
3573 /*if (packages.empty())
3574 packages_ = [[NSArray alloc] init];
3575 else
3576 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3577 _trace();*/
3578
3579 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3580 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3581 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3582
3583 /*_trace();
3584 PrintTimes();
3585 _trace();*/
3586
3587 _trace();
3588
3589 /*if (!packages.empty())
3590 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3591 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3592
3593 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3594
3595 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3596
3597 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3598
3599 _trace();
3600
3601 size_t count(CFArrayGetCount(packages_));
3602 MetaFile_->active_ = count;
3603
3604 for (size_t index(0); index != count; ++index)
3605 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3606
3607 _trace();
3608 }
3609 } } CYPoolEnd() _trace(); }
3610
3611 - (void) clear {
3612 @synchronized (self) {
3613 delete resolver_;
3614 resolver_ = new pkgProblemResolver(cache_);
3615
3616 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3617 if (!cache_[iterator].Keep())
3618 cache_->MarkKeep(iterator, false);
3619 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3620 cache_->SetReInstall(iterator, false);
3621 } }
3622
3623 - (void) configure {
3624 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3625 _trace();
3626 system([dpkg UTF8String]);
3627 _trace();
3628 }
3629
3630 - (bool) clean {
3631 // XXX: I don't remember this condition
3632 if (lock_ != NULL)
3633 return false;
3634
3635 FileFd Lock;
3636 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3637
3638 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3639
3640 if ([self popErrorWithTitle:title])
3641 return false;
3642
3643 pkgAcquire fetcher;
3644 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3645
3646 class LogCleaner :
3647 public pkgArchiveCleaner
3648 {
3649 protected:
3650 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3651 unlink(File);
3652 }
3653 } cleaner;
3654
3655 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3656 return false;
3657
3658 return true;
3659 }
3660
3661 - (bool) prepare {
3662 fetcher_->Shutdown();
3663
3664 pkgRecords records(cache_);
3665
3666 lock_ = new FileFd();
3667 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3668
3669 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3670
3671 if ([self popErrorWithTitle:title])
3672 return false;
3673
3674 pkgSourceList list;
3675 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3676 return false;
3677
3678 manager_ = (_system->CreatePM(cache_));
3679 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3680 return false;
3681
3682 return true;
3683 }
3684
3685 - (void) perform {
3686 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3687
3688 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3689 pkgSourceList list;
3690 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3691 return;
3692 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3693 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3694 }
3695
3696 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3697 _trace();
3698 return;
3699 }
3700
3701 [(id)CydiaApp performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3702
3703 bool failed = false;
3704 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3705 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3706 continue;
3707 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3708 continue;
3709
3710 std::string uri = (*item)->DescURI();
3711 std::string error = (*item)->ErrorText;
3712
3713 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3714 failed = true;
3715
3716 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3717 withObject:[NSArray arrayWithObjects:
3718 [NSString stringWithUTF8String:error.c_str()],
3719 nil]
3720 waitUntilDone:YES
3721 ];
3722 }
3723
3724 [(id)CydiaApp performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3725
3726 if (failed) {
3727 _trace();
3728 return;
3729 }
3730
3731 _system->UnLock();
3732 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3733
3734 if (_error->PendingError()) {
3735 _trace();
3736 return;
3737 }
3738
3739 if (result == pkgPackageManager::Failed) {
3740 _trace();
3741 return;
3742 }
3743
3744 if (result != pkgPackageManager::Completed) {
3745 _trace();
3746 return;
3747 }
3748
3749 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3750 pkgSourceList list;
3751 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3752 return;
3753 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3754 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3755 }
3756
3757 if (![before isEqualToArray:after])
3758 [self update];
3759 }
3760
3761 - (bool) upgrade {
3762 NSString *title(UCLocalize("UPGRADE"));
3763 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3764 return false;
3765 return true;
3766 }
3767
3768 - (void) update {
3769 [self updateWithStatus:status_];
3770 }
3771
3772 - (void) updateWithStatus:(Status &)status {
3773 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3774 NSString *title(UCLocalize("REFRESHING_DATA"));
3775
3776 pkgSourceList list;
3777 if (!list.ReadMainList())
3778 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3779
3780 FileFd lock;
3781 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3782 if ([self popErrorWithTitle:title])
3783 return;
3784
3785 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3786 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3787 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3788
3789 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3790 Changed_ = true;
3791 }
3792
3793 - (void) setDelegate:(id)delegate {
3794 delegate_ = delegate;
3795 status_.setDelegate(delegate);
3796 progress_.setDelegate(delegate);
3797 }
3798
3799 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3800 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3801 return i == sourceMap_.end() ? nil : i->second;
3802 }
3803
3804 - (NSString *) mappedSectionForPointer:(const char *)section {
3805 _H<NSString> *mapped;
3806
3807 _profile(Database$mappedSectionForPointer$Cache)
3808 mapped = &sections_[section];
3809 _end
3810
3811 if (*mapped == NULL) {
3812 size_t length(strlen(section));
3813 char spaced[length + 1];
3814
3815 _profile(Database$mappedSectionForPointer$Replace)
3816 for (size_t index(0); index != length; ++index)
3817 spaced[index] = section[index] == '_' ? ' ' : section[index];
3818 spaced[length] = '\0';
3819 _end
3820
3821 NSString *string;
3822
3823 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3824 string = [NSString stringWithUTF8String:spaced];
3825 _end
3826
3827 _profile(Database$mappedSectionForPointer$Map)
3828 string = [SectionMap_ objectForKey:string] ?: string;
3829 _end
3830
3831 *mapped = string;
3832 } return *mapped;
3833 }
3834
3835 @end
3836 /* }}} */
3837
3838 /* Web Scripting {{{ */
3839 @interface CydiaObject : NSObject {
3840 id indirect_;
3841 _transient id delegate_;
3842 }
3843
3844 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3845
3846 @end
3847
3848 @implementation CydiaObject
3849
3850 - (void) dealloc {
3851 [indirect_ release];
3852 [super dealloc];
3853 }
3854
3855 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3856 if ((self = [super init]) != nil) {
3857 indirect_ = [indirect retain];
3858 } return self;
3859 }
3860
3861 - (void) setDelegate:(id)delegate {
3862 delegate_ = delegate;
3863 }
3864
3865 + (NSArray *) _attributeKeys {
3866 return [NSArray arrayWithObjects:
3867 @"device",
3868 @"ecid",
3869 @"model",
3870 @"plmn",
3871 @"role",
3872 @"serial",
3873 nil];
3874 }
3875
3876 - (NSArray *) attributeKeys {
3877 return [[self class] _attributeKeys];
3878 }
3879
3880 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3881 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3882 }
3883
3884 - (NSString *) device {
3885 return [[UIDevice currentDevice] uniqueIdentifier];
3886 }
3887
3888 - (NSString *) plmn {
3889 return PLMN_;
3890 }
3891
3892 - (NSString *) ecid {
3893 return ChipID_;
3894 }
3895
3896 - (NSString *) serial {
3897 return SerialNumber_;
3898 }
3899
3900 - (NSString *) role {
3901 return Role_;
3902 }
3903
3904 - (NSString *) model {
3905 return [NSString stringWithUTF8String:Machine_];
3906 }
3907
3908 + (NSString *) webScriptNameForSelector:(SEL)selector {
3909 if (false);
3910 else if (selector == @selector(addTrivialSource:))
3911 return @"addTrivialSource";
3912 else if (selector == @selector(close))
3913 return @"close";
3914 else if (selector == @selector(du:))
3915 return @"du";
3916 else if (selector == @selector(stringWithFormat:arguments:))
3917 return @"format";
3918 else if (selector == @selector(getAllSources))
3919 return @"getAllSourcs";
3920 else if (selector == @selector(getKernelNumber:))
3921 return @"getKernelNumber";
3922 else if (selector == @selector(getKernelString:))
3923 return @"getKernelString";
3924 else if (selector == @selector(getInstalledPackages))
3925 return @"getInstalledPackages";
3926 else if (selector == @selector(getPackageById:))
3927 return @"getPackageById";
3928 else if (selector == @selector(installPackages:))
3929 return @"installPackages";
3930 else if (selector == @selector(localizedStringForKey:value:table:))
3931 return @"localize";
3932 else if (selector == @selector(refreshSources))
3933 return @"refreshSources";
3934 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3935 return @"setButtonImage";
3936 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3937 return @"setButtonTitle";
3938 else if (selector == @selector(setPopupHook:))
3939 return @"setPopupHook";
3940 else if (selector == @selector(setToken:))
3941 return @"setToken";
3942 else if (selector == @selector(setViewportWidth:))
3943 return @"setViewportWidth";
3944 else if (selector == @selector(statfs:))
3945 return @"statfs";
3946 else if (selector == @selector(supports:))
3947 return @"supports";
3948 else
3949 return nil;
3950 }
3951
3952 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3953 return [self webScriptNameForSelector:selector] == nil;
3954 }
3955
3956 - (BOOL) supports:(NSString *)feature {
3957 return [feature isEqualToString:@"window.open"];
3958 }
3959
3960 - (NSNumber *) getKernelNumber:(NSString *)name {
3961 const char *string([name UTF8String]);
3962
3963 size_t size;
3964 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3965 return (id) [NSNull null];
3966
3967 if (size != sizeof(int))
3968 return (id) [NSNull null];
3969
3970 int value;
3971 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3972 return (id) [NSNull null];
3973
3974 return [NSNumber numberWithInt:value];
3975 }
3976
3977 - (NSString *) getKernelString:(NSString *)name {
3978 const char *string([name UTF8String]);
3979
3980 size_t size;
3981 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3982 return (id) [NSNull null];
3983
3984 char value[size + 1];
3985 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3986 return (id) [NSNull null];
3987
3988 // XXX: just in case you request something ludicrous
3989 value[size] = '\0';
3990
3991 return [NSString stringWithCString:value];
3992 }
3993
3994 - (void) addTrivialSource:(NSString *)href {
3995 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3996 }
3997
3998 - (void) refreshSources {
3999 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4000 }
4001
4002 - (NSArray *) getAllSources {
4003 return [[Database sharedInstance] sources];
4004 }
4005
4006 - (NSArray *) getInstalledPackages {
4007 Database *database([Database sharedInstance]);
4008 @synchronized (database) {
4009 NSArray *packages([database packages]);
4010 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4011 for (Package *package in packages)
4012 if (![package uninstalled])
4013 [installed addObject:package];
4014 return installed;
4015 } }
4016
4017 - (Package *) getPackageById:(NSString *)id {
4018 Package *package([[Database sharedInstance] packageWithName:id]);
4019 [package parse];
4020 return package;
4021 }
4022
4023 - (NSArray *) statfs:(NSString *)path {
4024 struct statfs stat;
4025
4026 if (path == nil || statfs([path UTF8String], &stat) == -1)
4027 return nil;
4028
4029 return [NSArray arrayWithObjects:
4030 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4031 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4032 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4033 nil];
4034 }
4035
4036 - (NSNumber *) du:(NSString *)path {
4037 NSNumber *value(nil);
4038
4039 int fds[2];
4040 _assert(pipe(fds) != -1);
4041
4042 pid_t pid(ExecFork());
4043 if (pid == 0) {
4044 _assert(dup2(fds[1], 1) != -1);
4045 _assert(close(fds[0]) != -1);
4046 _assert(close(fds[1]) != -1);
4047 /* XXX: this should probably not use du */
4048 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4049 exit(1);
4050 _assert(false);
4051 }
4052
4053 _assert(close(fds[1]) != -1);
4054
4055 if (FILE *du = fdopen(fds[0], "r")) {
4056 char line[1024];
4057 while (fgets(line, sizeof(line), du) != NULL) {
4058 size_t length(strlen(line));
4059 while (length != 0 && line[length - 1] == '\n')
4060 line[--length] = '\0';
4061 if (char *tab = strchr(line, '\t')) {
4062 *tab = '\0';
4063 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4064 }
4065 }
4066
4067 fclose(du);
4068 } else _assert(close(fds[0]));
4069
4070 int status;
4071 wait:
4072 if (waitpid(pid, &status, 0) == -1)
4073 if (errno == EINTR)
4074 goto wait;
4075 else _assert(false);
4076
4077 return value;
4078 }
4079
4080 - (void) close {
4081 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4082 }
4083
4084 - (void) installPackages:(NSArray *)packages {
4085 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4086 }
4087
4088 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4089 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4090 }
4091
4092 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4093 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4094 }
4095
4096 - (void) _setToken:(NSString *)token {
4097 if (Token_ != nil)
4098 [Token_ release];
4099 Token_ = [token retain];
4100
4101 [Metadata_ setObject:Token_ forKey:@"Token"];
4102 Changed_ = true;
4103 }
4104
4105 - (void) setToken:(NSString *)token {
4106 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4107 }
4108
4109 - (void) setPopupHook:(id)function {
4110 [indirect_ setPopupHook:function];
4111 }
4112
4113 - (void) setViewportWidth:(float)width {
4114 [indirect_ setViewportWidthOnMainThread:width];
4115 }
4116
4117 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4118 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4119 unsigned count([arguments count]);
4120 id values[count];
4121 for (unsigned i(0); i != count; ++i)
4122 values[i] = [arguments objectAtIndex:i];
4123 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4124 }
4125
4126 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4127 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4128 value = nil;
4129 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4130 table = nil;
4131 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4132 }
4133
4134 @end
4135 /* }}} */
4136
4137 /* @ Loading... Indicator {{{ */
4138 @interface CYLoadingIndicator : UIView {
4139 UIActivityIndicatorView *spinner_;
4140 UILabel *label_;
4141 UIView *container_;
4142 }
4143
4144 @property (readonly, nonatomic) UILabel *label;
4145 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4146
4147 @end
4148
4149 @implementation CYLoadingIndicator
4150
4151 - (id) initWithFrame:(CGRect)frame {
4152 if ((self = [super initWithFrame:frame]) != nil) {
4153 container_ = [[[UIView alloc] init] autorelease];
4154 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4155
4156 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4157 [spinner_ startAnimating];
4158 [container_ addSubview:spinner_];
4159
4160 label_ = [[[UILabel alloc] init] autorelease];
4161 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4162 [label_ setBackgroundColor:[UIColor clearColor]];
4163 [label_ setTextColor:[UIColor blackColor]];
4164 [label_ setShadowColor:[UIColor whiteColor]];
4165 [label_ setShadowOffset:CGSizeMake(0, 1)];
4166 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4167 [container_ addSubview:label_];
4168
4169 CGSize viewsize = frame.size;
4170 CGSize spinnersize = [spinner_ bounds].size;
4171 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4172 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4173
4174 CGRect containrect = {
4175 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4176 CGSizeMake(bothwidth, spinnersize.height)
4177 };
4178 CGRect textrect = {
4179 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4180 textsize
4181 };
4182 CGRect spinrect = {
4183 CGPointZero,
4184 spinnersize
4185 };
4186
4187 [container_ setFrame:containrect];
4188 [spinner_ setFrame:spinrect];
4189 [label_ setFrame:textrect];
4190 [self addSubview:container_];
4191 } return self;
4192 }
4193
4194 - (UILabel *) label {
4195 return label_;
4196 }
4197
4198 - (UIActivityIndicatorView *) activityIndicatorView {
4199 return spinner_;
4200 }
4201
4202 @end
4203 /* }}} */
4204 /* Emulated Loading Controller {{{ */
4205 @interface CYEmulatedLoadingController : CYViewController <
4206 ProgressDelegate,
4207 ConfigurationDelegate
4208 > {
4209 _transient Database *database_;
4210 CYLoadingIndicator *indicator_;
4211 UITabBar *tabbar_;
4212 UINavigationBar *navbar_;
4213 }
4214
4215 @end
4216
4217 @implementation CYEmulatedLoadingController
4218
4219 - (void) dealloc {
4220 [self releaseSubviews];
4221 [database_ setDelegate:nil];
4222
4223 [super dealloc];
4224 }
4225
4226 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4227 CYAlertView *sheet([[[CYAlertView alloc]
4228 initWithTitle:title
4229 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4230 defaultButtonIndex:0
4231 ] autorelease]);
4232
4233 [sheet setMessage:error];
4234 [sheet yieldToPopupAlertAnimated:YES];
4235 [sheet dismiss];
4236 }
4237
4238 - (void) setProgressTitle:(NSString *)title { }
4239 - (void) setProgressPercent:(NSNumber *)percent { }
4240 - (void) startProgress { }
4241 - (void) addProgressOutput:(NSString *)output { }
4242 - (bool) isCancelling:(size_t)received { return NO; }
4243 - (void) setConfigurationData:(NSString *)data { }
4244
4245 - (void) repairWithSelector:(SEL)selector {
4246 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4247 [database_ performSelector:selector];
4248 sleep(10);
4249 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4250 }
4251
4252 - (id) initWithDatabase:(Database *)database {
4253 if ((self = [super init]) != nil) {
4254 database_ = database;
4255 [database_ setDelegate:self];
4256 } return self;
4257 }
4258
4259 - (void) loadView {
4260 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4261 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4262
4263 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4264 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4265 [[self view] addSubview:indicator_];
4266
4267 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4268 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4269 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4270 [[self view] addSubview:tabbar_];
4271
4272 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4273 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4274 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4275 [[self view] addSubview:navbar_];
4276 }
4277
4278 - (void) releaseSubviews {
4279 [indicator_ release];
4280 indicator_ = nil;
4281
4282 [tabbar_ release];
4283 tabbar_ = nil;
4284
4285 [navbar_ release];
4286 navbar_ = nil;
4287 }
4288
4289 @end
4290 /* }}} */
4291
4292 /* Cydia Browser Controller {{{ */
4293 @interface CYBrowserController : BrowserController {
4294 CydiaObject *cydia_;
4295 }
4296
4297 @end
4298
4299 @implementation CYBrowserController
4300
4301 - (void) dealloc {
4302 [cydia_ release];
4303 [super dealloc];
4304 }
4305
4306 - (NSURL *) navigationURL {
4307 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4308 }
4309
4310 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4311 }
4312
4313 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4314 [super webView:view didClearWindowObject:window forFrame:frame];
4315
4316 WebDataSource *source([frame dataSource]);
4317 NSURLResponse *response([source response]);
4318
4319 NSURL *url([response URL]);
4320 NSString *scheme([url scheme]);
4321 NSString *host([url host]);
4322
4323 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4324 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4325 NSDictionary *headers([http allHeaderFields]);
4326 [self setHeaders:headers forHost:host];
4327 }
4328
4329 if (
4330 [host isEqualToString:@"cydia.saurik.com"] ||
4331 [host hasSuffix:@".cydia.saurik.com"] ||
4332 [scheme isEqualToString:@"file"]
4333 )
4334 [window setValue:cydia_ forKey:@"cydia"];
4335 }
4336
4337 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4338 if (System_ != NULL)
4339 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4340 if (Machine_ != NULL)
4341 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4342 if (Token_ != nil)
4343 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4344 if (Role_ != nil)
4345 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4346 }
4347
4348 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4349 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4350 [self _setMoreHeaders:copy];
4351 return copy;
4352 }
4353
4354 - (void) setDelegate:(id)delegate {
4355 [super setDelegate:delegate];
4356 [cydia_ setDelegate:delegate];
4357 }
4358
4359 - (id) init {
4360 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4361 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4362
4363 WebView *webview([[webview_ _documentView] webView]);
4364
4365 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4366
4367 NSString *application = package == nil ? @"Cydia" : [NSString
4368 stringWithFormat:@"Cydia/%@",
4369 [package installed]
4370 ];
4371
4372 if (Safari_ != nil)
4373 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4374 if (Build_ != nil)
4375 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4376 if (Product_ != nil)
4377 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4378
4379 [webview setApplicationNameForUserAgent:application];
4380 } return self;
4381 }
4382
4383 @end
4384 /* }}} */
4385
4386 // CydiaScript {{{
4387 @interface NSObject (CydiaScript)
4388 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4389 @end
4390
4391 @implementation NSObject (CydiaScript)
4392
4393 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4394 return self;
4395 }
4396
4397 @end
4398
4399 @implementation NSArray (CydiaScript)
4400
4401 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4402 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4403 for (size_t i(0), e([self count]); i != e; ++i)
4404 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4405 return object;
4406 }
4407
4408 @end
4409
4410 @implementation NSDictionary (CydiaScript)
4411
4412 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4413 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4414 for (id i in self)
4415 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4416 return object;
4417 }
4418
4419 @end
4420 // }}}
4421
4422 /* Confirmation Controller {{{ */
4423 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4424 if (!iterator.end())
4425 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4426 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4427 continue;
4428 pkgCache::PkgIterator package(dep.TargetPkg());
4429 if (package.end())
4430 continue;
4431 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4432 return true;
4433 }
4434
4435 return false;
4436 }
4437
4438 @protocol ConfirmationControllerDelegate
4439 - (void) cancelAndClear:(bool)clear;
4440 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4441 - (void) queue;
4442 @end
4443
4444 @interface ConfirmationController : CYBrowserController {
4445 _transient Database *database_;
4446
4447 UIAlertView *essential_;
4448
4449 NSDictionary *changes_;
4450 NSMutableArray *issues_;
4451 NSDictionary *sizes_;
4452
4453 BOOL substrate_;
4454 }
4455
4456 - (id) initWithDatabase:(Database *)database;
4457
4458 @end
4459
4460 @implementation ConfirmationController
4461
4462 - (void) dealloc {
4463 [changes_ release];
4464 [issues_ release];
4465 [sizes_ release];
4466
4467 if (essential_ != nil)
4468 [essential_ release];
4469
4470 [super dealloc];
4471 }
4472
4473 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4474 NSString *context([alert context]);
4475
4476 if ([context isEqualToString:@"remove"]) {
4477 if (button == [alert cancelButtonIndex]) {
4478 [self dismissModalViewControllerAnimated:YES];
4479 } else if (button == [alert firstOtherButtonIndex]) {
4480 if (substrate_)
4481 Finish_ = 2;
4482 [delegate_ confirmWithNavigationController:[self navigationController]];
4483 }
4484
4485 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4486 } else if ([context isEqualToString:@"unable"]) {
4487 [self dismissModalViewControllerAnimated:YES];
4488 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4489 } else {
4490 [super alertView:alert clickedButtonAtIndex:button];
4491 }
4492 }
4493
4494 - (void) _doContinue {
4495 [self dismissModalViewControllerAnimated:YES];
4496 [delegate_ cancelAndClear:NO];
4497 }
4498
4499 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4500 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4501 return nil;
4502 }
4503
4504 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4505 [super webView:view didClearWindowObject:window forFrame:frame];
4506
4507 [window setValue:[changes_ Cydia$webScriptObjectInContext:window] forKey:@"changes"];
4508 [window setValue:[issues_ Cydia$webScriptObjectInContext:window] forKey:@"issues"];
4509 [window setValue:[sizes_ Cydia$webScriptObjectInContext:window] forKey:@"sizes"];
4510
4511 [window setValue:self forKey:@"queue"];
4512 }
4513
4514 - (id) initWithDatabase:(Database *)database {
4515 if ((self = [super init]) != nil) {
4516 database_ = database;
4517
4518 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4519 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4520 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4521 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4522 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4523
4524 bool remove(false);
4525
4526 pkgCacheFile &cache([database_ cache]);
4527 NSArray *packages([database_ packages]);
4528 pkgDepCache::Policy *policy([database_ policy]);
4529
4530 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4531
4532 for (Package *package in packages) {
4533 pkgCache::PkgIterator iterator([package iterator]);
4534 NSString *name([package id]);
4535
4536 if ([package broken]) {
4537 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4538
4539 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4540 name, @"package",
4541 reasons, @"reasons",
4542 nil]];
4543
4544 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4545 if (ver.end())
4546 continue;
4547
4548 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4549 pkgCache::DepIterator start;
4550 pkgCache::DepIterator end;
4551 dep.GlobOr(start, end); // ++dep
4552
4553 if (!cache->IsImportantDep(end))
4554 continue;
4555 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4556 continue;
4557
4558 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4559
4560 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4561 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4562 clauses, @"clauses",
4563 nil]];
4564
4565 _forever {
4566 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4567
4568 pkgCache::PkgIterator target(start.TargetPkg());
4569 if (target->ProvidesList != 0)
4570 reason = @"missing";
4571 else {
4572 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4573 if (!ver.end()) {
4574 reason = @"installed";
4575 installed = [NSString stringWithUTF8String:ver.VerStr()];
4576 } else if (!cache[target].CandidateVerIter(cache).end())
4577 reason = @"uninstalled";
4578 else if (target->ProvidesList == 0)
4579 reason = @"uninstallable";
4580 else
4581 reason = @"virtual";
4582 }
4583
4584 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4585 [NSString stringWithUTF8String:start.CompType()], @"operator",
4586 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4587 nil]);
4588
4589 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4590 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4591 version, @"version",
4592 reason, @"reason",
4593 installed, @"installed",
4594 nil]];
4595
4596 // yes, seriously. (wtf?)
4597 if (start == end)
4598 break;
4599 ++start;
4600 }
4601 }
4602 }
4603
4604 pkgDepCache::StateCache &state(cache[iterator]);
4605
4606 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4607
4608 if (state.NewInstall())
4609 [installs addObject:name];
4610 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4611 [reinstalls addObject:name];
4612 else if (state.Upgrade())
4613 [upgrades addObject:name];
4614 else if (state.Downgrade())
4615 [downgrades addObject:name];
4616 else if (!state.Delete())
4617 continue;
4618 else if (special_r(name))
4619 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4620 [NSNull null], @"package",
4621 [NSArray arrayWithObjects:
4622 [NSDictionary dictionaryWithObjectsAndKeys:
4623 @"Conflicts", @"relationship",
4624 [NSArray arrayWithObjects:
4625 [NSDictionary dictionaryWithObjectsAndKeys:
4626 name, @"package",
4627 [NSNull null], @"version",
4628 @"installed", @"reason",
4629 nil],
4630 nil], @"clauses",
4631 nil],
4632 nil], @"reasons",
4633 nil]];
4634 else {
4635 if ([package essential])
4636 remove = true;
4637 [removes addObject:name];
4638 }
4639
4640 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4641 substrate_ |= DepSubstrate(iterator.CurrentVer());
4642 }
4643
4644 if (!remove)
4645 essential_ = nil;
4646 else if (Advanced_) {
4647 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4648
4649 essential_ = [[UIAlertView alloc]
4650 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4651 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4652 delegate:self
4653 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4654 otherButtonTitles:
4655 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4656 nil
4657 ];
4658
4659 [essential_ setContext:@"remove"];
4660 } else {
4661 essential_ = [[UIAlertView alloc]
4662 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4663 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4664 delegate:self
4665 cancelButtonTitle:UCLocalize("OKAY")
4666 otherButtonTitles:nil
4667 ];
4668
4669 [essential_ setContext:@"unable"];
4670 }
4671
4672 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4673 installs, @"installs",
4674 reinstalls, @"reinstalls",
4675 upgrades, @"upgrades",
4676 downgrades, @"downgrades",
4677 removes, @"removes",
4678 nil];
4679
4680 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4681 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4682 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4683 nil];
4684
4685 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4686
4687 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4688 initWithTitle:UCLocalize("CANCEL")
4689 style:UIBarButtonItemStylePlain
4690 target:self
4691 action:@selector(cancelButtonClicked)
4692 ] autorelease]];
4693 } return self;
4694 }
4695
4696 #if !AlwaysReload
4697 - (void) applyRightButton {
4698 if ([issues_ count] == 0 && ![self isLoading])
4699 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4700 initWithTitle:UCLocalize("CONFIRM")
4701 style:UIBarButtonItemStyleDone
4702 target:self
4703 action:@selector(confirmButtonClicked)
4704 ] autorelease]];
4705 else
4706 [[self navigationItem] setRightBarButtonItem:nil];
4707 }
4708 #endif
4709
4710 - (void) cancelButtonClicked {
4711 [self dismissModalViewControllerAnimated:YES];
4712 [delegate_ cancelAndClear:YES];
4713 }
4714
4715 #if !AlwaysReload
4716 - (void) confirmButtonClicked {
4717 if (essential_ != nil)
4718 [essential_ show];
4719 else {
4720 if (substrate_)
4721 Finish_ = 2;
4722 [delegate_ confirmWithNavigationController:[self navigationController]];
4723 }
4724 }
4725 #endif
4726
4727 @end
4728 /* }}} */
4729
4730 /* Progress Data {{{ */
4731 @interface ProgressData : NSObject {
4732 SEL selector_;
4733 // XXX: should these really both be _transient?
4734 _transient id target_;
4735 _transient id object_;
4736 }
4737
4738 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4739
4740 - (SEL) selector;
4741 - (id) target;
4742 - (id) object;
4743
4744 @end
4745
4746 @implementation ProgressData
4747
4748 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4749 if ((self = [super init]) != nil) {
4750 selector_ = selector;
4751 target_ = target;
4752 object_ = object;
4753 } return self;
4754 }
4755
4756 - (SEL) selector {
4757 return selector_;
4758 }
4759
4760 - (id) target {
4761 return target_;
4762 }
4763
4764 - (id) object {
4765 return object_;
4766 }
4767
4768 @end
4769 /* }}} */
4770 /* Progress Controller {{{ */
4771 @interface ProgressController : CYViewController <
4772 ConfigurationDelegate,
4773 ProgressDelegate
4774 > {
4775 _transient Database *database_;
4776 UIProgressBar *progress_;
4777 UITextView *output_;
4778 UITextLabel *status_;
4779 UIPushButton *close_;
4780 BOOL running_;
4781 SHA1SumValue springlist_;
4782 SHA1SumValue notifyconf_;
4783 NSString *title_;
4784 }
4785
4786 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4787
4788 - (void) _retachThread;
4789 - (void) _detachNewThreadData:(ProgressData *)data;
4790 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4791
4792 - (BOOL) isRunning;
4793
4794 @end
4795
4796 @protocol ProgressControllerDelegate
4797 - (void) progressControllerIsComplete:(ProgressController *)sender;
4798 @end
4799
4800 @implementation ProgressController
4801
4802 - (void) dealloc {
4803 [database_ setDelegate:nil];
4804 [progress_ release];
4805 [output_ release];
4806 [status_ release];
4807 [close_ release];
4808 if (title_ != nil)
4809 [title_ release];
4810 [super dealloc];
4811 }
4812
4813 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4814 if ((self = [super init]) != nil) {
4815 database_ = database;
4816 [database_ setDelegate:self];
4817 delegate_ = delegate;
4818
4819 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4820
4821 progress_ = [[UIProgressBar alloc] init];
4822 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4823 [progress_ setStyle:0];
4824
4825 status_ = [[UITextLabel alloc] init];
4826 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4827 [status_ setColor:[UIColor whiteColor]];
4828 [status_ setBackgroundColor:[UIColor clearColor]];
4829 [status_ setCentersHorizontally:YES];
4830 //[status_ setFont:font];
4831
4832 output_ = [[UITextView alloc] init];
4833 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4834 //[output_ setTextFont:@"Courier New"];
4835 [output_ setFont:[[output_ font] fontWithSize:12]];
4836 [output_ setTextColor:[UIColor whiteColor]];
4837 [output_ setBackgroundColor:[UIColor clearColor]];
4838 [output_ setMarginTop:0];
4839 [output_ setAllowsRubberBanding:YES];
4840 [output_ setEditable:NO];
4841 [[self view] addSubview:output_];
4842
4843 close_ = [[UIPushButton alloc] init];
4844 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4845 [close_ setAutosizesToFit:NO];
4846 [close_ setDrawsShadow:YES];
4847 [close_ setStretchBackground:YES];
4848 [close_ setEnabled:YES];
4849 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4850 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4851 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4852 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4853 } return self;
4854 }
4855
4856 - (void) positionViews {
4857 CGRect bounds = [[self view] bounds];
4858 CGSize prgsize = [UIProgressBar defaultSize];
4859
4860 CGRect prgrect = {{
4861 (bounds.size.width - prgsize.width) / 2,
4862 bounds.size.height - prgsize.height - 20
4863 }, prgsize};
4864
4865 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4866
4867 [progress_ setFrame:prgrect];
4868 [status_ setFrame:CGRectMake(
4869 10,
4870 bounds.size.height - prgsize.height - 50,
4871 bounds.size.width - 20,
4872 24
4873 )];
4874 [output_ setFrame:CGRectMake(
4875 10,
4876 20,
4877 bounds.size.width - 20,
4878 bounds.size.height - 96
4879 )];
4880 [close_ setFrame:CGRectMake(
4881 (bounds.size.width - closewidth) / 2,
4882 bounds.size.height - prgsize.height - 50,
4883 closewidth,
4884 32 + prgsize.height
4885 )];
4886 }
4887
4888 - (void) viewWillAppear:(BOOL)animated {
4889 [super viewDidAppear:animated];
4890 [[self navigationItem] setHidesBackButton:YES];
4891 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4892
4893 [self positionViews];
4894 }
4895
4896 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4897 [self positionViews];
4898 }
4899
4900 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4901 NSString *context([alert context]);
4902
4903 if ([context isEqualToString:@"conffile"]) {
4904 FILE *input = [database_ input];
4905 if (button == [alert cancelButtonIndex])
4906 fprintf(input, "N\n");
4907 else if (button == [alert firstOtherButtonIndex])
4908 fprintf(input, "Y\n");
4909 fflush(input);
4910 }
4911 }
4912
4913 - (void) closeButtonPushed {
4914 running_ = NO;
4915
4916 UpdateExternalStatus(0);
4917
4918 switch (Finish_) {
4919 case 0:
4920 [self dismissModalViewControllerAnimated:YES];
4921 break;
4922
4923 case 1:
4924 [delegate_ terminateWithSuccess];
4925 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4926 [delegate_ suspendWithAnimation:YES];
4927 else
4928 [delegate_ suspend];*/
4929 break;
4930
4931 case 2:
4932 _trace();
4933 goto reload;
4934
4935 case 3:
4936 _trace();
4937 goto reload;
4938
4939 reload:
4940 system("/usr/bin/sbreload");
4941 _trace();
4942 break;
4943
4944 case 4:
4945 _trace();
4946 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4947 SBReboot(SBSSpringBoardServerPort());
4948 else
4949 reboot2(RB_AUTOBOOT);
4950 break;
4951 }
4952 }
4953
4954 - (void) _retachThread {
4955 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4956
4957 [[self view] addSubview:close_];
4958 [progress_ removeFromSuperview];
4959 [status_ removeFromSuperview];
4960
4961 [database_ popErrorWithTitle:title_];
4962 [delegate_ progressControllerIsComplete:self];
4963
4964 if (Finish_ < 4) {
4965 FileFd file;
4966 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4967 _error->Discard();
4968 else {
4969 MMap mmap(file, MMap::ReadOnly);
4970 SHA1Summation sha1;
4971 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4972 if (!(notifyconf_ == sha1.Result()))
4973 Finish_ = 4;
4974 }
4975 }
4976
4977 if (Finish_ < 3) {
4978 FileFd file;
4979 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4980 _error->Discard();
4981 else {
4982 MMap mmap(file, MMap::ReadOnly);
4983 SHA1Summation sha1;
4984 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4985 if (!(springlist_ == sha1.Result()))
4986 Finish_ = 3;
4987 }
4988 }
4989
4990 switch (Finish_) {
4991 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4992 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4993 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4994 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4995 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4996 }
4997
4998 _trace();
4999 system("su -c /usr/bin/uicache mobile");
5000 _trace();
5001
5002 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
5003
5004 [delegate_ setStatusBarShowsProgress:NO];
5005 }
5006
5007 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
5008 [[data target] performSelector:[data selector] withObject:[data object]];
5009 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
5010 }
5011
5012 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
5013 UpdateExternalStatus(1);
5014
5015 if (title_ != nil)
5016 [title_ release];
5017 if (title == nil)
5018 title_ = nil;
5019 else
5020 title_ = [title retain];
5021
5022 [[self navigationItem] setTitle:title_];
5023
5024 [status_ setText:nil];
5025 [output_ setText:@""];
5026 [progress_ setProgress:0];
5027
5028 [close_ removeFromSuperview];
5029 [[self view] addSubview:progress_];
5030 [[self view] addSubview:status_];
5031
5032 [delegate_ setStatusBarShowsProgress:YES];
5033 running_ = YES;
5034
5035 {
5036 FileFd file;
5037 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5038 _error->Discard();
5039 else {
5040 MMap mmap(file, MMap::ReadOnly);
5041 SHA1Summation sha1;
5042 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5043 notifyconf_ = sha1.Result();
5044 }
5045 }
5046
5047 {
5048 FileFd file;
5049 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5050 _error->Discard();
5051 else {
5052 MMap mmap(file, MMap::ReadOnly);
5053 SHA1Summation sha1;
5054 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5055 springlist_ = sha1.Result();
5056 }
5057 }
5058
5059 [NSThread
5060 detachNewThreadSelector:@selector(_detachNewThreadData:)
5061 toTarget:self
5062 withObject:[[[ProgressData alloc]
5063 initWithSelector:selector
5064 target:target
5065 object:object
5066 ] autorelease]
5067 ];
5068 }
5069
5070 - (void) repairWithSelector:(SEL)selector {
5071 [self
5072 detachNewThreadSelector:selector
5073 toTarget:database_
5074 withObject:nil
5075 title:UCLocalize("REPAIRING")
5076 ];
5077 }
5078
5079 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5080 CYAlertView *sheet([[[CYAlertView alloc]
5081 initWithTitle:title
5082 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5083 defaultButtonIndex:0
5084 ] autorelease]);
5085
5086 [sheet setMessage:error];
5087 [sheet yieldToPopupAlertAnimated:YES];
5088 [sheet dismiss];
5089 }
5090
5091 - (void) startProgress {
5092 }
5093
5094 - (bool) isCancelling:(size_t)received {
5095 return false;
5096 }
5097
5098 - (void) setConfigurationData:(NSString *)data {
5099 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5100
5101 if (!conffile_r(data)) {
5102 lprintf("E:invalid conffile\n");
5103 return;
5104 }
5105
5106 NSString *ofile = conffile_r[1];
5107 //NSString *nfile = conffile_r[2];
5108
5109 UIAlertView *alert = [[[UIAlertView alloc]
5110 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5111 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5112 delegate:self
5113 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5114 otherButtonTitles:
5115 UCLocalize("ACCEPT_NEW_COPY"),
5116 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5117 nil
5118 ] autorelease];
5119
5120 [alert setContext:@"conffile"];
5121 [alert show];
5122 }
5123
5124 - (void) setProgressTitle:(NSString *)title {
5125 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5126 for (size_t i(0), e([words count]); i != e; ++i) {
5127 NSString *word([words objectAtIndex:i]);
5128 if (Package *package = [database_ packageWithName:word])
5129 [words replaceObjectAtIndex:i withObject:[package name]];
5130 }
5131
5132 [status_ setText:[words componentsJoinedByString:@" "]];
5133 }
5134
5135 - (void) setProgressPercent:(NSNumber *)percent {
5136 [progress_ setProgress:[percent floatValue]];
5137 }
5138
5139 - (void) addProgressOutput:(NSString *)output {
5140 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5141 CGSize size = [output_ contentSize];
5142 CGPoint offset = [output_ contentOffset];
5143 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5144 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5145 [output_ scrollRectToVisible:rect animated:YES];
5146 }
5147 }
5148
5149 - (BOOL) isRunning {
5150 return running_;
5151 }
5152
5153 @end
5154 /* }}} */
5155
5156 /* Cell Content View {{{ */
5157 @protocol ContentDelegate
5158 - (void) drawContentRect:(CGRect)rect;
5159 @end
5160
5161 @interface ContentView : UIView {
5162 _transient id<ContentDelegate> delegate_;
5163 }
5164
5165 @end
5166
5167 @implementation ContentView
5168
5169 - (id) initWithFrame:(CGRect)frame {
5170 if ((self = [super initWithFrame:frame]) != nil) {
5171 [self setNeedsDisplayOnBoundsChange:YES];
5172 } return self;
5173 }
5174
5175 - (void) setDelegate:(id<ContentDelegate>)delegate {
5176 delegate_ = delegate;
5177 }
5178
5179 - (void) drawRect:(CGRect)rect {
5180 [super drawRect:rect];
5181 [delegate_ drawContentRect:rect];
5182 }
5183
5184 @end
5185 /* }}} */
5186 /* Cydia TableView Cell {{{ */
5187 @interface CYTableViewCell : UITableViewCell {
5188 ContentView *content_;
5189 bool highlighted_;
5190 }
5191
5192 @end
5193
5194 @implementation CYTableViewCell
5195
5196 - (void) dealloc {
5197 [content_ release];
5198 [super dealloc];
5199 }
5200
5201 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5202 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5203
5204 if (view == content_) {
5205 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5206 highlighted_ = highlighted;
5207 }
5208
5209 [super _updateHighlightColorsForView:view highlighted:highlighted];
5210 }
5211
5212 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5213 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5214 highlighted_ = selected;
5215
5216 [super setSelected:selected animated:animated];
5217 [content_ setNeedsDisplay];
5218 }
5219
5220 @end
5221 /* }}} */
5222
5223 /* Package Cell {{{ */
5224 @interface PackageCell : CYTableViewCell <
5225 ContentDelegate
5226 > {
5227 UIImage *icon_;
5228 NSString *name_;
5229 NSString *description_;
5230 bool commercial_;
5231 NSString *source_;
5232 UIImage *badge_;
5233 Package *package_;
5234 UIImage *placard_;
5235 }
5236
5237 - (PackageCell *) init;
5238 - (void) setPackage:(Package *)package;
5239
5240 - (void) drawContentRect:(CGRect)rect;
5241
5242 @end
5243
5244 @implementation PackageCell
5245
5246 - (void) clearPackage {
5247 if (icon_ != nil) {
5248 [icon_ release];
5249 icon_ = nil;
5250 }
5251
5252 if (name_ != nil) {
5253 [name_ release];
5254 name_ = nil;
5255 }
5256
5257 if (description_ != nil) {
5258 [description_ release];
5259 description_ = nil;
5260 }
5261
5262 if (source_ != nil) {
5263 [source_ release];
5264 source_ = nil;
5265 }
5266
5267 if (badge_ != nil) {
5268 [badge_ release];
5269 badge_ = nil;
5270 }
5271
5272 if (placard_ != nil) {
5273 [placard_ release];
5274 placard_ = nil;
5275 }
5276
5277 [package_ release];
5278 package_ = nil;
5279 }
5280
5281 - (void) dealloc {
5282 [self clearPackage];
5283 [super dealloc];
5284 }
5285
5286 - (PackageCell *) init {
5287 CGRect frame(CGRectMake(0, 0, 320, 74));
5288 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5289 UIView *content([self contentView]);
5290 CGRect bounds([content bounds]);
5291
5292 content_ = [[ContentView alloc] initWithFrame:bounds];
5293 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5294 [content addSubview:content_];
5295
5296 [content_ setDelegate:self];
5297 [content_ setOpaque:YES];
5298 } return self;
5299 }
5300
5301 - (NSString *) accessibilityLabel {
5302 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5303 }
5304
5305 - (void) setPackage:(Package *)package {
5306 [self clearPackage];
5307 [package parse];
5308
5309 Source *source = [package source];
5310
5311 icon_ = [[package icon] retain];
5312 name_ = [[package name] retain];
5313
5314 if (IsWildcat_)
5315 description_ = [package longDescription];
5316 if (description_ == nil)
5317 description_ = [package shortDescription];
5318 if (description_ != nil)
5319 description_ = [description_ retain];
5320
5321 commercial_ = [package isCommercial];
5322
5323 package_ = [package retain];
5324
5325 NSString *label = nil;
5326 bool trusted = false;
5327
5328 if (source != nil) {
5329 label = [source label];
5330 trusted = [source trusted];
5331 } else if ([[package id] isEqualToString:@"firmware"])
5332 label = UCLocalize("APPLE");
5333 else
5334 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5335
5336 NSString *from(label);
5337
5338 NSString *section = [package simpleSection];
5339 if (section != nil && ![section isEqualToString:label]) {
5340 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5341 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5342 }
5343
5344 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5345 source_ = [from retain];
5346
5347 if (NSString *purpose = [package primaryPurpose])
5348 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5349 badge_ = [badge_ retain];
5350
5351 UIColor *color;
5352 NSString *placard;
5353
5354 if (NSString *mode = [package_ mode]) {
5355 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5356 color = RemovingColor_;
5357 //placard = @"removing";
5358 } else {
5359 color = InstallingColor_;
5360 //placard = @"installing";
5361 }
5362
5363 // XXX: the removing/installing placards are not @2x
5364 placard = nil;
5365 } else {
5366 color = [UIColor whiteColor];
5367
5368 if ([package installed] != nil)
5369 placard = @"installed";
5370 else
5371 placard = nil;
5372 }
5373
5374 [content_ setBackgroundColor:color];
5375
5376 if (placard != nil)
5377 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5378 placard_ = [placard_ retain];
5379
5380 [self setNeedsDisplay];
5381 [content_ setNeedsDisplay];
5382 }
5383
5384 - (void) drawContentRect:(CGRect)rect {
5385 bool highlighted(highlighted_);
5386 float width([self bounds].size.width);
5387
5388 #if 0
5389 CGContextRef context(UIGraphicsGetCurrentContext());
5390 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5391 CGContextFillRect(context, rect);
5392 #endif
5393
5394 if (icon_ != nil) {
5395 CGRect rect;
5396 rect.size = [icon_ size];
5397
5398 rect.size.width /= 2;
5399 rect.size.height /= 2;
5400
5401 rect.origin.x = 25 - rect.size.width / 2;
5402 rect.origin.y = 25 - rect.size.height / 2;
5403
5404 [icon_ drawInRect:rect];
5405 }
5406
5407 if (badge_ != nil) {
5408 CGRect rect;
5409 rect.size = [badge_ size];
5410
5411 rect.size.width /= 2;
5412 rect.size.height /= 2;
5413
5414 rect.origin.x = 36 - rect.size.width / 2;
5415 rect.origin.y = 36 - rect.size.height / 2;
5416
5417 [badge_ drawInRect:rect];
5418 }
5419
5420 if (highlighted)
5421 UISetColor(White_);
5422
5423 if (!highlighted)
5424 UISetColor(commercial_ ? Purple_ : Black_);
5425 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5426 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5427
5428 if (!highlighted)
5429 UISetColor(commercial_ ? Purplish_ : Gray_);
5430 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5431
5432 if (placard_ != nil)
5433 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5434 }
5435
5436 @end
5437 /* }}} */
5438 /* Section Cell {{{ */
5439 @interface SectionCell : CYTableViewCell <
5440 ContentDelegate
5441 > {
5442 NSString *basic_;
5443 NSString *section_;
5444 NSString *name_;
5445 NSString *count_;
5446 UIImage *icon_;
5447 UISwitch *switch_;
5448 BOOL editing_;
5449 }
5450
5451 - (void) setSection:(Section *)section editing:(BOOL)editing;
5452
5453 @end
5454
5455 @implementation SectionCell
5456
5457 - (void) clearSection {
5458 if (basic_ != nil) {
5459 [basic_ release];
5460 basic_ = nil;
5461 }
5462
5463 if (section_ != nil) {
5464 [section_ release];
5465 section_ = nil;
5466 }
5467
5468 if (name_ != nil) {
5469 [name_ release];
5470 name_ = nil;
5471 }
5472
5473 if (count_ != nil) {
5474 [count_ release];
5475 count_ = nil;
5476 }
5477 }
5478
5479 - (void) dealloc {
5480 [self clearSection];
5481 [icon_ release];
5482 [switch_ release];
5483 [super dealloc];
5484 }
5485
5486 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5487 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5488 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5489 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5490 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5491
5492 UIView *content([self contentView]);
5493 CGRect bounds([content bounds]);
5494
5495 content_ = [[ContentView alloc] initWithFrame:bounds];
5496 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5497 [content addSubview:content_];
5498 [content_ setBackgroundColor:[UIColor whiteColor]];
5499
5500 [content_ setDelegate:self];
5501 } return self;
5502 }
5503
5504 - (void) onSwitch:(id)sender {
5505 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5506 if (metadata == nil) {
5507 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5508 [Sections_ setObject:metadata forKey:basic_];
5509 }
5510
5511 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5512 Changed_ = true;
5513 }
5514
5515 - (void) setSection:(Section *)section editing:(BOOL)editing {
5516 if (editing != editing_) {
5517 if (editing_)
5518 [switch_ removeFromSuperview];
5519 else
5520 [self addSubview:switch_];
5521 editing_ = editing;
5522 }
5523
5524 [self clearSection];
5525
5526 if (section == nil) {
5527 name_ = [UCLocalize("ALL_PACKAGES") retain];
5528 count_ = nil;
5529 } else {
5530 basic_ = [section name];
5531 if (basic_ != nil)
5532 basic_ = [basic_ retain];
5533
5534 section_ = [section localized];
5535 if (section_ != nil)
5536 section_ = [section_ retain];
5537
5538 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5539 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5540
5541 if (editing_)
5542 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5543 }
5544
5545 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5546 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5547
5548 [content_ setNeedsDisplay];
5549 }
5550
5551 - (void) setFrame:(CGRect)frame {
5552 [super setFrame:frame];
5553
5554 CGRect rect([switch_ frame]);
5555 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5556 }
5557
5558 - (NSString *) accessibilityLabel {
5559 return name_;
5560 }
5561
5562 - (void) drawContentRect:(CGRect)rect {
5563 bool highlighted(highlighted_ && !editing_);
5564
5565 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5566
5567 if (highlighted)
5568 UISetColor(White_);
5569
5570 float width(rect.size.width);
5571 if (editing_)
5572 width -= 87;
5573
5574 if (!highlighted)
5575 UISetColor(Black_);
5576 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5577
5578 CGSize size = [count_ sizeWithFont:Font14_];
5579
5580 UISetColor(White_);
5581 if (count_ != nil)
5582 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5583 }
5584
5585 @end
5586 /* }}} */
5587
5588 /* File Table {{{ */
5589 @interface FileTable : CYViewController <
5590 UITableViewDataSource,
5591 UITableViewDelegate
5592 > {
5593 _transient Database *database_;
5594 Package *package_;
5595 NSString *name_;
5596 NSMutableArray *files_;
5597 UITableView *list_;
5598 }
5599
5600 - (id) initWithDatabase:(Database *)database;
5601 - (void) setPackage:(Package *)package;
5602
5603 @end
5604
5605 @implementation FileTable
5606
5607 - (void) dealloc {
5608 [self releaseSubviews];
5609
5610 [package_ release];
5611 [name_ release];
5612 [files_ release];
5613
5614 [super dealloc];
5615 }
5616
5617 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5618 return files_ == nil ? 0 : [files_ count];
5619 }
5620
5621 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5622 return 24.0f;
5623 }*/
5624
5625 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5626 static NSString *reuseIdentifier = @"Cell";
5627
5628 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5629 if (cell == nil) {
5630 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5631 [cell setFont:[UIFont systemFontOfSize:16]];
5632 }
5633 [cell setText:[files_ objectAtIndex:indexPath.row]];
5634 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5635
5636 return cell;
5637 }
5638
5639 - (NSURL *) navigationURL {
5640 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5641 }
5642
5643 - (void) loadView {
5644 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5645
5646 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5647 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5648 [list_ setRowHeight:24.0f];
5649 [list_ setDataSource:self];
5650 [list_ setDelegate:self];
5651 [[self view] addSubview:list_];
5652 }
5653
5654 - (void) viewDidLoad {
5655 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5656 }
5657
5658 - (void) releaseSubviews {
5659 [list_ release];
5660 list_ = nil;
5661 }
5662
5663 - (id) initWithDatabase:(Database *)database {
5664 if ((self = [super init]) != nil) {
5665 database_ = database;
5666
5667 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5668 } return self;
5669 }
5670
5671 - (void) setPackage:(Package *)package {
5672 if (package_ != nil) {
5673 [package_ autorelease];
5674 package_ = nil;
5675 }
5676
5677 if (name_ != nil) {
5678 [name_ release];
5679 name_ = nil;
5680 }
5681
5682 [files_ removeAllObjects];
5683
5684 if (package != nil) {
5685 package_ = [package retain];
5686 name_ = [[package id] retain];
5687
5688 if (NSArray *files = [package files])
5689 [files_ addObjectsFromArray:files];
5690
5691 if ([files_ count] != 0) {
5692 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5693 [files_ removeObjectAtIndex:0];
5694 [files_ sortUsingSelector:@selector(compareByPath:)];
5695
5696 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5697 [stack addObject:@"/"];
5698
5699 for (int i(0), e([files_ count]); i != e; ++i) {
5700 NSString *file = [files_ objectAtIndex:i];
5701 while (![file hasPrefix:[stack lastObject]])
5702 [stack removeLastObject];
5703 NSString *directory = [stack lastObject];
5704 [stack addObject:[file stringByAppendingString:@"/"]];
5705 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5706 ([stack count] - 2) * 3, "",
5707 [file substringFromIndex:[directory length]]
5708 ]];
5709 }
5710 }
5711 }
5712
5713 [list_ reloadData];
5714 }
5715
5716 - (void) reloadData {
5717 [super reloadData];
5718
5719 [self setPackage:[database_ packageWithName:name_]];
5720 }
5721
5722 @end
5723 /* }}} */
5724 /* Package Controller {{{ */
5725 @interface CYPackageController : CYBrowserController <
5726 UIActionSheetDelegate
5727 > {
5728 _transient Database *database_;
5729 Package *package_;
5730 NSString *name_;
5731 bool commercial_;
5732 NSMutableArray *buttons_;
5733 UIBarButtonItem *button_;
5734 }
5735
5736 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5737
5738 @end
5739
5740 @implementation CYPackageController
5741
5742 - (void) dealloc {
5743 if (package_ != nil)
5744 [package_ release];
5745 if (name_ != nil)
5746 [name_ release];
5747
5748 [buttons_ release];
5749
5750 if (button_ != nil)
5751 [button_ release];
5752
5753 [super dealloc];
5754 }
5755
5756 - (NSURL *) navigationURL {
5757 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5758 }
5759
5760 /* XXX: this is not safe at all... localization of /fail/ */
5761 - (void) _clickButtonWithName:(NSString *)name {
5762 if ([name isEqualToString:UCLocalize("CLEAR")])
5763 [delegate_ clearPackage:package_];
5764 else if ([name isEqualToString:UCLocalize("INSTALL")])
5765 [delegate_ installPackage:package_];
5766 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5767 [delegate_ installPackage:package_];
5768 else if ([name isEqualToString:UCLocalize("REMOVE")])
5769 [delegate_ removePackage:package_];
5770 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5771 [delegate_ installPackage:package_];
5772 else _assert(false);
5773 }
5774
5775 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5776 NSString *context([sheet context]);
5777
5778 if ([context isEqualToString:@"modify"]) {
5779 if (button != [sheet cancelButtonIndex]) {
5780 NSString *buttonName = [buttons_ objectAtIndex:button];
5781 [self _clickButtonWithName:buttonName];
5782 }
5783
5784 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5785 }
5786 }
5787
5788 - (bool) _allowJavaScriptPanel {
5789 return commercial_;
5790 }
5791
5792 #if !AlwaysReload
5793 - (void) _customButtonClicked {
5794 int count([buttons_ count]);
5795 if (count == 0)
5796 return;
5797
5798 if (count == 1)
5799 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5800 else {
5801 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5802 [buttons addObjectsFromArray:buttons_];
5803
5804 UIActionSheet *sheet = [[[UIActionSheet alloc]
5805 initWithTitle:nil
5806 delegate:self
5807 cancelButtonTitle:nil
5808 destructiveButtonTitle:nil
5809 otherButtonTitles:nil
5810 ] autorelease];
5811
5812 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5813 if (!IsWildcat_) {
5814 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5815 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5816 }
5817 [sheet setContext:@"modify"];
5818
5819 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5820 }
5821 }
5822
5823 // We don't want to allow non-commercial packages to do custom things to the install button,
5824 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5825 - (void) customButtonClicked {
5826 if (commercial_)
5827 [super customButtonClicked];
5828 else
5829 [self _customButtonClicked];
5830 }
5831
5832 - (void) reloadButtonClicked {
5833 // Don't reload a commerical package by tapping the loading button,
5834 // but if it's not an Install button, we should forward it on.
5835 if (![package_ uninstalled])
5836 [self _customButtonClicked];
5837 }
5838
5839 - (void) applyLoadingTitle {
5840 // Don't show "Loading" as the title. Ever.
5841 }
5842
5843 - (UIBarButtonItem *) rightButton {
5844 return button_;
5845 }
5846 #endif
5847
5848 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5849 if ((self = [super init]) != nil) {
5850 database_ = database;
5851 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5852 name_ = [[NSString alloc] initWithString:name];
5853 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5854 } return self;
5855 }
5856
5857 - (void) reloadData {
5858 if (package_ != nil)
5859 [package_ autorelease];
5860 package_ = [database_ packageWithName:name_];
5861
5862 [buttons_ removeAllObjects];
5863
5864 if (package_ != nil) {
5865 [package_ parse];
5866
5867 package_ = [package_ retain];
5868 commercial_ = [package_ isCommercial];
5869
5870 if ([package_ mode] != nil)
5871 [buttons_ addObject:UCLocalize("CLEAR")];
5872 if ([package_ source] == nil);
5873 else if ([package_ upgradableAndEssential:NO])
5874 [buttons_ addObject:UCLocalize("UPGRADE")];
5875 else if ([package_ uninstalled])
5876 [buttons_ addObject:UCLocalize("INSTALL")];
5877 else
5878 [buttons_ addObject:UCLocalize("REINSTALL")];
5879 if (![package_ uninstalled])
5880 [buttons_ addObject:UCLocalize("REMOVE")];
5881 }
5882
5883 if (button_ != nil)
5884 [button_ release];
5885
5886 NSString *title;
5887 switch ([buttons_ count]) {
5888 case 0: title = nil; break;
5889 case 1: title = [buttons_ objectAtIndex:0]; break;
5890 default: title = UCLocalize("MODIFY"); break;
5891 }
5892
5893 button_ = [[UIBarButtonItem alloc]
5894 initWithTitle:title
5895 style:UIBarButtonItemStylePlain
5896 target:self
5897 action:@selector(customButtonClicked)
5898 ];
5899
5900 [super reloadData];
5901 }
5902
5903 - (bool) isLoading {
5904 return commercial_ ? [super isLoading] : false;
5905 }
5906
5907 @end
5908 /* }}} */
5909
5910 /* Package List Controller {{{ */
5911 @interface PackageListController : CYViewController <
5912 UITableViewDataSource,
5913 UITableViewDelegate
5914 > {
5915 _transient Database *database_;
5916 unsigned era_;
5917 NSMutableArray *packages_;
5918 NSMutableArray *sections_;
5919 UITableView *list_;
5920 NSMutableArray *index_;
5921 NSMutableDictionary *indices_;
5922 NSString *title_;
5923 }
5924
5925 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5926 - (void) setDelegate:(id)delegate;
5927 - (void) resetCursor;
5928
5929 @end
5930
5931 @implementation PackageListController
5932
5933 - (void) dealloc {
5934 [packages_ release];
5935 [sections_ release];
5936 [list_ release];
5937 [index_ release];
5938 [indices_ release];
5939 [title_ release];
5940
5941 [super dealloc];
5942 }
5943
5944 - (void) deselectWithAnimation:(BOOL)animated {
5945 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5946 }
5947
5948 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5949 CGRect base = [[self view] bounds];
5950 base.size.height -= bounds.size.height;
5951 base.origin = [list_ frame].origin;
5952
5953 [UIView beginAnimations:nil context:NULL];
5954 [UIView setAnimationBeginsFromCurrentState:YES];
5955 [UIView setAnimationCurve:curve];
5956 [UIView setAnimationDuration:duration];
5957 [list_ setFrame:base];
5958 [UIView commitAnimations];
5959 }
5960
5961 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5962 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5963 }
5964
5965 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5966 [self resizeForKeyboardBounds:bounds duration:0];
5967 }
5968
5969 - (void) keyboardWillShow:(NSNotification *)notification {
5970 CGRect bounds;
5971 CGPoint center;
5972 NSTimeInterval duration;
5973 UIViewAnimationCurve curve;
5974 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5975 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
5976 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5977 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5978
5979 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);
5980 UIViewController *base = self;
5981 while ([base parentViewController] != nil)
5982 base = [base parentViewController];
5983 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5984 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5985
5986 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5987 }
5988
5989 - (void) keyboardWillHide:(NSNotification *)notification {
5990 NSTimeInterval duration;
5991 UIViewAnimationCurve curve;
5992 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5993 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5994
5995 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5996 }
5997
5998 - (void) viewWillAppear:(BOOL)animated {
5999 [super viewWillAppear:animated];
6000
6001 [self resizeForKeyboardBounds:CGRectZero];
6002 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6003 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6004 }
6005
6006 - (void) viewWillDisappear:(BOOL)animated {
6007 [super viewWillDisappear:animated];
6008
6009 [self resizeForKeyboardBounds:CGRectZero];
6010 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6011 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6012 }
6013
6014 - (void) viewDidAppear:(BOOL)animated {
6015 [super viewDidAppear:animated];
6016 [self deselectWithAnimation:animated];
6017 }
6018
6019 - (void) didSelectPackage:(Package *)package {
6020 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6021 [view setDelegate:delegate_];
6022 [[self navigationController] pushViewController:view animated:YES];
6023 }
6024
6025 #if TryIndexedCollation
6026 + (BOOL) hasIndexedCollation {
6027 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6028 }
6029 #endif
6030
6031 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6032 NSInteger count([sections_ count]);
6033 return count == 0 ? 1 : count;
6034 }
6035
6036 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6037 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6038 return nil;
6039 return [[sections_ objectAtIndex:section] name];
6040 }
6041
6042 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6043 if ([sections_ count] == 0)
6044 return 0;
6045 return [[sections_ objectAtIndex:section] count];
6046 }
6047
6048 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6049 @synchronized (database_) {
6050 if ([database_ era] != era_)
6051 return nil;
6052
6053 Section *section([sections_ objectAtIndex:[path section]]);
6054 NSInteger row([path row]);
6055 Package *package([packages_ objectAtIndex:([section row] + row)]);
6056 return [[package retain] autorelease];
6057 } }
6058
6059 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6060 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6061 if (cell == nil)
6062 cell = [[[PackageCell alloc] init] autorelease];
6063 [cell setPackage:[self packageAtIndexPath:path]];
6064 return cell;
6065 }
6066
6067 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6068 Package *package([self packageAtIndexPath:path]);
6069 package = [database_ packageWithName:[package id]];
6070 [self didSelectPackage:package];
6071 }
6072
6073 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6074 // XXX: is 20 the most optimal number here?
6075 return [packages_ count] > 20 ? index_ : nil;
6076 }
6077
6078 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6079 #if TryIndexedCollation
6080 if ([[self class] hasIndexedCollation]) {
6081 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6082 }
6083 #endif
6084
6085 return index;
6086 }
6087
6088 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6089 if ((self = [super init]) != nil) {
6090 database_ = database;
6091 title_ = [title copy];
6092 [[self navigationItem] setTitle:title_];
6093
6094 #if TryIndexedCollation
6095 if ([[self class] hasIndexedCollation])
6096 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6097 else
6098 #endif
6099 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6100
6101 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6102
6103 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6104 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6105
6106 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6107 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6108 [list_ setRowHeight:73];
6109 [[self view] addSubview:list_];
6110
6111 [list_ setDataSource:self];
6112 [list_ setDelegate:self];
6113 } return self;
6114 }
6115
6116 - (void) setDelegate:(id)delegate {
6117 delegate_ = delegate;
6118 }
6119
6120 - (bool) hasPackage:(Package *)package {
6121 return true;
6122 }
6123
6124 - (void) reloadData {
6125 [super reloadData];
6126
6127 era_ = [database_ era];
6128 NSArray *packages = [database_ packages];
6129
6130 [packages_ removeAllObjects];
6131 [sections_ removeAllObjects];
6132
6133 _profile(PackageTable$reloadData$Filter)
6134 for (Package *package in packages)
6135 if ([self hasPackage:package])
6136 [packages_ addObject:package];
6137 _end
6138
6139 [indices_ removeAllObjects];
6140
6141 Section *section = nil;
6142
6143 #if TryIndexedCollation
6144 if ([[self class] hasIndexedCollation]) {
6145 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6146 NSArray *titles = [collation sectionIndexTitles];
6147 int secidx = -1;
6148
6149 _profile(PackageTable$reloadData$Section)
6150 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6151 Package *package;
6152 int index;
6153
6154 _profile(PackageTable$reloadData$Section$Package)
6155 package = [packages_ objectAtIndex:offset];
6156 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6157 _end
6158
6159 while (secidx < index) {
6160 secidx += 1;
6161
6162 _profile(PackageTable$reloadData$Section$Allocate)
6163 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6164 _end
6165
6166 _profile(PackageTable$reloadData$Section$Add)
6167 [sections_ addObject:section];
6168 _end
6169 }
6170
6171 [section addToCount];
6172 }
6173 _end
6174 } else
6175 #endif
6176 {
6177 [index_ removeAllObjects];
6178
6179 _profile(PackageTable$reloadData$Section)
6180 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6181 Package *package;
6182 unichar index;
6183
6184 _profile(PackageTable$reloadData$Section$Package)
6185 package = [packages_ objectAtIndex:offset];
6186 index = [package index];
6187 _end
6188
6189 if (section == nil || [section index] != index) {
6190 _profile(PackageTable$reloadData$Section$Allocate)
6191 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6192 _end
6193
6194 [index_ addObject:[section name]];
6195 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6196
6197 _profile(PackageTable$reloadData$Section$Add)
6198 [sections_ addObject:section];
6199 _end
6200 }
6201
6202 [section addToCount];
6203 }
6204 _end
6205 }
6206
6207 _profile(PackageTable$reloadData$List)
6208 [list_ reloadData];
6209 _end
6210 }
6211
6212 - (void) resetCursor {
6213 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6214 }
6215
6216 @end
6217 /* }}} */
6218 /* Filtered Package List Controller {{{ */
6219 @interface FilteredPackageListController : PackageListController {
6220 SEL filter_;
6221 IMP imp_;
6222 id object_;
6223 }
6224
6225 - (void) setObject:(id)object;
6226 - (void) setObject:(id)object forFilter:(SEL)filter;
6227
6228 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6229
6230 @end
6231
6232 @implementation FilteredPackageListController
6233
6234 - (void) dealloc {
6235 if (object_ != nil)
6236 [object_ release];
6237 [super dealloc];
6238 }
6239
6240 - (void) setFilter:(SEL)filter {
6241 filter_ = filter;
6242
6243 /* XXX: this is an unsafe optimization of doomy hell */
6244 Method method(class_getInstanceMethod([Package class], filter));
6245 _assert(method != NULL);
6246 imp_ = method_getImplementation(method);
6247 _assert(imp_ != NULL);
6248 }
6249
6250 - (void) setObject:(id)object {
6251 if (object_ != nil)
6252 [object_ release];
6253 if (object == nil)
6254 object_ = nil;
6255 else
6256 object_ = [object retain];
6257 }
6258
6259 - (void) setObject:(id)object forFilter:(SEL)filter {
6260 [self setFilter:filter];
6261 [self setObject:object];
6262 }
6263
6264 - (bool) hasPackage:(Package *)package {
6265 _profile(FilteredPackageTable$hasPackage)
6266 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6267 _end
6268 }
6269
6270 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6271 if ((self = [super initWithDatabase:database title:title]) != nil) {
6272 [self setFilter:filter];
6273 [self setObject:object];
6274 } return self;
6275 }
6276
6277 @end
6278 /* }}} */
6279
6280 /* Home Controller {{{ */
6281 @interface HomeController : CYBrowserController {
6282 }
6283
6284 @end
6285
6286 @implementation HomeController
6287
6288 + (BOOL) shouldHideNavigationBar {
6289 return NO;
6290 }
6291
6292 - (NSURL *) navigationURL {
6293 return [NSURL URLWithString:@"cydia://home"];
6294 }
6295
6296 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6297 [super _setMoreHeaders:request];
6298
6299 if (ChipID_ != nil)
6300 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6301 if (UniqueID_ != nil)
6302 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6303 if (PLMN_ != nil)
6304 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6305 }
6306
6307 - (void) aboutButtonClicked {
6308 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6309
6310 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6311 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6312 [alert setCancelButtonIndex:0];
6313
6314 [alert setMessage:
6315 @"Copyright (C) 2008-2011\n"
6316 "Jay Freeman (saurik)\n"
6317 "saurik@saurik.com\n"
6318 "http://www.saurik.com/"
6319 ];
6320
6321 [alert show];
6322 }
6323
6324 - (void) viewWillDisappear:(BOOL)animated {
6325 [super viewWillDisappear:animated];
6326
6327 if ([[self class] shouldHideNavigationBar])
6328 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6329 }
6330
6331 - (void) viewWillAppear:(BOOL)animated {
6332 if (![self hasLoaded])
6333 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6334
6335 [super viewWillAppear:animated];
6336
6337 if ([[self class] shouldHideNavigationBar])
6338 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6339 }
6340
6341 - (void) viewDidLoad {
6342 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6343 initWithTitle:UCLocalize("ABOUT")
6344 style:UIBarButtonItemStylePlain
6345 target:self
6346 action:@selector(aboutButtonClicked)
6347 ] autorelease]];
6348 }
6349
6350 @end
6351 /* }}} */
6352 /* Manage Controller {{{ */
6353 @interface ManageController : CYBrowserController {
6354 }
6355
6356 - (void) queueStatusDidChange;
6357
6358 @end
6359
6360 @implementation ManageController
6361
6362 - (NSURL *) navigationURL {
6363 return [NSURL URLWithString:@"cydia://manage"];
6364 }
6365
6366 - (void) viewWillAppear:(BOOL)animated {
6367 if (![self hasLoaded])
6368 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6369
6370 [super viewWillAppear:animated];
6371 }
6372
6373 - (void) viewDidLoad {
6374 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6375 initWithTitle:UCLocalize("SETTINGS")
6376 style:UIBarButtonItemStylePlain
6377 target:self
6378 action:@selector(settingsButtonClicked)
6379 ] autorelease]];
6380
6381 [self queueStatusDidChange];
6382 }
6383
6384 - (void) settingsButtonClicked {
6385 [delegate_ showSettings];
6386 }
6387
6388 #if !AlwaysReload
6389 - (void) queueButtonClicked {
6390 [delegate_ queue];
6391 }
6392
6393 - (void) applyLoadingTitle {
6394 // Disable "Loading" title.
6395 }
6396
6397 - (void) applyRightButton {
6398 // Disable right button.
6399 }
6400 #endif
6401
6402 - (void) queueStatusDidChange {
6403 #if !AlwaysReload
6404 if (!IsWildcat_ && Queuing_) {
6405 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6406 initWithTitle:UCLocalize("QUEUE")
6407 style:UIBarButtonItemStyleDone
6408 target:self
6409 action:@selector(queueButtonClicked)
6410 ] autorelease]];
6411 } else {
6412 [[self navigationItem] setRightBarButtonItem:nil];
6413 }
6414 #endif
6415 }
6416
6417 - (bool) isLoading {
6418 // Never show as loading.
6419 return false;
6420 }
6421
6422 @end
6423 /* }}} */
6424
6425 /* Refresh Bar {{{ */
6426 @interface RefreshBar : UINavigationBar {
6427 UIProgressIndicator *indicator_;
6428 UITextLabel *prompt_;
6429 UIProgressBar *progress_;
6430 UINavigationButton *cancel_;
6431 }
6432
6433 @end
6434
6435 @implementation RefreshBar
6436
6437 - (void) dealloc {
6438 [indicator_ release];
6439 [prompt_ release];
6440 [progress_ release];
6441 [cancel_ release];
6442 [super dealloc];
6443 }
6444
6445 - (void) positionViews {
6446 CGRect frame = [cancel_ frame];
6447 frame.size = [cancel_ sizeThatFits:frame.size];
6448 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6449 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6450 [cancel_ setFrame:frame];
6451
6452 CGSize prgsize = {75, 100};
6453 CGRect prgrect = {{
6454 [self frame].size.width - prgsize.width - 10,
6455 ([self frame].size.height - prgsize.height) / 2
6456 } , prgsize};
6457 [progress_ setFrame:prgrect];
6458
6459 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6460 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6461 CGRect indrect = {{indoffset, indoffset}, indsize};
6462 [indicator_ setFrame:indrect];
6463
6464 CGSize prmsize = {215, indsize.height + 4};
6465 CGRect prmrect = {{
6466 indoffset * 2 + indsize.width,
6467 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6468 }, prmsize};
6469 [prompt_ setFrame:prmrect];
6470 }
6471
6472 - (void) setFrame:(CGRect)frame {
6473 [super setFrame:frame];
6474 [self positionViews];
6475 }
6476
6477 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6478 if ((self = [super initWithFrame:frame]) != nil) {
6479 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6480
6481 [self setBarStyle:UIBarStyleBlack];
6482
6483 UIBarStyle barstyle([self _barStyle:NO]);
6484 bool ugly(barstyle == UIBarStyleDefault);
6485
6486 UIProgressIndicatorStyle style = ugly ?
6487 UIProgressIndicatorStyleMediumBrown :
6488 UIProgressIndicatorStyleMediumWhite;
6489
6490 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6491 [indicator_ setStyle:style];
6492 [indicator_ startAnimation];
6493 [self addSubview:indicator_];
6494
6495 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6496 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6497 [prompt_ setBackgroundColor:[UIColor clearColor]];
6498 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6499 [self addSubview:prompt_];
6500
6501 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6502 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6503 [progress_ setStyle:0];
6504 [self addSubview:progress_];
6505
6506 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6507 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6508 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6509 [cancel_ setBarStyle:barstyle];
6510
6511 [self positionViews];
6512 } return self;
6513 }
6514
6515 - (void) cancel {
6516 [cancel_ removeFromSuperview];
6517 }
6518
6519 - (void) start {
6520 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6521 [progress_ setProgress:0];
6522 [self addSubview:cancel_];
6523 }
6524
6525 - (void) stop {
6526 [cancel_ removeFromSuperview];
6527 }
6528
6529 - (void) setPrompt:(NSString *)prompt {
6530 [prompt_ setText:prompt];
6531 }
6532
6533 - (void) setProgress:(float)progress {
6534 [progress_ setProgress:progress];
6535 }
6536
6537 @end
6538 /* }}} */
6539
6540 @class CYNavigationController;
6541
6542 /* Cydia Tab Bar Controller {{{ */
6543 @interface CYTabBarController : UITabBarController <
6544 UITabBarControllerDelegate,
6545 ProgressDelegate
6546 > {
6547 _transient Database *database_;
6548 RefreshBar *refreshbar_;
6549
6550 bool dropped_;
6551 bool updating_;
6552 // XXX: ok, "updatedelegate_"?...
6553 _transient NSObject<CydiaDelegate> *updatedelegate_;
6554
6555 id root_;
6556 UIViewController *remembered_;
6557 _transient UIViewController *transient_;
6558 }
6559
6560 - (NSArray *) navigationURLCollection;
6561 - (void) dropBar:(BOOL)animated;
6562 - (void) beginUpdate;
6563 - (void) raiseBar:(BOOL)animated;
6564 - (BOOL) updating;
6565
6566 @end
6567
6568 @implementation CYTabBarController
6569
6570 - (void) setUnselectedViewController:(UIViewController *)transient {
6571 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6572 if (transient != nil) {
6573 if (transient_ == nil)
6574 remembered_ = [[controllers objectAtIndex:0] retain];
6575 transient_ = transient;
6576 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6577 [controllers replaceObjectAtIndex:0 withObject:transient_];
6578 [self setSelectedIndex:0];
6579 [self setViewControllers:controllers];
6580 [self concealTabBarSelection];
6581 } else if (remembered_ != nil) {
6582 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6583 transient_ = transient;
6584 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6585 [remembered_ release];
6586 remembered_ = nil;
6587 [self setViewControllers:controllers];
6588 [self revealTabBarSelection];
6589 }
6590 }
6591
6592 - (UIViewController *) unselectedViewController {
6593 return transient_;
6594 }
6595
6596 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6597 if ([self unselectedViewController])
6598 [self setUnselectedViewController:nil];
6599 }
6600
6601 - (NSArray *) navigationURLCollection {
6602 NSMutableArray *items([NSMutableArray array]);
6603
6604 // XXX: Should this deal with transient view controllers?
6605 for (id navigation in [self viewControllers]) {
6606 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6607 if (stack != nil)
6608 [items addObject:stack];
6609 }
6610
6611 return items;
6612 }
6613
6614 - (void) reloadData {
6615 for (CYViewController *controller in [self viewControllers])
6616 [controller reloadData];
6617
6618 [(CYNavigationController *)[self unselectedViewController] reloadData];
6619 }
6620
6621 - (void) dealloc {
6622 [refreshbar_ release];
6623 [[NSNotificationCenter defaultCenter] removeObserver:self];
6624
6625 [super dealloc];
6626 }
6627
6628 - (id) initWithDatabase:(Database *)database {
6629 if ((self = [super init]) != nil) {
6630 database_ = database;
6631 [self setDelegate:self];
6632
6633 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6634 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6635
6636 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6637 } return self;
6638 }
6639
6640 - (void) setUpdate:(NSDate *)date {
6641 [self beginUpdate];
6642 }
6643
6644 - (void) beginUpdate {
6645 [refreshbar_ start];
6646 [self dropBar:YES];
6647
6648 [updatedelegate_ retainNetworkActivityIndicator];
6649 updating_ = true;
6650
6651 [NSThread
6652 detachNewThreadSelector:@selector(performUpdate)
6653 toTarget:self
6654 withObject:nil
6655 ];
6656 }
6657
6658 - (void) performUpdate { _pooled
6659 Status status;
6660 status.setDelegate(self);
6661 [database_ updateWithStatus:status];
6662
6663 [self
6664 performSelectorOnMainThread:@selector(completeUpdate)
6665 withObject:nil
6666 waitUntilDone:NO
6667 ];
6668 }
6669
6670 - (void) stopUpdateWithSelector:(SEL)selector {
6671 updating_ = false;
6672 [updatedelegate_ releaseNetworkActivityIndicator];
6673
6674 [self raiseBar:YES];
6675 [refreshbar_ stop];
6676
6677 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6678 }
6679
6680 - (void) completeUpdate {
6681 if (!updating_)
6682 return;
6683 [self stopUpdateWithSelector:@selector(reloadData)];
6684 }
6685
6686 - (void) cancelUpdate {
6687 [self stopUpdateWithSelector:@selector(updateData)];
6688 }
6689
6690 - (void) cancelPressed {
6691 [self cancelUpdate];
6692 }
6693
6694 - (BOOL) updating {
6695 return updating_;
6696 }
6697
6698 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6699 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6700 }
6701
6702 - (void) startProgress {
6703 }
6704
6705 - (bool) isCancelling:(size_t)received {
6706 return !updating_;
6707 }
6708
6709 - (void) setProgressTitle:(NSString *)title {
6710 [refreshbar_ setPrompt:title];
6711 }
6712
6713 - (void) setProgressPercent:(NSNumber *)percent {
6714 [refreshbar_ setProgress:[percent floatValue]];
6715 }
6716
6717 - (void) addProgressOutput:(NSString *)output {
6718 }
6719
6720 - (void) setUpdateDelegate:(id)delegate {
6721 updatedelegate_ = delegate;
6722 }
6723
6724 - (CGFloat) statusBarHeight {
6725 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6726 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6727 } else {
6728 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6729 }
6730 }
6731
6732 - (UIView *) transitionView {
6733 if ([self respondsToSelector:@selector(_transitionView)])
6734 return [self _transitionView];
6735 else
6736 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6737 }
6738
6739 - (void) dropBar:(BOOL)animated {
6740 if (dropped_)
6741 return;
6742 dropped_ = true;
6743
6744 UIView *transition([self transitionView]);
6745 [[self view] addSubview:refreshbar_];
6746
6747 CGRect barframe([refreshbar_ frame]);
6748
6749 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6750 barframe.origin.y = [self statusBarHeight];
6751 else
6752 barframe.origin.y = 0;
6753
6754 [refreshbar_ setFrame:barframe];
6755
6756 if (animated)
6757 [UIView beginAnimations:nil context:NULL];
6758
6759 CGRect viewframe = [transition frame];
6760 viewframe.origin.y += barframe.size.height;
6761 viewframe.size.height -= barframe.size.height;
6762 [transition setFrame:viewframe];
6763
6764 if (animated)
6765 [UIView commitAnimations];
6766
6767 // Ensure bar has the proper width for our view, it might have changed
6768 barframe.size.width = viewframe.size.width;
6769 [refreshbar_ setFrame:barframe];
6770
6771 // XXX: fix Apple's layout bug
6772 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6773 }
6774
6775 - (void) raiseBar:(BOOL)animated {
6776 if (!dropped_)
6777 return;
6778 dropped_ = false;
6779
6780 UIView *transition([self transitionView]);
6781 [refreshbar_ removeFromSuperview];
6782
6783 CGRect barframe([refreshbar_ frame]);
6784
6785 if (animated)
6786 [UIView beginAnimations:nil context:NULL];
6787
6788 CGRect viewframe = [transition frame];
6789 viewframe.origin.y -= barframe.size.height;
6790 viewframe.size.height += barframe.size.height;
6791 [transition setFrame:viewframe];
6792
6793 if (animated)
6794 [UIView commitAnimations];
6795
6796 // XXX: fix Apple's layout bug
6797 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6798 }
6799
6800 #if 0
6801 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6802 // XXX: fix Apple's layout bug
6803 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6804 }
6805 #endif
6806
6807 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6808 bool dropped(dropped_);
6809
6810 if (dropped)
6811 [self raiseBar:NO];
6812
6813 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6814
6815 if (dropped)
6816 [self dropBar:NO];
6817
6818 // XXX: fix Apple's layout bug
6819 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6820 }
6821
6822 - (void) statusBarFrameChanged:(NSNotification *)notification {
6823 if (dropped_) {
6824 [self raiseBar:NO];
6825 [self dropBar:NO];
6826 }
6827 }
6828
6829 @end
6830 /* }}} */
6831 /* Cydia Navigation Controller {{{ */
6832 @interface CYNavigationController : UINavigationController {
6833 _transient Database *database_;
6834 _transient id<UINavigationControllerDelegate> delegate_;
6835 }
6836
6837 - (NSArray *) navigationURLCollection;
6838 - (id) initWithDatabase:(Database *)database;
6839 - (void) reloadData;
6840
6841 @end
6842
6843
6844 @implementation CYNavigationController
6845
6846 - (NSArray *) navigationURLCollection {
6847 NSMutableArray *stack([NSMutableArray array]);
6848
6849 for (CYViewController *controller in [self viewControllers]) {
6850 NSString *url = [[controller navigationURL] absoluteString];
6851 if (url != nil)
6852 [stack addObject:url];
6853 }
6854
6855 return stack;
6856 }
6857
6858 - (void) reloadData {
6859 for (CYViewController *page in [self viewControllers]) {
6860 // Only reload controllers that have already loaded.
6861 // This prevents a page from accidentally loading too
6862 // early if it hasn't been shown on the screen yet.
6863 if ([page hasLoaded])
6864 [page reloadData];
6865 }
6866 }
6867
6868 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6869 delegate_ = delegate;
6870 }
6871
6872 - (id) initWithDatabase:(Database *)database {
6873 if ((self = [super init]) != nil) {
6874 database_ = database;
6875 } return self;
6876 }
6877
6878 @end
6879 /* }}} */
6880
6881 /* Cydia:// Protocol {{{ */
6882 @interface CydiaURLProtocol : NSURLProtocol {
6883 }
6884
6885 @end
6886
6887 @implementation CydiaURLProtocol
6888
6889 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6890 NSURL *url([request URL]);
6891 if (url == nil)
6892 return NO;
6893 NSString *scheme([[url scheme] lowercaseString]);
6894 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6895 return NO;
6896 return YES;
6897 }
6898
6899 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6900 return request;
6901 }
6902
6903 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6904 id<NSURLProtocolClient> client([self client]);
6905 if (icon == nil)
6906 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6907 else {
6908 NSData *data(UIImagePNGRepresentation(icon));
6909
6910 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6911 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6912 [client URLProtocol:self didLoadData:data];
6913 [client URLProtocolDidFinishLoading:self];
6914 }
6915 }
6916
6917 - (void) startLoading {
6918 id<NSURLProtocolClient> client([self client]);
6919 NSURLRequest *request([self request]);
6920
6921 NSURL *url([request URL]);
6922 NSString *href([url absoluteString]);
6923
6924 NSString *path([href substringFromIndex:8]);
6925 NSRange slash([path rangeOfString:@"/"]);
6926
6927 NSString *command;
6928 if (slash.location == NSNotFound) {
6929 command = path;
6930 path = nil;
6931 } else {
6932 command = [path substringToIndex:slash.location];
6933 path = [path substringFromIndex:(slash.location + 1)];
6934 }
6935
6936 Database *database([Database sharedInstance]);
6937
6938 if ([command isEqualToString:@"package-icon"]) {
6939 if (path == nil)
6940 goto fail;
6941 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6942 Package *package([database packageWithName:path]);
6943 if (package == nil)
6944 goto fail;
6945 UIImage *icon([package icon]);
6946 [self _returnPNGWithImage:icon forRequest:request];
6947 } else if ([command isEqualToString:@"source-icon"]) {
6948 if (path == nil)
6949 goto fail;
6950 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6951 NSString *source(Simplify(path));
6952 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6953 if (icon == nil)
6954 icon = [UIImage applicationImageNamed:@"unknown.png"];
6955 [self _returnPNGWithImage:icon forRequest:request];
6956 } else if ([command isEqualToString:@"uikit-image"]) {
6957 if (path == nil)
6958 goto fail;
6959 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6960 UIImage *icon(_UIImageWithName(path));
6961 [self _returnPNGWithImage:icon forRequest:request];
6962 } else if ([command isEqualToString:@"section-icon"]) {
6963 if (path == nil)
6964 goto fail;
6965 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6966 NSString *section(Simplify(path));
6967 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6968 if (icon == nil)
6969 icon = [UIImage applicationImageNamed:@"unknown.png"];
6970 [self _returnPNGWithImage:icon forRequest:request];
6971 } else fail: {
6972 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6973 }
6974 }
6975
6976 - (void) stopLoading {
6977 }
6978
6979 @end
6980 /* }}} */
6981
6982 /* Section Controller {{{ */
6983 @interface SectionController : FilteredPackageListController {
6984 NSString *section_;
6985 }
6986
6987 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6988
6989 @end
6990
6991 @implementation SectionController
6992
6993 - (NSURL *) navigationURL {
6994 NSString *name = section_;
6995 if (name == nil)
6996 name = @"all";
6997
6998 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6999 }
7000
7001 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7002 NSString *title;
7003 if (name == nil)
7004 title = UCLocalize("ALL_PACKAGES");
7005 else if (![name isEqual:@""])
7006 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7007 else
7008 title = UCLocalize("NO_SECTION");
7009
7010 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7011 section_ = name;
7012 } return self;
7013 }
7014
7015 @end
7016 /* }}} */
7017 /* Sections Controller {{{ */
7018 @interface SectionsController : CYViewController <
7019 UITableViewDataSource,
7020 UITableViewDelegate
7021 > {
7022 _transient Database *database_;
7023 NSMutableArray *sections_;
7024 NSMutableArray *filtered_;
7025 UITableView *list_;
7026 BOOL editing_;
7027 }
7028
7029 - (id) initWithDatabase:(Database *)database;
7030 - (void) editButtonClicked;
7031
7032 @end
7033
7034 @implementation SectionsController
7035
7036 - (void) dealloc {
7037 [self releaseSubviews];
7038 [sections_ release];
7039 [filtered_ release];
7040
7041 [super dealloc];
7042 }
7043
7044 - (NSURL *) navigationURL {
7045 return [NSURL URLWithString:@"cydia://sections"];
7046 }
7047
7048 - (void) updateNavigationItem {
7049 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7050 if ([sections_ count] == 0) {
7051 [[self navigationItem] setRightBarButtonItem:nil];
7052 } else {
7053 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7054 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7055 target:self
7056 action:@selector(editButtonClicked)
7057 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7058 }
7059 }
7060
7061 - (BOOL) isEditing {
7062 return editing_;
7063 }
7064
7065 - (void) setEditing:(BOOL)editing {
7066 if ((editing_ = editing))
7067 [list_ reloadData];
7068 else
7069 [delegate_ updateData];
7070
7071 [self updateNavigationItem];
7072 }
7073
7074 - (void) viewDidAppear:(BOOL)animated {
7075 [super viewDidAppear:animated];
7076 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7077 }
7078
7079 - (void) viewWillDisappear:(BOOL)animated {
7080 [super viewWillDisappear:animated];
7081 if (editing_) [self setEditing:NO];
7082 }
7083
7084 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7085 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7086 return section;
7087 }
7088
7089 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7090 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7091 }
7092
7093 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7094 return 45.0f;
7095 }*/
7096
7097 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7098 static NSString *reuseIdentifier = @"SectionCell";
7099
7100 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7101 if (cell == nil)
7102 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7103
7104 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7105
7106 return cell;
7107 }
7108
7109 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7110 if (editing_)
7111 return;
7112
7113 Section *section = [self sectionAtIndexPath:indexPath];
7114
7115 SectionController *controller = [[[SectionController alloc]
7116 initWithDatabase:database_
7117 section:[section name]
7118 ] autorelease];
7119 [controller setDelegate:delegate_];
7120
7121 [[self navigationController] pushViewController:controller animated:YES];
7122 }
7123
7124 - (void) loadView {
7125 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7126
7127 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7128 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7129 [list_ setRowHeight:45.0f];
7130 [list_ setDataSource:self];
7131 [list_ setDelegate:self];
7132 [[self view] addSubview:list_];
7133 }
7134
7135 - (void) viewDidLoad {
7136 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7137 }
7138
7139 - (void) releaseSubviews {
7140 [list_ release];
7141 list_ = nil;
7142 }
7143
7144 - (id) initWithDatabase:(Database *)database {
7145 if ((self = [super init]) != nil) {
7146 database_ = database;
7147
7148 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7149 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7150 } return self;
7151 }
7152
7153 - (void) reloadData {
7154 [super reloadData];
7155
7156 NSArray *packages = [database_ packages];
7157
7158 [sections_ removeAllObjects];
7159 [filtered_ removeAllObjects];
7160
7161 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7162
7163 _trace();
7164 for (Package *package in packages) {
7165 NSString *name([package section]);
7166 NSString *key(name == nil ? @"" : name);
7167
7168 Section *section;
7169
7170 _profile(SectionsView$reloadData$Section)
7171 section = [sections objectForKey:key];
7172 if (section == nil) {
7173 _profile(SectionsView$reloadData$Section$Allocate)
7174 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7175 [sections setObject:section forKey:key];
7176 _end
7177 }
7178 _end
7179
7180 [section addToCount];
7181
7182 _profile(SectionsView$reloadData$Filter)
7183 if (![package valid] || ![package visible])
7184 continue;
7185 _end
7186
7187 [section addToRow];
7188 }
7189 _trace();
7190
7191 [sections_ addObjectsFromArray:[sections allValues]];
7192
7193 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7194
7195 for (Section *section in sections_) {
7196 size_t count([section row]);
7197 if (count == 0)
7198 continue;
7199
7200 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7201 [section setCount:count];
7202 [filtered_ addObject:section];
7203 }
7204
7205 [self updateNavigationItem];
7206 [list_ reloadData];
7207 _trace();
7208 }
7209
7210 - (void) editButtonClicked {
7211 [self setEditing:(!editing_)];
7212 }
7213
7214 @end
7215 /* }}} */
7216
7217 /* Changes Controller {{{ */
7218 @interface ChangesController : CYViewController <
7219 UITableViewDataSource,
7220 UITableViewDelegate
7221 > {
7222 _transient Database *database_;
7223 unsigned era_;
7224 CFMutableArrayRef packages_;
7225 NSMutableArray *sections_;
7226 UITableView *list_;
7227 unsigned upgrades_;
7228 BOOL hasSentFirstLoad_;
7229 }
7230
7231 - (id) initWithDatabase:(Database *)database;
7232
7233 @end
7234
7235 @implementation ChangesController
7236
7237 - (void) dealloc {
7238 [self releaseSubviews];
7239 CFRelease(packages_);
7240 [sections_ release];
7241
7242 [super dealloc];
7243 }
7244
7245 - (NSURL *) navigationURL {
7246 return [NSURL URLWithString:@"cydia://changes"];
7247 }
7248
7249 - (void) viewWillAppear:(BOOL)animated {
7250 // Loads after it appears, so don't load beforehand.
7251 loaded_ = YES;
7252 [super viewWillAppear:animated];
7253 }
7254
7255 - (void) viewDidAppear:(BOOL)animated {
7256 [super viewDidAppear:animated];
7257
7258 if (!hasSentFirstLoad_) {
7259 hasSentFirstLoad_ = YES;
7260 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7261 } else {
7262 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7263 }
7264 }
7265
7266 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7267 NSInteger count([sections_ count]);
7268 return count == 0 ? 1 : count;
7269 }
7270
7271 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7272 if ([sections_ count] == 0)
7273 return nil;
7274 return [[sections_ objectAtIndex:section] name];
7275 }
7276
7277 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7278 if ([sections_ count] == 0)
7279 return 0;
7280 return [[sections_ objectAtIndex:section] count];
7281 }
7282
7283 - (Package *) packageAtIndex:(NSUInteger)index {
7284 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7285 }
7286
7287 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7288 @synchronized (database_) {
7289 if ([database_ era] != era_)
7290 return nil;
7291
7292 NSUInteger sectionIndex([path section]);
7293 if (sectionIndex >= [sections_ count])
7294 return nil;
7295 Section *section([sections_ objectAtIndex:sectionIndex]);
7296 NSInteger row([path row]);
7297 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7298 } }
7299
7300 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7301 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7302 if (cell == nil)
7303 cell = [[[PackageCell alloc] init] autorelease];
7304 [cell setPackage:[self packageAtIndexPath:path]];
7305 return cell;
7306 }
7307
7308 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7309 Package *package([self packageAtIndexPath:path]);
7310 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7311 [view setDelegate:delegate_];
7312 [[self navigationController] pushViewController:view animated:YES];
7313 return path;
7314 }
7315
7316 - (void) refreshButtonClicked {
7317 [delegate_ beginUpdate];
7318 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7319 }
7320
7321 - (void) upgradeButtonClicked {
7322 [delegate_ distUpgrade];
7323 }
7324
7325 - (void) loadView {
7326 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7327
7328 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7329 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7330 [list_ setRowHeight:73];
7331 [list_ setDataSource:self];
7332 [list_ setDelegate:self];
7333 [[self view] addSubview:list_];
7334 }
7335
7336 - (void) viewDidLoad {
7337 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7338 }
7339
7340 - (void) releaseSubviews {
7341 [list_ release];
7342 list_ = nil;
7343 }
7344
7345 - (id) initWithDatabase:(Database *)database {
7346 if ((self = [super init]) != nil) {
7347 database_ = database;
7348
7349 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7350 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7351 } return self;
7352 }
7353
7354 // this mostly works because reloadData (below) is @synchronized (database_)
7355 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7356 - (void) _reloadPackages:(NSArray *)packages {
7357 CFRelease(packages_);
7358 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7359
7360 _trace();
7361 _profile(ChangesController$_reloadPackages$Filter)
7362 for (Package *package in packages)
7363 if ([package upgradableAndEssential:YES] || [package visible])
7364 CFArrayAppendValue(packages_, package);
7365 _end
7366 _trace();
7367 _profile(ChangesController$_reloadPackages$radixSort)
7368 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7369 _end
7370 _trace();
7371 }
7372
7373 - (void) reloadData {
7374 @synchronized (database_) {
7375 era_ = [database_ era];
7376 NSArray *packages = [database_ packages];
7377
7378 [sections_ removeAllObjects];
7379
7380 #if 1
7381 UIProgressHUD *hud([delegate_ addProgressHUD]);
7382 [hud setText:UCLocalize("LOADING")];
7383 //NSLog(@"HUD:%@::%@", delegate_, hud);
7384 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7385 [delegate_ removeProgressHUD:hud];
7386 #else
7387 [self _reloadPackages:packages];
7388 #endif
7389
7390 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7391 Section *ignored = nil;
7392 Section *section = nil;
7393 time_t last = 0;
7394
7395 upgrades_ = 0;
7396 bool unseens = false;
7397
7398 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7399
7400 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7401 Package *package = [self packageAtIndex:offset];
7402
7403 BOOL uae = [package upgradableAndEssential:YES];
7404
7405 if (!uae) {
7406 unseens = true;
7407 time_t seen([package seen]);
7408
7409 if (section == nil || last != seen) {
7410 last = seen;
7411
7412 NSString *name;
7413 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7414 [name autorelease];
7415
7416 _profile(ChangesController$reloadData$Allocate)
7417 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7418 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7419 [sections_ addObject:section];
7420 _end
7421 }
7422
7423 [section addToCount];
7424 } else if ([package ignored]) {
7425 if (ignored == nil) {
7426 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7427 }
7428 [ignored addToCount];
7429 } else {
7430 ++upgrades_;
7431 [upgradable addToCount];
7432 }
7433 }
7434 _trace();
7435
7436 CFRelease(formatter);
7437
7438 if (unseens) {
7439 Section *last = [sections_ lastObject];
7440 size_t count = [last count];
7441 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7442 [sections_ removeLastObject];
7443 }
7444
7445 if ([ignored count] != 0)
7446 [sections_ insertObject:ignored atIndex:0];
7447 if (upgrades_ != 0)
7448 [sections_ insertObject:upgradable atIndex:0];
7449
7450 [list_ reloadData];
7451
7452 if (upgrades_ > 0)
7453 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7454 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7455 style:UIBarButtonItemStylePlain
7456 target:self
7457 action:@selector(upgradeButtonClicked)
7458 ] autorelease]];
7459
7460 if (![delegate_ updating])
7461 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7462 initWithTitle:UCLocalize("REFRESH")
7463 style:UIBarButtonItemStylePlain
7464 target:self
7465 action:@selector(refreshButtonClicked)
7466 ] autorelease]];
7467
7468 PrintTimes();
7469 } }
7470
7471 @end
7472 /* }}} */
7473 /* Search Controller {{{ */
7474 @interface SearchController : FilteredPackageListController <
7475 UISearchBarDelegate
7476 > {
7477 UISearchBar *search_;
7478 BOOL searchloaded_;
7479 }
7480
7481 - (id) initWithDatabase:(Database *)database;
7482 - (void) setSearchTerm:(NSString *)term;
7483 - (void) reloadData;
7484
7485 @end
7486
7487 @implementation SearchController
7488
7489 - (void) dealloc {
7490 [search_ release];
7491 [super dealloc];
7492 }
7493
7494 - (NSURL *) navigationURL {
7495 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7496 return [NSURL URLWithString:@"cydia://search"];
7497 else
7498 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7499 }
7500
7501 - (void) setSearchTerm:(NSString *)searchTerm {
7502 [search_ setText:searchTerm];
7503 [self reloadData];
7504 }
7505
7506 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7507 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7508 [search_ resignFirstResponder];
7509 [self reloadData];
7510 }
7511
7512 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7513 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7514 [self reloadData];
7515 }
7516
7517 - (id) initWithDatabase:(Database *)database {
7518 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7519 search_ = [[UISearchBar alloc] init];
7520 } return self;
7521 }
7522
7523 - (void) viewDidAppear:(BOOL)animated {
7524 [super viewDidAppear:animated];
7525
7526 if (!searchloaded_) {
7527 searchloaded_ = YES;
7528 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7529 [search_ layoutSubviews];
7530 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7531
7532 UITextField *textField;
7533 if ([search_ respondsToSelector:@selector(searchField)])
7534 textField = [search_ searchField];
7535 else
7536 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7537
7538 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7539 [search_ setDelegate:self];
7540 [textField setEnablesReturnKeyAutomatically:NO];
7541 [[self navigationItem] setTitleView:textField];
7542 }
7543 }
7544
7545 - (void) reloadData {
7546 [self setObject:[search_ text]];
7547 [super reloadData];
7548 [self resetCursor];
7549 }
7550
7551 - (void) didSelectPackage:(Package *)package {
7552 [search_ resignFirstResponder];
7553 [super didSelectPackage:package];
7554 }
7555
7556 @end
7557 /* }}} */
7558 /* Package Settings Controller {{{ */
7559 @interface PackageSettingsController : CYViewController <
7560 UITableViewDataSource,
7561 UITableViewDelegate
7562 > {
7563 _transient Database *database_;
7564 NSString *name_;
7565 Package *package_;
7566 UITableView *table_;
7567 UISwitch *subscribedSwitch_;
7568 UISwitch *ignoredSwitch_;
7569 UITableViewCell *subscribedCell_;
7570 UITableViewCell *ignoredCell_;
7571 }
7572
7573 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7574
7575 @end
7576
7577 @implementation PackageSettingsController
7578
7579 - (void) dealloc {
7580 [self releaseSubviews];
7581 [name_ release];
7582 [package_ release];
7583
7584 [super dealloc];
7585 }
7586
7587 - (NSURL *) navigationURL {
7588 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7589 }
7590
7591 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7592 if (package_ == nil)
7593 return 0;
7594
7595 if ([package_ installed] == nil)
7596 return 1;
7597 else
7598 return 2;
7599 }
7600
7601 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7602 if (package_ == nil)
7603 return 0;
7604
7605 // both sections contain just one item right now.
7606 return 1;
7607 }
7608
7609 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7610 return nil;
7611 }
7612
7613 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7614 if (section == 0)
7615 return UCLocalize("SHOW_ALL_CHANGES_EX");
7616 else
7617 return UCLocalize("IGNORE_UPGRADES_EX");
7618 }
7619
7620 - (void) onSubscribed:(id)control {
7621 bool value([control isOn]);
7622 if (package_ == nil)
7623 return;
7624 if ([package_ setSubscribed:value])
7625 [delegate_ updateData];
7626 }
7627
7628 - (void) _updateIgnored {
7629 const char *package([name_ UTF8String]);
7630 bool on([ignoredSwitch_ isOn]);
7631
7632 pid_t pid(ExecFork());
7633 if (pid == 0) {
7634 FILE *dpkg(popen("dpkg --set-selections", "w"));
7635 fwrite(package, strlen(package), 1, dpkg);
7636
7637 if (on)
7638 fwrite(" hold\n", 6, 1, dpkg);
7639 else
7640 fwrite(" install\n", 9, 1, dpkg);
7641
7642 pclose(dpkg);
7643
7644 exit(0);
7645 _assert(false);
7646 }
7647
7648 _forever {
7649 int status;
7650 int result(waitpid(pid, &status, 0));
7651
7652 if (result != -1) {
7653 _assert(result == pid);
7654 break;
7655 }
7656 }
7657 }
7658
7659 - (void) onIgnored:(id)control {
7660 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7661 [invocation setTarget:self];
7662 [invocation setSelector:@selector(_updateIgnored)];
7663
7664 [delegate_ reloadDataWithInvocation:invocation];
7665 }
7666
7667 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7668 if (package_ == nil)
7669 return nil;
7670
7671 switch ([indexPath section]) {
7672 case 0: return subscribedCell_;
7673 case 1: return ignoredCell_;
7674
7675 _nodefault
7676 }
7677
7678 return nil;
7679 }
7680
7681 - (void) loadView {
7682 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7683
7684 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7685 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7686 [table_ setDataSource:self];
7687 [table_ setDelegate:self];
7688 [[self view] addSubview:table_];
7689
7690 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7691 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7692 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7693
7694 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7695 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7696 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7697
7698 subscribedCell_ = [[UITableViewCell alloc] init];
7699 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7700 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7701 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7702
7703 ignoredCell_ = [[UITableViewCell alloc] init];
7704 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7705 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7706 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7707 }
7708
7709 - (void) viewDidLoad {
7710 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7711 }
7712
7713 - (void) releaseSubviews {
7714 [ignoredCell_ release];
7715 ignoredCell_ = nil;
7716
7717 [subscribedCell_ release];
7718 subscribedCell_ = nil;
7719
7720 [table_ release];
7721 table_ = nil;
7722
7723 [ignoredSwitch_ release];
7724 ignoredSwitch_ = nil;
7725
7726 [subscribedSwitch_ release];
7727 subscribedSwitch_ = nil;
7728 }
7729
7730 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7731 if ((self = [super init]) != nil) {
7732 database_ = database;
7733 name_ = [package retain];
7734 } return self;
7735 }
7736
7737 - (void) reloadData {
7738 [super reloadData];
7739
7740 if (package_ != nil)
7741 [package_ autorelease];
7742 package_ = [database_ packageWithName:name_];
7743
7744 if (package_ != nil) {
7745 package_ = [package_ retain];
7746 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7747 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7748 } // XXX: what now, G?
7749
7750 [table_ reloadData];
7751 }
7752
7753 @end
7754 /* }}} */
7755
7756 /* Installed Controller {{{ */
7757 @interface InstalledController : FilteredPackageListController {
7758 BOOL expert_;
7759 }
7760
7761 - (id) initWithDatabase:(Database *)database;
7762
7763 - (void) updateRoleButton;
7764 - (void) queueStatusDidChange;
7765
7766 @end
7767
7768 @implementation InstalledController
7769
7770 - (void) dealloc {
7771 [super dealloc];
7772 }
7773
7774 - (NSURL *) navigationURL {
7775 return [NSURL URLWithString:@"cydia://installed"];
7776 }
7777
7778 - (id) initWithDatabase:(Database *)database {
7779 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7780 [self updateRoleButton];
7781 [self queueStatusDidChange];
7782 } return self;
7783 }
7784
7785 #if !AlwaysReload
7786 - (void) queueButtonClicked {
7787 [delegate_ queue];
7788 }
7789 #endif
7790
7791 - (void) queueStatusDidChange {
7792 #if !AlwaysReload
7793 if (IsWildcat_) {
7794 if (Queuing_) {
7795 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7796 initWithTitle:UCLocalize("QUEUE")
7797 style:UIBarButtonItemStyleDone
7798 target:self
7799 action:@selector(queueButtonClicked)
7800 ] autorelease]];
7801 } else {
7802 [[self navigationItem] setLeftBarButtonItem:nil];
7803 }
7804 }
7805 #endif
7806 }
7807
7808 - (void) updateRoleButton {
7809 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7810 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7811 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7812 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7813 target:self
7814 action:@selector(roleButtonClicked)
7815 ] autorelease]];
7816 }
7817
7818 - (void) roleButtonClicked {
7819 [self setObject:[NSNumber numberWithBool:expert_]];
7820 [self reloadData];
7821 expert_ = !expert_;
7822
7823 [self updateRoleButton];
7824 }
7825
7826 @end
7827 /* }}} */
7828
7829 /* Source Cell {{{ */
7830 @interface SourceCell : CYTableViewCell <
7831 ContentDelegate
7832 > {
7833 UIImage *icon_;
7834 NSString *origin_;
7835 NSString *label_;
7836 }
7837
7838 - (void) setSource:(Source *)source;
7839
7840 @end
7841
7842 @implementation SourceCell
7843
7844 - (void) clearSource {
7845 [icon_ release];
7846 [origin_ release];
7847 [label_ release];
7848
7849 icon_ = nil;
7850 origin_ = nil;
7851 label_ = nil;
7852 }
7853
7854 - (void) setSource:(Source *)source {
7855 [self clearSource];
7856
7857 if (icon_ == nil)
7858 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7859 if (icon_ == nil)
7860 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7861 icon_ = [icon_ retain];
7862
7863 origin_ = [[source name] retain];
7864 label_ = [[source uri] retain];
7865
7866 [content_ setNeedsDisplay];
7867 }
7868
7869 - (void) dealloc {
7870 [self clearSource];
7871 [super dealloc];
7872 }
7873
7874 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7875 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7876 UIView *content([self contentView]);
7877 CGRect bounds([content bounds]);
7878
7879 content_ = [[ContentView alloc] initWithFrame:bounds];
7880 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7881 [content_ setBackgroundColor:[UIColor whiteColor]];
7882 [content addSubview:content_];
7883
7884 [content_ setDelegate:self];
7885 [content_ setOpaque:YES];
7886 } return self;
7887 }
7888
7889 - (NSString *) accessibilityLabel {
7890 return label_;
7891 }
7892
7893 - (void) drawContentRect:(CGRect)rect {
7894 bool highlighted(highlighted_);
7895 float width(rect.size.width);
7896
7897 if (icon_ != nil)
7898 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7899
7900 if (highlighted)
7901 UISetColor(White_);
7902
7903 if (!highlighted)
7904 UISetColor(Black_);
7905 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7906
7907 if (!highlighted)
7908 UISetColor(Blue_);
7909 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7910 }
7911
7912 @end
7913 /* }}} */
7914 /* Source Controller {{{ */
7915 @interface SourceController : FilteredPackageListController {
7916 _transient Source *source_;
7917 NSString *key_;
7918 }
7919
7920 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7921
7922 @end
7923
7924 @implementation SourceController
7925
7926 - (NSURL *) navigationURL {
7927 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7928 }
7929
7930 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7931 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7932 source_ = source;
7933 key_ = [[source key] retain];
7934 } return self;
7935 }
7936
7937 - (void) reloadData {
7938 source_ = [database_ sourceWithKey:key_];
7939 [key_ release];
7940 key_ = [[source_ key] retain];
7941 [self setObject:source_];
7942 [[self navigationItem] setTitle:[source_ label]];
7943
7944 [super reloadData];
7945 }
7946
7947 @end
7948 /* }}} */
7949 /* Sources Controller {{{ */
7950 @interface SourcesController : CYViewController <
7951 UITableViewDataSource,
7952 UITableViewDelegate
7953 > {
7954 _transient Database *database_;
7955 UITableView *list_;
7956 NSMutableArray *sources_;
7957 int offset_;
7958
7959 NSString *href_;
7960 UIProgressHUD *hud_;
7961 NSError *error_;
7962
7963 //NSURLConnection *installer_;
7964 NSURLConnection *trivial_;
7965 NSURLConnection *trivial_bz2_;
7966 NSURLConnection *trivial_gz_;
7967 //NSURLConnection *automatic_;
7968
7969 BOOL cydia_;
7970 }
7971
7972 - (id) initWithDatabase:(Database *)database;
7973 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7974
7975 @end
7976
7977 @implementation SourcesController
7978
7979 - (void) _releaseConnection:(NSURLConnection *)connection {
7980 if (connection != nil) {
7981 [connection cancel];
7982 //[connection setDelegate:nil];
7983 [connection release];
7984 }
7985 }
7986
7987 - (void) dealloc {
7988 [self releaseSubviews];
7989
7990 [href_ release];
7991 [hud_ release];
7992 [error_ release];
7993
7994 //[self _releaseConnection:installer_];
7995 [self _releaseConnection:trivial_];
7996 [self _releaseConnection:trivial_gz_];
7997 [self _releaseConnection:trivial_bz2_];
7998 //[self _releaseConnection:automatic_];
7999
8000 [sources_ release];
8001 [super dealloc];
8002 }
8003
8004 - (NSURL *) navigationURL {
8005 return [NSURL URLWithString:@"cydia://sources"];
8006 }
8007
8008 - (void) viewDidAppear:(BOOL)animated {
8009 [super viewDidAppear:animated];
8010 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8011 }
8012
8013 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8014 return offset_ == 0 ? 1 : 2;
8015 }
8016
8017 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8018 switch (section + (offset_ == 0 ? 1 : 0)) {
8019 case 0: return UCLocalize("ENTERED_BY_USER");
8020 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8021
8022 _nodefault
8023 }
8024 }
8025
8026 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8027 int count = [sources_ count];
8028 switch (section) {
8029 case 0: return (offset_ == 0 ? count : offset_);
8030 case 1: return count - offset_;
8031
8032 _nodefault
8033 }
8034 }
8035
8036 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8037 unsigned idx = 0;
8038 switch (indexPath.section) {
8039 case 0: idx = indexPath.row; break;
8040 case 1: idx = indexPath.row + offset_; break;
8041
8042 _nodefault
8043 }
8044 return [sources_ objectAtIndex:idx];
8045 }
8046
8047 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8048 static NSString *cellIdentifier = @"SourceCell";
8049
8050 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8051 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8052 [cell setSource:[self sourceAtIndexPath:indexPath]];
8053 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8054
8055 return cell;
8056 }
8057
8058 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8059 Source *source = [self sourceAtIndexPath:indexPath];
8060
8061 SourceController *controller = [[[SourceController alloc]
8062 initWithDatabase:database_
8063 source:source
8064 ] autorelease];
8065
8066 [controller setDelegate:delegate_];
8067
8068 [[self navigationController] pushViewController:controller animated:YES];
8069 }
8070
8071 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8072 Source *source = [self sourceAtIndexPath:indexPath];
8073 return [source record] != nil;
8074 }
8075
8076 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8077 Source *source = [self sourceAtIndexPath:indexPath];
8078 [Sources_ removeObjectForKey:[source key]];
8079 [delegate_ syncData];
8080 }
8081
8082 - (void) complete {
8083 [delegate_ addTrivialSource:href_];
8084 [delegate_ syncData];
8085 }
8086
8087 - (NSString *) getWarning {
8088 NSString *href(href_);
8089 NSRange colon([href rangeOfString:@"://"]);
8090 if (colon.location != NSNotFound)
8091 href = [href substringFromIndex:(colon.location + 3)];
8092 href = [href stringByAddingPercentEscapes];
8093 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8094 href = [href stringByCachingURLWithCurrentCDN];
8095
8096 NSURL *url([NSURL URLWithString:href]);
8097
8098 NSStringEncoding encoding;
8099 NSError *error(nil);
8100
8101 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8102 return [warning length] == 0 ? nil : warning;
8103 return nil;
8104 }
8105
8106 - (void) _endConnection:(NSURLConnection *)connection {
8107 // XXX: the memory management in this method is horribly awkward
8108
8109 NSURLConnection **field = NULL;
8110 if (connection == trivial_)
8111 field = &trivial_;
8112 else if (connection == trivial_bz2_)
8113 field = &trivial_bz2_;
8114 else if (connection == trivial_gz_)
8115 field = &trivial_gz_;
8116 _assert(field != NULL);
8117 [connection release];
8118 *field = nil;
8119
8120 if (
8121 trivial_ == nil &&
8122 trivial_bz2_ == nil &&
8123 trivial_gz_ == nil
8124 ) {
8125 bool defer(false);
8126
8127 if (cydia_) {
8128 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8129 defer = true;
8130
8131 UIAlertView *alert = [[[UIAlertView alloc]
8132 initWithTitle:UCLocalize("SOURCE_WARNING")
8133 message:warning
8134 delegate:self
8135 cancelButtonTitle:UCLocalize("CANCEL")
8136 otherButtonTitles:
8137 UCLocalize("ADD_ANYWAY"),
8138 nil
8139 ] autorelease];
8140
8141 [alert setContext:@"warning"];
8142 [alert setNumberOfRows:1];
8143 [alert show];
8144 } else
8145 [self complete];
8146 } else if (error_ != nil) {
8147 UIAlertView *alert = [[[UIAlertView alloc]
8148 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8149 message:[error_ localizedDescription]
8150 delegate:self
8151 cancelButtonTitle:UCLocalize("OK")
8152 otherButtonTitles:nil
8153 ] autorelease];
8154
8155 [alert setContext:@"urlerror"];
8156 [alert show];
8157 } else {
8158 UIAlertView *alert = [[[UIAlertView alloc]
8159 initWithTitle:UCLocalize("NOT_REPOSITORY")
8160 message:UCLocalize("NOT_REPOSITORY_EX")
8161 delegate:self
8162 cancelButtonTitle:UCLocalize("OK")
8163 otherButtonTitles:nil
8164 ] autorelease];
8165
8166 [alert setContext:@"trivial"];
8167 [alert show];
8168 }
8169
8170 [delegate_ setStatusBarShowsProgress:NO];
8171 [delegate_ removeProgressHUD:hud_];
8172
8173 [hud_ autorelease];
8174 hud_ = nil;
8175
8176 if (!defer) {
8177 [href_ release];
8178 href_ = nil;
8179 }
8180
8181 if (error_ != nil) {
8182 [error_ release];
8183 error_ = nil;
8184 }
8185 }
8186 }
8187
8188 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8189 switch ([response statusCode]) {
8190 case 200:
8191 cydia_ = YES;
8192 }
8193 }
8194
8195 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8196 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8197 if (error_ != nil)
8198 error_ = [error retain];
8199 [self _endConnection:connection];
8200 }
8201
8202 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8203 [self _endConnection:connection];
8204 }
8205
8206 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8207 NSMutableURLRequest *request = [NSMutableURLRequest
8208 requestWithURL:[NSURL URLWithString:href]
8209 cachePolicy:NSURLRequestUseProtocolCachePolicy
8210 timeoutInterval:120.0
8211 ];
8212
8213 [request setHTTPMethod:method];
8214
8215 if (Machine_ != NULL)
8216 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8217 if (UniqueID_ != nil)
8218 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8219 if (Role_ != nil)
8220 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8221
8222 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8223 }
8224
8225 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8226 NSString *context([alert context]);
8227
8228 if ([context isEqualToString:@"source"]) {
8229 switch (button) {
8230 case 1: {
8231 NSString *href = [[alert textField] text];
8232
8233 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8234
8235 if (![href hasSuffix:@"/"])
8236 href_ = [href stringByAppendingString:@"/"];
8237 else
8238 href_ = href;
8239 href_ = [href_ retain];
8240
8241 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8242 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8243 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8244 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8245
8246 cydia_ = false;
8247
8248 // XXX: this is stupid
8249 hud_ = [[delegate_ addProgressHUD] retain];
8250 [hud_ setText:UCLocalize("VERIFYING_URL")];
8251 } break;
8252
8253 case 0:
8254 break;
8255
8256 _nodefault
8257 }
8258
8259 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8260 } else if ([context isEqualToString:@"trivial"])
8261 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8262 else if ([context isEqualToString:@"urlerror"])
8263 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8264 else if ([context isEqualToString:@"warning"]) {
8265 switch (button) {
8266 case 1:
8267 [self complete];
8268 break;
8269
8270 case 0:
8271 break;
8272
8273 _nodefault
8274 }
8275
8276 [href_ release];
8277 href_ = nil;
8278
8279 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8280 }
8281 }
8282
8283 - (void) loadView {
8284 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8285
8286 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8287 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8288 [list_ setRowHeight:56];
8289 [list_ setDataSource:self];
8290 [list_ setDelegate:self];
8291 [[self view] addSubview:list_];
8292 }
8293
8294 - (void) viewDidLoad {
8295 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8296 [self updateButtonsForEditingStatus:NO animated:NO];
8297 }
8298
8299 - (void) releaseSubviews {
8300 [list_ release];
8301 list_ = nil;
8302 }
8303
8304 - (id) initWithDatabase:(Database *)database {
8305 if ((self = [super init]) != nil) {
8306 database_ = database;
8307 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8308 } return self;
8309 }
8310
8311 - (void) reloadData {
8312 [super reloadData];
8313
8314 pkgSourceList list;
8315 if (!list.ReadMainList())
8316 return;
8317
8318 [sources_ removeAllObjects];
8319 [sources_ addObjectsFromArray:[database_ sources]];
8320 _trace();
8321 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8322 _trace();
8323
8324 int count([sources_ count]);
8325 offset_ = 0;
8326 for (int i = 0; i != count; i++) {
8327 if ([[sources_ objectAtIndex:i] record] == nil)
8328 break;
8329 offset_++;
8330 }
8331
8332 [list_ setEditing:NO];
8333 [self updateButtonsForEditingStatus:NO animated:NO];
8334 [list_ reloadData];
8335 }
8336
8337 - (void) showAddSourcePrompt {
8338 UIAlertView *alert = [[[UIAlertView alloc]
8339 initWithTitle:UCLocalize("ENTER_APT_URL")
8340 message:nil
8341 delegate:self
8342 cancelButtonTitle:UCLocalize("CANCEL")
8343 otherButtonTitles:
8344 UCLocalize("ADD_SOURCE"),
8345 nil
8346 ] autorelease];
8347
8348 [alert setContext:@"source"];
8349 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8350
8351 [alert setNumberOfRows:1];
8352 [alert addTextFieldWithValue:@"http://" label:@""];
8353
8354 UITextInputTraits *traits = [[alert textField] textInputTraits];
8355 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8356 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8357 [traits setKeyboardType:UIKeyboardTypeURL];
8358 // XXX: UIReturnKeyDone
8359 [traits setReturnKeyType:UIReturnKeyNext];
8360
8361 [alert show];
8362 }
8363
8364 - (void) addButtonClicked {
8365 [self showAddSourcePrompt];
8366 }
8367
8368 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8369 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8370 initWithTitle:UCLocalize("ADD")
8371 style:UIBarButtonItemStylePlain
8372 target:self
8373 action:@selector(addButtonClicked)
8374 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8375
8376 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8377 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8378 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8379 target:self
8380 action:@selector(editButtonClicked)
8381 ] autorelease] animated:animated];
8382
8383 if (IsWildcat_ && !editing)
8384 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8385 initWithTitle:UCLocalize("SETTINGS")
8386 style:UIBarButtonItemStylePlain
8387 target:self
8388 action:@selector(settingsButtonClicked)
8389 ] autorelease]];
8390 }
8391
8392 - (void) settingsButtonClicked {
8393 [delegate_ showSettings];
8394 }
8395
8396 - (void) editButtonClicked {
8397 [list_ setEditing:![list_ isEditing] animated:YES];
8398
8399 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8400 }
8401
8402 @end
8403 /* }}} */
8404
8405 /* Settings Controller {{{ */
8406 @interface SettingsController : CYViewController <
8407 UITableViewDataSource,
8408 UITableViewDelegate
8409 > {
8410 _transient Database *database_;
8411 // XXX: ok, "roledelegate_"?...
8412 _transient id roledelegate_;
8413 UITableView *table_;
8414 UISegmentedControl *segment_;
8415 UIView *container_;
8416 }
8417
8418 - (void) showDoneButton;
8419 - (void) resizeSegmentedControl;
8420
8421 @end
8422
8423 @implementation SettingsController
8424
8425 - (void) dealloc {
8426 [self releaseSubviews];
8427
8428 [super dealloc];
8429 }
8430
8431 - (void) loadView {
8432 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8433
8434 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8435 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8436 [table_ setDelegate:self];
8437 [table_ setDataSource:self];
8438 [[self view] addSubview:table_];
8439
8440 NSArray *items = [NSArray arrayWithObjects:
8441 UCLocalize("USER"),
8442 UCLocalize("HACKER"),
8443 UCLocalize("DEVELOPER"),
8444 nil];
8445 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8446 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8447 [container_ addSubview:segment_];
8448 }
8449
8450 - (void) viewDidLoad {
8451 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8452
8453 int index = -1;
8454 if ([Role_ isEqualToString:@"User"]) index = 0;
8455 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8456 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8457 if (index != -1) {
8458 [segment_ setSelectedSegmentIndex:index];
8459 [self showDoneButton];
8460 }
8461
8462 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8463 [self resizeSegmentedControl];
8464 }
8465
8466 - (void) releaseSubviews {
8467 [table_ release];
8468 table_ = nil;
8469
8470 [segment_ release];
8471 segment_ = nil;
8472
8473 [container_ release];
8474 container_ = nil;
8475 }
8476
8477 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8478 if ((self = [super init]) != nil) {
8479 database_ = database;
8480 roledelegate_ = delegate;
8481 } return self;
8482 }
8483
8484 - (void) resizeSegmentedControl {
8485 CGFloat width = [[self view] frame].size.width;
8486 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8487 }
8488
8489 - (void) viewWillAppear:(BOOL)animated {
8490 [super viewWillAppear:animated];
8491
8492 [self resizeSegmentedControl];
8493 }
8494
8495 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8496 [self resizeSegmentedControl];
8497 }
8498
8499 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8500 [self resizeSegmentedControl];
8501 }
8502
8503 - (void) save {
8504 NSString *role(nil);
8505
8506 switch ([segment_ selectedSegmentIndex]) {
8507 case 0: role = @"User"; break;
8508 case 1: role = @"Hacker"; break;
8509 case 2: role = @"Developer"; break;
8510
8511 _nodefault
8512 }
8513
8514 if (![role isEqualToString:Role_]) {
8515 bool rolling(Role_ == nil);
8516 Role_ = role;
8517
8518 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8519 Role_, @"Role",
8520 nil];
8521
8522 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8523 Changed_ = true;
8524
8525 if (rolling)
8526 [roledelegate_ loadData];
8527 else
8528 [roledelegate_ updateData];
8529 }
8530 }
8531
8532 - (void) segmentChanged:(UISegmentedControl *)control {
8533 [self showDoneButton];
8534 }
8535
8536 - (void) saveAndClose {
8537 [self save];
8538
8539 [[self navigationItem] setRightBarButtonItem:nil];
8540 [[self navigationController] dismissModalViewControllerAnimated:YES];
8541 }
8542
8543 - (void) doneButtonClicked {
8544 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8545 [spinner startAnimating];
8546 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8547 [[self navigationItem] setRightBarButtonItem:spinItem];
8548
8549 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8550 }
8551
8552 - (void) showDoneButton {
8553 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8554 initWithTitle:UCLocalize("DONE")
8555 style:UIBarButtonItemStyleDone
8556 target:self
8557 action:@selector(doneButtonClicked)
8558 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8559 }
8560
8561 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8562 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8563 return 6;
8564 }
8565
8566 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8567 return 0; // :(
8568 }
8569
8570 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8571 return nil; // This method is required by the protocol.
8572 }
8573
8574 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8575 if (section == 1)
8576 return UCLocalize("ROLE_EX");
8577 if (section == 4)
8578 return [NSString stringWithFormat:
8579 @"%@: %@\n%@: %@\n%@: %@",
8580 UCLocalize("USER"), UCLocalize("USER_EX"),
8581 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8582 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8583 ];
8584 else return nil;
8585 }
8586
8587 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8588 return section == 3 ? 44.0f : 0;
8589 }
8590
8591 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8592 return section == 3 ? container_ : nil;
8593 }
8594
8595 - (void) reloadData {
8596 [super reloadData];
8597 [table_ reloadData];
8598 }
8599
8600 @end
8601 /* }}} */
8602 /* Stash Controller {{{ */
8603 @interface StashController : CYViewController {
8604 UIActivityIndicatorView *spinner_;
8605 UILabel *status_;
8606 UILabel *caption_;
8607 }
8608
8609 @end
8610
8611 @implementation StashController
8612
8613 - (void) dealloc {
8614 [self releaseSubviews];
8615
8616 [super dealloc];
8617 }
8618
8619 - (void) loadView {
8620 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8621 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8622
8623 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8624 CGRect spinrect = [spinner_ frame];
8625 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8626 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8627 [spinner_ setFrame:spinrect];
8628 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8629 [[self view] addSubview:spinner_];
8630 [spinner_ startAnimating];
8631
8632 CGRect captrect;
8633 captrect.size.width = [[self view] frame].size.width;
8634 captrect.size.height = 40.0f;
8635 captrect.origin.x = 0;
8636 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8637 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8638 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8639 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8640 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8641 [caption_ setTextColor:[UIColor whiteColor]];
8642 [caption_ setBackgroundColor:[UIColor clearColor]];
8643 [caption_ setShadowColor:[UIColor blackColor]];
8644 [caption_ setTextAlignment:UITextAlignmentCenter];
8645 [[self view] addSubview:caption_];
8646
8647 CGRect statusrect;
8648 statusrect.size.width = [[self view] frame].size.width;
8649 statusrect.size.height = 30.0f;
8650 statusrect.origin.x = 0;
8651 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8652 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8653 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8654 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8655 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8656 [status_ setTextColor:[UIColor whiteColor]];
8657 [status_ setBackgroundColor:[UIColor clearColor]];
8658 [status_ setShadowColor:[UIColor blackColor]];
8659 [status_ setTextAlignment:UITextAlignmentCenter];
8660 [[self view] addSubview:status_];
8661 }
8662
8663 - (void) releaseSubviews {
8664 [spinner_ release];
8665 spinner_ = nil;
8666
8667 [status_ release];
8668 status_ = nil;
8669
8670 [caption_ release];
8671 caption_ = nil;
8672 }
8673
8674 @end
8675 /* }}} */
8676
8677 @interface Cydia : UIApplication <
8678 ConfirmationControllerDelegate,
8679 ProgressControllerDelegate,
8680 CydiaDelegate,
8681 UINavigationControllerDelegate,
8682 UITabBarControllerDelegate
8683 > {
8684 // XXX: evaluate all fields for _transient
8685
8686 UIWindow *window_;
8687 CYTabBarController *tabbar_;
8688
8689 NSMutableArray *essential_;
8690 NSMutableArray *broken_;
8691
8692 Database *database_;
8693
8694 NSURL *starturl_;
8695
8696 unsigned locked_;
8697 unsigned activity_;
8698
8699 StashController *stash_;
8700
8701 bool loaded_;
8702 }
8703
8704 - (void) loadData;
8705
8706 @end
8707
8708 @implementation Cydia
8709
8710 - (void) beginUpdate {
8711 [tabbar_ beginUpdate];
8712 }
8713
8714 - (BOOL) updating {
8715 return [tabbar_ updating];
8716 }
8717
8718 - (void) _loaded {
8719 if ([broken_ count] != 0) {
8720 int count = [broken_ count];
8721
8722 UIAlertView *alert = [[[UIAlertView alloc]
8723 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8724 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8725 delegate:self
8726 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8727 otherButtonTitles:
8728 UCLocalize("TEMPORARY_IGNORE"),
8729 nil
8730 ] autorelease];
8731
8732 [alert setContext:@"fixhalf"];
8733 [alert show];
8734 } else if (!Ignored_ && [essential_ count] != 0) {
8735 int count = [essential_ count];
8736
8737 UIAlertView *alert = [[[UIAlertView alloc]
8738 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8739 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8740 delegate:self
8741 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8742 otherButtonTitles:
8743 UCLocalize("UPGRADE_ESSENTIAL"),
8744 UCLocalize("COMPLETE_UPGRADE"),
8745 nil
8746 ] autorelease];
8747
8748 [alert setContext:@"upgrade"];
8749 [alert show];
8750 }
8751 }
8752
8753 - (void) _saveConfig {
8754 _trace();
8755 MetaFile_.Sync();
8756 _trace();
8757
8758 if (Changed_) {
8759 NSString *error(nil);
8760
8761 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8762 _trace();
8763 NSError *error(nil);
8764 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8765 NSLog(@"failure to save metadata data: %@", error);
8766 _trace();
8767
8768 Changed_ = false;
8769 } else {
8770 NSLog(@"failure to serialize metadata: %@", error);
8771 }
8772 }
8773 }
8774
8775 // Navigation controller for the queuing badge.
8776 - (CYNavigationController *) queueNavigationController {
8777 NSArray *controllers = [tabbar_ viewControllers];
8778 return [controllers objectAtIndex:3];
8779 }
8780
8781 - (void) _updateData {
8782 [self _saveConfig];
8783
8784 [tabbar_ reloadData];
8785
8786 CYNavigationController *navigation = [self queueNavigationController];
8787
8788 id queuedelegate = nil;
8789 if ([[navigation viewControllers] count] > 0)
8790 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8791
8792 [queuedelegate queueStatusDidChange];
8793 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8794 }
8795
8796 - (void) _refreshIfPossible:(NSDate *)update {
8797 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8798
8799 bool recently = false;
8800 if (update != nil) {
8801 NSTimeInterval interval([update timeIntervalSinceNow]);
8802 if (interval <= 0 && interval > -(15*60))
8803 recently = true;
8804 }
8805
8806 // Don't automatic refresh if:
8807 // - We already refreshed recently.
8808 // - We already auto-refreshed this launch.
8809 // - Auto-refresh is disabled.
8810 if (recently || loaded_ || ManualRefresh) {
8811 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8812
8813 // If we are cancelling, we need to make sure it knows it's already loaded.
8814 loaded_ = true;
8815 return;
8816 } else {
8817 // We are going to load, so remember that.
8818 loaded_ = true;
8819 }
8820
8821 SCNetworkReachabilityFlags flags; {
8822 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8823 SCNetworkReachabilityGetFlags(reachability, &flags);
8824 CFRelease(reachability);
8825 }
8826
8827 // XXX: this elaborate mess is what Apple is using to determine this? :(
8828 // XXX: do we care if the user has to intervene? maybe that's ok?
8829 bool reachable(
8830 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8831 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8832 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8833 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8834 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8835 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8836 )
8837 );
8838
8839 // If we can reach the server, auto-refresh!
8840 if (reachable)
8841 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8842
8843 [pool release];
8844 }
8845
8846 - (void) refreshIfPossible {
8847 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8848 }
8849
8850 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8851 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8852 [hud setText:UCLocalize("RELOADING_DATA")];
8853
8854 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8855
8856 if (hud != nil)
8857 [self removeProgressHUD:hud];
8858
8859 size_t changes(0);
8860
8861 [essential_ removeAllObjects];
8862 [broken_ removeAllObjects];
8863
8864 NSArray *packages([database_ packages]);
8865 for (Package *package in packages) {
8866 if ([package half])
8867 [broken_ addObject:package];
8868 if ([package upgradableAndEssential:NO]) {
8869 if ([package essential])
8870 [essential_ addObject:package];
8871 ++changes;
8872 }
8873 }
8874
8875 NSLog(@"changes:#%u", changes);
8876
8877 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8878 if (changes != 0) {
8879 _trace();
8880 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8881 [changesItem setBadgeValue:badge];
8882 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8883 [self setApplicationIconBadgeNumber:changes];
8884 } else {
8885 _trace();
8886 [changesItem setBadgeValue:nil];
8887 [changesItem setAnimatedBadge:NO];
8888 [self setApplicationIconBadgeNumber:0];
8889 }
8890
8891 [self _updateData];
8892
8893 [self refreshIfPossible];
8894 }
8895
8896 - (void) updateData {
8897 [self _updateData];
8898 }
8899
8900 - (void) update_ {
8901 [database_ update];
8902 }
8903
8904 - (void) syncData {
8905 [self _saveConfig];
8906
8907 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8908 _assert(file != NULL);
8909
8910 for (NSString *key in [Sources_ allKeys]) {
8911 NSDictionary *source([Sources_ objectForKey:key]);
8912
8913 fprintf(file, "%s %s %s\n",
8914 [[source objectForKey:@"Type"] UTF8String],
8915 [[source objectForKey:@"URI"] UTF8String],
8916 [[source objectForKey:@"Distribution"] UTF8String]
8917 );
8918 }
8919
8920 fclose(file);
8921
8922 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8923 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8924 if (IsWildcat_)
8925 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8926 [tabbar_ presentModalViewController:navigation animated:YES];
8927
8928 [progress
8929 detachNewThreadSelector:@selector(update_)
8930 toTarget:self
8931 withObject:nil
8932 title:UCLocalize("UPDATING_SOURCES")
8933 ];
8934 }
8935
8936 - (void) addTrivialSource:(NSString *)href {
8937 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8938 @"deb", @"Type",
8939 href, @"URI",
8940 @"./", @"Distribution",
8941 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8942
8943 Changed_ = true;
8944 }
8945
8946 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8947 @synchronized (self) {
8948 [self _reloadDataWithInvocation:invocation];
8949 }
8950 }
8951
8952 - (void) reloadData {
8953 [self reloadDataWithInvocation:nil];
8954 }
8955
8956 - (void) resolve {
8957 pkgProblemResolver *resolver = [database_ resolver];
8958
8959 resolver->InstallProtect();
8960 if (!resolver->Resolve(true))
8961 _error->Discard();
8962 }
8963
8964 - (bool) perform {
8965 // XXX: this is a really crappy way of doing this.
8966 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8967 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8968 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8969 if ([tabbar_ updating])
8970 [tabbar_ cancelUpdate];
8971
8972 if (![database_ prepare])
8973 return false;
8974
8975 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8976 [page setDelegate:self];
8977 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8978 [confirm_ setDelegate:self];
8979
8980 if (IsWildcat_)
8981 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8982 [tabbar_ presentModalViewController:confirm_ animated:YES];
8983
8984 return true;
8985 }
8986
8987 - (void) queue {
8988 @synchronized (self) {
8989 [self perform];
8990 }
8991 }
8992
8993 - (void) clearPackage:(Package *)package {
8994 @synchronized (self) {
8995 [package clear];
8996 [self resolve];
8997 [self perform];
8998 }
8999 }
9000
9001 - (void) installPackages:(NSArray *)packages {
9002 @synchronized (self) {
9003 for (Package *package in packages)
9004 [package install];
9005 [self resolve];
9006 [self perform];
9007 }
9008 }
9009
9010 - (void) installPackage:(Package *)package {
9011 @synchronized (self) {
9012 [package install];
9013 [self resolve];
9014 [self perform];
9015 }
9016 }
9017
9018 - (void) removePackage:(Package *)package {
9019 @synchronized (self) {
9020 [package remove];
9021 [self resolve];
9022 [self perform];
9023 }
9024 }
9025
9026 - (void) distUpgrade {
9027 @synchronized (self) {
9028 if (![database_ upgrade])
9029 return;
9030 [self perform];
9031 }
9032 }
9033
9034 - (void) complete {
9035 @synchronized (self) {
9036 [self _reloadDataWithInvocation:nil];
9037 }
9038 }
9039
9040 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9041 Queuing_ = false;
9042
9043 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9044
9045 if (navigation != nil) {
9046 [navigation pushViewController:progress animated:YES];
9047 } else {
9048 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9049 if (IsWildcat_)
9050 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9051 [tabbar_ presentModalViewController:navigation animated:YES];
9052 }
9053
9054 [progress
9055 detachNewThreadSelector:@selector(perform)
9056 toTarget:database_
9057 withObject:nil
9058 title:UCLocalize("RUNNING")
9059 ];
9060
9061 ++locked_;
9062 }
9063
9064 - (void) progressControllerIsComplete:(ProgressController *)progress {
9065 --locked_;
9066 [self complete];
9067 }
9068
9069 - (void) showSettings {
9070 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9071 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9072 if (IsWildcat_)
9073 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9074 [tabbar_ presentModalViewController:nav animated:YES];
9075 }
9076
9077 - (void) retainNetworkActivityIndicator {
9078 if (activity_++ == 0)
9079 [self setNetworkActivityIndicatorVisible:YES];
9080 }
9081
9082 - (void) releaseNetworkActivityIndicator {
9083 if (--activity_ == 0)
9084 [self setNetworkActivityIndicatorVisible:NO];
9085 }
9086
9087 - (void) cancelAndClear:(bool)clear {
9088 @synchronized (self) {
9089 if (clear) {
9090 [database_ clear];
9091 Queuing_ = false;
9092 } else {
9093 Queuing_ = true;
9094 }
9095
9096 [self _updateData];
9097 }
9098 }
9099
9100 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9101 NSString *context([alert context]);
9102
9103 if ([context isEqualToString:@"fixhalf"]) {
9104 if (button == [alert cancelButtonIndex]) {
9105 @synchronized (self) {
9106 for (Package *broken in broken_) {
9107 [broken remove];
9108
9109 NSString *id = [broken id];
9110 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9111 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9112 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9113 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9114 }
9115
9116 [self resolve];
9117 [self perform];
9118 }
9119 } else if (button == [alert firstOtherButtonIndex]) {
9120 [broken_ removeAllObjects];
9121 [self _loaded];
9122 }
9123
9124 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9125 } else if ([context isEqualToString:@"upgrade"]) {
9126 if (button == [alert firstOtherButtonIndex]) {
9127 @synchronized (self) {
9128 for (Package *essential in essential_)
9129 [essential install];
9130
9131 [self resolve];
9132 [self perform];
9133 }
9134 } else if (button == [alert firstOtherButtonIndex] + 1) {
9135 [self distUpgrade];
9136 } else if (button == [alert cancelButtonIndex]) {
9137 Ignored_ = YES;
9138 }
9139
9140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9141 }
9142 }
9143
9144 - (void) system:(NSString *)command { _pooled
9145 _trace();
9146 system([command UTF8String]);
9147 _trace();
9148 }
9149
9150 - (void) applicationWillSuspend {
9151 [database_ clean];
9152 [super applicationWillSuspend];
9153 }
9154
9155 - (BOOL) isSafeToSuspend {
9156 // Use external process status API internally.
9157 // This is probably a really bad idea.
9158 // XXX: what is the point of this? does this solve anything at all?
9159 uint64_t status = 0;
9160 int notify_token;
9161 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9162 notify_get_state(notify_token, &status);
9163 notify_cancel(notify_token);
9164 }
9165
9166 return locked_ == 0 && status == 0;
9167 }
9168
9169 - (void) applicationSuspend:(__GSEvent *)event {
9170 if ([self isSafeToSuspend])
9171 [super applicationSuspend:event];
9172 }
9173
9174 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9175 if ([self isSafeToSuspend])
9176 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9177 }
9178
9179 - (void) _setSuspended:(BOOL)value {
9180 if ([self isSafeToSuspend])
9181 [super _setSuspended:value];
9182 }
9183
9184 - (UIProgressHUD *) addProgressHUD {
9185 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9186 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9187
9188 [window_ setUserInteractionEnabled:NO];
9189 [hud show:YES];
9190
9191 UIViewController *target = tabbar_;
9192 while ([target modalViewController] != nil) target = [target modalViewController];
9193 [[target view] addSubview:hud];
9194
9195 ++locked_;
9196 return hud;
9197 }
9198
9199 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9200 [hud show:NO];
9201 [hud removeFromSuperview];
9202 [window_ setUserInteractionEnabled:YES];
9203 --locked_;
9204 }
9205
9206 - (CYViewController *) pageForPackage:(NSString *)name {
9207 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9208 }
9209
9210 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9211 NSString *scheme([[url scheme] lowercaseString]);
9212 if ([[url absoluteString] length] <= [scheme length] + 3)
9213 return nil;
9214 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9215 NSArray *components([path pathComponents]);
9216
9217 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9218 return [self pageForPackage:[components objectAtIndex:1]];
9219
9220 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9221 return nil;
9222
9223 NSString *base([components objectAtIndex:0]);
9224
9225 CYViewController *controller = nil;
9226
9227 if ([base isEqualToString:@"url"]) {
9228 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9229 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9230 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9231 } else if (!external && [components count] == 1) {
9232 if ([base isEqualToString:@"manage"]) {
9233 controller = [[[ManageController alloc] init] autorelease];
9234 }
9235
9236 if ([base isEqualToString:@"sources"]) {
9237 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9238 }
9239
9240 if ([base isEqualToString:@"home"]) {
9241 controller = [[[HomeController alloc] init] autorelease];
9242 }
9243
9244 if ([base isEqualToString:@"sections"]) {
9245 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9246 }
9247
9248 if ([base isEqualToString:@"search"]) {
9249 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9250 }
9251
9252 if ([base isEqualToString:@"changes"]) {
9253 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9254 }
9255
9256 if ([base isEqualToString:@"installed"]) {
9257 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9258 }
9259 } else if ([components count] == 2) {
9260 NSString *argument = [components objectAtIndex:1];
9261
9262 if ([base isEqualToString:@"package"]) {
9263 controller = [self pageForPackage:argument];
9264 }
9265
9266 if (!external && [base isEqualToString:@"search"]) {
9267 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9268 [(SearchController *)controller setSearchTerm:argument];
9269 }
9270
9271 if (!external && [base isEqualToString:@"sections"]) {
9272 if ([argument isEqualToString:@"all"])
9273 argument = nil;
9274 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9275 }
9276
9277 if (!external && [base isEqualToString:@"sources"]) {
9278 if ([argument isEqualToString:@"add"]) {
9279 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9280 [(SourcesController *)controller showAddSourcePrompt];
9281 } else {
9282 Source *source = [database_ sourceWithKey:argument];
9283 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9284 }
9285 }
9286
9287 if (!external && [base isEqualToString:@"launch"]) {
9288 [self launchApplicationWithIdentifier:argument suspended:NO];
9289 return nil;
9290 }
9291 } else if (!external && [components count] == 3) {
9292 NSString *arg1 = [components objectAtIndex:1];
9293 NSString *arg2 = [components objectAtIndex:2];
9294
9295 if ([base isEqualToString:@"package"]) {
9296 if ([arg2 isEqualToString:@"settings"]) {
9297 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9298 } else if ([arg2 isEqualToString:@"files"]) {
9299 if (Package *package = [database_ packageWithName:arg1]) {
9300 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9301 [(FileTable *)controller setPackage:package];
9302 }
9303 }
9304 }
9305 }
9306
9307 [controller setDelegate:self];
9308 return controller;
9309 }
9310
9311 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9312 CYViewController *page([self pageForURL:url forExternal:external]);
9313
9314 if (page != nil) {
9315 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9316 [nav setViewControllers:[NSArray arrayWithObject:page]];
9317 [tabbar_ setUnselectedViewController:nav];
9318 }
9319
9320 return page != nil;
9321 }
9322
9323 - (void) applicationOpenURL:(NSURL *)url {
9324 [super applicationOpenURL:url];
9325
9326 if (!loaded_) starturl_ = [url retain];
9327 else [self openCydiaURL:url forExternal:YES];
9328 }
9329
9330 - (void) applicationWillResignActive:(UIApplication *)application {
9331 // Stop refreshing if you get a phone call or lock the device.
9332 if ([tabbar_ updating])
9333 [tabbar_ cancelUpdate];
9334
9335 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9336 [super applicationWillResignActive:application];
9337 }
9338
9339 - (void) applicationWillTerminate:(UIApplication *)application {
9340 Changed_ = true;
9341 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9342 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9343 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9344
9345 [self _saveConfig];
9346 }
9347
9348 - (void) addStashController {
9349 ++locked_;
9350 stash_ = [[StashController alloc] init];
9351 [window_ addSubview:[stash_ view]];
9352 }
9353
9354 - (void) removeStashController {
9355 [[stash_ view] removeFromSuperview];
9356 [stash_ release];
9357 --locked_;
9358 }
9359
9360 - (void) stash {
9361 [self setIdleTimerDisabled:YES];
9362
9363 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9364 [self setStatusBarShowsProgress:YES];
9365 UpdateExternalStatus(1);
9366
9367 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9368
9369 UpdateExternalStatus(0);
9370 [self setStatusBarShowsProgress:NO];
9371
9372 [self removeStashController];
9373
9374 if (ExecFork() == 0) {
9375 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9376 perror("launchctl stop");
9377 }
9378 }
9379
9380 - (void) setupViewControllers {
9381 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9382
9383 NSMutableArray *items([NSMutableArray arrayWithObjects:
9384 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9385 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9386 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9387 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9388 nil]);
9389
9390 if (IsWildcat_) {
9391 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9392 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9393 } else {
9394 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9395 }
9396
9397 NSMutableArray *controllers([NSMutableArray array]);
9398 for (UITabBarItem *item in items) {
9399 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9400 [controller setTabBarItem:item];
9401 [controllers addObject:controller];
9402 }
9403 [tabbar_ setViewControllers:controllers];
9404
9405 [tabbar_ setUpdateDelegate:self];
9406 }
9407
9408 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9409 static CYEmulatedLoadingController *fake = nil;
9410
9411 if (view != nil) {
9412 if (fake == nil)
9413 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9414 [view addSubview:[fake view]];
9415 } else {
9416 [[fake view] removeFromSuperview];
9417 [fake release];
9418 fake = nil;
9419 }
9420
9421 return fake;
9422 }
9423
9424 - (void) applicationDidFinishLaunching:(id)unused {
9425 _trace();
9426 CydiaApp = self;
9427
9428 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9429 [self setApplicationSupportsShakeToEdit:NO];
9430
9431 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9432 initWithMemoryCapacity:524288
9433 diskCapacity:10485760
9434 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9435 ] autorelease]];
9436
9437 [CYBrowserController _initialize];
9438
9439 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9440
9441 Font12_ = [[UIFont systemFontOfSize:12] retain];
9442 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9443 Font14_ = [[UIFont systemFontOfSize:14] retain];
9444 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9445 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9446
9447 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9448 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9449
9450 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9451 [window_ orderFront:self];
9452 [window_ makeKey:self];
9453 [window_ setHidden:NO];
9454
9455 if (
9456 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9457 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9458 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9459 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9460 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9461 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9462 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9463 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9464 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9465 false
9466 ) {
9467 [self addStashController];
9468 // XXX: this would be much cleaner as a yieldToSelector:
9469 // that way the removeStashController could happen right here inline
9470 // we also could no longer require the useless stash_ field anymore
9471 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9472 return;
9473 }
9474
9475 database_ = [Database sharedInstance];
9476
9477 [window_ setUserInteractionEnabled:NO];
9478 [self setupViewControllers];
9479 [self showEmulatedLoadingControllerInView:window_];
9480
9481 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9482 _trace();
9483 }
9484
9485 - (void) loadData {
9486 _trace();
9487 if (Role_ == nil) {
9488 [window_ setUserInteractionEnabled:YES];
9489
9490 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9491 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9492 if (IsWildcat_)
9493 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9494 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9495
9496 return;
9497 } else {
9498 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9499 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9500 [window_ setUserInteractionEnabled:NO];
9501 }
9502
9503 [self reloadData];
9504 PrintTimes();
9505
9506 [window_ addSubview:[tabbar_ view]];
9507 [self showEmulatedLoadingControllerInView:nil];
9508 [window_ setUserInteractionEnabled:YES];
9509
9510 int selectedIndex = 0;
9511 NSMutableArray *items = nil;
9512
9513 bool recently = false;
9514 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9515 if (closed != nil) {
9516 NSTimeInterval interval([closed timeIntervalSinceNow]);
9517 // XXX: Is 15 minutes the optimal time here?
9518 if (interval <= 0 && interval > -(15*60))
9519 recently = true;
9520 }
9521
9522 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9523 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9524
9525 BOOL enough = YES;
9526 for (NSArray *entry in items)
9527 if ([entry count] <= 0)
9528 enough = NO;
9529
9530 if (!recently || !items || !enough) {
9531 selectedIndex = 0;
9532 items = [NSMutableArray array];
9533 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9534 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9535 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9536 if (!IsWildcat_) {
9537 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9538 } else {
9539 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9540 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9541 }
9542 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9543 }
9544
9545 [tabbar_ setSelectedIndex:selectedIndex];
9546 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9547 NSArray *stack = [items objectAtIndex:tab];
9548 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9549 NSMutableArray *current = [NSMutableArray array];
9550
9551 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9552 NSString *addr = [stack objectAtIndex:nav];
9553 NSURL *url = [NSURL URLWithString:addr];
9554 CYViewController *page = [self pageForURL:url forExternal:NO];
9555 if (page != nil)
9556 [current addObject:page];
9557 }
9558
9559 [navigation setViewControllers:current];
9560 }
9561
9562 // (Try to) show the startup URL.
9563 if (starturl_ != nil) {
9564 [self openCydiaURL:starturl_ forExternal:NO];
9565 [starturl_ release];
9566 starturl_ = nil;
9567 }
9568 }
9569
9570 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9571 if (item != nil && IsWildcat_) {
9572 [sheet showFromBarButtonItem:item animated:YES];
9573 } else {
9574 [sheet showInView:window_];
9575 }
9576 }
9577
9578 @end
9579
9580 /*IMP alloc_;
9581 id Alloc_(id self, SEL selector) {
9582 id object = alloc_(self, selector);
9583 lprintf("[%s]A-%p\n", self->isa->name, object);
9584 return object;
9585 }*/
9586
9587 /*IMP dealloc_;
9588 id Dealloc_(id self, SEL selector) {
9589 id object = dealloc_(self, selector);
9590 lprintf("[%s]D-%p\n", self->isa->name, object);
9591 return object;
9592 }*/
9593
9594 Class $WebDefaultUIKitDelegate;
9595
9596 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9597 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9598 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9599 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9600 }
9601
9602 static NSNumber *shouldPlayKeyboardSounds;
9603
9604 Class $UIHardware;
9605
9606 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9607 switch (sound) {
9608 case 1104: // Keyboard Button Clicked
9609 case 1105: // Keyboard Delete Repeated
9610 if (shouldPlayKeyboardSounds == nil) {
9611 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9612 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9613 }
9614
9615 if (![shouldPlayKeyboardSounds boolValue])
9616 break;
9617
9618 default:
9619 _UIHardware$_playSystemSound$(self, _cmd, sound);
9620 }
9621 }
9622
9623 Class $UIApplication;
9624
9625 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9626 static BOOL initialized = NO;
9627 static BOOL started = NO;
9628
9629 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9630 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9631
9632 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9633 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9634 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9635 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9636
9637 if (initialized && !enabled) {
9638 initialized = NO;
9639 [bundle performSelector:@selector(_accessibilityStopServer)];
9640 } else if (enabled) {
9641 initialized = YES;
9642 if (!started) {
9643 started = YES;
9644 [bundle performSelector:@selector(_accessibilityStartServer)];
9645 }
9646 }
9647 }
9648 }
9649
9650 int main(int argc, char *argv[]) { _pooled
9651 _trace();
9652
9653 if (Class $UIDevice = objc_getClass("UIDevice")) {
9654 UIDevice *device([$UIDevice currentDevice]);
9655 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9656 } else
9657 IsWildcat_ = false;
9658
9659 UIScreen *screen([UIScreen mainScreen]);
9660 if ([screen respondsToSelector:@selector(scale)])
9661 ScreenScale_ = [screen scale];
9662 else
9663 ScreenScale_ = 1;
9664
9665 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9666 if (ScreenScale_ > 1)
9667 [parts addObject:@"@2x"];
9668 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9669 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9670
9671 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9672
9673 /* Library Hacks {{{ */
9674 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9675
9676 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9677 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9678 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9679 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9680 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9681 }
9682
9683 $UIHardware = objc_getClass("UIHardware");
9684 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9685 if (UIHardware$_playSystemSound$ != NULL) {
9686 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9687 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9688 }
9689
9690 $UIApplication = objc_getClass("UIApplication");
9691 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9692 if (UIApplication$_updateApplicationAccessibility != NULL) {
9693 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9694 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9695 }
9696 /* }}} */
9697 /* Set Locale {{{ */
9698 Locale_ = CFLocaleCopyCurrent();
9699 Languages_ = [NSLocale preferredLanguages];
9700 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9701 //NSLog(@"%@", [Languages_ description]);
9702
9703 const char *lang;
9704 if (Languages_ == nil || [Languages_ count] == 0)
9705 // XXX: consider just setting to C and then falling through?
9706 lang = NULL;
9707 else {
9708 lang = [[Languages_ objectAtIndex:0] UTF8String];
9709 setenv("LANG", lang, true);
9710 }
9711
9712 //std::setlocale(LC_ALL, lang);
9713 NSLog(@"Setting Language: %s", lang);
9714 /* }}} */
9715
9716 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9717
9718 /* Parse Arguments {{{ */
9719 bool substrate(false);
9720
9721 if (argc != 0) {
9722 char **args(argv);
9723 int arge(1);
9724
9725 for (int argi(1); argi != argc; ++argi)
9726 if (strcmp(argv[argi], "--") == 0) {
9727 arge = argi;
9728 argv[argi] = argv[0];
9729 argv += argi;
9730 argc -= argi;
9731 break;
9732 }
9733
9734 for (int argi(1); argi != arge; ++argi)
9735 if (strcmp(args[argi], "--substrate") == 0)
9736 substrate = true;
9737 else
9738 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9739 }
9740 /* }}} */
9741
9742 App_ = [[NSBundle mainBundle] bundlePath];
9743 Home_ = NSHomeDirectory();
9744 Advanced_ = YES;
9745
9746 setuid(0);
9747 setgid(0);
9748
9749 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9750 alloc_ = alloc->method_imp;
9751 alloc->method_imp = (IMP) &Alloc_;*/
9752
9753 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9754 dealloc_ = dealloc->method_imp;
9755 dealloc->method_imp = (IMP) &Dealloc_;*/
9756
9757 /* System Information {{{ */
9758 size_t size;
9759
9760 int maxproc;
9761 size = sizeof(maxproc);
9762 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9763 perror("sysctlbyname(\"kern.maxproc\", ?)");
9764 else if (maxproc < 64) {
9765 maxproc = 64;
9766 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9767 perror("sysctlbyname(\"kern.maxproc\", #)");
9768 }
9769
9770 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9771 char *osversion = new char[size];
9772 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9773 perror("sysctlbyname(\"kern.osversion\", ?)");
9774 else
9775 System_ = [NSString stringWithUTF8String:osversion];
9776
9777 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9778 char *machine = new char[size];
9779 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9780 perror("sysctlbyname(\"hw.machine\", ?)");
9781 else
9782 Machine_ = machine;
9783
9784 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9785 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9786 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9787 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9788 CFRelease(serial);
9789 }
9790
9791 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9792 NSData *data((NSData *) ecid);
9793 size_t length([data length]);
9794 uint8_t bytes[length];
9795 [data getBytes:bytes];
9796 char string[length * 2 + 1];
9797 for (size_t i(0); i != length; ++i)
9798 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9799 ChipID_ = [NSString stringWithUTF8String:string];
9800 CFRelease(ecid);
9801 }
9802
9803 IOObjectRelease(service);
9804 }
9805 }
9806
9807 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9808
9809 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9810 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9811 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9812
9813 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9814 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9815 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9816
9817 if (mcc != NULL && mnc != NULL)
9818 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9819
9820 if (mnc != NULL)
9821 CFRelease(mnc);
9822 if (mcc != NULL)
9823 CFRelease(mcc);
9824
9825 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9826 Build_ = [system objectForKey:@"ProductBuildVersion"];
9827 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9828 Product_ = [info objectForKey:@"SafariProductVersion"];
9829 Safari_ = [info objectForKey:@"CFBundleVersion"];
9830 }
9831 /* }}} */
9832 /* Load Database {{{ */
9833 _trace();
9834 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9835 _trace();
9836 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9837
9838 if (Metadata_ == NULL)
9839 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9840 else {
9841 Settings_ = [Metadata_ objectForKey:@"Settings"];
9842
9843 Packages_ = [Metadata_ objectForKey:@"Packages"];
9844 Sections_ = [Metadata_ objectForKey:@"Sections"];
9845 Sources_ = [Metadata_ objectForKey:@"Sources"];
9846
9847 Token_ = [Metadata_ objectForKey:@"Token"];
9848 }
9849
9850 if (Settings_ != nil)
9851 Role_ = [Settings_ objectForKey:@"Role"];
9852
9853 if (Sections_ == nil) {
9854 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9855 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9856 }
9857
9858 if (Sources_ == nil) {
9859 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9860 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9861 }
9862 /* }}} */
9863
9864 _trace();
9865 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9866 _trace();
9867
9868 if (Packages_ != nil) {
9869 bool fail(false);
9870 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9871 _trace();
9872
9873 if (!fail) {
9874 [Metadata_ removeObjectForKey:@"Packages"];
9875 Packages_ = nil;
9876 Changed_ = true;
9877 }
9878 }
9879
9880 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9881
9882 #define MobileSubstrate_(name) \
9883 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9884 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9885
9886 MobileSubstrate_(Activator)
9887 MobileSubstrate_(libstatusbar)
9888 MobileSubstrate_(SimulatedKeyEvents)
9889 MobileSubstrate_(WinterBoard)
9890
9891 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9892 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9893
9894 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9895
9896 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9897 unlink("/tmp/.cydia.fw");
9898 goto firmware;
9899 } else if (access("/User", F_OK) != 0 || version < 2) {
9900 firmware:
9901 _trace();
9902 system("/usr/libexec/cydia/firmware.sh");
9903 _trace();
9904 }
9905
9906 _assert([[NSFileManager defaultManager]
9907 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9908 withIntermediateDirectories:YES
9909 attributes:nil
9910 error:NULL
9911 ]);
9912
9913 if (access("/tmp/cydia.chk", F_OK) == 0) {
9914 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9915 _assert(errno == ENOENT);
9916 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9917 _assert(errno == ENOENT);
9918 }
9919
9920 /* APT Initialization {{{ */
9921 _assert(pkgInitConfig(*_config));
9922 _assert(pkgInitSystem(*_config, _system));
9923
9924 if (lang != NULL)
9925 _config->Set("APT::Acquire::Translation", lang);
9926
9927 // XXX: this timeout might be important :(
9928 //_config->Set("Acquire::http::Timeout", 15);
9929
9930 _config->Set("Acquire::http::MaxParallel", 3);
9931 /* }}} */
9932 /* Color Choices {{{ */
9933 space_ = CGColorSpaceCreateDeviceRGB();
9934
9935 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9936 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9937 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9938 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9939 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9940 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9941 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9942 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9943 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9944
9945 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9946 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9947 /* }}}*/
9948 /* UIKit Configuration {{{ */
9949 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9950 if ($GSFontSetUseLegacyFontMetrics != NULL)
9951 $GSFontSetUseLegacyFontMetrics(YES);
9952
9953 // XXX: I have a feeling this was important
9954 //UIKeyboardDisableAutomaticAppearance();
9955 /* }}} */
9956
9957 Colon_ = UCLocalize("COLON_DELIMITED");
9958 Elision_ = UCLocalize("ELISION");
9959 Error_ = UCLocalize("ERROR");
9960 Warning_ = UCLocalize("WARNING");
9961
9962 _trace();
9963 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9964
9965 CGColorSpaceRelease(space_);
9966 CFRelease(Locale_);
9967
9968 return value;
9969 }