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