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