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