]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Restructure Cydia for browsing by Sources.
[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
71 #include <WebCore/WebCoreThread.h>
72
73 #include <algorithm>
74 #include <iomanip>
75 #include <sstream>
76 #include <string>
77
78 #include <ext/stdio_filebuf.h>
79
80 #undef ABS
81
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
99
100 #include <apr-1/apr_pools.h>
101
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
108
109 #include <fcntl.h>
110 #include <notify.h>
111 #include <dlfcn.h>
112
113 extern "C" {
114 #include <mach-o/nlist.h>
115 }
116
117 #include <cstdio>
118 #include <cstdlib>
119 #include <cstring>
120
121 #include <errno.h>
122
123 #include <Cytore.hpp>
124 #include "Sources.h"
125
126 #include <CydiaSubstrate/CydiaSubstrate.h>
127 #include "Menes/Menes.h"
128
129 #include "CyteKit/IndirectDelegate.h"
130 #include "CyteKit/PerlCompatibleRegEx.hpp"
131 #include "CyteKit/TableViewCell.h"
132 #include "CyteKit/WebScriptObject-Cyte.h"
133 #include "CyteKit/WebViewController.h"
134 #include "CyteKit/WebViewTableViewCell.h"
135 #include "CyteKit/stringWithUTF8Bytes.h"
136
137 #include "Cydia/MIMEAddress.h"
138 #include "Cydia/LoadingViewController.h"
139 #include "Cydia/ProgressEvent.h"
140
141 #include "SDURLCache/SDURLCache.h"
142 /* }}} */
143
144 /* Profiler {{{ */
145 struct timeval _ltv;
146 bool _itv;
147
148 #define _timestamp ({ \
149 struct timeval tv; \
150 gettimeofday(&tv, NULL); \
151 tv.tv_sec * 1000000 + tv.tv_usec; \
152 })
153
154 typedef std::vector<class ProfileTime *> TimeList;
155 TimeList times_;
156
157 class ProfileTime {
158 private:
159 const char *name_;
160 uint64_t total_;
161 uint64_t count_;
162
163 public:
164 ProfileTime(const char *name) :
165 name_(name),
166 total_(0)
167 {
168 times_.push_back(this);
169 }
170
171 void AddTime(uint64_t time) {
172 total_ += time;
173 ++count_;
174 }
175
176 void Print() {
177 if (total_ != 0)
178 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
179 total_ = 0;
180 count_ = 0;
181 }
182 };
183
184 class ProfileTimer {
185 private:
186 ProfileTime &time_;
187 uint64_t start_;
188
189 public:
190 ProfileTimer(ProfileTime &time) :
191 time_(time),
192 start_(_timestamp)
193 {
194 }
195
196 ~ProfileTimer() {
197 time_.AddTime(_timestamp - start_);
198 }
199 };
200
201 void PrintTimes() {
202 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
203 (*i)->Print();
204 std::cerr << "========" << std::endl;
205 }
206
207 #define _profile(name) { \
208 static ProfileTime name(#name); \
209 ProfileTimer _ ## name(name);
210
211 #define _end }
212 /* }}} */
213
214 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
215 #define synchronized(lock) \
216 synchronized(static_cast<NSObject *>(lock))
217
218 extern NSString *Cydia_;
219
220 #define lprintf(args...) fprintf(stderr, args)
221
222 #define ForRelease 1
223 #define TraceLogging (1 && !ForRelease)
224 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
225 #define ProfileTimes (0 && !ForRelease)
226 #define ForSaurik (0 && !ForRelease)
227 #define LogBrowser (0 && !ForRelease)
228 #define TrackResize (0 && !ForRelease)
229 #define ManualRefresh (1 && !ForRelease)
230 #define ShowInternals (0 && !ForRelease)
231 #define AlwaysReload (0 && !ForRelease)
232
233 #if !TraceLogging
234 #undef _trace
235 #define _trace(args...)
236 #endif
237
238 #if !ProfileTimes
239 #undef _profile
240 #define _profile(name) {
241 #undef _end
242 #define _end }
243 #define PrintTimes() do {} while (false)
244 #endif
245
246 // Hash Functions/Structures {{{
247 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248
249 union SplitHash {
250 uint32_t u32;
251 uint16_t u16[2];
252 };
253 // }}}
254
255 static bool ShowPromoted_;
256
257 static NSString *Colon_;
258 NSString *Elision_;
259 static NSString *Error_;
260 static NSString *Warning_;
261
262 static bool AprilFools_;
263
264 static bool IsReachable(const char *name) {
265 SCNetworkReachabilityFlags flags; {
266 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
267 SCNetworkReachabilityGetFlags(reachability, &flags);
268 CFRelease(reachability);
269 }
270
271 // XXX: this elaborate mess is what Apple is using to determine this? :(
272 // XXX: do we care if the user has to intervene? maybe that's ok?
273 return
274 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
275 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
276 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
277 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
278 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
279 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
280 )
281 ;
282 }
283
284 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
285
286 static _finline NSString *CydiaURL(NSString *path) {
287 char page[26];
288 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
289 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
290 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
291 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
292 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
293 page[25] = '\0';
294 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
295 }
296
297 static void ReapZombie(pid_t pid) {
298 int status;
299 wait:
300 if (waitpid(pid, &status, 0) == -1)
301 if (errno == EINTR)
302 goto wait;
303 else _assert(false);
304 }
305
306 static _finline void UpdateExternalStatus(uint64_t newStatus) {
307 int notify_token;
308 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
309 notify_set_state(notify_token, newStatus);
310 notify_cancel(notify_token);
311 }
312 notify_post("com.saurik.Cydia.status");
313 }
314
315 static CGFloat CYStatusBarHeight() {
316 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
317 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
318 }
319
320 /* NSForcedOrderingSearch doesn't work on the iPhone */
321 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
322 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
323 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
324
325 /* Insertion Sort {{{ */
326
327 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
328 const char *ptr = (const char *)list;
329 while (0 < count) {
330 CFIndex half = count / 2;
331 const char *probe = ptr + elementSize * half;
332 CFComparisonResult cr = comparator(element, probe, context);
333 if (0 == cr) return (probe - (const char *)list) / elementSize;
334 ptr = (cr < 0) ? ptr : probe + elementSize;
335 count = (cr < 0) ? half : (half + (count & 1) - 1);
336 }
337 return (ptr - (const char *)list) / elementSize;
338 }
339
340 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
341 const char *ptr = (const char *)list;
342 while (0 < count) {
343 CFIndex half = count / 2;
344 const char *probe = ptr + elementSize * half;
345 CFComparisonResult cr = comparator(element, probe, context);
346 if (0 == cr) return (probe - (const char *)list) / elementSize;
347 ptr = (cr < 0) ? ptr : probe + elementSize;
348 count = (cr < 0) ? half : (half + (count & 1) - 1);
349 }
350 return (ptr - (const char *)list) / elementSize;
351 }
352
353 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
354 if (range.length == 0)
355 return;
356 const void **values(new const void *[range.length]);
357 CFArrayGetValues(array, range, values);
358
359 #if HistogramInsertionSort > 0
360 uint32_t total(0), *offsets(new uint32_t[range.length]);
361 #endif
362
363 for (CFIndex index(1); index != range.length; ++index) {
364 const void *value(values[index]);
365 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
366 CFIndex correct(index);
367 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
368 #if HistogramInsertionSort > 1
369 NSLog(@"%@ < %@", value, values[correct - 1]);
370 #endif
371 if (--correct == 0)
372 break;
373 }
374 if (correct != index) {
375 size_t offset(index - correct);
376 #if HistogramInsertionSort
377 total += offset;
378 ++offsets[offset];
379 if (offset > 10)
380 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
381 #endif
382 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
383 values[correct] = value;
384 }
385 }
386
387 CFArrayReplaceValues(array, range, values, range.length);
388 delete [] values;
389
390 #if HistogramInsertionSort > 0
391 for (CFIndex index(0); index != range.length; ++index)
392 if (offsets[index] != 0)
393 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
394 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
395 delete [] offsets;
396 #endif
397 }
398
399 /* }}} */
400
401 /* Apple Bug Fixes {{{ */
402 @implementation UIWebDocumentView (Cydia)
403
404 - (void) _setScrollerOffset:(CGPoint)offset {
405 UIScroller *scroller([self _scroller]);
406
407 CGSize size([scroller contentSize]);
408 CGSize bounds([scroller bounds].size);
409
410 CGPoint max;
411 max.x = size.width - bounds.width;
412 max.y = size.height - bounds.height;
413
414 // wtf Apple?!
415 if (max.x < 0)
416 max.x = 0;
417 if (max.y < 0)
418 max.y = 0;
419
420 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
421 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
422
423 [scroller setOffset:offset];
424 }
425
426 @end
427 /* }}} */
428
429 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
430 size_t length([self length] - state->state);
431 if (length <= 0)
432 return 0;
433 else if (length > count)
434 length = count;
435 for (size_t i(0); i != length; ++i)
436 objects[i] = [self item:state->state++];
437 state->itemsPtr = objects;
438 state->mutationsPtr = (unsigned long *) self;
439 return length;
440 }
441
442 /* Cydia NSString Additions {{{ */
443 @interface NSString (Cydia)
444 - (NSComparisonResult) compareByPath:(NSString *)other;
445 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
446 @end
447
448 @implementation NSString (Cydia)
449
450 - (NSComparisonResult) compareByPath:(NSString *)other {
451 NSString *prefix = [self commonPrefixWithString:other options:0];
452 size_t length = [prefix length];
453
454 NSRange lrange = NSMakeRange(length, [self length] - length);
455 NSRange rrange = NSMakeRange(length, [other length] - length);
456
457 lrange = [self rangeOfString:@"/" options:0 range:lrange];
458 rrange = [other rangeOfString:@"/" options:0 range:rrange];
459
460 NSComparisonResult value;
461
462 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
463 value = NSOrderedSame;
464 else if (lrange.location == NSNotFound)
465 value = NSOrderedAscending;
466 else if (rrange.location == NSNotFound)
467 value = NSOrderedDescending;
468 else
469 value = NSOrderedSame;
470
471 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
472 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
473 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
474 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
475
476 NSComparisonResult result = [lpath compare:rpath];
477 return result == NSOrderedSame ? value : result;
478 }
479
480 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
481 return [(id)CFURLCreateStringByAddingPercentEscapes(
482 kCFAllocatorDefault,
483 (CFStringRef) self,
484 NULL,
485 CFSTR(";/?:@&=+$,"),
486 kCFStringEncodingUTF8
487 ) autorelease];
488 }
489
490 @end
491 /* }}} */
492
493 /* C++ NSString Wrapper Cache {{{ */
494 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
495 return size == 0 ? NULL :
496 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
497 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
498 }
499
500 static _finline CFStringRef CYStringCreate(const char *data) {
501 return CYStringCreate(data, strlen(data));
502 }
503
504 class CYString {
505 private:
506 char *data_;
507 size_t size_;
508 CFStringRef cache_;
509
510 _finline void clear_() {
511 if (cache_ != NULL) {
512 CFRelease(cache_);
513 cache_ = NULL;
514 }
515 }
516
517 public:
518 _finline bool empty() const {
519 return size_ == 0;
520 }
521
522 _finline size_t size() const {
523 return size_;
524 }
525
526 _finline char *data() const {
527 return data_;
528 }
529
530 _finline void clear() {
531 size_ = 0;
532 clear_();
533 }
534
535 _finline CYString() :
536 data_(0),
537 size_(0),
538 cache_(NULL)
539 {
540 }
541
542 _finline ~CYString() {
543 clear_();
544 }
545
546 void operator =(const CYString &rhs) {
547 data_ = rhs.data_;
548 size_ = rhs.size_;
549
550 if (rhs.cache_ == nil)
551 cache_ = NULL;
552 else
553 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
554 }
555
556 void copy(apr_pool_t *pool) {
557 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
558 memcpy(temp, data_, size_);
559 temp[size_] = '\0';
560 data_ = temp;
561 }
562
563 void set(apr_pool_t *pool, const char *data, size_t size) {
564 if (size == 0)
565 clear();
566 else {
567 clear_();
568
569 data_ = const_cast<char *>(data);
570 size_ = size;
571
572 if (pool != NULL)
573 copy(pool);
574 }
575 }
576
577 _finline void set(apr_pool_t *pool, const char *data) {
578 set(pool, data, data == NULL ? 0 : strlen(data));
579 }
580
581 _finline void set(apr_pool_t *pool, const std::string &rhs) {
582 set(pool, rhs.data(), rhs.size());
583 }
584
585 bool operator ==(const CYString &rhs) const {
586 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
587 }
588
589 _finline operator CFStringRef() {
590 if (cache_ == NULL)
591 cache_ = CYStringCreate(data_, size_);
592 return cache_;
593 }
594
595 _finline operator id() {
596 return (NSString *) static_cast<CFStringRef>(*this);
597 }
598
599 _finline operator const char *() {
600 return reinterpret_cast<const char *>(data_);
601 }
602 };
603 /* }}} */
604 /* C++ NSString Algorithm Adapters {{{ */
605 extern "C" {
606 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
607 }
608
609 struct NSStringMapHash :
610 std::unary_function<NSString *, size_t>
611 {
612 _finline size_t operator ()(NSString *value) const {
613 return CFStringHashNSString((CFStringRef) value);
614 }
615 };
616
617 struct NSStringMapLess :
618 std::binary_function<NSString *, NSString *, bool>
619 {
620 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
621 return [lhs compare:rhs] == NSOrderedAscending;
622 }
623 };
624
625 struct NSStringMapEqual :
626 std::binary_function<NSString *, NSString *, bool>
627 {
628 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
629 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
630 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
631 //[lhs isEqualToString:rhs];
632 }
633 };
634 /* }}} */
635
636 /* CoreGraphics Primitives {{{ */
637 class CYColor {
638 private:
639 CGColorRef color_;
640
641 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
642 CGFloat color[] = {red, green, blue, alpha};
643 return CGColorCreate(space, color);
644 }
645
646 public:
647 CYColor() :
648 color_(NULL)
649 {
650 }
651
652 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
653 color_(Create_(space, red, green, blue, alpha))
654 {
655 Set(space, red, green, blue, alpha);
656 }
657
658 void Clear() {
659 if (color_ != NULL)
660 CGColorRelease(color_);
661 }
662
663 ~CYColor() {
664 Clear();
665 }
666
667 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
668 Clear();
669 color_ = Create_(space, red, green, blue, alpha);
670 }
671
672 operator CGColorRef() {
673 return color_;
674 }
675 };
676 /* }}} */
677
678 /* Random Global Variables {{{ */
679 static int PulseInterval_ = 500000;
680
681 static const NSString *UI_;
682
683 static int Finish_;
684 static bool RestartSubstrate_;
685 static NSArray *Finishes_;
686
687 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
688 #define NotifyConfig_ "/etc/notify.conf"
689
690 static bool Queuing_;
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 /* Confirmation Controller {{{ */
4769 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4770 if (!iterator.end())
4771 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4772 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4773 continue;
4774 pkgCache::PkgIterator package(dep.TargetPkg());
4775 if (package.end())
4776 continue;
4777 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4778 return true;
4779 }
4780
4781 return false;
4782 }
4783
4784 @protocol ConfirmationControllerDelegate
4785 - (void) cancelAndClear:(bool)clear;
4786 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4787 - (void) queue;
4788 @end
4789
4790 @interface ConfirmationController : CydiaWebViewController {
4791 _transient Database *database_;
4792
4793 _H<UIAlertView> essential_;
4794
4795 _H<NSDictionary> changes_;
4796 _H<NSMutableArray> issues_;
4797 _H<NSDictionary> sizes_;
4798
4799 BOOL substrate_;
4800 }
4801
4802 - (id) initWithDatabase:(Database *)database;
4803
4804 @end
4805
4806 @implementation ConfirmationController
4807
4808 - (void) complete {
4809 if (substrate_)
4810 RestartSubstrate_ = true;
4811 [delegate_ confirmWithNavigationController:[self navigationController]];
4812 }
4813
4814 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4815 NSString *context([alert context]);
4816
4817 if ([context isEqualToString:@"remove"]) {
4818 if (button == [alert cancelButtonIndex])
4819 [self dismissModalViewControllerAnimated:YES];
4820 else if (button == [alert firstOtherButtonIndex]) {
4821 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4822 }
4823
4824 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4825 } else if ([context isEqualToString:@"unable"]) {
4826 [self dismissModalViewControllerAnimated:YES];
4827 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4828 } else {
4829 [super alertView:alert clickedButtonAtIndex:button];
4830 }
4831 }
4832
4833 - (void) _doContinue {
4834 [delegate_ cancelAndClear:NO];
4835 [self dismissModalViewControllerAnimated:YES];
4836 }
4837
4838 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4839 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4840 return nil;
4841 }
4842
4843 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4844 [super webView:view didClearWindowObject:window forFrame:frame];
4845
4846 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4847 (id) changes_, @"changes",
4848 (id) issues_, @"issues",
4849 (id) sizes_, @"sizes",
4850 self, @"queue",
4851 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4852 }
4853
4854 - (id) initWithDatabase:(Database *)database {
4855 if ((self = [super init]) != nil) {
4856 database_ = database;
4857
4858 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4859 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4860 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4861 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4862 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4863
4864 bool remove(false);
4865
4866 pkgCacheFile &cache([database_ cache]);
4867 NSArray *packages([database_ packages]);
4868 pkgDepCache::Policy *policy([database_ policy]);
4869
4870 issues_ = [NSMutableArray arrayWithCapacity:4];
4871
4872 for (Package *package in packages) {
4873 pkgCache::PkgIterator iterator([package iterator]);
4874 NSString *name([package id]);
4875
4876 if ([package broken]) {
4877 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4878
4879 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4880 name, @"package",
4881 reasons, @"reasons",
4882 nil]];
4883
4884 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4885 if (ver.end())
4886 continue;
4887
4888 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4889 pkgCache::DepIterator start;
4890 pkgCache::DepIterator end;
4891 dep.GlobOr(start, end); // ++dep
4892
4893 if (!cache->IsImportantDep(end))
4894 continue;
4895 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4896 continue;
4897
4898 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4899
4900 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4901 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4902 clauses, @"clauses",
4903 nil]];
4904
4905 _forever {
4906 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4907
4908 pkgCache::PkgIterator target(start.TargetPkg());
4909 if (target->ProvidesList != 0)
4910 reason = @"missing";
4911 else {
4912 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4913 if (!ver.end()) {
4914 reason = @"installed";
4915 installed = [NSString stringWithUTF8String:ver.VerStr()];
4916 } else if (!cache[target].CandidateVerIter(cache).end())
4917 reason = @"uninstalled";
4918 else if (target->ProvidesList == 0)
4919 reason = @"uninstallable";
4920 else
4921 reason = @"virtual";
4922 }
4923
4924 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4925 [NSString stringWithUTF8String:start.CompType()], @"operator",
4926 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4927 nil]);
4928
4929 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4930 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4931 version, @"version",
4932 reason, @"reason",
4933 installed, @"installed",
4934 nil]];
4935
4936 // yes, seriously. (wtf?)
4937 if (start == end)
4938 break;
4939 ++start;
4940 }
4941 }
4942 }
4943
4944 pkgDepCache::StateCache &state(cache[iterator]);
4945
4946 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4947
4948 if (state.NewInstall())
4949 [installs addObject:name];
4950 // XXX: else if (state.Install())
4951 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4952 [reinstalls addObject:name];
4953 // XXX: move before previous if
4954 else if (state.Upgrade())
4955 [upgrades addObject:name];
4956 else if (state.Downgrade())
4957 [downgrades addObject:name];
4958 else if (!state.Delete())
4959 // XXX: _assert(state.Keep());
4960 continue;
4961 else if (special_r(name))
4962 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4963 [NSNull null], @"package",
4964 [NSArray arrayWithObjects:
4965 [NSDictionary dictionaryWithObjectsAndKeys:
4966 @"Conflicts", @"relationship",
4967 [NSArray arrayWithObjects:
4968 [NSDictionary dictionaryWithObjectsAndKeys:
4969 name, @"package",
4970 [NSNull null], @"version",
4971 @"installed", @"reason",
4972 nil],
4973 nil], @"clauses",
4974 nil],
4975 nil], @"reasons",
4976 nil]];
4977 else {
4978 if ([package essential])
4979 remove = true;
4980 [removes addObject:name];
4981 }
4982
4983 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4984 substrate_ |= DepSubstrate(iterator.CurrentVer());
4985 }
4986
4987 if (!remove)
4988 essential_ = nil;
4989 else if (Advanced_) {
4990 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4991
4992 essential_ = [[[UIAlertView alloc]
4993 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4994 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4995 delegate:self
4996 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4997 otherButtonTitles:
4998 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4999 nil
5000 ] autorelease];
5001
5002 [essential_ setContext:@"remove"];
5003 [essential_ setNumberOfRows:2];
5004 } else {
5005 essential_ = [[[UIAlertView alloc]
5006 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5007 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5008 delegate:self
5009 cancelButtonTitle:UCLocalize("OKAY")
5010 otherButtonTitles:nil
5011 ] autorelease];
5012
5013 [essential_ setContext:@"unable"];
5014 }
5015
5016 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5017 installs, @"installs",
5018 reinstalls, @"reinstalls",
5019 upgrades, @"upgrades",
5020 downgrades, @"downgrades",
5021 removes, @"removes",
5022 nil];
5023
5024 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5025 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5026 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5027 nil];
5028
5029 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5030 } return self;
5031 }
5032
5033 - (UIBarButtonItem *) leftButton {
5034 return [[[UIBarButtonItem alloc]
5035 initWithTitle:UCLocalize("CANCEL")
5036 style:UIBarButtonItemStylePlain
5037 target:self
5038 action:@selector(cancelButtonClicked)
5039 ] autorelease];
5040 }
5041
5042 #if !AlwaysReload
5043 - (void) applyRightButton {
5044 if ([issues_ count] == 0 && ![self isLoading])
5045 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5046 initWithTitle:UCLocalize("CONFIRM")
5047 style:UIBarButtonItemStyleDone
5048 target:self
5049 action:@selector(confirmButtonClicked)
5050 ] autorelease]];
5051 else
5052 [[self navigationItem] setRightBarButtonItem:nil];
5053 }
5054 #endif
5055
5056 - (void) cancelButtonClicked {
5057 [delegate_ cancelAndClear:YES];
5058 [self dismissModalViewControllerAnimated:YES];
5059 }
5060
5061 #if !AlwaysReload
5062 - (void) confirmButtonClicked {
5063 if (essential_ != nil)
5064 [essential_ show];
5065 else
5066 [self complete];
5067 }
5068 #endif
5069
5070 @end
5071 /* }}} */
5072
5073 /* Progress Data {{{ */
5074 @interface CydiaProgressData : NSObject {
5075 _transient id delegate_;
5076
5077 bool running_;
5078 float percent_;
5079
5080 float current_;
5081 float total_;
5082 float speed_;
5083
5084 _H<NSMutableArray> events_;
5085 _H<NSString> title_;
5086
5087 _H<NSString> status_;
5088 _H<NSString> finish_;
5089 }
5090
5091 @end
5092
5093 @implementation CydiaProgressData
5094
5095 + (NSArray *) _attributeKeys {
5096 return [NSArray arrayWithObjects:
5097 @"current",
5098 @"events",
5099 @"finish",
5100 @"percent",
5101 @"running",
5102 @"speed",
5103 @"title",
5104 @"total",
5105 nil];
5106 }
5107
5108 - (NSArray *) attributeKeys {
5109 return [[self class] _attributeKeys];
5110 }
5111
5112 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5113 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5114 }
5115
5116 - (id) init {
5117 if ((self = [super init]) != nil) {
5118 events_ = [NSMutableArray arrayWithCapacity:32];
5119 } return self;
5120 }
5121
5122 - (void) setDelegate:(id)delegate {
5123 delegate_ = delegate;
5124 }
5125
5126 - (void) setPercent:(float)value {
5127 percent_ = value;
5128 }
5129
5130 - (NSNumber *) percent {
5131 return [NSNumber numberWithFloat:percent_];
5132 }
5133
5134 - (void) setCurrent:(float)value {
5135 current_ = value;
5136 }
5137
5138 - (NSNumber *) current {
5139 return [NSNumber numberWithFloat:current_];
5140 }
5141
5142 - (void) setTotal:(float)value {
5143 total_ = value;
5144 }
5145
5146 - (NSNumber *) total {
5147 return [NSNumber numberWithFloat:total_];
5148 }
5149
5150 - (void) setSpeed:(float)value {
5151 speed_ = value;
5152 }
5153
5154 - (NSNumber *) speed {
5155 return [NSNumber numberWithFloat:speed_];
5156 }
5157
5158 - (NSArray *) events {
5159 return events_;
5160 }
5161
5162 - (void) removeAllEvents {
5163 [events_ removeAllObjects];
5164 }
5165
5166 - (void) addEvent:(CydiaProgressEvent *)event {
5167 [events_ addObject:event];
5168 }
5169
5170 - (void) setTitle:(NSString *)text {
5171 title_ = text;
5172 }
5173
5174 - (NSString *) title {
5175 return title_;
5176 }
5177
5178 - (void) setFinish:(NSString *)text {
5179 finish_ = text;
5180 }
5181
5182 - (NSString *) finish {
5183 return (id) finish_ ?: [NSNull null];
5184 }
5185
5186 - (void) setRunning:(bool)running {
5187 running_ = running;
5188 }
5189
5190 - (NSNumber *) running {
5191 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5192 }
5193
5194 @end
5195 /* }}} */
5196 /* Progress Controller {{{ */
5197 @interface ProgressController : CydiaWebViewController <
5198 ProgressDelegate
5199 > {
5200 _transient Database *database_;
5201 _H<CydiaProgressData, 1> progress_;
5202 unsigned cancel_;
5203 }
5204
5205 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5206
5207 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5208
5209 - (void) setTitle:(NSString *)title;
5210 - (void) setCancellable:(bool)cancellable;
5211
5212 @end
5213
5214 @implementation ProgressController
5215
5216 - (void) dealloc {
5217 [database_ setProgressDelegate:nil];
5218 [super dealloc];
5219 }
5220
5221 - (UIBarButtonItem *) leftButton {
5222 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5223 initWithTitle:UCLocalize("CANCEL")
5224 style:UIBarButtonItemStylePlain
5225 target:self
5226 action:@selector(cancel)
5227 ] autorelease] : nil;
5228 }
5229
5230 - (void) updateCancel {
5231 [super applyLeftButton];
5232 }
5233
5234 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5235 if ((self = [super init]) != nil) {
5236 database_ = database;
5237 delegate_ = delegate;
5238
5239 [database_ setProgressDelegate:self];
5240
5241 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5242 [progress_ setDelegate:self];
5243
5244 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5245
5246 [scroller_ setBackgroundColor:[UIColor blackColor]];
5247
5248 [[self navigationItem] setHidesBackButton:YES];
5249
5250 [self updateCancel];
5251 } return self;
5252 }
5253
5254 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5255 [super webView:view didClearWindowObject:window forFrame:frame];
5256 [window setValue:progress_ forKey:@"cydiaProgress"];
5257 }
5258
5259 - (void) updateProgress {
5260 [self dispatchEvent:@"CydiaProgressUpdate"];
5261 }
5262
5263 - (void) viewWillAppear:(BOOL)animated {
5264 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5265 [super viewWillAppear:animated];
5266 }
5267
5268 - (void) reloadSpringBoard {
5269 pid_t pid(ExecFork());
5270 if (pid == 0) {
5271 pid_t pid(ExecFork());
5272 if (pid == 0) {
5273 execl("/usr/bin/sbreload", "sbreload", NULL);
5274 perror("sbreload");
5275 exit(0);
5276 }
5277
5278 exit(0);
5279 }
5280
5281 ReapZombie(pid);
5282
5283 sleep(15);
5284 system("/usr/bin/killall SpringBoard");
5285 }
5286
5287 - (void) close {
5288 UpdateExternalStatus(0);
5289
5290 if (Finish_ > 1)
5291 [delegate_ saveState];
5292
5293 switch (Finish_) {
5294 case 0:
5295 [delegate_ returnToCydia];
5296 break;
5297
5298 case 1:
5299 [delegate_ terminateWithSuccess];
5300 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5301 [delegate_ suspendWithAnimation:YES];
5302 else
5303 [delegate_ suspend];*/
5304 break;
5305
5306 case 2:
5307 _trace();
5308 goto reload;
5309
5310 case 3:
5311 _trace();
5312 goto reload;
5313
5314 reload: {
5315 UIProgressHUD *hud([delegate_ addProgressHUD]);
5316 [hud setText:UCLocalize("LOADING")];
5317 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5318 return;
5319 }
5320
5321 case 4:
5322 _trace();
5323 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5324 SBReboot(SBSSpringBoardServerPort());
5325 else
5326 reboot2(RB_AUTOBOOT);
5327 break;
5328 }
5329
5330 [super close];
5331 }
5332
5333 - (void) setTitle:(NSString *)title {
5334 [progress_ setTitle:title];
5335 [self updateProgress];
5336 }
5337
5338 - (UIBarButtonItem *) rightButton {
5339 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5340 initWithTitle:UCLocalize("CLOSE")
5341 style:UIBarButtonItemStylePlain
5342 target:self
5343 action:@selector(close)
5344 ] autorelease];
5345 }
5346
5347 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5348 UpdateExternalStatus(1);
5349
5350 [progress_ setRunning:true];
5351 [self setTitle:title];
5352 // implicit updateProgress
5353
5354 SHA1SumValue notifyconf; {
5355 FileFd file;
5356 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5357 _error->Discard();
5358 else {
5359 MMap mmap(file, MMap::ReadOnly);
5360 SHA1Summation sha1;
5361 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5362 notifyconf = sha1.Result();
5363 }
5364 }
5365
5366 SHA1SumValue springlist; {
5367 FileFd file;
5368 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5369 _error->Discard();
5370 else {
5371 MMap mmap(file, MMap::ReadOnly);
5372 SHA1Summation sha1;
5373 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5374 springlist = sha1.Result();
5375 }
5376 }
5377
5378 if (invocation != nil) {
5379 [invocation yieldToSelector:@selector(invoke)];
5380 [self setTitle:@"COMPLETE"];
5381 }
5382
5383 if (Finish_ < 4) {
5384 FileFd file;
5385 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5386 _error->Discard();
5387 else {
5388 MMap mmap(file, MMap::ReadOnly);
5389 SHA1Summation sha1;
5390 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5391 if (!(notifyconf == sha1.Result()))
5392 Finish_ = 4;
5393 }
5394 }
5395
5396 if (Finish_ < 3) {
5397 FileFd file;
5398 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5399 _error->Discard();
5400 else {
5401 MMap mmap(file, MMap::ReadOnly);
5402 SHA1Summation sha1;
5403 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5404 if (!(springlist == sha1.Result()))
5405 Finish_ = 3;
5406 }
5407 }
5408
5409 if (Finish_ < 2) {
5410 if (RestartSubstrate_)
5411 Finish_ = 2;
5412 }
5413
5414 RestartSubstrate_ = false;
5415
5416 switch (Finish_) {
5417 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5418 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5419 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5420 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5421 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5422 }
5423
5424 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5425
5426 [progress_ setRunning:false];
5427 [self updateProgress];
5428
5429 [self applyRightButton];
5430 }
5431
5432 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5433 [progress_ addEvent:event];
5434 [self updateProgress];
5435 }
5436
5437 - (bool) isProgressCancelled {
5438 return cancel_ == 2;
5439 }
5440
5441 - (void) cancel {
5442 cancel_ = 2;
5443 [self updateCancel];
5444 }
5445
5446 - (void) setCancellable:(bool)cancellable {
5447 unsigned cancel(cancel_);
5448
5449 if (!cancellable)
5450 cancel_ = 0;
5451 else if (cancel_ == 0)
5452 cancel_ = 1;
5453
5454 if (cancel != cancel_)
5455 [self updateCancel];
5456 }
5457
5458 - (void) setProgressCancellable:(NSNumber *)cancellable {
5459 [self setCancellable:[cancellable boolValue]];
5460 }
5461
5462 - (void) setProgressPercent:(NSNumber *)percent {
5463 [progress_ setPercent:[percent floatValue]];
5464 [self updateProgress];
5465 }
5466
5467 - (void) setProgressStatus:(NSDictionary *)status {
5468 if (status == nil) {
5469 [progress_ setCurrent:0];
5470 [progress_ setTotal:0];
5471 [progress_ setSpeed:0];
5472 } else {
5473 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5474
5475 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5476 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5477 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5478 }
5479
5480 [self updateProgress];
5481 }
5482
5483 @end
5484 /* }}} */
5485
5486 /* Package Cell {{{ */
5487 @interface PackageCell : CyteTableViewCell <
5488 CyteTableViewCellDelegate
5489 > {
5490 _H<UIImage> icon_;
5491 _H<NSString> name_;
5492 _H<NSString> description_;
5493 bool commercial_;
5494 _H<NSString> source_;
5495 _H<UIImage> badge_;
5496 _H<UIImage> placard_;
5497 }
5498
5499 - (PackageCell *) init;
5500 - (void) setPackage:(Package *)package;
5501
5502 - (void) drawContentRect:(CGRect)rect;
5503
5504 @end
5505
5506 @implementation PackageCell
5507
5508 - (PackageCell *) init {
5509 CGRect frame(CGRectMake(0, 0, 320, 74));
5510 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5511 UIView *content([self contentView]);
5512 CGRect bounds([content bounds]);
5513
5514 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5515 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5516 [content addSubview:content_];
5517
5518 [content_ setDelegate:self];
5519 [content_ setOpaque:YES];
5520 } return self;
5521 }
5522
5523 - (NSString *) accessibilityLabel {
5524 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5525 }
5526
5527 - (void) setPackage:(Package *)package {
5528 icon_ = nil;
5529 name_ = nil;
5530 description_ = nil;
5531 source_ = nil;
5532 badge_ = nil;
5533 placard_ = nil;
5534
5535 if (package == nil)
5536 [content_ setBackgroundColor:[UIColor whiteColor]];
5537 else {
5538 [package parse];
5539
5540 Source *source = [package source];
5541
5542 icon_ = [package icon];
5543
5544 if (NSString *name = [package name])
5545 name_ = [NSString stringWithString:name];
5546
5547 NSString *description(nil);
5548
5549 if (description == nil && IsWildcat_)
5550 description = [package longDescription];
5551 if (description == nil)
5552 description = [package shortDescription];
5553
5554 if (description != nil)
5555 description_ = [NSString stringWithString:description];
5556
5557 commercial_ = [package isCommercial];
5558
5559 NSString *label = nil;
5560 bool trusted = false;
5561
5562 if (source != nil) {
5563 label = [source label];
5564 trusted = [source trusted];
5565 } else if ([[package id] isEqualToString:@"firmware"])
5566 label = UCLocalize("APPLE");
5567 else
5568 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5569
5570 NSString *from(label);
5571
5572 NSString *section = [package simpleSection];
5573 if (section != nil && ![section isEqualToString:label]) {
5574 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5575 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5576 }
5577
5578 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5579
5580 if (NSString *purpose = [package primaryPurpose])
5581 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5582
5583 UIColor *color;
5584 NSString *placard;
5585
5586 if (NSString *mode = [package mode]) {
5587 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5588 color = RemovingColor_;
5589 //placard = @"removing";
5590 } else {
5591 color = InstallingColor_;
5592 //placard = @"installing";
5593 }
5594
5595 // XXX: the removing/installing placards are not @2x
5596 placard = nil;
5597 } else {
5598 color = [UIColor whiteColor];
5599
5600 if ([package installed] != nil)
5601 placard = @"installed";
5602 else
5603 placard = nil;
5604 }
5605
5606 [content_ setBackgroundColor:color];
5607
5608 if (placard != nil)
5609 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5610 }
5611
5612 [self setNeedsDisplay];
5613 [content_ setNeedsDisplay];
5614 }
5615
5616 - (void) drawContentRect:(CGRect)rect {
5617 bool highlighted(highlighted_);
5618 float width([self bounds].size.width);
5619
5620 if (icon_ != nil) {
5621 CGRect rect;
5622 rect.size = [(UIImage *) icon_ size];
5623
5624 while (rect.size.width > 32 || rect.size.height > 32) {
5625 rect.size.width /= 2;
5626 rect.size.height /= 2;
5627 }
5628
5629 rect.origin.x = 25 - rect.size.width / 2;
5630 rect.origin.y = 25 - rect.size.height / 2;
5631
5632 [icon_ drawInRect:rect];
5633 }
5634
5635 if (badge_ != nil) {
5636 CGRect rect;
5637 rect.size = [(UIImage *) badge_ size];
5638
5639 rect.size.width /= 2;
5640 rect.size.height /= 2;
5641
5642 rect.origin.x = 36 - rect.size.width / 2;
5643 rect.origin.y = 36 - rect.size.height / 2;
5644
5645 [badge_ drawInRect:rect];
5646 }
5647
5648 if (highlighted)
5649 UISetColor(White_);
5650
5651 if (!highlighted)
5652 UISetColor(commercial_ ? Purple_ : Black_);
5653 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5654 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5655
5656 if (!highlighted)
5657 UISetColor(commercial_ ? Purplish_ : Gray_);
5658 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5659
5660 if (placard_ != nil)
5661 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5662 }
5663
5664 @end
5665 /* }}} */
5666 /* Section Cell {{{ */
5667 @interface SectionCell : CyteTableViewCell <
5668 CyteTableViewCellDelegate
5669 > {
5670 _H<NSString> basic_;
5671 _H<NSString> section_;
5672 _H<NSString> name_;
5673 _H<NSString> count_;
5674 _H<UIImage> icon_;
5675 _H<UISwitch> switch_;
5676 BOOL editing_;
5677 }
5678
5679 - (void) setSection:(Section *)section editing:(BOOL)editing;
5680
5681 @end
5682
5683 @implementation SectionCell
5684
5685 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5686 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5687 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5688 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5689 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5690
5691 UIView *content([self contentView]);
5692 CGRect bounds([content bounds]);
5693
5694 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5695 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5696 [content addSubview:content_];
5697 [content_ setBackgroundColor:[UIColor whiteColor]];
5698
5699 [content_ setDelegate:self];
5700 } return self;
5701 }
5702
5703 - (void) onSwitch:(id)sender {
5704 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5705 if (metadata == nil) {
5706 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5707 [Sections_ setObject:metadata forKey:basic_];
5708 }
5709
5710 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5711 Changed_ = true;
5712 }
5713
5714 - (void) setSection:(Section *)section editing:(BOOL)editing {
5715 if (editing != editing_) {
5716 if (editing_)
5717 [switch_ removeFromSuperview];
5718 else
5719 [self addSubview:switch_];
5720 editing_ = editing;
5721 }
5722
5723 basic_ = nil;
5724 section_ = nil;
5725 name_ = nil;
5726 count_ = nil;
5727
5728 if (section == nil) {
5729 name_ = UCLocalize("ALL_PACKAGES");
5730 count_ = nil;
5731 } else {
5732 basic_ = [section name];
5733 section_ = [section localized];
5734
5735 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5736 count_ = [NSString stringWithFormat:@"%d", [section count]];
5737
5738 if (editing_)
5739 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5740 }
5741
5742 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5743 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5744
5745 [content_ setNeedsDisplay];
5746 }
5747
5748 - (void) setFrame:(CGRect)frame {
5749 [super setFrame:frame];
5750
5751 CGRect rect([switch_ frame]);
5752 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5753 }
5754
5755 - (NSString *) accessibilityLabel {
5756 return name_;
5757 }
5758
5759 - (void) drawContentRect:(CGRect)rect {
5760 bool highlighted(highlighted_ && !editing_);
5761
5762 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5763
5764 if (highlighted)
5765 UISetColor(White_);
5766
5767 float width(rect.size.width);
5768 if (editing_)
5769 width -= 87;
5770
5771 if (!highlighted)
5772 UISetColor(Black_);
5773 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5774
5775 CGSize size = [count_ sizeWithFont:Font14_];
5776
5777 UISetColor(White_);
5778 if (count_ != nil)
5779 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5780 }
5781
5782 @end
5783 /* }}} */
5784
5785 /* File Table {{{ */
5786 @interface FileTable : CyteViewController <
5787 UITableViewDataSource,
5788 UITableViewDelegate
5789 > {
5790 _transient Database *database_;
5791 _H<Package> package_;
5792 _H<NSString> name_;
5793 _H<NSMutableArray> files_;
5794 _H<UITableView, 2> list_;
5795 }
5796
5797 - (id) initWithDatabase:(Database *)database;
5798 - (void) setPackage:(Package *)package;
5799
5800 @end
5801
5802 @implementation FileTable
5803
5804 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5805 return files_ == nil ? 0 : [files_ count];
5806 }
5807
5808 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5809 return 24.0f;
5810 }*/
5811
5812 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5813 static NSString *reuseIdentifier = @"Cell";
5814
5815 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5816 if (cell == nil) {
5817 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5818 [cell setFont:[UIFont systemFontOfSize:16]];
5819 }
5820 [cell setText:[files_ objectAtIndex:indexPath.row]];
5821 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5822
5823 return cell;
5824 }
5825
5826 - (NSURL *) navigationURL {
5827 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5828 }
5829
5830 - (void) loadView {
5831 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5832 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5833 [list_ setRowHeight:24.0f];
5834 [(UITableView *) list_ setDataSource:self];
5835 [list_ setDelegate:self];
5836 [self setView:list_];
5837 }
5838
5839 - (void) viewDidLoad {
5840 [super viewDidLoad];
5841
5842 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5843 }
5844
5845 - (void) releaseSubviews {
5846 list_ = nil;
5847
5848 package_ = nil;
5849 files_ = nil;
5850
5851 [super releaseSubviews];
5852 }
5853
5854 - (id) initWithDatabase:(Database *)database {
5855 if ((self = [super init]) != nil) {
5856 database_ = database;
5857 } return self;
5858 }
5859
5860 - (void) setPackage:(Package *)package {
5861 package_ = nil;
5862 name_ = nil;
5863
5864 files_ = [NSMutableArray arrayWithCapacity:32];
5865
5866 if (package != nil) {
5867 package_ = package;
5868 name_ = [package id];
5869
5870 if (NSArray *files = [package files])
5871 [files_ addObjectsFromArray:files];
5872
5873 if ([files_ count] != 0) {
5874 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5875 [files_ removeObjectAtIndex:0];
5876 [files_ sortUsingSelector:@selector(compareByPath:)];
5877
5878 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5879 [stack addObject:@"/"];
5880
5881 for (int i(0), e([files_ count]); i != e; ++i) {
5882 NSString *file = [files_ objectAtIndex:i];
5883 while (![file hasPrefix:[stack lastObject]])
5884 [stack removeLastObject];
5885 NSString *directory = [stack lastObject];
5886 [stack addObject:[file stringByAppendingString:@"/"]];
5887 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5888 ([stack count] - 2) * 3, "",
5889 [file substringFromIndex:[directory length]]
5890 ]];
5891 }
5892 }
5893 }
5894
5895 [list_ reloadData];
5896 }
5897
5898 - (void) reloadData {
5899 [super reloadData];
5900
5901 [self setPackage:[database_ packageWithName:name_]];
5902 }
5903
5904 @end
5905 /* }}} */
5906 /* Package Controller {{{ */
5907 @interface CYPackageController : CydiaWebViewController <
5908 UIActionSheetDelegate
5909 > {
5910 _transient Database *database_;
5911 _H<Package> package_;
5912 _H<NSString> name_;
5913 bool commercial_;
5914 _H<NSMutableArray> buttons_;
5915 _H<UIBarButtonItem> button_;
5916 }
5917
5918 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5919
5920 @end
5921
5922 @implementation CYPackageController
5923
5924 - (NSURL *) navigationURL {
5925 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5926 }
5927
5928 /* XXX: this is not safe at all... localization of /fail/ */
5929 - (void) _clickButtonWithName:(NSString *)name {
5930 if ([name isEqualToString:UCLocalize("CLEAR")])
5931 [delegate_ clearPackage:package_];
5932 else if ([name isEqualToString:UCLocalize("INSTALL")])
5933 [delegate_ installPackage:package_];
5934 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5935 [delegate_ installPackage:package_];
5936 else if ([name isEqualToString:UCLocalize("REMOVE")])
5937 [delegate_ removePackage:package_];
5938 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5939 [delegate_ installPackage:package_];
5940 else _assert(false);
5941 }
5942
5943 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5944 NSString *context([sheet context]);
5945
5946 if ([context isEqualToString:@"modify"]) {
5947 if (button != [sheet cancelButtonIndex]) {
5948 NSString *buttonName = [buttons_ objectAtIndex:button];
5949 [self _clickButtonWithName:buttonName];
5950 }
5951
5952 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5953 }
5954 }
5955
5956 - (bool) _allowJavaScriptPanel {
5957 return commercial_;
5958 }
5959
5960 #if !AlwaysReload
5961 - (void) _customButtonClicked {
5962 int count([buttons_ count]);
5963 if (count == 0)
5964 return;
5965
5966 if (count == 1)
5967 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5968 else {
5969 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5970 [buttons addObjectsFromArray:buttons_];
5971
5972 UIActionSheet *sheet = [[[UIActionSheet alloc]
5973 initWithTitle:nil
5974 delegate:self
5975 cancelButtonTitle:nil
5976 destructiveButtonTitle:nil
5977 otherButtonTitles:nil
5978 ] autorelease];
5979
5980 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5981 if (!IsWildcat_) {
5982 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5983 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5984 }
5985 [sheet setContext:@"modify"];
5986
5987 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5988 }
5989 }
5990
5991 // We don't want to allow non-commercial packages to do custom things to the install button,
5992 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5993 - (void) customButtonClicked {
5994 if (commercial_)
5995 [super customButtonClicked];
5996 else
5997 [self _customButtonClicked];
5998 }
5999
6000 - (void) reloadButtonClicked {
6001 // Don't reload a commerical package by tapping the loading button,
6002 // but if it's not an Install button, we should forward it on.
6003 if (![package_ uninstalled])
6004 [self _customButtonClicked];
6005 }
6006
6007 - (void) applyLoadingTitle {
6008 // Don't show "Loading" as the title. Ever.
6009 }
6010
6011 - (UIBarButtonItem *) rightButton {
6012 return button_;
6013 }
6014 #endif
6015
6016 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6017 if ((self = [super init]) != nil) {
6018 database_ = database;
6019 buttons_ = [NSMutableArray arrayWithCapacity:4];
6020 name_ = name == nil ? @"" : [NSString stringWithString:name];
6021 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6022 } return self;
6023 }
6024
6025 - (void) reloadData {
6026 [super reloadData];
6027
6028 package_ = [database_ packageWithName:name_];
6029
6030 [buttons_ removeAllObjects];
6031
6032 if (package_ != nil) {
6033 [(Package *) package_ parse];
6034
6035 commercial_ = [package_ isCommercial];
6036
6037 if ([package_ mode] != nil)
6038 [buttons_ addObject:UCLocalize("CLEAR")];
6039 if ([package_ source] == nil);
6040 else if ([package_ upgradableAndEssential:NO])
6041 [buttons_ addObject:UCLocalize("UPGRADE")];
6042 else if ([package_ uninstalled])
6043 [buttons_ addObject:UCLocalize("INSTALL")];
6044 else
6045 [buttons_ addObject:UCLocalize("REINSTALL")];
6046 if (![package_ uninstalled])
6047 [buttons_ addObject:UCLocalize("REMOVE")];
6048 }
6049
6050 NSString *title;
6051 switch ([buttons_ count]) {
6052 case 0: title = nil; break;
6053 case 1: title = [buttons_ objectAtIndex:0]; break;
6054 default: title = UCLocalize("MODIFY"); break;
6055 }
6056
6057 button_ = [[[UIBarButtonItem alloc]
6058 initWithTitle:title
6059 style:UIBarButtonItemStylePlain
6060 target:self
6061 action:@selector(customButtonClicked)
6062 ] autorelease];
6063 }
6064
6065 - (bool) isLoading {
6066 return commercial_ ? [super isLoading] : false;
6067 }
6068
6069 @end
6070 /* }}} */
6071
6072 /* Package List Controller {{{ */
6073
6074 // This is used to sort the filters. We want this to ensure that the
6075 // cheapest filters run first. This is probably a premature optimization.
6076 typedef enum {
6077 kPackageListFilterPriorityLow,
6078 kPackageListFilterPriorityNormal,
6079 kPackageListFilterPriorityHigh
6080 } PackageListFilterPriority;
6081
6082 typedef struct {
6083 SEL selector;
6084 id object;
6085 PackageListFilterPriority priority;
6086 IMP implementation;
6087 } PackageListFilter;
6088
6089 @interface NSValue(PackageListFilter)
6090
6091 + (id)valueWithPackageListFilter:(PackageListFilter)filter;
6092 - (PackageListFilter)packageListFilterValue;
6093
6094 @end
6095
6096 @implementation NSValue(PackageListFilter)
6097
6098 + (id)valueWithPackageListFilter:(PackageListFilter)filter {
6099 return [NSValue valueWithBytes:&filter objCType:@encode(PackageListFilter)];
6100 }
6101
6102 - (PackageListFilter)packageListFilterValue {
6103 PackageListFilter filter;
6104 [self getValue:&filter];
6105 return filter;
6106 }
6107
6108 @end
6109
6110 @interface FilteredPackageListDataSource : NSObject <UITableViewDataSource> {
6111 _transient Database *database_;
6112 unsigned era_;
6113 _H<NSArray> packages_;
6114 _H<NSMutableArray> sections_;
6115 _H<NSMutableArray> index_;
6116 _H<NSMutableDictionary> indices_;
6117 _H<NSMutableDictionary> filters_;
6118 }
6119
6120 - (id)objectForFilter:(NSString *)filter;
6121 - (void)setObject:(id)object forFilter:(NSString *)filter;
6122 - (SEL)selectorForFilter:(NSString *)filter;
6123 - (void)setSelector:(SEL)selector forFilter:(NSString *)filter;
6124 - (PackageListFilterPriority)priorityForFilter:(NSString *)filter;
6125 - (void)setPriority:(PackageListFilterPriority)priority forFilter:(NSString *)filter;
6126
6127 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector;
6128 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector priority:(PackageListFilterPriority)priority;
6129 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector priority:(PackageListFilterPriority)priority object:(id)object;
6130 - (void)removeFilter:(NSString *)filter;
6131
6132 @end
6133
6134 @implementation FilteredPackageListDataSource
6135
6136 - (id) initWithDatabase:(Database *)database {
6137 if ((self = [super init]) != nil) {
6138 database_ = database;
6139 filters_ = [NSMutableDictionary dictionary];
6140 } return self;
6141 }
6142
6143 + (BOOL) supportsSearch {
6144 return YES;
6145 }
6146
6147 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6148 @synchronized (database_) {
6149 if ([database_ era] != era_)
6150 return nil;
6151
6152 Section *section([sections_ objectAtIndex:[path section]]);
6153 NSInteger row([path row]);
6154 Package *package([packages_ objectAtIndex:([section row] + row)]);
6155 return [[package retain] autorelease];
6156 } }
6157
6158 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6159 if ([[self class] supportsSearch])
6160 return [[NSArray arrayWithObject:UITableViewIndexSearch] arrayByAddingObjectsFromArray:index_];
6161 else
6162 return index_;
6163 }
6164
6165 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6166 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6167 if (cell == nil)
6168 cell = [[[PackageCell alloc] init] autorelease];
6169
6170 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6171 [cell setPackage:package];
6172 return cell;
6173 }
6174
6175 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6176 NSInteger count([sections_ count]);
6177 return count == 0 ? 1 : count;
6178 }
6179
6180 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6181 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6182 return nil;
6183 return [[sections_ objectAtIndex:section] name];
6184 }
6185
6186 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6187 if ([sections_ count] == 0)
6188 return 0;
6189 return [[sections_ objectAtIndex:section] count];
6190 }
6191
6192 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6193 if ([[self class] supportsSearch]) {
6194 if (index == 0) {
6195 [tableView setContentOffset:CGPointZero animated:NO];
6196 return NSNotFound;
6197 } else {
6198 return index - 1;
6199 }
6200 }
6201
6202 return index;
6203 }
6204
6205 - (IMP)implementationForSelector:(SEL)selector {
6206 @synchronized (self) {
6207 /* XXX: this is an unsafe optimization of doomy hell */
6208 Method method(class_getInstanceMethod([Package class], selector));
6209 _assert(method != NULL);
6210 IMP imp = method_getImplementation(method);
6211 _assert(imp != NULL);
6212
6213 return imp;
6214 } }
6215
6216 - (PackageListFilter)packageListFilterForFilter:(NSString *)filter {
6217 return [[filters_ objectForKey:filter] packageListFilterValue];
6218 }
6219
6220 - (void)setPackageListFilter:(PackageListFilter)filter forFilter:(NSString *)filterName {
6221 [filters_ setObject:[NSValue valueWithPackageListFilter:filter] forKey:filterName];
6222 }
6223
6224 - (id)objectForFilter:(NSString *)filter {
6225 return [self packageListFilterForFilter:filter].object;
6226 }
6227
6228 - (SEL)selectorForFilter:(NSString *)filter {
6229 return [self packageListFilterForFilter:filter].selector;
6230 }
6231
6232 - (IMP)implementationForFilter:(NSString *)filter {
6233 return [self packageListFilterForFilter:filter].implementation;
6234 }
6235
6236 - (PackageListFilterPriority)priorityForFilter:(NSString *)filter {
6237 return [self packageListFilterForFilter:filter].priority;
6238 }
6239
6240 - (void)setObject:(id)object forFilter:(NSString *)filterName {
6241 PackageListFilter filter = [self packageListFilterForFilter:filterName];
6242 filter.object = object;
6243 [self setPackageListFilter:filter forFilter:filterName];
6244 }
6245
6246 - (void)setPriority:(PackageListFilterPriority)priority forFilter:(NSString *)filterName {
6247 PackageListFilter filter = [self packageListFilterForFilter:filterName];
6248 filter.priority = priority;
6249 [self setPackageListFilter:filter forFilter:filterName];
6250 }
6251
6252 - (void)setImplementation:(IMP)implementation forFilter:(NSString *)filterName {
6253 PackageListFilter filter = [self packageListFilterForFilter:filterName];
6254 filter.implementation = implementation;
6255 [self setPackageListFilter:filter forFilter:filterName];
6256 }
6257
6258 - (void)setSelector:(SEL)selector forFilter:(NSString *)filterName {
6259 PackageListFilter filter = [self packageListFilterForFilter:filterName];
6260 filter.selector = selector;
6261 [self setPackageListFilter:filter forFilter:filterName];
6262
6263 [self setImplementation:[self implementationForSelector:selector] forFilter:filterName];
6264 }
6265
6266 - (void)addFilter:(NSString *)filterName {
6267 PackageListFilter filter;
6268 filter.object = nil;
6269 filter.selector = NULL;
6270 filter.implementation = NULL;
6271 filter.priority = kPackageListFilterPriorityNormal;
6272
6273 [self setPackageListFilter:filter forFilter:filterName];
6274 }
6275
6276 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector {
6277 [self addFilter:filter];
6278 [self setSelector:selector forFilter:filter];
6279 }
6280
6281 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector priority:(PackageListFilterPriority)priority {
6282 [self addFilter:filter withSelector:selector];
6283 [self setPriority:priority forFilter:filter];
6284 }
6285
6286 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector priority:(PackageListFilterPriority)priority object:(id)object {
6287 [self addFilter:filter withSelector:selector];
6288 [self setObject:object forFilter:filter];
6289 }
6290
6291 - (void)removeFilter:(NSString *)filter {
6292 [filters_ removeObjectForKey:filter];
6293 }
6294
6295 - (NSMutableArray *) _reloadPackages {
6296 @synchronized (database_) {
6297 era_ = [database_ era];
6298
6299 NSArray *packages([database_ packages]);
6300 NSMutableArray *filtered;
6301
6302 NSArray *filters = [filters_ allKeys];
6303
6304 for (PackageListFilterPriority currentPriority = kPackageListFilterPriorityHigh; currentPriority >= kPackageListFilterPriorityLow; currentPriority = static_cast<PackageListFilterPriority>(static_cast<int>(currentPriority) - 1)) {
6305 for (NSString *filterName in filters) {
6306 PackageListFilter filter = [self packageListFilterForFilter:filterName];
6307
6308 if (filter.priority == currentPriority) {
6309 filtered = [NSMutableArray arrayWithCapacity:[packages count]];
6310
6311 IMP implementation;
6312 SEL selector;
6313 _H<NSObject> object;
6314
6315 @synchronized (self) {
6316 implementation = filter.implementation;
6317 selector = filter.selector;
6318 object = filter.object;
6319 }
6320
6321 if (implementation == NULL) continue;
6322
6323 _profile(PackageTable$reloadData$Filter)
6324 for (Package *package in packages)
6325 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(implementation))(package, selector, object))
6326 [filtered addObject:package];
6327 _end
6328
6329 packages = filtered;
6330 }
6331 }
6332 }
6333
6334 // packages would also be valid here, but it's defined
6335 // as an immutable array. filtered works too, so use it.
6336 return filtered;
6337 } }
6338
6339 - (void) reloadData {
6340 NSArray *packages;
6341
6342 reload:
6343 packages = [self _reloadPackages];
6344
6345 @synchronized (database_) {
6346 if (era_ != [database_ era])
6347 goto reload;
6348
6349 packages_ = packages;
6350
6351 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6352 sections_ = [NSMutableArray arrayWithCapacity:16];
6353
6354 Section *section = nil;
6355 index_ = [NSMutableArray arrayWithCapacity:32];
6356
6357 _profile(PackageTable$reloadData$Section)
6358 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6359 Package *package;
6360 unichar index;
6361
6362 _profile(PackageTable$reloadData$Section$Package)
6363 package = [packages_ objectAtIndex:offset];
6364 index = [package index];
6365 _end
6366
6367 if (section == nil || [section index] != index) {
6368 _profile(PackageTable$reloadData$Section$Allocate)
6369 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6370 _end
6371
6372 [index_ addObject:[section name]];
6373 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6374
6375 _profile(PackageTable$reloadData$Section$Add)
6376 [sections_ addObject:section];
6377 _end
6378 }
6379
6380 [section addToCount];
6381 }
6382 _end
6383 } }
6384
6385 @end
6386
6387 @interface FilteredPackageListController : CyteViewController <UITableViewDelegate, UISearchDisplayDelegate> {
6388 _transient Database *database_;
6389 _H<UISearchDisplayController> searchController_;
6390 _H<UISearchBar> searchBar_;
6391 _H<FilteredPackageListDataSource> datasource_;
6392 _H<UITableView, 2> list_;
6393 _H<NSString> title_;
6394 }
6395
6396 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6397 - (void) clearData;
6398
6399 @end
6400
6401 @implementation FilteredPackageListController
6402
6403 - (NSURL *) referrerURL {
6404 return [self navigationURL];
6405 }
6406
6407 - (void) deselectWithAnimation:(BOOL)animated {
6408 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6409 }
6410
6411 - (void) viewDidAppear:(BOOL)animated {
6412 [super viewDidAppear:animated];
6413 [self deselectWithAnimation:animated];
6414 }
6415
6416 - (void) didSelectPackage:(Package *)package {
6417 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6418 [view setDelegate:delegate_];
6419 [[self navigationController] pushViewController:view animated:YES];
6420 }
6421
6422 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6423 FilteredPackageListDataSource *source = datasource_;
6424
6425 Package *package([source packageAtIndexPath:path]);
6426 package = [database_ packageWithName:[package id]];
6427 [self didSelectPackage:package];
6428 }
6429
6430 + (Class) dataSourceClass {
6431 return [FilteredPackageListDataSource class];
6432 }
6433
6434 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6435 if ((self = [super init]) != nil) {
6436 database_ = database;
6437
6438 datasource_ = [[[[[self class] dataSourceClass] alloc] initWithDatabase:database_] autorelease];
6439
6440 title_ = [title copy];
6441 [[self navigationItem] setTitle:title_];
6442 } return self;
6443 }
6444
6445 - (void) loadView {
6446 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6447 [view setBackgroundColor:[UIColor whiteColor]];
6448 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6449 [self setView:view];
6450
6451 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6452 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6453 [view addSubview:list_];
6454
6455 // XXX: is 20 the most optimal number here?
6456 [list_ setSectionIndexMinimumDisplayRowCount:20];
6457 [list_ setRowHeight:73];
6458 [(UITableView *) list_ setDataSource:datasource_];
6459 [list_ setDelegate:self];
6460
6461 if ([[[self class] dataSourceClass] supportsSearch]) {
6462 searchBar_ = [[UISearchBar alloc] init];
6463 [searchBar_ sizeToFit];
6464 searchController_ = [[UISearchDisplayController alloc] initWithSearchBar:searchBar_ contentsController:self];
6465 [searchController_ setDelegate:self];
6466 [list_ setTableHeaderView:searchBar_];
6467
6468 [searchController_ setSearchResultsDataSource:datasource_];
6469 [searchController_ setSearchResultsDelegate:self];
6470 }
6471 }
6472
6473 - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
6474 [datasource_ addFilter:@"search" withSelector:@selector(isUnfilteredAndSelectedForBy:) priority:kPackageListFilterPriorityLow object:searchString];
6475 [datasource_ reloadData];
6476 return YES;
6477 }
6478
6479 - (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller {
6480 [datasource_ removeFilter:@"search"];
6481 [self reloadData];
6482 }
6483
6484 - (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView {
6485 // XXX: is 20 the most optimal number here?
6486 [tableView setSectionIndexMinimumDisplayRowCount:20];
6487 [tableView setRowHeight:73];
6488 }
6489
6490 - (void) releaseSubviews {
6491 list_ = nil;
6492
6493 [super releaseSubviews];
6494 }
6495
6496 - (void) reloadData {
6497 [super reloadData];
6498
6499 [datasource_ reloadData];
6500 [list_ reloadData];
6501 }
6502
6503 - (void) resetScrollPosition {
6504 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6505 }
6506
6507 - (void) clearData {
6508 [list_ setDataSource:nil];
6509 [list_ reloadData];
6510
6511 [self resetScrollPosition];
6512 }
6513
6514 @end
6515 /* }}} */
6516
6517 /* Home Controller {{{ */
6518 @interface HomeController : CydiaWebViewController {
6519 CFRunLoopRef runloop_;
6520 SCNetworkReachabilityRef reachability_;
6521 }
6522
6523 @end
6524
6525 @implementation HomeController
6526
6527 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6528 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6529 }
6530
6531 - (id) init {
6532 if ((self = [super init]) != nil) {
6533 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6534 [self reloadData];
6535
6536 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6537 if (reachability_ != NULL) {
6538 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6539 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6540
6541 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6542 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6543 runloop_ = runloop;
6544 }
6545 } return self;
6546 }
6547
6548 - (void) dealloc {
6549 if (reachability_ != NULL && runloop_ != NULL)
6550 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6551 [super dealloc];
6552 }
6553
6554 - (NSURL *) navigationURL {
6555 return [NSURL URLWithString:@"cydia://home"];
6556 }
6557
6558 - (void) aboutButtonClicked {
6559 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6560
6561 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6562 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6563 [alert setCancelButtonIndex:0];
6564
6565 [alert setMessage:
6566 @"Copyright \u00a9 2008-2011\n"
6567 "SaurikIT, LLC\n"
6568 "\n"
6569 "Jay Freeman (saurik)\n"
6570 "saurik@saurik.com\n"
6571 "http://www.saurik.com/"
6572 ];
6573
6574 [alert show];
6575 }
6576
6577 - (UIBarButtonItem *) leftButton {
6578 return [[[UIBarButtonItem alloc]
6579 initWithTitle:UCLocalize("ABOUT")
6580 style:UIBarButtonItemStylePlain
6581 target:self
6582 action:@selector(aboutButtonClicked)
6583 ] autorelease];
6584 }
6585
6586 @end
6587 /* }}} */
6588
6589 /* Refresh Bar {{{ */
6590 @interface RefreshBar : UINavigationBar {
6591 _H<UIProgressIndicator> indicator_;
6592 _H<UITextLabel> prompt_;
6593 _H<UIProgressBar> progress_;
6594 _H<UINavigationButton> cancel_;
6595 }
6596
6597 @end
6598
6599 @implementation RefreshBar
6600
6601 - (void) positionViews {
6602 CGRect frame = [cancel_ frame];
6603 frame.size = [cancel_ sizeThatFits:frame.size];
6604 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6605 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6606 [cancel_ setFrame:frame];
6607
6608 CGSize prgsize = {75, 100};
6609 CGRect prgrect = {{
6610 [self frame].size.width - prgsize.width - 10,
6611 ([self frame].size.height - prgsize.height) / 2
6612 } , prgsize};
6613 [progress_ setFrame:prgrect];
6614
6615 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6616 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6617 CGRect indrect = {{indoffset, indoffset}, indsize};
6618 [indicator_ setFrame:indrect];
6619
6620 CGSize prmsize = {215, indsize.height + 4};
6621 CGRect prmrect = {{
6622 indoffset * 2 + indsize.width,
6623 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6624 }, prmsize};
6625 [prompt_ setFrame:prmrect];
6626 }
6627
6628 - (void) setFrame:(CGRect)frame {
6629 [super setFrame:frame];
6630 [self positionViews];
6631 }
6632
6633 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6634 if ((self = [super initWithFrame:frame]) != nil) {
6635 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6636
6637 [self setBarStyle:UIBarStyleBlack];
6638
6639 UIBarStyle barstyle([self _barStyle:NO]);
6640 bool ugly(barstyle == UIBarStyleDefault);
6641
6642 UIProgressIndicatorStyle style = ugly ?
6643 UIProgressIndicatorStyleMediumBrown :
6644 UIProgressIndicatorStyleMediumWhite;
6645
6646 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6647 [(UIProgressIndicator *) indicator_ setStyle:style];
6648 [indicator_ startAnimation];
6649 [self addSubview:indicator_];
6650
6651 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6652 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6653 [prompt_ setBackgroundColor:[UIColor clearColor]];
6654 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6655 [self addSubview:prompt_];
6656
6657 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6658 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6659 [(UIProgressBar *) progress_ setStyle:0];
6660 [self addSubview:progress_];
6661
6662 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6663 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6664 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6665 [cancel_ setBarStyle:barstyle];
6666
6667 [self positionViews];
6668 } return self;
6669 }
6670
6671 - (void) setCancellable:(bool)cancellable {
6672 if (cancellable)
6673 [self addSubview:cancel_];
6674 else
6675 [cancel_ removeFromSuperview];
6676 }
6677
6678 - (void) start {
6679 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6680 [progress_ setProgress:0];
6681 }
6682
6683 - (void) stop {
6684 [self setCancellable:NO];
6685 }
6686
6687 - (void) setPrompt:(NSString *)prompt {
6688 [prompt_ setText:prompt];
6689 }
6690
6691 - (void) setProgress:(float)progress {
6692 [progress_ setProgress:progress];
6693 }
6694
6695 @end
6696 /* }}} */
6697
6698 /* Cydia Navigation Controller Interface {{{ */
6699 @interface UINavigationController (Cydia)
6700
6701 - (NSArray *) navigationURLCollection;
6702 - (void) unloadData;
6703
6704 @end
6705 /* }}} */
6706
6707 /* Cydia Tab Bar Controller {{{ */
6708 @interface CYTabBarController : UITabBarController <
6709 UITabBarControllerDelegate,
6710 ProgressDelegate
6711 > {
6712 _transient Database *database_;
6713 _H<RefreshBar, 1> refreshbar_;
6714
6715 bool dropped_;
6716 bool updating_;
6717 // XXX: ok, "updatedelegate_"?...
6718 _transient NSObject<CydiaDelegate> *updatedelegate_;
6719
6720 _H<UIViewController> remembered_;
6721 _transient UIViewController *transient_;
6722 }
6723
6724 - (NSArray *) navigationURLCollection;
6725 - (void) dropBar:(BOOL)animated;
6726 - (void) beginUpdate;
6727 - (void) raiseBar:(BOOL)animated;
6728 - (BOOL) updating;
6729 - (void) unloadData;
6730
6731 @end
6732
6733 @implementation CYTabBarController
6734
6735 - (void) didReceiveMemoryWarning {
6736 [super didReceiveMemoryWarning];
6737
6738 // presenting a UINavigationController on 2.x does not update its transitionView
6739 // it thereby will not allow its topViewController to be unloaded by memory pressure
6740 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6741 UIViewController *selected([self selectedViewController]);
6742 for (UINavigationController *controller in [self viewControllers])
6743 if (controller != selected)
6744 if (UIViewController *top = [controller topViewController])
6745 [top unloadView];
6746 }
6747 }
6748
6749 - (void) setUnselectedViewController:(UIViewController *)transient {
6750 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6751 if (transient != nil) {
6752 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6753 [self setSelectedIndex:0];
6754 } return;
6755 }
6756
6757 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6758 if (transient != nil) {
6759 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6760 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6761 transient = navigation;
6762
6763 if (transient_ == nil)
6764 remembered_ = [controllers objectAtIndex:0];
6765 transient_ = transient;
6766 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6767 [controllers replaceObjectAtIndex:0 withObject:transient_];
6768 [self setSelectedIndex:0];
6769 [self setViewControllers:controllers];
6770 [self concealTabBarSelection];
6771 } else if (remembered_ != nil) {
6772 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6773 transient_ = transient;
6774 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6775 remembered_ = nil;
6776 [self setViewControllers:controllers];
6777 [self revealTabBarSelection];
6778 }
6779 }
6780
6781 - (UIViewController *) unselectedViewController {
6782 return transient_;
6783 }
6784
6785 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6786 if ([self unselectedViewController])
6787 [self setUnselectedViewController:nil];
6788
6789 // presenting a UINavigationController on 2.x does not update its transitionView
6790 // if this view was unloaded, the tranitionView may currently be presenting nothing
6791 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6792 UINavigationController *navigation((UINavigationController *) viewController);
6793 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6794 [navigation popViewControllerAnimated:NO];
6795 }
6796 }
6797
6798 - (NSArray *) navigationURLCollection {
6799 NSMutableArray *items([NSMutableArray array]);
6800
6801 // XXX: Should this deal with transient view controllers?
6802 for (id navigation in [self viewControllers]) {
6803 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6804 if (stack != nil)
6805 [items addObject:stack];
6806 }
6807
6808 return items;
6809 }
6810
6811 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6812 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6813 [self setUnselectedViewController:nil];
6814 else
6815 [super dismissModalViewControllerAnimated:YES];
6816 }
6817
6818 - (void) unloadData {
6819 [super unloadData];
6820
6821 for (UINavigationController *controller in [self viewControllers])
6822 [controller unloadData];
6823
6824 if (UIViewController *selected = [self selectedViewController])
6825 [selected reloadData];
6826
6827 if (UIViewController *unselected = [self unselectedViewController]) {
6828 [unselected unloadData];
6829 [unselected reloadData];
6830 }
6831 }
6832
6833 - (void) dealloc {
6834 [[NSNotificationCenter defaultCenter] removeObserver:self];
6835
6836 [super dealloc];
6837 }
6838
6839 - (id) initWithDatabase:(Database *)database {
6840 if ((self = [super init]) != nil) {
6841 database_ = database;
6842 [self setDelegate:self];
6843
6844 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6845 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6846
6847 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6848 } return self;
6849 }
6850
6851 - (void) setUpdate:(NSDate *)date {
6852 [self beginUpdate];
6853 }
6854
6855 - (void) beginUpdate {
6856 [(RefreshBar *) refreshbar_ start];
6857 [self dropBar:YES];
6858
6859 [updatedelegate_ retainNetworkActivityIndicator];
6860 updating_ = true;
6861
6862 [NSThread
6863 detachNewThreadSelector:@selector(performUpdate)
6864 toTarget:self
6865 withObject:nil
6866 ];
6867 }
6868
6869 - (void) performUpdate {
6870 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6871
6872 Status status;
6873 status.setDelegate(self);
6874 [database_ updateWithStatus:status];
6875
6876 [self
6877 performSelectorOnMainThread:@selector(completeUpdate)
6878 withObject:nil
6879 waitUntilDone:NO
6880 ];
6881
6882 [pool release];
6883 }
6884
6885 - (void) stopUpdateWithSelector:(SEL)selector {
6886 updating_ = false;
6887 [updatedelegate_ releaseNetworkActivityIndicator];
6888
6889 [self raiseBar:YES];
6890 [refreshbar_ stop];
6891
6892 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6893 }
6894
6895 - (void) completeUpdate {
6896 if (!updating_)
6897 return;
6898 [self stopUpdateWithSelector:@selector(reloadData)];
6899 }
6900
6901 - (void) cancelUpdate {
6902 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6903 }
6904
6905 - (void) cancelPressed {
6906 [self cancelUpdate];
6907 }
6908
6909 - (BOOL) updating {
6910 return updating_;
6911 }
6912
6913 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6914 [refreshbar_ setPrompt:[event compoundMessage]];
6915 }
6916
6917 - (bool) isProgressCancelled {
6918 return !updating_;
6919 }
6920
6921 - (void) setProgressCancellable:(NSNumber *)cancellable {
6922 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6923 }
6924
6925 - (void) setProgressPercent:(NSNumber *)percent {
6926 [refreshbar_ setProgress:[percent floatValue]];
6927 }
6928
6929 - (void) setProgressStatus:(NSDictionary *)status {
6930 if (status != nil)
6931 [self setProgressPercent:[status objectForKey:@"Percent"]];
6932 }
6933
6934 - (void) setUpdateDelegate:(id)delegate {
6935 updatedelegate_ = delegate;
6936 }
6937
6938 - (UIView *) transitionView {
6939 if ([self respondsToSelector:@selector(_transitionView)])
6940 return [self _transitionView];
6941 else
6942 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6943 }
6944
6945 - (void) dropBar:(BOOL)animated {
6946 if (dropped_)
6947 return;
6948 dropped_ = true;
6949
6950 UIView *transition([self transitionView]);
6951 [[self view] addSubview:refreshbar_];
6952
6953 CGRect barframe([refreshbar_ frame]);
6954
6955 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6956 barframe.origin.y = CYStatusBarHeight();
6957 else
6958 barframe.origin.y = 0;
6959
6960 [refreshbar_ setFrame:barframe];
6961
6962 if (animated)
6963 [UIView beginAnimations:nil context:NULL];
6964
6965 CGRect viewframe = [transition frame];
6966 viewframe.origin.y += barframe.size.height;
6967 viewframe.size.height -= barframe.size.height;
6968 [transition setFrame:viewframe];
6969
6970 if (animated)
6971 [UIView commitAnimations];
6972
6973 // Ensure bar has the proper width for our view, it might have changed
6974 barframe.size.width = viewframe.size.width;
6975 [refreshbar_ setFrame:barframe];
6976 }
6977
6978 - (void) raiseBar:(BOOL)animated {
6979 if (!dropped_)
6980 return;
6981 dropped_ = false;
6982
6983 UIView *transition([self transitionView]);
6984 [refreshbar_ removeFromSuperview];
6985
6986 CGRect barframe([refreshbar_ frame]);
6987
6988 if (animated)
6989 [UIView beginAnimations:nil context:NULL];
6990
6991 CGRect viewframe = [transition frame];
6992 viewframe.origin.y -= barframe.size.height;
6993 viewframe.size.height += barframe.size.height;
6994 [transition setFrame:viewframe];
6995
6996 if (animated)
6997 [UIView commitAnimations];
6998 }
6999
7000 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7001 bool dropped(dropped_);
7002
7003 if (dropped)
7004 [self raiseBar:NO];
7005
7006 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7007
7008 if (dropped)
7009 [self dropBar:NO];
7010 }
7011
7012 - (void) statusBarFrameChanged:(NSNotification *)notification {
7013 if (dropped_) {
7014 [self raiseBar:NO];
7015 [self dropBar:NO];
7016 }
7017 }
7018
7019 @end
7020 /* }}} */
7021
7022 /* Cydia Navigation Controller Implementation {{{ */
7023 @implementation UINavigationController (Cydia)
7024
7025 - (NSArray *) navigationURLCollection {
7026 NSMutableArray *stack([NSMutableArray array]);
7027
7028 for (CyteViewController *controller in [self viewControllers]) {
7029 NSString *url = [[controller navigationURL] absoluteString];
7030 if (url != nil)
7031 [stack addObject:url];
7032 }
7033
7034 return stack;
7035 }
7036
7037 - (void) reloadData {
7038 [super reloadData];
7039
7040 UIViewController *visible([self visibleViewController]);
7041 if (visible != nil)
7042 [visible reloadData];
7043
7044 // on the iPad, this view controller is ALSO visible. :(
7045 if (IsWildcat_)
7046 if (UIViewController *top = [self topViewController])
7047 if (top != visible)
7048 [top reloadData];
7049 }
7050
7051 - (void) unloadData {
7052 for (CyteViewController *page in [self viewControllers])
7053 [page unloadData];
7054
7055 [super unloadData];
7056 }
7057
7058 @end
7059 /* }}} */
7060
7061 /* Cydia:// Protocol {{{ */
7062 @interface CydiaURLProtocol : NSURLProtocol {
7063 }
7064
7065 @end
7066
7067 @implementation CydiaURLProtocol
7068
7069 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7070 NSURL *url([request URL]);
7071 if (url == nil)
7072 return NO;
7073
7074 NSString *scheme([[url scheme] lowercaseString]);
7075 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7076 return YES;
7077 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7078 return YES;
7079
7080 return NO;
7081 }
7082
7083 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7084 return request;
7085 }
7086
7087 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7088 id<NSURLProtocolClient> client([self client]);
7089 if (icon == nil)
7090 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7091 else {
7092 NSData *data(UIImagePNGRepresentation(icon));
7093
7094 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7095 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7096 [client URLProtocol:self didLoadData:data];
7097 [client URLProtocolDidFinishLoading:self];
7098 }
7099 }
7100
7101 - (void) startLoading {
7102 id<NSURLProtocolClient> client([self client]);
7103 NSURLRequest *request([self request]);
7104
7105 NSURL *url([request URL]);
7106 NSString *href([url absoluteString]);
7107 NSString *scheme([[url scheme] lowercaseString]);
7108
7109 NSString *path;
7110
7111 if ([scheme isEqualToString:@"cydia"])
7112 path = [href substringFromIndex:8];
7113 else if ([scheme isEqualToString:@"about"])
7114 path = [href substringFromIndex:12];
7115 else _assert(false);
7116
7117 NSRange slash([path rangeOfString:@"/"]);
7118
7119 NSString *command;
7120 if (slash.location == NSNotFound) {
7121 command = path;
7122 path = nil;
7123 } else {
7124 command = [path substringToIndex:slash.location];
7125 path = [path substringFromIndex:(slash.location + 1)];
7126 }
7127
7128 Database *database([Database sharedInstance]);
7129
7130 if ([command isEqualToString:@"package-icon"]) {
7131 if (path == nil)
7132 goto fail;
7133 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7134 Package *package([database packageWithName:path]);
7135 if (package == nil)
7136 goto fail;
7137 [package parse];
7138 UIImage *icon([package icon]);
7139 [self _returnPNGWithImage:icon forRequest:request];
7140 } else if ([command isEqualToString:@"uikit-image"]) {
7141 if (path == nil)
7142 goto fail;
7143 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7144 UIImage *icon(_UIImageWithName(path));
7145 [self _returnPNGWithImage:icon forRequest:request];
7146 } else if ([command isEqualToString:@"section-icon"]) {
7147 if (path == nil)
7148 goto fail;
7149 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7150 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7151 if (icon == nil)
7152 icon = [UIImage applicationImageNamed:@"unknown.png"];
7153 [self _returnPNGWithImage:icon forRequest:request];
7154 } else fail: {
7155 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7156 }
7157 }
7158
7159 - (void) stopLoading {
7160 }
7161
7162 @end
7163 /* }}} */
7164
7165 /* Section Controller {{{ */
7166 @interface SectionController : FilteredPackageListController {
7167 _H<IndirectDelegate, 1> indirect_;
7168 _H<CydiaObject> cydia_;
7169 _H<NSString> section_;
7170 _H<NSString> key_;
7171 _transient Source *source_;
7172 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7173 }
7174
7175 - (id) initWithDatabase:(Database *)database section:(NSString *)section source:(Source *)source;
7176
7177 @end
7178
7179 @implementation SectionController
7180
7181 - (NSURL *) referrerURL {
7182 NSMutableString *path = [NSMutableString string];
7183
7184 if (source_ != nil) {
7185 [path appendString:[NSString stringWithFormat:@"sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7186 } else {
7187 [path appendString:@"sections"];
7188 }
7189
7190 [path appendString:@"/"];
7191
7192 if (section_ != nil) {
7193 [path appendString:[NSString stringWithFormat:@"%@", [section_ stringByAddingPercentEscapesIncludingReserved]]];
7194 } else {
7195 [path appendString:@"all"];
7196 }
7197
7198 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/%@", UI_, path]];
7199 }
7200
7201 - (NSURL *) navigationURL {
7202 NSMutableString *path = [NSMutableString string];
7203
7204 if (source_ != nil) {
7205 [path appendString:[NSString stringWithFormat:@"sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7206 } else {
7207 [path appendString:@"sections"];
7208 }
7209
7210 [path appendString:@"/"];
7211
7212 if (section_ != nil) {
7213 [path appendString:[NSString stringWithFormat:@"%@", [section_ stringByAddingPercentEscapesIncludingReserved]]];
7214 } else {
7215 [path appendString:@"all"];
7216 }
7217
7218 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://%@", path]];
7219 }
7220
7221 - (id) initWithDatabase:(Database *)database section:(NSString *)name source:(Source *)source {
7222 NSString *title;
7223 if (name == nil)
7224 title = UCLocalize("ALL_PACKAGES");
7225 else if (![name isEqual:@""])
7226 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7227 else
7228 title = UCLocalize("NO_SECTION");
7229
7230 if ((self = [super initWithDatabase:database title:title]) != nil) {
7231 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7232 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7233
7234 [datasource_ addFilter:@"section" withSelector:@selector(isVisibleInSection:) priority:kPackageListFilterPriorityHigh object:name];
7235 [datasource_ addFilter:@"source" withSelector:@selector(isVisibleInSource:) priority:kPackageListFilterPriorityHigh object:source];
7236
7237 section_ = name;
7238 source_ = source;
7239 key_ = [source key];
7240 } return self;
7241 }
7242
7243 /*- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7244 return [super numberOfSectionsInTableView:list] + 1;
7245 }
7246
7247 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7248 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7249 }
7250
7251 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7252 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7253 }
7254
7255 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7256 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7257 }
7258
7259 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7260 if ([path section] != 0)
7261 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7262
7263 return promoted_[[path row]];
7264 }
7265
7266 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7267 if ([path section] != 0)
7268 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7269 }
7270
7271 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7272 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7273 return section == 0 ? 0 : section + 1;
7274 }*/
7275
7276 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7277 NSURL *url([request URL]);
7278 if (url == nil)
7279 return;
7280
7281 if ([frame isEqualToString:@"_open"])
7282 [delegate_ openURL:url];
7283 else {
7284 WebFrame *frame(nil);
7285 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7286 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7287 if (frame == nil)
7288 frame = [view mainFrame];
7289
7290 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7291
7292 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7293 [controller setDelegate:delegate_];
7294 [[self navigationController] pushViewController:controller animated:YES];
7295 }
7296
7297 [listener ignore];
7298 }
7299
7300 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7301 return [CydiaWebViewController requestWithHeaders:request];
7302 }
7303
7304 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7305 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7306 }
7307
7308 - (void) loadView {
7309 [super loadView];
7310
7311 // XXX: this code is horrible. I mean, wtf Jay?
7312 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7313 promoted_.resize(1);
7314
7315 for (unsigned i(0); i != promoted_.size(); ++i) {
7316 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7317 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7318 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7319 ]]
7320
7321 cachePolicy:NSURLRequestUseProtocolCachePolicy
7322 timeoutInterval:120
7323 ]]);
7324
7325 [promoted setDelegate:self];
7326 promoted_[i] = promoted;
7327 }
7328 }
7329 }
7330
7331 - (void) setDelegate:(id)delegate {
7332 [super setDelegate:delegate];
7333 [cydia_ setDelegate:delegate];
7334 }
7335
7336 - (void) releaseSubviews {
7337 promoted_.clear();
7338 [super releaseSubviews];
7339 }
7340
7341 - (void)reloadData {
7342 source_ = [database_ sourceWithKey:key_];
7343 key_ = [source_ key];
7344 [datasource_ setObject:source_ forFilter:@"source"];
7345
7346 [super reloadData];
7347 }
7348
7349 @end
7350 /* }}} */
7351 /* Sections Controller {{{ */
7352 @interface SectionsController : CyteViewController <
7353 UITableViewDataSource,
7354 UITableViewDelegate
7355 > {
7356 _transient Database *database_;
7357 _H<NSMutableArray> sections_;
7358 _H<NSMutableArray> filtered_;
7359 _H<UITableView, 2> list_;
7360 _H<NSString> key_;
7361 _transient Source *source_;
7362 }
7363
7364 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7365 - (void) editButtonClicked;
7366
7367 @end
7368
7369 @implementation SectionsController
7370
7371 - (NSURL *) navigationURL {
7372 if (source_ != nil) {
7373 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7374 } else {
7375 return [NSURL URLWithString:@"cydia://sections"];
7376 }
7377 }
7378
7379 - (NSString *)defaultTitle {
7380 if (source_ != nil) {
7381 return [source_ label];
7382 } else {
7383 return UCLocalize("SECTIONS");
7384 }
7385 }
7386
7387 - (void) updateNavigationItem {
7388 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : [self defaultTitle]];
7389 if ([sections_ count] == 0) {
7390 [[self navigationItem] setRightBarButtonItem:nil];
7391 } else {
7392 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7393 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7394 target:self
7395 action:@selector(editButtonClicked)
7396 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7397 }
7398 }
7399
7400 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7401 [super setEditing:editing animated:animated];
7402
7403 if (editing)
7404 [list_ reloadData];
7405 else
7406 [delegate_ updateData];
7407
7408 [self updateNavigationItem];
7409 }
7410
7411 - (void) viewDidAppear:(BOOL)animated {
7412 [super viewDidAppear:animated];
7413 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7414 }
7415
7416 - (void) viewWillDisappear:(BOOL)animated {
7417 [super viewWillDisappear:animated];
7418 [self setEditing:NO];
7419 }
7420
7421 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7422 Section *section = nil;
7423 int index = [indexPath row];
7424 if (![self isEditing]) {
7425 index -= 1;
7426 if (index >= 0)
7427 section = [filtered_ objectAtIndex:index];
7428 } else {
7429 section = [sections_ objectAtIndex:index];
7430 }
7431 return section;
7432 }
7433
7434 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7435 if ([self isEditing])
7436 return [sections_ count];
7437 else
7438 return [filtered_ count] + 1;
7439 }
7440
7441 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7442 return 45.0f;
7443 }*/
7444
7445 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7446 static NSString *reuseIdentifier = @"SectionCell";
7447
7448 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7449 if (cell == nil)
7450 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7451
7452 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7453
7454 return cell;
7455 }
7456
7457 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7458 if ([self isEditing])
7459 return;
7460
7461 Section *section = [self sectionAtIndexPath:indexPath];
7462
7463 SectionController *controller = [[[SectionController alloc]
7464 initWithDatabase:database_
7465 section:[section name]
7466 source:source_
7467 ] autorelease];
7468 [controller setDelegate:delegate_];
7469
7470 [[self navigationController] pushViewController:controller animated:YES];
7471 }
7472
7473 - (void) loadView {
7474 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7475 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7476 [list_ setRowHeight:45.0f];
7477 [(UITableView *) list_ setDataSource:self];
7478 [list_ setDelegate:self];
7479 [self setView:list_];
7480 }
7481
7482 - (void) viewDidLoad {
7483 [super viewDidLoad];
7484
7485 [[self navigationItem] setTitle:[self defaultTitle]];
7486 }
7487
7488 - (void) releaseSubviews {
7489 list_ = nil;
7490
7491 sections_ = nil;
7492 filtered_ = nil;
7493
7494 [super releaseSubviews];
7495 }
7496
7497 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7498 if ((self = [super init]) != nil) {
7499 database_ = database;
7500 source_ = source;
7501 key_ = [source_ key];
7502 } return self;
7503 }
7504
7505 - (void) reloadData {
7506 source_ = [database_ sourceWithKey:key_];
7507 key_ = [source_ key];
7508
7509 [[self navigationItem] setTitle:[source_ label]];
7510
7511 [super reloadData];
7512
7513 NSArray *packages = [database_ packages];
7514
7515 sections_ = [NSMutableArray arrayWithCapacity:16];
7516 filtered_ = [NSMutableArray arrayWithCapacity:16];
7517
7518 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7519
7520 _trace();
7521 for (Package *package in packages) {
7522 // Ignore packages from other sources (but allow all without a source).
7523 if (source_ != nil && ![package isVisibleInSource:source_]) continue;
7524
7525 NSString *name([package section]);
7526 NSString *key(name == nil ? @"" : name);
7527
7528 Section *section;
7529
7530 _profile(SectionsView$reloadData$Section)
7531 section = [sections objectForKey:key];
7532 if (section == nil) {
7533 _profile(SectionsView$reloadData$Section$Allocate)
7534 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7535 [sections setObject:section forKey:key];
7536 _end
7537 }
7538 _end
7539
7540 [section addToCount];
7541
7542 _profile(SectionsView$reloadData$Filter)
7543 if (![package valid] || ![package visible])
7544 continue;
7545 _end
7546
7547 [section addToRow];
7548 }
7549 _trace();
7550
7551 [sections_ addObjectsFromArray:[sections allValues]];
7552
7553 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7554
7555 for (Section *section in (id) sections_) {
7556 size_t count([section row]);
7557 if (count == 0)
7558 continue;
7559
7560 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7561 [section setCount:count];
7562 [filtered_ addObject:section];
7563 }
7564
7565 [self updateNavigationItem];
7566 [list_ reloadData];
7567 _trace();
7568 }
7569
7570 - (void) editButtonClicked {
7571 [self setEditing:![self isEditing] animated:YES];
7572 }
7573
7574 @end
7575 /* }}} */
7576
7577 /* Changes Controller {{{ */
7578 @interface ChangesPackageListDataSource : FilteredPackageListDataSource {
7579 unsigned upgrades_;
7580 }
7581
7582 @end
7583
7584 @implementation ChangesPackageListDataSource
7585
7586 - (NSMutableArray *) _reloadPackages {
7587 @synchronized (database_) {
7588 era_ = [database_ era];
7589 NSArray *packages([database_ packages]);
7590
7591 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7592
7593 _trace();
7594 _profile(ChangesPackageListController$_reloadPackages$Filter)
7595 for (Package *package in packages)
7596 if ([package upgradableAndEssential:YES] || [package visible])
7597 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7598 _end
7599 _trace();
7600 _profile(ChangesPackageListController$_reloadPackages$radixSort)
7601 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7602 _end
7603 _trace();
7604
7605 return filtered;
7606 } }
7607
7608 - (void) reloadData {
7609 NSArray *packages = [self _reloadPackages];
7610
7611 @synchronized (database_) {
7612 packages_ = packages;
7613 sections_ = [NSMutableArray arrayWithCapacity:16];
7614
7615 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7616 Section *ignored = nil;
7617 Section *section = nil;
7618 time_t last = 0;
7619
7620 upgrades_ = 0;
7621 bool unseens = false;
7622
7623 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7624
7625 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7626 Package *package = [packages_ objectAtIndex:offset];
7627
7628 BOOL uae = [package upgradableAndEssential:YES];
7629
7630 if (!uae) {
7631 unseens = true;
7632 time_t seen([package seen]);
7633
7634 if (section == nil || last != seen) {
7635 last = seen;
7636
7637 NSString *name;
7638 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7639 [name autorelease];
7640
7641 _profile(ChangesPackageListController$reloadData$Allocate)
7642 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7643 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7644 [sections_ addObject:section];
7645 _end
7646 }
7647
7648 [section addToCount];
7649 } else if ([package ignored]) {
7650 if (ignored == nil) {
7651 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7652 }
7653 [ignored addToCount];
7654 } else {
7655 ++upgrades_;
7656 [upgradable addToCount];
7657 }
7658 }
7659 _trace();
7660
7661 CFRelease(formatter);
7662
7663 if (unseens) {
7664 Section *last = [sections_ lastObject];
7665 size_t count = [last count];
7666 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7667 [sections_ removeLastObject];
7668 }
7669
7670 if ([ignored count] != 0)
7671 [sections_ insertObject:ignored atIndex:0];
7672 if (upgrades_ != 0)
7673 [sections_ insertObject:upgradable atIndex:0];
7674 } }
7675
7676 - (int) upgrades {
7677 return upgrades_;
7678 }
7679
7680 + (BOOL) supportsSearch {
7681 return NO;
7682 }
7683
7684 @end
7685
7686 @interface ChangesPackageListController : FilteredPackageListController <
7687 CyteWebViewDelegate
7688 > {
7689 _H<CyteWebView, 1> dickbar_;
7690 _H<IndirectDelegate, 1> indirect_;
7691 _H<CydiaObject> cydia_;
7692 }
7693
7694 - (id) initWithDatabase:(Database *)database;
7695
7696 @end
7697
7698 @implementation ChangesPackageListController
7699
7700 - (NSURL *) navigationURL {
7701 return [NSURL URLWithString:@"cydia://changes"];
7702 }
7703
7704 - (void) viewDidAppear:(BOOL)animated {
7705 [super viewDidAppear:animated];
7706 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7707 }
7708
7709 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7710 Package *package([datasource_ packageAtIndexPath:path]);
7711 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7712 [view setDelegate:delegate_];
7713 [[self navigationController] pushViewController:view animated:YES];
7714 }
7715
7716 + (Class) dataSourceClass {
7717 return [ChangesPackageListDataSource class];
7718 }
7719
7720 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7721 NSString *context([alert context]);
7722
7723 if ([context isEqualToString:@"norefresh"])
7724 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7725 }
7726
7727 - (void) refreshButtonClicked {
7728 if (IsReachable("cydia.saurik.com")) {
7729 [delegate_ beginUpdate];
7730 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7731 } else {
7732 UIAlertView *alert = [[[UIAlertView alloc]
7733 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7734 message:@"Host Unreachable" // XXX: Localize
7735 delegate:self
7736 cancelButtonTitle:UCLocalize("OK")
7737 otherButtonTitles:nil
7738 ] autorelease];
7739
7740 [alert setContext:@"norefresh"];
7741 [alert show];
7742 }
7743 }
7744
7745 - (void) upgradeButtonClicked {
7746 [delegate_ distUpgrade];
7747 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7748 }
7749
7750 - (void) loadView {
7751 [super loadView];
7752
7753 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7754 CGRect dickframe([[self view] bounds]);
7755 dickframe.size.height = 44;
7756
7757 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7758 [dickbar_ setDelegate:self];
7759 [[self view] addSubview:dickbar_];
7760
7761 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7762 [dickbar_ setScalesPageToFit:YES];
7763
7764 UIWebDocumentView *document([dickbar_ _documentView]);
7765 [document setBackgroundColor:[UIColor clearColor]];
7766 [document setDrawsBackground:NO];
7767
7768 WebView *webview([document webView]);
7769 [webview setShouldUpdateWhileOffscreen:NO];
7770
7771 UIScrollView *scroller([dickbar_ scrollView]);
7772 [scroller setScrollingEnabled:NO];
7773 [scroller setFixedBackgroundPattern:YES];
7774 [scroller setBackgroundColor:[UIColor clearColor]];
7775
7776 WebPreferences *preferences([webview preferences]);
7777 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7778 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7779 [preferences setOfflineWebApplicationCacheEnabled:YES];
7780
7781 [dickbar_ loadRequest:[NSURLRequest
7782 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7783 cachePolicy:NSURLRequestUseProtocolCachePolicy
7784 timeoutInterval:120
7785 ]];
7786
7787 UIEdgeInsets inset = {44, 0, 0, 0};
7788 [list_ setContentInset:inset];
7789
7790 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7791 }
7792 }
7793
7794 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7795 NSURL *url([request URL]);
7796 if (url == nil)
7797 return;
7798
7799 if ([frame isEqualToString:@"_open"])
7800 [delegate_ openURL:url];
7801 else {
7802 WebFrame *frame(nil);
7803 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7804 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7805 if (frame == nil)
7806 frame = [view mainFrame];
7807
7808 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7809
7810 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7811 [controller setDelegate:delegate_];
7812 [[self navigationController] pushViewController:controller animated:YES];
7813 }
7814
7815 [listener ignore];
7816 }
7817
7818 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7819 return [CydiaWebViewController requestWithHeaders:request];
7820 }
7821
7822 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7823 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7824 }
7825
7826 - (void) setDelegate:(id)delegate {
7827 [super setDelegate:delegate];
7828 [cydia_ setDelegate:delegate];
7829 }
7830
7831 - (void) releaseSubviews {
7832 dickbar_ = nil;
7833
7834 [super releaseSubviews];
7835 }
7836
7837 - (id) initWithDatabase:(Database *)database {
7838 if ((self = [super initWithDatabase:database title:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))]) != nil) {
7839 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7840 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7841 database_ = database;
7842 } return self;
7843 }
7844
7845 - (void) reloadData {
7846 [super reloadData];
7847
7848 [[self navigationItem] setRightBarButtonItem:([datasource_ upgrades] == 0 ? nil : [[[UIBarButtonItem alloc]
7849 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", [datasource_ upgrades]]]
7850 style:UIBarButtonItemStylePlain
7851 target:self
7852 action:@selector(upgradeButtonClicked)
7853 ] autorelease]) animated:YES];
7854
7855 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7856 initWithTitle:UCLocalize("REFRESH")
7857 style:UIBarButtonItemStylePlain
7858 target:self
7859 action:@selector(refreshButtonClicked)
7860 ] autorelease]) animated:YES];
7861
7862 PrintTimes();
7863 }
7864
7865 @end
7866 /* }}} */
7867 /* Package Settings Controller {{{ */
7868 @interface PackageSettingsController : CyteViewController <
7869 UITableViewDataSource,
7870 UITableViewDelegate
7871 > {
7872 _transient Database *database_;
7873 _H<NSString> name_;
7874 _H<Package> package_;
7875 _H<UITableView, 2> table_;
7876 _H<UISwitch> subscribedSwitch_;
7877 _H<UISwitch> ignoredSwitch_;
7878 _H<UITableViewCell> subscribedCell_;
7879 _H<UITableViewCell> ignoredCell_;
7880 }
7881
7882 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7883
7884 @end
7885
7886 @implementation PackageSettingsController
7887
7888 - (NSURL *) navigationURL {
7889 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7890 }
7891
7892 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7893 if (package_ == nil)
7894 return 0;
7895
7896 if ([package_ installed] == nil)
7897 return 1;
7898 else
7899 return 2;
7900 }
7901
7902 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7903 if (package_ == nil)
7904 return 0;
7905
7906 // both sections contain just one item right now.
7907 return 1;
7908 }
7909
7910 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7911 return nil;
7912 }
7913
7914 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7915 if (section == 0)
7916 return UCLocalize("SHOW_ALL_CHANGES_EX");
7917 else
7918 return UCLocalize("IGNORE_UPGRADES_EX");
7919 }
7920
7921 - (void) onSubscribed:(id)control {
7922 bool value([control isOn]);
7923 if (package_ == nil)
7924 return;
7925 if ([package_ setSubscribed:value])
7926 [delegate_ updateData];
7927 }
7928
7929 - (void) _updateIgnored {
7930 const char *package([name_ UTF8String]);
7931 bool on([ignoredSwitch_ isOn]);
7932
7933 pid_t pid(ExecFork());
7934 if (pid == 0) {
7935 FILE *dpkg(popen("dpkg --set-selections", "w"));
7936 fwrite(package, strlen(package), 1, dpkg);
7937
7938 if (on)
7939 fwrite(" hold\n", 6, 1, dpkg);
7940 else
7941 fwrite(" install\n", 9, 1, dpkg);
7942
7943 pclose(dpkg);
7944
7945 exit(0);
7946 _assert(false);
7947 }
7948
7949 ReapZombie(pid);
7950 }
7951
7952 - (void) onIgnored:(id)control {
7953 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7954 [invocation setTarget:self];
7955 [invocation setSelector:@selector(_updateIgnored)];
7956
7957 [delegate_ reloadDataWithInvocation:invocation];
7958 }
7959
7960 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7961 if (package_ == nil)
7962 return nil;
7963
7964 switch ([indexPath section]) {
7965 case 0: return subscribedCell_;
7966 case 1: return ignoredCell_;
7967
7968 _nodefault
7969 }
7970
7971 return nil;
7972 }
7973
7974 - (void) loadView {
7975 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7976 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7977 [self setView:view];
7978
7979 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7980 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7981 [(UITableView *) table_ setDataSource:self];
7982 [table_ setDelegate:self];
7983 [view addSubview:table_];
7984
7985 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7986 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7987 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7988
7989 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7990 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7991 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7992
7993 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7994 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7995 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7996 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7997
7998 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7999 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8000 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8001 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8002 }
8003
8004 - (void) viewDidLoad {
8005 [super viewDidLoad];
8006
8007 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8008 }
8009
8010 - (void) releaseSubviews {
8011 ignoredCell_ = nil;
8012 subscribedCell_ = nil;
8013 table_ = nil;
8014 ignoredSwitch_ = nil;
8015 subscribedSwitch_ = nil;
8016
8017 [super releaseSubviews];
8018 }
8019
8020 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8021 if ((self = [super init]) != nil) {
8022 database_ = database;
8023 name_ = package;
8024 } return self;
8025 }
8026
8027 - (void) reloadData {
8028 [super reloadData];
8029
8030 package_ = [database_ packageWithName:name_];
8031
8032 if (package_ != nil) {
8033 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8034 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8035 } // XXX: what now, G?
8036
8037 [table_ reloadData];
8038 }
8039
8040 @end
8041 /* }}} */
8042
8043 /* Installed Controller {{{ */
8044 @interface InstalledController : FilteredPackageListController {
8045 BOOL expert_;
8046 }
8047
8048 - (id) initWithDatabase:(Database *)database;
8049
8050 - (void) updateRoleButton;
8051 - (void) queueStatusDidChange;
8052
8053 @end
8054
8055 @implementation InstalledController
8056
8057 - (NSURL *) referrerURL {
8058 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8059 }
8060
8061 - (NSURL *) navigationURL {
8062 return [NSURL URLWithString:@"cydia://installed"];
8063 }
8064
8065 - (id) initWithDatabase:(Database *)database {
8066 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") ]) != nil) {
8067 [datasource_ addFilter:@"installed" withSelector:@selector(isInstalledAndUnfiltered:) priority:kPackageListFilterPriorityHigh object:[NSNumber numberWithBool:YES]];
8068 [self updateRoleButton];
8069 [self queueStatusDidChange];
8070 } return self;
8071 }
8072
8073 #if !AlwaysReload
8074 - (void) queueButtonClicked {
8075 [delegate_ queue];
8076 }
8077 #endif
8078
8079 - (void) queueStatusDidChange {
8080 #if !AlwaysReload
8081 if (Queuing_) {
8082 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8083 initWithTitle:UCLocalize("QUEUE")
8084 style:UIBarButtonItemStyleDone
8085 target:self
8086 action:@selector(queueButtonClicked)
8087 ] autorelease]];
8088 } else {
8089 [[self navigationItem] setLeftBarButtonItem:nil];
8090 }
8091 #endif
8092 }
8093
8094 - (void) updateRoleButton {
8095 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8096 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8097 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8098 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8099 target:self
8100 action:@selector(roleButtonClicked)
8101 ] autorelease]];
8102 }
8103
8104 - (void) roleButtonClicked {
8105 [datasource_ setObject:[NSNumber numberWithBool:expert_] forFilter:@"installed"];
8106 [self reloadData];
8107 expert_ = !expert_;
8108
8109 [self updateRoleButton];
8110 }
8111
8112 @end
8113 /* }}} */
8114
8115 /* Source Cell {{{ */
8116 @interface SourceCell : CyteTableViewCell <
8117 CyteTableViewCellDelegate
8118 > {
8119 _H<NSURL> url_;
8120 _H<UIImage> icon_;
8121 _H<NSString> origin_;
8122 _H<NSString> label_;
8123 }
8124
8125 - (void) setSource:(Source *)source;
8126
8127 @end
8128
8129 @implementation SourceCell
8130
8131 - (void) _setImage:(NSArray *)data {
8132 if ([url_ isEqual:[data objectAtIndex:0]]) {
8133 icon_ = [data objectAtIndex:1];
8134 [content_ setNeedsDisplay];
8135 }
8136 }
8137
8138 - (void) _setSource:(NSURL *) url {
8139 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8140
8141 if (NSData *data = [NSURLConnection
8142 sendSynchronousRequest:[NSURLRequest
8143 requestWithURL:url
8144 cachePolicy:NSURLRequestUseProtocolCachePolicy
8145 timeoutInterval:10
8146 ]
8147
8148 returningResponse:NULL
8149 error:NULL
8150 ])
8151 if (UIImage *image = [UIImage imageWithData:data])
8152 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8153
8154 [pool release];
8155 }
8156
8157 - (void) setSource:(Source *)source {
8158 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8159
8160 origin_ = [source name];
8161 label_ = [source rooturi];
8162
8163 [content_ setNeedsDisplay];
8164
8165 url_ = [source iconURL];
8166 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8167 }
8168
8169 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8170 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8171 UIView *content([self contentView]);
8172 CGRect bounds([content bounds]);
8173
8174 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8175 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8176 [content_ setBackgroundColor:[UIColor whiteColor]];
8177 [content addSubview:content_];
8178
8179 [content_ setDelegate:self];
8180 [content_ setOpaque:YES];
8181
8182 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8183 } return self;
8184 }
8185
8186 - (NSString *) accessibilityLabel {
8187 return label_;
8188 }
8189
8190 - (void) drawContentRect:(CGRect)rect {
8191 bool highlighted(highlighted_);
8192 float width(rect.size.width);
8193
8194 if (icon_ != nil) {
8195 CGRect rect;
8196 rect.size = [(UIImage *) icon_ size];
8197
8198 while (rect.size.width > 32 || rect.size.height > 32) {
8199 rect.size.width /= 2;
8200 rect.size.height /= 2;
8201 }
8202
8203 rect.origin.x = 25 - rect.size.width / 2;
8204 rect.origin.y = 25 - rect.size.height / 2;
8205
8206 [icon_ drawInRect:rect];
8207 }
8208
8209 if (highlighted)
8210 UISetColor(White_);
8211
8212 if (!highlighted)
8213 UISetColor(Black_);
8214 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8215
8216 if (!highlighted)
8217 UISetColor(Gray_);
8218 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8219 }
8220
8221 @end
8222 /* }}} */
8223 /* Sources Controller {{{ */
8224 @interface SourcesController : CyteViewController <
8225 UITableViewDataSource,
8226 UITableViewDelegate
8227 > {
8228 _transient Database *database_;
8229 unsigned era_;
8230
8231 _H<UITableView, 2> list_;
8232 _H<NSMutableArray> sources_;
8233 int offset_;
8234
8235 _H<NSString> href_;
8236 _H<UIProgressHUD> hud_;
8237 _H<NSError> error_;
8238
8239 //NSURLConnection *installer_;
8240 NSURLConnection *trivial_;
8241 NSURLConnection *trivial_bz2_;
8242 NSURLConnection *trivial_gz_;
8243 //NSURLConnection *automatic_;
8244
8245 BOOL cydia_;
8246 }
8247
8248 - (id) initWithDatabase:(Database *)database;
8249 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8250
8251 @end
8252
8253 @implementation SourcesController
8254
8255 - (void) _releaseConnection:(NSURLConnection *)connection {
8256 if (connection != nil) {
8257 [connection cancel];
8258 //[connection setDelegate:nil];
8259 [connection release];
8260 }
8261 }
8262
8263 - (void) dealloc {
8264 //[self _releaseConnection:installer_];
8265 [self _releaseConnection:trivial_];
8266 [self _releaseConnection:trivial_gz_];
8267 [self _releaseConnection:trivial_bz2_];
8268 //[self _releaseConnection:automatic_];
8269
8270 [super dealloc];
8271 }
8272
8273 - (NSURL *) navigationURL {
8274 return [NSURL URLWithString:@"cydia://sources"];
8275 }
8276
8277 - (void) viewDidAppear:(BOOL)animated {
8278 [super viewDidAppear:animated];
8279 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8280 }
8281
8282 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8283 return 1;
8284 }
8285
8286 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8287 return nil;
8288 }
8289
8290 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8291 return [sources_ count];
8292 }
8293
8294 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8295 @synchronized (database_) {
8296 if ([database_ era] != era_)
8297 return nil;
8298
8299 NSUInteger index([indexPath row]);
8300 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8301 } }
8302
8303 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8304 static NSString *cellIdentifier = @"SourceCell";
8305
8306 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8307 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8308 [cell setSource:[self sourceAtIndexPath:indexPath]];
8309 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8310
8311 return cell;
8312 }
8313
8314 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8315 Source *source = [self sourceAtIndexPath:indexPath];
8316 if (source == nil) return;
8317
8318 SectionsController *controller = [[[SectionsController alloc]
8319 initWithDatabase:database_
8320 source:source
8321 ] autorelease];
8322
8323 [controller setDelegate:delegate_];
8324
8325 [[self navigationController] pushViewController:controller animated:YES];
8326 }
8327
8328 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8329 Source *source = [self sourceAtIndexPath:indexPath];
8330 return [source record] != nil;
8331 }
8332
8333 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8334 if (editingStyle == UITableViewCellEditingStyleDelete) {
8335 Source *source = [self sourceAtIndexPath:indexPath];
8336 if (source == nil) return;
8337
8338 [Sources_ removeObjectForKey:[source key]];
8339 [delegate_ _saveConfig];
8340 [delegate_ reloadDataWithInvocation:nil];
8341 }
8342 }
8343
8344 - (void) complete {
8345 [delegate_ addTrivialSource:href_];
8346 href_ = nil;
8347
8348 [delegate_ syncData];
8349 }
8350
8351 - (NSString *) getWarning {
8352 NSString *href(href_);
8353 NSRange colon([href rangeOfString:@"://"]);
8354 if (colon.location != NSNotFound)
8355 href = [href substringFromIndex:(colon.location + 3)];
8356 href = [href stringByAddingPercentEscapes];
8357 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8358
8359 NSURL *url([NSURL URLWithString:href]);
8360
8361 NSStringEncoding encoding;
8362 NSError *error(nil);
8363
8364 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8365 return [warning length] == 0 ? nil : warning;
8366 return nil;
8367 }
8368
8369 - (void) _endConnection:(NSURLConnection *)connection {
8370 // XXX: the memory management in this method is horribly awkward
8371
8372 NSURLConnection **field = NULL;
8373 if (connection == trivial_)
8374 field = &trivial_;
8375 else if (connection == trivial_bz2_)
8376 field = &trivial_bz2_;
8377 else if (connection == trivial_gz_)
8378 field = &trivial_gz_;
8379 _assert(field != NULL);
8380 [connection release];
8381 *field = nil;
8382
8383 if (
8384 trivial_ == nil &&
8385 trivial_bz2_ == nil &&
8386 trivial_gz_ == nil
8387 ) {
8388 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8389
8390 [delegate_ releaseNetworkActivityIndicator];
8391
8392 [delegate_ removeProgressHUD:hud_];
8393 hud_ = nil;
8394
8395 if (cydia_) {
8396 if (warning != nil) {
8397 UIAlertView *alert = [[[UIAlertView alloc]
8398 initWithTitle:UCLocalize("SOURCE_WARNING")
8399 message:warning
8400 delegate:self
8401 cancelButtonTitle:UCLocalize("CANCEL")
8402 otherButtonTitles:
8403 UCLocalize("ADD_ANYWAY"),
8404 nil
8405 ] autorelease];
8406
8407 [alert setContext:@"warning"];
8408 [alert setNumberOfRows:1];
8409 [alert show];
8410
8411 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8412 error_ = nil;
8413 return;
8414 }
8415
8416 [self complete];
8417 } else if (error_ != nil) {
8418 UIAlertView *alert = [[[UIAlertView alloc]
8419 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8420 message:[error_ localizedDescription]
8421 delegate:self
8422 cancelButtonTitle:UCLocalize("OK")
8423 otherButtonTitles:nil
8424 ] autorelease];
8425
8426 [alert setContext:@"urlerror"];
8427 [alert show];
8428
8429 href_ = nil;
8430 } else {
8431 UIAlertView *alert = [[[UIAlertView alloc]
8432 initWithTitle:UCLocalize("NOT_REPOSITORY")
8433 message:UCLocalize("NOT_REPOSITORY_EX")
8434 delegate:self
8435 cancelButtonTitle:UCLocalize("OK")
8436 otherButtonTitles:nil
8437 ] autorelease];
8438
8439 [alert setContext:@"trivial"];
8440 [alert show];
8441
8442 href_ = nil;
8443 }
8444
8445 error_ = nil;
8446 }
8447 }
8448
8449 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8450 switch ([response statusCode]) {
8451 case 200:
8452 cydia_ = YES;
8453 }
8454 }
8455
8456 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8457 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8458 error_ = error;
8459 [self _endConnection:connection];
8460 }
8461
8462 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8463 [self _endConnection:connection];
8464 }
8465
8466 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8467 NSURL *url([NSURL URLWithString:href]);
8468
8469 NSMutableURLRequest *request = [NSMutableURLRequest
8470 requestWithURL:url
8471 cachePolicy:NSURLRequestUseProtocolCachePolicy
8472 timeoutInterval:10
8473 ];
8474
8475 [request setHTTPMethod:method];
8476
8477 if (Machine_ != NULL)
8478 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8479
8480 if (UniqueID_ != nil)
8481 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8482
8483 if ([url isCydiaSecure]) {
8484 if (UniqueID_ != nil)
8485 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8486 }
8487
8488 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8489 }
8490
8491 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8492 NSString *context([alert context]);
8493
8494 if ([context isEqualToString:@"source"]) {
8495 switch (button) {
8496 case 1: {
8497 NSString *href = [[alert textField] text];
8498
8499 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8500
8501 if (![href hasSuffix:@"/"])
8502 href_ = [href stringByAppendingString:@"/"];
8503 else
8504 href_ = href;
8505
8506 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8507 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8508 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8509 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8510
8511 cydia_ = false;
8512
8513 // XXX: this is stupid
8514 hud_ = [delegate_ addProgressHUD];
8515 [hud_ setText:UCLocalize("VERIFYING_URL")];
8516 [delegate_ retainNetworkActivityIndicator];
8517 } break;
8518
8519 case 0:
8520 break;
8521
8522 _nodefault
8523 }
8524
8525 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8526 } else if ([context isEqualToString:@"trivial"])
8527 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8528 else if ([context isEqualToString:@"urlerror"])
8529 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8530 else if ([context isEqualToString:@"warning"]) {
8531 switch (button) {
8532 case 1:
8533 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8534 break;
8535
8536 case 0:
8537 break;
8538
8539 _nodefault
8540 }
8541
8542 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8543 }
8544 }
8545
8546 - (void) loadView {
8547 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8548 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8549 [list_ setRowHeight:53];
8550 [(UITableView *) list_ setDataSource:self];
8551 [list_ setDelegate:self];
8552 [self setView:list_];
8553 }
8554
8555 - (void) viewDidLoad {
8556 [super viewDidLoad];
8557
8558 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8559 [self updateButtonsForEditingStatusAnimated:NO];
8560 }
8561
8562 - (void) viewWillDisappear:(BOOL)animated {
8563 [super viewWillAppear:animated];
8564
8565 [list_ setEditing:NO];
8566 [self updateButtonsForEditingStatusAnimated:NO];
8567 }
8568
8569 - (void) releaseSubviews {
8570 list_ = nil;
8571
8572 sources_ = nil;
8573
8574 [super releaseSubviews];
8575 }
8576
8577 - (id) initWithDatabase:(Database *)database {
8578 if ((self = [super init]) != nil) {
8579 database_ = database;
8580 } return self;
8581 }
8582
8583 - (void) reloadData {
8584 [super reloadData];
8585
8586 @synchronized (database_) {
8587 era_ = [database_ era];
8588
8589 sources_ = [NSMutableArray arrayWithCapacity:16];
8590 [sources_ addObjectsFromArray:[database_ sources]];
8591 _trace();
8592 [sources_ sortUsingSelector:@selector(compareByName:)];
8593 _trace();
8594
8595 int count([sources_ count]);
8596 offset_ = 0;
8597 for (int i = 0; i != count; i++) {
8598 if ([[sources_ objectAtIndex:i] record] == nil)
8599 break;
8600 offset_++;
8601 }
8602
8603 [list_ reloadData];
8604 } }
8605
8606 - (void) showAddSourcePrompt {
8607 UIAlertView *alert = [[[UIAlertView alloc]
8608 initWithTitle:UCLocalize("ENTER_APT_URL")
8609 message:nil
8610 delegate:self
8611 cancelButtonTitle:UCLocalize("CANCEL")
8612 otherButtonTitles:
8613 UCLocalize("ADD_SOURCE"),
8614 nil
8615 ] autorelease];
8616
8617 [alert setContext:@"source"];
8618
8619 [alert setNumberOfRows:1];
8620 [alert addTextFieldWithValue:@"http://" label:@""];
8621
8622 UITextInputTraits *traits = [[alert textField] textInputTraits];
8623 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8624 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8625 [traits setKeyboardType:UIKeyboardTypeURL];
8626 // XXX: UIReturnKeyDone
8627 [traits setReturnKeyType:UIReturnKeyNext];
8628
8629 [alert show];
8630 }
8631
8632 - (void) addButtonClicked {
8633 [self showAddSourcePrompt];
8634 }
8635
8636 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8637 BOOL editing([list_ isEditing]);
8638
8639 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8640 initWithTitle:UCLocalize("ADD")
8641 style:UIBarButtonItemStylePlain
8642 target:self
8643 action:@selector(addButtonClicked)
8644 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8645
8646 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8647 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8648 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8649 target:self
8650 action:@selector(editButtonClicked)
8651 ] autorelease] animated:animated];
8652
8653 if (!editing) {
8654 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8655 initWithTitle:UCLocalize("SETTINGS")
8656 style:UIBarButtonItemStylePlain
8657 target:self
8658 action:@selector(settingsButtonClicked)
8659 ] autorelease]];
8660 }
8661 }
8662
8663 - (void) settingsButtonClicked {
8664 [delegate_ showSettings];
8665 }
8666
8667 - (void) editButtonClicked {
8668 [list_ setEditing:![list_ isEditing] animated:YES];
8669 [self updateButtonsForEditingStatusAnimated:YES];
8670 }
8671
8672 @end
8673 /* }}} */
8674
8675 /* Settings Controller {{{ */
8676 @interface SettingsController : CyteViewController <
8677 UITableViewDataSource,
8678 UITableViewDelegate
8679 > {
8680 _transient Database *database_;
8681 // XXX: ok, "roledelegate_"?...
8682 _transient id roledelegate_;
8683 _H<UITableView, 2> table_;
8684 _H<UISegmentedControl> segment_;
8685 _H<UIView> container_;
8686 }
8687
8688 - (void) showDoneButton;
8689 - (void) resizeSegmentedControl;
8690
8691 @end
8692
8693 @implementation SettingsController
8694
8695 - (void) loadView {
8696 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8697 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8698 [table_ setDelegate:self];
8699 [(UITableView *) table_ setDataSource:self];
8700 [self setView:table_];
8701
8702 NSArray *items = [NSArray arrayWithObjects:
8703 UCLocalize("USER"),
8704 UCLocalize("HACKER"),
8705 UCLocalize("DEVELOPER"),
8706 nil];
8707 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8708 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8709 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8710 [container_ addSubview:segment_];
8711 }
8712
8713 - (void) viewDidLoad {
8714 [super viewDidLoad];
8715
8716 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8717
8718 int index = -1;
8719 if ([Role_ isEqualToString:@"User"]) index = 0;
8720 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8721 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8722 if (index != -1) {
8723 [segment_ setSelectedSegmentIndex:index];
8724 [self showDoneButton];
8725 }
8726
8727 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8728 [self resizeSegmentedControl];
8729 }
8730
8731 - (void) releaseSubviews {
8732 table_ = nil;
8733 segment_ = nil;
8734 container_ = nil;
8735
8736 [super releaseSubviews];
8737 }
8738
8739 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8740 if ((self = [super init]) != nil) {
8741 database_ = database;
8742 roledelegate_ = delegate;
8743 } return self;
8744 }
8745
8746 - (void) resizeSegmentedControl {
8747 CGFloat width = [[self view] frame].size.width;
8748 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8749 }
8750
8751 - (void) viewWillAppear:(BOOL)animated {
8752 [super viewWillAppear:animated];
8753
8754 [self resizeSegmentedControl];
8755 }
8756
8757 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8758 [self resizeSegmentedControl];
8759 }
8760
8761 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8762 [self resizeSegmentedControl];
8763 }
8764
8765 - (void) save {
8766 NSString *role(nil);
8767
8768 switch ([segment_ selectedSegmentIndex]) {
8769 case 0: role = @"User"; break;
8770 case 1: role = @"Hacker"; break;
8771 case 2: role = @"Developer"; break;
8772
8773 _nodefault
8774 }
8775
8776 if (![role isEqualToString:Role_]) {
8777 bool rolling(Role_ == nil);
8778 Role_ = role;
8779
8780 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8781 Role_, @"Role",
8782 nil];
8783
8784 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8785 Changed_ = true;
8786
8787 if (rolling)
8788 [roledelegate_ loadData];
8789 else
8790 [roledelegate_ updateData];
8791 }
8792 }
8793
8794 - (void) segmentChanged:(UISegmentedControl *)control {
8795 [self showDoneButton];
8796 }
8797
8798 - (void) saveAndClose {
8799 [self save];
8800
8801 [[self navigationItem] setRightBarButtonItem:nil];
8802 [[self navigationController] dismissModalViewControllerAnimated:YES];
8803 }
8804
8805 - (void) doneButtonClicked {
8806 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8807 [spinner startAnimating];
8808 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8809 [[self navigationItem] setRightBarButtonItem:spinItem];
8810
8811 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8812 }
8813
8814 - (void) showDoneButton {
8815 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8816 initWithTitle:UCLocalize("DONE")
8817 style:UIBarButtonItemStyleDone
8818 target:self
8819 action:@selector(doneButtonClicked)
8820 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8821 }
8822
8823 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8824 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8825 return 6;
8826 }
8827
8828 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8829 return 0; // :(
8830 }
8831
8832 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8833 return nil; // This method is required by the protocol.
8834 }
8835
8836 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8837 if (section == 1)
8838 return UCLocalize("ROLE_EX");
8839 if (section == 4)
8840 return [NSString stringWithFormat:
8841 @"%@: %@\n%@: %@\n%@: %@",
8842 UCLocalize("USER"), UCLocalize("USER_EX"),
8843 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8844 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8845 ];
8846 else return nil;
8847 }
8848
8849 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8850 return section == 3 ? 44.0f : 0;
8851 }
8852
8853 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8854 return section == 3 ? container_ : nil;
8855 }
8856
8857 - (void) reloadData {
8858 [super reloadData];
8859
8860 [table_ reloadData];
8861 }
8862
8863 @end
8864 /* }}} */
8865 /* Stash Controller {{{ */
8866 @interface StashController : CyteViewController {
8867 _H<UIActivityIndicatorView> spinner_;
8868 _H<UILabel> status_;
8869 _H<UILabel> caption_;
8870 }
8871
8872 @end
8873
8874 @implementation StashController
8875
8876 - (void) loadView {
8877 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8878 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8879 [self setView:view];
8880
8881 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8882
8883 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8884 CGRect spinrect = [spinner_ frame];
8885 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8886 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8887 [spinner_ setFrame:spinrect];
8888 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8889 [view addSubview:spinner_];
8890 [spinner_ startAnimating];
8891
8892 CGRect captrect;
8893 captrect.size.width = [[self view] frame].size.width;
8894 captrect.size.height = 40.0f;
8895 captrect.origin.x = 0;
8896 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8897 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8898 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8899 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8900 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8901 [caption_ setTextColor:[UIColor whiteColor]];
8902 [caption_ setBackgroundColor:[UIColor clearColor]];
8903 [caption_ setShadowColor:[UIColor blackColor]];
8904 [caption_ setTextAlignment:UITextAlignmentCenter];
8905 [view addSubview:caption_];
8906
8907 CGRect statusrect;
8908 statusrect.size.width = [[self view] frame].size.width;
8909 statusrect.size.height = 30.0f;
8910 statusrect.origin.x = 0;
8911 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8912 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8913 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8914 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8915 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8916 [status_ setTextColor:[UIColor whiteColor]];
8917 [status_ setBackgroundColor:[UIColor clearColor]];
8918 [status_ setShadowColor:[UIColor blackColor]];
8919 [status_ setTextAlignment:UITextAlignmentCenter];
8920 [view addSubview:status_];
8921 }
8922
8923 - (void) releaseSubviews {
8924 spinner_ = nil;
8925 status_ = nil;
8926 caption_ = nil;
8927
8928 [super releaseSubviews];
8929 }
8930
8931 @end
8932 /* }}} */
8933
8934 @interface CYURLCache : SDURLCache {
8935 }
8936
8937 @end
8938
8939 @implementation CYURLCache
8940
8941 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8942 #if !ForRelease
8943 if (false);
8944 else if ([event isEqualToString:@"no-cache"])
8945 event = @"!!!";
8946 else if ([event isEqualToString:@"store"])
8947 event = @">>>";
8948 else if ([event isEqualToString:@"invalid"])
8949 event = @"???";
8950 else if ([event isEqualToString:@"memory"])
8951 event = @"mem";
8952 else if ([event isEqualToString:@"disk"])
8953 event = @"ssd";
8954 else if ([event isEqualToString:@"miss"])
8955 event = @"---";
8956
8957 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8958 #endif
8959 }
8960
8961 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8962 if (NSURLResponse *response = [cached response])
8963 if (NSString *mime = [response MIMEType])
8964 if ([mime isEqualToString:@"text/cache-manifest"]) {
8965 NSURL *url([response URL]);
8966
8967 #if !ForRelease
8968 NSLog(@"###: %@", [url absoluteString]);
8969 #endif
8970
8971 @synchronized (HostConfig_) {
8972 [CachedURLs_ addObject:url];
8973 }
8974 }
8975
8976 [super storeCachedResponse:cached forRequest:request];
8977 }
8978
8979 @end
8980
8981 @interface Cydia : UIApplication <
8982 ConfirmationControllerDelegate,
8983 DatabaseDelegate,
8984 CydiaDelegate,
8985 UINavigationControllerDelegate,
8986 UITabBarControllerDelegate
8987 > {
8988 _H<UIWindow> window_;
8989 _H<CYTabBarController> tabbar_;
8990 _H<CydiaLoadingViewController> emulated_;
8991
8992 _H<NSMutableArray> essential_;
8993 _H<NSMutableArray> broken_;
8994
8995 Database *database_;
8996
8997 _H<NSURL> starturl_;
8998
8999 unsigned locked_;
9000 unsigned activity_;
9001
9002 _H<StashController> stash_;
9003
9004 bool loaded_;
9005 }
9006
9007 - (void) loadData;
9008
9009 @end
9010
9011 @implementation Cydia
9012
9013 - (void) beginUpdate {
9014 [tabbar_ beginUpdate];
9015 }
9016
9017 - (BOOL) updating {
9018 return [tabbar_ updating];
9019 }
9020
9021 - (void) _loaded {
9022 if ([broken_ count] != 0) {
9023 int count = [broken_ count];
9024
9025 UIAlertView *alert = [[[UIAlertView alloc]
9026 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9027 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9028 delegate:self
9029 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9030 otherButtonTitles:
9031 UCLocalize("TEMPORARY_IGNORE"),
9032 nil
9033 ] autorelease];
9034
9035 [alert setContext:@"fixhalf"];
9036 [alert setNumberOfRows:2];
9037 [alert show];
9038 } else if (!Ignored_ && [essential_ count] != 0) {
9039 int count = [essential_ count];
9040
9041 UIAlertView *alert = [[[UIAlertView alloc]
9042 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9043 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9044 delegate:self
9045 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9046 otherButtonTitles:
9047 UCLocalize("UPGRADE_ESSENTIAL"),
9048 UCLocalize("COMPLETE_UPGRADE"),
9049 nil
9050 ] autorelease];
9051
9052 [alert setContext:@"upgrade"];
9053 [alert show];
9054 }
9055 }
9056
9057 - (void) returnToCydia {
9058 [self _loaded];
9059 }
9060
9061 - (void) _saveConfig {
9062 @synchronized (database_) {
9063 _trace();
9064 MetaFile_.Sync();
9065 _trace();
9066 }
9067
9068 if (Changed_) {
9069 NSString *error(nil);
9070
9071 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9072 _trace();
9073 NSError *error(nil);
9074 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9075 NSLog(@"failure to save metadata data: %@", error);
9076 _trace();
9077
9078 Changed_ = false;
9079 } else {
9080 NSLog(@"failure to serialize metadata: %@", error);
9081 }
9082 }
9083
9084 CydiaWriteSources();
9085 }
9086
9087 // Navigation controller for the queuing badge.
9088 - (UINavigationController *) queueNavigationController {
9089 NSArray *controllers = [tabbar_ viewControllers];
9090 return [controllers objectAtIndex:3];
9091 }
9092
9093 - (void) unloadData {
9094 [tabbar_ unloadData];
9095 }
9096
9097 - (void) _updateData {
9098 [self _saveConfig];
9099 [self unloadData];
9100
9101 UINavigationController *navigation = [self queueNavigationController];
9102
9103 id queuedelegate = nil;
9104 if ([[navigation viewControllers] count] > 0)
9105 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9106
9107 [queuedelegate queueStatusDidChange];
9108 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9109 }
9110
9111 - (void) _refreshIfPossible:(NSDate *)update {
9112 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9113
9114 bool recently = false;
9115 if (update != nil) {
9116 NSTimeInterval interval([update timeIntervalSinceNow]);
9117 if (interval <= 0 && interval > -(15*60))
9118 recently = true;
9119 }
9120
9121 // Don't automatic refresh if:
9122 // - We already refreshed recently.
9123 // - We already auto-refreshed this launch.
9124 // - Auto-refresh is disabled.
9125 if (recently || loaded_ || ManualRefresh) {
9126 // If we are cancelling, we need to make sure it knows it's already loaded.
9127 loaded_ = true;
9128
9129 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9130 } else {
9131 // We are going to load, so remember that.
9132 loaded_ = true;
9133
9134 // If we can reach the server, auto-refresh!
9135 if (IsReachable("cydia.saurik.com"))
9136 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9137 }
9138
9139 [pool release];
9140 }
9141
9142 - (void) refreshIfPossible {
9143 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9144 }
9145
9146 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9147 @synchronized (self) {
9148 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9149 [hud setText:UCLocalize("RELOADING_DATA")];
9150
9151 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9152
9153 size_t changes(0);
9154
9155 [essential_ removeAllObjects];
9156 [broken_ removeAllObjects];
9157
9158 NSArray *packages([database_ packages]);
9159 for (Package *package in packages) {
9160 if ([package half])
9161 [broken_ addObject:package];
9162 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9163 if ([package essential] && [package installed] != nil)
9164 [essential_ addObject:package];
9165 ++changes;
9166 }
9167 }
9168
9169 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9170 if (changes != 0) {
9171 _trace();
9172 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9173 [changesItem setBadgeValue:badge];
9174 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9175 [self setApplicationIconBadgeNumber:changes];
9176 } else {
9177 _trace();
9178 [changesItem setBadgeValue:nil];
9179 [changesItem setAnimatedBadge:NO];
9180 [self setApplicationIconBadgeNumber:0];
9181 }
9182
9183 [self _updateData];
9184
9185 if (hud != nil)
9186 [self removeProgressHUD:hud];
9187 } }
9188
9189 - (void) updateData {
9190 [self _updateData];
9191 }
9192
9193 - (void) updateDataAndLoad {
9194 [self _updateData];
9195 if ([database_ progressDelegate] == nil)
9196 [self _loaded];
9197 }
9198
9199 - (void) update_ {
9200 [database_ update];
9201 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9202 }
9203
9204 - (void) disemulate {
9205 if (emulated_ == nil)
9206 return;
9207
9208 [window_ addSubview:[tabbar_ view]];
9209 [[emulated_ view] removeFromSuperview];
9210 emulated_ = nil;
9211 [window_ setUserInteractionEnabled:YES];
9212 }
9213
9214 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9215 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9216 if (IsWildcat_)
9217 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9218
9219 UIViewController *parent;
9220 if (emulated_ == nil)
9221 parent = tabbar_;
9222 else if (!force)
9223 parent = emulated_;
9224 else {
9225 [self disemulate];
9226 parent = tabbar_;
9227 }
9228
9229 [parent presentModalViewController:navigation animated:YES];
9230 }
9231
9232 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9233 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9234
9235 if (navigation != nil)
9236 [navigation pushViewController:progress animated:YES];
9237 else
9238 [self presentModalViewController:progress force:YES];
9239
9240 [progress invoke:invocation withTitle:title];
9241 return progress;
9242 }
9243
9244 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9245 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9246 }
9247
9248 - (void) repairWithInvocation:(NSInvocation *)invocation {
9249 _trace();
9250 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9251 _trace();
9252 }
9253
9254 - (void) repairWithSelector:(SEL)selector {
9255 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9256 }
9257
9258 - (void) reloadData {
9259 [self reloadDataWithInvocation:nil];
9260 if ([database_ progressDelegate] == nil)
9261 [self _loaded];
9262 }
9263
9264 - (void) syncData {
9265 [self _saveConfig];
9266 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9267 }
9268
9269 - (void) addSource:(NSDictionary *) source {
9270 CydiaAddSource(source);
9271 }
9272
9273 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9274 CydiaAddSource(href, distribution, sections);
9275 }
9276
9277 - (void) addTrivialSource:(NSString *)href {
9278 CydiaAddSource(href, @"./");
9279 }
9280
9281 - (void) updateValues {
9282 Changed_ = true;
9283 }
9284
9285 - (void) resolve {
9286 pkgProblemResolver *resolver = [database_ resolver];
9287
9288 resolver->InstallProtect();
9289 if (!resolver->Resolve(true))
9290 _error->Discard();
9291 }
9292
9293 - (bool) perform {
9294 // XXX: this is a really crappy way of doing this.
9295 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9296 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9297 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9298 if ([tabbar_ updating])
9299 [tabbar_ cancelUpdate];
9300
9301 if (![database_ prepare])
9302 return false;
9303
9304 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9305 [page setDelegate:self];
9306 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9307
9308 if (IsWildcat_)
9309 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9310 [tabbar_ presentModalViewController:confirm_ animated:YES];
9311
9312 return true;
9313 }
9314
9315 - (void) queue {
9316 @synchronized (self) {
9317 [self perform];
9318 }
9319 }
9320
9321 - (void) clearPackage:(Package *)package {
9322 @synchronized (self) {
9323 [package clear];
9324 [self resolve];
9325 [self perform];
9326 }
9327 }
9328
9329 - (void) installPackages:(NSArray *)packages {
9330 @synchronized (self) {
9331 for (Package *package in packages)
9332 [package install];
9333 [self resolve];
9334 [self perform];
9335 }
9336 }
9337
9338 - (void) installPackage:(Package *)package {
9339 @synchronized (self) {
9340 [package install];
9341 [self resolve];
9342 [self perform];
9343 }
9344 }
9345
9346 - (void) removePackage:(Package *)package {
9347 @synchronized (self) {
9348 [package remove];
9349 [self resolve];
9350 [self perform];
9351 }
9352 }
9353
9354 - (void) distUpgrade {
9355 @synchronized (self) {
9356 if (![database_ upgrade])
9357 return;
9358 [self perform];
9359 }
9360 }
9361
9362 - (void) _uicache {
9363 _trace();
9364 system("su -c /usr/bin/uicache mobile");
9365 _trace();
9366 }
9367
9368 - (void) uicache {
9369 UIProgressHUD *hud([self addProgressHUD]);
9370 [hud setText:UCLocalize("LOADING")];
9371 [self yieldToSelector:@selector(_uicache)];
9372 [self removeProgressHUD:hud];
9373 }
9374
9375 - (void) perform_ {
9376 [database_ perform];
9377 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9378 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9379 }
9380
9381 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9382 Queuing_ = false;
9383 ++locked_;
9384 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9385 --locked_;
9386 }
9387
9388 - (void) showSettings {
9389 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9390 }
9391
9392 - (void) retainNetworkActivityIndicator {
9393 if (activity_++ == 0)
9394 [self setNetworkActivityIndicatorVisible:YES];
9395
9396 #if TraceLogging
9397 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9398 #endif
9399 }
9400
9401 - (void) releaseNetworkActivityIndicator {
9402 if (--activity_ == 0)
9403 [self setNetworkActivityIndicatorVisible:NO];
9404
9405 #if TraceLogging
9406 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9407 #endif
9408
9409 }
9410
9411 - (void) cancelAndClear:(bool)clear {
9412 @synchronized (self) {
9413 if (clear) {
9414 [database_ clear];
9415 Queuing_ = false;
9416 } else {
9417 Queuing_ = true;
9418 }
9419
9420 [self _updateData];
9421 }
9422 }
9423
9424 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9425 NSString *context([alert context]);
9426
9427 if ([context isEqualToString:@"conffile"]) {
9428 FILE *input = [database_ input];
9429 if (button == [alert cancelButtonIndex])
9430 fprintf(input, "N\n");
9431 else if (button == [alert firstOtherButtonIndex])
9432 fprintf(input, "Y\n");
9433 fflush(input);
9434
9435 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9436 } else if ([context isEqualToString:@"fixhalf"]) {
9437 if (button == [alert cancelButtonIndex]) {
9438 @synchronized (self) {
9439 for (Package *broken in (id) broken_) {
9440 [broken remove];
9441
9442 NSString *id = [broken id];
9443 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9444 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9445 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9446 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9447 }
9448
9449 [self resolve];
9450 [self perform];
9451 }
9452 } else if (button == [alert firstOtherButtonIndex]) {
9453 [broken_ removeAllObjects];
9454 [self _loaded];
9455 }
9456
9457 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9458 } else if ([context isEqualToString:@"upgrade"]) {
9459 if (button == [alert firstOtherButtonIndex]) {
9460 @synchronized (self) {
9461 for (Package *essential in (id) essential_)
9462 [essential install];
9463
9464 [self resolve];
9465 [self perform];
9466 }
9467 } else if (button == [alert firstOtherButtonIndex] + 1) {
9468 [self distUpgrade];
9469 } else if (button == [alert cancelButtonIndex]) {
9470 Ignored_ = YES;
9471 }
9472
9473 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9474 }
9475 }
9476
9477 - (void) system:(NSString *)command {
9478 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9479
9480 _trace();
9481 system([command UTF8String]);
9482 _trace();
9483
9484 [pool release];
9485 }
9486
9487 - (void) applicationWillSuspend {
9488 [database_ clean];
9489 [super applicationWillSuspend];
9490 }
9491
9492 - (BOOL) isSafeToSuspend {
9493 if (locked_ != 0) {
9494 #if !ForRelease
9495 NSLog(@"isSafeToSuspend: locked_ != 0");
9496 #endif
9497 return false;
9498 }
9499
9500 // Use external process status API internally.
9501 // This is probably a really bad idea.
9502 // XXX: what is the point of this? does this solve anything at all?
9503 uint64_t status = 0;
9504 int notify_token;
9505 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9506 notify_get_state(notify_token, &status);
9507 notify_cancel(notify_token);
9508 }
9509
9510 if (status != 0) {
9511 #if !ForRelease
9512 NSLog(@"isSafeToSuspend: status != 0");
9513 #endif
9514 return false;
9515 }
9516
9517 #if !ForRelease
9518 NSLog(@"isSafeToSuspend: -> true");
9519 #endif
9520 return true;
9521 }
9522
9523 - (void) applicationSuspend:(__GSEvent *)event {
9524 if ([self isSafeToSuspend])
9525 [super applicationSuspend:event];
9526 }
9527
9528 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9529 if ([self isSafeToSuspend])
9530 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9531 }
9532
9533 - (void) _setSuspended:(BOOL)value {
9534 if ([self isSafeToSuspend])
9535 [super _setSuspended:value];
9536 }
9537
9538 - (UIProgressHUD *) addProgressHUD {
9539 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9540 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9541
9542 [window_ setUserInteractionEnabled:NO];
9543
9544 UIViewController *target(tabbar_);
9545 if (UIViewController *modal = [target modalViewController])
9546 target = modal;
9547
9548 [hud showInView:[target view]];
9549
9550 ++locked_;
9551 return hud;
9552 }
9553
9554 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9555 --locked_;
9556 [hud hide];
9557 [hud removeFromSuperview];
9558 [window_ setUserInteractionEnabled:YES];
9559 }
9560
9561 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9562 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9563 }
9564
9565 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9566 NSString *scheme([[url scheme] lowercaseString]);
9567 if ([[url absoluteString] length] <= [scheme length] + 3)
9568 return nil;
9569 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9570 NSArray *components([path componentsSeparatedByString:@"/"]);
9571
9572 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9573 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9574 if (controller != nil)
9575 [controller setDelegate:self];
9576 return controller;
9577 }
9578
9579 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9580 return nil;
9581
9582 NSString *base([components objectAtIndex:0]);
9583
9584 CyteViewController *controller = nil;
9585
9586 if ([base isEqualToString:@"url"]) {
9587 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9588 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9589 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9590 } else if (!external && [components count] == 1) {
9591 if ([base isEqualToString:@"storage"]) {
9592 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9593 }
9594
9595 if ([base isEqualToString:@"sources"]) {
9596 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9597 }
9598
9599 if ([base isEqualToString:@"home"]) {
9600 controller = [[[HomeController alloc] init] autorelease];
9601 }
9602
9603 if ([base isEqualToString:@"sections"]) {
9604 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9605 }
9606
9607 if ([base isEqualToString:@"changes"]) {
9608 controller = [[[ChangesPackageListController alloc] initWithDatabase:database_] autorelease];
9609 }
9610
9611 if ([base isEqualToString:@"installed"]) {
9612 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9613 }
9614 } else if ([components count] == 2) {
9615 NSString *argument = [components objectAtIndex:1];
9616
9617 if ([base isEqualToString:@"package"]) {
9618 controller = [self pageForPackage:argument withReferrer:referrer];
9619 }
9620
9621 if (!external && [base isEqualToString:@"sections"]) {
9622 if ([argument isEqualToString:@"all"])
9623 argument = nil;
9624 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] source:nil] autorelease];
9625 }
9626
9627 if (!external && [base isEqualToString:@"sources"]) {
9628 if ([argument isEqualToString:@"add"]) {
9629 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9630 [(SourcesController *)controller showAddSourcePrompt];
9631 }
9632 }
9633
9634 if (!external && [base isEqualToString:@"launch"]) {
9635 [self launchApplicationWithIdentifier:argument suspended:NO];
9636 return nil;
9637 }
9638 } else if ([components count] == 3) {
9639 NSString *arg1 = [components objectAtIndex:1];
9640 NSString *arg2 = [components objectAtIndex:2];
9641
9642 if (!external && [base isEqualToString:@"package"]) {
9643 if ([arg2 isEqualToString:@"settings"]) {
9644 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9645 } else if ([arg2 isEqualToString:@"files"]) {
9646 if (Package *package = [database_ packageWithName:arg1]) {
9647 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9648 [(FileTable *)controller setPackage:package];
9649 }
9650 }
9651 }
9652
9653 if (!external && [base isEqualToString:@"sources"]) {
9654 Source *source = [database_ sourceWithKey:[arg1 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9655 NSString *section = [arg2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9656 if ([section isEqualToString:@"all"])
9657 section = nil;
9658
9659 controller = [[[SectionController alloc] initWithDatabase:database_ section:arg2 source:source] autorelease];
9660 }
9661 }
9662
9663 [controller setDelegate:self];
9664 return controller;
9665 }
9666
9667 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9668 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9669
9670 if (page != nil)
9671 [tabbar_ setUnselectedViewController:page];
9672
9673 return page != nil;
9674 }
9675
9676 - (void) applicationOpenURL:(NSURL *)url {
9677 [super applicationOpenURL:url];
9678
9679 if (!loaded_)
9680 starturl_ = url;
9681 else
9682 [self openCydiaURL:url forExternal:YES];
9683 }
9684
9685 - (void) applicationWillResignActive:(UIApplication *)application {
9686 // Stop refreshing if you get a phone call or lock the device.
9687 if ([tabbar_ updating])
9688 [tabbar_ cancelUpdate];
9689
9690 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9691 [super applicationWillResignActive:application];
9692 }
9693
9694 - (void) saveState {
9695 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9696 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9697 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9698 Changed_ = true;
9699
9700 [self _saveConfig];
9701 }
9702
9703 - (void) applicationWillTerminate:(UIApplication *)application {
9704 [self saveState];
9705 }
9706
9707 - (void) setConfigurationData:(NSString *)data {
9708 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9709
9710 if (!conffile_r(data)) {
9711 lprintf("E:invalid conffile\n");
9712 return;
9713 }
9714
9715 NSString *ofile = conffile_r[1];
9716 //NSString *nfile = conffile_r[2];
9717
9718 UIAlertView *alert = [[[UIAlertView alloc]
9719 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9720 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9721 delegate:self
9722 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9723 otherButtonTitles:
9724 UCLocalize("ACCEPT_NEW_COPY"),
9725 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9726 nil
9727 ] autorelease];
9728
9729 [alert setContext:@"conffile"];
9730 [alert setNumberOfRows:2];
9731 [alert show];
9732 }
9733
9734 - (void) addStashController {
9735 ++locked_;
9736 stash_ = [[[StashController alloc] init] autorelease];
9737 [window_ addSubview:[stash_ view]];
9738 }
9739
9740 - (void) removeStashController {
9741 [[stash_ view] removeFromSuperview];
9742 stash_ = nil;
9743 --locked_;
9744 }
9745
9746 - (void) stash {
9747 [self setIdleTimerDisabled:YES];
9748
9749 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9750 UpdateExternalStatus(1);
9751 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9752 UpdateExternalStatus(0);
9753
9754 [self removeStashController];
9755
9756 pid_t pid(ExecFork());
9757 if (pid == 0) {
9758 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9759 perror("launchctl stop");
9760 exit(0);
9761 }
9762
9763 ReapZombie(pid);
9764 }
9765
9766 - (void) setupViewControllers {
9767 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9768
9769 NSMutableArray *items([NSMutableArray arrayWithObjects:
9770 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9771 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease],
9772 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9773 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9774 nil]);
9775
9776 NSMutableArray *controllers([NSMutableArray array]);
9777 for (UITabBarItem *item in items) {
9778 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9779 [controller setTabBarItem:item];
9780 [controllers addObject:controller];
9781 }
9782 [tabbar_ setViewControllers:controllers];
9783
9784 [tabbar_ setUpdateDelegate:self];
9785 }
9786
9787 - (void) _sendMemoryWarningNotification {
9788 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9789 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9790 else
9791 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9792 }
9793
9794 - (void) _sendMemoryWarningNotifications {
9795 while (true) {
9796 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9797 sleep(2);
9798 //usleep(2000000);
9799 }
9800 }
9801
9802 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9803 NSLog(@"--");
9804 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9805 }
9806
9807 - (void) applicationDidFinishLaunching:(id)unused {
9808 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9809
9810 _trace();
9811 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9812 [self setApplicationSupportsShakeToEdit:NO];
9813
9814 @synchronized (HostConfig_) {
9815 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9816 }
9817
9818 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9819 initWithMemoryCapacity:524288
9820 diskCapacity:10485760
9821 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9822 ] autorelease]];
9823
9824 [CydiaWebViewController _initialize];
9825
9826 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9827
9828 // this would disallow http{,s} URLs from accessing this data
9829 //[WebView registerURLSchemeAsLocal:@"cydia"];
9830
9831 Font12_ = [UIFont systemFontOfSize:12];
9832 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9833 Font14_ = [UIFont systemFontOfSize:14];
9834 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9835 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9836
9837 essential_ = [NSMutableArray arrayWithCapacity:4];
9838 broken_ = [NSMutableArray arrayWithCapacity:4];
9839
9840 // XXX: I really need this thing... like, seriously... I'm sorry
9841 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9842
9843 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9844 [window_ orderFront:self];
9845 [window_ makeKey:self];
9846 [window_ setHidden:NO];
9847
9848 if (false) stash: {
9849 [self addStashController];
9850 // XXX: this would be much cleaner as a yieldToSelector:
9851 // that way the removeStashController could happen right here inline
9852 // we also could no longer require the useless stash_ field anymore
9853 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9854 return;
9855 }
9856
9857 struct stat root;
9858 int error(stat("/", &root));
9859 _assert(error != -1);
9860
9861 #define Stash_(path) do { \
9862 struct stat folder; \
9863 int error(lstat((path), &folder)); \
9864 if (error != -1 && ( \
9865 folder.st_dev == root.st_dev && \
9866 S_ISDIR(folder.st_mode) \
9867 ) || error == -1 && ( \
9868 errno == ENOENT || \
9869 errno == ENOTDIR \
9870 )) goto stash; \
9871 } while (false)
9872
9873 Stash_("/Applications");
9874 Stash_("/Library/Ringtones");
9875 Stash_("/Library/Wallpaper");
9876 //Stash_("/usr/bin");
9877 Stash_("/usr/include");
9878 Stash_("/usr/lib/pam");
9879 Stash_("/usr/libexec");
9880 Stash_("/usr/share");
9881 //Stash_("/var/lib");
9882
9883 database_ = [Database sharedInstance];
9884 [database_ setDelegate:self];
9885
9886 [window_ setUserInteractionEnabled:NO];
9887 [self setupViewControllers];
9888
9889 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9890 [window_ addSubview:[emulated_ view]];
9891
9892 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9893 _trace();
9894 }
9895
9896 - (NSArray *) defaultStartPages {
9897 NSMutableArray *standard = [NSMutableArray array];
9898 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9899 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9900 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9901 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9902 return standard;
9903 }
9904
9905 - (void) loadData {
9906 _trace();
9907 if (Role_ == nil) {
9908 [window_ setUserInteractionEnabled:YES];
9909 [self showSettings];
9910 return;
9911 } else {
9912 if ([emulated_ modalViewController] != nil)
9913 [emulated_ dismissModalViewControllerAnimated:YES];
9914 [window_ setUserInteractionEnabled:NO];
9915 }
9916
9917 [self reloadDataWithInvocation:nil];
9918 [self refreshIfPossible];
9919 PrintTimes();
9920
9921 [self disemulate];
9922
9923 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9924 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9925 int standardIndex = 0;
9926 NSArray *standard = [self defaultStartPages];
9927
9928 BOOL valid = YES;
9929
9930 if (saved == nil)
9931 valid = NO;
9932
9933 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9934 if (valid && closed != nil) {
9935 NSTimeInterval interval([closed timeIntervalSinceNow]);
9936 // XXX: Is 30 minutes the optimal time here?
9937 if (interval <= -(30*60))
9938 valid = NO;
9939 }
9940
9941 if (valid && [saved count] != [standard count])
9942 valid = NO;
9943
9944 if (valid) {
9945 for (unsigned int i = 0; i < [standard count]; i++) {
9946 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9947 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9948 // but it's good enough for now.
9949 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9950 valid = NO;
9951 break;
9952 }
9953 }
9954 }
9955
9956 NSArray *items = nil;
9957 if (valid) {
9958 [tabbar_ setSelectedIndex:savedIndex];
9959 items = saved;
9960 } else {
9961 [tabbar_ setSelectedIndex:standardIndex];
9962 items = standard;
9963 }
9964
9965 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9966 NSArray *stack = [items objectAtIndex:tab];
9967 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9968 NSMutableArray *current = [NSMutableArray array];
9969
9970 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9971 NSString *addr = [stack objectAtIndex:nav];
9972 NSURL *url = [NSURL URLWithString:addr];
9973 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9974 if (page != nil)
9975 [current addObject:page];
9976 }
9977
9978 [navigation setViewControllers:current];
9979 }
9980
9981 // (Try to) show the startup URL.
9982 if (starturl_ != nil) {
9983 [self openCydiaURL:starturl_ forExternal:NO];
9984 starturl_ = nil;
9985 }
9986 }
9987
9988 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9989 if (item != nil && IsWildcat_) {
9990 [sheet showFromBarButtonItem:item animated:YES];
9991 } else {
9992 [sheet showInView:window_];
9993 }
9994 }
9995
9996 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9997 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9998 [progress setTitle:task];
9999 [progress addProgressEvent:event];
10000 }
10001
10002 - (void) addProgressEventForTask:(NSArray *)data {
10003 CydiaProgressEvent *event([data objectAtIndex:0]);
10004 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10005 [self addProgressEvent:event forTask:task];
10006 }
10007
10008 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10009 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10010 }
10011
10012 @end
10013
10014 /*IMP alloc_;
10015 id Alloc_(id self, SEL selector) {
10016 id object = alloc_(self, selector);
10017 lprintf("[%s]A-%p\n", self->isa->name, object);
10018 return object;
10019 }*/
10020
10021 /*IMP dealloc_;
10022 id Dealloc_(id self, SEL selector) {
10023 id object = dealloc_(self, selector);
10024 lprintf("[%s]D-%p\n", self->isa->name, object);
10025 return object;
10026 }*/
10027
10028 Class $WebDefaultUIKitDelegate;
10029
10030 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10031 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10032 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10033 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10034 }
10035
10036 static NSSet *MobilizedFiles_;
10037
10038 static NSURL *MobilizeURL(NSURL *url) {
10039 NSString *path([url path]);
10040 if ([path hasPrefix:@"/var/root/"]) {
10041 NSString *file([path substringFromIndex:10]);
10042 if ([MobilizedFiles_ containsObject:file])
10043 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10044 }
10045
10046 return url;
10047 }
10048
10049 Class $CFXPreferencesPropertyListSource;
10050 @class CFXPreferencesPropertyListSource;
10051
10052 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10053 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10054 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10055 url = MobilizeURL(url);
10056 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10057 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10058 url = old;
10059 [pool release];
10060 return value;
10061 }
10062
10063 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10064 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10065 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10066 url = MobilizeURL(url);
10067 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10068 //NSLog(@"%@ %@", [url absoluteString], value);
10069 url = old;
10070 [pool release];
10071 return value;
10072 }
10073
10074 Class $NSURLConnection;
10075
10076 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10077 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10078
10079 NSURL *url([copy URL]);
10080
10081 NSString *host([url host]);
10082 NSString *scheme([[url scheme] lowercaseString]);
10083
10084 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10085
10086 @synchronized (HostConfig_) {
10087 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10088 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10089 [copy setHTTPShouldUsePipelining:YES];
10090
10091 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10092 if ([control isEqualToString:@"max-age=0"])
10093 if ([CachedURLs_ containsObject:url]) {
10094 #if !ForRelease
10095 NSLog(@"~~~: %@", url);
10096 #endif
10097
10098 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10099
10100 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10101 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10102 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10103 }
10104 }
10105
10106 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10107 } return self;
10108 }
10109
10110 Class $WAKWindow;
10111
10112 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10113 CGSize size([[UIScreen mainScreen] bounds].size);
10114 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10115 if ([$WAKWindow hasLandscapeOrientation])
10116 std::swap(size.width, size.height);*/
10117 return size;
10118 }
10119
10120 int main(int argc, char *argv[]) {
10121 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10122
10123 _trace();
10124
10125 UpdateExternalStatus(0);
10126
10127 if (Class $UIDevice = objc_getClass("UIDevice")) {
10128 UIDevice *device([$UIDevice currentDevice]);
10129 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10130 } else
10131 IsWildcat_ = false;
10132
10133 UIScreen *screen([UIScreen mainScreen]);
10134 if ([screen respondsToSelector:@selector(scale)])
10135 ScreenScale_ = [screen scale];
10136 else
10137 ScreenScale_ = 1;
10138
10139 UIDevice *device([UIDevice currentDevice]);
10140 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10141 Idiom_ = @"iphone";
10142 else {
10143 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10144 if (idiom == UIUserInterfaceIdiomPhone)
10145 Idiom_ = @"iphone";
10146 else if (idiom == UIUserInterfaceIdiomPad)
10147 Idiom_ = @"ipad";
10148 else
10149 NSLog(@"unknown UIUserInterfaceIdiom!");
10150 }
10151
10152 Pcre pattern("^([0-9]+\\.[0-9]+)");
10153
10154 if (pattern([device systemVersion]))
10155 Firmware_ = pattern[1];
10156 if (pattern(Cydia_))
10157 Major_ = pattern[1];
10158
10159 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10160
10161 HostConfig_ = [[[NSObject alloc] init] autorelease];
10162 @synchronized (HostConfig_) {
10163 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10164 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10165 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10166 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10167 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10168 }
10169
10170 NSString *ui(@"ui/ios");
10171 if (Idiom_ != nil)
10172 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10173 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10174 UI_ = CydiaURL(ui);
10175
10176 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10177
10178 MobilizedFiles_ = [NSMutableSet setWithObjects:
10179 @"Library/Preferences/com.apple.Accessibility.plist",
10180 @"Library/Preferences/com.apple.preferences.sounds.plist",
10181 nil];
10182
10183 /* Library Hacks {{{ */
10184 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10185
10186 $WAKWindow = objc_getClass("WAKWindow");
10187 if ($WAKWindow != NULL)
10188 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10189 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10190
10191 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10192
10193 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10194 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10195 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10196 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10197 }
10198
10199 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10200 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10201 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10202 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10203 }
10204
10205 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10206 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10207 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10208 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10209 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10210 }
10211
10212 $NSURLConnection = objc_getClass("NSURLConnection");
10213 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10214 if (NSURLConnection$init$ != NULL) {
10215 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10216 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10217 }
10218 /* }}} */
10219 /* Set Locale {{{ */
10220 Locale_ = CFLocaleCopyCurrent();
10221 Languages_ = [NSLocale preferredLanguages];
10222
10223 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10224 //NSLog(@"%@", [Languages_ description]);
10225
10226 const char *lang;
10227 if (Locale_ != NULL)
10228 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10229 else if (Languages_ != nil && [Languages_ count] != 0)
10230 lang = [[Languages_ objectAtIndex:0] UTF8String];
10231 else
10232 // XXX: consider just setting to C and then falling through?
10233 lang = NULL;
10234
10235 if (lang != NULL) {
10236 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10237 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10238 }
10239
10240 NSLog(@"Setting Language: %s", lang);
10241
10242 if (lang != NULL) {
10243 setenv("LANG", lang, true);
10244 std::setlocale(LC_ALL, lang);
10245 }
10246 /* }}} */
10247
10248 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10249
10250 /* Parse Arguments {{{ */
10251 bool substrate(false);
10252
10253 if (argc != 0) {
10254 char **args(argv);
10255 int arge(1);
10256
10257 for (int argi(1); argi != argc; ++argi)
10258 if (strcmp(argv[argi], "--") == 0) {
10259 arge = argi;
10260 argv[argi] = argv[0];
10261 argv += argi;
10262 argc -= argi;
10263 break;
10264 }
10265
10266 for (int argi(1); argi != arge; ++argi)
10267 if (strcmp(args[argi], "--substrate") == 0)
10268 substrate = true;
10269 else
10270 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10271 }
10272 /* }}} */
10273
10274 App_ = [[NSBundle mainBundle] bundlePath];
10275 Advanced_ = YES;
10276
10277 setuid(0);
10278 setgid(0);
10279
10280 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10281 alloc_ = alloc->method_imp;
10282 alloc->method_imp = (IMP) &Alloc_;*/
10283
10284 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10285 dealloc_ = dealloc->method_imp;
10286 dealloc->method_imp = (IMP) &Dealloc_;*/
10287
10288 /* System Information {{{ */
10289 size_t size;
10290
10291 int maxproc;
10292 size = sizeof(maxproc);
10293 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10294 perror("sysctlbyname(\"kern.maxproc\", ?)");
10295 else if (maxproc < 64) {
10296 maxproc = 64;
10297 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10298 perror("sysctlbyname(\"kern.maxproc\", #)");
10299 }
10300
10301 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10302 char *osversion = new char[size];
10303 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10304 perror("sysctlbyname(\"kern.osversion\", ?)");
10305 else
10306 System_ = [NSString stringWithUTF8String:osversion];
10307
10308 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10309 char *machine = new char[size];
10310 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10311 perror("sysctlbyname(\"hw.machine\", ?)");
10312 else
10313 Machine_ = machine;
10314
10315 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10316 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10317 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10318
10319 UniqueID_ = [device uniqueIdentifier];
10320
10321 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10322 Product_ = [info objectForKey:@"SafariProductVersion"];
10323 Safari_ = [info objectForKey:@"CFBundleVersion"];
10324 }
10325
10326 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10327
10328 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10329 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10330 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10331 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10332 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10333 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10334
10335 UserAgent_ = agent;
10336 /* }}} */
10337 /* Load Database {{{ */
10338 _trace();
10339 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10340 _trace();
10341 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10342
10343 if (Metadata_ == NULL)
10344 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10345 else {
10346 Settings_ = [Metadata_ objectForKey:@"Settings"];
10347
10348 Packages_ = [Metadata_ objectForKey:@"Packages"];
10349
10350 Values_ = [Metadata_ objectForKey:@"Values"];
10351 Sections_ = [Metadata_ objectForKey:@"Sections"];
10352 Sources_ = [Metadata_ objectForKey:@"Sources"];
10353
10354 Token_ = [Metadata_ objectForKey:@"Token"];
10355
10356 Version_ = [Metadata_ objectForKey:@"Version"];
10357 }
10358
10359 if (Settings_ != nil)
10360 Role_ = [Settings_ objectForKey:@"Role"];
10361
10362 if (Values_ == nil) {
10363 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10364 [Metadata_ setObject:Values_ forKey:@"Values"];
10365 }
10366
10367 if (Sections_ == nil) {
10368 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10369 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10370 }
10371
10372 if (Sources_ == nil) {
10373 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10374 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10375 }
10376
10377 if (Version_ == nil) {
10378 Version_ = [NSNumber numberWithUnsignedInt:0];
10379 [Metadata_ setObject:Version_ forKey:@"Version"];
10380 }
10381
10382 if ([Version_ unsignedIntValue] == 0) {
10383 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10384 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10385 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10386 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10387
10388 Version_ = [NSNumber numberWithUnsignedInt:1];
10389 [Metadata_ setObject:Version_ forKey:@"Version"];
10390
10391 [Metadata_ removeObjectForKey:@"LastUpdate"];
10392
10393 Changed_ = true;
10394 }
10395 /* }}} */
10396
10397 CydiaWriteSources();
10398
10399 _trace();
10400 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10401 _trace();
10402
10403 if (Packages_ != nil) {
10404 bool fail(false);
10405 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10406 _trace();
10407
10408 if (!fail) {
10409 [Metadata_ removeObjectForKey:@"Packages"];
10410 Packages_ = nil;
10411 Changed_ = true;
10412 }
10413 }
10414
10415 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10416
10417 #define MobileSubstrate_(name) \
10418 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10419 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10420 if (handle == NULL) \
10421 NSLog(@"%s", dlerror()); \
10422 }
10423
10424 MobileSubstrate_(Activator)
10425 MobileSubstrate_(libstatusbar)
10426 MobileSubstrate_(SimulatedKeyEvents)
10427 MobileSubstrate_(WinterBoard)
10428
10429 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10430 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10431
10432 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10433
10434 if (access("/User", F_OK) != 0 || version != 5) {
10435 _trace();
10436 system("/usr/libexec/cydia/firmware.sh");
10437 _trace();
10438 }
10439
10440 _assert([[NSFileManager defaultManager]
10441 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10442 withIntermediateDirectories:YES
10443 attributes:nil
10444 error:NULL
10445 ]);
10446
10447 if (access("/tmp/cydia.chk", F_OK) == 0) {
10448 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10449 _assert(errno == ENOENT);
10450 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10451 _assert(errno == ENOENT);
10452 }
10453
10454 /* APT Initialization {{{ */
10455 _assert(pkgInitConfig(*_config));
10456 _assert(pkgInitSystem(*_config, _system));
10457
10458 if (lang != NULL)
10459 _config->Set("APT::Acquire::Translation", lang);
10460
10461 // XXX: this timeout might be important :(
10462 //_config->Set("Acquire::http::Timeout", 15);
10463
10464 _config->Set("Acquire::http::MaxParallel", 3);
10465 /* }}} */
10466 /* Color Choices {{{ */
10467 space_ = CGColorSpaceCreateDeviceRGB();
10468
10469 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10470 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10471 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10472 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10473 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10474 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10475 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10476 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10477 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10478
10479 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10480 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10481 /* }}}*/
10482 /* UIKit Configuration {{{ */
10483 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10484 if ($GSFontSetUseLegacyFontMetrics != NULL)
10485 $GSFontSetUseLegacyFontMetrics(YES);
10486
10487 // XXX: I have a feeling this was important
10488 //UIKeyboardDisableAutomaticAppearance();
10489 /* }}} */
10490
10491 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10492 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10493
10494 ShowPromoted_ = fast;
10495 PulseInterval_ = fast ? 50000 : 500000;
10496
10497 Colon_ = UCLocalize("COLON_DELIMITED");
10498 Elision_ = UCLocalize("ELISION");
10499 Error_ = UCLocalize("ERROR");
10500 Warning_ = UCLocalize("WARNING");
10501
10502 #if !ForRelease
10503 AprilFools_ = true;
10504 #else
10505 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10506 AprilFools_ = date.month == 4 && date.day == 1;
10507 #endif
10508
10509 _trace();
10510 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10511
10512 CGColorSpaceRelease(space_);
10513 CFRelease(Locale_);
10514
10515 [pool release];
10516 return value;
10517 }