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