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