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