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