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