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