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