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