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