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