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