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