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