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