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