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