]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
It's possible to externally lock dpkg under _root!
[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 _root(true) _system->Lock();
3819
3820 _trace();
3821 OpProgress progress;
3822 bool opened;
3823 open:
3824 _profile(reloadDataWithInvocation$pkgCacheFile)
3825 opened = cache_.Open(progress, false);
3826 _end
3827 if (!opened) {
3828 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3829 while (!_error->empty()) {
3830 std::string error;
3831 bool warning(!_error->PopMessage(error));
3832
3833 lprintf("cache_.Open():[%s]\n", error.c_str());
3834
3835 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3836
3837 SEL repair(NULL);
3838 if (false);
3839 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3840 repair = @selector(configure);
3841 //else if (error == "The package lists or status file could not be parsed or opened.")
3842 // repair = @selector(update);
3843 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3844 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3845 // else if (error == "Malformed Status line")
3846 // else if (error == "The list of sources could not be read.")
3847
3848 if (repair != NULL) {
3849 _error->Discard();
3850 [delegate_ repairWithSelector:repair];
3851 goto open;
3852 }
3853 }
3854
3855 _system->UnLock();
3856 return;
3857 }
3858 _trace();
3859
3860 unlink("/tmp/cydia.chk");
3861
3862 now_ = [[NSDate date] timeIntervalSince1970];
3863
3864 policy_ = new pkgDepCache::Policy();
3865 records_ = new pkgRecords(cache_);
3866 resolver_ = new pkgProblemResolver(cache_);
3867 fetcher_ = new pkgAcquire(&status_);
3868 lock_ = NULL;
3869
3870 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3871 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3872 return;
3873 }
3874
3875 _profile(reloadDataWithInvocation$pkgApplyStatus)
3876 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3877 return;
3878 _end
3879
3880 if (cache_->BrokenCount() != 0) {
3881 _profile(pkgApplyStatus$pkgFixBroken)
3882 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3883 return;
3884 _end
3885
3886 if (cache_->BrokenCount() != 0) {
3887 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3888 return;
3889 }
3890
3891 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3892 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3893 return;
3894 _end
3895 }
3896
3897 for (Source *object in (id) sourceList_) {
3898 metaIndex *source([object metaIndex]);
3899 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3900 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3901 // XXX: this could be more intelligent
3902 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3903 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3904 if (!cached.end())
3905 sourceMap_[cached->ID] = object;
3906 }
3907 }
3908
3909 {
3910 /*std::vector<Package *> packages;
3911 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3912 packages_ = nil;*/
3913
3914 _profile(reloadDataWithInvocation$packageWithIterator)
3915 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3916 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3917 //packages.push_back(package);
3918 CFArrayAppendValue(packages_, CFRetain(package));
3919 _end
3920
3921
3922 /*if (packages.empty())
3923 packages_ = [[NSArray alloc] init];
3924 else
3925 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3926 _trace();*/
3927
3928 _profile(reloadDataWithInvocation$radix$8)
3929 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3930 _end
3931
3932 _profile(reloadDataWithInvocation$radix$4)
3933 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3934 _end
3935
3936 _profile(reloadDataWithInvocation$radix$0)
3937 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3938 _end
3939
3940 _profile(reloadDataWithInvocation$insertion)
3941 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3942 _end
3943
3944 /*_profile(reloadDataWithInvocation$CFQSortArray)
3945 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3946 _end*/
3947
3948 /*_profile(reloadDataWithInvocation$stdsort)
3949 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3950 _end*/
3951
3952 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3953 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3954 _end*/
3955
3956 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3957 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3958 _end*/
3959
3960
3961 size_t count(CFArrayGetCount(packages_));
3962 MetaFile_->active_ = count;
3963 for (size_t index(0); index != count; ++index)
3964 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3965 }
3966 } }
3967
3968 - (void) clear {
3969 @synchronized (self) {
3970 delete resolver_;
3971 resolver_ = new pkgProblemResolver(cache_);
3972
3973 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3974 if (!cache_[iterator].Keep())
3975 cache_->MarkKeep(iterator, false);
3976 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3977 cache_->SetReInstall(iterator, false);
3978 } }
3979
3980 - (void) configure {
3981 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3982 _trace();
3983 system([dpkg UTF8String]);
3984 _trace();
3985 }
3986
3987 - (bool) clean {
3988 @synchronized (self) {
3989 // XXX: I don't remember this condition
3990 if (lock_ != NULL)
3991 return false;
3992
3993 FileFd Lock;
3994 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3995
3996 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3997
3998 if ([self popErrorWithTitle:title])
3999 return false;
4000
4001 pkgAcquire fetcher;
4002 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4003
4004 CydiaLogCleaner cleaner;
4005 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4006 return false;
4007
4008 return true;
4009 } }
4010
4011 - (bool) prepare {
4012 fetcher_->Shutdown();
4013
4014 pkgRecords records(cache_);
4015
4016 lock_ = new FileFd();
4017 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4018
4019 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4020
4021 if ([self popErrorWithTitle:title])
4022 return false;
4023
4024 pkgSourceList list;
4025 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4026 return false;
4027
4028 manager_ = (_system->CreatePM(cache_));
4029 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4030 return false;
4031
4032 return true;
4033 }
4034
4035 - (void) perform {
4036 bool substrate(RestartSubstrate_);
4037 RestartSubstrate_ = false;
4038
4039 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4040
4041 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4042 pkgSourceList list;
4043 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4044 return;
4045 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4046 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4047 }
4048
4049 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4050
4051 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4052 _trace();
4053 [self popErrorWithTitle:title];
4054 return;
4055 }
4056
4057 bool failed = false;
4058 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4059 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4060 continue;
4061 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4062 continue;
4063
4064 std::string uri = (*item)->DescURI();
4065 std::string error = (*item)->ErrorText;
4066
4067 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4068 failed = true;
4069
4070 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4071 [delegate_ addProgressEventOnMainThread:event forTask:title];
4072 }
4073
4074 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4075
4076 if (failed) {
4077 _trace();
4078 return;
4079 }
4080
4081 if (substrate)
4082 RestartSubstrate_ = true;
4083
4084 _system->UnLock();
4085 pkgPackageManager::OrderResult result;
4086 _root(true) result = manager_->DoInstall(statusfd_);
4087 if ([self popErrorWithTitle:title])
4088 return;
4089
4090 if (result == pkgPackageManager::Failed) {
4091 _trace();
4092 return;
4093 }
4094
4095 if (result != pkgPackageManager::Completed) {
4096 _trace();
4097 return;
4098 }
4099
4100 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4101 pkgSourceList list;
4102 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4103 return;
4104 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4105 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4106 }
4107
4108 if (![before isEqualToArray:after])
4109 [self update];
4110 }
4111
4112 - (bool) upgrade {
4113 NSString *title(UCLocalize("UPGRADE"));
4114 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4115 return false;
4116 return true;
4117 }
4118
4119 - (void) update {
4120 [self updateWithStatus:status_];
4121 }
4122
4123 - (void) updateWithStatus:(CancelStatus &)status {
4124 NSString *title(UCLocalize("REFRESHING_DATA"));
4125
4126 pkgSourceList list;
4127 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4128 return;
4129
4130 FileFd lock;
4131 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4132 if ([self popErrorWithTitle:title])
4133 return;
4134
4135 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4136
4137 bool success(ListUpdate(status, list, PulseInterval_));
4138 if (status.WasCancelled())
4139 _error->Discard();
4140 else {
4141 [self popErrorWithTitle:title forOperation:success];
4142 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4143 Changed_ = true;
4144 }
4145
4146 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4147 }
4148
4149 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4150 delegate_ = delegate;
4151 }
4152
4153 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4154 progress_ = delegate;
4155 status_.setDelegate(delegate);
4156 }
4157
4158 - (NSObject<ProgressDelegate> *) progressDelegate {
4159 return progress_;
4160 }
4161
4162 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4163 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4164 return i == sourceMap_.end() ? nil : i->second;
4165 }
4166
4167 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4168 for (Source *source in (id) sourceList_)
4169 [source setFetch:fetch forURI:uri];
4170 }
4171
4172 - (void) resetFetch {
4173 for (Source *source in (id) sourceList_)
4174 [source resetFetch];
4175 }
4176
4177 - (NSString *) mappedSectionForPointer:(const char *)section {
4178 _H<NSString> *mapped;
4179
4180 _profile(Database$mappedSectionForPointer$Cache)
4181 mapped = &sections_[section];
4182 _end
4183
4184 if (*mapped == NULL) {
4185 size_t length(strlen(section));
4186 char spaced[length + 1];
4187
4188 _profile(Database$mappedSectionForPointer$Replace)
4189 for (size_t index(0); index != length; ++index)
4190 spaced[index] = section[index] == '_' ? ' ' : section[index];
4191 spaced[length] = '\0';
4192 _end
4193
4194 NSString *string;
4195
4196 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4197 string = [NSString stringWithUTF8String:spaced];
4198 _end
4199
4200 _profile(Database$mappedSectionForPointer$Map)
4201 string = [SectionMap_ objectForKey:string] ?: string;
4202 _end
4203
4204 *mapped = string;
4205 } return *mapped;
4206 }
4207
4208 @end
4209 /* }}} */
4210
4211 static _H<NSMutableSet> Diversions_;
4212
4213 @interface Diversion : NSObject {
4214 Pcre pattern_;
4215 _H<NSString> key_;
4216 _H<NSString> format_;
4217 }
4218
4219 @end
4220
4221 @implementation Diversion
4222
4223 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4224 if ((self = [super init]) != nil) {
4225 pattern_ = [from UTF8String];
4226 key_ = from;
4227 format_ = to;
4228 } return self;
4229 }
4230
4231 - (NSString *) divert:(NSString *)url {
4232 return !pattern_(url) ? nil : pattern_->*format_;
4233 }
4234
4235 + (NSURL *) divertURL:(NSURL *)url {
4236 divert:
4237 NSString *href([url absoluteString]);
4238
4239 for (Diversion *diversion in (id) Diversions_)
4240 if (NSString *diverted = [diversion divert:href]) {
4241 #if !ForRelease
4242 NSLog(@"div: %@", diverted);
4243 #endif
4244 url = [NSURL URLWithString:diverted];
4245 goto divert;
4246 }
4247
4248 return url;
4249 }
4250
4251 - (NSString *) key {
4252 return key_;
4253 }
4254
4255 - (NSUInteger) hash {
4256 return [key_ hash];
4257 }
4258
4259 - (BOOL) isEqual:(Diversion *)object {
4260 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4261 }
4262
4263 @end
4264
4265 @interface CydiaObject : NSObject {
4266 _H<CyteWebViewController> indirect_;
4267 _transient id delegate_;
4268 }
4269
4270 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4271
4272 @end
4273
4274 @class CydiaObject;
4275
4276 @interface CydiaWebViewController : CyteWebViewController {
4277 _H<CydiaObject> cydia_;
4278 }
4279
4280 + (void) addDiversion:(Diversion *)diversion;
4281 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4282 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4283 - (void) setDelegate:(id)delegate;
4284
4285 @end
4286
4287 /* Web Scripting {{{ */
4288 @implementation CydiaObject
4289
4290 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4291 if ((self = [super init]) != nil) {
4292 indirect_ = (CyteWebViewController *) indirect;
4293 } return self;
4294 }
4295
4296 - (void) setDelegate:(id)delegate {
4297 delegate_ = delegate;
4298 }
4299
4300 + (NSArray *) _attributeKeys {
4301 return [NSArray arrayWithObjects:
4302 @"bbsnum",
4303 @"build",
4304 @"coreFoundationVersionNumber",
4305 @"device",
4306 @"ecid",
4307 @"firmware",
4308 @"hostname",
4309 @"idiom",
4310 @"mcc",
4311 @"mnc",
4312 @"model",
4313 @"operator",
4314 @"role",
4315 @"serial",
4316 @"token",
4317 @"version",
4318 nil];
4319 }
4320
4321 - (NSArray *) attributeKeys {
4322 return [[self class] _attributeKeys];
4323 }
4324
4325 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4326 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4327 }
4328
4329 - (NSString *) version {
4330 return Cydia_;
4331 }
4332
4333 - (NSString *) build {
4334 return System_;
4335 }
4336
4337 - (NSString *) coreFoundationVersionNumber {
4338 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4339 }
4340
4341 - (NSString *) device {
4342 return UniqueIdentifier();
4343 }
4344
4345 - (NSString *) firmware {
4346 return [[UIDevice currentDevice] systemVersion];
4347 }
4348
4349 - (NSString *) hostname {
4350 return [[UIDevice currentDevice] name];
4351 }
4352
4353 - (NSString *) idiom {
4354 return (id) Idiom_ ?: [NSNull null];
4355 }
4356
4357 - (NSString *) mcc {
4358 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4359 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4360 return nil;
4361 }
4362
4363 - (NSString *) mnc {
4364 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4365 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4366 return nil;
4367 }
4368
4369 - (NSString *) operator {
4370 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4371 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4372 return nil;
4373 }
4374
4375 - (NSString *) bbsnum {
4376 return (id) BBSNum_ ?: [NSNull null];
4377 }
4378
4379 - (NSString *) ecid {
4380 return (id) ChipID_ ?: [NSNull null];
4381 }
4382
4383 - (NSString *) serial {
4384 return SerialNumber_;
4385 }
4386
4387 - (NSString *) role {
4388 return (id) [NSNull null];
4389 }
4390
4391 - (NSString *) model {
4392 return [NSString stringWithUTF8String:Machine_];
4393 }
4394
4395 - (NSString *) token {
4396 return (id) Token_ ?: [NSNull null];
4397 }
4398
4399 + (NSString *) webScriptNameForSelector:(SEL)selector {
4400 if (false);
4401 else if (selector == @selector(addBridgedHost:))
4402 return @"addBridgedHost";
4403 else if (selector == @selector(addInsecureHost:))
4404 return @"addInsecureHost";
4405 else if (selector == @selector(addInternalRedirect::))
4406 return @"addInternalRedirect";
4407 else if (selector == @selector(addPipelinedHost:scheme:))
4408 return @"addPipelinedHost";
4409 else if (selector == @selector(addSource:::))
4410 return @"addSource";
4411 else if (selector == @selector(addTokenHost:))
4412 return @"addTokenHost";
4413 else if (selector == @selector(addTrivialSource:))
4414 return @"addTrivialSource";
4415 else if (selector == @selector(close))
4416 return @"close";
4417 else if (selector == @selector(du:))
4418 return @"du";
4419 else if (selector == @selector(stringWithFormat:arguments:))
4420 return @"format";
4421 else if (selector == @selector(getAllSources))
4422 return @"getAllSources";
4423 else if (selector == @selector(getApplicationInfo:value:))
4424 return @"getApplicationInfoValue";
4425 else if (selector == @selector(getKernelNumber:))
4426 return @"getKernelNumber";
4427 else if (selector == @selector(getKernelString:))
4428 return @"getKernelString";
4429 else if (selector == @selector(getInstalledPackages))
4430 return @"getInstalledPackages";
4431 else if (selector == @selector(getIORegistryEntry::))
4432 return @"getIORegistryEntry";
4433 else if (selector == @selector(getLocaleIdentifier))
4434 return @"getLocaleIdentifier";
4435 else if (selector == @selector(getPreferredLanguages))
4436 return @"getPreferredLanguages";
4437 else if (selector == @selector(getPackageById:))
4438 return @"getPackageById";
4439 else if (selector == @selector(getMetadataKeys))
4440 return @"getMetadataKeys";
4441 else if (selector == @selector(getMetadataValue:))
4442 return @"getMetadataValue";
4443 else if (selector == @selector(getSessionValue:))
4444 return @"getSessionValue";
4445 else if (selector == @selector(installPackages:))
4446 return @"installPackages";
4447 else if (selector == @selector(isReachable:))
4448 return @"isReachable";
4449 else if (selector == @selector(localizedStringForKey:value:table:))
4450 return @"localize";
4451 else if (selector == @selector(popViewController:))
4452 return @"popViewController";
4453 else if (selector == @selector(refreshSources))
4454 return @"refreshSources";
4455 else if (selector == @selector(registerFrame:))
4456 return @"registerFrame";
4457 else if (selector == @selector(removeButton))
4458 return @"removeButton";
4459 else if (selector == @selector(saveConfig))
4460 return @"saveConfig";
4461 else if (selector == @selector(setMetadataValue::))
4462 return @"setMetadataValue";
4463 else if (selector == @selector(setSessionValue::))
4464 return @"setSessionValue";
4465 else if (selector == @selector(substitutePackageNames:))
4466 return @"substitutePackageNames";
4467 else if (selector == @selector(scrollToBottom:))
4468 return @"scrollToBottom";
4469 else if (selector == @selector(setAllowsNavigationAction:))
4470 return @"setAllowsNavigationAction";
4471 else if (selector == @selector(setBadgeValue:))
4472 return @"setBadgeValue";
4473 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4474 return @"setButtonImage";
4475 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4476 return @"setButtonTitle";
4477 else if (selector == @selector(setHidesBackButton:))
4478 return @"setHidesBackButton";
4479 else if (selector == @selector(setHidesNavigationBar:))
4480 return @"setHidesNavigationBar";
4481 else if (selector == @selector(setNavigationBarStyle:))
4482 return @"setNavigationBarStyle";
4483 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4484 return @"setNavigationBarTintColor";
4485 else if (selector == @selector(setPasteboardString:))
4486 return @"setPasteboardString";
4487 else if (selector == @selector(setPasteboardURL:))
4488 return @"setPasteboardURL";
4489 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4490 return @"setScrollAlwaysBounceVertical";
4491 else if (selector == @selector(setScrollIndicatorStyle:))
4492 return @"setScrollIndicatorStyle";
4493 else if (selector == @selector(setToken:))
4494 return @"setToken";
4495 else if (selector == @selector(setViewportWidth:))
4496 return @"setViewportWidth";
4497 else if (selector == @selector(statfs:))
4498 return @"statfs";
4499 else if (selector == @selector(supports:))
4500 return @"supports";
4501 else if (selector == @selector(unload))
4502 return @"unload";
4503 else
4504 return nil;
4505 }
4506
4507 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4508 return [self webScriptNameForSelector:selector] == nil;
4509 }
4510
4511 - (BOOL) supports:(NSString *)feature {
4512 return [feature isEqualToString:@"window.open"];
4513 }
4514
4515 - (void) unload {
4516 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4517 }
4518
4519 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4520 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4521 }
4522
4523 - (void) setScrollIndicatorStyle:(NSString *)style {
4524 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4525 }
4526
4527 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4528 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4529 }
4530
4531 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4532 char path[1024];
4533 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4534 return (id) [NSNull null];
4535 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4536 if (info == nil)
4537 return (id) [NSNull null];
4538 return [info objectForKey:key];
4539 }
4540
4541 - (NSNumber *) getKernelNumber:(NSString *)name {
4542 const char *string([name UTF8String]);
4543
4544 size_t size;
4545 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4546 return (id) [NSNull null];
4547
4548 if (size != sizeof(int))
4549 return (id) [NSNull null];
4550
4551 int value;
4552 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4553 return (id) [NSNull null];
4554
4555 return [NSNumber numberWithInt:value];
4556 }
4557
4558 - (NSString *) getKernelString:(NSString *)name {
4559 const char *string([name UTF8String]);
4560
4561 size_t size;
4562 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4563 return (id) [NSNull null];
4564
4565 char value[size + 1];
4566 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4567 return (id) [NSNull null];
4568
4569 // XXX: just in case you request something ludicrous
4570 value[size] = '\0';
4571
4572 return [NSString stringWithCString:value];
4573 }
4574
4575 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4576 NSObject *value(CYIOGetValue([path UTF8String], entry));
4577
4578 if (value != nil)
4579 if ([value isKindOfClass:[NSData class]])
4580 value = CYHex((NSData *) value);
4581
4582 return value;
4583 }
4584
4585 - (NSArray *) getMetadataKeys {
4586 @synchronized (Values_) {
4587 return [Values_ allKeys];
4588 } }
4589
4590 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4591 WebFrame *frame([iframe contentFrame]);
4592 [indirect_ registerFrame:frame];
4593 }
4594
4595 - (id) getMetadataValue:(NSString *)key {
4596 @synchronized (Values_) {
4597 return [Values_ objectForKey:key];
4598 } }
4599
4600 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4601 @synchronized (Values_) {
4602 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4603 [Values_ removeObjectForKey:key];
4604 else
4605 [Values_ setObject:value forKey:key];
4606
4607 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4608 } }
4609
4610 - (id) getSessionValue:(NSString *)key {
4611 @synchronized (SessionData_) {
4612 return [SessionData_ objectForKey:key];
4613 } }
4614
4615 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4616 @synchronized (SessionData_) {
4617 if (value == (id) [WebUndefined undefined])
4618 [SessionData_ removeObjectForKey:key];
4619 else
4620 [SessionData_ setObject:value forKey:key];
4621 } }
4622
4623 - (void) addBridgedHost:(NSString *)host {
4624 @synchronized (HostConfig_) {
4625 [BridgedHosts_ addObject:host];
4626 } }
4627
4628 - (void) addInsecureHost:(NSString *)host {
4629 @synchronized (HostConfig_) {
4630 [InsecureHosts_ addObject:host];
4631 } }
4632
4633 - (void) addTokenHost:(NSString *)host {
4634 @synchronized (HostConfig_) {
4635 [TokenHosts_ addObject:host];
4636 } }
4637
4638 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4639 @synchronized (HostConfig_) {
4640 if (scheme != (id) [WebUndefined undefined])
4641 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4642
4643 [PipelinedHosts_ addObject:host];
4644 } }
4645
4646 - (void) popViewController:(NSNumber *)value {
4647 if (value == (id) [WebUndefined undefined])
4648 value = [NSNumber numberWithBool:YES];
4649 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4650 }
4651
4652 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4653 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4654
4655 for (NSString *section in sections)
4656 [array addObject:section];
4657
4658 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4659 @"deb", @"Type",
4660 href, @"URI",
4661 distribution, @"Distribution",
4662 array, @"Sections",
4663 nil] waitUntilDone:NO];
4664 }
4665
4666 - (void) addTrivialSource:(NSString *)href {
4667 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4668 }
4669
4670 - (void) refreshSources {
4671 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4672 }
4673
4674 - (void) saveConfig {
4675 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4676 }
4677
4678 - (NSArray *) getAllSources {
4679 return [[Database sharedInstance] sources];
4680 }
4681
4682 - (NSArray *) getInstalledPackages {
4683 Database *database([Database sharedInstance]);
4684 @synchronized (database) {
4685 NSArray *packages([database packages]);
4686 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4687 for (Package *package in packages)
4688 if (![package uninstalled])
4689 [installed addObject:package];
4690 return installed;
4691 } }
4692
4693 - (Package *) getPackageById:(NSString *)id {
4694 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4695 [package parse];
4696 return package;
4697 } else
4698 return (Package *) [NSNull null];
4699 }
4700
4701 - (NSString *) getLocaleIdentifier {
4702 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4703 }
4704
4705 - (NSArray *) getPreferredLanguages {
4706 return Languages_;
4707 }
4708
4709 - (NSArray *) statfs:(NSString *)path {
4710 struct statfs stat;
4711
4712 if (path == nil || statfs([path UTF8String], &stat) == -1)
4713 return nil;
4714
4715 return [NSArray arrayWithObjects:
4716 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4717 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4718 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4719 nil];
4720 }
4721
4722 - (NSNumber *) du:(NSString *)path {
4723 NSNumber *value(nil);
4724
4725 int fds[2];
4726 _assert(pipe(fds) != -1);
4727
4728 pid_t pid(ExecFork());
4729 if (pid == 0) {
4730 _assert(dup2(fds[1], 1) != -1);
4731 _assert(close(fds[0]) != -1);
4732 _assert(close(fds[1]) != -1);
4733 /* XXX: this should probably not use du */
4734 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4735 exit(1);
4736 } else {
4737 _assert(close(fds[1]) != -1);
4738
4739 if (FILE *du = fdopen(fds[0], "r")) {
4740 char line[1024];
4741 while (fgets(line, sizeof(line), du) != NULL) {
4742 size_t length(strlen(line));
4743 while (length != 0 && line[length - 1] == '\n')
4744 line[--length] = '\0';
4745 if (char *tab = strchr(line, '\t')) {
4746 *tab = '\0';
4747 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4748 }
4749 }
4750
4751 fclose(du);
4752 } else
4753 _assert(close(fds[0]) != -1);
4754 } ReapZombie(pid);
4755
4756 return value;
4757 }
4758
4759 - (void) close {
4760 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4761 }
4762
4763 - (NSNumber *) isReachable:(NSString *)name {
4764 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4765 }
4766
4767 - (void) installPackages:(NSArray *)packages {
4768 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4769 }
4770
4771 - (NSString *) substitutePackageNames:(NSString *)message {
4772 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4773 for (size_t i(0), e([words count]); i != e; ++i) {
4774 NSString *word([words objectAtIndex:i]);
4775 if (Package *package = [[Database sharedInstance] packageWithName:word])
4776 [words replaceObjectAtIndex:i withObject:[package name]];
4777 }
4778
4779 return [words componentsJoinedByString:@" "];
4780 }
4781
4782 - (void) removeButton {
4783 [indirect_ removeButton];
4784 }
4785
4786 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4787 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4788 }
4789
4790 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4791 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4792 }
4793
4794 - (void) setBadgeValue:(id)value {
4795 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4796 }
4797
4798 - (void) setAllowsNavigationAction:(NSString *)value {
4799 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4800 }
4801
4802 - (void) setHidesBackButton:(NSString *)value {
4803 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4804 }
4805
4806 - (void) setHidesNavigationBar:(NSString *)value {
4807 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4808 }
4809
4810 - (void) setNavigationBarStyle:(NSString *)value {
4811 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4812 }
4813
4814 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4815 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4816 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4817 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4818 }
4819
4820 - (void) setPasteboardString:(NSString *)value {
4821 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4822 }
4823
4824 - (void) setPasteboardURL:(NSString *)value {
4825 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4826 }
4827
4828 - (void) _setToken:(NSString *)token {
4829 Token_ = token;
4830
4831 if (token == nil)
4832 [Metadata_ removeObjectForKey:@"Token"];
4833 else
4834 [Metadata_ setObject:Token_ forKey:@"Token"];
4835
4836 Changed_ = true;
4837 }
4838
4839 - (void) setToken:(NSString *)token {
4840 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4841 }
4842
4843 - (void) scrollToBottom:(NSNumber *)animated {
4844 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4845 }
4846
4847 - (void) setViewportWidth:(float)width {
4848 [indirect_ setViewportWidthOnMainThread:width];
4849 }
4850
4851 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4852 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4853 unsigned count([arguments count]);
4854 id values[count];
4855 for (unsigned i(0); i != count; ++i)
4856 values[i] = [arguments objectAtIndex:i];
4857 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4858 }
4859
4860 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4861 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4862 value = nil;
4863 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4864 table = nil;
4865 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4866 }
4867
4868 @end
4869 /* }}} */
4870
4871 @interface NSURL (CydiaSecure)
4872 @end
4873
4874 @implementation NSURL (CydiaSecure)
4875
4876 - (bool) isCydiaSecure {
4877 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4878 return true;
4879
4880 @synchronized (HostConfig_) {
4881 if ([InsecureHosts_ containsObject:[self host]])
4882 return true;
4883 }
4884
4885 return false;
4886 }
4887
4888 @end
4889
4890 /* Cydia Browser Controller {{{ */
4891 @implementation CydiaWebViewController
4892
4893 - (NSURL *) navigationURL {
4894 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4895 }
4896
4897 + (void) _initialize {
4898 [super _initialize];
4899
4900 Diversions_ = [NSMutableSet setWithCapacity:0];
4901 }
4902
4903 + (void) addDiversion:(Diversion *)diversion {
4904 [Diversions_ addObject:diversion];
4905 }
4906
4907 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4908 [super webView:view didClearWindowObject:window forFrame:frame];
4909 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4910 }
4911
4912 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4913 WebDataSource *source([frame dataSource]);
4914 NSURLResponse *response([source response]);
4915 NSURL *url([response URL]);
4916 NSString *scheme([[url scheme] lowercaseString]);
4917
4918 bool bridged(false);
4919
4920 @synchronized (HostConfig_) {
4921 if ([scheme isEqualToString:@"file"])
4922 bridged = true;
4923 else if ([scheme isEqualToString:@"https"])
4924 if ([BridgedHosts_ containsObject:[url host]])
4925 bridged = true;
4926 }
4927
4928 if (bridged)
4929 [window setValue:cydia forKey:@"cydia"];
4930 }
4931
4932 - (void) _setupMail:(MFMailComposeViewController *)controller {
4933 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4934
4935 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4936 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4937 }
4938
4939 - (NSURL *) URLWithURL:(NSURL *)url {
4940 return [Diversion divertURL:url];
4941 }
4942
4943 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4944 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4945 }
4946
4947 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4948 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4949
4950 NSURL *url([copy URL]);
4951 NSString *href([url absoluteString]);
4952 NSString *host([url host]);
4953
4954 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4955 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4956 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4957 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4958 }
4959
4960 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4961 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4962
4963 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4964 return copy;
4965 }
4966
4967 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4968 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4969 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4970 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4971
4972 bool bridged;
4973 bool token;
4974
4975 @synchronized (HostConfig_) {
4976 bridged = [BridgedHosts_ containsObject:host];
4977 token = [TokenHosts_ containsObject:host];
4978 }
4979
4980 if ([url isCydiaSecure]) {
4981 if (bridged) {
4982 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4983 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4984 } else if (token) {
4985 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4986 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4987 }
4988 }
4989
4990 return copy;
4991 }
4992
4993 - (void) setDelegate:(id)delegate {
4994 [super setDelegate:delegate];
4995 [cydia_ setDelegate:delegate];
4996 }
4997
4998 - (NSString *) applicationNameForUserAgent {
4999 return UserAgent_;
5000 }
5001
5002 - (id) init {
5003 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5004 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5005 } return self;
5006 }
5007
5008 @end
5009
5010 @interface AppCacheController : CydiaWebViewController {
5011 }
5012
5013 @end
5014
5015 @implementation AppCacheController
5016
5017 - (void) didReceiveMemoryWarning {
5018 // XXX: this doesn't work
5019 }
5020
5021 - (bool) retainsNetworkActivityIndicator {
5022 return false;
5023 }
5024
5025 @end
5026 /* }}} */
5027
5028 // CydiaScript {{{
5029 @interface NSObject (CydiaScript)
5030 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5031 @end
5032
5033 @implementation NSObject (CydiaScript)
5034
5035 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5036 return self;
5037 }
5038
5039 @end
5040
5041 @implementation NSArray (CydiaScript)
5042
5043 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5044 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5045 for (size_t i(0), e([self count]); i != e; ++i)
5046 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5047 return object;
5048 }
5049
5050 @end
5051
5052 @implementation NSDictionary (CydiaScript)
5053
5054 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5055 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5056 for (id i in self)
5057 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5058 return object;
5059 }
5060
5061 @end
5062 // }}}
5063
5064 /* Confirmation Controller {{{ */
5065 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5066 if (!iterator.end())
5067 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5068 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5069 continue;
5070 pkgCache::PkgIterator package(dep.TargetPkg());
5071 if (package.end())
5072 continue;
5073 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5074 return true;
5075 }
5076
5077 return false;
5078 }
5079
5080 @protocol ConfirmationControllerDelegate
5081 - (void) cancelAndClear:(bool)clear;
5082 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5083 - (void) queue;
5084 @end
5085
5086 @interface ConfirmationController : CydiaWebViewController {
5087 _transient Database *database_;
5088
5089 _H<UIAlertView> essential_;
5090
5091 _H<NSDictionary> changes_;
5092 _H<NSMutableArray> issues_;
5093 _H<NSDictionary> sizes_;
5094
5095 BOOL substrate_;
5096 }
5097
5098 - (id) initWithDatabase:(Database *)database;
5099
5100 @end
5101
5102 @implementation ConfirmationController
5103
5104 - (void) complete {
5105 if (substrate_)
5106 RestartSubstrate_ = true;
5107 [delegate_ confirmWithNavigationController:[self navigationController]];
5108 }
5109
5110 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5111 NSString *context([alert context]);
5112
5113 if ([context isEqualToString:@"remove"]) {
5114 if (button == [alert cancelButtonIndex])
5115 [self dismissModalViewControllerAnimated:YES];
5116 else if (button == [alert firstOtherButtonIndex]) {
5117 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5118 }
5119
5120 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5121 } else if ([context isEqualToString:@"unable"]) {
5122 [self dismissModalViewControllerAnimated:YES];
5123 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5124 } else {
5125 [super alertView:alert clickedButtonAtIndex:button];
5126 }
5127 }
5128
5129 - (void) _doContinue {
5130 [delegate_ cancelAndClear:NO];
5131 [self dismissModalViewControllerAnimated:YES];
5132 }
5133
5134 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5135 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5136 return nil;
5137 }
5138
5139 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5140 [super webView:view didClearWindowObject:window forFrame:frame];
5141
5142 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5143 (id) changes_, @"changes",
5144 (id) issues_, @"issues",
5145 (id) sizes_, @"sizes",
5146 self, @"queue",
5147 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5148 }
5149
5150 - (id) initWithDatabase:(Database *)database {
5151 if ((self = [super init]) != nil) {
5152 database_ = database;
5153
5154 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5155 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5156 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5157 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5158 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5159
5160 bool remove(false);
5161
5162 pkgCacheFile &cache([database_ cache]);
5163 NSArray *packages([database_ packages]);
5164 pkgDepCache::Policy *policy([database_ policy]);
5165
5166 issues_ = [NSMutableArray arrayWithCapacity:4];
5167
5168 for (Package *package in packages) {
5169 pkgCache::PkgIterator iterator([package iterator]);
5170 NSString *name([package id]);
5171
5172 if ([package broken]) {
5173 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5174
5175 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5176 name, @"package",
5177 reasons, @"reasons",
5178 nil]];
5179
5180 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5181 if (ver.end())
5182 continue;
5183
5184 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5185 pkgCache::DepIterator start;
5186 pkgCache::DepIterator end;
5187 dep.GlobOr(start, end); // ++dep
5188
5189 if (!cache->IsImportantDep(end))
5190 continue;
5191 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5192 continue;
5193
5194 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5195
5196 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5197 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5198 clauses, @"clauses",
5199 nil]];
5200
5201 _forever {
5202 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5203
5204 pkgCache::PkgIterator target(start.TargetPkg());
5205 if (target->ProvidesList != 0)
5206 reason = @"missing";
5207 else {
5208 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5209 if (!ver.end()) {
5210 reason = @"installed";
5211 installed = [NSString stringWithUTF8String:ver.VerStr()];
5212 } else if (!cache[target].CandidateVerIter(cache).end())
5213 reason = @"uninstalled";
5214 else if (target->ProvidesList == 0)
5215 reason = @"uninstallable";
5216 else
5217 reason = @"virtual";
5218 }
5219
5220 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5221 [NSString stringWithUTF8String:start.CompType()], @"operator",
5222 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5223 nil]);
5224
5225 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5226 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5227 version, @"version",
5228 reason, @"reason",
5229 installed, @"installed",
5230 nil]];
5231
5232 // yes, seriously. (wtf?)
5233 if (start == end)
5234 break;
5235 ++start;
5236 }
5237 }
5238 }
5239
5240 pkgDepCache::StateCache &state(cache[iterator]);
5241
5242 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5243
5244 if (state.NewInstall())
5245 [installs addObject:name];
5246 // XXX: else if (state.Install())
5247 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5248 [reinstalls addObject:name];
5249 // XXX: move before previous if
5250 else if (state.Upgrade())
5251 [upgrades addObject:name];
5252 else if (state.Downgrade())
5253 [downgrades addObject:name];
5254 else if (!state.Delete())
5255 // XXX: _assert(state.Keep());
5256 continue;
5257 else if (special_r(name))
5258 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5259 [NSNull null], @"package",
5260 [NSArray arrayWithObjects:
5261 [NSDictionary dictionaryWithObjectsAndKeys:
5262 @"Conflicts", @"relationship",
5263 [NSArray arrayWithObjects:
5264 [NSDictionary dictionaryWithObjectsAndKeys:
5265 name, @"package",
5266 [NSNull null], @"version",
5267 @"installed", @"reason",
5268 nil],
5269 nil], @"clauses",
5270 nil],
5271 nil], @"reasons",
5272 nil]];
5273 else {
5274 if ([package essential])
5275 remove = true;
5276 [removes addObject:name];
5277 }
5278
5279 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5280 substrate_ |= DepSubstrate(iterator.CurrentVer());
5281 }
5282
5283 if (!remove)
5284 essential_ = nil;
5285 else if (Advanced_) {
5286 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5287
5288 essential_ = [[[UIAlertView alloc]
5289 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5290 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5291 delegate:self
5292 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5293 otherButtonTitles:
5294 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5295 nil
5296 ] autorelease];
5297
5298 [essential_ setContext:@"remove"];
5299 [essential_ setNumberOfRows:2];
5300 } else {
5301 essential_ = [[[UIAlertView alloc]
5302 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5303 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5304 delegate:self
5305 cancelButtonTitle:UCLocalize("OKAY")
5306 otherButtonTitles:nil
5307 ] autorelease];
5308
5309 [essential_ setContext:@"unable"];
5310 }
5311
5312 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5313 installs, @"installs",
5314 reinstalls, @"reinstalls",
5315 upgrades, @"upgrades",
5316 downgrades, @"downgrades",
5317 removes, @"removes",
5318 nil];
5319
5320 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5321 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5322 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5323 nil];
5324
5325 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5326 } return self;
5327 }
5328
5329 - (UIBarButtonItem *) leftButton {
5330 return [[[UIBarButtonItem alloc]
5331 initWithTitle:UCLocalize("CANCEL")
5332 style:UIBarButtonItemStylePlain
5333 target:self
5334 action:@selector(cancelButtonClicked)
5335 ] autorelease];
5336 }
5337
5338 #if !AlwaysReload
5339 - (void) applyRightButton {
5340 if ([issues_ count] == 0 && ![self isLoading])
5341 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5342 initWithTitle:UCLocalize("CONFIRM")
5343 style:UIBarButtonItemStyleDone
5344 target:self
5345 action:@selector(confirmButtonClicked)
5346 ] autorelease]];
5347 else
5348 [[self navigationItem] setRightBarButtonItem:nil];
5349 }
5350 #endif
5351
5352 - (void) cancelButtonClicked {
5353 [delegate_ cancelAndClear:YES];
5354 [self dismissModalViewControllerAnimated:YES];
5355 }
5356
5357 #if !AlwaysReload
5358 - (void) confirmButtonClicked {
5359 if (essential_ != nil)
5360 [essential_ show];
5361 else
5362 [self complete];
5363 }
5364 #endif
5365
5366 @end
5367 /* }}} */
5368
5369 /* Progress Data {{{ */
5370 @interface CydiaProgressData : NSObject {
5371 _transient id delegate_;
5372
5373 bool running_;
5374 float percent_;
5375
5376 float current_;
5377 float total_;
5378 float speed_;
5379
5380 _H<NSMutableArray> events_;
5381 _H<NSString> title_;
5382
5383 _H<NSString> status_;
5384 _H<NSString> finish_;
5385 }
5386
5387 @end
5388
5389 @implementation CydiaProgressData
5390
5391 + (NSArray *) _attributeKeys {
5392 return [NSArray arrayWithObjects:
5393 @"current",
5394 @"events",
5395 @"finish",
5396 @"percent",
5397 @"running",
5398 @"speed",
5399 @"title",
5400 @"total",
5401 nil];
5402 }
5403
5404 - (NSArray *) attributeKeys {
5405 return [[self class] _attributeKeys];
5406 }
5407
5408 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5409 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5410 }
5411
5412 - (id) init {
5413 if ((self = [super init]) != nil) {
5414 events_ = [NSMutableArray arrayWithCapacity:32];
5415 } return self;
5416 }
5417
5418 - (id) delegate {
5419 return delegate_;
5420 }
5421
5422 - (void) setDelegate:(id)delegate {
5423 delegate_ = delegate;
5424 }
5425
5426 - (void) setPercent:(float)value {
5427 percent_ = value;
5428 }
5429
5430 - (NSNumber *) percent {
5431 return [NSNumber numberWithFloat:percent_];
5432 }
5433
5434 - (void) setCurrent:(float)value {
5435 current_ = value;
5436 }
5437
5438 - (NSNumber *) current {
5439 return [NSNumber numberWithFloat:current_];
5440 }
5441
5442 - (void) setTotal:(float)value {
5443 total_ = value;
5444 }
5445
5446 - (NSNumber *) total {
5447 return [NSNumber numberWithFloat:total_];
5448 }
5449
5450 - (void) setSpeed:(float)value {
5451 speed_ = value;
5452 }
5453
5454 - (NSNumber *) speed {
5455 return [NSNumber numberWithFloat:speed_];
5456 }
5457
5458 - (NSArray *) events {
5459 return events_;
5460 }
5461
5462 - (void) removeAllEvents {
5463 [events_ removeAllObjects];
5464 }
5465
5466 - (void) addEvent:(CydiaProgressEvent *)event {
5467 [events_ addObject:event];
5468 }
5469
5470 - (void) setTitle:(NSString *)text {
5471 title_ = text;
5472 }
5473
5474 - (NSString *) title {
5475 return title_;
5476 }
5477
5478 - (void) setFinish:(NSString *)text {
5479 finish_ = text;
5480 }
5481
5482 - (NSString *) finish {
5483 return (id) finish_ ?: [NSNull null];
5484 }
5485
5486 - (void) setRunning:(bool)running {
5487 running_ = running;
5488 }
5489
5490 - (NSNumber *) running {
5491 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5492 }
5493
5494 @end
5495 /* }}} */
5496 /* Progress Controller {{{ */
5497 @interface ProgressController : CydiaWebViewController <
5498 ProgressDelegate
5499 > {
5500 _transient Database *database_;
5501 _H<CydiaProgressData, 1> progress_;
5502 unsigned cancel_;
5503 }
5504
5505 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5506
5507 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5508
5509 - (void) setTitle:(NSString *)title;
5510 - (void) setCancellable:(bool)cancellable;
5511
5512 @end
5513
5514 @implementation ProgressController
5515
5516 - (void) dealloc {
5517 [database_ setProgressDelegate:nil];
5518 [super dealloc];
5519 }
5520
5521 - (UIBarButtonItem *) leftButton {
5522 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5523 initWithTitle:UCLocalize("CANCEL")
5524 style:UIBarButtonItemStylePlain
5525 target:self
5526 action:@selector(cancel)
5527 ] autorelease] : nil;
5528 }
5529
5530 - (void) updateCancel {
5531 [super applyLeftButton];
5532 }
5533
5534 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5535 if ((self = [super init]) != nil) {
5536 database_ = database;
5537 delegate_ = delegate;
5538
5539 [database_ setProgressDelegate:self];
5540
5541 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5542 [progress_ setDelegate:self];
5543
5544 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5545
5546 [scroller_ setBackgroundColor:[UIColor blackColor]];
5547
5548 [[self navigationItem] setHidesBackButton:YES];
5549
5550 [self updateCancel];
5551 } return self;
5552 }
5553
5554 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5555 [super webView:view didClearWindowObject:window forFrame:frame];
5556 [window setValue:progress_ forKey:@"cydiaProgress"];
5557 }
5558
5559 - (void) updateProgress {
5560 [self dispatchEvent:@"CydiaProgressUpdate"];
5561 }
5562
5563 - (void) viewWillAppear:(BOOL)animated {
5564 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5565 [super viewWillAppear:animated];
5566 }
5567
5568 - (void) reloadSpringBoard {
5569 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5570 system("/bin/launchctl stop com.apple.backboardd");
5571 sleep(15);
5572 system("/usr/bin/killall backboardd SpringBoard sbreload");
5573 return;
5574 }
5575
5576 pid_t pid(ExecFork());
5577 if (pid == 0) {
5578 if (setsid() == -1)
5579 perror("setsid");
5580
5581 pid_t pid(ExecFork());
5582 if (pid == 0) {
5583 execl("/usr/bin/sbreload", "sbreload", NULL);
5584 perror("sbreload");
5585
5586 exit(0);
5587 } ReapZombie(pid);
5588
5589 exit(0);
5590 } ReapZombie(pid);
5591
5592 sleep(15);
5593 system("/usr/bin/killall backboardd SpringBoard sbreload");
5594 }
5595
5596 - (void) close {
5597 UpdateExternalStatus(0);
5598
5599 if (Finish_ > 1)
5600 [delegate_ saveState];
5601
5602 switch (Finish_) {
5603 case 0:
5604 [delegate_ returnToCydia];
5605 break;
5606
5607 case 1:
5608 [delegate_ terminateWithSuccess];
5609 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5610 [delegate_ suspendWithAnimation:YES];
5611 else
5612 [delegate_ suspend];*/
5613 break;
5614
5615 case 2:
5616 _trace();
5617 goto reload;
5618
5619 case 3:
5620 _trace();
5621 goto reload;
5622
5623 reload: {
5624 UIProgressHUD *hud([delegate_ addProgressHUD]);
5625 [hud setText:UCLocalize("LOADING")];
5626 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5627 return;
5628 }
5629
5630 case 4:
5631 _trace();
5632 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5633 SBReboot(SBSSpringBoardServerPort());
5634 else
5635 reboot2(RB_AUTOBOOT);
5636 break;
5637 }
5638
5639 [super close];
5640 }
5641
5642 - (void) setTitle:(NSString *)title {
5643 [progress_ setTitle:title];
5644 [self updateProgress];
5645 }
5646
5647 - (UIBarButtonItem *) rightButton {
5648 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5649 initWithTitle:UCLocalize("CLOSE")
5650 style:UIBarButtonItemStylePlain
5651 target:self
5652 action:@selector(close)
5653 ] autorelease];
5654 }
5655
5656 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5657 UpdateExternalStatus(1);
5658
5659 [progress_ setRunning:true];
5660 [self setTitle:title];
5661 // implicit updateProgress
5662
5663 SHA1SumValue notifyconf; {
5664 FileFd file;
5665 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5666 _error->Discard();
5667 else {
5668 MMap mmap(file, MMap::ReadOnly);
5669 SHA1Summation sha1;
5670 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5671 notifyconf = sha1.Result();
5672 }
5673 }
5674
5675 SHA1SumValue springlist; {
5676 FileFd file;
5677 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5678 _error->Discard();
5679 else {
5680 MMap mmap(file, MMap::ReadOnly);
5681 SHA1Summation sha1;
5682 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5683 springlist = sha1.Result();
5684 }
5685 }
5686
5687 if (invocation != nil) {
5688 [invocation yieldToSelector:@selector(invoke)];
5689 [self setTitle:@"COMPLETE"];
5690 }
5691
5692 if (Finish_ < 4) {
5693 FileFd file;
5694 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5695 _error->Discard();
5696 else {
5697 MMap mmap(file, MMap::ReadOnly);
5698 SHA1Summation sha1;
5699 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5700 if (!(notifyconf == sha1.Result()))
5701 Finish_ = 4;
5702 }
5703 }
5704
5705 if (Finish_ < 3) {
5706 FileFd file;
5707 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5708 _error->Discard();
5709 else {
5710 MMap mmap(file, MMap::ReadOnly);
5711 SHA1Summation sha1;
5712 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5713 if (!(springlist == sha1.Result()))
5714 Finish_ = 3;
5715 }
5716 }
5717
5718 if (Finish_ < 2) {
5719 if (RestartSubstrate_)
5720 Finish_ = 2;
5721 }
5722
5723 RestartSubstrate_ = false;
5724
5725 switch (Finish_) {
5726 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5727 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5728 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5729 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5730 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5731 }
5732
5733 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5734
5735 [progress_ setRunning:false];
5736 [self updateProgress];
5737
5738 [self applyRightButton];
5739 }
5740
5741 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5742 [progress_ addEvent:event];
5743 [self updateProgress];
5744 }
5745
5746 - (bool) isProgressCancelled {
5747 return cancel_ == 2;
5748 }
5749
5750 - (void) cancel {
5751 cancel_ = 2;
5752 [self updateCancel];
5753 }
5754
5755 - (void) setCancellable:(bool)cancellable {
5756 unsigned cancel(cancel_);
5757
5758 if (!cancellable)
5759 cancel_ = 0;
5760 else if (cancel_ == 0)
5761 cancel_ = 1;
5762
5763 if (cancel != cancel_)
5764 [self updateCancel];
5765 }
5766
5767 - (void) setProgressCancellable:(NSNumber *)cancellable {
5768 [self setCancellable:[cancellable boolValue]];
5769 }
5770
5771 - (void) setProgressPercent:(NSNumber *)percent {
5772 [progress_ setPercent:[percent floatValue]];
5773 [self updateProgress];
5774 }
5775
5776 - (void) setProgressStatus:(NSDictionary *)status {
5777 if (status == nil) {
5778 [progress_ setCurrent:0];
5779 [progress_ setTotal:0];
5780 [progress_ setSpeed:0];
5781 } else {
5782 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5783
5784 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5785 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5786 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5787 }
5788
5789 [self updateProgress];
5790 }
5791
5792 @end
5793 /* }}} */
5794
5795 /* Package Cell {{{ */
5796 @interface PackageCell : CyteTableViewCell <
5797 CyteTableViewCellDelegate
5798 > {
5799 _H<UIImage> icon_;
5800 _H<NSString> name_;
5801 _H<NSString> description_;
5802 bool commercial_;
5803 _H<NSString> source_;
5804 _H<UIImage> badge_;
5805 _H<UIImage> placard_;
5806 bool summarized_;
5807 }
5808
5809 - (PackageCell *) init;
5810 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5811
5812 - (void) drawContentRect:(CGRect)rect;
5813
5814 @end
5815
5816 @implementation PackageCell
5817
5818 - (PackageCell *) init {
5819 CGRect frame(CGRectMake(0, 0, 320, 74));
5820 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5821 UIView *content([self contentView]);
5822 CGRect bounds([content bounds]);
5823
5824 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5825 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5826 [content addSubview:content_];
5827
5828 [content_ setDelegate:self];
5829 [content_ setOpaque:YES];
5830 } return self;
5831 }
5832
5833 - (NSString *) accessibilityLabel {
5834 return name_;
5835 }
5836
5837 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5838 summarized_ = summary;
5839
5840 icon_ = nil;
5841 name_ = nil;
5842 description_ = nil;
5843 source_ = nil;
5844 badge_ = nil;
5845 placard_ = nil;
5846
5847 if (package == nil)
5848 [content_ setBackgroundColor:[UIColor whiteColor]];
5849 else {
5850 [package parse];
5851
5852 Source *source = [package source];
5853
5854 icon_ = [package icon];
5855
5856 if (NSString *name = [package name])
5857 name_ = [NSString stringWithString:name];
5858
5859 if (NSString *description = [package shortDescription])
5860 description_ = [NSString stringWithString:description];
5861
5862 commercial_ = [package isCommercial];
5863
5864 NSString *label = nil;
5865 bool trusted = false;
5866
5867 if (source != nil) {
5868 label = [source label];
5869 trusted = [source trusted];
5870 } else if ([[package id] isEqualToString:@"firmware"])
5871 label = UCLocalize("APPLE");
5872 else
5873 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5874
5875 NSString *from(label);
5876
5877 NSString *section = [package simpleSection];
5878 if (section != nil && ![section isEqualToString:label]) {
5879 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5880 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5881 }
5882
5883 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5884
5885 if (NSString *purpose = [package primaryPurpose])
5886 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5887
5888 UIColor *color;
5889 NSString *placard;
5890
5891 if (NSString *mode = [package mode]) {
5892 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5893 color = RemovingColor_;
5894 placard = @"removing";
5895 } else {
5896 color = InstallingColor_;
5897 placard = @"installing";
5898 }
5899 } else {
5900 color = [UIColor whiteColor];
5901
5902 if ([package installed] != nil)
5903 placard = @"installed";
5904 else
5905 placard = nil;
5906 }
5907
5908 [content_ setBackgroundColor:color];
5909
5910 if (placard != nil)
5911 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5912 }
5913
5914 [self setNeedsDisplay];
5915 [content_ setNeedsDisplay];
5916 }
5917
5918 - (void) drawSummaryContentRect:(CGRect)rect {
5919 bool highlighted(highlighted_);
5920 float width([self bounds].size.width);
5921
5922 if (icon_ != nil) {
5923 CGRect rect;
5924 rect.size = [(UIImage *) icon_ size];
5925
5926 while (rect.size.width > 16 || rect.size.height > 16) {
5927 rect.size.width /= 2;
5928 rect.size.height /= 2;
5929 }
5930
5931 rect.origin.x = 19 - rect.size.width / 2;
5932 rect.origin.y = 19 - rect.size.height / 2;
5933
5934 [icon_ drawInRect:Retina(rect)];
5935 }
5936
5937 if (badge_ != nil) {
5938 CGRect rect;
5939 rect.size = [(UIImage *) badge_ size];
5940
5941 rect.size.width /= 4;
5942 rect.size.height /= 4;
5943
5944 rect.origin.x = 25 - rect.size.width / 2;
5945 rect.origin.y = 25 - rect.size.height / 2;
5946
5947 [badge_ drawInRect:Retina(rect)];
5948 }
5949
5950 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5951 UISetColor(White_);
5952
5953 if (!highlighted)
5954 UISetColor(commercial_ ? Purple_ : Black_);
5955 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5956
5957 if (placard_ != nil)
5958 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5959 }
5960
5961 - (void) drawNormalContentRect:(CGRect)rect {
5962 bool highlighted(highlighted_);
5963 float width([self bounds].size.width);
5964
5965 if (icon_ != nil) {
5966 CGRect rect;
5967 rect.size = [(UIImage *) icon_ size];
5968
5969 while (rect.size.width > 32 || rect.size.height > 32) {
5970 rect.size.width /= 2;
5971 rect.size.height /= 2;
5972 }
5973
5974 rect.origin.x = 25 - rect.size.width / 2;
5975 rect.origin.y = 25 - rect.size.height / 2;
5976
5977 [icon_ drawInRect:Retina(rect)];
5978 }
5979
5980 if (badge_ != nil) {
5981 CGRect rect;
5982 rect.size = [(UIImage *) badge_ size];
5983
5984 rect.size.width /= 2;
5985 rect.size.height /= 2;
5986
5987 rect.origin.x = 36 - rect.size.width / 2;
5988 rect.origin.y = 36 - rect.size.height / 2;
5989
5990 [badge_ drawInRect:Retina(rect)];
5991 }
5992
5993 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5994 UISetColor(White_);
5995
5996 if (!highlighted)
5997 UISetColor(commercial_ ? Purple_ : Black_);
5998 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5999 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6000
6001 if (!highlighted)
6002 UISetColor(commercial_ ? Purplish_ : Gray_);
6003 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6004
6005 if (placard_ != nil)
6006 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6007 }
6008
6009 - (void) drawContentRect:(CGRect)rect {
6010 if (summarized_)
6011 [self drawSummaryContentRect:rect];
6012 else
6013 [self drawNormalContentRect:rect];
6014 }
6015
6016 @end
6017 /* }}} */
6018 /* Section Cell {{{ */
6019 @interface SectionCell : CyteTableViewCell <
6020 CyteTableViewCellDelegate
6021 > {
6022 _H<NSString> basic_;
6023 _H<NSString> section_;
6024 _H<NSString> name_;
6025 _H<NSString> count_;
6026 _H<UIImage> icon_;
6027 _H<UISwitch> switch_;
6028 BOOL editing_;
6029 }
6030
6031 - (void) setSection:(Section *)section editing:(BOOL)editing;
6032
6033 @end
6034
6035 @implementation SectionCell
6036
6037 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6038 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6039 icon_ = [UIImage imageNamed:@"folder.png"];
6040 // XXX: this initial frame is wrong, but is fixed later
6041 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6042 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6043
6044 UIView *content([self contentView]);
6045 CGRect bounds([content bounds]);
6046
6047 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6048 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6049 [content addSubview:content_];
6050 [content_ setBackgroundColor:[UIColor whiteColor]];
6051
6052 [content_ setDelegate:self];
6053 } return self;
6054 }
6055
6056 - (void) onSwitch:(id)sender {
6057 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6058 if (metadata == nil) {
6059 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6060 [Sections_ setObject:metadata forKey:basic_];
6061 }
6062
6063 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6064 Changed_ = true;
6065 }
6066
6067 - (void) setSection:(Section *)section editing:(BOOL)editing {
6068 if (editing != editing_) {
6069 if (editing_)
6070 [switch_ removeFromSuperview];
6071 else
6072 [self addSubview:switch_];
6073 editing_ = editing;
6074 }
6075
6076 basic_ = nil;
6077 section_ = nil;
6078 name_ = nil;
6079 count_ = nil;
6080
6081 if (section == nil) {
6082 name_ = UCLocalize("ALL_PACKAGES");
6083 count_ = nil;
6084 } else {
6085 basic_ = [section name];
6086 section_ = [section localized];
6087
6088 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6089 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6090
6091 if (editing_)
6092 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6093 }
6094
6095 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6096 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6097
6098 [content_ setNeedsDisplay];
6099 }
6100
6101 - (void) setFrame:(CGRect)frame {
6102 [super setFrame:frame];
6103
6104 CGRect rect([switch_ frame]);
6105 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6106 }
6107
6108 - (NSString *) accessibilityLabel {
6109 return name_;
6110 }
6111
6112 - (void) drawContentRect:(CGRect)rect {
6113 bool highlighted(highlighted_ && !editing_);
6114
6115 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6116
6117 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6118 UISetColor(White_);
6119
6120 float width(rect.size.width);
6121 if (editing_)
6122 width -= 9 + [switch_ frame].size.width;
6123
6124 if (!highlighted)
6125 UISetColor(Black_);
6126 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6127
6128 CGSize size = [count_ sizeWithFont:Font14_];
6129
6130 UISetColor(Folder_);
6131 if (count_ != nil)
6132 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6133 }
6134
6135 @end
6136 /* }}} */
6137
6138 /* File Table {{{ */
6139 @interface FileTable : CyteViewController <
6140 UITableViewDataSource,
6141 UITableViewDelegate
6142 > {
6143 _transient Database *database_;
6144 _H<Package> package_;
6145 _H<NSString> name_;
6146 _H<NSMutableArray> files_;
6147 _H<UITableView, 2> list_;
6148 }
6149
6150 - (id) initWithDatabase:(Database *)database;
6151 - (void) setPackage:(Package *)package;
6152
6153 @end
6154
6155 @implementation FileTable
6156
6157 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6158 return files_ == nil ? 0 : [files_ count];
6159 }
6160
6161 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6162 return 24.0f;
6163 }*/
6164
6165 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6166 static NSString *reuseIdentifier = @"Cell";
6167
6168 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6169 if (cell == nil) {
6170 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6171 [cell setFont:[UIFont systemFontOfSize:16]];
6172 }
6173 [cell setText:[files_ objectAtIndex:indexPath.row]];
6174 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6175
6176 return cell;
6177 }
6178
6179 - (NSURL *) navigationURL {
6180 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6181 }
6182
6183 - (void) loadView {
6184 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6185 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6186 [list_ setRowHeight:24.0f];
6187 [(UITableView *) list_ setDataSource:self];
6188 [list_ setDelegate:self];
6189 [self setView:list_];
6190 }
6191
6192 - (void) viewDidLoad {
6193 [super viewDidLoad];
6194
6195 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6196 }
6197
6198 - (void) releaseSubviews {
6199 list_ = nil;
6200
6201 package_ = nil;
6202 files_ = nil;
6203
6204 [super releaseSubviews];
6205 }
6206
6207 - (id) initWithDatabase:(Database *)database {
6208 if ((self = [super init]) != nil) {
6209 database_ = database;
6210 } return self;
6211 }
6212
6213 - (void) setPackage:(Package *)package {
6214 package_ = nil;
6215 name_ = nil;
6216
6217 files_ = [NSMutableArray arrayWithCapacity:32];
6218
6219 if (package != nil) {
6220 package_ = package;
6221 name_ = [package id];
6222
6223 if (NSArray *files = [package files])
6224 [files_ addObjectsFromArray:files];
6225
6226 if ([files_ count] != 0) {
6227 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6228 [files_ removeObjectAtIndex:0];
6229 [files_ sortUsingSelector:@selector(compareByPath:)];
6230
6231 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6232 [stack addObject:@"/"];
6233
6234 for (int i(0), e([files_ count]); i != e; ++i) {
6235 NSString *file = [files_ objectAtIndex:i];
6236 while (![file hasPrefix:[stack lastObject]])
6237 [stack removeLastObject];
6238 NSString *directory = [stack lastObject];
6239 [stack addObject:[file stringByAppendingString:@"/"]];
6240 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6241 ([stack count] - 2) * 3, "",
6242 [file substringFromIndex:[directory length]]
6243 ]];
6244 }
6245 }
6246 }
6247
6248 [list_ reloadData];
6249 }
6250
6251 - (void) reloadData {
6252 [super reloadData];
6253
6254 [self setPackage:[database_ packageWithName:name_]];
6255 }
6256
6257 @end
6258 /* }}} */
6259 /* Package Controller {{{ */
6260 @interface CYPackageController : CydiaWebViewController <
6261 UIActionSheetDelegate
6262 > {
6263 _transient Database *database_;
6264 _H<Package> package_;
6265 _H<NSString> name_;
6266 bool commercial_;
6267 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6268 _H<UIBarButtonItem> button_;
6269 }
6270
6271 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6272
6273 @end
6274
6275 @implementation CYPackageController
6276
6277 - (NSURL *) navigationURL {
6278 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6279 }
6280
6281 - (void) _clickButtonWithName:(NSString *)name {
6282 if ([name isEqualToString:@"CLEAR"])
6283 [delegate_ clearPackage:package_];
6284 else if ([name isEqualToString:@"INSTALL"])
6285 [delegate_ installPackage:package_];
6286 else if ([name isEqualToString:@"REINSTALL"])
6287 [delegate_ installPackage:package_];
6288 else if ([name isEqualToString:@"REMOVE"])
6289 [delegate_ removePackage:package_];
6290 else if ([name isEqualToString:@"UPGRADE"])
6291 [delegate_ installPackage:package_];
6292 else _assert(false);
6293 }
6294
6295 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6296 NSString *context([sheet context]);
6297
6298 if ([context isEqualToString:@"modify"]) {
6299 if (button != [sheet cancelButtonIndex]) {
6300 [self _clickButtonWithName:buttons_[button].first];
6301 }
6302
6303 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6304 }
6305 }
6306
6307 - (bool) _allowJavaScriptPanel {
6308 return commercial_;
6309 }
6310
6311 #if !AlwaysReload
6312 - (void) _customButtonClicked {
6313 size_t count(buttons_.size());
6314 if (count == 0)
6315 return;
6316
6317 if (count == 1)
6318 [self _clickButtonWithName:buttons_[0].first];
6319 else {
6320 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6321 for (const auto &button : buttons_)
6322 [buttons addObject:button.second];
6323
6324 UIActionSheet *sheet = [[[UIActionSheet alloc]
6325 initWithTitle:nil
6326 delegate:self
6327 cancelButtonTitle:nil
6328 destructiveButtonTitle:nil
6329 otherButtonTitles:nil
6330 ] autorelease];
6331
6332 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6333 if (!IsWildcat_) {
6334 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6335 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6336 }
6337 [sheet setContext:@"modify"];
6338
6339 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6340 }
6341 }
6342
6343 - (void) reloadButtonClicked {
6344 if (commercial_ && function_ == nil && [package_ uninstalled])
6345 return;
6346 [self customButtonClicked];
6347 }
6348
6349 - (void) applyLoadingTitle {
6350 // Don't show "Loading" as the title. Ever.
6351 }
6352
6353 - (UIBarButtonItem *) rightButton {
6354 return button_;
6355 }
6356 #endif
6357
6358 - (void) setPageColor:(UIColor *)color {
6359 return [super setPageColor:nil];
6360 }
6361
6362 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6363 if ((self = [super init]) != nil) {
6364 database_ = database;
6365 name_ = name == nil ? @"" : [NSString stringWithString:name];
6366 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6367 } return self;
6368 }
6369
6370 - (void) reloadData {
6371 [super reloadData];
6372
6373 package_ = [database_ packageWithName:name_];
6374
6375 buttons_.clear();
6376
6377 if (package_ != nil) {
6378 [(Package *) package_ parse];
6379
6380 commercial_ = [package_ isCommercial];
6381
6382 if ([package_ mode] != nil)
6383 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6384 if ([package_ source] == nil);
6385 else if ([package_ upgradableAndEssential:NO])
6386 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6387 else if ([package_ uninstalled])
6388 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6389 else
6390 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6391 if (![package_ uninstalled])
6392 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6393 }
6394
6395 NSString *title;
6396 switch (buttons_.size()) {
6397 case 0: title = nil; break;
6398 case 1: title = buttons_[0].second; break;
6399 default: title = UCLocalize("MODIFY"); break;
6400 }
6401
6402 button_ = [[[UIBarButtonItem alloc]
6403 initWithTitle:title
6404 style:UIBarButtonItemStylePlain
6405 target:self
6406 action:@selector(customButtonClicked)
6407 ] autorelease];
6408 }
6409
6410 - (bool) isLoading {
6411 return commercial_ ? [super isLoading] : false;
6412 }
6413
6414 @end
6415 /* }}} */
6416
6417 /* Package List Controller {{{ */
6418 @interface PackageListController : CyteViewController <
6419 UITableViewDataSource,
6420 UITableViewDelegate
6421 > {
6422 _transient Database *database_;
6423 unsigned era_;
6424 _H<NSArray> packages_;
6425 _H<NSArray> sections_;
6426 _H<UITableView, 2> list_;
6427
6428 _H<NSArray> thumbs_;
6429 std::vector<NSInteger> offset_;
6430
6431 _H<NSString> title_;
6432 unsigned reloading_;
6433 }
6434
6435 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6436 - (void) setDelegate:(id)delegate;
6437 - (void) resetCursor;
6438 - (void) clearData;
6439
6440 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6441
6442 @end
6443
6444 @implementation PackageListController
6445
6446 - (NSURL *) referrerURL {
6447 return [self navigationURL];
6448 }
6449
6450 - (bool) isSummarized {
6451 return false;
6452 }
6453
6454 - (bool) showsSections {
6455 return true;
6456 }
6457
6458 - (void) deselectWithAnimation:(BOOL)animated {
6459 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6460 }
6461
6462 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6463 CGRect base = [[self view] bounds];
6464 base.size.height -= bounds.size.height;
6465 base.origin = [list_ frame].origin;
6466
6467 [UIView beginAnimations:nil context:NULL];
6468 [UIView setAnimationBeginsFromCurrentState:YES];
6469 [UIView setAnimationCurve:curve];
6470 [UIView setAnimationDuration:duration];
6471 [list_ setFrame:base];
6472 [UIView commitAnimations];
6473 }
6474
6475 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6476 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6477 }
6478
6479 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6480 [self resizeForKeyboardBounds:bounds duration:0];
6481 }
6482
6483 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6484 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6485 *curve = UIViewAnimationCurveEaseInOut;
6486 else
6487 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6488
6489 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6490 *duration = 0.3;
6491 else
6492 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6493 }
6494
6495 - (void) keyboardWillShow:(NSNotification *)notification {
6496 CGRect bounds;
6497 CGPoint center;
6498 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6499 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6500
6501 NSTimeInterval duration;
6502 UIViewAnimationCurve curve;
6503 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6504
6505 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6506 UIViewController *base = self;
6507 while ([base parentOrPresentingViewController] != nil)
6508 base = [base parentOrPresentingViewController];
6509 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6510 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6511
6512 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6513 intersection.size.height += CYStatusBarHeight();
6514
6515 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6516 }
6517
6518 - (void) keyboardWillHide:(NSNotification *)notification {
6519 NSTimeInterval duration;
6520 UIViewAnimationCurve curve;
6521 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6522
6523 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6524 }
6525
6526 - (void) viewWillAppear:(BOOL)animated {
6527 [super viewWillAppear:animated];
6528
6529 [self resizeForKeyboardBounds:CGRectZero];
6530 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6531 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6532 }
6533
6534 - (void) viewWillDisappear:(BOOL)animated {
6535 [super viewWillDisappear:animated];
6536
6537 [self resizeForKeyboardBounds:CGRectZero];
6538 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6539 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6540 }
6541
6542 - (void) viewDidAppear:(BOOL)animated {
6543 [super viewDidAppear:animated];
6544 [self deselectWithAnimation:animated];
6545 }
6546
6547 - (void) didSelectPackage:(Package *)package {
6548 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6549 [view setDelegate:delegate_];
6550 [[self navigationController] pushViewController:view animated:YES];
6551 }
6552
6553 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6554 NSInteger count([sections_ count]);
6555 return count == 0 ? 1 : count;
6556 }
6557
6558 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6559 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6560 return nil;
6561 return [[sections_ objectAtIndex:section] name];
6562 }
6563
6564 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6565 if ([sections_ count] == 0)
6566 return 0;
6567 return [[sections_ objectAtIndex:section] count];
6568 }
6569
6570 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6571 @synchronized (database_) {
6572 if ([database_ era] != era_)
6573 return nil;
6574
6575 Section *section([sections_ objectAtIndex:[path section]]);
6576 NSInteger row([path row]);
6577 Package *package([packages_ objectAtIndex:([section row] + row)]);
6578 return [[package retain] autorelease];
6579 } }
6580
6581 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6582 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6583 if (cell == nil)
6584 cell = [[[PackageCell alloc] init] autorelease];
6585
6586 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6587 [cell setPackage:package asSummary:[self isSummarized]];
6588 return cell;
6589 }
6590
6591 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6592 Package *package([self packageAtIndexPath:path]);
6593 package = [database_ packageWithName:[package id]];
6594 [self didSelectPackage:package];
6595 }
6596
6597 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6598 return thumbs_;
6599 }
6600
6601 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6602 return offset_[index];
6603 }
6604
6605 - (void) updateHeight {
6606 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6607 }
6608
6609 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6610 if ((self = [super init]) != nil) {
6611 database_ = database;
6612 title_ = [title copy];
6613 [[self navigationItem] setTitle:title_];
6614 } return self;
6615 }
6616
6617 - (void) loadView {
6618 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6619 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6620 [self setView:view];
6621
6622 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6623 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6624 [view addSubview:list_];
6625
6626 // XXX: is 20 the most optimal number here?
6627 [list_ setSectionIndexMinimumDisplayRowCount:20];
6628
6629 [(UITableView *) list_ setDataSource:self];
6630 [list_ setDelegate:self];
6631
6632 [self updateHeight];
6633 }
6634
6635 - (void) releaseSubviews {
6636 list_ = nil;
6637
6638 packages_ = nil;
6639 sections_ = nil;
6640
6641 thumbs_ = nil;
6642 offset_.clear();
6643
6644 [super releaseSubviews];
6645 }
6646
6647 - (void) setDelegate:(id)delegate {
6648 delegate_ = delegate;
6649 }
6650
6651 - (bool) shouldYield {
6652 return false;
6653 }
6654
6655 - (bool) shouldBlock {
6656 return false;
6657 }
6658
6659 - (NSMutableArray *) _reloadPackages {
6660 @synchronized (database_) {
6661 era_ = [database_ era];
6662 NSArray *packages([database_ packages]);
6663
6664 return [NSMutableArray arrayWithArray:packages];
6665 } }
6666
6667 - (void) _reloadData {
6668 if (reloading_ != 0) {
6669 reloading_ = 2;
6670 return;
6671 }
6672
6673 NSMutableArray *packages;
6674
6675 reload:
6676 if ([self shouldYield]) {
6677 do {
6678 UIProgressHUD *hud;
6679
6680 if (![self shouldBlock])
6681 hud = nil;
6682 else {
6683 hud = [delegate_ addProgressHUD];
6684 [hud setText:UCLocalize("LOADING")];
6685 }
6686
6687 reloading_ = 1;
6688 packages = [self yieldToSelector:@selector(_reloadPackages)];
6689
6690 if (hud != nil)
6691 [delegate_ removeProgressHUD:hud];
6692 } while (reloading_ == 2);
6693 } else {
6694 packages = [self _reloadPackages];
6695 }
6696
6697 @synchronized (database_) {
6698 if (era_ != [database_ era])
6699 goto reload;
6700 reloading_ = 0;
6701
6702 thumbs_ = nil;
6703 offset_.clear();
6704
6705 packages_ = packages;
6706
6707 if ([self showsSections])
6708 sections_ = [self sectionsForPackages:packages];
6709 else {
6710 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6711 [section setCount:[packages_ count]];
6712 sections_ = [NSArray arrayWithObject:section];
6713 }
6714
6715 [self updateHeight];
6716
6717 _profile(PackageTable$reloadData$List)
6718 [(UITableView *) list_ setDataSource:self];
6719 [list_ reloadData];
6720 _end
6721 }
6722
6723 PrintTimes();
6724 }
6725
6726 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6727 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6728 size_t end([packages count]);
6729
6730 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6731 Section *section(prefix);
6732
6733 thumbs_ = CollationThumbs_;
6734 offset_ = CollationOffset_;
6735
6736 size_t offset(0);
6737 size_t offsets([CollationStarts_ count]);
6738
6739 NSString *start([CollationStarts_ objectAtIndex:offset]);
6740 size_t length([start length]);
6741
6742 for (size_t index(0); index != end; ++index) {
6743 if (start != nil) {
6744 Package *package([packages objectAtIndex:index]);
6745 NSString *name(PackageName(package, @selector(cyname)));
6746
6747 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6748 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6749 NSString *title([CollationTitles_ objectAtIndex:offset]);
6750 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6751 [sections addObject:section];
6752
6753 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6754 if (start == nil)
6755 break;
6756 length = [start length];
6757 }
6758 }
6759
6760 [section addToCount];
6761 }
6762
6763 for (; offset != offsets; ++offset) {
6764 NSString *title([CollationTitles_ objectAtIndex:offset]);
6765 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6766 [sections addObject:section];
6767 }
6768
6769 if ([prefix count] != 0) {
6770 Section *suffix([sections lastObject]);
6771 [prefix setName:[suffix name]];
6772 [suffix setName:nil];
6773 [sections insertObject:prefix atIndex:(offsets - 1)];
6774 }
6775
6776 return sections;
6777 }
6778
6779 - (void) reloadData {
6780 [super reloadData];
6781
6782 if ([self shouldYield])
6783 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6784 else
6785 [self _reloadData];
6786 }
6787
6788 - (void) resetCursor {
6789 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6790 }
6791
6792 - (void) clearData {
6793 [self updateHeight];
6794
6795 [list_ setDataSource:nil];
6796 [list_ reloadData];
6797
6798 [self resetCursor];
6799 }
6800
6801 @end
6802 /* }}} */
6803 /* Filtered Package List Controller {{{ */
6804 typedef Function<bool, Package *> PackageFilter;
6805 typedef Function<void, NSMutableArray *> PackageSorter;
6806 @interface FilteredPackageListController : PackageListController {
6807 PackageFilter filter_;
6808 PackageSorter sorter_;
6809 }
6810
6811 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6812
6813 - (void) setFilter:(PackageFilter)filter;
6814 - (void) setSorter:(PackageSorter)sorter;
6815
6816 @end
6817
6818 @implementation FilteredPackageListController
6819
6820 - (void) setFilter:(PackageFilter)filter {
6821 @synchronized (self) {
6822 filter_ = filter;
6823 } }
6824
6825 - (void) setSorter:(PackageSorter)sorter {
6826 @synchronized (self) {
6827 sorter_ = sorter;
6828 } }
6829
6830 - (NSMutableArray *) _reloadPackages {
6831 @synchronized (database_) {
6832 era_ = [database_ era];
6833
6834 NSArray *packages([database_ packages]);
6835 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6836
6837 PackageFilter filter;
6838 PackageSorter sorter;
6839
6840 @synchronized (self) {
6841 filter = filter_;
6842 sorter = sorter_;
6843 }
6844
6845 _profile(PackageTable$reloadData$Filter)
6846 for (Package *package in packages)
6847 if ([package valid] && filter(package))
6848 [filtered addObject:package];
6849 _end
6850
6851 if (sorter)
6852 sorter(filtered);
6853 return filtered;
6854 } }
6855
6856 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6857 if ((self = [super initWithDatabase:database title:title]) != nil) {
6858 [self setFilter:filter];
6859 } return self;
6860 }
6861
6862 @end
6863 /* }}} */
6864
6865 /* Home Controller {{{ */
6866 @interface HomeController : CydiaWebViewController {
6867 CFRunLoopRef runloop_;
6868 SCNetworkReachabilityRef reachability_;
6869 }
6870
6871 @end
6872
6873 @implementation HomeController
6874
6875 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6876 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6877 }
6878
6879 - (id) init {
6880 if ((self = [super init]) != nil) {
6881 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6882 [self reloadData];
6883
6884 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6885 if (reachability_ != NULL) {
6886 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6887 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6888
6889 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6890 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6891 runloop_ = runloop;
6892 }
6893 } return self;
6894 }
6895
6896 - (void) dealloc {
6897 if (reachability_ != NULL && runloop_ != NULL)
6898 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6899 [super dealloc];
6900 }
6901
6902 - (NSURL *) navigationURL {
6903 return [NSURL URLWithString:@"cydia://home"];
6904 }
6905
6906 - (void) aboutButtonClicked {
6907 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6908
6909 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6910 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6911 [alert setCancelButtonIndex:0];
6912
6913 [alert setMessage:
6914 @"Copyright \u00a9 2008-2014\n"
6915 "SaurikIT, LLC\n"
6916 "\n"
6917 "Jay Freeman (saurik)\n"
6918 "saurik@saurik.com\n"
6919 "http://www.saurik.com/"
6920 ];
6921
6922 [alert show];
6923 }
6924
6925 - (UIBarButtonItem *) leftButton {
6926 return [[[UIBarButtonItem alloc]
6927 initWithTitle:UCLocalize("ABOUT")
6928 style:UIBarButtonItemStylePlain
6929 target:self
6930 action:@selector(aboutButtonClicked)
6931 ] autorelease];
6932 }
6933
6934 @end
6935 /* }}} */
6936
6937 /* Cydia Navigation Controller Interface {{{ */
6938 @interface UINavigationController (Cydia)
6939
6940 - (NSArray *) navigationURLCollection;
6941 - (void) unloadData;
6942
6943 @end
6944 /* }}} */
6945
6946 /* Cydia Tab Bar Controller {{{ */
6947 @interface CydiaTabBarController : CyteTabBarController <
6948 UITabBarControllerDelegate,
6949 FetchDelegate
6950 > {
6951 _transient Database *database_;
6952
6953 _H<UIActivityIndicatorView> indicator_;
6954
6955 bool updating_;
6956 // XXX: ok, "updatedelegate_"?...
6957 _transient NSObject<CydiaDelegate> *updatedelegate_;
6958 }
6959
6960 - (NSArray *) navigationURLCollection;
6961 - (void) beginUpdate;
6962 - (BOOL) updating;
6963
6964 @end
6965
6966 @implementation CydiaTabBarController
6967
6968 - (NSArray *) navigationURLCollection {
6969 NSMutableArray *items([NSMutableArray array]);
6970
6971 // XXX: Should this deal with transient view controllers?
6972 for (id navigation in [self viewControllers]) {
6973 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6974 if (stack != nil)
6975 [items addObject:stack];
6976 }
6977
6978 return items;
6979 }
6980
6981 - (id) initWithDatabase:(Database *)database {
6982 if ((self = [super init]) != nil) {
6983 database_ = database;
6984 [self setDelegate:self];
6985
6986 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6987 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6988
6989 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6990 } return self;
6991 }
6992
6993 - (void) setUpdate:(NSDate *)date {
6994 [self beginUpdate];
6995 }
6996
6997 - (void) beginUpdate {
6998 if (updating_)
6999 return;
7000
7001 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7002 UITabBarItem *item([controller tabBarItem]);
7003
7004 [item setBadgeValue:@""];
7005 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7006
7007 [indicator_ startAnimating];
7008 [badge addSubview:indicator_];
7009
7010 [updatedelegate_ retainNetworkActivityIndicator];
7011 updating_ = true;
7012
7013 [NSThread
7014 detachNewThreadSelector:@selector(performUpdate)
7015 toTarget:self
7016 withObject:nil
7017 ];
7018 }
7019
7020 - (void) performUpdate {
7021 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7022
7023 SourceStatus status(self, database_);
7024 [database_ updateWithStatus:status];
7025
7026 [self
7027 performSelectorOnMainThread:@selector(completeUpdate)
7028 withObject:nil
7029 waitUntilDone:NO
7030 ];
7031
7032 [pool release];
7033 }
7034
7035 - (void) stopUpdateWithSelector:(SEL)selector {
7036 updating_ = false;
7037 [updatedelegate_ releaseNetworkActivityIndicator];
7038
7039 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7040 [[controller tabBarItem] setBadgeValue:nil];
7041
7042 [indicator_ removeFromSuperview];
7043 [indicator_ stopAnimating];
7044
7045 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7046 }
7047
7048 - (void) completeUpdate {
7049 if (!updating_)
7050 return;
7051 [self stopUpdateWithSelector:@selector(reloadData)];
7052 }
7053
7054 - (void) cancelUpdate {
7055 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7056 }
7057
7058 - (void) cancelPressed {
7059 [self cancelUpdate];
7060 }
7061
7062 - (BOOL) updating {
7063 return updating_;
7064 }
7065
7066 - (bool) isSourceCancelled {
7067 return !updating_;
7068 }
7069
7070 - (void) startSourceFetch:(NSString *)uri {
7071 }
7072
7073 - (void) stopSourceFetch:(NSString *)uri {
7074 }
7075
7076 - (void) setUpdateDelegate:(id)delegate {
7077 updatedelegate_ = delegate;
7078 }
7079
7080 @end
7081 /* }}} */
7082
7083 /* Cydia Navigation Controller Implementation {{{ */
7084 @implementation UINavigationController (Cydia)
7085
7086 - (NSArray *) navigationURLCollection {
7087 NSMutableArray *stack([NSMutableArray array]);
7088
7089 for (CyteViewController *controller in [self viewControllers]) {
7090 NSString *url = [[controller navigationURL] absoluteString];
7091 if (url != nil)
7092 [stack addObject:url];
7093 }
7094
7095 return stack;
7096 }
7097
7098 - (void) reloadData {
7099 [super reloadData];
7100
7101 UIViewController *visible([self visibleViewController]);
7102 if (visible != nil)
7103 [visible reloadData];
7104
7105 // on the iPad, this view controller is ALSO visible. :(
7106 if (IsWildcat_)
7107 if (UIViewController *top = [self topViewController])
7108 if (top != visible)
7109 [top reloadData];
7110 }
7111
7112 - (void) unloadData {
7113 for (CyteViewController *page in [self viewControllers])
7114 [page unloadData];
7115
7116 [super unloadData];
7117 }
7118
7119 @end
7120 /* }}} */
7121
7122 /* Cydia:// Protocol {{{ */
7123 @interface CydiaURLProtocol : NSURLProtocol {
7124 }
7125
7126 @end
7127
7128 @implementation CydiaURLProtocol
7129
7130 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7131 NSURL *url([request URL]);
7132 if (url == nil)
7133 return NO;
7134
7135 NSString *scheme([[url scheme] lowercaseString]);
7136 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7137 return YES;
7138 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7139 return YES;
7140
7141 return NO;
7142 }
7143
7144 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7145 return request;
7146 }
7147
7148 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7149 id<NSURLProtocolClient> client([self client]);
7150 if (icon == nil)
7151 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7152 else {
7153 NSData *data(UIImagePNGRepresentation(icon));
7154
7155 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7156 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7157 [client URLProtocol:self didLoadData:data];
7158 [client URLProtocolDidFinishLoading:self];
7159 }
7160 }
7161
7162 - (void) startLoading {
7163 id<NSURLProtocolClient> client([self client]);
7164 NSURLRequest *request([self request]);
7165
7166 NSURL *url([request URL]);
7167 NSString *href([url absoluteString]);
7168 NSString *scheme([[url scheme] lowercaseString]);
7169
7170 NSString *path;
7171
7172 if ([scheme isEqualToString:@"cydia"])
7173 path = [href substringFromIndex:8];
7174 else if ([scheme isEqualToString:@"about"])
7175 path = [href substringFromIndex:12];
7176 else _assert(false);
7177
7178 NSRange slash([path rangeOfString:@"/"]);
7179
7180 NSString *command;
7181 if (slash.location == NSNotFound) {
7182 command = path;
7183 path = nil;
7184 } else {
7185 command = [path substringToIndex:slash.location];
7186 path = [path substringFromIndex:(slash.location + 1)];
7187 }
7188
7189 Database *database([Database sharedInstance]);
7190
7191 if ([command isEqualToString:@"package-icon"]) {
7192 if (path == nil)
7193 goto fail;
7194 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7195 Package *package([database packageWithName:path]);
7196 if (package == nil)
7197 goto fail;
7198 [package parse];
7199 UIImage *icon([package icon]);
7200 [self _returnPNGWithImage:icon forRequest:request];
7201 } else if ([command isEqualToString:@"uikit-image"]) {
7202 if (path == nil)
7203 goto fail;
7204 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7205 UIImage *icon(_UIImageWithName(path));
7206 [self _returnPNGWithImage:icon forRequest:request];
7207 } else if ([command isEqualToString:@"section-icon"]) {
7208 if (path == nil)
7209 goto fail;
7210 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7211 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7212 if (icon == nil)
7213 icon = [UIImage imageNamed:@"unknown.png"];
7214 [self _returnPNGWithImage:icon forRequest:request];
7215 } else fail: {
7216 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7217 }
7218 }
7219
7220 - (void) stopLoading {
7221 }
7222
7223 @end
7224 /* }}} */
7225
7226 /* Section Controller {{{ */
7227 @interface SectionController : FilteredPackageListController {
7228 _H<NSString> key_;
7229 _H<NSString> section_;
7230 }
7231
7232 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7233
7234 @end
7235
7236 @implementation SectionController
7237
7238 - (NSURL *) referrerURL {
7239 NSString *name(section_);
7240 name = name ?: @"*";
7241 NSString *key(key_);
7242 key = key ?: @"*";
7243 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7244 }
7245
7246 - (NSURL *) navigationURL {
7247 NSString *name(section_);
7248 name = name ?: @"*";
7249 NSString *key(key_);
7250 key = key ?: @"*";
7251 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7252 }
7253
7254 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7255 NSString *title;
7256 if (section == nil)
7257 title = UCLocalize("ALL_PACKAGES");
7258 else if (![section isEqual:@""])
7259 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7260 else
7261 title = UCLocalize("NO_SECTION");
7262
7263 if ((self = [super initWithDatabase:database title:title]) != nil) {
7264 key_ = [source key];
7265 section_ = section;
7266 } return self;
7267 }
7268
7269 - (void) reloadData {
7270 Source *source([database_ sourceWithKey:key_]);
7271 _H<NSString> name(section_);
7272
7273 [self setFilter:[=](Package *package) {
7274 NSString *section([package section]);
7275
7276 return (
7277 name == nil ||
7278 section == nil && [name length] == 0 ||
7279 [name isEqualToString:section]
7280 ) && (
7281 source == nil ||
7282 [package source] == source
7283 ) && [package visible];
7284 }];
7285
7286 [super reloadData];
7287 }
7288
7289 @end
7290 /* }}} */
7291 /* Sections Controller {{{ */
7292 @interface SectionsController : CyteViewController <
7293 UITableViewDataSource,
7294 UITableViewDelegate
7295 > {
7296 _transient Database *database_;
7297 _H<NSString> key_;
7298 _H<NSMutableArray> sections_;
7299 _H<NSMutableArray> filtered_;
7300 _H<UITableView, 2> list_;
7301 }
7302
7303 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7304 - (void) editButtonClicked;
7305
7306 @end
7307
7308 @implementation SectionsController
7309
7310 - (NSURL *) navigationURL {
7311 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7312 }
7313
7314 - (Source *) source {
7315 if (key_ == nil)
7316 return nil;
7317 return [database_ sourceWithKey:key_];
7318 }
7319
7320 - (void) updateNavigationItem {
7321 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7322 if ([sections_ count] == 0) {
7323 [[self navigationItem] setRightBarButtonItem:nil];
7324 } else {
7325 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7326 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7327 target:self
7328 action:@selector(editButtonClicked)
7329 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7330 }
7331 }
7332
7333 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7334 [super setEditing:editing animated:animated];
7335
7336 if (editing)
7337 [list_ reloadData];
7338 else
7339 [delegate_ updateData];
7340
7341 [self updateNavigationItem];
7342 }
7343
7344 - (void) viewDidAppear:(BOOL)animated {
7345 [super viewDidAppear:animated];
7346 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7347 }
7348
7349 - (void) viewWillDisappear:(BOOL)animated {
7350 [super viewWillDisappear:animated];
7351 [self setEditing:NO];
7352 }
7353
7354 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7355 Section *section = nil;
7356 int index = [indexPath row];
7357 if (![self isEditing]) {
7358 index -= 1;
7359 if (index >= 0)
7360 section = [filtered_ objectAtIndex:index];
7361 } else {
7362 section = [sections_ objectAtIndex:index];
7363 }
7364 return section;
7365 }
7366
7367 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7368 if ([self isEditing])
7369 return [sections_ count];
7370 else
7371 return [filtered_ count] + 1;
7372 }
7373
7374 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7375 return 45.0f;
7376 }*/
7377
7378 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7379 static NSString *reuseIdentifier = @"SectionCell";
7380
7381 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7382 if (cell == nil)
7383 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7384
7385 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7386
7387 return cell;
7388 }
7389
7390 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7391 if ([self isEditing])
7392 return;
7393
7394 Section *section = [self sectionAtIndexPath:indexPath];
7395
7396 SectionController *controller = [[[SectionController alloc]
7397 initWithDatabase:database_
7398 source:[self source]
7399 section:[section name]
7400 ] autorelease];
7401 [controller setDelegate:delegate_];
7402
7403 [[self navigationController] pushViewController:controller animated:YES];
7404 }
7405
7406 - (void) loadView {
7407 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7408 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7409 [list_ setRowHeight:46];
7410 [(UITableView *) list_ setDataSource:self];
7411 [list_ setDelegate:self];
7412 [self setView:list_];
7413 }
7414
7415 - (void) viewDidLoad {
7416 [super viewDidLoad];
7417
7418 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7419 }
7420
7421 - (void) releaseSubviews {
7422 list_ = nil;
7423
7424 sections_ = nil;
7425 filtered_ = nil;
7426
7427 [super releaseSubviews];
7428 }
7429
7430 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7431 if ((self = [super init]) != nil) {
7432 database_ = database;
7433 key_ = [source key];
7434 } return self;
7435 }
7436
7437 - (void) reloadData {
7438 [super reloadData];
7439
7440 NSArray *packages = [database_ packages];
7441
7442 sections_ = [NSMutableArray arrayWithCapacity:16];
7443 filtered_ = [NSMutableArray arrayWithCapacity:16];
7444
7445 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7446
7447 Source *source([self source]);
7448
7449 _trace();
7450 for (Package *package in packages) {
7451 if (source != nil && [package source] != source)
7452 continue;
7453
7454 NSString *name([package section]);
7455 NSString *key(name == nil ? @"" : name);
7456
7457 Section *section;
7458
7459 _profile(SectionsView$reloadData$Section)
7460 section = [sections objectForKey:key];
7461 if (section == nil) {
7462 _profile(SectionsView$reloadData$Section$Allocate)
7463 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7464 [sections setObject:section forKey:key];
7465 _end
7466 }
7467 _end
7468
7469 [section addToCount];
7470
7471 _profile(SectionsView$reloadData$Filter)
7472 if (![package valid] || ![package visible])
7473 continue;
7474 _end
7475
7476 [section addToRow];
7477 }
7478 _trace();
7479
7480 [sections_ addObjectsFromArray:[sections allValues]];
7481
7482 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7483
7484 for (Section *section in (id) sections_) {
7485 size_t count([section row]);
7486 if (count == 0)
7487 continue;
7488
7489 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7490 [section setCount:count];
7491 [filtered_ addObject:section];
7492 }
7493
7494 [self updateNavigationItem];
7495 [list_ reloadData];
7496 _trace();
7497 }
7498
7499 - (void) editButtonClicked {
7500 [self setEditing:![self isEditing] animated:YES];
7501 }
7502
7503 @end
7504 /* }}} */
7505
7506 /* Changes Controller {{{ */
7507 @interface ChangesController : FilteredPackageListController {
7508 unsigned upgrades_;
7509 }
7510
7511 - (id) initWithDatabase:(Database *)database;
7512
7513 @end
7514
7515 @implementation ChangesController
7516
7517 - (NSURL *) referrerURL {
7518 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7519 }
7520
7521 - (NSURL *) navigationURL {
7522 return [NSURL URLWithString:@"cydia://changes"];
7523 }
7524
7525 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7526 @synchronized (database_) {
7527 if ([database_ era] != era_)
7528 return nil;
7529
7530 NSUInteger sectionIndex([path section]);
7531 if (sectionIndex >= [sections_ count])
7532 return nil;
7533 Section *section([sections_ objectAtIndex:sectionIndex]);
7534 NSInteger row([path row]);
7535 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7536 } }
7537
7538 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7539 NSString *context([alert context]);
7540
7541 if ([context isEqualToString:@"norefresh"])
7542 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7543 }
7544
7545 - (void) setLeftBarButtonItem {
7546 if ([delegate_ updating])
7547 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7548 initWithTitle:UCLocalize("CANCEL")
7549 style:UIBarButtonItemStyleDone
7550 target:self
7551 action:@selector(cancelButtonClicked)
7552 ] autorelease] animated:YES];
7553 else
7554 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7555 initWithTitle:UCLocalize("REFRESH")
7556 style:UIBarButtonItemStylePlain
7557 target:self
7558 action:@selector(refreshButtonClicked)
7559 ] autorelease] animated:YES];
7560 }
7561
7562 - (void) refreshButtonClicked {
7563 if ([delegate_ requestUpdate])
7564 [self setLeftBarButtonItem];
7565 }
7566
7567 - (void) cancelButtonClicked {
7568 [delegate_ cancelUpdate];
7569 }
7570
7571 - (void) upgradeButtonClicked {
7572 [delegate_ distUpgrade];
7573 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7574 }
7575
7576 - (bool) shouldYield {
7577 return true;
7578 }
7579
7580 - (bool) shouldBlock {
7581 return true;
7582 }
7583
7584 - (void) useFilter {
7585 @synchronized (self) {
7586 [self setFilter:[](Package *package) {
7587 return [package upgradableAndEssential:YES] || [package visible];
7588 }];
7589
7590 [self setSorter:[](NSMutableArray *packages) {
7591 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7592 }];
7593 } }
7594
7595 - (id) initWithDatabase:(Database *)database {
7596 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7597 [self useFilter];
7598 } return self;
7599 }
7600
7601 - (void) viewDidLoad {
7602 [super viewDidLoad];
7603 [self setLeftBarButtonItem];
7604 }
7605
7606 - (void) viewWillAppear:(BOOL)animated {
7607 [super viewWillAppear:animated];
7608 [self setLeftBarButtonItem];
7609 }
7610
7611 - (void) reloadData {
7612 [self setLeftBarButtonItem];
7613 [super reloadData];
7614 }
7615
7616 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7617 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7618
7619 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7620 Section *ignored = nil;
7621 Section *section = nil;
7622 time_t last = 0;
7623
7624 upgrades_ = 0;
7625 bool unseens = false;
7626
7627 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7628
7629 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7630 Package *package = [packages objectAtIndex:offset];
7631
7632 BOOL uae = [package upgradableAndEssential:YES];
7633
7634 if (!uae) {
7635 unseens = true;
7636 time_t seen([package seen]);
7637
7638 if (section == nil || last != seen) {
7639 last = seen;
7640
7641 NSString *name;
7642 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7643 [name autorelease];
7644
7645 _profile(ChangesController$reloadData$Allocate)
7646 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7647 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7648 [sections addObject:section];
7649 _end
7650 }
7651
7652 [section addToCount];
7653 } else if ([package ignored]) {
7654 if (ignored == nil) {
7655 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7656 }
7657 [ignored addToCount];
7658 } else {
7659 ++upgrades_;
7660 [upgradable addToCount];
7661 }
7662 }
7663 _trace();
7664
7665 CFRelease(formatter);
7666
7667 if (unseens) {
7668 Section *last = [sections lastObject];
7669 size_t count = [last count];
7670 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7671 [sections removeLastObject];
7672 }
7673
7674 if ([ignored count] != 0)
7675 [sections insertObject:ignored atIndex:0];
7676 if (upgrades_ != 0)
7677 [sections insertObject:upgradable atIndex:0];
7678
7679 [list_ reloadData];
7680
7681 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7682 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7683 style:UIBarButtonItemStylePlain
7684 target:self
7685 action:@selector(upgradeButtonClicked)
7686 ] autorelease]) animated:YES];
7687
7688 return sections;
7689 }
7690
7691 @end
7692 /* }}} */
7693 /* Search Controller {{{ */
7694 @interface SearchController : FilteredPackageListController <
7695 UISearchBarDelegate
7696 > {
7697 _H<UISearchBar, 1> search_;
7698 BOOL searchloaded_;
7699 bool summary_;
7700 }
7701
7702 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7703 - (void) reloadData;
7704
7705 @end
7706
7707 @implementation SearchController
7708
7709 - (NSURL *) referrerURL {
7710 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7711 }
7712
7713 - (NSURL *) navigationURL {
7714 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7715 return [NSURL URLWithString:@"cydia://search"];
7716 else
7717 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7718 }
7719
7720 - (NSArray *) termsForQuery:(NSString *)query {
7721 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7722 for (NSString *component in [query componentsSeparatedByString:@" "])
7723 if ([component length] != 0)
7724 [terms addObject:component];
7725
7726 return terms;
7727 }
7728
7729 - (void) useSearch {
7730 _H<NSArray> query([self termsForQuery:[search_ text]]);
7731 summary_ = false;
7732
7733 @synchronized (self) {
7734 [self setFilter:[=](Package *package) {
7735 if (![package unfiltered])
7736 return false;
7737 if (![package matches:query])
7738 return false;
7739 return true;
7740 }];
7741
7742 [self setSorter:[](NSMutableArray *packages) {
7743 [packages radixSortUsingSelector:@selector(rank)];
7744 }];
7745 }
7746
7747 [self clearData];
7748 [self reloadData];
7749 }
7750
7751 - (void) usePrefix:(NSString *)prefix {
7752 _H<NSString> query(prefix);
7753 summary_ = true;
7754
7755 @synchronized (self) {
7756 [self setFilter:[=](Package *package) {
7757 if ([query length] == 0)
7758 return false;
7759 if (![package unfiltered])
7760 return false;
7761 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7762 return false;
7763 return true;
7764 }];
7765
7766 [self setSorter:nullptr];
7767 }
7768
7769 [self reloadData];
7770 }
7771
7772 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7773 [self clearData];
7774 [self usePrefix:[search_ text]];
7775 }
7776
7777 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7778 [search_ resignFirstResponder];
7779 [self useSearch];
7780 }
7781
7782 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7783 [search_ setText:@""];
7784 [self searchBarButtonClicked:searchBar];
7785 }
7786
7787 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7788 [self searchBarButtonClicked:searchBar];
7789 }
7790
7791 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7792 [self usePrefix:text];
7793 }
7794
7795 - (bool) shouldYield {
7796 return YES;
7797 }
7798
7799 - (bool) shouldBlock {
7800 return !summary_;
7801 }
7802
7803 - (bool) isSummarized {
7804 return summary_;
7805 }
7806
7807 - (bool) showsSections {
7808 return false;
7809 }
7810
7811 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7812 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7813 search_ = [[[UISearchBar alloc] init] autorelease];
7814 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7815 [search_ setDelegate:self];
7816
7817 UITextField *textField;
7818 if ([search_ respondsToSelector:@selector(searchField)])
7819 textField = [search_ searchField];
7820 else
7821 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7822
7823 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7824 [textField setEnablesReturnKeyAutomatically:NO];
7825 [[self navigationItem] setTitleView:textField];
7826
7827 if (query != nil)
7828 [search_ setText:query];
7829 [self useSearch];
7830 } return self;
7831 }
7832
7833 - (void) viewDidAppear:(BOOL)animated {
7834 [super viewDidAppear:animated];
7835
7836 if (!searchloaded_) {
7837 searchloaded_ = YES;
7838 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7839 [search_ layoutSubviews];
7840 }
7841
7842 if ([self isSummarized])
7843 [search_ becomeFirstResponder];
7844 }
7845
7846 - (void) reloadData {
7847 [self resetCursor];
7848 [super reloadData];
7849 }
7850
7851 - (void) didSelectPackage:(Package *)package {
7852 [search_ resignFirstResponder];
7853 [super didSelectPackage:package];
7854 }
7855
7856 @end
7857 /* }}} */
7858 /* Package Settings Controller {{{ */
7859 @interface PackageSettingsController : CyteViewController <
7860 UITableViewDataSource,
7861 UITableViewDelegate
7862 > {
7863 _transient Database *database_;
7864 _H<NSString> name_;
7865 _H<Package> package_;
7866 _H<UITableView, 2> table_;
7867 _H<UISwitch> subscribedSwitch_;
7868 _H<UISwitch> ignoredSwitch_;
7869 _H<UITableViewCell> subscribedCell_;
7870 _H<UITableViewCell> ignoredCell_;
7871 }
7872
7873 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7874
7875 @end
7876
7877 @implementation PackageSettingsController
7878
7879 - (NSURL *) navigationURL {
7880 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7881 }
7882
7883 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7884 if (package_ == nil)
7885 return 0;
7886
7887 if ([package_ installed] == nil)
7888 return 1;
7889 else
7890 return 2;
7891 }
7892
7893 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7894 if (package_ == nil)
7895 return 0;
7896
7897 // both sections contain just one item right now.
7898 return 1;
7899 }
7900
7901 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7902 return nil;
7903 }
7904
7905 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7906 if (section == 0)
7907 return UCLocalize("SHOW_ALL_CHANGES_EX");
7908 else
7909 return UCLocalize("IGNORE_UPGRADES_EX");
7910 }
7911
7912 - (void) onSubscribed:(id)control {
7913 bool value([control isOn]);
7914 if (package_ == nil)
7915 return;
7916 if ([package_ setSubscribed:value])
7917 [delegate_ updateData];
7918 }
7919
7920 - (void) _updateIgnored {
7921 const char *package([name_ UTF8String]);
7922 bool on([ignoredSwitch_ isOn]);
7923
7924 pid_t pid(ExecFork());
7925 if (pid == 0) {
7926 FILE *dpkg(popen("dpkg --set-selections", "w"));
7927 fwrite(package, strlen(package), 1, dpkg);
7928
7929 if (on)
7930 fwrite(" hold\n", 6, 1, dpkg);
7931 else
7932 fwrite(" install\n", 9, 1, dpkg);
7933
7934 pclose(dpkg);
7935
7936 exit(0);
7937 } ReapZombie(pid);
7938 }
7939
7940 - (void) onIgnored:(id)control {
7941 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7942 [invocation setTarget:self];
7943 [invocation setSelector:@selector(_updateIgnored)];
7944
7945 [delegate_ reloadDataWithInvocation:invocation];
7946 }
7947
7948 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7949 if (package_ == nil)
7950 return nil;
7951
7952 switch ([indexPath section]) {
7953 case 0: return subscribedCell_;
7954 case 1: return ignoredCell_;
7955
7956 _nodefault
7957 }
7958
7959 return nil;
7960 }
7961
7962 - (void) loadView {
7963 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7964 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7965 [self setView:view];
7966
7967 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7968 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7969 [(UITableView *) table_ setDataSource:self];
7970 [table_ setDelegate:self];
7971 [view addSubview:table_];
7972
7973 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7974 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7975 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7976
7977 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7978 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7979 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7980
7981 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7982 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7983 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7984 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7985
7986 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7987 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7988 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7989 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7990 }
7991
7992 - (void) viewDidLoad {
7993 [super viewDidLoad];
7994
7995 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7996 }
7997
7998 - (void) releaseSubviews {
7999 ignoredCell_ = nil;
8000 subscribedCell_ = nil;
8001 table_ = nil;
8002 ignoredSwitch_ = nil;
8003 subscribedSwitch_ = nil;
8004
8005 [super releaseSubviews];
8006 }
8007
8008 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8009 if ((self = [super init]) != nil) {
8010 database_ = database;
8011 name_ = package;
8012 } return self;
8013 }
8014
8015 - (void) reloadData {
8016 [super reloadData];
8017
8018 package_ = [database_ packageWithName:name_];
8019
8020 if (package_ != nil) {
8021 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8022 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8023 } // XXX: what now, G?
8024
8025 [table_ reloadData];
8026 }
8027
8028 @end
8029 /* }}} */
8030
8031 /* Installed Controller {{{ */
8032 @interface InstalledController : FilteredPackageListController {
8033 bool sectioned_;
8034 }
8035
8036 - (id) initWithDatabase:(Database *)database;
8037 - (void) queueStatusDidChange;
8038
8039 @end
8040
8041 @implementation InstalledController
8042
8043 - (NSURL *) referrerURL {
8044 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8045 }
8046
8047 - (NSURL *) navigationURL {
8048 return [NSURL URLWithString:@"cydia://installed"];
8049 }
8050
8051 - (void) useRecent {
8052 sectioned_ = false;
8053
8054 @synchronized (self) {
8055 [self setFilter:[](Package *package) {
8056 return ![package uninstalled] && package->role_ < 7;
8057 }];
8058
8059 [self setSorter:[](NSMutableArray *packages) {
8060 [packages radixSortUsingSelector:@selector(recent)];
8061 }];
8062 } }
8063
8064 - (void) useFilter:(UISegmentedControl *)segmented {
8065 NSInteger selected([segmented selectedSegmentIndex]);
8066 if (selected == 2)
8067 return [self useRecent];
8068 bool simple(selected == 0);
8069 sectioned_ = true;
8070
8071 @synchronized (self) {
8072 [self setFilter:[=](Package *package) {
8073 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8074 }];
8075
8076 [self setSorter:nullptr];
8077 } }
8078
8079 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8080 if (sectioned_)
8081 return [super sectionsForPackages:packages];
8082
8083 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8084
8085 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8086 Section *section(nil);
8087 time_t last(0);
8088
8089 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8090 Package *package([packages objectAtIndex:offset]);
8091
8092 time_t upgraded([package upgraded]);
8093 if (upgraded < 1168364520)
8094 upgraded = 0;
8095 else
8096 upgraded -= upgraded % (60 * 60 * 24);
8097
8098 if (section == nil || upgraded != last) {
8099 last = upgraded;
8100
8101 NSString *name;
8102 if (upgraded == 0)
8103 continue; // XXX: name = UCLocalize("...");
8104 else {
8105 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8106 [name autorelease];
8107 }
8108
8109 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8110 [sections addObject:section];
8111 }
8112
8113 [section addToCount];
8114 }
8115
8116 CFRelease(formatter);
8117 return sections;
8118 }
8119
8120 - (id) initWithDatabase:(Database *)database {
8121 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8122 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8123 [segmented setSelectedSegmentIndex:0];
8124 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8125 [[self navigationItem] setTitleView:segmented];
8126
8127 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8128 [self useFilter:segmented];
8129
8130 [self queueStatusDidChange];
8131 } return self;
8132 }
8133
8134 #if !AlwaysReload
8135 - (void) queueButtonClicked {
8136 [delegate_ queue];
8137 }
8138 #endif
8139
8140 - (void) queueStatusDidChange {
8141 #if !AlwaysReload
8142 if (Queuing_) {
8143 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8144 initWithTitle:UCLocalize("QUEUE")
8145 style:UIBarButtonItemStyleDone
8146 target:self
8147 action:@selector(queueButtonClicked)
8148 ] autorelease]];
8149 } else {
8150 [[self navigationItem] setRightBarButtonItem:nil];
8151 }
8152 #endif
8153 }
8154
8155 - (void) modeChanged:(UISegmentedControl *)segmented {
8156 [self useFilter:segmented];
8157 [self reloadData];
8158 }
8159
8160 @end
8161 /* }}} */
8162
8163 /* Source Cell {{{ */
8164 @interface SourceCell : CyteTableViewCell <
8165 CyteTableViewCellDelegate,
8166 SourceDelegate
8167 > {
8168 _H<Source, 1> source_;
8169 _H<NSURL> url_;
8170 _H<UIImage> icon_;
8171 _H<NSString> origin_;
8172 _H<NSString> label_;
8173 _H<UIActivityIndicatorView> indicator_;
8174 }
8175
8176 - (void) setSource:(Source *)source;
8177 - (void) setFetch:(NSNumber *)fetch;
8178
8179 @end
8180
8181 @implementation SourceCell
8182
8183 - (void) _setImage:(NSArray *)data {
8184 if ([url_ isEqual:[data objectAtIndex:0]]) {
8185 icon_ = [data objectAtIndex:1];
8186 [content_ setNeedsDisplay];
8187 }
8188 }
8189
8190 - (void) _setSource:(NSURL *) url {
8191 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8192
8193 if (NSData *data = [NSURLConnection
8194 sendSynchronousRequest:[NSURLRequest
8195 requestWithURL:url
8196 cachePolicy:NSURLRequestUseProtocolCachePolicy
8197 timeoutInterval:10
8198 ]
8199
8200 returningResponse:NULL
8201 error:NULL
8202 ])
8203 if (UIImage *image = [UIImage imageWithData:data])
8204 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8205
8206 [pool release];
8207 }
8208
8209 - (void) setSource:(Source *)source {
8210 source_ = source;
8211 [source_ setDelegate:self];
8212
8213 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8214
8215 icon_ = [UIImage imageNamed:@"unknown.png"];
8216
8217 origin_ = [source name];
8218 label_ = [source rooturi];
8219
8220 [content_ setNeedsDisplay];
8221
8222 url_ = [source iconURL];
8223 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8224 }
8225
8226 - (void) setAllSource {
8227 source_ = nil;
8228 [indicator_ stopAnimating];
8229
8230 icon_ = [UIImage imageNamed:@"folder.png"];
8231 origin_ = UCLocalize("ALL_SOURCES");
8232 label_ = UCLocalize("ALL_SOURCES_EX");
8233 [content_ setNeedsDisplay];
8234 }
8235
8236 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8237 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8238 UIView *content([self contentView]);
8239 CGRect bounds([content bounds]);
8240
8241 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8242 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8243 [content_ setBackgroundColor:[UIColor whiteColor]];
8244 [content addSubview:content_];
8245
8246 [content_ setDelegate:self];
8247 [content_ setOpaque:YES];
8248
8249 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8250 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8251 [content addSubview:indicator_];
8252
8253 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8254 } return self;
8255 }
8256
8257 - (void) layoutSubviews {
8258 [super layoutSubviews];
8259
8260 UIView *content([self contentView]);
8261 CGRect bounds([content bounds]);
8262
8263 CGRect frame([indicator_ frame]);
8264 frame.origin.x = bounds.size.width - frame.size.width;
8265 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8266
8267 if (kCFCoreFoundationVersionNumber < 800)
8268 frame.origin.x -= 8;
8269 [indicator_ setFrame:frame];
8270 }
8271
8272 - (NSString *) accessibilityLabel {
8273 return origin_;
8274 }
8275
8276 - (void) drawContentRect:(CGRect)rect {
8277 bool highlighted(highlighted_);
8278 float width(rect.size.width);
8279
8280 if (icon_ != nil) {
8281 CGRect rect;
8282 rect.size = [(UIImage *) icon_ size];
8283
8284 while (rect.size.width > 32 || rect.size.height > 32) {
8285 rect.size.width /= 2;
8286 rect.size.height /= 2;
8287 }
8288
8289 rect.origin.x = 26 - rect.size.width / 2;
8290 rect.origin.y = 26 - rect.size.height / 2;
8291
8292 [icon_ drawInRect:Retina(rect)];
8293 }
8294
8295 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8296 UISetColor(White_);
8297
8298 if (!highlighted)
8299 UISetColor(Black_);
8300 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8301
8302 if (!highlighted)
8303 UISetColor(Gray_);
8304 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8305 }
8306
8307 - (void) setFetch:(NSNumber *)fetch {
8308 if ([fetch boolValue])
8309 [indicator_ startAnimating];
8310 else
8311 [indicator_ stopAnimating];
8312 }
8313
8314 @end
8315 /* }}} */
8316 /* Sources Controller {{{ */
8317 @interface SourcesController : CyteViewController <
8318 UITableViewDataSource,
8319 UITableViewDelegate
8320 > {
8321 _transient Database *database_;
8322 unsigned era_;
8323
8324 _H<UITableView, 2> list_;
8325 _H<NSMutableArray> sources_;
8326 int offset_;
8327
8328 _H<NSString> href_;
8329 _H<UIProgressHUD> hud_;
8330 _H<NSError> error_;
8331
8332 NSURLConnection *trivial_bz2_;
8333 NSURLConnection *trivial_gz_;
8334
8335 BOOL cydia_;
8336 }
8337
8338 - (id) initWithDatabase:(Database *)database;
8339 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8340
8341 @end
8342
8343 @implementation SourcesController
8344
8345 - (void) _releaseConnection:(NSURLConnection *)connection {
8346 if (connection != nil) {
8347 [connection cancel];
8348 //[connection setDelegate:nil];
8349 [connection release];
8350 }
8351 }
8352
8353 - (void) dealloc {
8354 [self _releaseConnection:trivial_gz_];
8355 [self _releaseConnection:trivial_bz2_];
8356
8357 [super dealloc];
8358 }
8359
8360 - (NSURL *) navigationURL {
8361 return [NSURL URLWithString:@"cydia://sources"];
8362 }
8363
8364 - (void) viewDidAppear:(BOOL)animated {
8365 [super viewDidAppear:animated];
8366 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8367 }
8368
8369 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8370 return 2;
8371 }
8372
8373 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8374 if (section == 1)
8375 return UCLocalize("INDIVIDUAL_SOURCES");
8376 return nil;
8377 }
8378
8379 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8380 switch (section) {
8381 case 0: return 1;
8382 case 1: return [sources_ count];
8383 default: return 0;
8384 }
8385 }
8386
8387 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8388 @synchronized (database_) {
8389 if ([database_ era] != era_)
8390 return nil;
8391 if ([indexPath section] != 1)
8392 return nil;
8393 NSUInteger index([indexPath row]);
8394 if (index >= [sources_ count])
8395 return nil;
8396 return [sources_ objectAtIndex:index];
8397 } }
8398
8399 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8400 static NSString *cellIdentifier = @"SourceCell";
8401
8402 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8403 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8404 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8405
8406 Source *source([self sourceAtIndexPath:indexPath]);
8407 if (source == nil)
8408 [cell setAllSource];
8409 else
8410 [cell setSource:source];
8411
8412 return cell;
8413 }
8414
8415 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8416 SectionsController *controller([[[SectionsController alloc]
8417 initWithDatabase:database_
8418 source:[self sourceAtIndexPath:indexPath]
8419 ] autorelease]);
8420
8421 [controller setDelegate:delegate_];
8422 [[self navigationController] pushViewController:controller animated:YES];
8423 }
8424
8425 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8426 if ([indexPath section] != 1)
8427 return false;
8428 Source *source = [self sourceAtIndexPath:indexPath];
8429 return [source record] != nil;
8430 }
8431
8432 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8433 _assert([indexPath section] == 1);
8434 if (editingStyle == UITableViewCellEditingStyleDelete) {
8435 Source *source = [self sourceAtIndexPath:indexPath];
8436 if (source == nil) return;
8437
8438 [Sources_ removeObjectForKey:[source key]];
8439 Changed_ = true;
8440
8441 [delegate_ _saveConfig];
8442 [delegate_ reloadDataWithInvocation:nil];
8443 }
8444 }
8445
8446 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8447 [self updateButtonsForEditingStatusAnimated:YES];
8448 }
8449
8450 - (void) complete {
8451 [delegate_ addTrivialSource:href_];
8452 href_ = nil;
8453
8454 [delegate_ syncData];
8455 }
8456
8457 - (NSString *) getWarning {
8458 NSString *href(href_);
8459 NSRange colon([href rangeOfString:@"://"]);
8460 if (colon.location != NSNotFound)
8461 href = [href substringFromIndex:(colon.location + 3)];
8462 href = [href stringByAddingPercentEscapes];
8463 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8464
8465 NSURL *url([NSURL URLWithString:href]);
8466
8467 NSStringEncoding encoding;
8468 NSError *error(nil);
8469
8470 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8471 return [warning length] == 0 ? nil : warning;
8472 return nil;
8473 }
8474
8475 - (void) _endConnection:(NSURLConnection *)connection {
8476 // XXX: the memory management in this method is horribly awkward
8477
8478 NSURLConnection **field = NULL;
8479 if (connection == trivial_bz2_)
8480 field = &trivial_bz2_;
8481 else if (connection == trivial_gz_)
8482 field = &trivial_gz_;
8483 _assert(field != NULL);
8484 [connection release];
8485 *field = nil;
8486
8487 if (
8488 trivial_bz2_ == nil &&
8489 trivial_gz_ == nil
8490 ) {
8491 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8492
8493 [delegate_ releaseNetworkActivityIndicator];
8494
8495 [delegate_ removeProgressHUD:hud_];
8496 hud_ = nil;
8497
8498 if (cydia_) {
8499 if (warning != nil) {
8500 UIAlertView *alert = [[[UIAlertView alloc]
8501 initWithTitle:UCLocalize("SOURCE_WARNING")
8502 message:warning
8503 delegate:self
8504 cancelButtonTitle:UCLocalize("CANCEL")
8505 otherButtonTitles:
8506 UCLocalize("ADD_ANYWAY"),
8507 nil
8508 ] autorelease];
8509
8510 [alert setContext:@"warning"];
8511 [alert setNumberOfRows:1];
8512 [alert show];
8513
8514 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8515 error_ = nil;
8516 return;
8517 }
8518
8519 [self complete];
8520 } else if (error_ != nil) {
8521 UIAlertView *alert = [[[UIAlertView alloc]
8522 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8523 message:[error_ localizedDescription]
8524 delegate:self
8525 cancelButtonTitle:UCLocalize("OK")
8526 otherButtonTitles:nil
8527 ] autorelease];
8528
8529 [alert setContext:@"urlerror"];
8530 [alert show];
8531
8532 href_ = nil;
8533 } else {
8534 UIAlertView *alert = [[[UIAlertView alloc]
8535 initWithTitle:UCLocalize("NOT_REPOSITORY")
8536 message:UCLocalize("NOT_REPOSITORY_EX")
8537 delegate:self
8538 cancelButtonTitle:UCLocalize("OK")
8539 otherButtonTitles:nil
8540 ] autorelease];
8541
8542 [alert setContext:@"trivial"];
8543 [alert show];
8544
8545 href_ = nil;
8546 }
8547
8548 error_ = nil;
8549 }
8550 }
8551
8552 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8553 switch ([response statusCode]) {
8554 case 200:
8555 cydia_ = YES;
8556 }
8557 }
8558
8559 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8560 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8561 error_ = error;
8562 [self _endConnection:connection];
8563 }
8564
8565 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8566 [self _endConnection:connection];
8567 }
8568
8569 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8570 NSURL *url([NSURL URLWithString:href]);
8571
8572 NSMutableURLRequest *request = [NSMutableURLRequest
8573 requestWithURL:url
8574 cachePolicy:NSURLRequestUseProtocolCachePolicy
8575 timeoutInterval:10
8576 ];
8577
8578 [request setHTTPMethod:method];
8579
8580 if (Machine_ != NULL)
8581 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8582
8583 if (UniqueID_ != nil)
8584 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8585
8586 if ([url isCydiaSecure]) {
8587 if (UniqueID_ != nil)
8588 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8589 }
8590
8591 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8592 }
8593
8594 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8595 NSString *context([alert context]);
8596
8597 if ([context isEqualToString:@"source"]) {
8598 switch (button) {
8599 case 1: {
8600 NSString *href = [[alert textField] text];
8601
8602 static Pcre href_r("^http(s?)://[^# ]*$");
8603 if (!href_r(href)) {
8604 UIAlertView *alert = [[[UIAlertView alloc]
8605 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8606 message:UCLocalize("INVALID_URL_EX")
8607 delegate:self
8608 cancelButtonTitle:UCLocalize("OK")
8609 otherButtonTitles:nil
8610 ] autorelease];
8611
8612 [alert setContext:@"badurl"];
8613 [alert show];
8614
8615 break;
8616 }
8617
8618 if (![href hasSuffix:@"/"])
8619 href_ = [href stringByAppendingString:@"/"];
8620 else
8621 href_ = href;
8622
8623 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8624 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8625
8626 cydia_ = false;
8627
8628 // XXX: this is stupid
8629 hud_ = [delegate_ addProgressHUD];
8630 [hud_ setText:UCLocalize("VERIFYING_URL")];
8631 [delegate_ retainNetworkActivityIndicator];
8632 } break;
8633
8634 case 0:
8635 break;
8636
8637 _nodefault
8638 }
8639
8640 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8641 } else if ([context isEqualToString:@"trivial"])
8642 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8643 else if ([context isEqualToString:@"urlerror"])
8644 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8645 else if ([context isEqualToString:@"warning"]) {
8646 switch (button) {
8647 case 1:
8648 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8649 break;
8650
8651 case 0:
8652 break;
8653
8654 _nodefault
8655 }
8656
8657 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8658 }
8659 }
8660
8661 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8662 BOOL editing([list_ isEditing]);
8663
8664 if (editing)
8665 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8666 initWithTitle:UCLocalize("ADD")
8667 style:UIBarButtonItemStylePlain
8668 target:self
8669 action:@selector(addButtonClicked)
8670 ] autorelease] animated:animated];
8671 else if ([delegate_ updating])
8672 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8673 initWithTitle:UCLocalize("CANCEL")
8674 style:UIBarButtonItemStyleDone
8675 target:self
8676 action:@selector(cancelButtonClicked)
8677 ] autorelease] animated:animated];
8678 else
8679 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8680 initWithTitle:UCLocalize("REFRESH")
8681 style:UIBarButtonItemStylePlain
8682 target:self
8683 action:@selector(refreshButtonClicked)
8684 ] autorelease] animated:animated];
8685
8686 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8687 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8688 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8689 target:self
8690 action:@selector(editButtonClicked)
8691 ] autorelease] animated:animated];
8692 }
8693
8694 - (void) loadView {
8695 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8696 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8697 [list_ setRowHeight:53];
8698 [(UITableView *) list_ setDataSource:self];
8699 [list_ setDelegate:self];
8700 [self setView:list_];
8701 }
8702
8703 - (void) viewDidLoad {
8704 [super viewDidLoad];
8705
8706 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8707 [self updateButtonsForEditingStatusAnimated:NO];
8708 }
8709
8710 - (void) viewWillAppear:(BOOL)animated {
8711 [super viewWillAppear:animated];
8712
8713 [list_ setEditing:NO];
8714 [self updateButtonsForEditingStatusAnimated:NO];
8715 }
8716
8717 - (void) releaseSubviews {
8718 list_ = nil;
8719
8720 sources_ = nil;
8721
8722 [super releaseSubviews];
8723 }
8724
8725 - (id) initWithDatabase:(Database *)database {
8726 if ((self = [super init]) != nil) {
8727 database_ = database;
8728 } return self;
8729 }
8730
8731 - (void) reloadData {
8732 [super reloadData];
8733 [self updateButtonsForEditingStatusAnimated:YES];
8734
8735 @synchronized (database_) {
8736 era_ = [database_ era];
8737
8738 sources_ = [NSMutableArray arrayWithCapacity:16];
8739 [sources_ addObjectsFromArray:[database_ sources]];
8740 _trace();
8741 [sources_ sortUsingSelector:@selector(compareByName:)];
8742 _trace();
8743
8744 int count([sources_ count]);
8745 offset_ = 0;
8746 for (int i = 0; i != count; i++) {
8747 if ([[sources_ objectAtIndex:i] record] == nil)
8748 break;
8749 offset_++;
8750 }
8751
8752 [list_ reloadData];
8753 } }
8754
8755 - (void) showAddSourcePrompt {
8756 UIAlertView *alert = [[[UIAlertView alloc]
8757 initWithTitle:UCLocalize("ENTER_APT_URL")
8758 message:nil
8759 delegate:self
8760 cancelButtonTitle:UCLocalize("CANCEL")
8761 otherButtonTitles:
8762 UCLocalize("ADD_SOURCE"),
8763 nil
8764 ] autorelease];
8765
8766 [alert setContext:@"source"];
8767
8768 [alert setNumberOfRows:1];
8769 [alert addTextFieldWithValue:@"http://" label:@""];
8770
8771 UITextInputTraits *traits = [[alert textField] textInputTraits];
8772 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8773 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8774 [traits setKeyboardType:UIKeyboardTypeURL];
8775 // XXX: UIReturnKeyDone
8776 [traits setReturnKeyType:UIReturnKeyNext];
8777
8778 [alert show];
8779 }
8780
8781 - (void) addButtonClicked {
8782 [self showAddSourcePrompt];
8783 }
8784
8785 - (void) refreshButtonClicked {
8786 if ([delegate_ requestUpdate])
8787 [self updateButtonsForEditingStatusAnimated:YES];
8788 }
8789
8790 - (void) cancelButtonClicked {
8791 [delegate_ cancelUpdate];
8792 }
8793
8794 - (void) editButtonClicked {
8795 [list_ setEditing:![list_ isEditing] animated:YES];
8796 [self updateButtonsForEditingStatusAnimated:YES];
8797 }
8798
8799 @end
8800 /* }}} */
8801
8802 /* Stash Controller {{{ */
8803 @interface StashController : CyteViewController {
8804 _H<UIActivityIndicatorView> spinner_;
8805 _H<UILabel> status_;
8806 _H<UILabel> caption_;
8807 }
8808
8809 @end
8810
8811 @implementation StashController
8812
8813 - (void) loadView {
8814 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8815 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8816 [self setView:view];
8817
8818 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8819
8820 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8821 CGRect spinrect = [spinner_ frame];
8822 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8823 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8824 [spinner_ setFrame:spinrect];
8825 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8826 [view addSubview:spinner_];
8827 [spinner_ startAnimating];
8828
8829 CGRect captrect;
8830 captrect.size.width = [[self view] frame].size.width;
8831 captrect.size.height = 40.0f;
8832 captrect.origin.x = 0;
8833 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8834 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8835 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8836 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8837 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8838 [caption_ setTextColor:[UIColor whiteColor]];
8839 [caption_ setBackgroundColor:[UIColor clearColor]];
8840 [caption_ setShadowColor:[UIColor blackColor]];
8841 [caption_ setTextAlignment:NSTextAlignmentCenter];
8842 [view addSubview:caption_];
8843
8844 CGRect statusrect;
8845 statusrect.size.width = [[self view] frame].size.width;
8846 statusrect.size.height = 30.0f;
8847 statusrect.origin.x = 0;
8848 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8849 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8850 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8851 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8852 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8853 [status_ setTextColor:[UIColor whiteColor]];
8854 [status_ setBackgroundColor:[UIColor clearColor]];
8855 [status_ setShadowColor:[UIColor blackColor]];
8856 [status_ setTextAlignment:NSTextAlignmentCenter];
8857 [view addSubview:status_];
8858 }
8859
8860 - (void) releaseSubviews {
8861 spinner_ = nil;
8862 status_ = nil;
8863 caption_ = nil;
8864
8865 [super releaseSubviews];
8866 }
8867
8868 @end
8869 /* }}} */
8870
8871 @interface CYURLCache : SDURLCache {
8872 }
8873
8874 @end
8875
8876 @implementation CYURLCache
8877
8878 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8879 #if !ForRelease
8880 if (false);
8881 else if ([event isEqualToString:@"no-cache"])
8882 event = @"!!!";
8883 else if ([event isEqualToString:@"store"])
8884 event = @">>>";
8885 else if ([event isEqualToString:@"invalid"])
8886 event = @"???";
8887 else if ([event isEqualToString:@"memory"])
8888 event = @"mem";
8889 else if ([event isEqualToString:@"disk"])
8890 event = @"ssd";
8891 else if ([event isEqualToString:@"miss"])
8892 event = @"---";
8893
8894 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8895 #endif
8896 }
8897
8898 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8899 if (NSURLResponse *response = [cached response])
8900 if (NSString *mime = [response MIMEType])
8901 if ([mime isEqualToString:@"text/cache-manifest"]) {
8902 NSURL *url([response URL]);
8903
8904 #if !ForRelease
8905 NSLog(@"###: %@", [url absoluteString]);
8906 #endif
8907
8908 @synchronized (HostConfig_) {
8909 [CachedURLs_ addObject:url];
8910 }
8911 }
8912
8913 [super storeCachedResponse:cached forRequest:request];
8914 }
8915
8916 @end
8917
8918 @interface Cydia : UIApplication <
8919 ConfirmationControllerDelegate,
8920 DatabaseDelegate,
8921 CydiaDelegate
8922 > {
8923 _H<UIWindow> window_;
8924 _H<CydiaTabBarController> tabbar_;
8925 _H<CyteTabBarController> emulated_;
8926
8927 _H<NSMutableArray> essential_;
8928 _H<NSMutableArray> broken_;
8929
8930 Database *database_;
8931
8932 _H<NSURL> starturl_;
8933
8934 unsigned locked_;
8935 unsigned activity_;
8936
8937 _H<StashController> stash_;
8938
8939 bool loaded_;
8940 }
8941
8942 - (void) loadData;
8943
8944 @end
8945
8946 @implementation Cydia
8947
8948 - (void) lockSuspend {
8949 if (locked_++ == 0) {
8950 if ($SBSSetInterceptsMenuButtonForever != NULL)
8951 (*$SBSSetInterceptsMenuButtonForever)(true);
8952
8953 [self setIdleTimerDisabled:YES];
8954 }
8955 }
8956
8957 - (void) unlockSuspend {
8958 if (--locked_ == 0) {
8959 [self setIdleTimerDisabled:NO];
8960
8961 if ($SBSSetInterceptsMenuButtonForever != NULL)
8962 (*$SBSSetInterceptsMenuButtonForever)(false);
8963 }
8964 }
8965
8966 - (void) beginUpdate {
8967 [tabbar_ beginUpdate];
8968 }
8969
8970 - (void) cancelUpdate {
8971 [tabbar_ cancelUpdate];
8972 }
8973
8974 - (bool) requestUpdate {
8975 if (IsReachable("cydia.saurik.com")) {
8976 [self beginUpdate];
8977 return true;
8978 } else {
8979 UIAlertView *alert = [[[UIAlertView alloc]
8980 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8981 message:@"Host Unreachable" // XXX: Localize
8982 delegate:self
8983 cancelButtonTitle:UCLocalize("OK")
8984 otherButtonTitles:nil
8985 ] autorelease];
8986
8987 [alert setContext:@"norefresh"];
8988 [alert show];
8989
8990 return false;
8991 }
8992 }
8993
8994 - (BOOL) updating {
8995 return [tabbar_ updating];
8996 }
8997
8998 - (void) _loaded {
8999 if ([broken_ count] != 0) {
9000 int count = [broken_ count];
9001
9002 UIAlertView *alert = [[[UIAlertView alloc]
9003 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9004 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9005 delegate:self
9006 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9007 otherButtonTitles:
9008 UCLocalize("TEMPORARY_IGNORE"),
9009 nil
9010 ] autorelease];
9011
9012 [alert setContext:@"fixhalf"];
9013 [alert setNumberOfRows:2];
9014 [alert show];
9015 } else if (!Ignored_ && [essential_ count] != 0) {
9016 int count = [essential_ count];
9017
9018 UIAlertView *alert = [[[UIAlertView alloc]
9019 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9020 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9021 delegate:self
9022 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9023 otherButtonTitles:
9024 UCLocalize("UPGRADE_ESSENTIAL"),
9025 UCLocalize("COMPLETE_UPGRADE"),
9026 nil
9027 ] autorelease];
9028
9029 [alert setContext:@"upgrade"];
9030 [alert show];
9031 }
9032 }
9033
9034 - (void) returnToCydia {
9035 [self _loaded];
9036 }
9037
9038 - (void) _saveConfig {
9039 @synchronized (database_) {
9040 _trace();
9041 MetaFile_.Sync();
9042 _trace();
9043 }
9044
9045 if (Changed_) {
9046 NSString *error(nil);
9047
9048 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9049 _trace();
9050 NSError *error(nil);
9051 _root(true) if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9052 NSLog(@"failure to save metadata data: %@", error);
9053 _trace();
9054
9055 Changed_ = false;
9056 } else {
9057 NSLog(@"failure to serialize metadata: %@", error);
9058 }
9059 }
9060
9061 CydiaWriteSources();
9062 }
9063
9064 // Navigation controller for the queuing badge.
9065 - (UINavigationController *) queueNavigationController {
9066 NSArray *controllers = [tabbar_ viewControllers];
9067 return [controllers objectAtIndex:3];
9068 }
9069
9070 - (void) unloadData {
9071 [tabbar_ unloadData];
9072 }
9073
9074 - (void) _updateData {
9075 [self _saveConfig];
9076 [self unloadData];
9077
9078 UINavigationController *navigation = [self queueNavigationController];
9079
9080 id queuedelegate = nil;
9081 if ([[navigation viewControllers] count] > 0)
9082 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9083
9084 [queuedelegate queueStatusDidChange];
9085 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9086 }
9087
9088 - (void) _refreshIfPossible:(NSDate *)update {
9089 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9090
9091 bool recently = false;
9092 if (update != nil) {
9093 NSTimeInterval interval([update timeIntervalSinceNow]);
9094 if (interval <= 0 && interval > -(15*60))
9095 recently = true;
9096 }
9097
9098 // Don't automatic refresh if:
9099 // - We already refreshed recently.
9100 // - We already auto-refreshed this launch.
9101 // - Auto-refresh is disabled.
9102 // - Cydia's server is not reachable
9103 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9104 // If we are cancelling, we need to make sure it knows it's already loaded.
9105 loaded_ = true;
9106
9107 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9108 } else {
9109 // We are going to load, so remember that.
9110 loaded_ = true;
9111
9112 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9113 }
9114
9115 [pool release];
9116 }
9117
9118 - (void) refreshIfPossible {
9119 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9120 }
9121
9122 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9123 _profile(reloadDataWithInvocation)
9124 @synchronized (self) {
9125 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9126 if (hud != nil)
9127 [hud setText:UCLocalize("RELOADING_DATA")];
9128
9129 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9130
9131 size_t changes(0);
9132
9133 [essential_ removeAllObjects];
9134 [broken_ removeAllObjects];
9135
9136 _profile(reloadDataWithInvocation$Essential)
9137 NSArray *packages([database_ packages]);
9138 for (Package *package in packages) {
9139 if ([package half])
9140 [broken_ addObject:package];
9141 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9142 if ([package essential] && [package installed] != nil)
9143 [essential_ addObject:package];
9144 ++changes;
9145 }
9146 }
9147 _end
9148
9149 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9150 if (changes != 0) {
9151 _trace();
9152 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9153 [changesItem setBadgeValue:badge];
9154 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9155 [self setApplicationIconBadgeNumber:changes];
9156 } else {
9157 _trace();
9158 [changesItem setBadgeValue:nil];
9159 [changesItem setAnimatedBadge:NO];
9160 [self setApplicationIconBadgeNumber:0];
9161 }
9162
9163 [self _updateData];
9164
9165 if (hud != nil)
9166 [self removeProgressHUD:hud];
9167 }
9168 _end
9169
9170 PrintTimes();
9171 }
9172
9173 - (void) updateData {
9174 [self _updateData];
9175 }
9176
9177 - (void) updateDataAndLoad {
9178 [self _updateData];
9179 if ([database_ progressDelegate] == nil)
9180 [self _loaded];
9181 }
9182
9183 - (void) update_ {
9184 [database_ update];
9185 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9186 }
9187
9188 - (void) disemulate {
9189 if (emulated_ == nil)
9190 return;
9191
9192 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9193 [window_ setRootViewController:tabbar_];
9194 else {
9195 [window_ addSubview:[tabbar_ view]];
9196 [[emulated_ view] removeFromSuperview];
9197 }
9198
9199 emulated_ = nil;
9200 [window_ setUserInteractionEnabled:YES];
9201 }
9202
9203 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9204 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9205 if (IsWildcat_)
9206 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9207
9208 UIViewController *parent;
9209 if (emulated_ == nil)
9210 parent = tabbar_;
9211 else if (!force)
9212 parent = emulated_;
9213 else {
9214 [self disemulate];
9215 parent = tabbar_;
9216 }
9217
9218 [parent presentModalViewController:navigation animated:YES];
9219 }
9220
9221 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9222 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9223
9224 if (navigation != nil)
9225 [navigation pushViewController:progress animated:YES];
9226 else
9227 [self presentModalViewController:progress force:YES];
9228
9229 [progress invoke:invocation withTitle:title];
9230 return progress;
9231 }
9232
9233 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9234 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9235 }
9236
9237 - (void) repairWithInvocation:(NSInvocation *)invocation {
9238 _trace();
9239 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9240 _trace();
9241 }
9242
9243 - (void) repairWithSelector:(SEL)selector {
9244 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9245 }
9246
9247 - (void) reloadData {
9248 [self reloadDataWithInvocation:nil];
9249 if ([database_ progressDelegate] == nil)
9250 [self _loaded];
9251 }
9252
9253 - (void) syncData {
9254 [self _saveConfig];
9255 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9256 }
9257
9258 - (void) addSource:(NSDictionary *) source {
9259 CydiaAddSource(source);
9260 }
9261
9262 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9263 CydiaAddSource(href, distribution, sections);
9264 }
9265
9266 - (void) addTrivialSource:(NSString *)href {
9267 CydiaAddSource(href, @"./");
9268 }
9269
9270 - (void) updateValues {
9271 Changed_ = true;
9272 }
9273
9274 - (void) resolve {
9275 pkgProblemResolver *resolver = [database_ resolver];
9276
9277 resolver->InstallProtect();
9278 if (!resolver->Resolve(true))
9279 _error->Discard();
9280 }
9281
9282 - (bool) perform {
9283 // XXX: this is a really crappy way of doing this.
9284 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9285 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9286 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9287 if ([tabbar_ updating])
9288 [tabbar_ cancelUpdate];
9289
9290 if (![database_ prepare])
9291 return false;
9292
9293 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9294 [page setDelegate:self];
9295 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9296
9297 if (IsWildcat_)
9298 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9299 [tabbar_ presentModalViewController:confirm_ animated:YES];
9300
9301 return true;
9302 }
9303
9304 - (void) queue {
9305 @synchronized (self) {
9306 [self perform];
9307 }
9308 }
9309
9310 - (void) clearPackage:(Package *)package {
9311 @synchronized (self) {
9312 [package clear];
9313 [self resolve];
9314 [self perform];
9315 }
9316 }
9317
9318 - (void) installPackages:(NSArray *)packages {
9319 @synchronized (self) {
9320 for (Package *package in packages)
9321 [package install];
9322 [self resolve];
9323 [self perform];
9324 }
9325 }
9326
9327 - (void) installPackage:(Package *)package {
9328 @synchronized (self) {
9329 [package install];
9330 [self resolve];
9331 [self perform];
9332 }
9333 }
9334
9335 - (void) removePackage:(Package *)package {
9336 @synchronized (self) {
9337 [package remove];
9338 [self resolve];
9339 [self perform];
9340 }
9341 }
9342
9343 - (void) distUpgrade {
9344 @synchronized (self) {
9345 if (![database_ upgrade])
9346 return;
9347 [self perform];
9348 }
9349 }
9350
9351 - (void) _uicache {
9352 _trace();
9353 system("/usr/bin/uicache");
9354 _trace();
9355 }
9356
9357 - (void) uicache {
9358 UIProgressHUD *hud([self addProgressHUD]);
9359 [hud setText:UCLocalize("LOADING")];
9360 [self yieldToSelector:@selector(_uicache)];
9361 [self removeProgressHUD:hud];
9362 }
9363
9364 - (void) perform_ {
9365 [database_ perform];
9366 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9367 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9368 }
9369
9370 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9371 Queuing_ = false;
9372 [self lockSuspend];
9373 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9374 [self unlockSuspend];
9375 }
9376
9377 - (void) retainNetworkActivityIndicator {
9378 if (activity_++ == 0)
9379 [self setNetworkActivityIndicatorVisible:YES];
9380
9381 #if TraceLogging
9382 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9383 #endif
9384 }
9385
9386 - (void) releaseNetworkActivityIndicator {
9387 if (--activity_ == 0)
9388 [self setNetworkActivityIndicatorVisible:NO];
9389
9390 #if TraceLogging
9391 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9392 #endif
9393
9394 }
9395
9396 - (void) cancelAndClear:(bool)clear {
9397 @synchronized (self) {
9398 if (clear) {
9399 [database_ clear];
9400 Queuing_ = false;
9401 } else {
9402 Queuing_ = true;
9403 }
9404
9405 [self _updateData];
9406 }
9407 }
9408
9409 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9410 NSString *context([alert context]);
9411
9412 if ([context isEqualToString:@"conffile"]) {
9413 FILE *input = [database_ input];
9414 if (button == [alert cancelButtonIndex])
9415 fprintf(input, "N\n");
9416 else if (button == [alert firstOtherButtonIndex])
9417 fprintf(input, "Y\n");
9418 fflush(input);
9419
9420 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9421 } else if ([context isEqualToString:@"fixhalf"]) {
9422 if (button == [alert cancelButtonIndex]) {
9423 @synchronized (self) {
9424 _root(false) for (Package *broken in (id) broken_) {
9425 [broken remove];
9426
9427 NSString *id = [broken id];
9428 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9429 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9430 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9431 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9432 }
9433
9434 [self resolve];
9435 [self perform];
9436 }
9437 } else if (button == [alert firstOtherButtonIndex]) {
9438 [broken_ removeAllObjects];
9439 [self _loaded];
9440 }
9441
9442 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9443 } else if ([context isEqualToString:@"upgrade"]) {
9444 if (button == [alert firstOtherButtonIndex]) {
9445 @synchronized (self) {
9446 for (Package *essential in (id) essential_)
9447 [essential install];
9448
9449 [self resolve];
9450 [self perform];
9451 }
9452 } else if (button == [alert firstOtherButtonIndex] + 1) {
9453 [self distUpgrade];
9454 } else if (button == [alert cancelButtonIndex]) {
9455 Ignored_ = YES;
9456 }
9457
9458 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9459 }
9460 }
9461
9462 - (void) system:(NSString *)command {
9463 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9464
9465 _trace();
9466 system([command UTF8String]);
9467 _trace();
9468
9469 [pool release];
9470 }
9471
9472 - (void) applicationWillSuspend {
9473 [database_ clean];
9474 [super applicationWillSuspend];
9475 }
9476
9477 - (BOOL) isSafeToSuspend {
9478 if (locked_ != 0) {
9479 #if !ForRelease
9480 NSLog(@"isSafeToSuspend: locked_ != 0");
9481 #endif
9482 return false;
9483 }
9484
9485 if ([tabbar_ modalViewController] != nil)
9486 return false;
9487
9488 // Use external process status API internally.
9489 // This is probably a really bad idea.
9490 // XXX: what is the point of this? does this solve anything at all?
9491 uint64_t status = 0;
9492 int notify_token;
9493 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9494 notify_get_state(notify_token, &status);
9495 notify_cancel(notify_token);
9496 }
9497
9498 if (status != 0) {
9499 #if !ForRelease
9500 NSLog(@"isSafeToSuspend: status != 0");
9501 #endif
9502 return false;
9503 }
9504
9505 #if !ForRelease
9506 NSLog(@"isSafeToSuspend: -> true");
9507 #endif
9508 return true;
9509 }
9510
9511 - (void) applicationSuspend:(__GSEvent *)event {
9512 if ([self isSafeToSuspend])
9513 [super applicationSuspend:event];
9514 }
9515
9516 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9517 if ([self isSafeToSuspend])
9518 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9519 }
9520
9521 - (void) _setSuspended:(BOOL)value {
9522 if ([self isSafeToSuspend])
9523 [super _setSuspended:value];
9524 }
9525
9526 - (UIProgressHUD *) addProgressHUD {
9527 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9528 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9529
9530 [window_ setUserInteractionEnabled:NO];
9531
9532 UIViewController *target(tabbar_);
9533 if (UIViewController *modal = [target modalViewController])
9534 target = modal;
9535
9536 [hud showInView:[target view]];
9537
9538 [self lockSuspend];
9539 return hud;
9540 }
9541
9542 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9543 [self unlockSuspend];
9544 [hud hide];
9545 [hud removeFromSuperview];
9546 [window_ setUserInteractionEnabled:YES];
9547 }
9548
9549 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9550 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9551 }
9552
9553 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9554 NSString *scheme([[url scheme] lowercaseString]);
9555 if ([[url absoluteString] length] <= [scheme length] + 3)
9556 return nil;
9557 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9558 NSArray *components([path componentsSeparatedByString:@"/"]);
9559
9560 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9561 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9562 if (controller != nil)
9563 [controller setDelegate:self];
9564 return controller;
9565 }
9566
9567 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9568 return nil;
9569
9570 NSString *base([components objectAtIndex:0]);
9571
9572 CyteViewController *controller = nil;
9573
9574 if ([base isEqualToString:@"url"]) {
9575 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9576 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9577 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9578 } else if (!external && [components count] == 1) {
9579 if ([base isEqualToString:@"sources"]) {
9580 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9581 }
9582
9583 if ([base isEqualToString:@"home"]) {
9584 controller = [[[HomeController alloc] init] autorelease];
9585 }
9586
9587 if ([base isEqualToString:@"sections"]) {
9588 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9589 }
9590
9591 if ([base isEqualToString:@"search"]) {
9592 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9593 }
9594
9595 if ([base isEqualToString:@"changes"]) {
9596 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9597 }
9598
9599 if ([base isEqualToString:@"installed"]) {
9600 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9601 }
9602 } else if ([components count] == 2) {
9603 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9604
9605 if ([base isEqualToString:@"package"]) {
9606 controller = [self pageForPackage:argument withReferrer:referrer];
9607 }
9608
9609 if (!external && [base isEqualToString:@"search"]) {
9610 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9611 }
9612
9613 if (!external && [base isEqualToString:@"sections"]) {
9614 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9615 argument = nil;
9616 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9617 }
9618
9619 if (!external && [base isEqualToString:@"sources"]) {
9620 if ([argument isEqualToString:@"add"]) {
9621 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9622 [(SourcesController *)controller showAddSourcePrompt];
9623 } else {
9624 Source *source([database_ sourceWithKey:argument]);
9625 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9626 }
9627 }
9628
9629 if (!external && [base isEqualToString:@"launch"]) {
9630 [self launchApplicationWithIdentifier:argument suspended:NO];
9631 return nil;
9632 }
9633 } else if (!external && [components count] == 3) {
9634 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9635 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9636
9637 if ([base isEqualToString:@"package"]) {
9638 if ([arg2 isEqualToString:@"settings"]) {
9639 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9640 } else if ([arg2 isEqualToString:@"files"]) {
9641 if (Package *package = [database_ packageWithName:arg1]) {
9642 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9643 [(FileTable *)controller setPackage:package];
9644 }
9645 }
9646 }
9647
9648 if ([base isEqualToString:@"sections"]) {
9649 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9650 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9651 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9652 }
9653 }
9654
9655 [controller setDelegate:self];
9656 return controller;
9657 }
9658
9659 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9660 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9661
9662 if (page != nil)
9663 [tabbar_ setUnselectedViewController:page];
9664
9665 return page != nil;
9666 }
9667
9668 - (void) applicationOpenURL:(NSURL *)url {
9669 [super applicationOpenURL:url];
9670
9671 if (!loaded_)
9672 starturl_ = url;
9673 else
9674 [self openCydiaURL:url forExternal:YES];
9675 }
9676
9677 - (void) applicationWillResignActive:(UIApplication *)application {
9678 // Stop refreshing if you get a phone call or lock the device.
9679 if ([tabbar_ updating])
9680 [tabbar_ cancelUpdate];
9681
9682 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9683 [super applicationWillResignActive:application];
9684 }
9685
9686 - (void) saveState {
9687 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9688 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9689 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9690 Changed_ = true;
9691
9692 [self _saveConfig];
9693 }
9694
9695 - (void) applicationWillTerminate:(UIApplication *)application {
9696 [self saveState];
9697 }
9698
9699 - (void) setConfigurationData:(NSString *)data {
9700 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9701
9702 if (!conffile_r(data)) {
9703 lprintf("E:invalid conffile\n");
9704 return;
9705 }
9706
9707 NSString *ofile = conffile_r[1];
9708 //NSString *nfile = conffile_r[2];
9709
9710 UIAlertView *alert = [[[UIAlertView alloc]
9711 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9712 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9713 delegate:self
9714 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9715 otherButtonTitles:
9716 UCLocalize("ACCEPT_NEW_COPY"),
9717 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9718 nil
9719 ] autorelease];
9720
9721 [alert setContext:@"conffile"];
9722 [alert setNumberOfRows:2];
9723 [alert show];
9724 }
9725
9726 - (void) addStashController {
9727 [self lockSuspend];
9728 stash_ = [[[StashController alloc] init] autorelease];
9729 [window_ addSubview:[stash_ view]];
9730 }
9731
9732 - (void) removeStashController {
9733 [[stash_ view] removeFromSuperview];
9734 stash_ = nil;
9735 [self unlockSuspend];
9736 }
9737
9738 - (void) stash {
9739 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9740 UpdateExternalStatus(1);
9741 _root(true) [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9742 UpdateExternalStatus(0);
9743
9744 [self removeStashController];
9745
9746 pid_t pid(ExecFork());
9747 if (pid == 0) {
9748 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9749 perror("launchctl stop");
9750
9751 exit(0);
9752 } ReapZombie(pid);
9753 }
9754
9755 - (void) setupViewControllers {
9756 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9757
9758 NSMutableArray *items;
9759 if (kCFCoreFoundationVersionNumber < 800) {
9760 items = [NSMutableArray arrayWithObjects:
9761 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9762 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9763 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9764 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9765 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9766 nil];
9767 } else {
9768 items = [NSMutableArray arrayWithObjects:
9769 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9770 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9771 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9772 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9773 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9774 nil];
9775 }
9776
9777 NSMutableArray *controllers([NSMutableArray array]);
9778 for (UITabBarItem *item in items) {
9779 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9780 [controller setTabBarItem:item];
9781 [controllers addObject:controller];
9782 }
9783 [tabbar_ setViewControllers:controllers];
9784
9785 [tabbar_ setUpdateDelegate:self];
9786 }
9787
9788 - (void) _sendMemoryWarningNotification {
9789 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9790 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9791 else
9792 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9793 }
9794
9795 - (void) _sendMemoryWarningNotifications {
9796 while (true) {
9797 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9798 sleep(2);
9799 //usleep(2000000);
9800 }
9801 }
9802
9803 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9804 NSLog(@"--");
9805 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9806 }
9807
9808 - (void) applicationDidFinishLaunching:(id)unused {
9809 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9810
9811 _trace();
9812 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9813 [self setApplicationSupportsShakeToEdit:NO];
9814
9815 @synchronized (HostConfig_) {
9816 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9817 }
9818
9819 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9820 initWithMemoryCapacity:524288
9821 diskCapacity:10485760
9822 diskPath:Cache("SDURLCache")
9823 ] autorelease]];
9824
9825 [CydiaWebViewController _initialize];
9826
9827 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9828
9829 // this would disallow http{,s} URLs from accessing this data
9830 //[WebView registerURLSchemeAsLocal:@"cydia"];
9831
9832 Font12_ = [UIFont systemFontOfSize:12];
9833 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9834 Font14_ = [UIFont systemFontOfSize:14];
9835 Font18_ = [UIFont systemFontOfSize:18];
9836 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9837 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9838
9839 essential_ = [NSMutableArray arrayWithCapacity:4];
9840 broken_ = [NSMutableArray arrayWithCapacity:4];
9841
9842 // XXX: I really need this thing... like, seriously... I'm sorry
9843 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9844
9845 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9846 [window_ orderFront:self];
9847 [window_ makeKey:self];
9848 [window_ setHidden:NO];
9849
9850 if (false) stash: {
9851 [self addStashController];
9852 // XXX: this would be much cleaner as a yieldToSelector:
9853 // that way the removeStashController could happen right here inline
9854 // we also could no longer require the useless stash_ field anymore
9855 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9856 return;
9857 }
9858
9859 struct stat root;
9860 int error(stat("/", &root));
9861 _assert(error != -1);
9862
9863 #define Stash_(path) do { \
9864 struct stat folder; \
9865 int error(lstat((path), &folder)); \
9866 if (error != -1 && ( \
9867 folder.st_dev == root.st_dev && \
9868 S_ISDIR(folder.st_mode) \
9869 ) || error == -1 && ( \
9870 errno == ENOENT || \
9871 errno == ENOTDIR \
9872 )) goto stash; \
9873 } while (false)
9874
9875 Stash_("/Applications");
9876 Stash_("/Library/Ringtones");
9877 Stash_("/Library/Wallpaper");
9878 //Stash_("/usr/bin");
9879 Stash_("/usr/include");
9880 Stash_("/usr/lib/pam");
9881 Stash_("/usr/share");
9882 //Stash_("/var/lib");
9883
9884 database_ = [Database sharedInstance];
9885 [database_ setDelegate:self];
9886
9887 [window_ setUserInteractionEnabled:NO];
9888 [self setupViewControllers];
9889
9890 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9891 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9892 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9893
9894 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9895 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9896 [emulated_ setSelectedIndex:0];
9897
9898 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9899 [emulated_ concealTabBarSelection];
9900
9901 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9902 [window_ setRootViewController:emulated_];
9903 else
9904 [window_ addSubview:[emulated_ view]];
9905
9906 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9907 _trace();
9908 }
9909
9910 - (NSArray *) defaultStartPages {
9911 NSMutableArray *standard = [NSMutableArray array];
9912 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9913 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9914 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9915 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9916 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9917 return standard;
9918 }
9919
9920 - (void) loadData {
9921 _trace();
9922 if ([emulated_ modalViewController] != nil)
9923 [emulated_ dismissModalViewControllerAnimated:YES];
9924 [window_ setUserInteractionEnabled:NO];
9925
9926 [self reloadDataWithInvocation:nil];
9927 [self refreshIfPossible];
9928 [self disemulate];
9929
9930 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9931 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9932 int standardIndex = 0;
9933 NSArray *standard = [self defaultStartPages];
9934
9935 BOOL valid = YES;
9936
9937 if (saved == nil)
9938 valid = NO;
9939
9940 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9941 if (valid && closed != nil) {
9942 NSTimeInterval interval([closed timeIntervalSinceNow]);
9943 // XXX: Is 30 minutes the optimal time here?
9944 if (interval <= -(30*60))
9945 valid = NO;
9946 }
9947
9948 if (valid && [saved count] != [standard count])
9949 valid = NO;
9950
9951 if (valid) {
9952 for (unsigned int i = 0; i < [standard count]; i++) {
9953 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9954 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9955 // but it's good enough for now.
9956 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9957 valid = NO;
9958 break;
9959 }
9960 }
9961 }
9962
9963 NSArray *items = nil;
9964 if (valid) {
9965 [tabbar_ setSelectedIndex:savedIndex];
9966 items = saved;
9967 } else {
9968 [tabbar_ setSelectedIndex:standardIndex];
9969 items = standard;
9970 }
9971
9972 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9973 NSArray *stack = [items objectAtIndex:tab];
9974 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9975 NSMutableArray *current = [NSMutableArray array];
9976
9977 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9978 NSString *addr = [stack objectAtIndex:nav];
9979 NSURL *url = [NSURL URLWithString:addr];
9980 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9981 if (page != nil)
9982 [current addObject:page];
9983 }
9984
9985 [navigation setViewControllers:current];
9986 }
9987
9988 // (Try to) show the startup URL.
9989 if (starturl_ != nil) {
9990 [self openCydiaURL:starturl_ forExternal:YES];
9991 starturl_ = nil;
9992 }
9993 }
9994
9995 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9996 if (item != nil && IsWildcat_) {
9997 [sheet showFromBarButtonItem:item animated:YES];
9998 } else {
9999 [sheet showInView:window_];
10000 }
10001 }
10002
10003 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10004 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10005 [progress setTitle:task];
10006 [progress addProgressEvent:event];
10007 }
10008
10009 - (void) addProgressEventForTask:(NSArray *)data {
10010 CydiaProgressEvent *event([data objectAtIndex:0]);
10011 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10012 [self addProgressEvent:event forTask:task];
10013 }
10014
10015 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10016 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10017 }
10018
10019 @end
10020
10021 /*IMP alloc_;
10022 id Alloc_(id self, SEL selector) {
10023 id object = alloc_(self, selector);
10024 lprintf("[%s]A-%p\n", self->isa->name, object);
10025 return object;
10026 }*/
10027
10028 /*IMP dealloc_;
10029 id Dealloc_(id self, SEL selector) {
10030 id object = dealloc_(self, selector);
10031 lprintf("[%s]D-%p\n", self->isa->name, object);
10032 return object;
10033 }*/
10034
10035 Class $NSURLConnection;
10036
10037 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10038 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10039
10040 NSURL *url([copy URL]);
10041
10042 NSString *host([url host]);
10043 NSString *scheme([[url scheme] lowercaseString]);
10044
10045 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10046
10047 @synchronized (HostConfig_) {
10048 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10049 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10050 [copy setHTTPShouldUsePipelining:YES];
10051
10052 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10053 if ([control isEqualToString:@"max-age=0"])
10054 if ([CachedURLs_ containsObject:url]) {
10055 #if !ForRelease
10056 NSLog(@"~~~: %@", url);
10057 #endif
10058
10059 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10060
10061 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10062 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10063 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10064 }
10065 }
10066
10067 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10068 } return self;
10069 }
10070
10071 Class $WAKWindow;
10072
10073 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10074 CGSize size([[UIScreen mainScreen] bounds].size);
10075 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10076 if ([$WAKWindow hasLandscapeOrientation])
10077 std::swap(size.width, size.height);*/
10078 return size;
10079 }
10080
10081 Class $NSUserDefaults;
10082
10083 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10084 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10085 return Cache("LocalStorage");
10086 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10087 }
10088
10089 int main(int argc, char *argv[]) {
10090 seteuid(501);
10091
10092 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10093
10094 _trace();
10095
10096 UpdateExternalStatus(0);
10097
10098 UIScreen *screen([UIScreen mainScreen]);
10099 if ([screen respondsToSelector:@selector(scale)])
10100 ScreenScale_ = [screen scale];
10101 else
10102 ScreenScale_ = 1;
10103
10104 UIDevice *device([UIDevice currentDevice]);
10105 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10106 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10107 if (idiom == UIUserInterfaceIdiomPad)
10108 IsWildcat_ = true;
10109 }
10110
10111 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10112
10113 Pcre pattern("^([0-9]+\\.[0-9]+)");
10114
10115 if (pattern([device systemVersion]))
10116 Firmware_ = pattern[1];
10117 if (pattern(Cydia_))
10118 Major_ = pattern[1];
10119
10120 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10121
10122 HostConfig_ = [[[NSObject alloc] init] autorelease];
10123 @synchronized (HostConfig_) {
10124 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10125 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10126 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10127 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10128 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10129 }
10130
10131 NSString *ui(@"ui/ios");
10132 if (Idiom_ != nil)
10133 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10134 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10135 UI_ = CydiaURL(ui);
10136
10137 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10138
10139 /* Library Hacks {{{ */
10140 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10141
10142 $WAKWindow = objc_getClass("WAKWindow");
10143 if ($WAKWindow != NULL)
10144 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10145 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10146
10147 $NSURLConnection = objc_getClass("NSURLConnection");
10148 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10149 if (NSURLConnection$init$ != NULL) {
10150 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10151 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10152 }
10153
10154 $NSUserDefaults = objc_getClass("NSUserDefaults");
10155 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10156 if (NSUserDefaults$objectForKey$ != NULL) {
10157 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10158 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10159 }
10160 /* }}} */
10161 /* Set Locale {{{ */
10162 Locale_ = CFLocaleCopyCurrent();
10163 Languages_ = [NSLocale preferredLanguages];
10164
10165 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10166 //NSLog(@"%@", [Languages_ description]);
10167
10168 const char *lang;
10169 if (Locale_ != NULL)
10170 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10171 else if (Languages_ != nil && [Languages_ count] != 0)
10172 lang = [[Languages_ objectAtIndex:0] UTF8String];
10173 else
10174 // XXX: consider just setting to C and then falling through?
10175 lang = NULL;
10176
10177 if (lang != NULL) {
10178 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10179 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10180 }
10181
10182 NSLog(@"Setting Language: %s", lang);
10183
10184 if (lang != NULL) {
10185 setenv("LANG", lang, true);
10186 std::setlocale(LC_ALL, lang);
10187 }
10188 /* }}} */
10189 /* Index Collation {{{ */
10190 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10191 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10192 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10193 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10194 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10195 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10196
10197 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10198
10199 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10200 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10201 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})
10202 CollationOffset_.push_back(offset);
10203 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];
10204 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];
10205 } else {
10206
10207 CollationThumbs_ = [collation sectionIndexTitles];
10208 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10209 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10210
10211 CollationTitles_ = [collation sectionTitles];
10212 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10213
10214 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10215 if (&transform != NULL && transform != nil) {
10216 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10217 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10218 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10219 UErrorCode code(U_ZERO_ERROR);
10220 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10221 if (!U_SUCCESS(code))
10222 NSLog(@"%s", u_errorName(code));
10223 }
10224
10225 }
10226 } @catch (NSException *e) {
10227 NSLog(@"%@", e);
10228 goto hard;
10229 } } else hard: {
10230 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10231
10232 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];
10233 for (NSInteger offset(0); offset != 28; ++offset)
10234 CollationOffset_.push_back(offset);
10235
10236 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];
10237 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];
10238 }
10239 /* }}} */
10240
10241 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10242
10243 /* Parse Arguments {{{ */
10244 bool substrate(false);
10245
10246 if (argc != 0) {
10247 char **args(argv);
10248 int arge(1);
10249
10250 for (int argi(1); argi != argc; ++argi)
10251 if (strcmp(argv[argi], "--") == 0) {
10252 arge = argi;
10253 argv[argi] = argv[0];
10254 argv += argi;
10255 argc -= argi;
10256 break;
10257 }
10258
10259 for (int argi(1); argi != arge; ++argi)
10260 if (strcmp(args[argi], "--substrate") == 0)
10261 substrate = true;
10262 else
10263 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10264 }
10265 /* }}} */
10266
10267 App_ = [[NSBundle mainBundle] bundlePath];
10268 Advanced_ = YES;
10269
10270 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10271
10272 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10273 alloc_ = alloc->method_imp;
10274 alloc->method_imp = (IMP) &Alloc_;*/
10275
10276 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10277 dealloc_ = dealloc->method_imp;
10278 dealloc->method_imp = (IMP) &Dealloc_;*/
10279
10280 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10281 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10282
10283 /* System Information {{{ */
10284 size_t size;
10285
10286 int maxproc;
10287 size = sizeof(maxproc);
10288 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10289 perror("sysctlbyname(\"kern.maxproc\", ?)");
10290 else if (maxproc < 64) {
10291 maxproc = 64;
10292 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10293 perror("sysctlbyname(\"kern.maxproc\", #)");
10294 }
10295
10296 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10297 char *osversion = new char[size];
10298 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10299 perror("sysctlbyname(\"kern.osversion\", ?)");
10300 else
10301 System_ = [NSString stringWithUTF8String:osversion];
10302
10303 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10304 char *machine = new char[size];
10305 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10306 perror("sysctlbyname(\"hw.machine\", ?)");
10307 else
10308 Machine_ = machine;
10309
10310 int64_t usermem(0);
10311 size = sizeof(usermem);
10312 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10313 usermem = 0;
10314
10315 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10316 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10317 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10318
10319 UniqueID_ = UniqueIdentifier(device);
10320
10321 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10322 Product_ = [info objectForKey:@"SafariProductVersion"];
10323 Safari_ = [info objectForKey:@"CFBundleVersion"];
10324 }
10325
10326 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10327
10328 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10329 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10330 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10331 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10332 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10333 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10334
10335 UserAgent_ = agent;
10336 /* }}} */
10337 /* Load Database {{{ */
10338 _trace();
10339 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10340 _trace();
10341 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10342
10343 if (Metadata_ == NULL)
10344 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10345 else {
10346 Settings_ = [Metadata_ objectForKey:@"Settings"];
10347
10348 Packages_ = [Metadata_ objectForKey:@"Packages"];
10349
10350 Values_ = [Metadata_ objectForKey:@"Values"];
10351 Sections_ = [Metadata_ objectForKey:@"Sections"];
10352 Sources_ = [Metadata_ objectForKey:@"Sources"];
10353
10354 Token_ = [Metadata_ objectForKey:@"Token"];
10355
10356 Version_ = [Metadata_ objectForKey:@"Version"];
10357 }
10358
10359 if (Values_ == nil) {
10360 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10361 [Metadata_ setObject:Values_ forKey:@"Values"];
10362 }
10363
10364 if (Sections_ == nil) {
10365 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10366 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10367 }
10368
10369 if (Sources_ == nil) {
10370 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10371 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10372 }
10373
10374 if (Version_ == nil) {
10375 Version_ = [NSNumber numberWithUnsignedInt:0];
10376 [Metadata_ setObject:Version_ forKey:@"Version"];
10377 }
10378
10379 if ([Version_ unsignedIntValue] == 0) {
10380 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10381 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10382 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10383 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10384
10385 Version_ = [NSNumber numberWithUnsignedInt:1];
10386 [Metadata_ setObject:Version_ forKey:@"Version"];
10387
10388 [Metadata_ removeObjectForKey:@"LastUpdate"];
10389
10390 Changed_ = true;
10391 }
10392
10393 _H<NSMutableArray> broken([NSMutableArray array]);
10394 for (NSString *key in (id) Sources_)
10395 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10396 [broken addObject:key];
10397 if ([broken count] != 0) {
10398 for (NSString *key in (id) broken)
10399 [Sources_ removeObjectForKey:key];
10400 Changed_ = true;
10401 } broken = nil;
10402 /* }}} */
10403
10404 CydiaWriteSources();
10405
10406 _trace();
10407 _root(true) MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10408 _trace();
10409
10410 if (Packages_ != nil) {
10411 bool fail(false);
10412 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10413 _trace();
10414
10415 if (!fail) {
10416 [Metadata_ removeObjectForKey:@"Packages"];
10417 Packages_ = nil;
10418 Changed_ = true;
10419 }
10420 }
10421
10422 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10423
10424 #define MobileSubstrate_(name) \
10425 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10426 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10427 if (handle == NULL) \
10428 NSLog(@"%s", dlerror()); \
10429 }
10430
10431 MobileSubstrate_(Activator)
10432 MobileSubstrate_(libstatusbar)
10433 MobileSubstrate_(SimulatedKeyEvents)
10434 MobileSubstrate_(WinterBoard)
10435
10436 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10437 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10438
10439 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10440
10441 _root(true) if (access("/User", F_OK) != 0 || version != 6) {
10442 _trace();
10443 system("/usr/libexec/cydia/firmware.sh");
10444 _trace();
10445 }
10446
10447 if (access("/tmp/cydia.chk", F_OK) == 0) {
10448 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10449 _assert(errno == ENOENT);
10450 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10451 _assert(errno == ENOENT);
10452 }
10453
10454 /* APT Initialization {{{ */
10455 _assert(pkgInitConfig(*_config));
10456 _assert(pkgInitSystem(*_config, _system));
10457
10458 if (lang != NULL)
10459 _config->Set("APT::Acquire::Translation", lang);
10460
10461 // XXX: this timeout might be important :(
10462 //_config->Set("Acquire::http::Timeout", 15);
10463
10464 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10465
10466 mkdir([Cache_ UTF8String], 0755);
10467 mkdir([Cache("archives") UTF8String], 0755);
10468 mkdir([Cache("archives/partial") UTF8String], 0755);
10469 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10470
10471 mkdir([Cache("lists") UTF8String], 0755);
10472 mkdir([Cache("lists/partial") UTF8String], 0755);
10473 mkdir([Cache("periodic") UTF8String], 0755);
10474 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10475 /* }}} */
10476 /* Color Choices {{{ */
10477 space_ = CGColorSpaceCreateDeviceRGB();
10478
10479 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10480 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10481 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10482 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10483 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10484 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10485 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10486 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10487 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10488 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10489
10490 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10491 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10492 /* }}}*/
10493 /* UIKit Configuration {{{ */
10494 // XXX: I have a feeling this was important
10495 //UIKeyboardDisableAutomaticAppearance();
10496 /* }}} */
10497
10498 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10499
10500 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10501 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10502 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10503
10504 PulseInterval_ = fast ? 50000 : 500000;
10505
10506 Colon_ = UCLocalize("COLON_DELIMITED");
10507 Elision_ = UCLocalize("ELISION");
10508 Error_ = UCLocalize("ERROR");
10509 Warning_ = UCLocalize("WARNING");
10510
10511 _trace();
10512 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10513
10514 CGColorSpaceRelease(space_);
10515 CFRelease(Locale_);
10516
10517 [pool release];
10518 return value;
10519 }