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