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