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