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