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