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