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