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