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