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