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