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