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