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