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