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