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