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