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