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