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