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