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