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