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