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