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