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