]> git.saurik.com Git - cydia.git/blame_incremental - MobileCydia.mm
On 64-bit some of these floats are really CGFloat.
[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#include <WebKit/DOMHTMLIFrameElement.h>
57
58#include <algorithm>
59#include <fstream>
60#include <iomanip>
61#include <set>
62#include <sstream>
63#include <string>
64
65#include "fdstream.hpp"
66
67#undef ABS
68
69#include "apt.h"
70#include <apt-pkg/acquire.h>
71#include <apt-pkg/acquire-item.h>
72#include <apt-pkg/algorithms.h>
73#include <apt-pkg/cachefile.h>
74#include <apt-pkg/clean.h>
75#include <apt-pkg/configuration.h>
76#include <apt-pkg/debindexfile.h>
77#include <apt-pkg/debmetaindex.h>
78#include <apt-pkg/error.h>
79#include <apt-pkg/init.h>
80#include <apt-pkg/mmap.h>
81#include <apt-pkg/pkgrecords.h>
82#include <apt-pkg/sha1.h>
83#include <apt-pkg/sourcelist.h>
84#include <apt-pkg/sptr.h>
85#include <apt-pkg/strutl.h>
86#include <apt-pkg/tagfile.h>
87
88#include <sys/types.h>
89#include <sys/stat.h>
90#include <sys/sysctl.h>
91#include <sys/param.h>
92#include <sys/mount.h>
93#include <sys/reboot.h>
94
95#include <dirent.h>
96#include <fcntl.h>
97#include <notify.h>
98#include <dlfcn.h>
99
100extern "C" {
101#include <mach-o/nlist.h>
102}
103
104#include <cstdio>
105#include <cstdlib>
106#include <cstring>
107
108#include <errno.h>
109
110#include <Cytore.hpp>
111#include "Sources.h"
112
113#include "Substrate.hpp"
114#include "Menes/Menes.h"
115
116#include "CyteKit/IndirectDelegate.h"
117#include "CyteKit/RegEx.hpp"
118#include "CyteKit/TableViewCell.h"
119#include "CyteKit/TabBarController.h"
120#include "CyteKit/WebScriptObject-Cyte.h"
121#include "CyteKit/WebViewController.h"
122#include "CyteKit/WebViewTableViewCell.h"
123#include "CyteKit/stringWithUTF8Bytes.h"
124
125#include "Cydia/MIMEAddress.h"
126#include "Cydia/LoadingViewController.h"
127#include "Cydia/ProgressEvent.h"
128
129#include "SDURLCache/SDURLCache.h"
130/* }}} */
131
132/* Profiler {{{ */
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:(IndirectDelegate *)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:(IndirectDelegate *)indirect {
4362 if ((self = [super init]) != nil) {
4363 indirect_ = (CyteWebViewController *) 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 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4983}
4984
4985+ (void) _initialize {
4986 [super _initialize];
4987
4988 Diversions_ = [NSMutableSet setWithCapacity:0];
4989}
4990
4991+ (void) addDiversion:(Diversion *)diversion {
4992 [Diversions_ addObject:diversion];
4993}
4994
4995- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4996 [super webView:view didClearWindowObject:window forFrame:frame];
4997 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4998}
4999
5000+ (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
5001 WebDataSource *source([frame dataSource]);
5002 NSURLResponse *response([source response]);
5003 NSURL *url([response URL]);
5004 NSString *scheme([[url scheme] lowercaseString]);
5005
5006 bool bridged(false);
5007
5008 @synchronized (HostConfig_) {
5009 if ([scheme isEqualToString:@"file"])
5010 bridged = true;
5011 else if ([scheme isEqualToString:@"https"])
5012 if ([BridgedHosts_ containsObject:[url host]])
5013 bridged = true;
5014 }
5015
5016 if (bridged)
5017 [window setValue:cydia forKey:@"cydia"];
5018}
5019
5020- (void) _setupMail:(MFMailComposeViewController *)controller {
5021 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5022
5023 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5024 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5025}
5026
5027- (NSURL *) URLWithURL:(NSURL *)url {
5028 return [Diversion divertURL:url];
5029}
5030
5031- (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5032 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5033}
5034
5035- (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5036 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5037}
5038
5039+ (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5040 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5041
5042 NSURL *url([copy URL]);
5043 NSString *href([url absoluteString]);
5044 NSString *host([url host]);
5045
5046 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5047 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5048 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5049 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5050 }
5051
5052 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5053 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5054
5055 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5056 return copy;
5057 }
5058
5059 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5060 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5061 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5062 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5063
5064 bool bridged; @synchronized (HostConfig_) {
5065 bridged = [BridgedHosts_ containsObject:host];
5066 }
5067
5068 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5069 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5070
5071 return copy;
5072}
5073
5074- (void) setDelegate:(id)delegate {
5075 [super setDelegate:delegate];
5076 [cydia_ setDelegate:delegate];
5077}
5078
5079- (NSString *) applicationNameForUserAgent {
5080 return UserAgent_;
5081}
5082
5083- (id) init {
5084 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5085 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5086 } return self;
5087}
5088
5089@end
5090
5091@interface AppCacheController : CydiaWebViewController {
5092}
5093
5094@end
5095
5096@implementation AppCacheController
5097
5098- (void) didReceiveMemoryWarning {
5099 // XXX: this doesn't work
5100}
5101
5102- (bool) retainsNetworkActivityIndicator {
5103 return false;
5104}
5105
5106@end
5107/* }}} */
5108
5109// CydiaScript {{{
5110@interface NSObject (CydiaScript)
5111- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5112@end
5113
5114@implementation NSObject (CydiaScript)
5115
5116- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5117 return self;
5118}
5119
5120@end
5121
5122@implementation NSArray (CydiaScript)
5123
5124- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5125 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5126 for (size_t i(0), e([self count]); i != e; ++i)
5127 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5128 return object;
5129}
5130
5131@end
5132
5133@implementation NSDictionary (CydiaScript)
5134
5135- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5136 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5137 for (id i in self)
5138 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5139 return object;
5140}
5141
5142@end
5143// }}}
5144
5145/* Confirmation Controller {{{ */
5146bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5147 if (!iterator.end())
5148 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5149 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5150 continue;
5151 pkgCache::PkgIterator package(dep.TargetPkg());
5152 if (package.end())
5153 continue;
5154 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5155 return true;
5156 }
5157
5158 return false;
5159}
5160
5161@protocol ConfirmationControllerDelegate
5162- (void) cancelAndClear:(bool)clear;
5163- (void) confirmWithNavigationController:(UINavigationController *)navigation;
5164- (void) queue;
5165@end
5166
5167@interface ConfirmationController : CydiaWebViewController {
5168 _transient Database *database_;
5169
5170 _H<UIAlertView> essential_;
5171
5172 _H<NSDictionary> changes_;
5173 _H<NSMutableArray> issues_;
5174 _H<NSDictionary> sizes_;
5175
5176 BOOL substrate_;
5177}
5178
5179- (id) initWithDatabase:(Database *)database;
5180
5181@end
5182
5183@implementation ConfirmationController
5184
5185- (void) complete {
5186 if (substrate_)
5187 RestartSubstrate_ = true;
5188 [delegate_ confirmWithNavigationController:[self navigationController]];
5189}
5190
5191- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5192 NSString *context([alert context]);
5193
5194 if ([context isEqualToString:@"remove"]) {
5195 if (button == [alert cancelButtonIndex])
5196 [self _doContinue];
5197 else if (button == [alert firstOtherButtonIndex]) {
5198 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5199 }
5200
5201 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5202 } else if ([context isEqualToString:@"unable"]) {
5203 [self dismissModalViewControllerAnimated:YES];
5204 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5205 } else {
5206 [super alertView:alert clickedButtonAtIndex:button];
5207 }
5208}
5209
5210- (void) _doContinue {
5211 [delegate_ cancelAndClear:NO];
5212 [self dismissModalViewControllerAnimated:YES];
5213}
5214
5215- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5216 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5217 return nil;
5218}
5219
5220- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5221 [super webView:view didClearWindowObject:window forFrame:frame];
5222
5223 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5224 (id) changes_, @"changes",
5225 (id) issues_, @"issues",
5226 (id) sizes_, @"sizes",
5227 self, @"queue",
5228 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5229}
5230
5231- (id) initWithDatabase:(Database *)database {
5232 if ((self = [super init]) != nil) {
5233 database_ = database;
5234
5235 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5236 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5237 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5238 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5239 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5240
5241 bool remove(false);
5242
5243 pkgCacheFile &cache([database_ cache]);
5244 NSArray *packages([database_ packages]);
5245 pkgDepCache::Policy *policy([database_ policy]);
5246
5247 issues_ = [NSMutableArray arrayWithCapacity:4];
5248
5249 for (Package *package in packages) {
5250 pkgCache::PkgIterator iterator([package iterator]);
5251 NSString *name([package id]);
5252
5253 if ([package broken]) {
5254 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5255
5256 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5257 name, @"package",
5258 reasons, @"reasons",
5259 nil]];
5260
5261 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5262 if (ver.end())
5263 continue;
5264
5265 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5266 pkgCache::DepIterator start;
5267 pkgCache::DepIterator end;
5268 dep.GlobOr(start, end); // ++dep
5269
5270 if (!cache->IsImportantDep(end))
5271 continue;
5272 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5273 continue;
5274
5275 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5276
5277 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5278 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5279 clauses, @"clauses",
5280 nil]];
5281
5282 _forever {
5283 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5284
5285 pkgCache::PkgIterator target(start.TargetPkg());
5286 if (target->ProvidesList != 0)
5287 reason = @"missing";
5288 else {
5289 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5290 if (!ver.end()) {
5291 reason = @"installed";
5292 installed = [NSString stringWithUTF8String:ver.VerStr()];
5293 } else if (!cache[target].CandidateVerIter(cache).end())
5294 reason = @"uninstalled";
5295 else if (target->ProvidesList == 0)
5296 reason = @"uninstallable";
5297 else
5298 reason = @"virtual";
5299 }
5300
5301 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5302 [NSString stringWithUTF8String:start.CompType()], @"operator",
5303 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5304 nil]);
5305
5306 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5307 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5308 version, @"version",
5309 reason, @"reason",
5310 installed, @"installed",
5311 nil]];
5312
5313 // yes, seriously. (wtf?)
5314 if (start == end)
5315 break;
5316 ++start;
5317 }
5318 }
5319 }
5320
5321 pkgDepCache::StateCache &state(cache[iterator]);
5322
5323 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5324
5325 if (state.NewInstall())
5326 [installs addObject:name];
5327 // XXX: else if (state.Install())
5328 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5329 [reinstalls addObject:name];
5330 // XXX: move before previous if
5331 else if (state.Upgrade())
5332 [upgrades addObject:name];
5333 else if (state.Downgrade())
5334 [downgrades addObject:name];
5335 else if (!state.Delete())
5336 // XXX: _assert(state.Keep());
5337 continue;
5338 else if (special_r(name))
5339 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5340 [NSNull null], @"package",
5341 [NSArray arrayWithObjects:
5342 [NSDictionary dictionaryWithObjectsAndKeys:
5343 @"Conflicts", @"relationship",
5344 [NSArray arrayWithObjects:
5345 [NSDictionary dictionaryWithObjectsAndKeys:
5346 name, @"package",
5347 [NSNull null], @"version",
5348 @"installed", @"reason",
5349 nil],
5350 nil], @"clauses",
5351 nil],
5352 nil], @"reasons",
5353 nil]];
5354 else {
5355 if ([package essential])
5356 remove = true;
5357 [removes addObject:name];
5358 }
5359
5360 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5361 substrate_ |= DepSubstrate(iterator.CurrentVer());
5362 }
5363
5364 if (!remove)
5365 essential_ = nil;
5366 else if (Advanced_) {
5367 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5368
5369 essential_ = [[[UIAlertView alloc]
5370 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5371 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5372 delegate:self
5373 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5374 otherButtonTitles:
5375 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5376 nil
5377 ] autorelease];
5378
5379 [essential_ setContext:@"remove"];
5380 [essential_ setNumberOfRows:2];
5381 } else {
5382 essential_ = [[[UIAlertView alloc]
5383 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5384 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5385 delegate:self
5386 cancelButtonTitle:UCLocalize("OKAY")
5387 otherButtonTitles:nil
5388 ] autorelease];
5389
5390 [essential_ setContext:@"unable"];
5391 }
5392
5393 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5394 installs, @"installs",
5395 reinstalls, @"reinstalls",
5396 upgrades, @"upgrades",
5397 downgrades, @"downgrades",
5398 removes, @"removes",
5399 nil];
5400
5401 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5402 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5403 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5404 nil];
5405
5406 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5407 } return self;
5408}
5409
5410- (UIBarButtonItem *) leftButton {
5411 return [[[UIBarButtonItem alloc]
5412 initWithTitle:UCLocalize("CANCEL")
5413 style:UIBarButtonItemStylePlain
5414 target:self
5415 action:@selector(cancelButtonClicked)
5416 ] autorelease];
5417}
5418
5419#if !AlwaysReload
5420- (void) applyRightButton {
5421 if ([issues_ count] == 0 && ![self isLoading])
5422 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5423 initWithTitle:UCLocalize("CONFIRM")
5424 style:UIBarButtonItemStyleDone
5425 target:self
5426 action:@selector(confirmButtonClicked)
5427 ] autorelease]];
5428 else
5429 [[self navigationItem] setRightBarButtonItem:nil];
5430}
5431#endif
5432
5433- (void) cancelButtonClicked {
5434 [delegate_ cancelAndClear:YES];
5435 [self dismissModalViewControllerAnimated:YES];
5436}
5437
5438#if !AlwaysReload
5439- (void) confirmButtonClicked {
5440 if (essential_ != nil)
5441 [essential_ show];
5442 else
5443 [self complete];
5444}
5445#endif
5446
5447@end
5448/* }}} */
5449
5450/* Progress Data {{{ */
5451@interface CydiaProgressData : NSObject {
5452 _transient id delegate_;
5453
5454 bool running_;
5455 float percent_;
5456
5457 float current_;
5458 float total_;
5459 float speed_;
5460
5461 _H<NSMutableArray> events_;
5462 _H<NSString> title_;
5463
5464 _H<NSString> status_;
5465 _H<NSString> finish_;
5466}
5467
5468@end
5469
5470@implementation CydiaProgressData
5471
5472+ (NSArray *) _attributeKeys {
5473 return [NSArray arrayWithObjects:
5474 @"current",
5475 @"events",
5476 @"finish",
5477 @"percent",
5478 @"running",
5479 @"speed",
5480 @"title",
5481 @"total",
5482 nil];
5483}
5484
5485- (NSArray *) attributeKeys {
5486 return [[self class] _attributeKeys];
5487}
5488
5489+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5490 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5491}
5492
5493- (id) init {
5494 if ((self = [super init]) != nil) {
5495 events_ = [NSMutableArray arrayWithCapacity:32];
5496 } return self;
5497}
5498
5499- (id) delegate {
5500 return delegate_;
5501}
5502
5503- (void) setDelegate:(id)delegate {
5504 delegate_ = delegate;
5505}
5506
5507- (void) setPercent:(float)value {
5508 percent_ = value;
5509}
5510
5511- (NSNumber *) percent {
5512 return [NSNumber numberWithFloat:percent_];
5513}
5514
5515- (void) setCurrent:(float)value {
5516 current_ = value;
5517}
5518
5519- (NSNumber *) current {
5520 return [NSNumber numberWithFloat:current_];
5521}
5522
5523- (void) setTotal:(float)value {
5524 total_ = value;
5525}
5526
5527- (NSNumber *) total {
5528 return [NSNumber numberWithFloat:total_];
5529}
5530
5531- (void) setSpeed:(float)value {
5532 speed_ = value;
5533}
5534
5535- (NSNumber *) speed {
5536 return [NSNumber numberWithFloat:speed_];
5537}
5538
5539- (NSArray *) events {
5540 return events_;
5541}
5542
5543- (void) removeAllEvents {
5544 [events_ removeAllObjects];
5545}
5546
5547- (void) addEvent:(CydiaProgressEvent *)event {
5548 [events_ addObject:event];
5549}
5550
5551- (void) setTitle:(NSString *)text {
5552 title_ = text;
5553}
5554
5555- (NSString *) title {
5556 return title_;
5557}
5558
5559- (void) setFinish:(NSString *)text {
5560 finish_ = text;
5561}
5562
5563- (NSString *) finish {
5564 return (id) finish_ ?: [NSNull null];
5565}
5566
5567- (void) setRunning:(bool)running {
5568 running_ = running;
5569}
5570
5571- (NSNumber *) running {
5572 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5573}
5574
5575@end
5576/* }}} */
5577/* Progress Controller {{{ */
5578@interface ProgressController : CydiaWebViewController <
5579 ProgressDelegate
5580> {
5581 _transient Database *database_;
5582 _H<CydiaProgressData, 1> progress_;
5583 unsigned cancel_;
5584}
5585
5586- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5587
5588- (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5589
5590- (void) setTitle:(NSString *)title;
5591- (void) setCancellable:(bool)cancellable;
5592
5593@end
5594
5595@implementation ProgressController
5596
5597- (void) dealloc {
5598 [database_ setProgressDelegate:nil];
5599 [super dealloc];
5600}
5601
5602- (UIBarButtonItem *) leftButton {
5603 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5604 initWithTitle:UCLocalize("CANCEL")
5605 style:UIBarButtonItemStylePlain
5606 target:self
5607 action:@selector(cancel)
5608 ] autorelease] : nil;
5609}
5610
5611- (void) updateCancel {
5612 [super applyLeftButton];
5613}
5614
5615- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5616 if ((self = [super init]) != nil) {
5617 database_ = database;
5618 delegate_ = delegate;
5619
5620 [database_ setProgressDelegate:self];
5621
5622 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5623 [progress_ setDelegate:self];
5624
5625 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5626
5627 [scroller_ setBackgroundColor:[UIColor blackColor]];
5628
5629 [[self navigationItem] setHidesBackButton:YES];
5630
5631 [self updateCancel];
5632 } return self;
5633}
5634
5635- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5636 [super webView:view didClearWindowObject:window forFrame:frame];
5637 [window setValue:progress_ forKey:@"cydiaProgress"];
5638}
5639
5640- (void) updateProgress {
5641 [self dispatchEvent:@"CydiaProgressUpdate"];
5642}
5643
5644- (void) viewWillAppear:(BOOL)animated {
5645 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5646 [super viewWillAppear:animated];
5647}
5648
5649- (void) close {
5650 UpdateExternalStatus(0);
5651
5652 if (Finish_ > 1)
5653 [delegate_ saveState];
5654
5655 switch (Finish_) {
5656 case 0:
5657 [delegate_ returnToCydia];
5658 break;
5659
5660 case 1:
5661 [delegate_ terminateWithSuccess];
5662 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5663 [delegate_ suspendWithAnimation:YES];
5664 else
5665 [delegate_ suspend];*/
5666 break;
5667
5668 case 2:
5669 _trace();
5670 goto reload;
5671
5672 case 3:
5673 _trace();
5674 goto reload;
5675
5676 reload: {
5677 UIProgressHUD *hud([delegate_ addProgressHUD]);
5678 [hud setText:UCLocalize("LOADING")];
5679 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5680 return;
5681 }
5682
5683 case 4:
5684 _trace();
5685 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5686 SBReboot(SBSSpringBoardServerPort());
5687 else
5688 reboot2(RB_AUTOBOOT);
5689 break;
5690 }
5691
5692 [super close];
5693}
5694
5695- (void) setTitle:(NSString *)title {
5696 [progress_ setTitle:title];
5697 [self updateProgress];
5698}
5699
5700- (UIBarButtonItem *) rightButton {
5701 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5702 initWithTitle:UCLocalize("CLOSE")
5703 style:UIBarButtonItemStylePlain
5704 target:self
5705 action:@selector(close)
5706 ] autorelease];
5707}
5708
5709- (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5710 UpdateExternalStatus(1);
5711
5712 [progress_ setRunning:true];
5713 [self setTitle:title];
5714 // implicit updateProgress
5715
5716 SHA1SumValue notifyconf; {
5717 FileFd file;
5718 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5719 _error->Discard();
5720 else {
5721 MMap mmap(file, MMap::ReadOnly);
5722 SHA1Summation sha1;
5723 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5724 notifyconf = sha1.Result();
5725 }
5726 }
5727
5728 SHA1SumValue springlist; {
5729 FileFd file;
5730 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5731 _error->Discard();
5732 else {
5733 MMap mmap(file, MMap::ReadOnly);
5734 SHA1Summation sha1;
5735 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5736 springlist = sha1.Result();
5737 }
5738 }
5739
5740 if (invocation != nil) {
5741 [invocation yieldToSelector:@selector(invoke)];
5742 [self setTitle:@"COMPLETE"];
5743 }
5744
5745 if (Finish_ < 4) {
5746 FileFd file;
5747 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5748 _error->Discard();
5749 else {
5750 MMap mmap(file, MMap::ReadOnly);
5751 SHA1Summation sha1;
5752 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5753 if (!(notifyconf == sha1.Result()))
5754 Finish_ = 4;
5755 }
5756 }
5757
5758 if (Finish_ < 3) {
5759 FileFd file;
5760 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5761 _error->Discard();
5762 else {
5763 MMap mmap(file, MMap::ReadOnly);
5764 SHA1Summation sha1;
5765 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5766 if (!(springlist == sha1.Result()))
5767 Finish_ = 3;
5768 }
5769 }
5770
5771 if (Finish_ < 2) {
5772 if (RestartSubstrate_)
5773 Finish_ = 2;
5774 }
5775
5776 RestartSubstrate_ = false;
5777
5778 switch (Finish_) {
5779 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5780 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5781 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5782 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5783 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5784 }
5785
5786 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5787
5788 [progress_ setRunning:false];
5789 [self updateProgress];
5790
5791 [self applyRightButton];
5792}
5793
5794- (void) addProgressEvent:(CydiaProgressEvent *)event {
5795 [progress_ addEvent:event];
5796 [self updateProgress];
5797}
5798
5799- (bool) isProgressCancelled {
5800 return cancel_ == 2;
5801}
5802
5803- (void) cancel {
5804 cancel_ = 2;
5805 [self updateCancel];
5806}
5807
5808- (void) setCancellable:(bool)cancellable {
5809 unsigned cancel(cancel_);
5810
5811 if (!cancellable)
5812 cancel_ = 0;
5813 else if (cancel_ == 0)
5814 cancel_ = 1;
5815
5816 if (cancel != cancel_)
5817 [self updateCancel];
5818}
5819
5820- (void) setProgressCancellable:(NSNumber *)cancellable {
5821 [self setCancellable:[cancellable boolValue]];
5822}
5823
5824- (void) setProgressPercent:(NSNumber *)percent {
5825 [progress_ setPercent:[percent floatValue]];
5826 [self updateProgress];
5827}
5828
5829- (void) setProgressStatus:(NSDictionary *)status {
5830 if (status == nil) {
5831 [progress_ setCurrent:0];
5832 [progress_ setTotal:0];
5833 [progress_ setSpeed:0];
5834 } else {
5835 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5836
5837 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5838 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5839 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5840 }
5841
5842 [self updateProgress];
5843}
5844
5845@end
5846/* }}} */
5847
5848/* Package Cell {{{ */
5849@interface PackageCell : CyteTableViewCell <
5850 CyteTableViewCellDelegate
5851> {
5852 _H<UIImage> icon_;
5853 _H<NSString> name_;
5854 _H<NSString> description_;
5855 bool commercial_;
5856 _H<NSString> source_;
5857 _H<UIImage> badge_;
5858 _H<UIImage> placard_;
5859 bool summarized_;
5860}
5861
5862- (PackageCell *) init;
5863- (void) setPackage:(Package *)package asSummary:(bool)summary;
5864
5865- (void) drawContentRect:(CGRect)rect;
5866
5867@end
5868
5869@implementation PackageCell
5870
5871- (PackageCell *) init {
5872 CGRect frame(CGRectMake(0, 0, 320, 74));
5873 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5874 UIView *content([self contentView]);
5875 CGRect bounds([content bounds]);
5876
5877 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5878 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5879 [content addSubview:content_];
5880
5881 [content_ setDelegate:self];
5882 [content_ setOpaque:YES];
5883 } return self;
5884}
5885
5886- (NSString *) accessibilityLabel {
5887 return name_;
5888}
5889
5890- (void) setPackage:(Package *)package asSummary:(bool)summary {
5891 summarized_ = summary;
5892
5893 icon_ = nil;
5894 name_ = nil;
5895 description_ = nil;
5896 source_ = nil;
5897 badge_ = nil;
5898 placard_ = nil;
5899
5900 if (package == nil)
5901 [content_ setBackgroundColor:[UIColor whiteColor]];
5902 else {
5903 [package parse];
5904
5905 Source *source = [package source];
5906
5907 icon_ = [package icon];
5908
5909 if (NSString *name = [package name])
5910 name_ = [NSString stringWithString:name];
5911
5912 if (NSString *description = [package shortDescription])
5913 description_ = [NSString stringWithString:description];
5914
5915 commercial_ = [package isCommercial];
5916
5917 NSString *label = nil;
5918 bool trusted = false;
5919
5920 if (source != nil) {
5921 label = [source label];
5922 trusted = [source trusted];
5923 } else if ([[package id] isEqualToString:@"firmware"])
5924 label = UCLocalize("APPLE");
5925 else
5926 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5927
5928 NSString *from(label);
5929
5930 NSString *section = [package simpleSection];
5931 if (section != nil && ![section isEqualToString:label]) {
5932 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5933 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5934 }
5935
5936 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5937
5938 if (NSString *purpose = [package primaryPurpose])
5939 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5940
5941 UIColor *color;
5942 NSString *placard;
5943
5944 if (NSString *mode = [package mode]) {
5945 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5946 color = RemovingColor_;
5947 placard = @"removing";
5948 } else {
5949 color = InstallingColor_;
5950 placard = @"installing";
5951 }
5952 } else {
5953 color = [UIColor whiteColor];
5954
5955 if ([package installed] != nil)
5956 placard = @"installed";
5957 else
5958 placard = nil;
5959 }
5960
5961 [content_ setBackgroundColor:color];
5962
5963 if (placard != nil)
5964 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5965 }
5966
5967 [self setNeedsDisplay];
5968 [content_ setNeedsDisplay];
5969}
5970
5971- (void) drawSummaryContentRect:(CGRect)rect {
5972 bool highlighted(highlighted_);
5973 float width([self bounds].size.width);
5974
5975 if (icon_ != nil) {
5976 CGRect rect;
5977 rect.size = [(UIImage *) icon_ size];
5978
5979 while (rect.size.width > 16 || rect.size.height > 16) {
5980 rect.size.width /= 2;
5981 rect.size.height /= 2;
5982 }
5983
5984 rect.origin.x = 19 - rect.size.width / 2;
5985 rect.origin.y = 19 - rect.size.height / 2;
5986
5987 [icon_ drawInRect:Retina(rect)];
5988 }
5989
5990 if (badge_ != nil) {
5991 CGRect rect;
5992 rect.size = [(UIImage *) badge_ size];
5993
5994 rect.size.width /= 4;
5995 rect.size.height /= 4;
5996
5997 rect.origin.x = 25 - rect.size.width / 2;
5998 rect.origin.y = 25 - rect.size.height / 2;
5999
6000 [badge_ drawInRect:Retina(rect)];
6001 }
6002
6003 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6004 UISetColor(White_);
6005
6006 if (!highlighted)
6007 UISetColor(commercial_ ? Purple_ : Black_);
6008 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6009
6010 if (placard_ != nil)
6011 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6012}
6013
6014- (void) drawNormalContentRect:(CGRect)rect {
6015 bool highlighted(highlighted_);
6016 float width([self bounds].size.width);
6017
6018 if (icon_ != nil) {
6019 CGRect rect;
6020 rect.size = [(UIImage *) icon_ size];
6021
6022 while (rect.size.width > 32 || rect.size.height > 32) {
6023 rect.size.width /= 2;
6024 rect.size.height /= 2;
6025 }
6026
6027 rect.origin.x = 25 - rect.size.width / 2;
6028 rect.origin.y = 25 - rect.size.height / 2;
6029
6030 [icon_ drawInRect:Retina(rect)];
6031 }
6032
6033 if (badge_ != nil) {
6034 CGRect rect;
6035 rect.size = [(UIImage *) badge_ size];
6036
6037 rect.size.width /= 2;
6038 rect.size.height /= 2;
6039
6040 rect.origin.x = 36 - rect.size.width / 2;
6041 rect.origin.y = 36 - rect.size.height / 2;
6042
6043 [badge_ drawInRect:Retina(rect)];
6044 }
6045
6046 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6047 UISetColor(White_);
6048
6049 if (!highlighted)
6050 UISetColor(commercial_ ? Purple_ : Black_);
6051 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6052 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6053
6054 if (!highlighted)
6055 UISetColor(commercial_ ? Purplish_ : Gray_);
6056 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6057
6058 if (placard_ != nil)
6059 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6060}
6061
6062- (void) drawContentRect:(CGRect)rect {
6063 if (summarized_)
6064 [self drawSummaryContentRect:rect];
6065 else
6066 [self drawNormalContentRect:rect];
6067}
6068
6069@end
6070/* }}} */
6071/* Section Cell {{{ */
6072@interface SectionCell : CyteTableViewCell <
6073 CyteTableViewCellDelegate
6074> {
6075 _H<NSString> basic_;
6076 _H<NSString> section_;
6077 _H<NSString> name_;
6078 _H<NSString> count_;
6079 _H<UIImage> icon_;
6080 _H<UISwitch> switch_;
6081 BOOL editing_;
6082}
6083
6084- (void) setSection:(Section *)section editing:(BOOL)editing;
6085
6086@end
6087
6088@implementation SectionCell
6089
6090- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6091 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6092 icon_ = [UIImage imageNamed:@"folder.png"];
6093 // XXX: this initial frame is wrong, but is fixed later
6094 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6095 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6096
6097 UIView *content([self contentView]);
6098 CGRect bounds([content bounds]);
6099
6100 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6101 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6102 [content addSubview:content_];
6103 [content_ setBackgroundColor:[UIColor whiteColor]];
6104
6105 [content_ setDelegate:self];
6106 } return self;
6107}
6108
6109- (void) onSwitch:(id)sender {
6110 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6111 if (metadata == nil) {
6112 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6113 [Sections_ setObject:metadata forKey:basic_];
6114 }
6115
6116 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6117}
6118
6119- (void) setSection:(Section *)section editing:(BOOL)editing {
6120 if (editing != editing_) {
6121 if (editing_)
6122 [switch_ removeFromSuperview];
6123 else
6124 [self addSubview:switch_];
6125 editing_ = editing;
6126 }
6127
6128 basic_ = nil;
6129 section_ = nil;
6130 name_ = nil;
6131 count_ = nil;
6132
6133 if (section == nil) {
6134 name_ = UCLocalize("ALL_PACKAGES");
6135 count_ = nil;
6136 } else {
6137 basic_ = [section name];
6138 section_ = [section localized];
6139
6140 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6141 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6142
6143 if (editing_)
6144 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6145 }
6146
6147 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6148 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6149
6150 [content_ setNeedsDisplay];
6151}
6152
6153- (void) setFrame:(CGRect)frame {
6154 [super setFrame:frame];
6155
6156 CGRect rect([switch_ frame]);
6157 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6158}
6159
6160- (NSString *) accessibilityLabel {
6161 return name_;
6162}
6163
6164- (void) drawContentRect:(CGRect)rect {
6165 bool highlighted(highlighted_ && !editing_);
6166
6167 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6168
6169 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6170 UISetColor(White_);
6171
6172 float width(rect.size.width);
6173 if (editing_)
6174 width -= 9 + [switch_ frame].size.width;
6175
6176 if (!highlighted)
6177 UISetColor(Black_);
6178 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6179
6180 CGSize size = [count_ sizeWithFont:Font14_];
6181
6182 UISetColor(Folder_);
6183 if (count_ != nil)
6184 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6185}
6186
6187@end
6188/* }}} */
6189
6190/* File Table {{{ */
6191@interface FileTable : CyteViewController <
6192 UITableViewDataSource,
6193 UITableViewDelegate
6194> {
6195 _transient Database *database_;
6196 _H<Package> package_;
6197 _H<NSString> name_;
6198 _H<NSMutableArray> files_;
6199 _H<UITableView, 2> list_;
6200}
6201
6202- (id) initWithDatabase:(Database *)database;
6203- (void) setPackage:(Package *)package;
6204
6205@end
6206
6207@implementation FileTable
6208
6209- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6210 return files_ == nil ? 0 : [files_ count];
6211}
6212
6213/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6214 return 24.0f;
6215}*/
6216
6217- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6218 static NSString *reuseIdentifier = @"Cell";
6219
6220 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6221 if (cell == nil) {
6222 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6223 [cell setFont:[UIFont systemFontOfSize:16]];
6224 }
6225 [cell setText:[files_ objectAtIndex:indexPath.row]];
6226 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6227
6228 return cell;
6229}
6230
6231- (NSURL *) navigationURL {
6232 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6233}
6234
6235- (void) loadView {
6236 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6237 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6238 [list_ setRowHeight:24.0f];
6239 [(UITableView *) list_ setDataSource:self];
6240 [list_ setDelegate:self];
6241 [self setView:list_];
6242}
6243
6244- (void) viewDidLoad {
6245 [super viewDidLoad];
6246
6247 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6248}
6249
6250- (void) releaseSubviews {
6251 list_ = nil;
6252
6253 package_ = nil;
6254 files_ = nil;
6255
6256 [super releaseSubviews];
6257}
6258
6259- (id) initWithDatabase:(Database *)database {
6260 if ((self = [super init]) != nil) {
6261 database_ = database;
6262 } return self;
6263}
6264
6265- (void) setPackage:(Package *)package {
6266 package_ = nil;
6267 name_ = nil;
6268
6269 files_ = [NSMutableArray arrayWithCapacity:32];
6270
6271 if (package != nil) {
6272 package_ = package;
6273 name_ = [package id];
6274
6275 if (NSArray *files = [package files])
6276 [files_ addObjectsFromArray:files];
6277
6278 if ([files_ count] != 0) {
6279 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6280 [files_ removeObjectAtIndex:0];
6281 [files_ sortUsingSelector:@selector(compareByPath:)];
6282
6283 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6284 [stack addObject:@"/"];
6285
6286 for (int i(0), e([files_ count]); i != e; ++i) {
6287 NSString *file = [files_ objectAtIndex:i];
6288 while (![file hasPrefix:[stack lastObject]])
6289 [stack removeLastObject];
6290 NSString *directory = [stack lastObject];
6291 [stack addObject:[file stringByAppendingString:@"/"]];
6292 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6293 int(([stack count] - 2) * 3), "",
6294 [file substringFromIndex:[directory length]]
6295 ]];
6296 }
6297 }
6298 }
6299
6300 [list_ reloadData];
6301}
6302
6303- (void) reloadData {
6304 [super reloadData];
6305
6306 [self setPackage:[database_ packageWithName:name_]];
6307}
6308
6309@end
6310/* }}} */
6311/* Package Controller {{{ */
6312@interface CYPackageController : CydiaWebViewController <
6313 UIActionSheetDelegate
6314> {
6315 _transient Database *database_;
6316 _H<Package> package_;
6317 _H<NSString> name_;
6318 bool commercial_;
6319 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6320 _H<UIActionSheet> sheet_;
6321 _H<UIBarButtonItem> button_;
6322 _H<NSArray> versions_;
6323}
6324
6325- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6326
6327@end
6328
6329@implementation CYPackageController
6330
6331- (NSURL *) navigationURL {
6332 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6333}
6334
6335- (void) _clickButtonWithPackage:(Package *)package {
6336 [delegate_ installPackage:package];
6337}
6338
6339- (void) _clickButtonWithName:(NSString *)name {
6340 if ([name isEqualToString:@"CLEAR"])
6341 return [delegate_ clearPackage:package_];
6342 else if ([name isEqualToString:@"REMOVE"])
6343 return [delegate_ removePackage:package_];
6344 else if ([name isEqualToString:@"DOWNGRADE"]) {
6345 sheet_ = [[[UIActionSheet alloc]
6346 initWithTitle:nil
6347 delegate:self
6348 cancelButtonTitle:nil
6349 destructiveButtonTitle:nil
6350 otherButtonTitles:nil
6351 ] autorelease];
6352
6353 for (Package *version in (id) versions_)
6354 [sheet_ addButtonWithTitle:[version latest]];
6355 [sheet_ setContext:@"version"];
6356
6357 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6358 return;
6359 }
6360
6361 else if ([name isEqualToString:@"INSTALL"]);
6362 else if ([name isEqualToString:@"REINSTALL"]);
6363 else if ([name isEqualToString:@"UPGRADE"]);
6364 else _assert(false);
6365
6366 [delegate_ installPackage:package_];
6367}
6368
6369- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6370 NSString *context([sheet context]);
6371 if (sheet_ == sheet)
6372 sheet_ = nil;
6373
6374 if ([context isEqualToString:@"modify"]) {
6375 if (button != [sheet cancelButtonIndex]) {
6376 if (IsWildcat_)
6377 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6378 else
6379 [self _clickButtonWithName:buttons_[button].first];
6380 }
6381
6382 [sheet dismissWithClickedButtonIndex:button animated:YES];
6383 } else if ([context isEqualToString:@"version"]) {
6384 if (button != [sheet cancelButtonIndex]) {
6385 Package *version([versions_ objectAtIndex:button]);
6386 if (IsWildcat_)
6387 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6388 else
6389 [self _clickButtonWithPackage:version];
6390 }
6391
6392 [sheet dismissWithClickedButtonIndex:button animated:YES];
6393 }
6394}
6395
6396- (bool) _allowJavaScriptPanel {
6397 return commercial_;
6398}
6399
6400#if !AlwaysReload
6401- (void) _customButtonClicked {
6402 size_t count(buttons_.size());
6403 if (count == 0)
6404 return;
6405
6406 if (count == 1)
6407 [self _clickButtonWithName:buttons_[0].first];
6408 else {
6409 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6410 for (const auto &button : buttons_)
6411 [buttons addObject:button.second];
6412
6413 sheet_ = [[[UIActionSheet alloc]
6414 initWithTitle:nil
6415 delegate:self
6416 cancelButtonTitle:nil
6417 destructiveButtonTitle:nil
6418 otherButtonTitles:nil
6419 ] autorelease];
6420
6421 for (NSString *button in buttons)
6422 [sheet_ addButtonWithTitle:button];
6423 [sheet_ setContext:@"modify"];
6424
6425 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6426 }
6427}
6428
6429- (void) reloadButtonClicked {
6430 if (commercial_ && function_ == nil && [package_ uninstalled])
6431 return;
6432 [self customButtonClicked];
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) setDelegate:(id)delegate;
6529- (void) resetCursor;
6530- (void) clearData;
6531
6532- (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6533
6534@end
6535
6536@implementation PackageListController
6537
6538- (NSURL *) referrerURL {
6539 return [self navigationURL];
6540}
6541
6542- (bool) isSummarized {
6543 return false;
6544}
6545
6546- (bool) showsSections {
6547 return true;
6548}
6549
6550- (void) deselectWithAnimation:(BOOL)animated {
6551 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6552}
6553
6554- (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6555 CGRect base = [[self view] bounds];
6556 base.size.height -= bounds.size.height;
6557 base.origin = [list_ frame].origin;
6558
6559 [UIView beginAnimations:nil context:NULL];
6560 [UIView setAnimationBeginsFromCurrentState:YES];
6561 [UIView setAnimationCurve:curve];
6562 [UIView setAnimationDuration:duration];
6563 [list_ setFrame:base];
6564 [UIView commitAnimations];
6565}
6566
6567- (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6568 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6569}
6570
6571- (void) resizeForKeyboardBounds:(CGRect)bounds {
6572 [self resizeForKeyboardBounds:bounds duration:0];
6573}
6574
6575- (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6576 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6577 *curve = UIViewAnimationCurveEaseInOut;
6578 else
6579 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6580
6581 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6582 *duration = 0.3;
6583 else
6584 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6585}
6586
6587- (void) keyboardWillShow:(NSNotification *)notification {
6588 CGRect bounds;
6589 CGPoint center;
6590 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6591 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6592
6593 NSTimeInterval duration;
6594 UIViewAnimationCurve curve;
6595 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6596
6597 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6598 UIViewController *base = self;
6599 while ([base parentOrPresentingViewController] != nil)
6600 base = [base parentOrPresentingViewController];
6601 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6602 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6603
6604 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6605 intersection.size.height += CYStatusBarHeight();
6606
6607 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6608}
6609
6610- (void) keyboardWillHide:(NSNotification *)notification {
6611 NSTimeInterval duration;
6612 UIViewAnimationCurve curve;
6613 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6614
6615 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6616}
6617
6618- (void) viewWillAppear:(BOOL)animated {
6619 [super viewWillAppear:animated];
6620
6621 [self resizeForKeyboardBounds:CGRectZero];
6622 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6623 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6624}
6625
6626- (void) viewWillDisappear:(BOOL)animated {
6627 [super viewWillDisappear:animated];
6628
6629 [self resizeForKeyboardBounds:CGRectZero];
6630 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6631 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6632}
6633
6634- (void) viewDidAppear:(BOOL)animated {
6635 [super viewDidAppear:animated];
6636 [self deselectWithAnimation:animated];
6637}
6638
6639- (void) didSelectPackage:(Package *)package {
6640 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6641 [view setDelegate:delegate_];
6642 [[self navigationController] pushViewController:view animated:YES];
6643}
6644
6645- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6646 NSInteger count([sections_ count]);
6647 return count == 0 ? 1 : count;
6648}
6649
6650- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6651 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6652 return nil;
6653 return [[sections_ objectAtIndex:section] name];
6654}
6655
6656- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6657 if ([sections_ count] == 0)
6658 return 0;
6659 return [[sections_ objectAtIndex:section] count];
6660}
6661
6662- (Package *) packageAtIndexPath:(NSIndexPath *)path {
6663@synchronized (database_) {
6664 if ([database_ era] != era_)
6665 return nil;
6666
6667 Section *section([sections_ objectAtIndex:[path section]]);
6668 NSInteger row([path row]);
6669 Package *package([packages_ objectAtIndex:([section row] + row)]);
6670 return [[package retain] autorelease];
6671} }
6672
6673- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6674 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6675 if (cell == nil)
6676 cell = [[[PackageCell alloc] init] autorelease];
6677
6678 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6679 [cell setPackage:package asSummary:[self isSummarized]];
6680 return cell;
6681}
6682
6683- (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6684 Package *package([self packageAtIndexPath:path]);
6685 package = [database_ packageWithName:[package id]];
6686 [self didSelectPackage:package];
6687}
6688
6689- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6690 return thumbs_;
6691}
6692
6693- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6694 return offset_[index];
6695}
6696
6697- (void) updateHeight {
6698 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6699}
6700
6701- (id) initWithDatabase:(Database *)database title:(NSString *)title {
6702 if ((self = [super init]) != nil) {
6703 database_ = database;
6704 title_ = [title copy];
6705 [[self navigationItem] setTitle:title_];
6706 } return self;
6707}
6708
6709- (void) loadView {
6710 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6711 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6712 [self setView:view];
6713
6714 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6715 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6716 [view addSubview:list_];
6717
6718 // XXX: is 20 the most optimal number here?
6719 [list_ setSectionIndexMinimumDisplayRowCount:20];
6720
6721 [(UITableView *) list_ setDataSource:self];
6722 [list_ setDelegate:self];
6723
6724 [self updateHeight];
6725}
6726
6727- (void) releaseSubviews {
6728 list_ = nil;
6729
6730 packages_ = nil;
6731 sections_ = nil;
6732
6733 thumbs_ = nil;
6734 offset_.clear();
6735
6736 [super releaseSubviews];
6737}
6738
6739- (void) setDelegate:(id)delegate {
6740 delegate_ = delegate;
6741}
6742
6743- (bool) shouldYield {
6744 return false;
6745}
6746
6747- (bool) shouldBlock {
6748 return false;
6749}
6750
6751- (NSMutableArray *) _reloadPackages {
6752@synchronized (database_) {
6753 era_ = [database_ era];
6754 NSArray *packages([database_ packages]);
6755
6756 return [NSMutableArray arrayWithArray:packages];
6757} }
6758
6759- (void) _reloadData {
6760 if (reloading_ != 0) {
6761 reloading_ = 2;
6762 return;
6763 }
6764
6765 NSMutableArray *packages;
6766
6767 reload:
6768 if ([self shouldYield]) {
6769 do {
6770 UIProgressHUD *hud;
6771
6772 if (![self shouldBlock])
6773 hud = nil;
6774 else {
6775 hud = [delegate_ addProgressHUD];
6776 [hud setText:UCLocalize("LOADING")];
6777 }
6778
6779 reloading_ = 1;
6780 packages = [self yieldToSelector:@selector(_reloadPackages)];
6781
6782 if (hud != nil)
6783 [delegate_ removeProgressHUD:hud];
6784 } while (reloading_ == 2);
6785 } else {
6786 packages = [self _reloadPackages];
6787 }
6788
6789@synchronized (database_) {
6790 if (era_ != [database_ era])
6791 goto reload;
6792 reloading_ = 0;
6793
6794 thumbs_ = nil;
6795 offset_.clear();
6796
6797 packages_ = packages;
6798
6799 if ([self showsSections])
6800 sections_ = [self sectionsForPackages:packages];
6801 else {
6802 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6803 [section setCount:[packages_ count]];
6804 sections_ = [NSArray arrayWithObject:section];
6805 }
6806
6807 [self updateHeight];
6808
6809 _profile(PackageTable$reloadData$List)
6810 [(UITableView *) list_ setDataSource:self];
6811 [list_ reloadData];
6812 _end
6813}
6814
6815 PrintTimes();
6816}
6817
6818- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6819 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6820 size_t end([packages count]);
6821
6822 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6823 Section *section(prefix);
6824
6825 thumbs_ = CollationThumbs_;
6826 offset_ = CollationOffset_;
6827
6828 size_t offset(0);
6829 size_t offsets([CollationStarts_ count]);
6830
6831 NSString *start([CollationStarts_ objectAtIndex:offset]);
6832 size_t length([start length]);
6833
6834 for (size_t index(0); index != end; ++index) {
6835 if (start != nil) {
6836 Package *package([packages objectAtIndex:index]);
6837 NSString *name(PackageName(package, @selector(cyname)));
6838
6839 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6840 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6841 NSString *title([CollationTitles_ objectAtIndex:offset]);
6842 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6843 [sections addObject:section];
6844
6845 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6846 if (start == nil)
6847 break;
6848 length = [start length];
6849 }
6850 }
6851
6852 [section addToCount];
6853 }
6854
6855 for (; offset != offsets; ++offset) {
6856 NSString *title([CollationTitles_ objectAtIndex:offset]);
6857 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6858 [sections addObject:section];
6859 }
6860
6861 if ([prefix count] != 0) {
6862 Section *suffix([sections lastObject]);
6863 [prefix setName:[suffix name]];
6864 [suffix setName:nil];
6865 [sections insertObject:prefix atIndex:(offsets - 1)];
6866 }
6867
6868 return sections;
6869}
6870
6871- (void) reloadData {
6872 [super reloadData];
6873
6874 if ([self shouldYield])
6875 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6876 else
6877 [self _reloadData];
6878}
6879
6880- (void) resetCursor {
6881 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6882}
6883
6884- (void) clearData {
6885 [self updateHeight];
6886
6887 [list_ setDataSource:nil];
6888 [list_ reloadData];
6889
6890 [self resetCursor];
6891}
6892
6893@end
6894/* }}} */
6895/* Filtered Package List Controller {{{ */
6896typedef Function<bool, Package *> PackageFilter;
6897typedef Function<void, NSMutableArray *> PackageSorter;
6898@interface FilteredPackageListController : PackageListController {
6899 PackageFilter filter_;
6900 PackageSorter sorter_;
6901}
6902
6903- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6904
6905- (void) setFilter:(PackageFilter)filter;
6906- (void) setSorter:(PackageSorter)sorter;
6907
6908@end
6909
6910@implementation FilteredPackageListController
6911
6912- (void) setFilter:(PackageFilter)filter {
6913@synchronized (self) {
6914 filter_ = filter;
6915} }
6916
6917- (void) setSorter:(PackageSorter)sorter {
6918@synchronized (self) {
6919 sorter_ = sorter;
6920} }
6921
6922- (NSMutableArray *) _reloadPackages {
6923@synchronized (database_) {
6924 era_ = [database_ era];
6925
6926 NSArray *packages([database_ packages]);
6927 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6928
6929 PackageFilter filter;
6930 PackageSorter sorter;
6931
6932 @synchronized (self) {
6933 filter = filter_;
6934 sorter = sorter_;
6935 }
6936
6937 _profile(PackageTable$reloadData$Filter)
6938 for (Package *package in packages)
6939 if (filter(package))
6940 [filtered addObject:package];
6941 _end
6942
6943 if (sorter)
6944 sorter(filtered);
6945 return filtered;
6946} }
6947
6948- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6949 if ((self = [super initWithDatabase:database title:title]) != nil) {
6950 [self setFilter:filter];
6951 } return self;
6952}
6953
6954@end
6955/* }}} */
6956
6957/* Home Controller {{{ */
6958@interface HomeController : CydiaWebViewController {
6959 CFRunLoopRef runloop_;
6960 SCNetworkReachabilityRef reachability_;
6961}
6962
6963@end
6964
6965@implementation HomeController
6966
6967static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6968 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6969}
6970
6971- (id) init {
6972 if ((self = [super init]) != nil) {
6973 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6974 [self reloadData];
6975
6976 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6977 if (reachability_ != NULL) {
6978 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6979 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6980
6981 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6982 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6983 runloop_ = runloop;
6984 }
6985 } return self;
6986}
6987
6988- (void) dealloc {
6989 if (reachability_ != NULL && runloop_ != NULL)
6990 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6991 [super dealloc];
6992}
6993
6994- (NSURL *) navigationURL {
6995 return [NSURL URLWithString:@"cydia://home"];
6996}
6997
6998- (void) aboutButtonClicked {
6999 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
7000
7001 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
7002 [alert addButtonWithTitle:UCLocalize("CLOSE")];
7003 [alert setCancelButtonIndex:0];
7004
7005 [alert setMessage:
7006 @"Copyright \u00a9 2008-2015\n"
7007 "SaurikIT, LLC\n"
7008 "\n"
7009 "Jay Freeman (saurik)\n"
7010 "saurik@saurik.com\n"
7011 "http://www.saurik.com/"
7012 ];
7013
7014 [alert show];
7015}
7016
7017- (UIBarButtonItem *) leftButton {
7018 return [[[UIBarButtonItem alloc]
7019 initWithTitle:UCLocalize("ABOUT")
7020 style:UIBarButtonItemStylePlain
7021 target:self
7022 action:@selector(aboutButtonClicked)
7023 ] autorelease];
7024}
7025
7026@end
7027/* }}} */
7028
7029/* Cydia Navigation Controller Interface {{{ */
7030@interface UINavigationController (Cydia)
7031
7032- (NSArray *) navigationURLCollection;
7033- (void) unloadData;
7034
7035@end
7036/* }}} */
7037
7038/* Cydia Tab Bar Controller {{{ */
7039@interface CydiaTabBarController : CyteTabBarController <
7040 UITabBarControllerDelegate,
7041 FetchDelegate
7042> {
7043 _transient Database *database_;
7044
7045 _H<UIActivityIndicatorView> indicator_;
7046
7047 bool updating_;
7048 // XXX: ok, "updatedelegate_"?...
7049 _transient NSObject<CydiaDelegate> *updatedelegate_;
7050}
7051
7052- (NSArray *) navigationURLCollection;
7053- (void) beginUpdate;
7054- (BOOL) updating;
7055
7056@end
7057
7058@implementation CydiaTabBarController
7059
7060- (NSArray *) navigationURLCollection {
7061 NSMutableArray *items([NSMutableArray array]);
7062
7063 // XXX: Should this deal with transient view controllers?
7064 for (id navigation in [self viewControllers]) {
7065 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
7066 if (stack != nil)
7067 [items addObject:stack];
7068 }
7069
7070 return items;
7071}
7072
7073- (id) initWithDatabase:(Database *)database {
7074 if ((self = [super init]) != nil) {
7075 database_ = database;
7076 [self setDelegate:self];
7077
7078 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7079 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7080
7081 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7082 } return self;
7083}
7084
7085- (void) beginUpdate {
7086 if (updating_)
7087 return;
7088
7089 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7090 UITabBarItem *item([controller tabBarItem]);
7091
7092 [item setBadgeValue:@""];
7093 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7094
7095 [indicator_ startAnimating];
7096 [badge addSubview:indicator_];
7097
7098 [updatedelegate_ retainNetworkActivityIndicator];
7099 updating_ = true;
7100
7101 [NSThread
7102 detachNewThreadSelector:@selector(performUpdate)
7103 toTarget:self
7104 withObject:nil
7105 ];
7106}
7107
7108- (void) performUpdate {
7109 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7110
7111 SourceStatus status(self, database_);
7112 [database_ updateWithStatus:status];
7113
7114 [self
7115 performSelectorOnMainThread:@selector(completeUpdate)
7116 withObject:nil
7117 waitUntilDone:NO
7118 ];
7119
7120 [pool release];
7121}
7122
7123- (void) stopUpdateWithSelector:(SEL)selector {
7124 updating_ = false;
7125 [updatedelegate_ releaseNetworkActivityIndicator];
7126
7127 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7128 [[controller tabBarItem] setBadgeValue:nil];
7129
7130 [indicator_ removeFromSuperview];
7131 [indicator_ stopAnimating];
7132
7133 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7134}
7135
7136- (void) completeUpdate {
7137 if (!updating_)
7138 return;
7139 [self stopUpdateWithSelector:@selector(reloadData)];
7140}
7141
7142- (void) cancelUpdate {
7143 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7144}
7145
7146- (void) cancelPressed {
7147 [self cancelUpdate];
7148}
7149
7150- (BOOL) updating {
7151 return updating_;
7152}
7153
7154- (bool) isSourceCancelled {
7155 return !updating_;
7156}
7157
7158- (void) startSourceFetch:(NSString *)uri {
7159}
7160
7161- (void) stopSourceFetch:(NSString *)uri {
7162}
7163
7164- (void) setUpdateDelegate:(id)delegate {
7165 updatedelegate_ = delegate;
7166}
7167
7168@end
7169/* }}} */
7170
7171/* Cydia Navigation Controller Implementation {{{ */
7172@implementation UINavigationController (Cydia)
7173
7174- (NSArray *) navigationURLCollection {
7175 NSMutableArray *stack([NSMutableArray array]);
7176
7177 for (CyteViewController *controller in [self viewControllers]) {
7178 NSString *url = [[controller navigationURL] absoluteString];
7179 if (url != nil)
7180 [stack addObject:url];
7181 }
7182
7183 return stack;
7184}
7185
7186- (void) reloadData {
7187 [super reloadData];
7188
7189 UIViewController *visible([self visibleViewController]);
7190 if (visible != nil)
7191 [visible reloadData];
7192
7193 // on the iPad, this view controller is ALSO visible. :(
7194 if (IsWildcat_)
7195 if (UIViewController *modal = [self modalViewController])
7196 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7197 if (UIViewController *top = [self topViewController])
7198 if (top != visible)
7199 [top reloadData];
7200}
7201
7202- (void) unloadData {
7203 for (CyteViewController *page in [self viewControllers])
7204 [page unloadData];
7205
7206 [super unloadData];
7207}
7208
7209@end
7210/* }}} */
7211
7212/* Cydia:// Protocol {{{ */
7213@interface CydiaURLProtocol : NSURLProtocol {
7214}
7215
7216@end
7217
7218@implementation CydiaURLProtocol
7219
7220+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
7221 NSURL *url([request URL]);
7222 if (url == nil)
7223 return NO;
7224
7225 NSString *scheme([[url scheme] lowercaseString]);
7226 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7227 return YES;
7228 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7229 return YES;
7230
7231 return NO;
7232}
7233
7234+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7235 return request;
7236}
7237
7238- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7239 id<NSURLProtocolClient> client([self client]);
7240 if (icon == nil)
7241 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7242 else {
7243 NSData *data(UIImagePNGRepresentation(icon));
7244
7245 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7246 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7247 [client URLProtocol:self didLoadData:data];
7248 [client URLProtocolDidFinishLoading:self];
7249 }
7250}
7251
7252- (void) startLoading {
7253 id<NSURLProtocolClient> client([self client]);
7254 NSURLRequest *request([self request]);
7255
7256 NSURL *url([request URL]);
7257 NSString *href([url absoluteString]);
7258 NSString *scheme([[url scheme] lowercaseString]);
7259
7260 NSString *path;
7261
7262 if ([scheme isEqualToString:@"cydia"])
7263 path = [href substringFromIndex:8];
7264 else if ([scheme isEqualToString:@"about"])
7265 path = [href substringFromIndex:12];
7266 else _assert(false);
7267
7268 NSRange slash([path rangeOfString:@"/"]);
7269
7270 NSString *command;
7271 if (slash.location == NSNotFound) {
7272 command = path;
7273 path = nil;
7274 } else {
7275 command = [path substringToIndex:slash.location];
7276 path = [path substringFromIndex:(slash.location + 1)];
7277 }
7278
7279 Database *database([Database sharedInstance]);
7280
7281 if (false);
7282 else if ([command isEqualToString:@"application-icon"]) {
7283 if (path == nil)
7284 goto fail;
7285 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7286
7287 UIImage *icon(nil);
7288
7289 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7290 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7291 icon = [UIImage imageWithData:data];
7292 }
7293
7294 if (icon == nil)
7295 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7296 icon = [UIImage imageAtPath:file];
7297
7298 if (icon == nil)
7299 icon = [UIImage imageNamed:@"unknown.png"];
7300
7301 [self _returnPNGWithImage:icon forRequest:request];
7302 } else if ([command isEqualToString:@"package-icon"]) {
7303 if (path == nil)
7304 goto fail;
7305 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7306 Package *package([database packageWithName:path]);
7307 if (package == nil)
7308 goto fail;
7309 [package parse];
7310 UIImage *icon([package icon]);
7311 [self _returnPNGWithImage:icon forRequest:request];
7312 } else if ([command isEqualToString:@"uikit-image"]) {
7313 if (path == nil)
7314 goto fail;
7315 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7316 UIImage *icon(_UIImageWithName(path));
7317 [self _returnPNGWithImage:icon forRequest:request];
7318 } else if ([command isEqualToString:@"section-icon"]) {
7319 if (path == nil)
7320 goto fail;
7321 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7322 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7323 if (icon == nil)
7324 icon = [UIImage imageNamed:@"unknown.png"];
7325 [self _returnPNGWithImage:icon forRequest:request];
7326 } else fail: {
7327 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7328 }
7329}
7330
7331- (void) stopLoading {
7332}
7333
7334@end
7335/* }}} */
7336
7337/* Section Controller {{{ */
7338@interface SectionController : FilteredPackageListController {
7339 _H<NSString> key_;
7340 _H<NSString> section_;
7341}
7342
7343- (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7344
7345@end
7346
7347@implementation SectionController
7348
7349- (NSURL *) referrerURL {
7350 NSString *name(section_);
7351 name = name ?: @"*";
7352 NSString *key(key_);
7353 key = key ?: @"*";
7354 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7355}
7356
7357- (NSURL *) navigationURL {
7358 NSString *name(section_);
7359 name = name ?: @"*";
7360 NSString *key(key_);
7361 key = key ?: @"*";
7362 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7363}
7364
7365- (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7366 NSString *title;
7367 if (section == nil)
7368 title = UCLocalize("ALL_PACKAGES");
7369 else if (![section isEqual:@""])
7370 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7371 else
7372 title = UCLocalize("NO_SECTION");
7373
7374 if ((self = [super initWithDatabase:database title:title]) != nil) {
7375 key_ = [source key];
7376 section_ = section;
7377 } return self;
7378}
7379
7380- (void) reloadData {
7381 Source *source([database_ sourceWithKey:key_]);
7382 _H<NSString> name(section_);
7383
7384 [self setFilter:[=](Package *package) {
7385 NSString *section([package section]);
7386
7387 return (
7388 name == nil ||
7389 section == nil && [name length] == 0 ||
7390 [name isEqualToString:section]
7391 ) && (
7392 source == nil ||
7393 [package source] == source
7394 ) && [package visible];
7395 }];
7396
7397 [super reloadData];
7398}
7399
7400@end
7401/* }}} */
7402/* Sections Controller {{{ */
7403@interface SectionsController : CyteViewController <
7404 UITableViewDataSource,
7405 UITableViewDelegate
7406> {
7407 _transient Database *database_;
7408 _H<NSString> key_;
7409 _H<NSMutableArray> sections_;
7410 _H<NSMutableArray> filtered_;
7411 _H<UITableView, 2> list_;
7412}
7413
7414- (id) initWithDatabase:(Database *)database source:(Source *)source;
7415- (void) editButtonClicked;
7416
7417@end
7418
7419@implementation SectionsController
7420
7421- (NSURL *) navigationURL {
7422 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7423}
7424
7425- (Source *) source {
7426 if (key_ == nil)
7427 return nil;
7428 return [database_ sourceWithKey:key_];
7429}
7430
7431- (void) updateNavigationItem {
7432 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7433 if ([sections_ count] == 0) {
7434 [[self navigationItem] setRightBarButtonItem:nil];
7435 } else {
7436 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7437 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7438 target:self
7439 action:@selector(editButtonClicked)
7440 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7441 }
7442}
7443
7444- (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7445 [super setEditing:editing animated:animated];
7446
7447 if (editing)
7448 [list_ reloadData];
7449 else
7450 [delegate_ updateData];
7451
7452 [self updateNavigationItem];
7453}
7454
7455- (void) viewDidAppear:(BOOL)animated {
7456 [super viewDidAppear:animated];
7457 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7458}
7459
7460- (void) viewWillDisappear:(BOOL)animated {
7461 [super viewWillDisappear:animated];
7462 [self setEditing:NO];
7463}
7464
7465- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7466 Section *section = nil;
7467 int index = [indexPath row];
7468 if (![self isEditing]) {
7469 index -= 1;
7470 if (index >= 0)
7471 section = [filtered_ objectAtIndex:index];
7472 } else {
7473 section = [sections_ objectAtIndex:index];
7474 }
7475 return section;
7476}
7477
7478- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7479 if ([self isEditing])
7480 return [sections_ count];
7481 else
7482 return [filtered_ count] + 1;
7483}
7484
7485/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7486 return 45.0f;
7487}*/
7488
7489- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7490 static NSString *reuseIdentifier = @"SectionCell";
7491
7492 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7493 if (cell == nil)
7494 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7495
7496 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7497
7498 return cell;
7499}
7500
7501- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7502 if ([self isEditing])
7503 return;
7504
7505 Section *section = [self sectionAtIndexPath:indexPath];
7506
7507 SectionController *controller = [[[SectionController alloc]
7508 initWithDatabase:database_
7509 source:[self source]
7510 section:[section name]
7511 ] autorelease];
7512 [controller setDelegate:delegate_];
7513
7514 [[self navigationController] pushViewController:controller animated:YES];
7515}
7516
7517- (void) loadView {
7518 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7519 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7520 [list_ setRowHeight:46];
7521 [(UITableView *) list_ setDataSource:self];
7522 [list_ setDelegate:self];
7523 [self setView:list_];
7524}
7525
7526- (void) viewDidLoad {
7527 [super viewDidLoad];
7528
7529 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7530}
7531
7532- (void) releaseSubviews {
7533 list_ = nil;
7534
7535 sections_ = nil;
7536 filtered_ = nil;
7537
7538 [super releaseSubviews];
7539}
7540
7541- (id) initWithDatabase:(Database *)database source:(Source *)source {
7542 if ((self = [super init]) != nil) {
7543 database_ = database;
7544 key_ = [source key];
7545 } return self;
7546}
7547
7548- (void) reloadData {
7549 [super reloadData];
7550
7551 NSArray *packages = [database_ packages];
7552
7553 sections_ = [NSMutableArray arrayWithCapacity:16];
7554 filtered_ = [NSMutableArray arrayWithCapacity:16];
7555
7556 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7557
7558 Source *source([self source]);
7559
7560 _trace();
7561 for (Package *package in packages) {
7562 if (source != nil && [package source] != source)
7563 continue;
7564
7565 NSString *name([package section]);
7566 NSString *key(name == nil ? @"" : name);
7567
7568 Section *section;
7569
7570 _profile(SectionsView$reloadData$Section)
7571 section = [sections objectForKey:key];
7572 if (section == nil) {
7573 _profile(SectionsView$reloadData$Section$Allocate)
7574 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7575 [sections setObject:section forKey:key];
7576 _end
7577 }
7578 _end
7579
7580 [section addToCount];
7581
7582 _profile(SectionsView$reloadData$Filter)
7583 if (![package visible])
7584 continue;
7585 _end
7586
7587 [section addToRow];
7588 }
7589 _trace();
7590
7591 [sections_ addObjectsFromArray:[sections allValues]];
7592
7593 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7594
7595 for (Section *section in (id) sections_) {
7596 size_t count([section row]);
7597 if (count == 0)
7598 continue;
7599
7600 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7601 [section setCount:count];
7602 [filtered_ addObject:section];
7603 }
7604
7605 [self updateNavigationItem];
7606 [list_ reloadData];
7607 _trace();
7608}
7609
7610- (void) editButtonClicked {
7611 [self setEditing:![self isEditing] animated:YES];
7612}
7613
7614@end
7615/* }}} */
7616
7617/* Changes Controller {{{ */
7618@interface ChangesController : FilteredPackageListController {
7619 unsigned upgrades_;
7620}
7621
7622- (id) initWithDatabase:(Database *)database;
7623
7624@end
7625
7626@implementation ChangesController
7627
7628- (NSURL *) referrerURL {
7629 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7630}
7631
7632- (NSURL *) navigationURL {
7633 return [NSURL URLWithString:@"cydia://changes"];
7634}
7635
7636- (Package *) packageAtIndexPath:(NSIndexPath *)path {
7637@synchronized (database_) {
7638 if ([database_ era] != era_)
7639 return nil;
7640
7641 NSUInteger sectionIndex([path section]);
7642 if (sectionIndex >= [sections_ count])
7643 return nil;
7644 Section *section([sections_ objectAtIndex:sectionIndex]);
7645 NSInteger row([path row]);
7646 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7647} }
7648
7649- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7650 NSString *context([alert context]);
7651
7652 if ([context isEqualToString:@"norefresh"])
7653 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7654}
7655
7656- (void) setLeftBarButtonItem {
7657 if ([delegate_ updating])
7658 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7659 initWithTitle:UCLocalize("CANCEL")
7660 style:UIBarButtonItemStyleDone
7661 target:self
7662 action:@selector(cancelButtonClicked)
7663 ] autorelease] animated:YES];
7664 else
7665 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7666 initWithTitle:UCLocalize("REFRESH")
7667 style:UIBarButtonItemStylePlain
7668 target:self
7669 action:@selector(refreshButtonClicked)
7670 ] autorelease] animated:YES];
7671}
7672
7673- (void) refreshButtonClicked {
7674 if ([delegate_ requestUpdate])
7675 [self setLeftBarButtonItem];
7676}
7677
7678- (void) cancelButtonClicked {
7679 [delegate_ cancelUpdate];
7680}
7681
7682- (void) upgradeButtonClicked {
7683 [delegate_ distUpgrade];
7684 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7685}
7686
7687- (bool) shouldYield {
7688 return true;
7689}
7690
7691- (bool) shouldBlock {
7692 return true;
7693}
7694
7695- (void) useFilter {
7696@synchronized (self) {
7697 [self setFilter:[](Package *package) {
7698 return [package upgradableAndEssential:YES] || [package visible];
7699 }];
7700
7701 [self setSorter:[](NSMutableArray *packages) {
7702 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7703 }];
7704} }
7705
7706- (id) initWithDatabase:(Database *)database {
7707 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7708 [self useFilter];
7709 } return self;
7710}
7711
7712- (void) viewDidLoad {
7713 [super viewDidLoad];
7714 [self setLeftBarButtonItem];
7715}
7716
7717- (void) viewWillAppear:(BOOL)animated {
7718 [super viewWillAppear:animated];
7719 [self setLeftBarButtonItem];
7720}
7721
7722- (void) reloadData {
7723 [self setLeftBarButtonItem];
7724 [super reloadData];
7725}
7726
7727- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7728 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7729
7730 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7731 Section *ignored = nil;
7732 Section *section = nil;
7733 time_t last = 0;
7734
7735 upgrades_ = 0;
7736 bool unseens = false;
7737
7738 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7739
7740 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7741 Package *package = [packages objectAtIndex:offset];
7742
7743 BOOL uae = [package upgradableAndEssential:YES];
7744
7745 if (!uae) {
7746 unseens = true;
7747 time_t seen([package seen]);
7748
7749 if (section == nil || last != seen) {
7750 last = seen;
7751
7752 NSString *name;
7753 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7754 [name autorelease];
7755
7756 _profile(ChangesController$reloadData$Allocate)
7757 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7758 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7759 [sections addObject:section];
7760 _end
7761 }
7762
7763 [section addToCount];
7764 } else if ([package ignored]) {
7765 if (ignored == nil) {
7766 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7767 }
7768 [ignored addToCount];
7769 } else {
7770 ++upgrades_;
7771 [upgradable addToCount];
7772 }
7773 }
7774 _trace();
7775
7776 CFRelease(formatter);
7777
7778 if (unseens) {
7779 Section *last = [sections lastObject];
7780 size_t count = [last count];
7781 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7782 [sections removeLastObject];
7783 }
7784
7785 if ([ignored count] != 0)
7786 [sections insertObject:ignored atIndex:0];
7787 if (upgrades_ != 0)
7788 [sections insertObject:upgradable atIndex:0];
7789
7790 [list_ reloadData];
7791
7792 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7793 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7794 style:UIBarButtonItemStylePlain
7795 target:self
7796 action:@selector(upgradeButtonClicked)
7797 ] autorelease]) animated:YES];
7798
7799 return sections;
7800}
7801
7802@end
7803/* }}} */
7804/* Search Controller {{{ */
7805@interface SearchController : FilteredPackageListController <
7806 UISearchBarDelegate
7807> {
7808 _H<UISearchBar, 1> search_;
7809 BOOL searchloaded_;
7810 bool summary_;
7811}
7812
7813- (id) initWithDatabase:(Database *)database query:(NSString *)query;
7814- (void) reloadData;
7815
7816@end
7817
7818@implementation SearchController
7819
7820- (NSURL *) referrerURL {
7821 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7822}
7823
7824- (NSURL *) navigationURL {
7825 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7826 return [NSURL URLWithString:@"cydia://search"];
7827 else
7828 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7829}
7830
7831- (NSArray *) termsForQuery:(NSString *)query {
7832 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7833 for (NSString *component in [query componentsSeparatedByString:@" "])
7834 if ([component length] != 0)
7835 [terms addObject:component];
7836
7837 return terms;
7838}
7839
7840- (void) useSearch {
7841 _H<NSArray> query([self termsForQuery:[search_ text]]);
7842 summary_ = false;
7843
7844@synchronized (self) {
7845 [self setFilter:[=](Package *package) {
7846 if (![package unfiltered])
7847 return false;
7848 if (![package matches:query])
7849 return false;
7850 return true;
7851 }];
7852
7853 [self setSorter:[](NSMutableArray *packages) {
7854 [packages radixSortUsingSelector:@selector(rank)];
7855 }];
7856}
7857
7858 [self clearData];
7859 [self reloadData];
7860}
7861
7862- (void) usePrefix:(NSString *)prefix {
7863 _H<NSString> query(prefix);
7864 summary_ = true;
7865
7866@synchronized (self) {
7867 [self setFilter:[=](Package *package) {
7868 if ([query length] == 0)
7869 return false;
7870 if (![package unfiltered])
7871 return false;
7872 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7873 return false;
7874 return true;
7875 }];
7876
7877 [self setSorter:nullptr];
7878}
7879
7880 [self reloadData];
7881}
7882
7883- (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7884 [self clearData];
7885 [self usePrefix:[search_ text]];
7886}
7887
7888- (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7889 [search_ resignFirstResponder];
7890 [self useSearch];
7891}
7892
7893- (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7894 [search_ setText:@""];
7895 [self searchBarButtonClicked:searchBar];
7896}
7897
7898- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7899 [self searchBarButtonClicked:searchBar];
7900}
7901
7902- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7903 [self usePrefix:text];
7904}
7905
7906- (bool) shouldYield {
7907 return YES;
7908}
7909
7910- (bool) shouldBlock {
7911 return !summary_;
7912}
7913
7914- (bool) isSummarized {
7915 return summary_;
7916}
7917
7918- (bool) showsSections {
7919 return false;
7920}
7921
7922- (id) initWithDatabase:(Database *)database query:(NSString *)query {
7923 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7924 search_ = [[[UISearchBar alloc] init] autorelease];
7925 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7926 [search_ setDelegate:self];
7927
7928 UITextField *textField;
7929 if ([search_ respondsToSelector:@selector(searchField)])
7930 textField = [search_ searchField];
7931 else
7932 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7933
7934 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7935 [textField setEnablesReturnKeyAutomatically:NO];
7936 [[self navigationItem] setTitleView:textField];
7937
7938 if (query != nil)
7939 [search_ setText:query];
7940 [self useSearch];
7941 } return self;
7942}
7943
7944- (void) viewDidAppear:(BOOL)animated {
7945 [super viewDidAppear:animated];
7946
7947 if (!searchloaded_) {
7948 searchloaded_ = YES;
7949 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7950 [search_ layoutSubviews];
7951 }
7952
7953 if ([self isSummarized])
7954 [search_ becomeFirstResponder];
7955}
7956
7957- (void) reloadData {
7958 [self resetCursor];
7959 [super reloadData];
7960}
7961
7962- (void) didSelectPackage:(Package *)package {
7963 [search_ resignFirstResponder];
7964 [super didSelectPackage:package];
7965}
7966
7967@end
7968/* }}} */
7969/* Package Settings Controller {{{ */
7970@interface PackageSettingsController : CyteViewController <
7971 UITableViewDataSource,
7972 UITableViewDelegate
7973> {
7974 _transient Database *database_;
7975 _H<NSString> name_;
7976 _H<Package> package_;
7977 _H<UITableView, 2> table_;
7978 _H<UISwitch> subscribedSwitch_;
7979 _H<UISwitch> ignoredSwitch_;
7980 _H<UITableViewCell> subscribedCell_;
7981 _H<UITableViewCell> ignoredCell_;
7982}
7983
7984- (id) initWithDatabase:(Database *)database package:(NSString *)package;
7985
7986@end
7987
7988@implementation PackageSettingsController
7989
7990- (NSURL *) navigationURL {
7991 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7992}
7993
7994- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7995 if (package_ == nil)
7996 return 0;
7997
7998 if ([package_ installed] == nil)
7999 return 1;
8000 else
8001 return 2;
8002}
8003
8004- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8005 if (package_ == nil)
8006 return 0;
8007
8008 // both sections contain just one item right now.
8009 return 1;
8010}
8011
8012- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8013 return nil;
8014}
8015
8016- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8017 if (section == 0)
8018 return UCLocalize("SHOW_ALL_CHANGES_EX");
8019 else
8020 return UCLocalize("IGNORE_UPGRADES_EX");
8021}
8022
8023- (void) onSubscribed:(id)control {
8024 bool value([control isOn]);
8025 if (package_ == nil)
8026 return;
8027 if ([package_ setSubscribed:value])
8028 [delegate_ updateData];
8029}
8030
8031- (void) _updateIgnored {
8032 const char *package([name_ UTF8String]);
8033 bool on([ignoredSwitch_ isOn]);
8034
8035 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
8036 fwrite(package, strlen(package), 1, dpkg);
8037
8038 if (on)
8039 fwrite(" hold\n", 6, 1, dpkg);
8040 else
8041 fwrite(" install\n", 9, 1, dpkg);
8042
8043 pclose(dpkg);
8044}
8045
8046- (void) onIgnored:(id)control {
8047 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8048 [invocation setTarget:self];
8049 [invocation setSelector:@selector(_updateIgnored)];
8050
8051 [delegate_ reloadDataWithInvocation:invocation];
8052}
8053
8054- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8055 if (package_ == nil)
8056 return nil;
8057
8058 switch ([indexPath section]) {
8059 case 0: return subscribedCell_;
8060 case 1: return ignoredCell_;
8061
8062 _nodefault
8063 }
8064
8065 return nil;
8066}
8067
8068- (void) loadView {
8069 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8070 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8071 [self setView:view];
8072
8073 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8074 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8075 [(UITableView *) table_ setDataSource:self];
8076 [table_ setDelegate:self];
8077 [view addSubview:table_];
8078
8079 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8080 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8081 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8082
8083 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8084 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8085 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8086
8087 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8088 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8089 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8090 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8091
8092 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8093 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8094 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8095 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8096}
8097
8098- (void) viewDidLoad {
8099 [super viewDidLoad];
8100
8101 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8102}
8103
8104- (void) releaseSubviews {
8105 ignoredCell_ = nil;
8106 subscribedCell_ = nil;
8107 table_ = nil;
8108 ignoredSwitch_ = nil;
8109 subscribedSwitch_ = nil;
8110
8111 [super releaseSubviews];
8112}
8113
8114- (id) initWithDatabase:(Database *)database package:(NSString *)package {
8115 if ((self = [super init]) != nil) {
8116 database_ = database;
8117 name_ = package;
8118 } return self;
8119}
8120
8121- (void) reloadData {
8122 [super reloadData];
8123
8124 package_ = [database_ packageWithName:name_];
8125
8126 if (package_ != nil) {
8127 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8128 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8129 } // XXX: what now, G?
8130
8131 [table_ reloadData];
8132}
8133
8134@end
8135/* }}} */
8136
8137/* Installed Controller {{{ */
8138@interface InstalledController : FilteredPackageListController {
8139 bool sectioned_;
8140}
8141
8142- (id) initWithDatabase:(Database *)database;
8143- (void) queueStatusDidChange;
8144
8145@end
8146
8147@implementation InstalledController
8148
8149- (NSURL *) referrerURL {
8150 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8151}
8152
8153- (NSURL *) navigationURL {
8154 return [NSURL URLWithString:@"cydia://installed"];
8155}
8156
8157- (void) useRecent {
8158 sectioned_ = false;
8159
8160@synchronized (self) {
8161 [self setFilter:[](Package *package) {
8162 return ![package uninstalled] && package->role_ < 7;
8163 }];
8164
8165 [self setSorter:[](NSMutableArray *packages) {
8166 [packages radixSortUsingSelector:@selector(recent)];
8167 }];
8168} }
8169
8170- (void) useFilter:(UISegmentedControl *)segmented {
8171 NSInteger selected([segmented selectedSegmentIndex]);
8172 if (selected == 2)
8173 return [self useRecent];
8174 bool simple(selected == 0);
8175 sectioned_ = true;
8176
8177@synchronized (self) {
8178 [self setFilter:[=](Package *package) {
8179 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8180 }];
8181
8182 [self setSorter:nullptr];
8183} }
8184
8185- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8186 if (sectioned_)
8187 return [super sectionsForPackages:packages];
8188
8189 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8190
8191 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8192 Section *section(nil);
8193 time_t last(0);
8194
8195 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8196 Package *package([packages objectAtIndex:offset]);
8197
8198 time_t upgraded([package upgraded]);
8199 if (upgraded < 1168364520)
8200 upgraded = 0;
8201 else
8202 upgraded -= upgraded % (60 * 60 * 24);
8203
8204 if (section == nil || upgraded != last) {
8205 last = upgraded;
8206
8207 NSString *name;
8208 if (upgraded == 0)
8209 continue; // XXX: name = UCLocalize("...");
8210 else {
8211 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8212 [name autorelease];
8213 }
8214
8215 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8216 [sections addObject:section];
8217 }
8218
8219 [section addToCount];
8220 }
8221
8222 CFRelease(formatter);
8223 return sections;
8224}
8225
8226- (id) initWithDatabase:(Database *)database {
8227 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8228 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8229 [segmented setSelectedSegmentIndex:0];
8230 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8231 [[self navigationItem] setTitleView:segmented];
8232
8233 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8234 [self useFilter:segmented];
8235
8236 [self queueStatusDidChange];
8237 } return self;
8238}
8239
8240#if !AlwaysReload
8241- (void) queueButtonClicked {
8242 [delegate_ queue];
8243}
8244#endif
8245
8246- (void) queueStatusDidChange {
8247#if !AlwaysReload
8248 if (Queuing_) {
8249 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8250 initWithTitle:UCLocalize("QUEUE")
8251 style:UIBarButtonItemStyleDone
8252 target:self
8253 action:@selector(queueButtonClicked)
8254 ] autorelease]];
8255 } else {
8256 [[self navigationItem] setRightBarButtonItem:nil];
8257 }
8258#endif
8259}
8260
8261- (void) modeChanged:(UISegmentedControl *)segmented {
8262 [self useFilter:segmented];
8263 [self reloadData];
8264}
8265
8266@end
8267/* }}} */
8268
8269/* Source Cell {{{ */
8270@interface SourceCell : CyteTableViewCell <
8271 CyteTableViewCellDelegate,
8272 SourceDelegate
8273> {
8274 _H<Source, 1> source_;
8275 _H<NSURL> url_;
8276 _H<UIImage> icon_;
8277 _H<NSString> origin_;
8278 _H<NSString> label_;
8279 _H<UIActivityIndicatorView> indicator_;
8280}
8281
8282- (void) setSource:(Source *)source;
8283- (void) setFetch:(NSNumber *)fetch;
8284
8285@end
8286
8287@implementation SourceCell
8288
8289- (void) _setImage:(NSArray *)data {
8290 if ([url_ isEqual:[data objectAtIndex:0]]) {
8291 icon_ = [data objectAtIndex:1];
8292 [content_ setNeedsDisplay];
8293 }
8294}
8295
8296- (void) _setSource:(NSURL *) url {
8297 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8298
8299 if (NSData *data = [NSURLConnection
8300 sendSynchronousRequest:[NSURLRequest
8301 requestWithURL:url
8302 cachePolicy:NSURLRequestUseProtocolCachePolicy
8303 timeoutInterval:10
8304 ]
8305
8306 returningResponse:NULL
8307 error:NULL
8308 ])
8309 if (UIImage *image = [UIImage imageWithData:data])
8310 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8311
8312 [pool release];
8313}
8314
8315- (void) setSource:(Source *)source {
8316 source_ = source;
8317 [source_ setDelegate:self];
8318
8319 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8320
8321 icon_ = [UIImage imageNamed:@"unknown.png"];
8322
8323 origin_ = [source name];
8324 label_ = [source rooturi];
8325
8326 [content_ setNeedsDisplay];
8327
8328 url_ = [source iconURL];
8329 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8330}
8331
8332- (void) setAllSource {
8333 source_ = nil;
8334 [indicator_ stopAnimating];
8335
8336 icon_ = [UIImage imageNamed:@"folder.png"];
8337 origin_ = UCLocalize("ALL_SOURCES");
8338 label_ = UCLocalize("ALL_SOURCES_EX");
8339 [content_ setNeedsDisplay];
8340}
8341
8342- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8343 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8344 UIView *content([self contentView]);
8345 CGRect bounds([content bounds]);
8346
8347 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8348 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8349 [content_ setBackgroundColor:[UIColor whiteColor]];
8350 [content addSubview:content_];
8351
8352 [content_ setDelegate:self];
8353 [content_ setOpaque:YES];
8354
8355 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8356 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8357 [content addSubview:indicator_];
8358
8359 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8360 } return self;
8361}
8362
8363- (void) layoutSubviews {
8364 [super layoutSubviews];
8365
8366 UIView *content([self contentView]);
8367 CGRect bounds([content bounds]);
8368
8369 CGRect frame([indicator_ frame]);
8370 frame.origin.x = bounds.size.width - frame.size.width;
8371 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8372
8373 if (kCFCoreFoundationVersionNumber < 800)
8374 frame.origin.x -= 8;
8375 [indicator_ setFrame:frame];
8376}
8377
8378- (NSString *) accessibilityLabel {
8379 return origin_;
8380}
8381
8382- (void) drawContentRect:(CGRect)rect {
8383 bool highlighted(highlighted_);
8384 float width(rect.size.width);
8385
8386 if (icon_ != nil) {
8387 CGRect rect;
8388 rect.size = [(UIImage *) icon_ size];
8389
8390 while (rect.size.width > 32 || rect.size.height > 32) {
8391 rect.size.width /= 2;
8392 rect.size.height /= 2;
8393 }
8394
8395 rect.origin.x = 26 - rect.size.width / 2;
8396 rect.origin.y = 26 - rect.size.height / 2;
8397
8398 [icon_ drawInRect:Retina(rect)];
8399 }
8400
8401 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8402 UISetColor(White_);
8403
8404 if (!highlighted)
8405 UISetColor(Black_);
8406 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8407
8408 if (!highlighted)
8409 UISetColor(Gray_);
8410 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8411}
8412
8413- (void) setFetch:(NSNumber *)fetch {
8414 if ([fetch boolValue])
8415 [indicator_ startAnimating];
8416 else
8417 [indicator_ stopAnimating];
8418}
8419
8420@end
8421/* }}} */
8422/* Sources Controller {{{ */
8423@interface SourcesController : CyteViewController <
8424 UITableViewDataSource,
8425 UITableViewDelegate
8426> {
8427 _transient Database *database_;
8428 unsigned era_;
8429
8430 _H<UITableView, 2> list_;
8431 _H<NSMutableArray> sources_;
8432 int offset_;
8433
8434 _H<NSString> href_;
8435 _H<UIProgressHUD> hud_;
8436 _H<NSError> error_;
8437
8438 NSURLConnection *trivial_bz2_;
8439 NSURLConnection *trivial_gz_;
8440
8441 BOOL cydia_;
8442}
8443
8444- (id) initWithDatabase:(Database *)database;
8445- (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8446
8447@end
8448
8449@implementation SourcesController
8450
8451- (void) _releaseConnection:(NSURLConnection *)connection {
8452 if (connection != nil) {
8453 [connection cancel];
8454 //[connection setDelegate:nil];
8455 [connection release];
8456 }
8457}
8458
8459- (void) dealloc {
8460 [self _releaseConnection:trivial_gz_];
8461 [self _releaseConnection:trivial_bz2_];
8462
8463 [super dealloc];
8464}
8465
8466- (NSURL *) navigationURL {
8467 return [NSURL URLWithString:@"cydia://sources"];
8468}
8469
8470- (void) viewDidAppear:(BOOL)animated {
8471 [super viewDidAppear:animated];
8472 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8473}
8474
8475- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8476 return 2;
8477}
8478
8479- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8480 if (section == 1)
8481 return UCLocalize("INDIVIDUAL_SOURCES");
8482 return nil;
8483}
8484
8485- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8486 switch (section) {
8487 case 0: return 1;
8488 case 1: return [sources_ count];
8489 default: return 0;
8490 }
8491}
8492
8493- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8494@synchronized (database_) {
8495 if ([database_ era] != era_)
8496 return nil;
8497 if ([indexPath section] != 1)
8498 return nil;
8499 NSUInteger index([indexPath row]);
8500 if (index >= [sources_ count])
8501 return nil;
8502 return [sources_ objectAtIndex:index];
8503} }
8504
8505- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8506 static NSString *cellIdentifier = @"SourceCell";
8507
8508 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8509 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8510 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8511
8512 Source *source([self sourceAtIndexPath:indexPath]);
8513 if (source == nil)
8514 [cell setAllSource];
8515 else
8516 [cell setSource:source];
8517
8518 return cell;
8519}
8520
8521- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8522 SectionsController *controller([[[SectionsController alloc]
8523 initWithDatabase:database_
8524 source:[self sourceAtIndexPath:indexPath]
8525 ] autorelease]);
8526
8527 [controller setDelegate:delegate_];
8528 [[self navigationController] pushViewController:controller animated:YES];
8529}
8530
8531- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8532 if ([indexPath section] != 1)
8533 return false;
8534 Source *source = [self sourceAtIndexPath:indexPath];
8535 return [source record] != nil;
8536}
8537
8538- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8539 _assert([indexPath section] == 1);
8540 if (editingStyle == UITableViewCellEditingStyleDelete) {
8541 Source *source = [self sourceAtIndexPath:indexPath];
8542 if (source == nil) return;
8543
8544 [Sources_ removeObjectForKey:[source key]];
8545
8546 [delegate_ syncData];
8547 }
8548}
8549
8550- (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8551 [self updateButtonsForEditingStatusAnimated:YES];
8552}
8553
8554- (void) complete {
8555 [delegate_ addTrivialSource:href_];
8556 href_ = nil;
8557
8558 [delegate_ syncData];
8559}
8560
8561- (NSString *) getWarning {
8562 NSString *href(href_);
8563 NSRange colon([href rangeOfString:@"://"]);
8564 if (colon.location != NSNotFound)
8565 href = [href substringFromIndex:(colon.location + 3)];
8566 href = [href stringByAddingPercentEscapes];
8567 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8568
8569 NSURL *url([NSURL URLWithString:href]);
8570
8571 NSStringEncoding encoding;
8572 NSError *error(nil);
8573
8574 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8575 return [warning length] == 0 ? nil : warning;
8576 return nil;
8577}
8578
8579- (void) _endConnection:(NSURLConnection *)connection {
8580 // XXX: the memory management in this method is horribly awkward
8581
8582 NSURLConnection **field = NULL;
8583 if (connection == trivial_bz2_)
8584 field = &trivial_bz2_;
8585 else if (connection == trivial_gz_)
8586 field = &trivial_gz_;
8587 _assert(field != NULL);
8588 [connection release];
8589 *field = nil;
8590
8591 if (
8592 trivial_bz2_ == nil &&
8593 trivial_gz_ == nil
8594 ) {
8595 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8596
8597 [delegate_ releaseNetworkActivityIndicator];
8598
8599 [delegate_ removeProgressHUD:hud_];
8600 hud_ = nil;
8601
8602 if (cydia_) {
8603 if (warning != nil) {
8604 UIAlertView *alert = [[[UIAlertView alloc]
8605 initWithTitle:UCLocalize("SOURCE_WARNING")
8606 message:warning
8607 delegate:self
8608 cancelButtonTitle:UCLocalize("CANCEL")
8609 otherButtonTitles:
8610 UCLocalize("ADD_ANYWAY"),
8611 nil
8612 ] autorelease];
8613
8614 [alert setContext:@"warning"];
8615 [alert setNumberOfRows:1];
8616 [alert show];
8617
8618 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8619 error_ = nil;
8620 return;
8621 }
8622
8623 [self complete];
8624 } else if (error_ != nil) {
8625 UIAlertView *alert = [[[UIAlertView alloc]
8626 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8627 message:[error_ localizedDescription]
8628 delegate:self
8629 cancelButtonTitle:UCLocalize("OK")
8630 otherButtonTitles:nil
8631 ] autorelease];
8632
8633 [alert setContext:@"urlerror"];
8634 [alert show];
8635
8636 href_ = nil;
8637 } else {
8638 UIAlertView *alert = [[[UIAlertView alloc]
8639 initWithTitle:UCLocalize("NOT_REPOSITORY")
8640 message:UCLocalize("NOT_REPOSITORY_EX")
8641 delegate:self
8642 cancelButtonTitle:UCLocalize("OK")
8643 otherButtonTitles:nil
8644 ] autorelease];
8645
8646 [alert setContext:@"trivial"];
8647 [alert show];
8648
8649 href_ = nil;
8650 }
8651
8652 error_ = nil;
8653 }
8654}
8655
8656- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8657 switch ([response statusCode]) {
8658 case 200:
8659 cydia_ = YES;
8660 }
8661}
8662
8663- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8664 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8665 error_ = error;
8666 [self _endConnection:connection];
8667}
8668
8669- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8670 [self _endConnection:connection];
8671}
8672
8673- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8674 NSURL *url([NSURL URLWithString:href]);
8675
8676 NSMutableURLRequest *request = [NSMutableURLRequest
8677 requestWithURL:url
8678 cachePolicy:NSURLRequestUseProtocolCachePolicy
8679 timeoutInterval:10
8680 ];
8681
8682 [request setHTTPMethod:method];
8683
8684 if (Machine_ != NULL)
8685 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8686
8687 if (UniqueID_ != nil)
8688 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8689
8690 if ([url isCydiaSecure]) {
8691 if (UniqueID_ != nil)
8692 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8693 }
8694
8695 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8696}
8697
8698- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8699 NSString *context([alert context]);
8700
8701 if ([context isEqualToString:@"source"]) {
8702 switch (button) {
8703 case 1: {
8704 NSString *href = [[alert textField] text];
8705 href = VerifySource(href);
8706 if (href == nil)
8707 break;
8708 href_ = href;
8709
8710 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8711 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8712
8713 cydia_ = false;
8714
8715 // XXX: this is stupid
8716 hud_ = [delegate_ addProgressHUD];
8717 [hud_ setText:UCLocalize("VERIFYING_URL")];
8718 [delegate_ retainNetworkActivityIndicator];
8719 } break;
8720
8721 case 0:
8722 break;
8723
8724 _nodefault
8725 }
8726
8727 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8728 } else if ([context isEqualToString:@"trivial"])
8729 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8730 else if ([context isEqualToString:@"urlerror"])
8731 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8732 else if ([context isEqualToString:@"warning"]) {
8733 switch (button) {
8734 case 1:
8735 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8736 break;
8737
8738 case 0:
8739 break;
8740
8741 _nodefault
8742 }
8743
8744 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8745 }
8746}
8747
8748- (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8749 BOOL editing([list_ isEditing]);
8750
8751 if (editing)
8752 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8753 initWithTitle:UCLocalize("ADD")
8754 style:UIBarButtonItemStylePlain
8755 target:self
8756 action:@selector(addButtonClicked)
8757 ] autorelease] animated:animated];
8758 else if ([delegate_ updating])
8759 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8760 initWithTitle:UCLocalize("CANCEL")
8761 style:UIBarButtonItemStyleDone
8762 target:self
8763 action:@selector(cancelButtonClicked)
8764 ] autorelease] animated:animated];
8765 else
8766 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8767 initWithTitle:UCLocalize("REFRESH")
8768 style:UIBarButtonItemStylePlain
8769 target:self
8770 action:@selector(refreshButtonClicked)
8771 ] autorelease] animated:animated];
8772
8773 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8774 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8775 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8776 target:self
8777 action:@selector(editButtonClicked)
8778 ] autorelease] animated:animated];
8779}
8780
8781- (void) loadView {
8782 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8783 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8784 [list_ setRowHeight:53];
8785 [(UITableView *) list_ setDataSource:self];
8786 [list_ setDelegate:self];
8787 [self setView:list_];
8788}
8789
8790- (void) viewDidLoad {
8791 [super viewDidLoad];
8792
8793 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8794 [self updateButtonsForEditingStatusAnimated:NO];
8795}
8796
8797- (void) viewWillAppear:(BOOL)animated {
8798 [super viewWillAppear:animated];
8799
8800 [list_ setEditing:NO];
8801 [self updateButtonsForEditingStatusAnimated:NO];
8802}
8803
8804- (void) releaseSubviews {
8805 list_ = nil;
8806
8807 sources_ = nil;
8808
8809 [super releaseSubviews];
8810}
8811
8812- (id) initWithDatabase:(Database *)database {
8813 if ((self = [super init]) != nil) {
8814 database_ = database;
8815 } return self;
8816}
8817
8818- (void) reloadData {
8819 [super reloadData];
8820 [self updateButtonsForEditingStatusAnimated:YES];
8821
8822@synchronized (database_) {
8823 era_ = [database_ era];
8824
8825 sources_ = [NSMutableArray arrayWithCapacity:16];
8826 [sources_ addObjectsFromArray:[database_ sources]];
8827 _trace();
8828 [sources_ sortUsingSelector:@selector(compareByName:)];
8829 _trace();
8830
8831 int count([sources_ count]);
8832 offset_ = 0;
8833 for (int i = 0; i != count; i++) {
8834 if ([[sources_ objectAtIndex:i] record] == nil)
8835 break;
8836 offset_++;
8837 }
8838
8839 [list_ reloadData];
8840} }
8841
8842- (void) showAddSourcePrompt {
8843 UIAlertView *alert = [[[UIAlertView alloc]
8844 initWithTitle:UCLocalize("ENTER_APT_URL")
8845 message:nil
8846 delegate:self
8847 cancelButtonTitle:UCLocalize("CANCEL")
8848 otherButtonTitles:
8849 UCLocalize("ADD_SOURCE"),
8850 nil
8851 ] autorelease];
8852
8853 [alert setContext:@"source"];
8854
8855 [alert setNumberOfRows:1];
8856 [alert addTextFieldWithValue:@"http://" label:@""];
8857
8858 UITextInputTraits *traits = [[alert textField] textInputTraits];
8859 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8860 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8861 [traits setKeyboardType:UIKeyboardTypeURL];
8862 // XXX: UIReturnKeyDone
8863 [traits setReturnKeyType:UIReturnKeyNext];
8864
8865 [alert show];
8866}
8867
8868- (void) addButtonClicked {
8869 [self showAddSourcePrompt];
8870}
8871
8872- (void) refreshButtonClicked {
8873 if ([delegate_ requestUpdate])
8874 [self updateButtonsForEditingStatusAnimated:YES];
8875}
8876
8877- (void) cancelButtonClicked {
8878 [delegate_ cancelUpdate];
8879}
8880
8881- (void) editButtonClicked {
8882 [list_ setEditing:![list_ isEditing] animated:YES];
8883 [self updateButtonsForEditingStatusAnimated:YES];
8884}
8885
8886@end
8887/* }}} */
8888
8889/* Stash Controller {{{ */
8890@interface StashController : CyteViewController {
8891 _H<UIActivityIndicatorView> spinner_;
8892 _H<UILabel> status_;
8893 _H<UILabel> caption_;
8894}
8895
8896@end
8897
8898@implementation StashController
8899
8900- (void) loadView {
8901 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8902 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8903 [self setView:view];
8904
8905 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8906
8907 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8908 CGRect spinrect = [spinner_ frame];
8909 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8910 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8911 [spinner_ setFrame:spinrect];
8912 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8913 [view addSubview:spinner_];
8914 [spinner_ startAnimating];
8915
8916 CGRect captrect;
8917 captrect.size.width = [[self view] frame].size.width;
8918 captrect.size.height = 40.0f;
8919 captrect.origin.x = 0;
8920 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8921 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8922 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8923 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8924 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8925 [caption_ setTextColor:[UIColor whiteColor]];
8926 [caption_ setBackgroundColor:[UIColor clearColor]];
8927 [caption_ setShadowColor:[UIColor blackColor]];
8928 [caption_ setTextAlignment:NSTextAlignmentCenter];
8929 [view addSubview:caption_];
8930
8931 CGRect statusrect;
8932 statusrect.size.width = [[self view] frame].size.width;
8933 statusrect.size.height = 30.0f;
8934 statusrect.origin.x = 0;
8935 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8936 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8937 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8938 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8939 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8940 [status_ setTextColor:[UIColor whiteColor]];
8941 [status_ setBackgroundColor:[UIColor clearColor]];
8942 [status_ setShadowColor:[UIColor blackColor]];
8943 [status_ setTextAlignment:NSTextAlignmentCenter];
8944 [view addSubview:status_];
8945}
8946
8947- (void) releaseSubviews {
8948 spinner_ = nil;
8949 status_ = nil;
8950 caption_ = nil;
8951
8952 [super releaseSubviews];
8953}
8954
8955@end
8956/* }}} */
8957
8958@interface CYURLCache : SDURLCache {
8959}
8960
8961@end
8962
8963@implementation CYURLCache
8964
8965- (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8966#if !ForRelease
8967 if (false);
8968 else if ([event isEqualToString:@"no-cache"])
8969 event = @"!!!";
8970 else if ([event isEqualToString:@"store"])
8971 event = @">>>";
8972 else if ([event isEqualToString:@"invalid"])
8973 event = @"???";
8974 else if ([event isEqualToString:@"memory"])
8975 event = @"mem";
8976 else if ([event isEqualToString:@"disk"])
8977 event = @"ssd";
8978 else if ([event isEqualToString:@"miss"])
8979 event = @"---";
8980
8981 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8982#endif
8983}
8984
8985- (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8986 if (NSURLResponse *response = [cached response])
8987 if (NSString *mime = [response MIMEType])
8988 if ([mime isEqualToString:@"text/cache-manifest"]) {
8989 NSURL *url([response URL]);
8990
8991#if !ForRelease
8992 NSLog(@"###: %@", [url absoluteString]);
8993#endif
8994
8995 @synchronized (HostConfig_) {
8996 [CachedURLs_ addObject:url];
8997 }
8998 }
8999
9000 [super storeCachedResponse:cached forRequest:request];
9001}
9002
9003- (void) createDiskCachePath {
9004 [super createDiskCachePath];
9005}
9006
9007@end
9008
9009@interface Cydia : UIApplication <
9010 ConfirmationControllerDelegate,
9011 DatabaseDelegate,
9012 CydiaDelegate
9013> {
9014 _H<UIWindow> window_;
9015 _H<CydiaTabBarController> tabbar_;
9016 _H<CyteTabBarController> emulated_;
9017 _H<AppCacheController> appcache_;
9018
9019 _H<NSMutableArray> essential_;
9020 _H<NSMutableArray> broken_;
9021
9022 Database *database_;
9023
9024 _H<NSURL> starturl_;
9025
9026 unsigned locked_;
9027 unsigned activity_;
9028
9029 _H<StashController> stash_;
9030
9031 bool loaded_;
9032}
9033
9034- (void) loadData;
9035
9036@end
9037
9038@implementation Cydia
9039
9040- (void) lockSuspend {
9041 if (locked_++ == 0) {
9042 if ($SBSSetInterceptsMenuButtonForever != NULL)
9043 (*$SBSSetInterceptsMenuButtonForever)(true);
9044
9045 [self setIdleTimerDisabled:YES];
9046 }
9047}
9048
9049- (void) unlockSuspend {
9050 if (--locked_ == 0) {
9051 [self setIdleTimerDisabled:NO];
9052
9053 if ($SBSSetInterceptsMenuButtonForever != NULL)
9054 (*$SBSSetInterceptsMenuButtonForever)(false);
9055 }
9056}
9057
9058- (void) beginUpdate {
9059 [tabbar_ beginUpdate];
9060}
9061
9062- (void) cancelUpdate {
9063 [tabbar_ cancelUpdate];
9064}
9065
9066- (bool) requestUpdate {
9067 if (IsReachable("cydia.saurik.com")) {
9068 [self beginUpdate];
9069 return true;
9070 } else {
9071 UIAlertView *alert = [[[UIAlertView alloc]
9072 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9073 message:@"Host Unreachable" // XXX: Localize
9074 delegate:self
9075 cancelButtonTitle:UCLocalize("OK")
9076 otherButtonTitles:nil
9077 ] autorelease];
9078
9079 [alert setContext:@"norefresh"];
9080 [alert show];
9081
9082 return false;
9083 }
9084}
9085
9086- (BOOL) updating {
9087 return [tabbar_ updating];
9088}
9089
9090- (void) _loaded {
9091 if ([broken_ count] != 0) {
9092 int count = [broken_ count];
9093
9094 UIAlertView *alert = [[[UIAlertView alloc]
9095 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9096 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9097 delegate:self
9098 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9099 otherButtonTitles:
9100 UCLocalize("TEMPORARY_IGNORE"),
9101 nil
9102 ] autorelease];
9103
9104 [alert setContext:@"fixhalf"];
9105 [alert setNumberOfRows:2];
9106 [alert show];
9107 } else if (!Ignored_ && [essential_ count] != 0) {
9108 int count = [essential_ count];
9109
9110 UIAlertView *alert = [[[UIAlertView alloc]
9111 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9112 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9113 delegate:self
9114 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9115 otherButtonTitles:
9116 UCLocalize("UPGRADE_ESSENTIAL"),
9117 UCLocalize("COMPLETE_UPGRADE"),
9118 nil
9119 ] autorelease];
9120
9121 [alert setContext:@"upgrade"];
9122 [alert show];
9123 }
9124}
9125
9126- (void) returnToCydia {
9127 [self _loaded];
9128}
9129
9130- (void) reloadSpringBoard {
9131 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9132 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
9133 else
9134 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
9135 sleep(15);
9136 system("/usr/bin/killall backboardd SpringBoard");
9137}
9138
9139- (void) _saveConfig {
9140 SaveConfig(database_);
9141}
9142
9143// Navigation controller for the queuing badge.
9144- (UINavigationController *) queueNavigationController {
9145 NSArray *controllers = [tabbar_ viewControllers];
9146 return [controllers objectAtIndex:3];
9147}
9148
9149- (void) unloadData {
9150 [tabbar_ unloadData];
9151}
9152
9153- (void) _updateData {
9154 [self _saveConfig];
9155 [self unloadData];
9156
9157 UINavigationController *navigation = [self queueNavigationController];
9158
9159 id queuedelegate = nil;
9160 if ([[navigation viewControllers] count] > 0)
9161 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9162
9163 [queuedelegate queueStatusDidChange];
9164 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9165}
9166
9167- (void) _refreshIfPossible {
9168 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9169
9170 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9171
9172 bool recently = false;
9173 if (update != nil) {
9174 NSTimeInterval interval([update timeIntervalSinceNow]);
9175 if (interval > -(15*60))
9176 recently = true;
9177 }
9178
9179 // Don't automatic refresh if:
9180 // - We already refreshed recently.
9181 // - We already auto-refreshed this launch.
9182 // - Auto-refresh is disabled.
9183 // - Cydia's server is not reachable
9184 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9185 // If we are cancelling, we need to make sure it knows it's already loaded.
9186 loaded_ = true;
9187
9188 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9189 } else {
9190 // We are going to load, so remember that.
9191 loaded_ = true;
9192
9193 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9194 }
9195
9196 [pool release];
9197}
9198
9199- (void) refreshIfPossible {
9200 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9201}
9202
9203- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9204_profile(reloadDataWithInvocation)
9205@synchronized (self) {
9206 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9207 if (hud != nil)
9208 [hud setText:UCLocalize("RELOADING_DATA")];
9209
9210 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9211
9212 size_t changes(0);
9213
9214 [essential_ removeAllObjects];
9215 [broken_ removeAllObjects];
9216
9217 _profile(reloadDataWithInvocation$Essential)
9218 NSArray *packages([database_ packages]);
9219 for (Package *package in packages) {
9220 if ([package half])
9221 [broken_ addObject:package];
9222 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9223 if ([package essential] && [package installed] != nil)
9224 [essential_ addObject:package];
9225 ++changes;
9226 }
9227 }
9228 _end
9229
9230 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9231 if (changes != 0) {
9232 _trace();
9233 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9234 [changesItem setBadgeValue:badge];
9235 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9236 [self setApplicationIconBadgeNumber:changes];
9237 } else {
9238 _trace();
9239 [changesItem setBadgeValue:nil];
9240 [changesItem setAnimatedBadge:NO];
9241 [self setApplicationIconBadgeNumber:0];
9242 }
9243
9244 Queuing_ = false;
9245 [self _updateData];
9246
9247 if (hud != nil)
9248 [self removeProgressHUD:hud];
9249}
9250_end
9251
9252 PrintTimes();
9253}
9254
9255- (void) updateData {
9256 [self _updateData];
9257}
9258
9259- (void) updateDataAndLoad {
9260 [self _updateData];
9261 if ([database_ progressDelegate] == nil)
9262 [self _loaded];
9263}
9264
9265- (void) update_ {
9266 [database_ update];
9267 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9268}
9269
9270- (void) disemulate {
9271 if (emulated_ == nil)
9272 return;
9273
9274 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9275 [window_ setRootViewController:tabbar_];
9276 else {
9277 [window_ addSubview:[tabbar_ view]];
9278 [[emulated_ view] removeFromSuperview];
9279 }
9280
9281 emulated_ = nil;
9282 [window_ setUserInteractionEnabled:YES];
9283}
9284
9285- (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9286 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9287
9288 UIViewController *parent;
9289 if (emulated_ == nil)
9290 parent = tabbar_;
9291 else if (!force)
9292 parent = emulated_;
9293 else {
9294 [self disemulate];
9295 parent = tabbar_;
9296 }
9297
9298 if (IsWildcat_)
9299 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9300 [parent presentModalViewController:navigation animated:YES];
9301}
9302
9303- (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9304 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9305
9306 if (navigation != nil)
9307 [navigation pushViewController:progress animated:YES];
9308 else
9309 [self presentModalViewController:progress force:YES];
9310
9311 [progress invoke:invocation withTitle:title];
9312 return progress;
9313}
9314
9315- (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9316 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9317}
9318
9319- (void) repairWithInvocation:(NSInvocation *)invocation {
9320 _trace();
9321 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9322 _trace();
9323}
9324
9325- (void) repairWithSelector:(SEL)selector {
9326 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9327}
9328
9329- (void) reloadData {
9330 [self reloadDataWithInvocation:nil];
9331 if ([database_ progressDelegate] == nil)
9332 [self _loaded];
9333}
9334
9335- (void) syncData {
9336 [self _saveConfig];
9337 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9338}
9339
9340- (void) addSource:(NSDictionary *) source {
9341 CydiaAddSource(source);
9342}
9343
9344- (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9345 CydiaAddSource(href, distribution, sections);
9346}
9347
9348// XXX: this method should not return anything
9349- (BOOL) addTrivialSource:(NSString *)href {
9350 CydiaAddSource(href, @"./");
9351 return YES;
9352}
9353
9354- (void) resolve {
9355 pkgProblemResolver *resolver = [database_ resolver];
9356
9357 resolver->InstallProtect();
9358 if (!resolver->Resolve(true))
9359 _error->Discard();
9360}
9361
9362- (bool) perform {
9363 // XXX: this is a really crappy way of doing this.
9364 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9365 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9366 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9367 if ([tabbar_ updating])
9368 [tabbar_ cancelUpdate];
9369
9370 if (![database_ prepare])
9371 return false;
9372
9373 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9374 [page setDelegate:self];
9375 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9376
9377 if (IsWildcat_)
9378 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9379 [tabbar_ presentModalViewController:confirm_ animated:YES];
9380
9381 return true;
9382}
9383
9384- (void) queue {
9385 @synchronized (self) {
9386 [self perform];
9387 }
9388}
9389
9390- (void) clearPackage:(Package *)package {
9391 @synchronized (self) {
9392 [package clear];
9393 [self resolve];
9394 [self perform];
9395 }
9396}
9397
9398- (void) installPackages:(NSArray *)packages {
9399 @synchronized (self) {
9400 for (Package *package in packages)
9401 [package install];
9402 [self resolve];
9403 [self perform];
9404 }
9405}
9406
9407- (void) installPackage:(Package *)package {
9408 @synchronized (self) {
9409 [package install];
9410 [self resolve];
9411 [self perform];
9412 }
9413}
9414
9415- (void) removePackage:(Package *)package {
9416 @synchronized (self) {
9417 [package remove];
9418 [self resolve];
9419 [self perform];
9420 }
9421}
9422
9423- (void) distUpgrade {
9424 @synchronized (self) {
9425 if (![database_ upgrade])
9426 return;
9427 [self perform];
9428 }
9429}
9430
9431- (void) _uicache {
9432 _trace();
9433 system("/usr/bin/uicache");
9434 _trace();
9435}
9436
9437- (void) uicache {
9438 UIProgressHUD *hud([self addProgressHUD]);
9439 [hud setText:UCLocalize("LOADING")];
9440 [self yieldToSelector:@selector(_uicache)];
9441 [self removeProgressHUD:hud];
9442}
9443
9444- (void) perform_ {
9445 [database_ perform];
9446 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9447 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9448}
9449
9450- (void) confirmWithNavigationController:(UINavigationController *)navigation {
9451 Queuing_ = false;
9452 [self lockSuspend];
9453 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9454 [self unlockSuspend];
9455}
9456
9457- (void) retainNetworkActivityIndicator {
9458 if (activity_++ == 0)
9459 [self setNetworkActivityIndicatorVisible:YES];
9460
9461#if TraceLogging
9462 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9463#endif
9464}
9465
9466- (void) releaseNetworkActivityIndicator {
9467 if (--activity_ == 0)
9468 [self setNetworkActivityIndicatorVisible:NO];
9469
9470#if TraceLogging
9471 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9472#endif
9473
9474}
9475
9476- (void) cancelAndClear:(bool)clear {
9477 @synchronized (self) {
9478 if (clear) {
9479 [database_ clear];
9480 Queuing_ = false;
9481 } else {
9482 Queuing_ = true;
9483 }
9484
9485 [self _updateData];
9486 }
9487}
9488
9489- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9490 NSString *context([alert context]);
9491
9492 if ([context isEqualToString:@"conffile"]) {
9493 FILE *input = [database_ input];
9494 if (button == [alert cancelButtonIndex])
9495 fprintf(input, "N\n");
9496 else if (button == [alert firstOtherButtonIndex])
9497 fprintf(input, "Y\n");
9498 fflush(input);
9499
9500 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9501 } else if ([context isEqualToString:@"fixhalf"]) {
9502 if (button == [alert cancelButtonIndex]) {
9503 @synchronized (self) {
9504 for (Package *broken in (id) broken_) {
9505 [broken remove];
9506 NSString *id(ShellEscape([broken id]));
9507 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9508 " /var/lib/dpkg/info/%@.prerm"
9509 " /var/lib/dpkg/info/%@.postrm"
9510 " /var/lib/dpkg/info/%@.preinst"
9511 " /var/lib/dpkg/info/%@.postinst"
9512 " /var/lib/dpkg/info/%@.extrainst_"
9513 "", id, id, id, id, id] UTF8String]);
9514 }
9515
9516 [self resolve];
9517 [self perform];
9518 }
9519 } else if (button == [alert firstOtherButtonIndex]) {
9520 [broken_ removeAllObjects];
9521 [self _loaded];
9522 }
9523
9524 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9525 } else if ([context isEqualToString:@"upgrade"]) {
9526 if (button == [alert firstOtherButtonIndex]) {
9527 @synchronized (self) {
9528 for (Package *essential in (id) essential_)
9529 [essential install];
9530
9531 [self resolve];
9532 [self perform];
9533 }
9534 } else if (button == [alert firstOtherButtonIndex] + 1) {
9535 [self distUpgrade];
9536 } else if (button == [alert cancelButtonIndex]) {
9537 Ignored_ = YES;
9538 }
9539
9540 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9541 }
9542}
9543
9544- (void) system:(NSString *)command {
9545 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9546
9547 _trace();
9548 system([command UTF8String]);
9549 _trace();
9550
9551 [pool release];
9552}
9553
9554- (void) applicationWillSuspend {
9555 [database_ clean];
9556 [super applicationWillSuspend];
9557}
9558
9559- (BOOL) isSafeToSuspend {
9560 if (locked_ != 0) {
9561#if !ForRelease
9562 NSLog(@"isSafeToSuspend: locked_ != 0");
9563#endif
9564 return false;
9565 }
9566
9567 if ([tabbar_ modalViewController] != nil)
9568 return false;
9569
9570 // Use external process status API internally.
9571 // This is probably a really bad idea.
9572 // XXX: what is the point of this? does this solve anything at all?
9573 uint64_t status = 0;
9574 int notify_token;
9575 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9576 notify_get_state(notify_token, &status);
9577 notify_cancel(notify_token);
9578 }
9579
9580 if (status != 0) {
9581#if !ForRelease
9582 NSLog(@"isSafeToSuspend: status != 0");
9583#endif
9584 return false;
9585 }
9586
9587#if !ForRelease
9588 NSLog(@"isSafeToSuspend: -> true");
9589#endif
9590 return true;
9591}
9592
9593- (void) suspendReturningToLastApp:(BOOL)returning {
9594 if ([self isSafeToSuspend])
9595 [super suspendReturningToLastApp:returning];
9596}
9597
9598- (void) suspend {
9599 if ([self isSafeToSuspend])
9600 [super suspend];
9601}
9602
9603- (void) applicationSuspend {
9604 if ([self isSafeToSuspend])
9605 [super applicationSuspend];
9606}
9607
9608- (void) applicationSuspend:(__GSEvent *)event {
9609 if ([self isSafeToSuspend])
9610 [super applicationSuspend:event];
9611}
9612
9613- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9614 if ([self isSafeToSuspend])
9615 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9616}
9617
9618- (void) _setSuspended:(BOOL)value {
9619 if ([self isSafeToSuspend])
9620 [super _setSuspended:value];
9621}
9622
9623- (UIProgressHUD *) addProgressHUD {
9624 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9625 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9626
9627 [window_ setUserInteractionEnabled:NO];
9628
9629 UIViewController *target(tabbar_);
9630 if (UIViewController *modal = [target modalViewController])
9631 target = modal;
9632
9633 [hud showInView:[target view]];
9634
9635 [self lockSuspend];
9636 return hud;
9637}
9638
9639- (void) removeProgressHUD:(UIProgressHUD *)hud {
9640 [self unlockSuspend];
9641 [hud hide];
9642 [hud removeFromSuperview];
9643 [window_ setUserInteractionEnabled:YES];
9644}
9645
9646- (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9647 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9648}
9649
9650- (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9651 NSString *scheme([[url scheme] lowercaseString]);
9652 if ([[url absoluteString] length] <= [scheme length] + 3)
9653 return nil;
9654 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9655 NSArray *components([path componentsSeparatedByString:@"/"]);
9656
9657 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9658 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9659 if (controller != nil)
9660 [controller setDelegate:self];
9661 return controller;
9662 }
9663
9664 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9665 return nil;
9666
9667 NSString *base([components objectAtIndex:0]);
9668
9669 CyteViewController *controller = nil;
9670
9671 if ([base isEqualToString:@"url"]) {
9672 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9673 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9674 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9675 } else if (!external && [components count] == 1) {
9676 if ([base isEqualToString:@"sources"]) {
9677 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9678 }
9679
9680 if ([base isEqualToString:@"home"]) {
9681 controller = [[[HomeController alloc] init] autorelease];
9682 }
9683
9684 if ([base isEqualToString:@"sections"]) {
9685 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9686 }
9687
9688 if ([base isEqualToString:@"search"]) {
9689 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9690 }
9691
9692 if ([base isEqualToString:@"changes"]) {
9693 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9694 }
9695
9696 if ([base isEqualToString:@"installed"]) {
9697 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9698 }
9699 } else if ([components count] == 2) {
9700 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9701
9702 if ([base isEqualToString:@"package"]) {
9703 controller = [self pageForPackage:argument withReferrer:referrer];
9704 }
9705
9706 if (!external && [base isEqualToString:@"search"]) {
9707 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9708 }
9709
9710 if (!external && [base isEqualToString:@"sections"]) {
9711 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9712 argument = nil;
9713 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9714 }
9715
9716 if ([base isEqualToString:@"sources"]) {
9717 if ([argument isEqualToString:@"add"]) {
9718 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9719 [(SourcesController *)controller showAddSourcePrompt];
9720 } else {
9721 Source *source([database_ sourceWithKey:argument]);
9722 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9723 }
9724 }
9725
9726 if (!external && [base isEqualToString:@"launch"]) {
9727 [self launchApplicationWithIdentifier:argument suspended:NO];
9728 return nil;
9729 }
9730 } else if (!external && [components count] == 3) {
9731 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9732 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9733
9734 if ([base isEqualToString:@"package"]) {
9735 if ([arg2 isEqualToString:@"settings"]) {
9736 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9737 } else if ([arg2 isEqualToString:@"files"]) {
9738 if (Package *package = [database_ packageWithName:arg1]) {
9739 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9740 [(FileTable *)controller setPackage:package];
9741 }
9742 }
9743 }
9744
9745 if ([base isEqualToString:@"sections"]) {
9746 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9747 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9748 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9749 }
9750 }
9751
9752 [controller setDelegate:self];
9753 return controller;
9754}
9755
9756- (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9757 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9758
9759 if (page != nil)
9760 [tabbar_ setUnselectedViewController:page];
9761
9762 return page != nil;
9763}
9764
9765- (void) applicationOpenURL:(NSURL *)url {
9766 [super applicationOpenURL:url];
9767
9768 if (!loaded_)
9769 starturl_ = url;
9770 else
9771 [self openCydiaURL:url forExternal:YES];
9772}
9773
9774- (void) applicationWillResignActive:(UIApplication *)application {
9775 // Stop refreshing if you get a phone call or lock the device.
9776 if ([tabbar_ updating])
9777 [tabbar_ cancelUpdate];
9778
9779 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9780 [super applicationWillResignActive:application];
9781}
9782
9783- (void) saveState {
9784 [[NSDictionary dictionaryWithObjectsAndKeys:
9785 @"InterfaceState", [tabbar_ navigationURLCollection],
9786 @"LastClosed", [NSDate date],
9787 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9788 nil] writeToFile:@ SavedState_ atomically:YES];
9789
9790 [self _saveConfig];
9791}
9792
9793- (void) applicationWillTerminate:(UIApplication *)application {
9794 [self saveState];
9795}
9796
9797- (void) applicationDidEnterBackground:(UIApplication *)application {
9798 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9799 return [self terminateWithSuccess];
9800 Backgrounded_ = [NSDate date];
9801 [self saveState];
9802}
9803
9804- (void) applicationWillEnterForeground:(UIApplication *)application {
9805 if (Backgrounded_ == nil)
9806 return;
9807
9808 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9809
9810 if (interval <= -(30*60)) {
9811 [tabbar_ setSelectedIndex:0];
9812 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9813 }
9814
9815 if (interval <= -(15*60)) {
9816 if (IsReachable("cydia.saurik.com")) {
9817 [tabbar_ beginUpdate];
9818 [appcache_ reloadURLWithCache:YES];
9819 }
9820 }
9821
9822 if ([database_ delocked])
9823 [self reloadData];
9824}
9825
9826- (void) setConfigurationData:(NSString *)data {
9827 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9828
9829 if (!conffile_r(data)) {
9830 lprintf("E:invalid conffile\n");
9831 return;
9832 }
9833
9834 NSString *ofile = conffile_r[1];
9835 //NSString *nfile = conffile_r[2];
9836
9837 UIAlertView *alert = [[[UIAlertView alloc]
9838 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9839 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9840 delegate:self
9841 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9842 otherButtonTitles:
9843 UCLocalize("ACCEPT_NEW_COPY"),
9844 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9845 nil
9846 ] autorelease];
9847
9848 [alert setContext:@"conffile"];
9849 [alert setNumberOfRows:2];
9850 [alert show];
9851}
9852
9853- (void) addStashController {
9854 [self lockSuspend];
9855 stash_ = [[[StashController alloc] init] autorelease];
9856 [window_ addSubview:[stash_ view]];
9857}
9858
9859- (void) removeStashController {
9860 [[stash_ view] removeFromSuperview];
9861 stash_ = nil;
9862 [self unlockSuspend];
9863}
9864
9865- (void) stash {
9866 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9867 UpdateExternalStatus(1);
9868 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9869 UpdateExternalStatus(0);
9870
9871 [self removeStashController];
9872 [self reloadSpringBoard];
9873}
9874
9875- (void) setupViewControllers {
9876 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9877
9878 NSMutableArray *items;
9879 if (kCFCoreFoundationVersionNumber < 800) {
9880 items = [NSMutableArray arrayWithObjects:
9881 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9882 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9883 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9884 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9885 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9886 nil];
9887 } else {
9888 items = [NSMutableArray arrayWithObjects:
9889 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9890 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9891 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9892 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9893 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9894 nil];
9895 }
9896
9897 NSMutableArray *controllers([NSMutableArray array]);
9898 for (UITabBarItem *item in items) {
9899 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9900 [controller setTabBarItem:item];
9901 [controllers addObject:controller];
9902 }
9903 [tabbar_ setViewControllers:controllers];
9904
9905 [tabbar_ setUpdateDelegate:self];
9906}
9907
9908- (void) _sendMemoryWarningNotification {
9909 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9910 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9911 else
9912 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9913}
9914
9915- (void) _sendMemoryWarningNotifications {
9916 while (true) {
9917 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9918 sleep(2);
9919 //usleep(2000000);
9920 }
9921}
9922
9923- (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9924 NSLog(@"--");
9925 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9926}
9927
9928- (void) applicationDidFinishLaunching:(id)unused {
9929 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9930
9931_trace();
9932 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9933 [self setApplicationSupportsShakeToEdit:NO];
9934
9935 @synchronized (HostConfig_) {
9936 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9937 }
9938
9939 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9940 initWithMemoryCapacity:524288
9941 diskCapacity:10485760
9942 diskPath:Cache("SDURLCache")
9943 ] autorelease]];
9944
9945 [CydiaWebViewController _initialize];
9946
9947 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9948
9949 // this would disallow http{,s} URLs from accessing this data
9950 //[WebView registerURLSchemeAsLocal:@"cydia"];
9951
9952 Font12_ = [UIFont systemFontOfSize:12];
9953 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9954 Font14_ = [UIFont systemFontOfSize:14];
9955 Font18_ = [UIFont systemFontOfSize:18];
9956 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9957 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9958
9959 essential_ = [NSMutableArray arrayWithCapacity:4];
9960 broken_ = [NSMutableArray arrayWithCapacity:4];
9961
9962 // XXX: I really need this thing... like, seriously... I'm sorry
9963 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9964 [appcache_ reloadData];
9965
9966 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9967 [window_ orderFront:self];
9968 [window_ makeKey:self];
9969 [window_ setHidden:NO];
9970
9971 if (access("/.cydia_no_stash", F_OK) == 0);
9972 else {
9973
9974 if (false) stash: {
9975 [self addStashController];
9976 // XXX: this would be much cleaner as a yieldToSelector:
9977 // that way the removeStashController could happen right here inline
9978 // we also could no longer require the useless stash_ field anymore
9979 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9980 return;
9981 }
9982
9983 struct stat root;
9984 int error(stat("/", &root));
9985 _assert(error != -1);
9986
9987 #define Stash_(path) do { \
9988 struct stat folder; \
9989 int error(lstat((path), &folder)); \
9990 if (error != -1 && ( \
9991 folder.st_dev == root.st_dev && \
9992 S_ISDIR(folder.st_mode) \
9993 ) || error == -1 && ( \
9994 errno == ENOENT || \
9995 errno == ENOTDIR \
9996 )) goto stash; \
9997 } while (false)
9998
9999 Stash_("/Applications");
10000 Stash_("/Library/Ringtones");
10001 Stash_("/Library/Wallpaper");
10002 //Stash_("/usr/bin");
10003 Stash_("/usr/include");
10004 Stash_("/usr/share");
10005 //Stash_("/var/lib");
10006
10007 }
10008
10009 database_ = [Database sharedInstance];
10010 [database_ setDelegate:self];
10011
10012 [window_ setUserInteractionEnabled:NO];
10013 [self setupViewControllers];
10014
10015 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
10016 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
10017 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
10018
10019 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
10020 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
10021 [emulated_ setSelectedIndex:0];
10022
10023 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
10024 [emulated_ concealTabBarSelection];
10025
10026 if ([window_ respondsToSelector:@selector(setRootViewController:)])
10027 [window_ setRootViewController:emulated_];
10028 else
10029 [window_ addSubview:[emulated_ view]];
10030
10031 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10032_trace();
10033}
10034
10035- (NSArray *) defaultStartPages {
10036 NSMutableArray *standard = [NSMutableArray array];
10037 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10038 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10039 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10040 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10041 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10042 return standard;
10043}
10044
10045- (void) loadData {
10046_trace();
10047 if ([emulated_ modalViewController] != nil)
10048 [emulated_ dismissModalViewControllerAnimated:YES];
10049 [window_ setUserInteractionEnabled:NO];
10050
10051 [self reloadDataWithInvocation:nil];
10052 [self refreshIfPossible];
10053 [self disemulate];
10054
10055 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10056
10057 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10058 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10059 int standardIndex = 0;
10060 NSArray *standard = [self defaultStartPages];
10061
10062 BOOL valid = YES;
10063
10064 if (saved == nil)
10065 valid = NO;
10066
10067 NSDate *closed = [state objectForKey:@"LastClosed"];
10068 if (valid && closed != nil) {
10069 NSTimeInterval interval([closed timeIntervalSinceNow]);
10070 if (interval <= -(30*60))
10071 valid = NO;
10072 }
10073
10074 if (valid && [saved count] != [standard count])
10075 valid = NO;
10076
10077 if (valid) {
10078 for (unsigned int i = 0; i < [standard count]; i++) {
10079 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10080 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10081 // but it's good enough for now.
10082 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10083 valid = NO;
10084 break;
10085 }
10086 }
10087 }
10088
10089 NSArray *items = nil;
10090 if (valid) {
10091 [tabbar_ setSelectedIndex:savedIndex];
10092 items = saved;
10093 } else {
10094 [tabbar_ setSelectedIndex:standardIndex];
10095 items = standard;
10096 }
10097
10098 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10099 NSArray *stack = [items objectAtIndex:tab];
10100 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10101 NSMutableArray *current = [NSMutableArray array];
10102
10103 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10104 NSString *addr = [stack objectAtIndex:nav];
10105 NSURL *url = [NSURL URLWithString:addr];
10106 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10107 if (page != nil)
10108 [current addObject:page];
10109 }
10110
10111 [navigation setViewControllers:current];
10112 }
10113
10114 // (Try to) show the startup URL.
10115 if (starturl_ != nil) {
10116 [self openCydiaURL:starturl_ forExternal:YES];
10117 starturl_ = nil;
10118 }
10119}
10120
10121- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10122 if (!IsWildcat_) {
10123 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10124 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10125 }
10126
10127 if (item != nil && IsWildcat_) {
10128 [sheet showFromBarButtonItem:item animated:YES];
10129 } else {
10130 [sheet showInView:window_];
10131 }
10132}
10133
10134- (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10135 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10136 [progress setTitle:task];
10137 [progress addProgressEvent:event];
10138}
10139
10140- (void) addProgressEventForTask:(NSArray *)data {
10141 CydiaProgressEvent *event([data objectAtIndex:0]);
10142 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10143 [self addProgressEvent:event forTask:task];
10144}
10145
10146- (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10147 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10148}
10149
10150@end
10151
10152/*IMP alloc_;
10153id Alloc_(id self, SEL selector) {
10154 id object = alloc_(self, selector);
10155 lprintf("[%s]A-%p\n", self->isa->name, object);
10156 return object;
10157}*/
10158
10159/*IMP dealloc_;
10160id Dealloc_(id self, SEL selector) {
10161 id object = dealloc_(self, selector);
10162 lprintf("[%s]D-%p\n", self->isa->name, object);
10163 return object;
10164}*/
10165
10166Class $NSURLConnection;
10167
10168MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10169 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10170
10171 NSURL *url([copy URL]);
10172
10173 NSString *host([url host]);
10174 NSString *scheme([[url scheme] lowercaseString]);
10175
10176 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10177
10178 @synchronized (HostConfig_) {
10179 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10180 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10181 [copy setHTTPShouldUsePipelining:YES];
10182
10183 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10184 if ([control isEqualToString:@"max-age=0"])
10185 if ([CachedURLs_ containsObject:url]) {
10186#if !ForRelease
10187 NSLog(@"~~~: %@", url);
10188#endif
10189
10190 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10191
10192 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10193 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10194 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10195 }
10196 }
10197
10198 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10199 } return self;
10200}
10201
10202Class $WAKWindow;
10203
10204static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10205 CGSize size([[UIScreen mainScreen] bounds].size);
10206 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10207 if ([$WAKWindow hasLandscapeOrientation])
10208 std::swap(size.width, size.height);*/
10209 return size;
10210}
10211
10212Class $NSUserDefaults;
10213
10214MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10215 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10216 return Cache("LocalStorage");
10217 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10218}
10219
10220static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10221 if (type == NULL)
10222 return nil;
10223 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10224 return nil;
10225 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10226 CFRelease(type);
10227 return [(NSMutableDictionary *) copy autorelease];
10228}
10229
10230int main_store(int, char *argv[]);
10231
10232int main(int argc, char *argv[]) {
10233#ifdef __arm64__
10234 const char *argv0(argv[0]);
10235 if (const char *slash = strrchr(argv0, '/'))
10236 argv0 = slash + 1;
10237 if (false);
10238 else if (!strcmp(argv0, "store"))
10239 return main_store(argc, argv);
10240#endif
10241
10242 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10243 dup2(fd, 2);
10244 close(fd);
10245
10246 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10247
10248 _trace();
10249
10250 UpdateExternalStatus(0);
10251
10252 UIScreen *screen([UIScreen mainScreen]);
10253 if ([screen respondsToSelector:@selector(scale)])
10254 ScreenScale_ = [screen scale];
10255 else
10256 ScreenScale_ = 1;
10257
10258 UIDevice *device([UIDevice currentDevice]);
10259 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10260 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10261 if (idiom == UIUserInterfaceIdiomPad)
10262 IsWildcat_ = true;
10263 }
10264
10265 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10266
10267 RegEx pattern("([0-9]+\\.[0-9]+).*");
10268
10269 if (pattern([device systemVersion]))
10270 Firmware_ = pattern[1];
10271 if (pattern(Cydia_))
10272 Major_ = pattern[1];
10273
10274 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10275
10276 HostConfig_ = [[[NSObject alloc] init] autorelease];
10277 @synchronized (HostConfig_) {
10278 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10279 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10280 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10281 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10282 }
10283
10284 NSString *ui(@"ui/ios");
10285 if (Idiom_ != nil)
10286 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10287 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10288 UI_ = CydiaURL(ui);
10289
10290 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10291
10292 /* Library Hacks {{{ */
10293 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10294
10295 $WAKWindow = objc_getClass("WAKWindow");
10296 if ($WAKWindow != NULL)
10297 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10298 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10299
10300 $NSURLConnection = objc_getClass("NSURLConnection");
10301 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10302 if (NSURLConnection$init$ != NULL) {
10303 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10304 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10305 }
10306
10307 $NSUserDefaults = objc_getClass("NSUserDefaults");
10308 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10309 if (NSUserDefaults$objectForKey$ != NULL) {
10310 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10311 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10312 }
10313 /* }}} */
10314 /* Set Locale {{{ */
10315 Locale_ = CFLocaleCopyCurrent();
10316 Languages_ = [NSLocale preferredLanguages];
10317
10318 std::string languages;
10319 const char *translation(NULL);
10320
10321 // XXX: this isn't really a language, but this is compatible with older Cydia builds
10322 if (Locale_ != NULL)
10323 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
10324 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10325 if (pattern(language)) {
10326 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
10327 languages += translation;
10328 languages += ",";
10329 }
10330 }
10331
10332 if (Languages_ != nil)
10333 for (NSString *language : Languages_) {
10334 languages += [language UTF8String];
10335 languages += ",";
10336 }
10337
10338 languages += "en";
10339 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10340 /* }}} */
10341 /* Index Collation {{{ */
10342 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10343 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10344 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10345 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10346 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10347 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10348
10349 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10350
10351 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10352 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10353 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})
10354 CollationOffset_.push_back(offset);
10355 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];
10356 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];
10357 } else {
10358
10359 CollationThumbs_ = [collation sectionIndexTitles];
10360 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10361 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10362
10363 CollationTitles_ = [collation sectionTitles];
10364 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10365
10366 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10367 if (&transform != NULL && transform != nil) {
10368 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10369 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10370 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10371 UErrorCode code(U_ZERO_ERROR);
10372 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10373 if (!U_SUCCESS(code))
10374 NSLog(@"%s", u_errorName(code));
10375 }
10376
10377 }
10378 } @catch (NSException *e) {
10379 NSLog(@"%@", e);
10380 goto hard;
10381 } } else hard: {
10382 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10383
10384 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];
10385 for (NSInteger offset(0); offset != 28; ++offset)
10386 CollationOffset_.push_back(offset);
10387
10388 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];
10389 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];
10390 }
10391 /* }}} */
10392 /* Parse Arguments {{{ */
10393 bool substrate(false);
10394
10395 if (argc != 0) {
10396 char **args(argv);
10397 int arge(1);
10398
10399 for (int argi(1); argi != argc; ++argi)
10400 if (strcmp(argv[argi], "--") == 0) {
10401 arge = argi;
10402 argv[argi] = argv[0];
10403 argv += argi;
10404 argc -= argi;
10405 break;
10406 }
10407
10408 for (int argi(1); argi != arge; ++argi)
10409 if (strcmp(args[argi], "--substrate") == 0)
10410 substrate = true;
10411 else
10412 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10413 }
10414 /* }}} */
10415
10416 App_ = [[NSBundle mainBundle] bundlePath];
10417 Advanced_ = YES;
10418
10419 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10420 mkdir([Cache_ UTF8String], 0755);
10421
10422 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10423 alloc_ = alloc->method_imp;
10424 alloc->method_imp = (IMP) &Alloc_;*/
10425
10426 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10427 dealloc_ = dealloc->method_imp;
10428 dealloc->method_imp = (IMP) &Dealloc_;*/
10429
10430 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10431 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10432
10433 /* System Information {{{ */
10434 size_t size;
10435
10436 int maxproc;
10437 size = sizeof(maxproc);
10438 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10439 perror("sysctlbyname(\"kern.maxproc\", ?)");
10440 else if (maxproc < 64) {
10441 maxproc = 64;
10442 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10443 perror("sysctlbyname(\"kern.maxproc\", #)");
10444 }
10445
10446 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10447 char *osversion = new char[size];
10448 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10449 perror("sysctlbyname(\"kern.osversion\", ?)");
10450 else
10451 System_ = [NSString stringWithUTF8String:osversion];
10452
10453 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10454 char *machine = new char[size];
10455 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10456 perror("sysctlbyname(\"hw.machine\", ?)");
10457 else
10458 Machine_ = machine;
10459
10460 int64_t usermem(0);
10461 size = sizeof(usermem);
10462 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10463 usermem = 0;
10464
10465 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10466 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10467 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10468
10469 UniqueID_ = UniqueIdentifier(device);
10470
10471 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10472 Product_ = [info objectForKey:@"SafariProductVersion"];
10473 Safari_ = [info objectForKey:@"CFBundleVersion"];
10474 }
10475
10476 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10477
10478 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10479 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10480 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10481 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10482 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10483 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10484
10485 UserAgent_ = agent;
10486 /* }}} */
10487 /* Load Database {{{ */
10488 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10489
10490 _trace();
10491 mkdir("/var/mobile/Library/Cydia", 0755);
10492 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10493 _trace();
10494
10495 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10496 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10497 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10498 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10499
10500 _trace();
10501 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10502
10503 if (Values_ == nil)
10504 Values_ = [metadata objectForKey:@"Values"];
10505 if (Values_ == nil)
10506 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10507
10508 if (Sections_ == nil)
10509 Sections_ = [metadata objectForKey:@"Sections"];
10510 if (Sections_ == nil)
10511 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10512
10513 if (Sources_ == nil)
10514 Sources_ = [metadata objectForKey:@"Sources"];
10515 if (Sources_ == nil)
10516 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10517
10518 // XXX: this wrong, but in a way that doesn't matter :/
10519 if (Version_ == nil)
10520 Version_ = [metadata objectForKey:@"Version"];
10521 if (Version_ == nil)
10522 Version_ = [NSNumber numberWithUnsignedInt:0];
10523
10524 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10525 bool fail(false);
10526 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10527 _trace();
10528 if (fail)
10529 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10530 }
10531
10532 if ([Version_ unsignedIntValue] == 0) {
10533 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10534 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10535 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10536 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10537
10538 Version_ = [NSNumber numberWithUnsignedInt:1];
10539
10540 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10541 [cache removeObjectForKey:@"LastUpdate"];
10542 [cache writeToFile:@ CacheState_ atomically:YES];
10543 }
10544 }
10545
10546 _H<NSMutableArray> broken([NSMutableArray array]);
10547 for (NSString *key in (id) Sources_)
10548 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10549 [broken addObject:key];
10550 if ([broken count] != 0)
10551 for (NSString *key in (id) broken)
10552 [Sources_ removeObjectForKey:key];
10553 broken = nil;
10554
10555 SaveConfig(nil);
10556 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10557 /* }}} */
10558
10559 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10560
10561 if (kCFCoreFoundationVersionNumber > 1000)
10562 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10563
10564 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10565
10566 if (access("/User", F_OK) != 0 || version != 6) {
10567 _trace();
10568 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10569 _trace();
10570 }
10571
10572 if (access("/tmp/cydia.chk", F_OK) == 0) {
10573 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10574 _assert(errno == ENOENT);
10575 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10576 _assert(errno == ENOENT);
10577 }
10578
10579 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10580
10581 /* APT Initialization {{{ */
10582 _assert(pkgInitConfig(*_config));
10583 _assert(pkgInitSystem(*_config, _system));
10584
10585 _config->Set("Acquire::AllowInsecureRepositories", true);
10586 _config->Set("Acquire::Check-Valid-Until", false);
10587 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10588
10589 _config->Set("pkgCacheGen::ForceEssential", "");
10590
10591 if (translation != NULL)
10592 _config->Set("APT::Acquire::Translation", translation);
10593 _config->Set("Acquire::Languages", languages);
10594
10595 // XXX: this timeout might be important :(
10596 //_config->Set("Acquire::http::Timeout", 15);
10597
10598 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10599
10600 mkdir([Cache("archives") UTF8String], 0755);
10601 mkdir([Cache("archives/partial") UTF8String], 0755);
10602 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10603
10604 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10605 _config->Set("Dir::State", [Cache_ UTF8String]);
10606
10607 mkdir([Cache("lists") UTF8String], 0755);
10608 mkdir([Cache("lists/partial") UTF8String], 0755);
10609 mkdir([Cache("periodic") UTF8String], 0755);
10610 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10611
10612 std::string logs("/var/mobile/Library/Logs/Cydia");
10613 mkdir(logs.c_str(), 0755);
10614 _config->Set("Dir::Log", logs);
10615
10616 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10617 /* }}} */
10618 /* Color Choices {{{ */
10619 space_ = CGColorSpaceCreateDeviceRGB();
10620
10621 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10622 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10623 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10624 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10625 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10626 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10627 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10628 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10629 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10630 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10631
10632 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10633 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10634 /* }}}*/
10635 /* UIKit Configuration {{{ */
10636 // XXX: I have a feeling this was important
10637 //UIKeyboardDisableAutomaticAppearance();
10638 /* }}} */
10639
10640 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10641 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10642
10643 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10644 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10645 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10646
10647 PulseInterval_ = fast ? 50000 : 500000;
10648
10649 Colon_ = UCLocalize("COLON_DELIMITED");
10650 Elision_ = UCLocalize("ELISION");
10651 Error_ = UCLocalize("ERROR");
10652 Warning_ = UCLocalize("WARNING");
10653
10654 _trace();
10655 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10656
10657 CGColorSpaceRelease(space_);
10658 CFRelease(Locale_);
10659
10660 [pool release];
10661 return value;
10662}