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