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