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