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