]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Remove seemingly incorrect special case for /var/lib/dpkg/lock.
[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
3392 while (!_error->empty()) {
3393 std::string error;
3394 bool warning(!_error->PopMessage(error));
3395 if (!warning)
3396 fatal = true;
3397
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
3405 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3406
3407 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, (warning ? Warning_ : Error_), title]];
3408 }
3409
3410 return fatal;
3411 }
3412
3413 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3414 return [self popErrorWithTitle:title] || !success;
3415 }
3416
3417 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3418 @synchronized (self) {
3419 ++era_;
3420
3421 [self releasePackages];
3422
3423 sourceMap_.clear();
3424 [sourceList_ removeAllObjects];
3425
3426 _error->Discard();
3427
3428 delete list_;
3429 list_ = NULL;
3430 manager_ = NULL;
3431 delete lock_;
3432 lock_ = NULL;
3433 delete fetcher_;
3434 fetcher_ = NULL;
3435 delete resolver_;
3436 resolver_ = NULL;
3437 delete records_;
3438 records_ = NULL;
3439 delete policy_;
3440 policy_ = NULL;
3441
3442 cache_.Close();
3443
3444 apr_pool_clear(pool_);
3445
3446 NSRecycleZone(zone_);
3447 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3448
3449 int chk(creat("/tmp/cydia.chk", 0644));
3450 if (chk != -1)
3451 close(chk);
3452
3453 if (invocation != nil)
3454 [invocation invoke];
3455
3456 NSString *title(UCLocalize("DATABASE"));
3457
3458 _trace();
3459 OpProgress progress;
3460 while (!cache_.Open(progress, true)) { pop:
3461 std::string error;
3462 bool warning(!_error->PopMessage(error));
3463 lprintf("cache_.Open():[%s]\n", error.c_str());
3464
3465 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3466 [delegate_ repairWithSelector:@selector(configure)];
3467 else if (error == "The package lists or status file could not be parsed or opened.")
3468 [delegate_ repairWithSelector:@selector(update)];
3469 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3470 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3471 // else if (error == "The list of sources could not be read.")
3472 else {
3473 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3474 return;
3475 }
3476
3477 if (warning)
3478 goto pop;
3479 _error->Discard();
3480 }
3481 _trace();
3482
3483 unlink("/tmp/cydia.chk");
3484
3485 now_ = [[NSDate date] timeIntervalSince1970];
3486
3487 policy_ = new pkgDepCache::Policy();
3488 records_ = new pkgRecords(cache_);
3489 resolver_ = new pkgProblemResolver(cache_);
3490 fetcher_ = new pkgAcquire(&status_);
3491 lock_ = NULL;
3492
3493 list_ = new pkgSourceList();
3494 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3495 return;
3496
3497 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3498 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3499 return;
3500 }
3501
3502 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3503 return;
3504
3505 if (cache_->BrokenCount() != 0) {
3506 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3507 return;
3508
3509 if (cache_->BrokenCount() != 0) {
3510 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3511 return;
3512 }
3513
3514 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3515 return;
3516 }
3517
3518 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3519 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3520 [sourceList_ addObject:object];
3521
3522 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3523 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3524 // XXX: this could be more intelligent
3525 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3526 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3527 if (!cached.end())
3528 sourceMap_[cached->ID] = object;
3529 }
3530 }
3531
3532 {
3533 /*std::vector<Package *> packages;
3534 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3535 [packages_ release];
3536 packages_ = nil;*/
3537
3538 _trace();
3539
3540 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3541 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3542 //packages.push_back(package);
3543 CFArrayAppendValue(packages_, [package retain]);
3544
3545 _trace();
3546
3547 /*if (packages.empty())
3548 packages_ = [[NSArray alloc] init];
3549 else
3550 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3551 _trace();*/
3552
3553 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3554 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3555 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3556
3557 /*_trace();
3558 PrintTimes();
3559 _trace();*/
3560
3561 _trace();
3562
3563 /*if (!packages.empty())
3564 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3565 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3566
3567 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3568
3569 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3570
3571 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3572
3573 _trace();
3574
3575 size_t count(CFArrayGetCount(packages_));
3576 MetaFile_->active_ = count;
3577
3578 for (size_t index(0); index != count; ++index)
3579 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3580
3581 _trace();
3582 }
3583 } } CYPoolEnd() _trace(); }
3584
3585 - (void) clear {
3586 @synchronized (self) {
3587 delete resolver_;
3588 resolver_ = new pkgProblemResolver(cache_);
3589
3590 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3591 if (!cache_[iterator].Keep())
3592 cache_->MarkKeep(iterator, false);
3593 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3594 cache_->SetReInstall(iterator, false);
3595 } }
3596
3597 - (void) configure {
3598 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3599 _trace();
3600 system([dpkg UTF8String]);
3601 _trace();
3602 }
3603
3604 - (bool) clean {
3605 // XXX: I don't remember this condition
3606 if (lock_ != NULL)
3607 return false;
3608
3609 FileFd Lock;
3610 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3611
3612 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3613
3614 if ([self popErrorWithTitle:title])
3615 return false;
3616
3617 pkgAcquire fetcher;
3618 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3619
3620 class LogCleaner :
3621 public pkgArchiveCleaner
3622 {
3623 protected:
3624 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3625 unlink(File);
3626 }
3627 } cleaner;
3628
3629 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3630 return false;
3631
3632 return true;
3633 }
3634
3635 - (bool) prepare {
3636 fetcher_->Shutdown();
3637
3638 pkgRecords records(cache_);
3639
3640 lock_ = new FileFd();
3641 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3642
3643 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3644
3645 if ([self popErrorWithTitle:title])
3646 return false;
3647
3648 pkgSourceList list;
3649 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3650 return false;
3651
3652 manager_ = (_system->CreatePM(cache_));
3653 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3654 return false;
3655
3656 return true;
3657 }
3658
3659 - (void) perform {
3660 bool substrate(RestartSubstrate_);
3661 RestartSubstrate_ = false;
3662
3663 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3664
3665 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3666 pkgSourceList list;
3667 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3668 return;
3669 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3670 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3671 }
3672
3673 [CydiaApp performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3674
3675 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3676 _trace();
3677 [self popErrorWithTitle:title];
3678 return;
3679 }
3680
3681 bool failed = false;
3682 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3683 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3684 continue;
3685 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3686 continue;
3687
3688 failed = true;
3689 }
3690
3691 [CydiaApp performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3692
3693 if (failed) {
3694 _trace();
3695 return;
3696 }
3697
3698 if (substrate)
3699 RestartSubstrate_ = true;
3700
3701 _system->UnLock();
3702 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3703
3704 if (_error->PendingError()) {
3705 _trace();
3706 return;
3707 }
3708
3709 if (result == pkgPackageManager::Failed) {
3710 _trace();
3711 return;
3712 }
3713
3714 if (result != pkgPackageManager::Completed) {
3715 _trace();
3716 return;
3717 }
3718
3719 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3720 pkgSourceList list;
3721 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3722 return;
3723 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3724 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3725 }
3726
3727 if (![before isEqualToArray:after])
3728 [self update];
3729 }
3730
3731 - (bool) upgrade {
3732 NSString *title(UCLocalize("UPGRADE"));
3733 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3734 return false;
3735 return true;
3736 }
3737
3738 - (void) update {
3739 [self updateWithStatus:status_];
3740 }
3741
3742 - (void) updateWithStatus:(Status &)status {
3743 NSString *title(UCLocalize("REFRESHING_DATA"));
3744
3745 pkgSourceList list;
3746 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3747 return;
3748
3749 FileFd lock;
3750 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3751 if ([self popErrorWithTitle:title])
3752 return;
3753
3754 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3755 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3756 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3757
3758 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3759 Changed_ = true;
3760 }
3761
3762 - (void) setDelegate:(id)delegate {
3763 delegate_ = delegate;
3764 status_.setDelegate(delegate);
3765 }
3766
3767 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3768 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3769 return i == sourceMap_.end() ? nil : i->second;
3770 }
3771
3772 - (NSString *) mappedSectionForPointer:(const char *)section {
3773 _H<NSString> *mapped;
3774
3775 _profile(Database$mappedSectionForPointer$Cache)
3776 mapped = &sections_[section];
3777 _end
3778
3779 if (*mapped == NULL) {
3780 size_t length(strlen(section));
3781 char spaced[length + 1];
3782
3783 _profile(Database$mappedSectionForPointer$Replace)
3784 for (size_t index(0); index != length; ++index)
3785 spaced[index] = section[index] == '_' ? ' ' : section[index];
3786 spaced[length] = '\0';
3787 _end
3788
3789 NSString *string;
3790
3791 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3792 string = [NSString stringWithUTF8String:spaced];
3793 _end
3794
3795 _profile(Database$mappedSectionForPointer$Map)
3796 string = [SectionMap_ objectForKey:string] ?: string;
3797 _end
3798
3799 *mapped = string;
3800 } return *mapped;
3801 }
3802
3803 @end
3804 /* }}} */
3805
3806 /* Web Scripting {{{ */
3807 @interface CydiaObject : NSObject {
3808 id indirect_;
3809 _transient id delegate_;
3810 }
3811
3812 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3813
3814 @end
3815
3816 @implementation CydiaObject
3817
3818 - (void) dealloc {
3819 [indirect_ release];
3820 [super dealloc];
3821 }
3822
3823 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3824 if ((self = [super init]) != nil) {
3825 indirect_ = [indirect retain];
3826 } return self;
3827 }
3828
3829 - (void) setDelegate:(id)delegate {
3830 delegate_ = delegate;
3831 }
3832
3833 + (NSArray *) _attributeKeys {
3834 return [NSArray arrayWithObjects:
3835 @"device",
3836 @"ecid",
3837 @"model",
3838 @"plmn",
3839 @"role",
3840 @"serial",
3841 nil];
3842 }
3843
3844 - (NSArray *) attributeKeys {
3845 return [[self class] _attributeKeys];
3846 }
3847
3848 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3849 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3850 }
3851
3852 - (NSString *) device {
3853 return [[UIDevice currentDevice] uniqueIdentifier];
3854 }
3855
3856 - (NSString *) plmn {
3857 return PLMN_;
3858 }
3859
3860 - (NSString *) ecid {
3861 return ChipID_;
3862 }
3863
3864 - (NSString *) serial {
3865 return SerialNumber_;
3866 }
3867
3868 - (NSString *) role {
3869 return Role_;
3870 }
3871
3872 - (NSString *) model {
3873 return [NSString stringWithUTF8String:Machine_];
3874 }
3875
3876 + (NSString *) webScriptNameForSelector:(SEL)selector {
3877 if (false);
3878 else if (selector == @selector(addTrivialSource:))
3879 return @"addTrivialSource";
3880 else if (selector == @selector(close))
3881 return @"close";
3882 else if (selector == @selector(du:))
3883 return @"du";
3884 else if (selector == @selector(stringWithFormat:arguments:))
3885 return @"format";
3886 else if (selector == @selector(getAllSources))
3887 return @"getAllSourcs";
3888 else if (selector == @selector(getKernelNumber:))
3889 return @"getKernelNumber";
3890 else if (selector == @selector(getKernelString:))
3891 return @"getKernelString";
3892 else if (selector == @selector(getInstalledPackages))
3893 return @"getInstalledPackages";
3894 else if (selector == @selector(getPackageById:))
3895 return @"getPackageById";
3896 else if (selector == @selector(installPackages:))
3897 return @"installPackages";
3898 else if (selector == @selector(localizedStringForKey:value:table:))
3899 return @"localize";
3900 else if (selector == @selector(refreshSources))
3901 return @"refreshSources";
3902 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3903 return @"setButtonImage";
3904 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3905 return @"setButtonTitle";
3906 else if (selector == @selector(setPopupHook:))
3907 return @"setPopupHook";
3908 else if (selector == @selector(setToken:))
3909 return @"setToken";
3910 else if (selector == @selector(setViewportWidth:))
3911 return @"setViewportWidth";
3912 else if (selector == @selector(statfs:))
3913 return @"statfs";
3914 else if (selector == @selector(supports:))
3915 return @"supports";
3916 else
3917 return nil;
3918 }
3919
3920 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3921 return [self webScriptNameForSelector:selector] == nil;
3922 }
3923
3924 - (BOOL) supports:(NSString *)feature {
3925 return [feature isEqualToString:@"window.open"];
3926 }
3927
3928 - (NSNumber *) getKernelNumber:(NSString *)name {
3929 const char *string([name UTF8String]);
3930
3931 size_t size;
3932 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3933 return (id) [NSNull null];
3934
3935 if (size != sizeof(int))
3936 return (id) [NSNull null];
3937
3938 int value;
3939 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3940 return (id) [NSNull null];
3941
3942 return [NSNumber numberWithInt:value];
3943 }
3944
3945 - (NSString *) getKernelString:(NSString *)name {
3946 const char *string([name UTF8String]);
3947
3948 size_t size;
3949 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3950 return (id) [NSNull null];
3951
3952 char value[size + 1];
3953 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3954 return (id) [NSNull null];
3955
3956 // XXX: just in case you request something ludicrous
3957 value[size] = '\0';
3958
3959 return [NSString stringWithCString:value];
3960 }
3961
3962 - (void) addTrivialSource:(NSString *)href {
3963 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3964 }
3965
3966 - (void) refreshSources {
3967 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3968 }
3969
3970 - (NSArray *) getAllSources {
3971 return [[Database sharedInstance] sources];
3972 }
3973
3974 - (NSArray *) getInstalledPackages {
3975 Database *database([Database sharedInstance]);
3976 @synchronized (database) {
3977 NSArray *packages([database packages]);
3978 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3979 for (Package *package in packages)
3980 if (![package uninstalled])
3981 [installed addObject:package];
3982 return installed;
3983 } }
3984
3985 - (Package *) getPackageById:(NSString *)id {
3986 Package *package([[Database sharedInstance] packageWithName:id]);
3987 [package parse];
3988 return package;
3989 }
3990
3991 - (NSArray *) statfs:(NSString *)path {
3992 struct statfs stat;
3993
3994 if (path == nil || statfs([path UTF8String], &stat) == -1)
3995 return nil;
3996
3997 return [NSArray arrayWithObjects:
3998 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3999 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4000 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4001 nil];
4002 }
4003
4004 - (NSNumber *) du:(NSString *)path {
4005 NSNumber *value(nil);
4006
4007 int fds[2];
4008 _assert(pipe(fds) != -1);
4009
4010 pid_t pid(ExecFork());
4011 if (pid == 0) {
4012 _assert(dup2(fds[1], 1) != -1);
4013 _assert(close(fds[0]) != -1);
4014 _assert(close(fds[1]) != -1);
4015 /* XXX: this should probably not use du */
4016 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4017 exit(1);
4018 _assert(false);
4019 }
4020
4021 _assert(close(fds[1]) != -1);
4022
4023 if (FILE *du = fdopen(fds[0], "r")) {
4024 char line[1024];
4025 while (fgets(line, sizeof(line), du) != NULL) {
4026 size_t length(strlen(line));
4027 while (length != 0 && line[length - 1] == '\n')
4028 line[--length] = '\0';
4029 if (char *tab = strchr(line, '\t')) {
4030 *tab = '\0';
4031 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4032 }
4033 }
4034
4035 fclose(du);
4036 } else _assert(close(fds[0]));
4037
4038 int status;
4039 wait:
4040 if (waitpid(pid, &status, 0) == -1)
4041 if (errno == EINTR)
4042 goto wait;
4043 else _assert(false);
4044
4045 return value;
4046 }
4047
4048 - (void) close {
4049 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4050 }
4051
4052 - (void) installPackages:(NSArray *)packages {
4053 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4054 }
4055
4056 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4057 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4058 }
4059
4060 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4061 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4062 }
4063
4064 - (void) _setToken:(NSString *)token {
4065 if (Token_ != nil)
4066 [Token_ release];
4067 Token_ = [token retain];
4068
4069 [Metadata_ setObject:Token_ forKey:@"Token"];
4070 Changed_ = true;
4071 }
4072
4073 - (void) setToken:(NSString *)token {
4074 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4075 }
4076
4077 - (void) setPopupHook:(id)function {
4078 [indirect_ setPopupHook:function];
4079 }
4080
4081 - (void) setViewportWidth:(float)width {
4082 [indirect_ setViewportWidthOnMainThread:width];
4083 }
4084
4085 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4086 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4087 unsigned count([arguments count]);
4088 id values[count];
4089 for (unsigned i(0); i != count; ++i)
4090 values[i] = [arguments objectAtIndex:i];
4091 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4092 }
4093
4094 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4095 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4096 value = nil;
4097 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4098 table = nil;
4099 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4100 }
4101
4102 @end
4103 /* }}} */
4104
4105 /* @ Loading... Indicator {{{ */
4106 @interface CYLoadingIndicator : UIView {
4107 UIActivityIndicatorView *spinner_;
4108 UILabel *label_;
4109 UIView *container_;
4110 }
4111
4112 @property (readonly, nonatomic) UILabel *label;
4113 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4114
4115 @end
4116
4117 @implementation CYLoadingIndicator
4118
4119 - (id) initWithFrame:(CGRect)frame {
4120 if ((self = [super initWithFrame:frame]) != nil) {
4121 container_ = [[[UIView alloc] init] autorelease];
4122 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4123
4124 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4125 [spinner_ startAnimating];
4126 [container_ addSubview:spinner_];
4127
4128 label_ = [[[UILabel alloc] init] autorelease];
4129 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4130 [label_ setBackgroundColor:[UIColor clearColor]];
4131 [label_ setTextColor:[UIColor blackColor]];
4132 [label_ setShadowColor:[UIColor whiteColor]];
4133 [label_ setShadowOffset:CGSizeMake(0, 1)];
4134 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4135 [container_ addSubview:label_];
4136
4137 CGSize viewsize = frame.size;
4138 CGSize spinnersize = [spinner_ bounds].size;
4139 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4140 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4141
4142 CGRect containrect = {
4143 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4144 CGSizeMake(bothwidth, spinnersize.height)
4145 };
4146 CGRect textrect = {
4147 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4148 textsize
4149 };
4150 CGRect spinrect = {
4151 CGPointZero,
4152 spinnersize
4153 };
4154
4155 [container_ setFrame:containrect];
4156 [spinner_ setFrame:spinrect];
4157 [label_ setFrame:textrect];
4158 [self addSubview:container_];
4159 } return self;
4160 }
4161
4162 - (UILabel *) label {
4163 return label_;
4164 }
4165
4166 - (UIActivityIndicatorView *) activityIndicatorView {
4167 return spinner_;
4168 }
4169
4170 @end
4171 /* }}} */
4172 /* Emulated Loading Controller {{{ */
4173 @interface CYEmulatedLoadingController : CYViewController <
4174 ProgressDelegate,
4175 ConfigurationDelegate
4176 > {
4177 _transient Database *database_;
4178 CYLoadingIndicator *indicator_;
4179 UITabBar *tabbar_;
4180 UINavigationBar *navbar_;
4181 }
4182
4183 @end
4184
4185 @implementation CYEmulatedLoadingController
4186
4187 - (void) dealloc {
4188 [self releaseSubviews];
4189 [database_ setDelegate:nil];
4190
4191 [super dealloc];
4192 }
4193
4194 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4195 CYAlertView *sheet([[[CYAlertView alloc]
4196 initWithTitle:title
4197 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4198 defaultButtonIndex:0
4199 ] autorelease]);
4200
4201 [sheet setMessage:error];
4202 [sheet yieldToPopupAlertAnimated:YES];
4203 [sheet dismiss];
4204 }
4205
4206 - (void) setProgressTitle:(NSString *)title { }
4207 - (void) setProgressPercent:(NSNumber *)percent { }
4208 - (void) startProgress { }
4209 - (void) addProgressOutput:(NSString *)output { }
4210 - (bool) isProgressCancelled { return NO; }
4211 - (void) setConfigurationData:(NSString *)data { }
4212
4213 - (void) repairWithSelector:(SEL)selector {
4214 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("REPAIRING"), nil] waitUntilDone:YES];
4215 [database_ performSelector:selector];
4216 sleep(10);
4217 [[indicator_ label] performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil] waitUntilDone:YES];
4218 }
4219
4220 - (id) initWithDatabase:(Database *)database {
4221 if ((self = [super init]) != nil) {
4222 database_ = database;
4223 [database_ setDelegate:self];
4224 } return self;
4225 }
4226
4227 - (void) loadView {
4228 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4229 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4230
4231 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4232 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4233 [[self view] addSubview:indicator_];
4234
4235 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4236 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4237 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4238 [[self view] addSubview:tabbar_];
4239
4240 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4241 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4242 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4243 [[self view] addSubview:navbar_];
4244 }
4245
4246 - (void) releaseSubviews {
4247 [indicator_ release];
4248 indicator_ = nil;
4249
4250 [tabbar_ release];
4251 tabbar_ = nil;
4252
4253 [navbar_ release];
4254 navbar_ = nil;
4255 }
4256
4257 @end
4258 /* }}} */
4259
4260 /* Cydia Browser Controller {{{ */
4261 @interface CYBrowserController : BrowserController {
4262 CydiaObject *cydia_;
4263 }
4264
4265 @end
4266
4267 @implementation CYBrowserController
4268
4269 - (void) dealloc {
4270 [cydia_ release];
4271 [super dealloc];
4272 }
4273
4274 - (NSURL *) navigationURL {
4275 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4276 }
4277
4278 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4279 }
4280
4281 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4282 [super webView:view didClearWindowObject:window forFrame:frame];
4283
4284 WebDataSource *source([frame dataSource]);
4285 NSURLResponse *response([source response]);
4286
4287 NSURL *url([response URL]);
4288 NSString *scheme([url scheme]);
4289 NSString *host([url host]);
4290
4291 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4292 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4293 NSDictionary *headers([http allHeaderFields]);
4294 [self setHeaders:headers forHost:host];
4295 }
4296
4297 if (
4298 [host isEqualToString:@"cydia.saurik.com"] ||
4299 [host hasSuffix:@".cydia.saurik.com"] ||
4300 [scheme isEqualToString:@"file"]
4301 )
4302 [window setValue:cydia_ forKey:@"cydia"];
4303 }
4304
4305 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4306 if (System_ != NULL)
4307 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4308 if (Machine_ != NULL)
4309 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4310 if (Token_ != nil)
4311 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4312 if (Role_ != nil)
4313 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4314 }
4315
4316 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4317 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4318 [self _setMoreHeaders:copy];
4319 return copy;
4320 }
4321
4322 - (void) setDelegate:(id)delegate {
4323 [super setDelegate:delegate];
4324 [cydia_ setDelegate:delegate];
4325 }
4326
4327 - (id) init {
4328 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4329 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4330
4331 WebView *webview([[webview_ _documentView] webView]);
4332
4333 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4334
4335 NSString *application = package == nil ? @"Cydia" : [NSString
4336 stringWithFormat:@"Cydia/%@",
4337 [package installed]
4338 ];
4339
4340 if (Safari_ != nil)
4341 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4342 if (Build_ != nil)
4343 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4344 if (Product_ != nil)
4345 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4346
4347 [webview setApplicationNameForUserAgent:application];
4348 } return self;
4349 }
4350
4351 @end
4352 /* }}} */
4353
4354 // CydiaScript {{{
4355 @interface NSObject (CydiaScript)
4356 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4357 @end
4358
4359 @implementation NSObject (CydiaScript)
4360
4361 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4362 return self;
4363 }
4364
4365 @end
4366
4367 @implementation NSArray (CydiaScript)
4368
4369 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4370 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4371 for (size_t i(0), e([self count]); i != e; ++i)
4372 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4373 return object;
4374 }
4375
4376 @end
4377
4378 @implementation NSDictionary (CydiaScript)
4379
4380 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4381 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4382 for (id i in self)
4383 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4384 return object;
4385 }
4386
4387 @end
4388 // }}}
4389
4390 /* Confirmation Controller {{{ */
4391 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4392 if (!iterator.end())
4393 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4394 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4395 continue;
4396 pkgCache::PkgIterator package(dep.TargetPkg());
4397 if (package.end())
4398 continue;
4399 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4400 return true;
4401 }
4402
4403 return false;
4404 }
4405
4406 @protocol ConfirmationControllerDelegate
4407 - (void) cancelAndClear:(bool)clear;
4408 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4409 - (void) queue;
4410 @end
4411
4412 @interface ConfirmationController : CYBrowserController {
4413 _transient Database *database_;
4414
4415 UIAlertView *essential_;
4416
4417 NSDictionary *changes_;
4418 NSMutableArray *issues_;
4419 NSDictionary *sizes_;
4420
4421 BOOL substrate_;
4422 }
4423
4424 - (id) initWithDatabase:(Database *)database;
4425
4426 @end
4427
4428 @implementation ConfirmationController
4429
4430 - (void) dealloc {
4431 [changes_ release];
4432 [issues_ release];
4433 [sizes_ release];
4434
4435 if (essential_ != nil)
4436 [essential_ release];
4437
4438 [super dealloc];
4439 }
4440
4441 - (void) complete {
4442 if (substrate_)
4443 RestartSubstrate_ = true;
4444 [delegate_ confirmWithNavigationController:[self navigationController]];
4445 }
4446
4447 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4448 NSString *context([alert context]);
4449
4450 if ([context isEqualToString:@"remove"]) {
4451 if (button == [alert cancelButtonIndex])
4452 [self dismissModalViewControllerAnimated:YES];
4453 else if (button == [alert firstOtherButtonIndex]) {
4454 [self complete];
4455 }
4456
4457 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4458 } else if ([context isEqualToString:@"unable"]) {
4459 [self dismissModalViewControllerAnimated:YES];
4460 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4461 } else {
4462 [super alertView:alert clickedButtonAtIndex:button];
4463 }
4464 }
4465
4466 - (void) _doContinue {
4467 [self dismissModalViewControllerAnimated:YES];
4468 [delegate_ cancelAndClear:NO];
4469 }
4470
4471 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4472 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4473 return nil;
4474 }
4475
4476 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4477 [super webView:view didClearWindowObject:window forFrame:frame];
4478
4479 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4480 changes_, @"changes",
4481 issues_, @"issues",
4482 sizes_, @"sizes",
4483 self, @"queue",
4484 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4485 }
4486
4487 - (id) initWithDatabase:(Database *)database {
4488 if ((self = [super init]) != nil) {
4489 database_ = database;
4490
4491 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4492 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4493 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4494 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4495 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4496
4497 bool remove(false);
4498
4499 pkgCacheFile &cache([database_ cache]);
4500 NSArray *packages([database_ packages]);
4501 pkgDepCache::Policy *policy([database_ policy]);
4502
4503 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4504
4505 for (Package *package in packages) {
4506 pkgCache::PkgIterator iterator([package iterator]);
4507 NSString *name([package id]);
4508
4509 if ([package broken]) {
4510 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4511
4512 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4513 name, @"package",
4514 reasons, @"reasons",
4515 nil]];
4516
4517 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4518 if (ver.end())
4519 continue;
4520
4521 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4522 pkgCache::DepIterator start;
4523 pkgCache::DepIterator end;
4524 dep.GlobOr(start, end); // ++dep
4525
4526 if (!cache->IsImportantDep(end))
4527 continue;
4528 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4529 continue;
4530
4531 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4532
4533 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4534 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4535 clauses, @"clauses",
4536 nil]];
4537
4538 _forever {
4539 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4540
4541 pkgCache::PkgIterator target(start.TargetPkg());
4542 if (target->ProvidesList != 0)
4543 reason = @"missing";
4544 else {
4545 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4546 if (!ver.end()) {
4547 reason = @"installed";
4548 installed = [NSString stringWithUTF8String:ver.VerStr()];
4549 } else if (!cache[target].CandidateVerIter(cache).end())
4550 reason = @"uninstalled";
4551 else if (target->ProvidesList == 0)
4552 reason = @"uninstallable";
4553 else
4554 reason = @"virtual";
4555 }
4556
4557 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4558 [NSString stringWithUTF8String:start.CompType()], @"operator",
4559 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4560 nil]);
4561
4562 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4563 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4564 version, @"version",
4565 reason, @"reason",
4566 installed, @"installed",
4567 nil]];
4568
4569 // yes, seriously. (wtf?)
4570 if (start == end)
4571 break;
4572 ++start;
4573 }
4574 }
4575 }
4576
4577 pkgDepCache::StateCache &state(cache[iterator]);
4578
4579 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4580
4581 if (state.NewInstall())
4582 [installs addObject:name];
4583 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4584 [reinstalls addObject:name];
4585 else if (state.Upgrade())
4586 [upgrades addObject:name];
4587 else if (state.Downgrade())
4588 [downgrades addObject:name];
4589 else if (!state.Delete())
4590 continue;
4591 else if (special_r(name))
4592 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4593 [NSNull null], @"package",
4594 [NSArray arrayWithObjects:
4595 [NSDictionary dictionaryWithObjectsAndKeys:
4596 @"Conflicts", @"relationship",
4597 [NSArray arrayWithObjects:
4598 [NSDictionary dictionaryWithObjectsAndKeys:
4599 name, @"package",
4600 [NSNull null], @"version",
4601 @"installed", @"reason",
4602 nil],
4603 nil], @"clauses",
4604 nil],
4605 nil], @"reasons",
4606 nil]];
4607 else {
4608 if ([package essential])
4609 remove = true;
4610 [removes addObject:name];
4611 }
4612
4613 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4614 substrate_ |= DepSubstrate(iterator.CurrentVer());
4615 }
4616
4617 if (!remove)
4618 essential_ = nil;
4619 else if (Advanced_) {
4620 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4621
4622 essential_ = [[UIAlertView alloc]
4623 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4624 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4625 delegate:self
4626 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4627 otherButtonTitles:
4628 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4629 nil
4630 ];
4631
4632 [essential_ setContext:@"remove"];
4633 } else {
4634 essential_ = [[UIAlertView alloc]
4635 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4636 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4637 delegate:self
4638 cancelButtonTitle:UCLocalize("OKAY")
4639 otherButtonTitles:nil
4640 ];
4641
4642 [essential_ setContext:@"unable"];
4643 }
4644
4645 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4646 installs, @"installs",
4647 reinstalls, @"reinstalls",
4648 upgrades, @"upgrades",
4649 downgrades, @"downgrades",
4650 removes, @"removes",
4651 nil];
4652
4653 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4654 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4655 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4656 nil];
4657
4658 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4659
4660 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4661 initWithTitle:UCLocalize("CANCEL")
4662 style:UIBarButtonItemStylePlain
4663 target:self
4664 action:@selector(cancelButtonClicked)
4665 ] autorelease]];
4666 } return self;
4667 }
4668
4669 #if !AlwaysReload
4670 - (void) applyRightButton {
4671 if ([issues_ count] == 0 && ![self isLoading])
4672 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4673 initWithTitle:UCLocalize("CONFIRM")
4674 style:UIBarButtonItemStyleDone
4675 target:self
4676 action:@selector(confirmButtonClicked)
4677 ] autorelease]];
4678 else
4679 [[self navigationItem] setRightBarButtonItem:nil];
4680 }
4681 #endif
4682
4683 - (void) cancelButtonClicked {
4684 [self dismissModalViewControllerAnimated:YES];
4685 [delegate_ cancelAndClear:YES];
4686 }
4687
4688 #if !AlwaysReload
4689 - (void) confirmButtonClicked {
4690 if (essential_ != nil)
4691 [essential_ show];
4692 else
4693 [self complete];
4694 }
4695 #endif
4696
4697 @end
4698 /* }}} */
4699
4700 /* Progress Data {{{ */
4701 @interface ProgressData : NSObject {
4702 SEL selector_;
4703 // XXX: should these really both be _transient?
4704 _transient id target_;
4705 _transient id object_;
4706 }
4707
4708 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4709
4710 - (SEL) selector;
4711 - (id) target;
4712 - (id) object;
4713
4714 @end
4715
4716 @implementation ProgressData
4717
4718 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4719 if ((self = [super init]) != nil) {
4720 selector_ = selector;
4721 target_ = target;
4722 object_ = object;
4723 } return self;
4724 }
4725
4726 - (SEL) selector {
4727 return selector_;
4728 }
4729
4730 - (id) target {
4731 return target_;
4732 }
4733
4734 - (id) object {
4735 return object_;
4736 }
4737
4738 @end
4739 /* }}} */
4740 /* Progress Controller {{{ */
4741 @interface ProgressController : CYViewController <
4742 ConfigurationDelegate,
4743 ProgressDelegate
4744 > {
4745 _transient Database *database_;
4746 UIProgressBar *progress_;
4747 UITextView *output_;
4748 UITextLabel *status_;
4749 UIPushButton *close_;
4750 BOOL running_;
4751 SHA1SumValue springlist_;
4752 SHA1SumValue notifyconf_;
4753 NSString *title_;
4754 }
4755
4756 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4757
4758 - (void) _retachThread;
4759 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4760
4761 - (BOOL) isRunning;
4762
4763 @end
4764
4765 @protocol ProgressControllerDelegate
4766 - (void) progressControllerIsComplete:(ProgressController *)sender;
4767 @end
4768
4769 @implementation ProgressController
4770
4771 - (void) dealloc {
4772 [database_ setDelegate:nil];
4773 [progress_ release];
4774 [output_ release];
4775 [status_ release];
4776 [close_ release];
4777 if (title_ != nil)
4778 [title_ release];
4779 [super dealloc];
4780 }
4781
4782 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4783 if ((self = [super init]) != nil) {
4784 database_ = database;
4785 [database_ setDelegate:self];
4786 delegate_ = delegate;
4787
4788 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4789
4790 progress_ = [[UIProgressBar alloc] init];
4791 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4792 [progress_ setStyle:0];
4793
4794 status_ = [[UITextLabel alloc] init];
4795 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4796 [status_ setColor:[UIColor whiteColor]];
4797 [status_ setBackgroundColor:[UIColor clearColor]];
4798 [status_ setCentersHorizontally:YES];
4799 //[status_ setFont:font];
4800
4801 output_ = [[UITextView alloc] init];
4802 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4803 //[output_ setTextFont:@"Courier New"];
4804 [output_ setFont:[[output_ font] fontWithSize:12]];
4805 [output_ setTextColor:[UIColor whiteColor]];
4806 [output_ setBackgroundColor:[UIColor clearColor]];
4807 [output_ setMarginTop:0];
4808 [output_ setAllowsRubberBanding:YES];
4809 [output_ setEditable:NO];
4810 [[self view] addSubview:output_];
4811
4812 close_ = [[UIPushButton alloc] init];
4813 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4814 [close_ setAutosizesToFit:NO];
4815 [close_ setDrawsShadow:YES];
4816 [close_ setStretchBackground:YES];
4817 [close_ setEnabled:YES];
4818 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4819 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4820 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4821 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4822 } return self;
4823 }
4824
4825 - (void) positionViews {
4826 CGRect bounds = [[self view] bounds];
4827 CGSize prgsize = [UIProgressBar defaultSize];
4828
4829 CGRect prgrect = {{
4830 (bounds.size.width - prgsize.width) / 2,
4831 bounds.size.height - prgsize.height - 20
4832 }, prgsize};
4833
4834 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4835
4836 [progress_ setFrame:prgrect];
4837 [status_ setFrame:CGRectMake(
4838 10,
4839 bounds.size.height - prgsize.height - 50,
4840 bounds.size.width - 20,
4841 24
4842 )];
4843 [output_ setFrame:CGRectMake(
4844 10,
4845 20,
4846 bounds.size.width - 20,
4847 bounds.size.height - 96
4848 )];
4849 [close_ setFrame:CGRectMake(
4850 (bounds.size.width - closewidth) / 2,
4851 bounds.size.height - prgsize.height - 50,
4852 closewidth,
4853 32 + prgsize.height
4854 )];
4855 }
4856
4857 - (void) viewWillAppear:(BOOL)animated {
4858 [super viewDidAppear:animated];
4859 [[self navigationItem] setHidesBackButton:YES];
4860 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4861
4862 [self positionViews];
4863 }
4864
4865 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4866 [self positionViews];
4867 }
4868
4869 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4870 NSString *context([alert context]);
4871
4872 if ([context isEqualToString:@"conffile"]) {
4873 FILE *input = [database_ input];
4874 if (button == [alert cancelButtonIndex])
4875 fprintf(input, "N\n");
4876 else if (button == [alert firstOtherButtonIndex])
4877 fprintf(input, "Y\n");
4878 fflush(input);
4879
4880 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4881 }
4882 }
4883
4884 - (void) closeButtonPushed {
4885 running_ = NO;
4886
4887 UpdateExternalStatus(0);
4888
4889 switch (Finish_) {
4890 case 0:
4891 [self dismissModalViewControllerAnimated:YES];
4892 break;
4893
4894 case 1:
4895 [delegate_ terminateWithSuccess];
4896 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4897 [delegate_ suspendWithAnimation:YES];
4898 else
4899 [delegate_ suspend];*/
4900 break;
4901
4902 case 2:
4903 _trace();
4904 goto reload;
4905
4906 case 3:
4907 _trace();
4908 goto reload;
4909
4910 reload:
4911 system("/usr/bin/sbreload");
4912 _trace();
4913 break;
4914
4915 case 4:
4916 _trace();
4917 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4918 SBReboot(SBSSpringBoardServerPort());
4919 else
4920 reboot2(RB_AUTOBOOT);
4921 break;
4922 }
4923 }
4924
4925 - (void) _retachThread {
4926 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4927
4928 [[self view] addSubview:close_];
4929 [progress_ removeFromSuperview];
4930 [status_ removeFromSuperview];
4931
4932 [database_ popErrorWithTitle:title_];
4933 [delegate_ progressControllerIsComplete:self];
4934
4935 if (Finish_ < 4) {
4936 FileFd file;
4937 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4938 _error->Discard();
4939 else {
4940 MMap mmap(file, MMap::ReadOnly);
4941 SHA1Summation sha1;
4942 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4943 if (!(notifyconf_ == sha1.Result()))
4944 Finish_ = 4;
4945 }
4946 }
4947
4948 if (Finish_ < 3) {
4949 FileFd file;
4950 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4951 _error->Discard();
4952 else {
4953 MMap mmap(file, MMap::ReadOnly);
4954 SHA1Summation sha1;
4955 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4956 if (!(springlist_ == sha1.Result()))
4957 Finish_ = 3;
4958 }
4959 }
4960
4961 if (Finish_ < 2) {
4962 if (RestartSubstrate_)
4963 Finish_ = 2;
4964 }
4965
4966 RestartSubstrate_ = false;
4967
4968 switch (Finish_) {
4969 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4970 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4971 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4972 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4973 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4974 }
4975
4976 _trace();
4977 system("su -c /usr/bin/uicache mobile");
4978 _trace();
4979
4980 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4981
4982 [delegate_ setStatusBarShowsProgress:NO];
4983 }
4984
4985 - (void) _detachNewThreadInvocation:(NSInvocation *)invocation { _pooled
4986 [invocation invoke];
4987 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4988 }
4989
4990 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4991 UpdateExternalStatus(1);
4992
4993 if (title_ != nil)
4994 [title_ release];
4995 if (title == nil)
4996 title_ = nil;
4997 else
4998 title_ = [title retain];
4999
5000 [[self navigationItem] setTitle:title_];
5001
5002 [status_ setText:nil];
5003 [output_ setText:@""];
5004 [progress_ setProgress:0];
5005
5006 [close_ removeFromSuperview];
5007 [[self view] addSubview:progress_];
5008 [[self view] addSubview:status_];
5009
5010 [delegate_ setStatusBarShowsProgress:YES];
5011 running_ = YES;
5012
5013 {
5014 FileFd file;
5015 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5016 _error->Discard();
5017 else {
5018 MMap mmap(file, MMap::ReadOnly);
5019 SHA1Summation sha1;
5020 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5021 notifyconf_ = sha1.Result();
5022 }
5023 }
5024
5025 {
5026 FileFd file;
5027 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5028 _error->Discard();
5029 else {
5030 MMap mmap(file, MMap::ReadOnly);
5031 SHA1Summation sha1;
5032 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5033 springlist_ = sha1.Result();
5034 }
5035 }
5036
5037 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
5038 [invocation setTarget:target];
5039 [invocation setSelector:selector];
5040 _assert(object == nil);
5041
5042 [NSThread detachNewThreadSelector:@selector(_detachNewThreadInvocation:) toTarget:self withObject:invocation];
5043 }
5044
5045 - (void) repairWithSelector:(SEL)selector {
5046 [self
5047 detachNewThreadSelector:selector
5048 toTarget:database_
5049 withObject:nil
5050 title:UCLocalize("REPAIRING")
5051 ];
5052 }
5053
5054 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
5055 CYAlertView *sheet([[[CYAlertView alloc]
5056 initWithTitle:title
5057 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5058 defaultButtonIndex:0
5059 ] autorelease]);
5060
5061 [sheet setMessage:error];
5062 [sheet yieldToPopupAlertAnimated:YES];
5063 [sheet dismiss];
5064 }
5065
5066 - (void) startProgress {
5067 }
5068
5069 - (bool) isProgressCancelled {
5070 return false;
5071 }
5072
5073 - (void) setConfigurationData:(NSString *)data {
5074 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
5075
5076 if (!conffile_r(data)) {
5077 lprintf("E:invalid conffile\n");
5078 return;
5079 }
5080
5081 NSString *ofile = conffile_r[1];
5082 //NSString *nfile = conffile_r[2];
5083
5084 UIAlertView *alert = [[[UIAlertView alloc]
5085 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
5086 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
5087 delegate:self
5088 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
5089 otherButtonTitles:
5090 UCLocalize("ACCEPT_NEW_COPY"),
5091 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
5092 nil
5093 ] autorelease];
5094
5095 [alert setContext:@"conffile"];
5096 [alert show];
5097 }
5098
5099 - (void) setProgressTitle:(NSString *)title {
5100 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
5101 for (size_t i(0), e([words count]); i != e; ++i) {
5102 NSString *word([words objectAtIndex:i]);
5103 if (Package *package = [database_ packageWithName:word])
5104 [words replaceObjectAtIndex:i withObject:[package name]];
5105 }
5106
5107 [status_ setText:[words componentsJoinedByString:@" "]];
5108 }
5109
5110 - (void) setProgressPercent:(NSNumber *)percent {
5111 [progress_ setProgress:[percent floatValue]];
5112 }
5113
5114 - (void) addProgressOutput:(NSString *)output {
5115 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
5116 CGSize size = [output_ contentSize];
5117 CGPoint offset = [output_ contentOffset];
5118 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5119 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5120 [output_ scrollRectToVisible:rect animated:YES];
5121 }
5122 }
5123
5124 - (BOOL) isRunning {
5125 return running_;
5126 }
5127
5128 @end
5129 /* }}} */
5130
5131 /* Cell Content View {{{ */
5132 @protocol ContentDelegate
5133 - (void) drawContentRect:(CGRect)rect;
5134 @end
5135
5136 @interface ContentView : UIView {
5137 _transient id<ContentDelegate> delegate_;
5138 }
5139
5140 @end
5141
5142 @implementation ContentView
5143
5144 - (id) initWithFrame:(CGRect)frame {
5145 if ((self = [super initWithFrame:frame]) != nil) {
5146 [self setNeedsDisplayOnBoundsChange:YES];
5147 } return self;
5148 }
5149
5150 - (void) setDelegate:(id<ContentDelegate>)delegate {
5151 delegate_ = delegate;
5152 }
5153
5154 - (void) drawRect:(CGRect)rect {
5155 [super drawRect:rect];
5156 [delegate_ drawContentRect:rect];
5157 }
5158
5159 @end
5160 /* }}} */
5161 /* Cydia TableView Cell {{{ */
5162 @interface CYTableViewCell : UITableViewCell {
5163 ContentView *content_;
5164 bool highlighted_;
5165 }
5166
5167 @end
5168
5169 @implementation CYTableViewCell
5170
5171 - (void) dealloc {
5172 [content_ release];
5173 [super dealloc];
5174 }
5175
5176 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5177 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5178
5179 if (view == content_) {
5180 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5181 highlighted_ = highlighted;
5182 }
5183
5184 [super _updateHighlightColorsForView:view highlighted:highlighted];
5185 }
5186
5187 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5188 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5189 highlighted_ = selected;
5190
5191 [super setSelected:selected animated:animated];
5192 [content_ setNeedsDisplay];
5193 }
5194
5195 @end
5196 /* }}} */
5197
5198 /* Package Cell {{{ */
5199 @interface PackageCell : CYTableViewCell <
5200 ContentDelegate
5201 > {
5202 UIImage *icon_;
5203 NSString *name_;
5204 NSString *description_;
5205 bool commercial_;
5206 NSString *source_;
5207 UIImage *badge_;
5208 Package *package_;
5209 UIImage *placard_;
5210 }
5211
5212 - (PackageCell *) init;
5213 - (void) setPackage:(Package *)package;
5214
5215 - (void) drawContentRect:(CGRect)rect;
5216
5217 @end
5218
5219 @implementation PackageCell
5220
5221 - (void) clearPackage {
5222 if (icon_ != nil) {
5223 [icon_ release];
5224 icon_ = nil;
5225 }
5226
5227 if (name_ != nil) {
5228 [name_ release];
5229 name_ = nil;
5230 }
5231
5232 if (description_ != nil) {
5233 [description_ release];
5234 description_ = nil;
5235 }
5236
5237 if (source_ != nil) {
5238 [source_ release];
5239 source_ = nil;
5240 }
5241
5242 if (badge_ != nil) {
5243 [badge_ release];
5244 badge_ = nil;
5245 }
5246
5247 if (placard_ != nil) {
5248 [placard_ release];
5249 placard_ = nil;
5250 }
5251
5252 [package_ release];
5253 package_ = nil;
5254 }
5255
5256 - (void) dealloc {
5257 [self clearPackage];
5258 [super dealloc];
5259 }
5260
5261 - (PackageCell *) init {
5262 CGRect frame(CGRectMake(0, 0, 320, 74));
5263 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5264 UIView *content([self contentView]);
5265 CGRect bounds([content bounds]);
5266
5267 content_ = [[ContentView alloc] initWithFrame:bounds];
5268 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5269 [content addSubview:content_];
5270
5271 [content_ setDelegate:self];
5272 [content_ setOpaque:YES];
5273 } return self;
5274 }
5275
5276 - (NSString *) accessibilityLabel {
5277 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5278 }
5279
5280 - (void) setPackage:(Package *)package {
5281 [self clearPackage];
5282 [package parse];
5283
5284 Source *source = [package source];
5285
5286 icon_ = [[package icon] retain];
5287 name_ = [[package name] retain];
5288
5289 if (IsWildcat_)
5290 description_ = [package longDescription];
5291 if (description_ == nil)
5292 description_ = [package shortDescription];
5293 if (description_ != nil)
5294 description_ = [description_ retain];
5295
5296 commercial_ = [package isCommercial];
5297
5298 package_ = [package retain];
5299
5300 NSString *label = nil;
5301 bool trusted = false;
5302
5303 if (source != nil) {
5304 label = [source label];
5305 trusted = [source trusted];
5306 } else if ([[package id] isEqualToString:@"firmware"])
5307 label = UCLocalize("APPLE");
5308 else
5309 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5310
5311 NSString *from(label);
5312
5313 NSString *section = [package simpleSection];
5314 if (section != nil && ![section isEqualToString:label]) {
5315 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5316 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5317 }
5318
5319 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5320 source_ = [from retain];
5321
5322 if (NSString *purpose = [package primaryPurpose])
5323 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5324 badge_ = [badge_ retain];
5325
5326 UIColor *color;
5327 NSString *placard;
5328
5329 if (NSString *mode = [package_ mode]) {
5330 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5331 color = RemovingColor_;
5332 //placard = @"removing";
5333 } else {
5334 color = InstallingColor_;
5335 //placard = @"installing";
5336 }
5337
5338 // XXX: the removing/installing placards are not @2x
5339 placard = nil;
5340 } else {
5341 color = [UIColor whiteColor];
5342
5343 if ([package installed] != nil)
5344 placard = @"installed";
5345 else
5346 placard = nil;
5347 }
5348
5349 [content_ setBackgroundColor:color];
5350
5351 if (placard != nil)
5352 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5353 placard_ = [placard_ retain];
5354
5355 [self setNeedsDisplay];
5356 [content_ setNeedsDisplay];
5357 }
5358
5359 - (void) drawContentRect:(CGRect)rect {
5360 bool highlighted(highlighted_);
5361 float width([self bounds].size.width);
5362
5363 #if 0
5364 CGContextRef context(UIGraphicsGetCurrentContext());
5365 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5366 CGContextFillRect(context, rect);
5367 #endif
5368
5369 if (icon_ != nil) {
5370 CGRect rect;
5371 rect.size = [icon_ size];
5372
5373 rect.size.width /= 2;
5374 rect.size.height /= 2;
5375
5376 rect.origin.x = 25 - rect.size.width / 2;
5377 rect.origin.y = 25 - rect.size.height / 2;
5378
5379 [icon_ drawInRect:rect];
5380 }
5381
5382 if (badge_ != nil) {
5383 CGRect rect;
5384 rect.size = [badge_ size];
5385
5386 rect.size.width /= 2;
5387 rect.size.height /= 2;
5388
5389 rect.origin.x = 36 - rect.size.width / 2;
5390 rect.origin.y = 36 - rect.size.height / 2;
5391
5392 [badge_ drawInRect:rect];
5393 }
5394
5395 if (highlighted)
5396 UISetColor(White_);
5397
5398 if (!highlighted)
5399 UISetColor(commercial_ ? Purple_ : Black_);
5400 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5401 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5402
5403 if (!highlighted)
5404 UISetColor(commercial_ ? Purplish_ : Gray_);
5405 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5406
5407 if (placard_ != nil)
5408 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5409 }
5410
5411 @end
5412 /* }}} */
5413 /* Section Cell {{{ */
5414 @interface SectionCell : CYTableViewCell <
5415 ContentDelegate
5416 > {
5417 NSString *basic_;
5418 NSString *section_;
5419 NSString *name_;
5420 NSString *count_;
5421 UIImage *icon_;
5422 UISwitch *switch_;
5423 BOOL editing_;
5424 }
5425
5426 - (void) setSection:(Section *)section editing:(BOOL)editing;
5427
5428 @end
5429
5430 @implementation SectionCell
5431
5432 - (void) clearSection {
5433 if (basic_ != nil) {
5434 [basic_ release];
5435 basic_ = nil;
5436 }
5437
5438 if (section_ != nil) {
5439 [section_ release];
5440 section_ = nil;
5441 }
5442
5443 if (name_ != nil) {
5444 [name_ release];
5445 name_ = nil;
5446 }
5447
5448 if (count_ != nil) {
5449 [count_ release];
5450 count_ = nil;
5451 }
5452 }
5453
5454 - (void) dealloc {
5455 [self clearSection];
5456 [icon_ release];
5457 [switch_ release];
5458 [super dealloc];
5459 }
5460
5461 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5462 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5463 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5464 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5465 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5466
5467 UIView *content([self contentView]);
5468 CGRect bounds([content bounds]);
5469
5470 content_ = [[ContentView alloc] initWithFrame:bounds];
5471 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5472 [content addSubview:content_];
5473 [content_ setBackgroundColor:[UIColor whiteColor]];
5474
5475 [content_ setDelegate:self];
5476 } return self;
5477 }
5478
5479 - (void) onSwitch:(id)sender {
5480 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5481 if (metadata == nil) {
5482 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5483 [Sections_ setObject:metadata forKey:basic_];
5484 }
5485
5486 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5487 Changed_ = true;
5488 }
5489
5490 - (void) setSection:(Section *)section editing:(BOOL)editing {
5491 if (editing != editing_) {
5492 if (editing_)
5493 [switch_ removeFromSuperview];
5494 else
5495 [self addSubview:switch_];
5496 editing_ = editing;
5497 }
5498
5499 [self clearSection];
5500
5501 if (section == nil) {
5502 name_ = [UCLocalize("ALL_PACKAGES") retain];
5503 count_ = nil;
5504 } else {
5505 basic_ = [section name];
5506 if (basic_ != nil)
5507 basic_ = [basic_ retain];
5508
5509 section_ = [section localized];
5510 if (section_ != nil)
5511 section_ = [section_ retain];
5512
5513 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5514 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5515
5516 if (editing_)
5517 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5518 }
5519
5520 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5521 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5522
5523 [content_ setNeedsDisplay];
5524 }
5525
5526 - (void) setFrame:(CGRect)frame {
5527 [super setFrame:frame];
5528
5529 CGRect rect([switch_ frame]);
5530 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5531 }
5532
5533 - (NSString *) accessibilityLabel {
5534 return name_;
5535 }
5536
5537 - (void) drawContentRect:(CGRect)rect {
5538 bool highlighted(highlighted_ && !editing_);
5539
5540 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5541
5542 if (highlighted)
5543 UISetColor(White_);
5544
5545 float width(rect.size.width);
5546 if (editing_)
5547 width -= 87;
5548
5549 if (!highlighted)
5550 UISetColor(Black_);
5551 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5552
5553 CGSize size = [count_ sizeWithFont:Font14_];
5554
5555 UISetColor(White_);
5556 if (count_ != nil)
5557 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5558 }
5559
5560 @end
5561 /* }}} */
5562
5563 /* File Table {{{ */
5564 @interface FileTable : CYViewController <
5565 UITableViewDataSource,
5566 UITableViewDelegate
5567 > {
5568 _transient Database *database_;
5569 Package *package_;
5570 NSString *name_;
5571 NSMutableArray *files_;
5572 UITableView *list_;
5573 }
5574
5575 - (id) initWithDatabase:(Database *)database;
5576 - (void) setPackage:(Package *)package;
5577
5578 @end
5579
5580 @implementation FileTable
5581
5582 - (void) dealloc {
5583 [self releaseSubviews];
5584
5585 [package_ release];
5586 [name_ release];
5587 [files_ release];
5588
5589 [super dealloc];
5590 }
5591
5592 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5593 return files_ == nil ? 0 : [files_ count];
5594 }
5595
5596 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5597 return 24.0f;
5598 }*/
5599
5600 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5601 static NSString *reuseIdentifier = @"Cell";
5602
5603 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5604 if (cell == nil) {
5605 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5606 [cell setFont:[UIFont systemFontOfSize:16]];
5607 }
5608 [cell setText:[files_ objectAtIndex:indexPath.row]];
5609 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5610
5611 return cell;
5612 }
5613
5614 - (NSURL *) navigationURL {
5615 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5616 }
5617
5618 - (void) loadView {
5619 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5620
5621 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5622 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5623 [list_ setRowHeight:24.0f];
5624 [list_ setDataSource:self];
5625 [list_ setDelegate:self];
5626 [[self view] addSubview:list_];
5627 }
5628
5629 - (void) viewDidLoad {
5630 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5631 }
5632
5633 - (void) releaseSubviews {
5634 [list_ release];
5635 list_ = nil;
5636 }
5637
5638 - (id) initWithDatabase:(Database *)database {
5639 if ((self = [super init]) != nil) {
5640 database_ = database;
5641
5642 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5643 } return self;
5644 }
5645
5646 - (void) setPackage:(Package *)package {
5647 if (package_ != nil) {
5648 [package_ autorelease];
5649 package_ = nil;
5650 }
5651
5652 if (name_ != nil) {
5653 [name_ release];
5654 name_ = nil;
5655 }
5656
5657 [files_ removeAllObjects];
5658
5659 if (package != nil) {
5660 package_ = [package retain];
5661 name_ = [[package id] retain];
5662
5663 if (NSArray *files = [package files])
5664 [files_ addObjectsFromArray:files];
5665
5666 if ([files_ count] != 0) {
5667 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5668 [files_ removeObjectAtIndex:0];
5669 [files_ sortUsingSelector:@selector(compareByPath:)];
5670
5671 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5672 [stack addObject:@"/"];
5673
5674 for (int i(0), e([files_ count]); i != e; ++i) {
5675 NSString *file = [files_ objectAtIndex:i];
5676 while (![file hasPrefix:[stack lastObject]])
5677 [stack removeLastObject];
5678 NSString *directory = [stack lastObject];
5679 [stack addObject:[file stringByAppendingString:@"/"]];
5680 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5681 ([stack count] - 2) * 3, "",
5682 [file substringFromIndex:[directory length]]
5683 ]];
5684 }
5685 }
5686 }
5687
5688 [list_ reloadData];
5689 }
5690
5691 - (void) reloadData {
5692 [super reloadData];
5693
5694 [self setPackage:[database_ packageWithName:name_]];
5695 }
5696
5697 @end
5698 /* }}} */
5699 /* Package Controller {{{ */
5700 @interface CYPackageController : CYBrowserController <
5701 UIActionSheetDelegate
5702 > {
5703 _transient Database *database_;
5704 Package *package_;
5705 NSString *name_;
5706 bool commercial_;
5707 NSMutableArray *buttons_;
5708 UIBarButtonItem *button_;
5709 }
5710
5711 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5712
5713 @end
5714
5715 @implementation CYPackageController
5716
5717 - (void) dealloc {
5718 if (package_ != nil)
5719 [package_ release];
5720 if (name_ != nil)
5721 [name_ release];
5722
5723 [buttons_ release];
5724
5725 if (button_ != nil)
5726 [button_ release];
5727
5728 [super dealloc];
5729 }
5730
5731 - (NSURL *) navigationURL {
5732 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5733 }
5734
5735 /* XXX: this is not safe at all... localization of /fail/ */
5736 - (void) _clickButtonWithName:(NSString *)name {
5737 if ([name isEqualToString:UCLocalize("CLEAR")])
5738 [delegate_ clearPackage:package_];
5739 else if ([name isEqualToString:UCLocalize("INSTALL")])
5740 [delegate_ installPackage:package_];
5741 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5742 [delegate_ installPackage:package_];
5743 else if ([name isEqualToString:UCLocalize("REMOVE")])
5744 [delegate_ removePackage:package_];
5745 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5746 [delegate_ installPackage:package_];
5747 else _assert(false);
5748 }
5749
5750 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5751 NSString *context([sheet context]);
5752
5753 if ([context isEqualToString:@"modify"]) {
5754 if (button != [sheet cancelButtonIndex]) {
5755 NSString *buttonName = [buttons_ objectAtIndex:button];
5756 [self _clickButtonWithName:buttonName];
5757 }
5758
5759 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5760 }
5761 }
5762
5763 - (bool) _allowJavaScriptPanel {
5764 return commercial_;
5765 }
5766
5767 #if !AlwaysReload
5768 - (void) _customButtonClicked {
5769 int count([buttons_ count]);
5770 if (count == 0)
5771 return;
5772
5773 if (count == 1)
5774 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5775 else {
5776 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5777 [buttons addObjectsFromArray:buttons_];
5778
5779 UIActionSheet *sheet = [[[UIActionSheet alloc]
5780 initWithTitle:nil
5781 delegate:self
5782 cancelButtonTitle:nil
5783 destructiveButtonTitle:nil
5784 otherButtonTitles:nil
5785 ] autorelease];
5786
5787 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5788 if (!IsWildcat_) {
5789 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5790 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5791 }
5792 [sheet setContext:@"modify"];
5793
5794 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5795 }
5796 }
5797
5798 // We don't want to allow non-commercial packages to do custom things to the install button,
5799 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5800 - (void) customButtonClicked {
5801 if (commercial_)
5802 [super customButtonClicked];
5803 else
5804 [self _customButtonClicked];
5805 }
5806
5807 - (void) reloadButtonClicked {
5808 // Don't reload a commerical package by tapping the loading button,
5809 // but if it's not an Install button, we should forward it on.
5810 if (![package_ uninstalled])
5811 [self _customButtonClicked];
5812 }
5813
5814 - (void) applyLoadingTitle {
5815 // Don't show "Loading" as the title. Ever.
5816 }
5817
5818 - (UIBarButtonItem *) rightButton {
5819 return button_;
5820 }
5821 #endif
5822
5823 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5824 if ((self = [super init]) != nil) {
5825 database_ = database;
5826 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5827 name_ = [[NSString alloc] initWithString:name];
5828 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5829 } return self;
5830 }
5831
5832 - (void) reloadData {
5833 if (package_ != nil)
5834 [package_ autorelease];
5835 package_ = [database_ packageWithName:name_];
5836
5837 [buttons_ removeAllObjects];
5838
5839 if (package_ != nil) {
5840 [package_ parse];
5841
5842 package_ = [package_ retain];
5843 commercial_ = [package_ isCommercial];
5844
5845 if ([package_ mode] != nil)
5846 [buttons_ addObject:UCLocalize("CLEAR")];
5847 if ([package_ source] == nil);
5848 else if ([package_ upgradableAndEssential:NO])
5849 [buttons_ addObject:UCLocalize("UPGRADE")];
5850 else if ([package_ uninstalled])
5851 [buttons_ addObject:UCLocalize("INSTALL")];
5852 else
5853 [buttons_ addObject:UCLocalize("REINSTALL")];
5854 if (![package_ uninstalled])
5855 [buttons_ addObject:UCLocalize("REMOVE")];
5856 }
5857
5858 if (button_ != nil)
5859 [button_ release];
5860
5861 NSString *title;
5862 switch ([buttons_ count]) {
5863 case 0: title = nil; break;
5864 case 1: title = [buttons_ objectAtIndex:0]; break;
5865 default: title = UCLocalize("MODIFY"); break;
5866 }
5867
5868 button_ = [[UIBarButtonItem alloc]
5869 initWithTitle:title
5870 style:UIBarButtonItemStylePlain
5871 target:self
5872 action:@selector(customButtonClicked)
5873 ];
5874
5875 [super reloadData];
5876 }
5877
5878 - (bool) isLoading {
5879 return commercial_ ? [super isLoading] : false;
5880 }
5881
5882 @end
5883 /* }}} */
5884
5885 /* Package List Controller {{{ */
5886 @interface PackageListController : CYViewController <
5887 UITableViewDataSource,
5888 UITableViewDelegate
5889 > {
5890 _transient Database *database_;
5891 unsigned era_;
5892 NSMutableArray *packages_;
5893 NSMutableArray *sections_;
5894 UITableView *list_;
5895 NSMutableArray *index_;
5896 NSMutableDictionary *indices_;
5897 NSString *title_;
5898 }
5899
5900 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5901 - (void) setDelegate:(id)delegate;
5902 - (void) resetCursor;
5903
5904 @end
5905
5906 @implementation PackageListController
5907
5908 - (void) dealloc {
5909 [packages_ release];
5910 [sections_ release];
5911 [list_ release];
5912 [index_ release];
5913 [indices_ release];
5914 [title_ release];
5915
5916 [super dealloc];
5917 }
5918
5919 - (void) deselectWithAnimation:(BOOL)animated {
5920 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5921 }
5922
5923 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5924 CGRect base = [[self view] bounds];
5925 base.size.height -= bounds.size.height;
5926 base.origin = [list_ frame].origin;
5927
5928 [UIView beginAnimations:nil context:NULL];
5929 [UIView setAnimationBeginsFromCurrentState:YES];
5930 [UIView setAnimationCurve:curve];
5931 [UIView setAnimationDuration:duration];
5932 [list_ setFrame:base];
5933 [UIView commitAnimations];
5934 }
5935
5936 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5937 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5938 }
5939
5940 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5941 [self resizeForKeyboardBounds:bounds duration:0];
5942 }
5943
5944 - (void) keyboardWillShow:(NSNotification *)notification {
5945 CGRect bounds;
5946 CGPoint center;
5947 NSTimeInterval duration;
5948 UIViewAnimationCurve curve;
5949 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5950 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
5951 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5952 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5953
5954 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);
5955 UIViewController *base = self;
5956 while ([base parentViewController] != nil)
5957 base = [base parentViewController];
5958 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5959 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5960
5961 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5962 }
5963
5964 - (void) keyboardWillHide:(NSNotification *)notification {
5965 NSTimeInterval duration;
5966 UIViewAnimationCurve curve;
5967 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5968 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5969
5970 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5971 }
5972
5973 - (void) viewWillAppear:(BOOL)animated {
5974 [super viewWillAppear:animated];
5975
5976 [self resizeForKeyboardBounds:CGRectZero];
5977 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5978 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5979 }
5980
5981 - (void) viewWillDisappear:(BOOL)animated {
5982 [super viewWillDisappear:animated];
5983
5984 [self resizeForKeyboardBounds:CGRectZero];
5985 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5986 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5987 }
5988
5989 - (void) viewDidAppear:(BOOL)animated {
5990 [super viewDidAppear:animated];
5991 [self deselectWithAnimation:animated];
5992 }
5993
5994 - (void) didSelectPackage:(Package *)package {
5995 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5996 [view setDelegate:delegate_];
5997 [[self navigationController] pushViewController:view animated:YES];
5998 }
5999
6000 #if TryIndexedCollation
6001 + (BOOL) hasIndexedCollation {
6002 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6003 }
6004 #endif
6005
6006 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6007 NSInteger count([sections_ count]);
6008 return count == 0 ? 1 : count;
6009 }
6010
6011 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6012 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6013 return nil;
6014 return [[sections_ objectAtIndex:section] name];
6015 }
6016
6017 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6018 if ([sections_ count] == 0)
6019 return 0;
6020 return [[sections_ objectAtIndex:section] count];
6021 }
6022
6023 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6024 @synchronized (database_) {
6025 if ([database_ era] != era_)
6026 return nil;
6027
6028 Section *section([sections_ objectAtIndex:[path section]]);
6029 NSInteger row([path row]);
6030 Package *package([packages_ objectAtIndex:([section row] + row)]);
6031 return [[package retain] autorelease];
6032 } }
6033
6034 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6035 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6036 if (cell == nil)
6037 cell = [[[PackageCell alloc] init] autorelease];
6038 [cell setPackage:[self packageAtIndexPath:path]];
6039 return cell;
6040 }
6041
6042 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6043 Package *package([self packageAtIndexPath:path]);
6044 package = [database_ packageWithName:[package id]];
6045 [self didSelectPackage:package];
6046 }
6047
6048 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6049 // XXX: is 20 the most optimal number here?
6050 return [packages_ count] > 20 ? index_ : nil;
6051 }
6052
6053 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6054 #if TryIndexedCollation
6055 if ([[self class] hasIndexedCollation]) {
6056 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6057 }
6058 #endif
6059
6060 return index;
6061 }
6062
6063 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6064 if ((self = [super init]) != nil) {
6065 database_ = database;
6066 title_ = [title copy];
6067 [[self navigationItem] setTitle:title_];
6068
6069 #if TryIndexedCollation
6070 if ([[self class] hasIndexedCollation])
6071 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6072 else
6073 #endif
6074 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6075
6076 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6077
6078 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6079 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6080
6081 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6082 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6083 [list_ setRowHeight:73];
6084 [[self view] addSubview:list_];
6085
6086 [list_ setDataSource:self];
6087 [list_ setDelegate:self];
6088 } return self;
6089 }
6090
6091 - (void) setDelegate:(id)delegate {
6092 delegate_ = delegate;
6093 }
6094
6095 - (bool) hasPackage:(Package *)package {
6096 return true;
6097 }
6098
6099 - (void) reloadData {
6100 [super reloadData];
6101
6102 era_ = [database_ era];
6103 NSArray *packages = [database_ packages];
6104
6105 [packages_ removeAllObjects];
6106 [sections_ removeAllObjects];
6107
6108 _profile(PackageTable$reloadData$Filter)
6109 for (Package *package in packages)
6110 if ([self hasPackage:package])
6111 [packages_ addObject:package];
6112 _end
6113
6114 [indices_ removeAllObjects];
6115
6116 Section *section = nil;
6117
6118 #if TryIndexedCollation
6119 if ([[self class] hasIndexedCollation]) {
6120 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6121 NSArray *titles = [collation sectionIndexTitles];
6122 int secidx = -1;
6123
6124 _profile(PackageTable$reloadData$Section)
6125 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6126 Package *package;
6127 int index;
6128
6129 _profile(PackageTable$reloadData$Section$Package)
6130 package = [packages_ objectAtIndex:offset];
6131 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6132 _end
6133
6134 while (secidx < index) {
6135 secidx += 1;
6136
6137 _profile(PackageTable$reloadData$Section$Allocate)
6138 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6139 _end
6140
6141 _profile(PackageTable$reloadData$Section$Add)
6142 [sections_ addObject:section];
6143 _end
6144 }
6145
6146 [section addToCount];
6147 }
6148 _end
6149 } else
6150 #endif
6151 {
6152 [index_ removeAllObjects];
6153
6154 _profile(PackageTable$reloadData$Section)
6155 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6156 Package *package;
6157 unichar index;
6158
6159 _profile(PackageTable$reloadData$Section$Package)
6160 package = [packages_ objectAtIndex:offset];
6161 index = [package index];
6162 _end
6163
6164 if (section == nil || [section index] != index) {
6165 _profile(PackageTable$reloadData$Section$Allocate)
6166 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6167 _end
6168
6169 [index_ addObject:[section name]];
6170 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6171
6172 _profile(PackageTable$reloadData$Section$Add)
6173 [sections_ addObject:section];
6174 _end
6175 }
6176
6177 [section addToCount];
6178 }
6179 _end
6180 }
6181
6182 _profile(PackageTable$reloadData$List)
6183 [list_ reloadData];
6184 _end
6185 }
6186
6187 - (void) resetCursor {
6188 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6189 }
6190
6191 @end
6192 /* }}} */
6193 /* Filtered Package List Controller {{{ */
6194 @interface FilteredPackageListController : PackageListController {
6195 SEL filter_;
6196 IMP imp_;
6197 id object_;
6198 }
6199
6200 - (void) setObject:(id)object;
6201 - (void) setObject:(id)object forFilter:(SEL)filter;
6202
6203 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6204
6205 @end
6206
6207 @implementation FilteredPackageListController
6208
6209 - (void) dealloc {
6210 if (object_ != nil)
6211 [object_ release];
6212 [super dealloc];
6213 }
6214
6215 - (void) setFilter:(SEL)filter {
6216 filter_ = filter;
6217
6218 /* XXX: this is an unsafe optimization of doomy hell */
6219 Method method(class_getInstanceMethod([Package class], filter));
6220 _assert(method != NULL);
6221 imp_ = method_getImplementation(method);
6222 _assert(imp_ != NULL);
6223 }
6224
6225 - (void) setObject:(id)object {
6226 if (object_ != nil)
6227 [object_ release];
6228 if (object == nil)
6229 object_ = nil;
6230 else
6231 object_ = [object retain];
6232 }
6233
6234 - (void) setObject:(id)object forFilter:(SEL)filter {
6235 [self setFilter:filter];
6236 [self setObject:object];
6237 }
6238
6239 - (bool) hasPackage:(Package *)package {
6240 _profile(FilteredPackageTable$hasPackage)
6241 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6242 _end
6243 }
6244
6245 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6246 if ((self = [super initWithDatabase:database title:title]) != nil) {
6247 [self setFilter:filter];
6248 [self setObject:object];
6249 } return self;
6250 }
6251
6252 @end
6253 /* }}} */
6254
6255 /* Home Controller {{{ */
6256 @interface HomeController : CYBrowserController {
6257 }
6258
6259 @end
6260
6261 @implementation HomeController
6262
6263 + (BOOL) shouldHideNavigationBar {
6264 return NO;
6265 }
6266
6267 - (NSURL *) navigationURL {
6268 return [NSURL URLWithString:@"cydia://home"];
6269 }
6270
6271 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6272 [super _setMoreHeaders:request];
6273
6274 if (ChipID_ != nil)
6275 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6276 if (UniqueID_ != nil)
6277 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6278 if (PLMN_ != nil)
6279 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6280 }
6281
6282 - (void) aboutButtonClicked {
6283 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6284
6285 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6286 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6287 [alert setCancelButtonIndex:0];
6288
6289 [alert setMessage:
6290 @"Copyright (C) 2008-2011\n"
6291 "Jay Freeman (saurik)\n"
6292 "saurik@saurik.com\n"
6293 "http://www.saurik.com/"
6294 ];
6295
6296 [alert show];
6297 }
6298
6299 - (void) viewWillDisappear:(BOOL)animated {
6300 [super viewWillDisappear:animated];
6301
6302 if ([[self class] shouldHideNavigationBar])
6303 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6304 }
6305
6306 - (void) viewWillAppear:(BOOL)animated {
6307 if (![self hasLoaded])
6308 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6309
6310 [super viewWillAppear:animated];
6311
6312 if ([[self class] shouldHideNavigationBar])
6313 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6314 }
6315
6316 - (void) viewDidLoad {
6317 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6318 initWithTitle:UCLocalize("ABOUT")
6319 style:UIBarButtonItemStylePlain
6320 target:self
6321 action:@selector(aboutButtonClicked)
6322 ] autorelease]];
6323 }
6324
6325 @end
6326 /* }}} */
6327 /* Manage Controller {{{ */
6328 @interface ManageController : CYBrowserController {
6329 }
6330
6331 - (void) queueStatusDidChange;
6332
6333 @end
6334
6335 @implementation ManageController
6336
6337 - (NSURL *) navigationURL {
6338 return [NSURL URLWithString:@"cydia://manage"];
6339 }
6340
6341 - (void) viewWillAppear:(BOOL)animated {
6342 if (![self hasLoaded])
6343 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6344
6345 [super viewWillAppear:animated];
6346 }
6347
6348 - (void) viewDidLoad {
6349 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6350 initWithTitle:UCLocalize("SETTINGS")
6351 style:UIBarButtonItemStylePlain
6352 target:self
6353 action:@selector(settingsButtonClicked)
6354 ] autorelease]];
6355
6356 [self queueStatusDidChange];
6357 }
6358
6359 - (void) settingsButtonClicked {
6360 [delegate_ showSettings];
6361 }
6362
6363 #if !AlwaysReload
6364 - (void) queueButtonClicked {
6365 [delegate_ queue];
6366 }
6367
6368 - (void) applyLoadingTitle {
6369 // Disable "Loading" title.
6370 }
6371
6372 - (void) applyRightButton {
6373 // Disable right button.
6374 }
6375 #endif
6376
6377 - (void) queueStatusDidChange {
6378 #if !AlwaysReload
6379 if (!IsWildcat_ && Queuing_) {
6380 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6381 initWithTitle:UCLocalize("QUEUE")
6382 style:UIBarButtonItemStyleDone
6383 target:self
6384 action:@selector(queueButtonClicked)
6385 ] autorelease]];
6386 } else {
6387 [[self navigationItem] setRightBarButtonItem:nil];
6388 }
6389 #endif
6390 }
6391
6392 - (bool) isLoading {
6393 // Never show as loading.
6394 return false;
6395 }
6396
6397 @end
6398 /* }}} */
6399
6400 /* Refresh Bar {{{ */
6401 @interface RefreshBar : UINavigationBar {
6402 UIProgressIndicator *indicator_;
6403 UITextLabel *prompt_;
6404 UIProgressBar *progress_;
6405 UINavigationButton *cancel_;
6406 }
6407
6408 @end
6409
6410 @implementation RefreshBar
6411
6412 - (void) dealloc {
6413 [indicator_ release];
6414 [prompt_ release];
6415 [progress_ release];
6416 [cancel_ release];
6417 [super dealloc];
6418 }
6419
6420 - (void) positionViews {
6421 CGRect frame = [cancel_ frame];
6422 frame.size = [cancel_ sizeThatFits:frame.size];
6423 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6424 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6425 [cancel_ setFrame:frame];
6426
6427 CGSize prgsize = {75, 100};
6428 CGRect prgrect = {{
6429 [self frame].size.width - prgsize.width - 10,
6430 ([self frame].size.height - prgsize.height) / 2
6431 } , prgsize};
6432 [progress_ setFrame:prgrect];
6433
6434 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6435 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6436 CGRect indrect = {{indoffset, indoffset}, indsize};
6437 [indicator_ setFrame:indrect];
6438
6439 CGSize prmsize = {215, indsize.height + 4};
6440 CGRect prmrect = {{
6441 indoffset * 2 + indsize.width,
6442 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6443 }, prmsize};
6444 [prompt_ setFrame:prmrect];
6445 }
6446
6447 - (void) setFrame:(CGRect)frame {
6448 [super setFrame:frame];
6449 [self positionViews];
6450 }
6451
6452 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6453 if ((self = [super initWithFrame:frame]) != nil) {
6454 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6455
6456 [self setBarStyle:UIBarStyleBlack];
6457
6458 UIBarStyle barstyle([self _barStyle:NO]);
6459 bool ugly(barstyle == UIBarStyleDefault);
6460
6461 UIProgressIndicatorStyle style = ugly ?
6462 UIProgressIndicatorStyleMediumBrown :
6463 UIProgressIndicatorStyleMediumWhite;
6464
6465 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6466 [indicator_ setStyle:style];
6467 [indicator_ startAnimation];
6468 [self addSubview:indicator_];
6469
6470 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6471 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6472 [prompt_ setBackgroundColor:[UIColor clearColor]];
6473 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6474 [self addSubview:prompt_];
6475
6476 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6477 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6478 [progress_ setStyle:0];
6479 [self addSubview:progress_];
6480
6481 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6482 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6483 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6484 [cancel_ setBarStyle:barstyle];
6485
6486 [self positionViews];
6487 } return self;
6488 }
6489
6490 - (void) cancel {
6491 [cancel_ removeFromSuperview];
6492 }
6493
6494 - (void) start {
6495 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6496 [progress_ setProgress:0];
6497 [self addSubview:cancel_];
6498 }
6499
6500 - (void) stop {
6501 [cancel_ removeFromSuperview];
6502 }
6503
6504 - (void) setPrompt:(NSString *)prompt {
6505 [prompt_ setText:prompt];
6506 }
6507
6508 - (void) setProgress:(float)progress {
6509 [progress_ setProgress:progress];
6510 }
6511
6512 @end
6513 /* }}} */
6514
6515 @class CYNavigationController;
6516
6517 /* Cydia Tab Bar Controller {{{ */
6518 @interface CYTabBarController : UITabBarController <
6519 UITabBarControllerDelegate,
6520 ProgressDelegate
6521 > {
6522 _transient Database *database_;
6523 RefreshBar *refreshbar_;
6524
6525 bool dropped_;
6526 bool updating_;
6527 // XXX: ok, "updatedelegate_"?...
6528 _transient NSObject<CydiaDelegate> *updatedelegate_;
6529
6530 id root_;
6531 UIViewController *remembered_;
6532 _transient UIViewController *transient_;
6533 }
6534
6535 - (NSArray *) navigationURLCollection;
6536 - (void) dropBar:(BOOL)animated;
6537 - (void) beginUpdate;
6538 - (void) raiseBar:(BOOL)animated;
6539 - (BOOL) updating;
6540
6541 @end
6542
6543 @implementation CYTabBarController
6544
6545 - (void) setUnselectedViewController:(UIViewController *)transient {
6546 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6547 if (transient != nil) {
6548 if (transient_ == nil)
6549 remembered_ = [[controllers objectAtIndex:0] retain];
6550 transient_ = transient;
6551 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6552 [controllers replaceObjectAtIndex:0 withObject:transient_];
6553 [self setSelectedIndex:0];
6554 [self setViewControllers:controllers];
6555 [self concealTabBarSelection];
6556 } else if (remembered_ != nil) {
6557 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6558 transient_ = transient;
6559 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6560 [remembered_ release];
6561 remembered_ = nil;
6562 [self setViewControllers:controllers];
6563 [self revealTabBarSelection];
6564 }
6565 }
6566
6567 - (UIViewController *) unselectedViewController {
6568 return transient_;
6569 }
6570
6571 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6572 if ([self unselectedViewController])
6573 [self setUnselectedViewController:nil];
6574 }
6575
6576 - (NSArray *) navigationURLCollection {
6577 NSMutableArray *items([NSMutableArray array]);
6578
6579 // XXX: Should this deal with transient view controllers?
6580 for (id navigation in [self viewControllers]) {
6581 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6582 if (stack != nil)
6583 [items addObject:stack];
6584 }
6585
6586 return items;
6587 }
6588
6589 - (void) reloadData {
6590 for (CYViewController *controller in [self viewControllers])
6591 [controller reloadData];
6592
6593 [(CYNavigationController *)[self unselectedViewController] reloadData];
6594 }
6595
6596 - (void) dealloc {
6597 [refreshbar_ release];
6598 [[NSNotificationCenter defaultCenter] removeObserver:self];
6599
6600 [super dealloc];
6601 }
6602
6603 - (id) initWithDatabase:(Database *)database {
6604 if ((self = [super init]) != nil) {
6605 database_ = database;
6606 [self setDelegate:self];
6607
6608 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6609 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6610
6611 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6612 } return self;
6613 }
6614
6615 - (void) setUpdate:(NSDate *)date {
6616 [self beginUpdate];
6617 }
6618
6619 - (void) beginUpdate {
6620 [refreshbar_ start];
6621 [self dropBar:YES];
6622
6623 [updatedelegate_ retainNetworkActivityIndicator];
6624 updating_ = true;
6625
6626 [NSThread
6627 detachNewThreadSelector:@selector(performUpdate)
6628 toTarget:self
6629 withObject:nil
6630 ];
6631 }
6632
6633 - (void) performUpdate { _pooled
6634 Status status;
6635 status.setDelegate(self);
6636 [database_ updateWithStatus:status];
6637
6638 [self
6639 performSelectorOnMainThread:@selector(completeUpdate)
6640 withObject:nil
6641 waitUntilDone:NO
6642 ];
6643 }
6644
6645 - (void) stopUpdateWithSelector:(SEL)selector {
6646 updating_ = false;
6647 [updatedelegate_ releaseNetworkActivityIndicator];
6648
6649 [self raiseBar:YES];
6650 [refreshbar_ stop];
6651
6652 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6653 }
6654
6655 - (void) completeUpdate {
6656 if (!updating_)
6657 return;
6658 [self stopUpdateWithSelector:@selector(reloadData)];
6659 }
6660
6661 - (void) cancelUpdate {
6662 [self stopUpdateWithSelector:@selector(updateData)];
6663 }
6664
6665 - (void) cancelPressed {
6666 [self cancelUpdate];
6667 }
6668
6669 - (BOOL) updating {
6670 return updating_;
6671 }
6672
6673 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6674 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6675 }
6676
6677 - (void) startProgress {
6678 }
6679
6680 - (bool) isProgressCancelled {
6681 return !updating_;
6682 }
6683
6684 - (void) setProgressTitle:(NSString *)title {
6685 [refreshbar_ setPrompt:title];
6686 }
6687
6688 - (void) setProgressPercent:(NSNumber *)percent {
6689 [refreshbar_ setProgress:[percent floatValue]];
6690 }
6691
6692 - (void) addProgressOutput:(NSString *)output {
6693 }
6694
6695 - (void) setUpdateDelegate:(id)delegate {
6696 updatedelegate_ = delegate;
6697 }
6698
6699 - (CGFloat) statusBarHeight {
6700 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6701 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6702 } else {
6703 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6704 }
6705 }
6706
6707 - (UIView *) transitionView {
6708 if ([self respondsToSelector:@selector(_transitionView)])
6709 return [self _transitionView];
6710 else
6711 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6712 }
6713
6714 - (void) dropBar:(BOOL)animated {
6715 if (dropped_)
6716 return;
6717 dropped_ = true;
6718
6719 UIView *transition([self transitionView]);
6720 [[self view] addSubview:refreshbar_];
6721
6722 CGRect barframe([refreshbar_ frame]);
6723
6724 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6725 barframe.origin.y = [self statusBarHeight];
6726 else
6727 barframe.origin.y = 0;
6728
6729 [refreshbar_ setFrame:barframe];
6730
6731 if (animated)
6732 [UIView beginAnimations:nil context:NULL];
6733
6734 CGRect viewframe = [transition frame];
6735 viewframe.origin.y += barframe.size.height;
6736 viewframe.size.height -= barframe.size.height;
6737 [transition setFrame:viewframe];
6738
6739 if (animated)
6740 [UIView commitAnimations];
6741
6742 // Ensure bar has the proper width for our view, it might have changed
6743 barframe.size.width = viewframe.size.width;
6744 [refreshbar_ setFrame:barframe];
6745
6746 // XXX: fix Apple's layout bug
6747 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6748 }
6749
6750 - (void) raiseBar:(BOOL)animated {
6751 if (!dropped_)
6752 return;
6753 dropped_ = false;
6754
6755 UIView *transition([self transitionView]);
6756 [refreshbar_ removeFromSuperview];
6757
6758 CGRect barframe([refreshbar_ frame]);
6759
6760 if (animated)
6761 [UIView beginAnimations:nil context:NULL];
6762
6763 CGRect viewframe = [transition frame];
6764 viewframe.origin.y -= barframe.size.height;
6765 viewframe.size.height += barframe.size.height;
6766 [transition setFrame:viewframe];
6767
6768 if (animated)
6769 [UIView commitAnimations];
6770
6771 // XXX: fix Apple's layout bug
6772 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6773 }
6774
6775 #if 0
6776 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6777 // XXX: fix Apple's layout bug
6778 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6779 }
6780 #endif
6781
6782 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6783 bool dropped(dropped_);
6784
6785 if (dropped)
6786 [self raiseBar:NO];
6787
6788 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6789
6790 if (dropped)
6791 [self dropBar:NO];
6792
6793 // XXX: fix Apple's layout bug
6794 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6795 }
6796
6797 - (void) statusBarFrameChanged:(NSNotification *)notification {
6798 if (dropped_) {
6799 [self raiseBar:NO];
6800 [self dropBar:NO];
6801 }
6802 }
6803
6804 @end
6805 /* }}} */
6806 /* Cydia Navigation Controller {{{ */
6807 @interface CYNavigationController : UINavigationController {
6808 _transient Database *database_;
6809 _transient id<UINavigationControllerDelegate> delegate_;
6810 }
6811
6812 - (NSArray *) navigationURLCollection;
6813 - (id) initWithDatabase:(Database *)database;
6814 - (void) reloadData;
6815
6816 @end
6817
6818
6819 @implementation CYNavigationController
6820
6821 - (NSArray *) navigationURLCollection {
6822 NSMutableArray *stack([NSMutableArray array]);
6823
6824 for (CYViewController *controller in [self viewControllers]) {
6825 NSString *url = [[controller navigationURL] absoluteString];
6826 if (url != nil)
6827 [stack addObject:url];
6828 }
6829
6830 return stack;
6831 }
6832
6833 - (void) reloadData {
6834 for (CYViewController *page in [self viewControllers]) {
6835 // Only reload controllers that have already loaded.
6836 // This prevents a page from accidentally loading too
6837 // early if it hasn't been shown on the screen yet.
6838 if ([page hasLoaded])
6839 [page reloadData];
6840 }
6841 }
6842
6843 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6844 delegate_ = delegate;
6845 }
6846
6847 - (id) initWithDatabase:(Database *)database {
6848 if ((self = [super init]) != nil) {
6849 database_ = database;
6850 } return self;
6851 }
6852
6853 @end
6854 /* }}} */
6855
6856 /* Cydia:// Protocol {{{ */
6857 @interface CydiaURLProtocol : NSURLProtocol {
6858 }
6859
6860 @end
6861
6862 @implementation CydiaURLProtocol
6863
6864 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6865 NSURL *url([request URL]);
6866 if (url == nil)
6867 return NO;
6868 NSString *scheme([[url scheme] lowercaseString]);
6869 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6870 return NO;
6871 return YES;
6872 }
6873
6874 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6875 return request;
6876 }
6877
6878 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6879 id<NSURLProtocolClient> client([self client]);
6880 if (icon == nil)
6881 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6882 else {
6883 NSData *data(UIImagePNGRepresentation(icon));
6884
6885 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6886 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6887 [client URLProtocol:self didLoadData:data];
6888 [client URLProtocolDidFinishLoading:self];
6889 }
6890 }
6891
6892 - (void) startLoading {
6893 id<NSURLProtocolClient> client([self client]);
6894 NSURLRequest *request([self request]);
6895
6896 NSURL *url([request URL]);
6897 NSString *href([url absoluteString]);
6898
6899 NSString *path([href substringFromIndex:8]);
6900 NSRange slash([path rangeOfString:@"/"]);
6901
6902 NSString *command;
6903 if (slash.location == NSNotFound) {
6904 command = path;
6905 path = nil;
6906 } else {
6907 command = [path substringToIndex:slash.location];
6908 path = [path substringFromIndex:(slash.location + 1)];
6909 }
6910
6911 Database *database([Database sharedInstance]);
6912
6913 if ([command isEqualToString:@"package-icon"]) {
6914 if (path == nil)
6915 goto fail;
6916 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6917 Package *package([database packageWithName:path]);
6918 if (package == nil)
6919 goto fail;
6920 UIImage *icon([package icon]);
6921 [self _returnPNGWithImage:icon forRequest:request];
6922 } else if ([command isEqualToString:@"source-icon"]) {
6923 if (path == nil)
6924 goto fail;
6925 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6926 NSString *source(Simplify(path));
6927 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6928 if (icon == nil)
6929 icon = [UIImage applicationImageNamed:@"unknown.png"];
6930 [self _returnPNGWithImage:icon forRequest:request];
6931 } else if ([command isEqualToString:@"uikit-image"]) {
6932 if (path == nil)
6933 goto fail;
6934 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6935 UIImage *icon(_UIImageWithName(path));
6936 [self _returnPNGWithImage:icon forRequest:request];
6937 } else if ([command isEqualToString:@"section-icon"]) {
6938 if (path == nil)
6939 goto fail;
6940 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6941 NSString *section(Simplify(path));
6942 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6943 if (icon == nil)
6944 icon = [UIImage applicationImageNamed:@"unknown.png"];
6945 [self _returnPNGWithImage:icon forRequest:request];
6946 } else fail: {
6947 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6948 }
6949 }
6950
6951 - (void) stopLoading {
6952 }
6953
6954 @end
6955 /* }}} */
6956
6957 /* Section Controller {{{ */
6958 @interface SectionController : FilteredPackageListController {
6959 NSString *section_;
6960 }
6961
6962 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6963
6964 @end
6965
6966 @implementation SectionController
6967
6968 - (NSURL *) navigationURL {
6969 NSString *name = section_;
6970 if (name == nil)
6971 name = @"all";
6972
6973 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6974 }
6975
6976 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6977 NSString *title;
6978 if (name == nil)
6979 title = UCLocalize("ALL_PACKAGES");
6980 else if (![name isEqual:@""])
6981 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6982 else
6983 title = UCLocalize("NO_SECTION");
6984
6985 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6986 section_ = name;
6987 } return self;
6988 }
6989
6990 @end
6991 /* }}} */
6992 /* Sections Controller {{{ */
6993 @interface SectionsController : CYViewController <
6994 UITableViewDataSource,
6995 UITableViewDelegate
6996 > {
6997 _transient Database *database_;
6998 NSMutableArray *sections_;
6999 NSMutableArray *filtered_;
7000 UITableView *list_;
7001 BOOL editing_;
7002 }
7003
7004 - (id) initWithDatabase:(Database *)database;
7005 - (void) editButtonClicked;
7006
7007 @end
7008
7009 @implementation SectionsController
7010
7011 - (void) dealloc {
7012 [self releaseSubviews];
7013 [sections_ release];
7014 [filtered_ release];
7015
7016 [super dealloc];
7017 }
7018
7019 - (NSURL *) navigationURL {
7020 return [NSURL URLWithString:@"cydia://sections"];
7021 }
7022
7023 - (void) updateNavigationItem {
7024 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7025 if ([sections_ count] == 0) {
7026 [[self navigationItem] setRightBarButtonItem:nil];
7027 } else {
7028 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7029 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7030 target:self
7031 action:@selector(editButtonClicked)
7032 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7033 }
7034 }
7035
7036 - (BOOL) isEditing {
7037 return editing_;
7038 }
7039
7040 - (void) setEditing:(BOOL)editing {
7041 if ((editing_ = editing))
7042 [list_ reloadData];
7043 else
7044 [delegate_ updateData];
7045
7046 [self updateNavigationItem];
7047 }
7048
7049 - (void) viewDidAppear:(BOOL)animated {
7050 [super viewDidAppear:animated];
7051 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7052 }
7053
7054 - (void) viewWillDisappear:(BOOL)animated {
7055 [super viewWillDisappear:animated];
7056 if (editing_) [self setEditing:NO];
7057 }
7058
7059 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7060 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7061 return section;
7062 }
7063
7064 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7065 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7066 }
7067
7068 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7069 return 45.0f;
7070 }*/
7071
7072 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7073 static NSString *reuseIdentifier = @"SectionCell";
7074
7075 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7076 if (cell == nil)
7077 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7078
7079 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7080
7081 return cell;
7082 }
7083
7084 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7085 if (editing_)
7086 return;
7087
7088 Section *section = [self sectionAtIndexPath:indexPath];
7089
7090 SectionController *controller = [[[SectionController alloc]
7091 initWithDatabase:database_
7092 section:[section name]
7093 ] autorelease];
7094 [controller setDelegate:delegate_];
7095
7096 [[self navigationController] pushViewController:controller animated:YES];
7097 }
7098
7099 - (void) loadView {
7100 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7101
7102 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7103 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7104 [list_ setRowHeight:45.0f];
7105 [list_ setDataSource:self];
7106 [list_ setDelegate:self];
7107 [[self view] addSubview:list_];
7108 }
7109
7110 - (void) viewDidLoad {
7111 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7112 }
7113
7114 - (void) releaseSubviews {
7115 [list_ release];
7116 list_ = nil;
7117 }
7118
7119 - (id) initWithDatabase:(Database *)database {
7120 if ((self = [super init]) != nil) {
7121 database_ = database;
7122
7123 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7124 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7125 } return self;
7126 }
7127
7128 - (void) reloadData {
7129 [super reloadData];
7130
7131 NSArray *packages = [database_ packages];
7132
7133 [sections_ removeAllObjects];
7134 [filtered_ removeAllObjects];
7135
7136 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7137
7138 _trace();
7139 for (Package *package in packages) {
7140 NSString *name([package section]);
7141 NSString *key(name == nil ? @"" : name);
7142
7143 Section *section;
7144
7145 _profile(SectionsView$reloadData$Section)
7146 section = [sections objectForKey:key];
7147 if (section == nil) {
7148 _profile(SectionsView$reloadData$Section$Allocate)
7149 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7150 [sections setObject:section forKey:key];
7151 _end
7152 }
7153 _end
7154
7155 [section addToCount];
7156
7157 _profile(SectionsView$reloadData$Filter)
7158 if (![package valid] || ![package visible])
7159 continue;
7160 _end
7161
7162 [section addToRow];
7163 }
7164 _trace();
7165
7166 [sections_ addObjectsFromArray:[sections allValues]];
7167
7168 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7169
7170 for (Section *section in sections_) {
7171 size_t count([section row]);
7172 if (count == 0)
7173 continue;
7174
7175 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7176 [section setCount:count];
7177 [filtered_ addObject:section];
7178 }
7179
7180 [self updateNavigationItem];
7181 [list_ reloadData];
7182 _trace();
7183 }
7184
7185 - (void) editButtonClicked {
7186 [self setEditing:(!editing_)];
7187 }
7188
7189 @end
7190 /* }}} */
7191
7192 /* Changes Controller {{{ */
7193 @interface ChangesController : CYViewController <
7194 UITableViewDataSource,
7195 UITableViewDelegate
7196 > {
7197 _transient Database *database_;
7198 unsigned era_;
7199 CFMutableArrayRef packages_;
7200 NSMutableArray *sections_;
7201 UITableView *list_;
7202 unsigned upgrades_;
7203 BOOL hasSentFirstLoad_;
7204 }
7205
7206 - (id) initWithDatabase:(Database *)database;
7207
7208 @end
7209
7210 @implementation ChangesController
7211
7212 - (void) dealloc {
7213 [self releaseSubviews];
7214 CFRelease(packages_);
7215 [sections_ release];
7216
7217 [super dealloc];
7218 }
7219
7220 - (NSURL *) navigationURL {
7221 return [NSURL URLWithString:@"cydia://changes"];
7222 }
7223
7224 - (void) viewWillAppear:(BOOL)animated {
7225 // Loads after it appears, so don't load beforehand.
7226 loaded_ = YES;
7227 [super viewWillAppear:animated];
7228 }
7229
7230 - (void) viewDidAppear:(BOOL)animated {
7231 [super viewDidAppear:animated];
7232
7233 if (!hasSentFirstLoad_) {
7234 hasSentFirstLoad_ = YES;
7235 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7236 } else {
7237 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7238 }
7239 }
7240
7241 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7242 NSInteger count([sections_ count]);
7243 return count == 0 ? 1 : count;
7244 }
7245
7246 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7247 if ([sections_ count] == 0)
7248 return nil;
7249 return [[sections_ objectAtIndex:section] name];
7250 }
7251
7252 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7253 if ([sections_ count] == 0)
7254 return 0;
7255 return [[sections_ objectAtIndex:section] count];
7256 }
7257
7258 - (Package *) packageAtIndex:(NSUInteger)index {
7259 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7260 }
7261
7262 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7263 @synchronized (database_) {
7264 if ([database_ era] != era_)
7265 return nil;
7266
7267 NSUInteger sectionIndex([path section]);
7268 if (sectionIndex >= [sections_ count])
7269 return nil;
7270 Section *section([sections_ objectAtIndex:sectionIndex]);
7271 NSInteger row([path row]);
7272 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7273 } }
7274
7275 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7276 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7277 if (cell == nil)
7278 cell = [[[PackageCell alloc] init] autorelease];
7279 [cell setPackage:[self packageAtIndexPath:path]];
7280 return cell;
7281 }
7282
7283 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7284 Package *package([self packageAtIndexPath:path]);
7285 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7286 [view setDelegate:delegate_];
7287 [[self navigationController] pushViewController:view animated:YES];
7288 return path;
7289 }
7290
7291 - (void) refreshButtonClicked {
7292 [delegate_ beginUpdate];
7293 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7294 }
7295
7296 - (void) upgradeButtonClicked {
7297 [delegate_ distUpgrade];
7298 }
7299
7300 - (void) loadView {
7301 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7302
7303 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7304 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7305 [list_ setRowHeight:73];
7306 [list_ setDataSource:self];
7307 [list_ setDelegate:self];
7308 [[self view] addSubview:list_];
7309 }
7310
7311 - (void) viewDidLoad {
7312 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7313 }
7314
7315 - (void) releaseSubviews {
7316 [list_ release];
7317 list_ = nil;
7318 }
7319
7320 - (id) initWithDatabase:(Database *)database {
7321 if ((self = [super init]) != nil) {
7322 database_ = database;
7323
7324 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7325 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7326 } return self;
7327 }
7328
7329 // this mostly works because reloadData (below) is @synchronized (database_)
7330 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7331 - (void) _reloadPackages:(NSArray *)packages {
7332 CFRelease(packages_);
7333 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7334
7335 _trace();
7336 _profile(ChangesController$_reloadPackages$Filter)
7337 for (Package *package in packages)
7338 if ([package upgradableAndEssential:YES] || [package visible])
7339 CFArrayAppendValue(packages_, package);
7340 _end
7341 _trace();
7342 _profile(ChangesController$_reloadPackages$radixSort)
7343 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7344 _end
7345 _trace();
7346 }
7347
7348 - (void) reloadData {
7349 @synchronized (database_) {
7350 era_ = [database_ era];
7351 NSArray *packages = [database_ packages];
7352
7353 [sections_ removeAllObjects];
7354
7355 #if 1
7356 UIProgressHUD *hud([delegate_ addProgressHUD]);
7357 [hud setText:UCLocalize("LOADING")];
7358 //NSLog(@"HUD:%@::%@", delegate_, hud);
7359 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7360 [delegate_ removeProgressHUD:hud];
7361 #else
7362 [self _reloadPackages:packages];
7363 #endif
7364
7365 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7366 Section *ignored = nil;
7367 Section *section = nil;
7368 time_t last = 0;
7369
7370 upgrades_ = 0;
7371 bool unseens = false;
7372
7373 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7374
7375 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7376 Package *package = [self packageAtIndex:offset];
7377
7378 BOOL uae = [package upgradableAndEssential:YES];
7379
7380 if (!uae) {
7381 unseens = true;
7382 time_t seen([package seen]);
7383
7384 if (section == nil || last != seen) {
7385 last = seen;
7386
7387 NSString *name;
7388 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7389 [name autorelease];
7390
7391 _profile(ChangesController$reloadData$Allocate)
7392 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7393 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7394 [sections_ addObject:section];
7395 _end
7396 }
7397
7398 [section addToCount];
7399 } else if ([package ignored]) {
7400 if (ignored == nil) {
7401 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7402 }
7403 [ignored addToCount];
7404 } else {
7405 ++upgrades_;
7406 [upgradable addToCount];
7407 }
7408 }
7409 _trace();
7410
7411 CFRelease(formatter);
7412
7413 if (unseens) {
7414 Section *last = [sections_ lastObject];
7415 size_t count = [last count];
7416 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7417 [sections_ removeLastObject];
7418 }
7419
7420 if ([ignored count] != 0)
7421 [sections_ insertObject:ignored atIndex:0];
7422 if (upgrades_ != 0)
7423 [sections_ insertObject:upgradable atIndex:0];
7424
7425 [list_ reloadData];
7426
7427 if (upgrades_ > 0)
7428 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7429 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7430 style:UIBarButtonItemStylePlain
7431 target:self
7432 action:@selector(upgradeButtonClicked)
7433 ] autorelease]];
7434
7435 if (![delegate_ updating])
7436 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7437 initWithTitle:UCLocalize("REFRESH")
7438 style:UIBarButtonItemStylePlain
7439 target:self
7440 action:@selector(refreshButtonClicked)
7441 ] autorelease]];
7442
7443 PrintTimes();
7444 } }
7445
7446 @end
7447 /* }}} */
7448 /* Search Controller {{{ */
7449 @interface SearchController : FilteredPackageListController <
7450 UISearchBarDelegate
7451 > {
7452 UISearchBar *search_;
7453 BOOL searchloaded_;
7454 }
7455
7456 - (id) initWithDatabase:(Database *)database;
7457 - (void) setSearchTerm:(NSString *)term;
7458 - (void) reloadData;
7459
7460 @end
7461
7462 @implementation SearchController
7463
7464 - (void) dealloc {
7465 [search_ release];
7466 [super dealloc];
7467 }
7468
7469 - (NSURL *) navigationURL {
7470 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7471 return [NSURL URLWithString:@"cydia://search"];
7472 else
7473 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7474 }
7475
7476 - (void) setSearchTerm:(NSString *)searchTerm {
7477 [search_ setText:searchTerm];
7478 [self reloadData];
7479 }
7480
7481 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7482 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7483 [search_ resignFirstResponder];
7484 [self reloadData];
7485 }
7486
7487 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7488 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7489 [self reloadData];
7490 }
7491
7492 - (id) initWithDatabase:(Database *)database {
7493 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7494 search_ = [[UISearchBar alloc] init];
7495 } return self;
7496 }
7497
7498 - (void) viewDidAppear:(BOOL)animated {
7499 [super viewDidAppear:animated];
7500
7501 if (!searchloaded_) {
7502 searchloaded_ = YES;
7503 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7504 [search_ layoutSubviews];
7505 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7506
7507 UITextField *textField;
7508 if ([search_ respondsToSelector:@selector(searchField)])
7509 textField = [search_ searchField];
7510 else
7511 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7512
7513 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7514 [search_ setDelegate:self];
7515 [textField setEnablesReturnKeyAutomatically:NO];
7516 [[self navigationItem] setTitleView:textField];
7517 }
7518 }
7519
7520 - (void) reloadData {
7521 [self setObject:[search_ text]];
7522 [super reloadData];
7523 [self resetCursor];
7524 }
7525
7526 - (void) didSelectPackage:(Package *)package {
7527 [search_ resignFirstResponder];
7528 [super didSelectPackage:package];
7529 }
7530
7531 @end
7532 /* }}} */
7533 /* Package Settings Controller {{{ */
7534 @interface PackageSettingsController : CYViewController <
7535 UITableViewDataSource,
7536 UITableViewDelegate
7537 > {
7538 _transient Database *database_;
7539 NSString *name_;
7540 Package *package_;
7541 UITableView *table_;
7542 UISwitch *subscribedSwitch_;
7543 UISwitch *ignoredSwitch_;
7544 UITableViewCell *subscribedCell_;
7545 UITableViewCell *ignoredCell_;
7546 }
7547
7548 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7549
7550 @end
7551
7552 @implementation PackageSettingsController
7553
7554 - (void) dealloc {
7555 [self releaseSubviews];
7556 [name_ release];
7557 [package_ release];
7558
7559 [super dealloc];
7560 }
7561
7562 - (NSURL *) navigationURL {
7563 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7564 }
7565
7566 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7567 if (package_ == nil)
7568 return 0;
7569
7570 if ([package_ installed] == nil)
7571 return 1;
7572 else
7573 return 2;
7574 }
7575
7576 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7577 if (package_ == nil)
7578 return 0;
7579
7580 // both sections contain just one item right now.
7581 return 1;
7582 }
7583
7584 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7585 return nil;
7586 }
7587
7588 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7589 if (section == 0)
7590 return UCLocalize("SHOW_ALL_CHANGES_EX");
7591 else
7592 return UCLocalize("IGNORE_UPGRADES_EX");
7593 }
7594
7595 - (void) onSubscribed:(id)control {
7596 bool value([control isOn]);
7597 if (package_ == nil)
7598 return;
7599 if ([package_ setSubscribed:value])
7600 [delegate_ updateData];
7601 }
7602
7603 - (void) _updateIgnored {
7604 const char *package([name_ UTF8String]);
7605 bool on([ignoredSwitch_ isOn]);
7606
7607 pid_t pid(ExecFork());
7608 if (pid == 0) {
7609 FILE *dpkg(popen("dpkg --set-selections", "w"));
7610 fwrite(package, strlen(package), 1, dpkg);
7611
7612 if (on)
7613 fwrite(" hold\n", 6, 1, dpkg);
7614 else
7615 fwrite(" install\n", 9, 1, dpkg);
7616
7617 pclose(dpkg);
7618
7619 exit(0);
7620 _assert(false);
7621 }
7622
7623 _forever {
7624 int status;
7625 int result(waitpid(pid, &status, 0));
7626
7627 if (result != -1) {
7628 _assert(result == pid);
7629 break;
7630 }
7631 }
7632 }
7633
7634 - (void) onIgnored:(id)control {
7635 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7636 [invocation setTarget:self];
7637 [invocation setSelector:@selector(_updateIgnored)];
7638
7639 [delegate_ reloadDataWithInvocation:invocation];
7640 }
7641
7642 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7643 if (package_ == nil)
7644 return nil;
7645
7646 switch ([indexPath section]) {
7647 case 0: return subscribedCell_;
7648 case 1: return ignoredCell_;
7649
7650 _nodefault
7651 }
7652
7653 return nil;
7654 }
7655
7656 - (void) loadView {
7657 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7658
7659 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7660 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7661 [table_ setDataSource:self];
7662 [table_ setDelegate:self];
7663 [[self view] addSubview:table_];
7664
7665 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7666 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7667 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7668
7669 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7670 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7671 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7672
7673 subscribedCell_ = [[UITableViewCell alloc] init];
7674 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7675 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7676 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7677
7678 ignoredCell_ = [[UITableViewCell alloc] init];
7679 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7680 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7681 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7682 }
7683
7684 - (void) viewDidLoad {
7685 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7686 }
7687
7688 - (void) releaseSubviews {
7689 [ignoredCell_ release];
7690 ignoredCell_ = nil;
7691
7692 [subscribedCell_ release];
7693 subscribedCell_ = nil;
7694
7695 [table_ release];
7696 table_ = nil;
7697
7698 [ignoredSwitch_ release];
7699 ignoredSwitch_ = nil;
7700
7701 [subscribedSwitch_ release];
7702 subscribedSwitch_ = nil;
7703 }
7704
7705 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7706 if ((self = [super init]) != nil) {
7707 database_ = database;
7708 name_ = [package retain];
7709 } return self;
7710 }
7711
7712 - (void) reloadData {
7713 [super reloadData];
7714
7715 if (package_ != nil)
7716 [package_ autorelease];
7717 package_ = [database_ packageWithName:name_];
7718
7719 if (package_ != nil) {
7720 package_ = [package_ retain];
7721 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7722 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7723 } // XXX: what now, G?
7724
7725 [table_ reloadData];
7726 }
7727
7728 @end
7729 /* }}} */
7730
7731 /* Installed Controller {{{ */
7732 @interface InstalledController : FilteredPackageListController {
7733 BOOL expert_;
7734 }
7735
7736 - (id) initWithDatabase:(Database *)database;
7737
7738 - (void) updateRoleButton;
7739 - (void) queueStatusDidChange;
7740
7741 @end
7742
7743 @implementation InstalledController
7744
7745 - (void) dealloc {
7746 [super dealloc];
7747 }
7748
7749 - (NSURL *) navigationURL {
7750 return [NSURL URLWithString:@"cydia://installed"];
7751 }
7752
7753 - (id) initWithDatabase:(Database *)database {
7754 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7755 [self updateRoleButton];
7756 [self queueStatusDidChange];
7757 } return self;
7758 }
7759
7760 #if !AlwaysReload
7761 - (void) queueButtonClicked {
7762 [delegate_ queue];
7763 }
7764 #endif
7765
7766 - (void) queueStatusDidChange {
7767 #if !AlwaysReload
7768 if (IsWildcat_) {
7769 if (Queuing_) {
7770 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7771 initWithTitle:UCLocalize("QUEUE")
7772 style:UIBarButtonItemStyleDone
7773 target:self
7774 action:@selector(queueButtonClicked)
7775 ] autorelease]];
7776 } else {
7777 [[self navigationItem] setLeftBarButtonItem:nil];
7778 }
7779 }
7780 #endif
7781 }
7782
7783 - (void) updateRoleButton {
7784 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7785 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7786 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7787 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7788 target:self
7789 action:@selector(roleButtonClicked)
7790 ] autorelease]];
7791 }
7792
7793 - (void) roleButtonClicked {
7794 [self setObject:[NSNumber numberWithBool:expert_]];
7795 [self reloadData];
7796 expert_ = !expert_;
7797
7798 [self updateRoleButton];
7799 }
7800
7801 @end
7802 /* }}} */
7803
7804 /* Source Cell {{{ */
7805 @interface SourceCell : CYTableViewCell <
7806 ContentDelegate
7807 > {
7808 UIImage *icon_;
7809 NSString *origin_;
7810 NSString *label_;
7811 }
7812
7813 - (void) setSource:(Source *)source;
7814
7815 @end
7816
7817 @implementation SourceCell
7818
7819 - (void) clearSource {
7820 [icon_ release];
7821 [origin_ release];
7822 [label_ release];
7823
7824 icon_ = nil;
7825 origin_ = nil;
7826 label_ = nil;
7827 }
7828
7829 - (void) setSource:(Source *)source {
7830 [self clearSource];
7831
7832 if (icon_ == nil)
7833 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7834 if (icon_ == nil)
7835 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7836 icon_ = [icon_ retain];
7837
7838 origin_ = [[source name] retain];
7839 label_ = [[source uri] retain];
7840
7841 [content_ setNeedsDisplay];
7842 }
7843
7844 - (void) dealloc {
7845 [self clearSource];
7846 [super dealloc];
7847 }
7848
7849 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7850 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7851 UIView *content([self contentView]);
7852 CGRect bounds([content bounds]);
7853
7854 content_ = [[ContentView alloc] initWithFrame:bounds];
7855 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7856 [content_ setBackgroundColor:[UIColor whiteColor]];
7857 [content addSubview:content_];
7858
7859 [content_ setDelegate:self];
7860 [content_ setOpaque:YES];
7861 } return self;
7862 }
7863
7864 - (NSString *) accessibilityLabel {
7865 return label_;
7866 }
7867
7868 - (void) drawContentRect:(CGRect)rect {
7869 bool highlighted(highlighted_);
7870 float width(rect.size.width);
7871
7872 if (icon_ != nil)
7873 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7874
7875 if (highlighted)
7876 UISetColor(White_);
7877
7878 if (!highlighted)
7879 UISetColor(Black_);
7880 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7881
7882 if (!highlighted)
7883 UISetColor(Blue_);
7884 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7885 }
7886
7887 @end
7888 /* }}} */
7889 /* Source Controller {{{ */
7890 @interface SourceController : FilteredPackageListController {
7891 _transient Source *source_;
7892 NSString *key_;
7893 }
7894
7895 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7896
7897 @end
7898
7899 @implementation SourceController
7900
7901 - (NSURL *) navigationURL {
7902 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7903 }
7904
7905 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7906 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7907 source_ = source;
7908 key_ = [[source key] retain];
7909 } return self;
7910 }
7911
7912 - (void) reloadData {
7913 source_ = [database_ sourceWithKey:key_];
7914 [key_ release];
7915 key_ = [[source_ key] retain];
7916 [self setObject:source_];
7917 [[self navigationItem] setTitle:[source_ label]];
7918
7919 [super reloadData];
7920 }
7921
7922 @end
7923 /* }}} */
7924 /* Sources Controller {{{ */
7925 @interface SourcesController : CYViewController <
7926 UITableViewDataSource,
7927 UITableViewDelegate
7928 > {
7929 _transient Database *database_;
7930 UITableView *list_;
7931 NSMutableArray *sources_;
7932 int offset_;
7933
7934 NSString *href_;
7935 UIProgressHUD *hud_;
7936 NSError *error_;
7937
7938 //NSURLConnection *installer_;
7939 NSURLConnection *trivial_;
7940 NSURLConnection *trivial_bz2_;
7941 NSURLConnection *trivial_gz_;
7942 //NSURLConnection *automatic_;
7943
7944 BOOL cydia_;
7945 }
7946
7947 - (id) initWithDatabase:(Database *)database;
7948 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7949
7950 @end
7951
7952 @implementation SourcesController
7953
7954 - (void) _releaseConnection:(NSURLConnection *)connection {
7955 if (connection != nil) {
7956 [connection cancel];
7957 //[connection setDelegate:nil];
7958 [connection release];
7959 }
7960 }
7961
7962 - (void) dealloc {
7963 [self releaseSubviews];
7964
7965 [href_ release];
7966 [hud_ release];
7967 [error_ release];
7968
7969 //[self _releaseConnection:installer_];
7970 [self _releaseConnection:trivial_];
7971 [self _releaseConnection:trivial_gz_];
7972 [self _releaseConnection:trivial_bz2_];
7973 //[self _releaseConnection:automatic_];
7974
7975 [sources_ release];
7976 [super dealloc];
7977 }
7978
7979 - (NSURL *) navigationURL {
7980 return [NSURL URLWithString:@"cydia://sources"];
7981 }
7982
7983 - (void) viewDidAppear:(BOOL)animated {
7984 [super viewDidAppear:animated];
7985 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7986 }
7987
7988 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7989 return offset_ == 0 ? 1 : 2;
7990 }
7991
7992 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7993 switch (section + (offset_ == 0 ? 1 : 0)) {
7994 case 0: return UCLocalize("ENTERED_BY_USER");
7995 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7996
7997 _nodefault
7998 }
7999 }
8000
8001 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8002 int count = [sources_ count];
8003 switch (section) {
8004 case 0: return (offset_ == 0 ? count : offset_);
8005 case 1: return count - offset_;
8006
8007 _nodefault
8008 }
8009 }
8010
8011 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8012 unsigned idx = 0;
8013 switch (indexPath.section) {
8014 case 0: idx = indexPath.row; break;
8015 case 1: idx = indexPath.row + offset_; break;
8016
8017 _nodefault
8018 }
8019 return [sources_ objectAtIndex:idx];
8020 }
8021
8022 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8023 static NSString *cellIdentifier = @"SourceCell";
8024
8025 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8026 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8027 [cell setSource:[self sourceAtIndexPath:indexPath]];
8028 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8029
8030 return cell;
8031 }
8032
8033 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8034 Source *source = [self sourceAtIndexPath:indexPath];
8035
8036 SourceController *controller = [[[SourceController alloc]
8037 initWithDatabase:database_
8038 source:source
8039 ] autorelease];
8040
8041 [controller setDelegate:delegate_];
8042
8043 [[self navigationController] pushViewController:controller animated:YES];
8044 }
8045
8046 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8047 Source *source = [self sourceAtIndexPath:indexPath];
8048 return [source record] != nil;
8049 }
8050
8051 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8052 Source *source = [self sourceAtIndexPath:indexPath];
8053 [Sources_ removeObjectForKey:[source key]];
8054 [delegate_ syncData];
8055 }
8056
8057 - (void) complete {
8058 [delegate_ addTrivialSource:href_];
8059 [delegate_ syncData];
8060 }
8061
8062 - (NSString *) getWarning {
8063 NSString *href(href_);
8064 NSRange colon([href rangeOfString:@"://"]);
8065 if (colon.location != NSNotFound)
8066 href = [href substringFromIndex:(colon.location + 3)];
8067 href = [href stringByAddingPercentEscapes];
8068 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8069 href = [href stringByCachingURLWithCurrentCDN];
8070
8071 NSURL *url([NSURL URLWithString:href]);
8072
8073 NSStringEncoding encoding;
8074 NSError *error(nil);
8075
8076 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8077 return [warning length] == 0 ? nil : warning;
8078 return nil;
8079 }
8080
8081 - (void) _endConnection:(NSURLConnection *)connection {
8082 // XXX: the memory management in this method is horribly awkward
8083
8084 NSURLConnection **field = NULL;
8085 if (connection == trivial_)
8086 field = &trivial_;
8087 else if (connection == trivial_bz2_)
8088 field = &trivial_bz2_;
8089 else if (connection == trivial_gz_)
8090 field = &trivial_gz_;
8091 _assert(field != NULL);
8092 [connection release];
8093 *field = nil;
8094
8095 if (
8096 trivial_ == nil &&
8097 trivial_bz2_ == nil &&
8098 trivial_gz_ == nil
8099 ) {
8100 bool defer(false);
8101
8102 if (cydia_) {
8103 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8104 defer = true;
8105
8106 UIAlertView *alert = [[[UIAlertView alloc]
8107 initWithTitle:UCLocalize("SOURCE_WARNING")
8108 message:warning
8109 delegate:self
8110 cancelButtonTitle:UCLocalize("CANCEL")
8111 otherButtonTitles:
8112 UCLocalize("ADD_ANYWAY"),
8113 nil
8114 ] autorelease];
8115
8116 [alert setContext:@"warning"];
8117 [alert setNumberOfRows:1];
8118 [alert show];
8119 } else
8120 [self complete];
8121 } else if (error_ != nil) {
8122 UIAlertView *alert = [[[UIAlertView alloc]
8123 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8124 message:[error_ localizedDescription]
8125 delegate:self
8126 cancelButtonTitle:UCLocalize("OK")
8127 otherButtonTitles:nil
8128 ] autorelease];
8129
8130 [alert setContext:@"urlerror"];
8131 [alert show];
8132 } else {
8133 UIAlertView *alert = [[[UIAlertView alloc]
8134 initWithTitle:UCLocalize("NOT_REPOSITORY")
8135 message:UCLocalize("NOT_REPOSITORY_EX")
8136 delegate:self
8137 cancelButtonTitle:UCLocalize("OK")
8138 otherButtonTitles:nil
8139 ] autorelease];
8140
8141 [alert setContext:@"trivial"];
8142 [alert show];
8143 }
8144
8145 [delegate_ setStatusBarShowsProgress:NO];
8146 [delegate_ removeProgressHUD:hud_];
8147
8148 [hud_ autorelease];
8149 hud_ = nil;
8150
8151 if (!defer) {
8152 [href_ release];
8153 href_ = nil;
8154 }
8155
8156 if (error_ != nil) {
8157 [error_ release];
8158 error_ = nil;
8159 }
8160 }
8161 }
8162
8163 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8164 switch ([response statusCode]) {
8165 case 200:
8166 cydia_ = YES;
8167 }
8168 }
8169
8170 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8171 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8172 if (error_ != nil)
8173 error_ = [error retain];
8174 [self _endConnection:connection];
8175 }
8176
8177 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8178 [self _endConnection:connection];
8179 }
8180
8181 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8182 NSMutableURLRequest *request = [NSMutableURLRequest
8183 requestWithURL:[NSURL URLWithString:href]
8184 cachePolicy:NSURLRequestUseProtocolCachePolicy
8185 timeoutInterval:120.0
8186 ];
8187
8188 [request setHTTPMethod:method];
8189
8190 if (Machine_ != NULL)
8191 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8192 if (UniqueID_ != nil)
8193 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8194 if (Role_ != nil)
8195 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8196
8197 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8198 }
8199
8200 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8201 NSString *context([alert context]);
8202
8203 if ([context isEqualToString:@"source"]) {
8204 switch (button) {
8205 case 1: {
8206 NSString *href = [[alert textField] text];
8207
8208 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8209
8210 if (![href hasSuffix:@"/"])
8211 href_ = [href stringByAppendingString:@"/"];
8212 else
8213 href_ = href;
8214 href_ = [href_ retain];
8215
8216 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8217 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8218 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8219 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8220
8221 cydia_ = false;
8222
8223 // XXX: this is stupid
8224 hud_ = [[delegate_ addProgressHUD] retain];
8225 [hud_ setText:UCLocalize("VERIFYING_URL")];
8226 } break;
8227
8228 case 0:
8229 break;
8230
8231 _nodefault
8232 }
8233
8234 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8235 } else if ([context isEqualToString:@"trivial"])
8236 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8237 else if ([context isEqualToString:@"urlerror"])
8238 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8239 else if ([context isEqualToString:@"warning"]) {
8240 switch (button) {
8241 case 1:
8242 [self complete];
8243 break;
8244
8245 case 0:
8246 break;
8247
8248 _nodefault
8249 }
8250
8251 [href_ release];
8252 href_ = nil;
8253
8254 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8255 }
8256 }
8257
8258 - (void) loadView {
8259 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8260
8261 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8262 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8263 [list_ setRowHeight:56];
8264 [list_ setDataSource:self];
8265 [list_ setDelegate:self];
8266 [[self view] addSubview:list_];
8267 }
8268
8269 - (void) viewDidLoad {
8270 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8271 [self updateButtonsForEditingStatus:NO animated:NO];
8272 }
8273
8274 - (void) releaseSubviews {
8275 [list_ release];
8276 list_ = nil;
8277 }
8278
8279 - (id) initWithDatabase:(Database *)database {
8280 if ((self = [super init]) != nil) {
8281 database_ = database;
8282 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8283 } return self;
8284 }
8285
8286 - (void) reloadData {
8287 [super reloadData];
8288
8289 pkgSourceList list;
8290 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8291 return;
8292
8293 [sources_ removeAllObjects];
8294 [sources_ addObjectsFromArray:[database_ sources]];
8295 _trace();
8296 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8297 _trace();
8298
8299 int count([sources_ count]);
8300 offset_ = 0;
8301 for (int i = 0; i != count; i++) {
8302 if ([[sources_ objectAtIndex:i] record] == nil)
8303 break;
8304 offset_++;
8305 }
8306
8307 [list_ setEditing:NO];
8308 [self updateButtonsForEditingStatus:NO animated:NO];
8309 [list_ reloadData];
8310 }
8311
8312 - (void) showAddSourcePrompt {
8313 UIAlertView *alert = [[[UIAlertView alloc]
8314 initWithTitle:UCLocalize("ENTER_APT_URL")
8315 message:nil
8316 delegate:self
8317 cancelButtonTitle:UCLocalize("CANCEL")
8318 otherButtonTitles:
8319 UCLocalize("ADD_SOURCE"),
8320 nil
8321 ] autorelease];
8322
8323 [alert setContext:@"source"];
8324 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8325
8326 [alert setNumberOfRows:1];
8327 [alert addTextFieldWithValue:@"http://" label:@""];
8328
8329 UITextInputTraits *traits = [[alert textField] textInputTraits];
8330 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8331 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8332 [traits setKeyboardType:UIKeyboardTypeURL];
8333 // XXX: UIReturnKeyDone
8334 [traits setReturnKeyType:UIReturnKeyNext];
8335
8336 [alert show];
8337 }
8338
8339 - (void) addButtonClicked {
8340 [self showAddSourcePrompt];
8341 }
8342
8343 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8344 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8345 initWithTitle:UCLocalize("ADD")
8346 style:UIBarButtonItemStylePlain
8347 target:self
8348 action:@selector(addButtonClicked)
8349 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8350
8351 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8352 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8353 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8354 target:self
8355 action:@selector(editButtonClicked)
8356 ] autorelease] animated:animated];
8357
8358 if (IsWildcat_ && !editing)
8359 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8360 initWithTitle:UCLocalize("SETTINGS")
8361 style:UIBarButtonItemStylePlain
8362 target:self
8363 action:@selector(settingsButtonClicked)
8364 ] autorelease]];
8365 }
8366
8367 - (void) settingsButtonClicked {
8368 [delegate_ showSettings];
8369 }
8370
8371 - (void) editButtonClicked {
8372 [list_ setEditing:![list_ isEditing] animated:YES];
8373
8374 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8375 }
8376
8377 @end
8378 /* }}} */
8379
8380 /* Settings Controller {{{ */
8381 @interface SettingsController : CYViewController <
8382 UITableViewDataSource,
8383 UITableViewDelegate
8384 > {
8385 _transient Database *database_;
8386 // XXX: ok, "roledelegate_"?...
8387 _transient id roledelegate_;
8388 UITableView *table_;
8389 UISegmentedControl *segment_;
8390 UIView *container_;
8391 }
8392
8393 - (void) showDoneButton;
8394 - (void) resizeSegmentedControl;
8395
8396 @end
8397
8398 @implementation SettingsController
8399
8400 - (void) dealloc {
8401 [self releaseSubviews];
8402
8403 [super dealloc];
8404 }
8405
8406 - (void) loadView {
8407 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8408
8409 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8410 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8411 [table_ setDelegate:self];
8412 [table_ setDataSource:self];
8413 [[self view] addSubview:table_];
8414
8415 NSArray *items = [NSArray arrayWithObjects:
8416 UCLocalize("USER"),
8417 UCLocalize("HACKER"),
8418 UCLocalize("DEVELOPER"),
8419 nil];
8420 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8421 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8422 [container_ addSubview:segment_];
8423 }
8424
8425 - (void) viewDidLoad {
8426 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8427
8428 int index = -1;
8429 if ([Role_ isEqualToString:@"User"]) index = 0;
8430 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8431 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8432 if (index != -1) {
8433 [segment_ setSelectedSegmentIndex:index];
8434 [self showDoneButton];
8435 }
8436
8437 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8438 [self resizeSegmentedControl];
8439 }
8440
8441 - (void) releaseSubviews {
8442 [table_ release];
8443 table_ = nil;
8444
8445 [segment_ release];
8446 segment_ = nil;
8447
8448 [container_ release];
8449 container_ = nil;
8450 }
8451
8452 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8453 if ((self = [super init]) != nil) {
8454 database_ = database;
8455 roledelegate_ = delegate;
8456 } return self;
8457 }
8458
8459 - (void) resizeSegmentedControl {
8460 CGFloat width = [[self view] frame].size.width;
8461 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8462 }
8463
8464 - (void) viewWillAppear:(BOOL)animated {
8465 [super viewWillAppear:animated];
8466
8467 [self resizeSegmentedControl];
8468 }
8469
8470 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8471 [self resizeSegmentedControl];
8472 }
8473
8474 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8475 [self resizeSegmentedControl];
8476 }
8477
8478 - (void) save {
8479 NSString *role(nil);
8480
8481 switch ([segment_ selectedSegmentIndex]) {
8482 case 0: role = @"User"; break;
8483 case 1: role = @"Hacker"; break;
8484 case 2: role = @"Developer"; break;
8485
8486 _nodefault
8487 }
8488
8489 if (![role isEqualToString:Role_]) {
8490 bool rolling(Role_ == nil);
8491 Role_ = role;
8492
8493 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8494 Role_, @"Role",
8495 nil];
8496
8497 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8498 Changed_ = true;
8499
8500 if (rolling)
8501 [roledelegate_ loadData];
8502 else
8503 [roledelegate_ updateData];
8504 }
8505 }
8506
8507 - (void) segmentChanged:(UISegmentedControl *)control {
8508 [self showDoneButton];
8509 }
8510
8511 - (void) saveAndClose {
8512 [self save];
8513
8514 [[self navigationItem] setRightBarButtonItem:nil];
8515 [[self navigationController] dismissModalViewControllerAnimated:YES];
8516 }
8517
8518 - (void) doneButtonClicked {
8519 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8520 [spinner startAnimating];
8521 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8522 [[self navigationItem] setRightBarButtonItem:spinItem];
8523
8524 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8525 }
8526
8527 - (void) showDoneButton {
8528 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8529 initWithTitle:UCLocalize("DONE")
8530 style:UIBarButtonItemStyleDone
8531 target:self
8532 action:@selector(doneButtonClicked)
8533 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8534 }
8535
8536 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8537 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8538 return 6;
8539 }
8540
8541 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8542 return 0; // :(
8543 }
8544
8545 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8546 return nil; // This method is required by the protocol.
8547 }
8548
8549 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8550 if (section == 1)
8551 return UCLocalize("ROLE_EX");
8552 if (section == 4)
8553 return [NSString stringWithFormat:
8554 @"%@: %@\n%@: %@\n%@: %@",
8555 UCLocalize("USER"), UCLocalize("USER_EX"),
8556 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8557 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8558 ];
8559 else return nil;
8560 }
8561
8562 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8563 return section == 3 ? 44.0f : 0;
8564 }
8565
8566 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8567 return section == 3 ? container_ : nil;
8568 }
8569
8570 - (void) reloadData {
8571 [super reloadData];
8572 [table_ reloadData];
8573 }
8574
8575 @end
8576 /* }}} */
8577 /* Stash Controller {{{ */
8578 @interface StashController : CYViewController {
8579 UIActivityIndicatorView *spinner_;
8580 UILabel *status_;
8581 UILabel *caption_;
8582 }
8583
8584 @end
8585
8586 @implementation StashController
8587
8588 - (void) dealloc {
8589 [self releaseSubviews];
8590
8591 [super dealloc];
8592 }
8593
8594 - (void) loadView {
8595 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8596 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8597
8598 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8599 CGRect spinrect = [spinner_ frame];
8600 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8601 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8602 [spinner_ setFrame:spinrect];
8603 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8604 [[self view] addSubview:spinner_];
8605 [spinner_ startAnimating];
8606
8607 CGRect captrect;
8608 captrect.size.width = [[self view] frame].size.width;
8609 captrect.size.height = 40.0f;
8610 captrect.origin.x = 0;
8611 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8612 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8613 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8614 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8615 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8616 [caption_ setTextColor:[UIColor whiteColor]];
8617 [caption_ setBackgroundColor:[UIColor clearColor]];
8618 [caption_ setShadowColor:[UIColor blackColor]];
8619 [caption_ setTextAlignment:UITextAlignmentCenter];
8620 [[self view] addSubview:caption_];
8621
8622 CGRect statusrect;
8623 statusrect.size.width = [[self view] frame].size.width;
8624 statusrect.size.height = 30.0f;
8625 statusrect.origin.x = 0;
8626 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8627 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8628 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8629 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8630 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8631 [status_ setTextColor:[UIColor whiteColor]];
8632 [status_ setBackgroundColor:[UIColor clearColor]];
8633 [status_ setShadowColor:[UIColor blackColor]];
8634 [status_ setTextAlignment:UITextAlignmentCenter];
8635 [[self view] addSubview:status_];
8636 }
8637
8638 - (void) releaseSubviews {
8639 [spinner_ release];
8640 spinner_ = nil;
8641
8642 [status_ release];
8643 status_ = nil;
8644
8645 [caption_ release];
8646 caption_ = nil;
8647 }
8648
8649 @end
8650 /* }}} */
8651
8652 @interface Cydia : UIApplication <
8653 ConfirmationControllerDelegate,
8654 ProgressControllerDelegate,
8655 CydiaDelegate,
8656 UINavigationControllerDelegate,
8657 UITabBarControllerDelegate
8658 > {
8659 // XXX: evaluate all fields for _transient
8660
8661 UIWindow *window_;
8662 CYTabBarController *tabbar_;
8663
8664 NSMutableArray *essential_;
8665 NSMutableArray *broken_;
8666
8667 Database *database_;
8668
8669 NSURL *starturl_;
8670
8671 unsigned locked_;
8672 unsigned activity_;
8673
8674 StashController *stash_;
8675
8676 bool loaded_;
8677 }
8678
8679 - (void) loadData;
8680
8681 @end
8682
8683 @implementation Cydia
8684
8685 - (void) beginUpdate {
8686 [tabbar_ beginUpdate];
8687 }
8688
8689 - (BOOL) updating {
8690 return [tabbar_ updating];
8691 }
8692
8693 - (void) _loaded {
8694 if ([broken_ count] != 0) {
8695 int count = [broken_ count];
8696
8697 UIAlertView *alert = [[[UIAlertView alloc]
8698 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8699 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8700 delegate:self
8701 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8702 otherButtonTitles:
8703 UCLocalize("TEMPORARY_IGNORE"),
8704 nil
8705 ] autorelease];
8706
8707 [alert setContext:@"fixhalf"];
8708 [alert show];
8709 } else if (!Ignored_ && [essential_ count] != 0) {
8710 int count = [essential_ count];
8711
8712 UIAlertView *alert = [[[UIAlertView alloc]
8713 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8714 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8715 delegate:self
8716 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8717 otherButtonTitles:
8718 UCLocalize("UPGRADE_ESSENTIAL"),
8719 UCLocalize("COMPLETE_UPGRADE"),
8720 nil
8721 ] autorelease];
8722
8723 [alert setContext:@"upgrade"];
8724 [alert show];
8725 }
8726 }
8727
8728 - (void) _saveConfig {
8729 _trace();
8730 MetaFile_.Sync();
8731 _trace();
8732
8733 if (Changed_) {
8734 NSString *error(nil);
8735
8736 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8737 _trace();
8738 NSError *error(nil);
8739 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8740 NSLog(@"failure to save metadata data: %@", error);
8741 _trace();
8742
8743 Changed_ = false;
8744 } else {
8745 NSLog(@"failure to serialize metadata: %@", error);
8746 }
8747 }
8748 }
8749
8750 // Navigation controller for the queuing badge.
8751 - (CYNavigationController *) queueNavigationController {
8752 NSArray *controllers = [tabbar_ viewControllers];
8753 return [controllers objectAtIndex:3];
8754 }
8755
8756 - (void) _updateData {
8757 [self _saveConfig];
8758
8759 [tabbar_ reloadData];
8760
8761 CYNavigationController *navigation = [self queueNavigationController];
8762
8763 id queuedelegate = nil;
8764 if ([[navigation viewControllers] count] > 0)
8765 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8766
8767 [queuedelegate queueStatusDidChange];
8768 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8769 }
8770
8771 - (void) _refreshIfPossible:(NSDate *)update {
8772 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8773
8774 bool recently = false;
8775 if (update != nil) {
8776 NSTimeInterval interval([update timeIntervalSinceNow]);
8777 if (interval <= 0 && interval > -(15*60))
8778 recently = true;
8779 }
8780
8781 // Don't automatic refresh if:
8782 // - We already refreshed recently.
8783 // - We already auto-refreshed this launch.
8784 // - Auto-refresh is disabled.
8785 if (recently || loaded_ || ManualRefresh) {
8786 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8787
8788 // If we are cancelling, we need to make sure it knows it's already loaded.
8789 loaded_ = true;
8790 return;
8791 } else {
8792 // We are going to load, so remember that.
8793 loaded_ = true;
8794 }
8795
8796 SCNetworkReachabilityFlags flags; {
8797 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8798 SCNetworkReachabilityGetFlags(reachability, &flags);
8799 CFRelease(reachability);
8800 }
8801
8802 // XXX: this elaborate mess is what Apple is using to determine this? :(
8803 // XXX: do we care if the user has to intervene? maybe that's ok?
8804 bool reachable(
8805 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8806 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8807 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8808 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8809 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8810 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8811 )
8812 );
8813
8814 // If we can reach the server, auto-refresh!
8815 if (reachable)
8816 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8817
8818 [pool release];
8819 }
8820
8821 - (void) refreshIfPossible {
8822 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8823 }
8824
8825 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8826 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8827 [hud setText:UCLocalize("RELOADING_DATA")];
8828
8829 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8830
8831 if (hud != nil)
8832 [self removeProgressHUD:hud];
8833
8834 size_t changes(0);
8835
8836 [essential_ removeAllObjects];
8837 [broken_ removeAllObjects];
8838
8839 NSArray *packages([database_ packages]);
8840 for (Package *package in packages) {
8841 if ([package half])
8842 [broken_ addObject:package];
8843 if ([package upgradableAndEssential:NO]) {
8844 if ([package essential])
8845 [essential_ addObject:package];
8846 ++changes;
8847 }
8848 }
8849
8850 NSLog(@"changes:#%u", changes);
8851
8852 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8853 if (changes != 0) {
8854 _trace();
8855 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8856 [changesItem setBadgeValue:badge];
8857 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8858 [self setApplicationIconBadgeNumber:changes];
8859 } else {
8860 _trace();
8861 [changesItem setBadgeValue:nil];
8862 [changesItem setAnimatedBadge:NO];
8863 [self setApplicationIconBadgeNumber:0];
8864 }
8865
8866 [self _updateData];
8867
8868 [self refreshIfPossible];
8869 }
8870
8871 - (void) updateData {
8872 [self _updateData];
8873 }
8874
8875 - (void) update_ {
8876 [database_ update];
8877 }
8878
8879 - (void) syncData {
8880 [self _saveConfig];
8881
8882 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8883 _assert(file != NULL);
8884
8885 for (NSString *key in [Sources_ allKeys]) {
8886 NSDictionary *source([Sources_ objectForKey:key]);
8887
8888 fprintf(file, "%s %s %s\n",
8889 [[source objectForKey:@"Type"] UTF8String],
8890 [[source objectForKey:@"URI"] UTF8String],
8891 [[source objectForKey:@"Distribution"] UTF8String]
8892 );
8893 }
8894
8895 fclose(file);
8896
8897 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8898 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8899 if (IsWildcat_)
8900 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8901 [tabbar_ presentModalViewController:navigation animated:YES];
8902
8903 [progress
8904 detachNewThreadSelector:@selector(update_)
8905 toTarget:self
8906 withObject:nil
8907 title:UCLocalize("UPDATING_SOURCES")
8908 ];
8909 }
8910
8911 - (void) addTrivialSource:(NSString *)href {
8912 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8913 @"deb", @"Type",
8914 href, @"URI",
8915 @"./", @"Distribution",
8916 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8917
8918 Changed_ = true;
8919 }
8920
8921 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8922 @synchronized (self) {
8923 [self _reloadDataWithInvocation:invocation];
8924 }
8925 }
8926
8927 - (void) reloadData {
8928 [self reloadDataWithInvocation:nil];
8929 }
8930
8931 - (void) resolve {
8932 pkgProblemResolver *resolver = [database_ resolver];
8933
8934 resolver->InstallProtect();
8935 if (!resolver->Resolve(true))
8936 _error->Discard();
8937 }
8938
8939 - (bool) perform {
8940 // XXX: this is a really crappy way of doing this.
8941 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8942 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8943 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8944 if ([tabbar_ updating])
8945 [tabbar_ cancelUpdate];
8946
8947 if (![database_ prepare])
8948 return false;
8949
8950 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8951 [page setDelegate:self];
8952 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8953 [confirm_ setDelegate:self];
8954
8955 if (IsWildcat_)
8956 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8957 [tabbar_ presentModalViewController:confirm_ animated:YES];
8958
8959 return true;
8960 }
8961
8962 - (void) queue {
8963 @synchronized (self) {
8964 [self perform];
8965 }
8966 }
8967
8968 - (void) clearPackage:(Package *)package {
8969 @synchronized (self) {
8970 [package clear];
8971 [self resolve];
8972 [self perform];
8973 }
8974 }
8975
8976 - (void) installPackages:(NSArray *)packages {
8977 @synchronized (self) {
8978 for (Package *package in packages)
8979 [package install];
8980 [self resolve];
8981 [self perform];
8982 }
8983 }
8984
8985 - (void) installPackage:(Package *)package {
8986 @synchronized (self) {
8987 [package install];
8988 [self resolve];
8989 [self perform];
8990 }
8991 }
8992
8993 - (void) removePackage:(Package *)package {
8994 @synchronized (self) {
8995 [package remove];
8996 [self resolve];
8997 [self perform];
8998 }
8999 }
9000
9001 - (void) distUpgrade {
9002 @synchronized (self) {
9003 if (![database_ upgrade])
9004 return;
9005 [self perform];
9006 }
9007 }
9008
9009 - (void) complete {
9010 @synchronized (self) {
9011 [self _reloadDataWithInvocation:nil];
9012 }
9013 }
9014
9015 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9016 Queuing_ = false;
9017
9018 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
9019
9020 if (navigation != nil) {
9021 [navigation pushViewController:progress animated:YES];
9022 } else {
9023 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
9024 if (IsWildcat_)
9025 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9026 [tabbar_ presentModalViewController:navigation animated:YES];
9027 }
9028
9029 [progress
9030 detachNewThreadSelector:@selector(perform)
9031 toTarget:database_
9032 withObject:nil
9033 title:UCLocalize("RUNNING")
9034 ];
9035
9036 ++locked_;
9037 }
9038
9039 - (void) progressControllerIsComplete:(ProgressController *)progress {
9040 --locked_;
9041 [self complete];
9042 }
9043
9044 - (void) showSettings {
9045 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9046 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9047 if (IsWildcat_)
9048 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9049 [tabbar_ presentModalViewController:nav animated:YES];
9050 }
9051
9052 - (void) retainNetworkActivityIndicator {
9053 if (activity_++ == 0)
9054 [self setNetworkActivityIndicatorVisible:YES];
9055 }
9056
9057 - (void) releaseNetworkActivityIndicator {
9058 if (--activity_ == 0)
9059 [self setNetworkActivityIndicatorVisible:NO];
9060 }
9061
9062 - (void) cancelAndClear:(bool)clear {
9063 @synchronized (self) {
9064 if (clear) {
9065 [database_ clear];
9066 Queuing_ = false;
9067 } else {
9068 Queuing_ = true;
9069 }
9070
9071 [self _updateData];
9072 }
9073 }
9074
9075 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9076 NSString *context([alert context]);
9077
9078 if ([context isEqualToString:@"fixhalf"]) {
9079 if (button == [alert cancelButtonIndex]) {
9080 @synchronized (self) {
9081 for (Package *broken in broken_) {
9082 [broken remove];
9083
9084 NSString *id = [broken id];
9085 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9086 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9087 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9088 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9089 }
9090
9091 [self resolve];
9092 [self perform];
9093 }
9094 } else if (button == [alert firstOtherButtonIndex]) {
9095 [broken_ removeAllObjects];
9096 [self _loaded];
9097 }
9098
9099 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9100 } else if ([context isEqualToString:@"upgrade"]) {
9101 if (button == [alert firstOtherButtonIndex]) {
9102 @synchronized (self) {
9103 for (Package *essential in essential_)
9104 [essential install];
9105
9106 [self resolve];
9107 [self perform];
9108 }
9109 } else if (button == [alert firstOtherButtonIndex] + 1) {
9110 [self distUpgrade];
9111 } else if (button == [alert cancelButtonIndex]) {
9112 Ignored_ = YES;
9113 }
9114
9115 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9116 }
9117 }
9118
9119 - (void) system:(NSString *)command { _pooled
9120 _trace();
9121 system([command UTF8String]);
9122 _trace();
9123 }
9124
9125 - (void) applicationWillSuspend {
9126 [database_ clean];
9127 [super applicationWillSuspend];
9128 }
9129
9130 - (BOOL) isSafeToSuspend {
9131 // Use external process status API internally.
9132 // This is probably a really bad idea.
9133 // XXX: what is the point of this? does this solve anything at all?
9134 uint64_t status = 0;
9135 int notify_token;
9136 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9137 notify_get_state(notify_token, &status);
9138 notify_cancel(notify_token);
9139 }
9140
9141 return locked_ == 0 && status == 0;
9142 }
9143
9144 - (void) applicationSuspend:(__GSEvent *)event {
9145 if ([self isSafeToSuspend])
9146 [super applicationSuspend:event];
9147 }
9148
9149 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9150 if ([self isSafeToSuspend])
9151 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9152 }
9153
9154 - (void) _setSuspended:(BOOL)value {
9155 if ([self isSafeToSuspend])
9156 [super _setSuspended:value];
9157 }
9158
9159 - (UIProgressHUD *) addProgressHUD {
9160 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9161 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9162
9163 [window_ setUserInteractionEnabled:NO];
9164 [hud show:YES];
9165
9166 UIViewController *target = tabbar_;
9167 while ([target modalViewController] != nil) target = [target modalViewController];
9168 [[target view] addSubview:hud];
9169
9170 ++locked_;
9171 return hud;
9172 }
9173
9174 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9175 [hud show:NO];
9176 [hud removeFromSuperview];
9177 [window_ setUserInteractionEnabled:YES];
9178 --locked_;
9179 }
9180
9181 - (CYViewController *) pageForPackage:(NSString *)name {
9182 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9183 }
9184
9185 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9186 NSString *scheme([[url scheme] lowercaseString]);
9187 if ([[url absoluteString] length] <= [scheme length] + 3)
9188 return nil;
9189 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9190 NSArray *components([path pathComponents]);
9191
9192 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9193 return [self pageForPackage:[components objectAtIndex:1]];
9194
9195 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9196 return nil;
9197
9198 NSString *base([components objectAtIndex:0]);
9199
9200 CYViewController *controller = nil;
9201
9202 if ([base isEqualToString:@"url"]) {
9203 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9204 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9205 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9206 } else if (!external && [components count] == 1) {
9207 if ([base isEqualToString:@"manage"]) {
9208 controller = [[[ManageController alloc] init] autorelease];
9209 }
9210
9211 if ([base isEqualToString:@"sources"]) {
9212 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9213 }
9214
9215 if ([base isEqualToString:@"home"]) {
9216 controller = [[[HomeController alloc] init] autorelease];
9217 }
9218
9219 if ([base isEqualToString:@"sections"]) {
9220 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9221 }
9222
9223 if ([base isEqualToString:@"search"]) {
9224 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9225 }
9226
9227 if ([base isEqualToString:@"changes"]) {
9228 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9229 }
9230
9231 if ([base isEqualToString:@"installed"]) {
9232 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9233 }
9234 } else if ([components count] == 2) {
9235 NSString *argument = [components objectAtIndex:1];
9236
9237 if ([base isEqualToString:@"package"]) {
9238 controller = [self pageForPackage:argument];
9239 }
9240
9241 if (!external && [base isEqualToString:@"search"]) {
9242 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9243 [(SearchController *)controller setSearchTerm:argument];
9244 }
9245
9246 if (!external && [base isEqualToString:@"sections"]) {
9247 if ([argument isEqualToString:@"all"])
9248 argument = nil;
9249 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9250 }
9251
9252 if (!external && [base isEqualToString:@"sources"]) {
9253 if ([argument isEqualToString:@"add"]) {
9254 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9255 [(SourcesController *)controller showAddSourcePrompt];
9256 } else {
9257 Source *source = [database_ sourceWithKey:argument];
9258 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9259 }
9260 }
9261
9262 if (!external && [base isEqualToString:@"launch"]) {
9263 [self launchApplicationWithIdentifier:argument suspended:NO];
9264 return nil;
9265 }
9266 } else if (!external && [components count] == 3) {
9267 NSString *arg1 = [components objectAtIndex:1];
9268 NSString *arg2 = [components objectAtIndex:2];
9269
9270 if ([base isEqualToString:@"package"]) {
9271 if ([arg2 isEqualToString:@"settings"]) {
9272 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9273 } else if ([arg2 isEqualToString:@"files"]) {
9274 if (Package *package = [database_ packageWithName:arg1]) {
9275 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9276 [(FileTable *)controller setPackage:package];
9277 }
9278 }
9279 }
9280 }
9281
9282 [controller setDelegate:self];
9283 return controller;
9284 }
9285
9286 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9287 CYViewController *page([self pageForURL:url forExternal:external]);
9288
9289 if (page != nil) {
9290 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9291 [nav setViewControllers:[NSArray arrayWithObject:page]];
9292 [tabbar_ setUnselectedViewController:nav];
9293 }
9294
9295 return page != nil;
9296 }
9297
9298 - (void) applicationOpenURL:(NSURL *)url {
9299 [super applicationOpenURL:url];
9300
9301 if (!loaded_) starturl_ = [url retain];
9302 else [self openCydiaURL:url forExternal:YES];
9303 }
9304
9305 - (void) applicationWillResignActive:(UIApplication *)application {
9306 // Stop refreshing if you get a phone call or lock the device.
9307 if ([tabbar_ updating])
9308 [tabbar_ cancelUpdate];
9309
9310 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9311 [super applicationWillResignActive:application];
9312 }
9313
9314 - (void) applicationWillTerminate:(UIApplication *)application {
9315 Changed_ = true;
9316 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9317 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9318 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9319
9320 [self _saveConfig];
9321 }
9322
9323 - (void) addStashController {
9324 ++locked_;
9325 stash_ = [[StashController alloc] init];
9326 [window_ addSubview:[stash_ view]];
9327 }
9328
9329 - (void) removeStashController {
9330 [[stash_ view] removeFromSuperview];
9331 [stash_ release];
9332 --locked_;
9333 }
9334
9335 - (void) stash {
9336 [self setIdleTimerDisabled:YES];
9337
9338 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9339 [self setStatusBarShowsProgress:YES];
9340 UpdateExternalStatus(1);
9341
9342 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9343
9344 UpdateExternalStatus(0);
9345 [self setStatusBarShowsProgress:NO];
9346
9347 [self removeStashController];
9348
9349 if (ExecFork() == 0) {
9350 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9351 perror("launchctl stop");
9352 }
9353 }
9354
9355 - (void) setupViewControllers {
9356 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9357
9358 NSMutableArray *items([NSMutableArray arrayWithObjects:
9359 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9360 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9361 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9362 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9363 nil]);
9364
9365 if (IsWildcat_) {
9366 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9367 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9368 } else {
9369 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9370 }
9371
9372 NSMutableArray *controllers([NSMutableArray array]);
9373 for (UITabBarItem *item in items) {
9374 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9375 [controller setTabBarItem:item];
9376 [controllers addObject:controller];
9377 }
9378 [tabbar_ setViewControllers:controllers];
9379
9380 [tabbar_ setUpdateDelegate:self];
9381 }
9382
9383 - (CYEmulatedLoadingController *) showEmulatedLoadingControllerInView:(UIView *)view {
9384 static CYEmulatedLoadingController *fake = nil;
9385
9386 if (view != nil) {
9387 if (fake == nil)
9388 fake = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9389 [view addSubview:[fake view]];
9390 } else {
9391 [[fake view] removeFromSuperview];
9392 [fake release];
9393 fake = nil;
9394 }
9395
9396 return fake;
9397 }
9398
9399 - (void) applicationDidFinishLaunching:(id)unused {
9400 _trace();
9401 CydiaApp = self;
9402
9403 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9404 [self setApplicationSupportsShakeToEdit:NO];
9405
9406 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9407 initWithMemoryCapacity:524288
9408 diskCapacity:10485760
9409 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9410 ] autorelease]];
9411
9412 [CYBrowserController _initialize];
9413
9414 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9415
9416 Font12_ = [[UIFont systemFontOfSize:12] retain];
9417 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9418 Font14_ = [[UIFont systemFontOfSize:14] retain];
9419 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9420 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9421
9422 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9423 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9424
9425 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9426 [window_ orderFront:self];
9427 [window_ makeKey:self];
9428 [window_ setHidden:NO];
9429
9430 if (
9431 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9432 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9433 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9434 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9435 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9436 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9437 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9438 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9439 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9440 false
9441 ) {
9442 [self addStashController];
9443 // XXX: this would be much cleaner as a yieldToSelector:
9444 // that way the removeStashController could happen right here inline
9445 // we also could no longer require the useless stash_ field anymore
9446 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9447 return;
9448 }
9449
9450 database_ = [Database sharedInstance];
9451
9452 [window_ setUserInteractionEnabled:NO];
9453 [self setupViewControllers];
9454 [self showEmulatedLoadingControllerInView:window_];
9455
9456 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9457 _trace();
9458 }
9459
9460 - (void) loadData {
9461 _trace();
9462 if (Role_ == nil) {
9463 [window_ setUserInteractionEnabled:YES];
9464
9465 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9466 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9467 if (IsWildcat_)
9468 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9469 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9470
9471 return;
9472 } else {
9473 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9474 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9475 [window_ setUserInteractionEnabled:NO];
9476 }
9477
9478 [self reloadData];
9479 PrintTimes();
9480
9481 [window_ addSubview:[tabbar_ view]];
9482 [self showEmulatedLoadingControllerInView:nil];
9483 [window_ setUserInteractionEnabled:YES];
9484
9485 int selectedIndex = 0;
9486 NSMutableArray *items = nil;
9487
9488 bool recently = false;
9489 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9490 if (closed != nil) {
9491 NSTimeInterval interval([closed timeIntervalSinceNow]);
9492 // XXX: Is 15 minutes the optimal time here?
9493 if (interval <= 0 && interval > -(15*60))
9494 recently = true;
9495 }
9496
9497 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9498 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9499
9500 BOOL enough = YES;
9501 for (NSArray *entry in items)
9502 if ([entry count] <= 0)
9503 enough = NO;
9504
9505 if (!recently || !items || !enough) {
9506 selectedIndex = 0;
9507 items = [NSMutableArray array];
9508 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9509 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9510 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9511 if (!IsWildcat_) {
9512 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9513 } else {
9514 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9515 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9516 }
9517 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9518 }
9519
9520 [tabbar_ setSelectedIndex:selectedIndex];
9521 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9522 NSArray *stack = [items objectAtIndex:tab];
9523 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9524 NSMutableArray *current = [NSMutableArray array];
9525
9526 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9527 NSString *addr = [stack objectAtIndex:nav];
9528 NSURL *url = [NSURL URLWithString:addr];
9529 CYViewController *page = [self pageForURL:url forExternal:NO];
9530 if (page != nil)
9531 [current addObject:page];
9532 }
9533
9534 [navigation setViewControllers:current];
9535 }
9536
9537 // (Try to) show the startup URL.
9538 if (starturl_ != nil) {
9539 [self openCydiaURL:starturl_ forExternal:NO];
9540 [starturl_ release];
9541 starturl_ = nil;
9542 }
9543 }
9544
9545 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9546 if (item != nil && IsWildcat_) {
9547 [sheet showFromBarButtonItem:item animated:YES];
9548 } else {
9549 [sheet showInView:window_];
9550 }
9551 }
9552
9553 @end
9554
9555 /*IMP alloc_;
9556 id Alloc_(id self, SEL selector) {
9557 id object = alloc_(self, selector);
9558 lprintf("[%s]A-%p\n", self->isa->name, object);
9559 return object;
9560 }*/
9561
9562 /*IMP dealloc_;
9563 id Dealloc_(id self, SEL selector) {
9564 id object = dealloc_(self, selector);
9565 lprintf("[%s]D-%p\n", self->isa->name, object);
9566 return object;
9567 }*/
9568
9569 Class $WebDefaultUIKitDelegate;
9570
9571 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9572 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9573 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9574 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9575 }
9576
9577 static NSNumber *shouldPlayKeyboardSounds;
9578
9579 Class $UIHardware;
9580
9581 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9582 switch (sound) {
9583 case 1104: // Keyboard Button Clicked
9584 case 1105: // Keyboard Delete Repeated
9585 if (shouldPlayKeyboardSounds == nil) {
9586 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9587 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9588 }
9589
9590 if (![shouldPlayKeyboardSounds boolValue])
9591 break;
9592
9593 default:
9594 _UIHardware$_playSystemSound$(self, _cmd, sound);
9595 }
9596 }
9597
9598 Class $UIApplication;
9599
9600 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9601 static BOOL initialized = NO;
9602 static BOOL started = NO;
9603
9604 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9605 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9606
9607 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9608 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9609 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9610 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9611
9612 if (initialized && !enabled) {
9613 initialized = NO;
9614 [bundle performSelector:@selector(_accessibilityStopServer)];
9615 } else if (enabled) {
9616 initialized = YES;
9617 if (!started) {
9618 started = YES;
9619 [bundle performSelector:@selector(_accessibilityStartServer)];
9620 }
9621 }
9622 }
9623 }
9624
9625 int main(int argc, char *argv[]) { _pooled
9626 _trace();
9627
9628 UpdateExternalStatus(0);
9629
9630 if (Class $UIDevice = objc_getClass("UIDevice")) {
9631 UIDevice *device([$UIDevice currentDevice]);
9632 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9633 } else
9634 IsWildcat_ = false;
9635
9636 UIScreen *screen([UIScreen mainScreen]);
9637 if ([screen respondsToSelector:@selector(scale)])
9638 ScreenScale_ = [screen scale];
9639 else
9640 ScreenScale_ = 1;
9641
9642 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9643 if (ScreenScale_ > 1)
9644 [parts addObject:@"@2x"];
9645 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9646 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9647
9648 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9649
9650 /* Library Hacks {{{ */
9651 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9652
9653 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9654 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9655 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9656 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9657 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9658 }
9659
9660 $UIHardware = objc_getClass("UIHardware");
9661 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9662 if (UIHardware$_playSystemSound$ != NULL) {
9663 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9664 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9665 }
9666
9667 $UIApplication = objc_getClass("UIApplication");
9668 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9669 if (UIApplication$_updateApplicationAccessibility != NULL) {
9670 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9671 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9672 }
9673 /* }}} */
9674 /* Set Locale {{{ */
9675 Locale_ = CFLocaleCopyCurrent();
9676 Languages_ = [NSLocale preferredLanguages];
9677 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9678 //NSLog(@"%@", [Languages_ description]);
9679
9680 const char *lang;
9681 if (Languages_ == nil || [Languages_ count] == 0)
9682 // XXX: consider just setting to C and then falling through?
9683 lang = NULL;
9684 else {
9685 lang = [[Languages_ objectAtIndex:0] UTF8String];
9686 setenv("LANG", lang, true);
9687 }
9688
9689 //std::setlocale(LC_ALL, lang);
9690 NSLog(@"Setting Language: %s", lang);
9691 /* }}} */
9692
9693 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9694
9695 /* Parse Arguments {{{ */
9696 bool substrate(false);
9697
9698 if (argc != 0) {
9699 char **args(argv);
9700 int arge(1);
9701
9702 for (int argi(1); argi != argc; ++argi)
9703 if (strcmp(argv[argi], "--") == 0) {
9704 arge = argi;
9705 argv[argi] = argv[0];
9706 argv += argi;
9707 argc -= argi;
9708 break;
9709 }
9710
9711 for (int argi(1); argi != arge; ++argi)
9712 if (strcmp(args[argi], "--substrate") == 0)
9713 substrate = true;
9714 else
9715 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9716 }
9717 /* }}} */
9718
9719 App_ = [[NSBundle mainBundle] bundlePath];
9720 Home_ = NSHomeDirectory();
9721 Advanced_ = YES;
9722
9723 setuid(0);
9724 setgid(0);
9725
9726 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9727 alloc_ = alloc->method_imp;
9728 alloc->method_imp = (IMP) &Alloc_;*/
9729
9730 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9731 dealloc_ = dealloc->method_imp;
9732 dealloc->method_imp = (IMP) &Dealloc_;*/
9733
9734 /* System Information {{{ */
9735 size_t size;
9736
9737 int maxproc;
9738 size = sizeof(maxproc);
9739 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9740 perror("sysctlbyname(\"kern.maxproc\", ?)");
9741 else if (maxproc < 64) {
9742 maxproc = 64;
9743 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9744 perror("sysctlbyname(\"kern.maxproc\", #)");
9745 }
9746
9747 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9748 char *osversion = new char[size];
9749 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9750 perror("sysctlbyname(\"kern.osversion\", ?)");
9751 else
9752 System_ = [NSString stringWithUTF8String:osversion];
9753
9754 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9755 char *machine = new char[size];
9756 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9757 perror("sysctlbyname(\"hw.machine\", ?)");
9758 else
9759 Machine_ = machine;
9760
9761 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9762 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9763 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9764 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9765 CFRelease(serial);
9766 }
9767
9768 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9769 NSData *data((NSData *) ecid);
9770 size_t length([data length]);
9771 uint8_t bytes[length];
9772 [data getBytes:bytes];
9773 char string[length * 2 + 1];
9774 for (size_t i(0); i != length; ++i)
9775 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9776 ChipID_ = [NSString stringWithUTF8String:string];
9777 CFRelease(ecid);
9778 }
9779
9780 IOObjectRelease(service);
9781 }
9782 }
9783
9784 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9785
9786 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9787 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9788 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9789
9790 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9791 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9792 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9793
9794 if (mcc != NULL && mnc != NULL)
9795 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9796
9797 if (mnc != NULL)
9798 CFRelease(mnc);
9799 if (mcc != NULL)
9800 CFRelease(mcc);
9801
9802 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9803 Build_ = [system objectForKey:@"ProductBuildVersion"];
9804 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9805 Product_ = [info objectForKey:@"SafariProductVersion"];
9806 Safari_ = [info objectForKey:@"CFBundleVersion"];
9807 }
9808 /* }}} */
9809 /* Load Database {{{ */
9810 _trace();
9811 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9812 _trace();
9813 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9814
9815 if (Metadata_ == NULL)
9816 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9817 else {
9818 Settings_ = [Metadata_ objectForKey:@"Settings"];
9819
9820 Packages_ = [Metadata_ objectForKey:@"Packages"];
9821 Sections_ = [Metadata_ objectForKey:@"Sections"];
9822 Sources_ = [Metadata_ objectForKey:@"Sources"];
9823
9824 Token_ = [Metadata_ objectForKey:@"Token"];
9825 }
9826
9827 if (Settings_ != nil)
9828 Role_ = [Settings_ objectForKey:@"Role"];
9829
9830 if (Sections_ == nil) {
9831 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9832 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9833 }
9834
9835 if (Sources_ == nil) {
9836 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9837 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9838 }
9839 /* }}} */
9840
9841 _trace();
9842 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9843 _trace();
9844
9845 if (Packages_ != nil) {
9846 bool fail(false);
9847 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9848 _trace();
9849
9850 if (!fail) {
9851 [Metadata_ removeObjectForKey:@"Packages"];
9852 Packages_ = nil;
9853 Changed_ = true;
9854 }
9855 }
9856
9857 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9858
9859 #define MobileSubstrate_(name) \
9860 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9861 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9862
9863 MobileSubstrate_(Activator)
9864 MobileSubstrate_(libstatusbar)
9865 MobileSubstrate_(SimulatedKeyEvents)
9866 MobileSubstrate_(WinterBoard)
9867
9868 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9869 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9870
9871 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9872
9873 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9874 unlink("/tmp/.cydia.fw");
9875 goto firmware;
9876 } else if (access("/User", F_OK) != 0 || version < 2) {
9877 firmware:
9878 _trace();
9879 system("/usr/libexec/cydia/firmware.sh");
9880 _trace();
9881 }
9882
9883 _assert([[NSFileManager defaultManager]
9884 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9885 withIntermediateDirectories:YES
9886 attributes:nil
9887 error:NULL
9888 ]);
9889
9890 if (access("/tmp/cydia.chk", F_OK) == 0) {
9891 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9892 _assert(errno == ENOENT);
9893 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9894 _assert(errno == ENOENT);
9895 }
9896
9897 /* APT Initialization {{{ */
9898 _assert(pkgInitConfig(*_config));
9899 _assert(pkgInitSystem(*_config, _system));
9900
9901 if (lang != NULL)
9902 _config->Set("APT::Acquire::Translation", lang);
9903
9904 // XXX: this timeout might be important :(
9905 //_config->Set("Acquire::http::Timeout", 15);
9906
9907 _config->Set("Acquire::http::MaxParallel", 3);
9908 /* }}} */
9909 /* Color Choices {{{ */
9910 space_ = CGColorSpaceCreateDeviceRGB();
9911
9912 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9913 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9914 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9915 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9916 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9917 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9918 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9919 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9920 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9921
9922 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9923 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9924 /* }}}*/
9925 /* UIKit Configuration {{{ */
9926 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9927 if ($GSFontSetUseLegacyFontMetrics != NULL)
9928 $GSFontSetUseLegacyFontMetrics(YES);
9929
9930 // XXX: I have a feeling this was important
9931 //UIKeyboardDisableAutomaticAppearance();
9932 /* }}} */
9933
9934 Colon_ = UCLocalize("COLON_DELIMITED");
9935 Elision_ = UCLocalize("ELISION");
9936 Error_ = UCLocalize("ERROR");
9937 Warning_ = UCLocalize("WARNING");
9938
9939 _trace();
9940 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9941
9942 CGColorSpaceRelease(space_);
9943 CFRelease(Locale_);
9944
9945 return value;
9946 }