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