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