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