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