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