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