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