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