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