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