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