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