]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Do not draw null package cells.
[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 [super releaseSubviews];
5735 }
5736
5737 - (id) initWithDatabase:(Database *)database {
5738 if ((self = [super init]) != nil) {
5739 database_ = database;
5740
5741 files_ = [NSMutableArray arrayWithCapacity:32];
5742 } return self;
5743 }
5744
5745 - (void) setPackage:(Package *)package {
5746 package_ = nil;
5747 name_ = nil;
5748
5749 [files_ removeAllObjects];
5750
5751 if (package != nil) {
5752 package_ = package;
5753 name_ = [package id];
5754
5755 if (NSArray *files = [package files])
5756 [files_ addObjectsFromArray:files];
5757
5758 if ([files_ count] != 0) {
5759 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5760 [files_ removeObjectAtIndex:0];
5761 [files_ sortUsingSelector:@selector(compareByPath:)];
5762
5763 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5764 [stack addObject:@"/"];
5765
5766 for (int i(0), e([files_ count]); i != e; ++i) {
5767 NSString *file = [files_ objectAtIndex:i];
5768 while (![file hasPrefix:[stack lastObject]])
5769 [stack removeLastObject];
5770 NSString *directory = [stack lastObject];
5771 [stack addObject:[file stringByAppendingString:@"/"]];
5772 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5773 ([stack count] - 2) * 3, "",
5774 [file substringFromIndex:[directory length]]
5775 ]];
5776 }
5777 }
5778 }
5779
5780 [list_ reloadData];
5781 }
5782
5783 - (void) reloadData {
5784 [super reloadData];
5785
5786 [self setPackage:[database_ packageWithName:name_]];
5787 }
5788
5789 @end
5790 /* }}} */
5791 /* Package Controller {{{ */
5792 @interface CYPackageController : CydiaWebViewController <
5793 UIActionSheetDelegate
5794 > {
5795 _transient Database *database_;
5796 _H<Package> package_;
5797 _H<NSString> name_;
5798 bool commercial_;
5799 _H<NSMutableArray> buttons_;
5800 _H<UIBarButtonItem> button_;
5801 }
5802
5803 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5804
5805 @end
5806
5807 @implementation CYPackageController
5808
5809 - (NSURL *) navigationURL {
5810 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5811 }
5812
5813 /* XXX: this is not safe at all... localization of /fail/ */
5814 - (void) _clickButtonWithName:(NSString *)name {
5815 if ([name isEqualToString:UCLocalize("CLEAR")])
5816 [delegate_ clearPackage:package_];
5817 else if ([name isEqualToString:UCLocalize("INSTALL")])
5818 [delegate_ installPackage:package_];
5819 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5820 [delegate_ installPackage:package_];
5821 else if ([name isEqualToString:UCLocalize("REMOVE")])
5822 [delegate_ removePackage:package_];
5823 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5824 [delegate_ installPackage:package_];
5825 else _assert(false);
5826 }
5827
5828 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5829 NSString *context([sheet context]);
5830
5831 if ([context isEqualToString:@"modify"]) {
5832 if (button != [sheet cancelButtonIndex]) {
5833 NSString *buttonName = [buttons_ objectAtIndex:button];
5834 [self _clickButtonWithName:buttonName];
5835 }
5836
5837 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5838 }
5839 }
5840
5841 - (bool) _allowJavaScriptPanel {
5842 return commercial_;
5843 }
5844
5845 #if !AlwaysReload
5846 - (void) _customButtonClicked {
5847 int count([buttons_ count]);
5848 if (count == 0)
5849 return;
5850
5851 if (count == 1)
5852 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5853 else {
5854 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5855 [buttons addObjectsFromArray:buttons_];
5856
5857 UIActionSheet *sheet = [[[UIActionSheet alloc]
5858 initWithTitle:nil
5859 delegate:self
5860 cancelButtonTitle:nil
5861 destructiveButtonTitle:nil
5862 otherButtonTitles:nil
5863 ] autorelease];
5864
5865 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5866 if (!IsWildcat_) {
5867 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5868 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5869 }
5870 [sheet setContext:@"modify"];
5871
5872 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5873 }
5874 }
5875
5876 // We don't want to allow non-commercial packages to do custom things to the install button,
5877 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5878 - (void) customButtonClicked {
5879 if (commercial_)
5880 [super customButtonClicked];
5881 else
5882 [self _customButtonClicked];
5883 }
5884
5885 - (void) reloadButtonClicked {
5886 // Don't reload a commerical package by tapping the loading button,
5887 // but if it's not an Install button, we should forward it on.
5888 if (![package_ uninstalled])
5889 [self _customButtonClicked];
5890 }
5891
5892 - (void) applyLoadingTitle {
5893 // Don't show "Loading" as the title. Ever.
5894 }
5895
5896 - (UIBarButtonItem *) rightButton {
5897 return button_;
5898 }
5899 #endif
5900
5901 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5902 if ((self = [super init]) != nil) {
5903 database_ = database;
5904 buttons_ = [NSMutableArray arrayWithCapacity:4];
5905 name_ = [NSString stringWithString:name];
5906 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5907 } return self;
5908 }
5909
5910 - (void) reloadData {
5911 [super reloadData];
5912
5913 package_ = [database_ packageWithName:name_];
5914
5915 [buttons_ removeAllObjects];
5916
5917 if (package_ != nil) {
5918 [(Package *) package_ parse];
5919
5920 commercial_ = [package_ isCommercial];
5921
5922 if ([package_ mode] != nil)
5923 [buttons_ addObject:UCLocalize("CLEAR")];
5924 if ([package_ source] == nil);
5925 else if ([package_ upgradableAndEssential:NO])
5926 [buttons_ addObject:UCLocalize("UPGRADE")];
5927 else if ([package_ uninstalled])
5928 [buttons_ addObject:UCLocalize("INSTALL")];
5929 else
5930 [buttons_ addObject:UCLocalize("REINSTALL")];
5931 if (![package_ uninstalled])
5932 [buttons_ addObject:UCLocalize("REMOVE")];
5933 }
5934
5935 NSString *title;
5936 switch ([buttons_ count]) {
5937 case 0: title = nil; break;
5938 case 1: title = [buttons_ objectAtIndex:0]; break;
5939 default: title = UCLocalize("MODIFY"); break;
5940 }
5941
5942 button_ = [[[UIBarButtonItem alloc]
5943 initWithTitle:title
5944 style:UIBarButtonItemStylePlain
5945 target:self
5946 action:@selector(customButtonClicked)
5947 ] autorelease];
5948 }
5949
5950 - (bool) isLoading {
5951 return commercial_ ? [super isLoading] : false;
5952 }
5953
5954 @end
5955 /* }}} */
5956
5957 /* Package List Controller {{{ */
5958 @interface PackageListController : CyteViewController <
5959 UITableViewDataSource,
5960 UITableViewDelegate
5961 > {
5962 _transient Database *database_;
5963 unsigned era_;
5964 _H<NSArray> packages_;
5965 _H<NSMutableArray> sections_;
5966 _H<UITableView, 2> list_;
5967 _H<NSMutableArray> index_;
5968 _H<NSMutableDictionary> indices_;
5969 _H<NSString> title_;
5970 unsigned reloading_;
5971 }
5972
5973 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5974 - (void) setDelegate:(id)delegate;
5975 - (void) resetCursor;
5976 - (void) clearData;
5977
5978 @end
5979
5980 @implementation PackageListController
5981
5982 - (bool) isSummarized {
5983 return false;
5984 }
5985
5986 - (bool) showsSections {
5987 return true;
5988 }
5989
5990 - (void) deselectWithAnimation:(BOOL)animated {
5991 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5992 }
5993
5994 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5995 CGRect base = [[self view] bounds];
5996 base.size.height -= bounds.size.height;
5997 base.origin = [list_ frame].origin;
5998
5999 [UIView beginAnimations:nil context:NULL];
6000 [UIView setAnimationBeginsFromCurrentState:YES];
6001 [UIView setAnimationCurve:curve];
6002 [UIView setAnimationDuration:duration];
6003 [list_ setFrame:base];
6004 [UIView commitAnimations];
6005 }
6006
6007 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6008 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6009 }
6010
6011 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6012 [self resizeForKeyboardBounds:bounds duration:0];
6013 }
6014
6015 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6016 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6017 *curve = UIViewAnimationCurveEaseInOut;
6018 else
6019 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6020
6021 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6022 *duration = 0.3;
6023 else
6024 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6025 }
6026
6027 - (void) keyboardWillShow:(NSNotification *)notification {
6028 CGRect bounds;
6029 CGPoint center;
6030 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6031 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6032
6033 NSTimeInterval duration;
6034 UIViewAnimationCurve curve;
6035 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6036
6037 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);
6038 UIViewController *base = self;
6039 while ([base parentViewController] != nil)
6040 base = [base parentViewController];
6041 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6042 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6043
6044 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6045 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6046
6047 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6048 }
6049
6050 - (void) keyboardWillHide:(NSNotification *)notification {
6051 NSTimeInterval duration;
6052 UIViewAnimationCurve curve;
6053 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6054
6055 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6056 }
6057
6058 - (void) viewWillAppear:(BOOL)animated {
6059 [super viewWillAppear:animated];
6060
6061 [self resizeForKeyboardBounds:CGRectZero];
6062 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6063 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6064 }
6065
6066 - (void) viewWillDisappear:(BOOL)animated {
6067 [super viewWillDisappear:animated];
6068
6069 [self resizeForKeyboardBounds:CGRectZero];
6070 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6071 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6072 }
6073
6074 - (void) viewDidAppear:(BOOL)animated {
6075 [super viewDidAppear:animated];
6076 [self deselectWithAnimation:animated];
6077 }
6078
6079 - (void) didSelectPackage:(Package *)package {
6080 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6081 [view setDelegate:delegate_];
6082 [[self navigationController] pushViewController:view animated:YES];
6083 }
6084
6085 #if TryIndexedCollation
6086 + (BOOL) hasIndexedCollation {
6087 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6088 }
6089 #endif
6090
6091 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6092 NSInteger count([sections_ count]);
6093 return count == 0 ? 1 : count;
6094 }
6095
6096 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6097 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6098 return nil;
6099 return [[sections_ objectAtIndex:section] name];
6100 }
6101
6102 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6103 if ([sections_ count] == 0)
6104 return 0;
6105 return [[sections_ objectAtIndex:section] count];
6106 }
6107
6108 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6109 @synchronized (database_) {
6110 if ([database_ era] != era_)
6111 return nil;
6112
6113 Section *section([sections_ objectAtIndex:[path section]]);
6114 NSInteger row([path row]);
6115 Package *package([packages_ objectAtIndex:([section row] + row)]);
6116 return [[package retain] autorelease];
6117 } }
6118
6119 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6120 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6121 if (cell == nil)
6122 cell = [[[PackageCell alloc] init] autorelease];
6123
6124 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6125 [cell setPackage:package asSummary:[self isSummarized]];
6126 return cell;
6127 }
6128
6129 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6130 Package *package([self packageAtIndexPath:path]);
6131 package = [database_ packageWithName:[package id]];
6132 [self didSelectPackage:package];
6133 }
6134
6135 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6136 if (![self showsSections])
6137 return nil;
6138
6139 return index_;
6140 }
6141
6142 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6143 #if TryIndexedCollation
6144 if ([[self class] hasIndexedCollation]) {
6145 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6146 }
6147 #endif
6148
6149 return index;
6150 }
6151
6152 - (void) updateHeight {
6153 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6154 }
6155
6156 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6157 if ((self = [super init]) != nil) {
6158 database_ = database;
6159 title_ = [title copy];
6160 [[self navigationItem] setTitle:title_];
6161
6162 #if TryIndexedCollation
6163 if ([[self class] hasIndexedCollation])
6164 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6165 else
6166 #endif
6167 index_ = [NSMutableArray arrayWithCapacity:32];
6168
6169 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6170
6171 packages_ = [NSArray array];
6172 sections_ = [NSMutableArray arrayWithCapacity:16];
6173 } return self;
6174 }
6175
6176 - (void) loadView {
6177 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6178
6179 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6180 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6181 [[self view] addSubview:list_];
6182
6183 // XXX: is 20 the most optimal number here?
6184 [list_ setSectionIndexMinimumDisplayRowCount:20];
6185
6186 [(UITableView *) list_ setDataSource:self];
6187 [list_ setDelegate:self];
6188
6189 [self updateHeight];
6190 }
6191
6192 - (void) releaseSubviews {
6193 list_ = nil;
6194
6195 [super releaseSubviews];
6196 }
6197
6198 - (void) setDelegate:(id)delegate {
6199 delegate_ = delegate;
6200 }
6201
6202 - (bool) shouldYield {
6203 return false;
6204 }
6205
6206 - (bool) shouldBlock {
6207 return false;
6208 }
6209
6210 - (NSMutableArray *) _reloadPackages {
6211 @synchronized (database_) {
6212 era_ = [database_ era];
6213 NSArray *packages([database_ packages]);
6214
6215 return [NSMutableArray arrayWithArray:packages];
6216 } }
6217
6218 - (void) _reloadData {
6219 if (reloading_ != 0) {
6220 reloading_ = 2;
6221 return;
6222 }
6223
6224 NSArray *packages;
6225
6226 if ([self shouldYield]) {
6227 do {
6228 UIProgressHUD *hud;
6229
6230 if (![self shouldBlock])
6231 hud = nil;
6232 else {
6233 hud = [delegate_ addProgressHUD];
6234 [hud setText:UCLocalize("LOADING")];
6235 }
6236
6237 reloading_ = 1;
6238 packages = [self yieldToSelector:@selector(_reloadPackages)];
6239
6240 if (hud != nil)
6241 [delegate_ removeProgressHUD:hud];
6242 } while (reloading_ == 2);
6243
6244 reloading_ = 0;
6245 } else {
6246 packages = [self _reloadPackages];
6247 }
6248
6249 packages_ = packages;
6250
6251 [indices_ removeAllObjects];
6252 [sections_ removeAllObjects];
6253
6254 Section *section = nil;
6255
6256 #if TryIndexedCollation
6257 if ([[self class] hasIndexedCollation]) {
6258 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6259 NSArray *titles = [collation sectionIndexTitles];
6260 int secidx = -1;
6261
6262 _profile(PackageTable$reloadData$Section)
6263 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6264 Package *package;
6265 int index;
6266
6267 _profile(PackageTable$reloadData$Section$Package)
6268 package = [packages_ objectAtIndex:offset];
6269 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6270 _end
6271
6272 while (secidx < index) {
6273 secidx += 1;
6274
6275 _profile(PackageTable$reloadData$Section$Allocate)
6276 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6277 _end
6278
6279 _profile(PackageTable$reloadData$Section$Add)
6280 [sections_ addObject:section];
6281 _end
6282 }
6283
6284 [section addToCount];
6285 }
6286 _end
6287 } else
6288 #endif
6289 {
6290 [index_ removeAllObjects];
6291
6292 bool sectioned([self showsSections]);
6293 if (!sectioned) {
6294 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6295 [sections_ addObject:section];
6296 }
6297
6298 _profile(PackageTable$reloadData$Section)
6299 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6300 Package *package;
6301 unichar index;
6302
6303 _profile(PackageTable$reloadData$Section$Package)
6304 package = [packages_ objectAtIndex:offset];
6305 index = [package index];
6306 _end
6307
6308 if (sectioned && (section == nil || [section index] != index)) {
6309 _profile(PackageTable$reloadData$Section$Allocate)
6310 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6311 _end
6312
6313 [index_ addObject:[section name]];
6314 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6315
6316 _profile(PackageTable$reloadData$Section$Add)
6317 [sections_ addObject:section];
6318 _end
6319 }
6320
6321 [section addToCount];
6322 }
6323 _end
6324 }
6325
6326 [self updateHeight];
6327
6328 _profile(PackageTable$reloadData$List)
6329 [(UITableView *) list_ setDataSource:self];
6330 [list_ reloadData];
6331 _end
6332 }
6333
6334 - (void) reloadData {
6335 [super reloadData];
6336 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6337 }
6338
6339 - (void) resetCursor {
6340 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6341 }
6342
6343 - (void) clearData {
6344 [self updateHeight];
6345
6346 [list_ setDataSource:nil];
6347 [list_ reloadData];
6348
6349 [self resetCursor];
6350 }
6351
6352 @end
6353 /* }}} */
6354 /* Filtered Package List Controller {{{ */
6355 @interface FilteredPackageListController : PackageListController {
6356 SEL filter_;
6357 IMP imp_;
6358 _H<NSObject> object_;
6359 }
6360
6361 - (void) setObject:(id)object;
6362 - (void) setObject:(id)object forFilter:(SEL)filter;
6363
6364 - (SEL) filter;
6365 - (void) setFilter:(SEL)filter;
6366
6367 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6368
6369 @end
6370
6371 @implementation FilteredPackageListController
6372
6373 - (SEL) filter {
6374 return filter_;
6375 }
6376
6377 - (void) setFilter:(SEL)filter {
6378 @synchronized (self) {
6379 filter_ = filter;
6380
6381 /* XXX: this is an unsafe optimization of doomy hell */
6382 Method method(class_getInstanceMethod([Package class], filter));
6383 _assert(method != NULL);
6384 imp_ = method_getImplementation(method);
6385 _assert(imp_ != NULL);
6386 } }
6387
6388 - (void) setObject:(id)object {
6389 @synchronized (self) {
6390 object_ = object;
6391 } }
6392
6393 - (void) setObject:(id)object forFilter:(SEL)filter {
6394 @synchronized (self) {
6395 [self setFilter:filter];
6396 [self setObject:object];
6397 } }
6398
6399 - (NSMutableArray *) _reloadPackages {
6400 @synchronized (database_) {
6401 era_ = [database_ era];
6402 NSArray *packages([database_ packages]);
6403
6404 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6405
6406 IMP imp;
6407 SEL filter;
6408 _H<NSObject> object;
6409
6410 @synchronized (self) {
6411 imp = imp_;
6412 filter = filter_;
6413 object = object_;
6414 }
6415
6416 _profile(PackageTable$reloadData$Filter)
6417 for (Package *package in packages)
6418 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6419 [filtered addObject:package];
6420 _end
6421
6422 return filtered;
6423 } }
6424
6425 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6426 if ((self = [super initWithDatabase:database title:title]) != nil) {
6427 [self setFilter:filter];
6428 [self setObject:object];
6429 } return self;
6430 }
6431
6432 @end
6433 /* }}} */
6434
6435 /* Home Controller {{{ */
6436 @interface HomeController : CydiaWebViewController {
6437 }
6438
6439 @end
6440
6441 @implementation HomeController
6442
6443 - (id) init {
6444 if ((self = [super init]) != nil) {
6445 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6446 [self reloadData];
6447 } return self;
6448 }
6449
6450 - (NSURL *) navigationURL {
6451 return [NSURL URLWithString:@"cydia://home"];
6452 }
6453
6454 - (void) didReceiveMemoryWarning {
6455 }
6456
6457 - (void) aboutButtonClicked {
6458 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6459
6460 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6461 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6462 [alert setCancelButtonIndex:0];
6463
6464 [alert setMessage:
6465 @"Copyright \u00a9 2008-2011\n"
6466 "SaurikIT, LLC\n"
6467 "\n"
6468 "Jay Freeman (saurik)\n"
6469 "saurik@saurik.com\n"
6470 "http://www.saurik.com/"
6471 ];
6472
6473 [alert show];
6474 }
6475
6476 - (UIBarButtonItem *) leftButton {
6477 return [[[UIBarButtonItem alloc]
6478 initWithTitle:UCLocalize("ABOUT")
6479 style:UIBarButtonItemStylePlain
6480 target:self
6481 action:@selector(aboutButtonClicked)
6482 ] autorelease];
6483 }
6484
6485 @end
6486 /* }}} */
6487 /* Manage Controller {{{ */
6488 @interface ManageController : CydiaWebViewController {
6489 }
6490
6491 - (void) queueStatusDidChange;
6492
6493 @end
6494
6495 @implementation ManageController
6496
6497 - (id) init {
6498 if ((self = [super init]) != nil) {
6499 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6500 } return self;
6501 }
6502
6503 - (NSURL *) navigationURL {
6504 return [NSURL URLWithString:@"cydia://manage"];
6505 }
6506
6507 - (UIBarButtonItem *) leftButton {
6508 return [[[UIBarButtonItem alloc]
6509 initWithTitle:UCLocalize("SETTINGS")
6510 style:UIBarButtonItemStylePlain
6511 target:self
6512 action:@selector(settingsButtonClicked)
6513 ] autorelease];
6514 }
6515
6516 - (void) settingsButtonClicked {
6517 [delegate_ showSettings];
6518 }
6519
6520 - (void) queueButtonClicked {
6521 [delegate_ queue];
6522 }
6523
6524 - (UIBarButtonItem *) customButton {
6525 return Queuing_ ? [[[UIBarButtonItem alloc]
6526 initWithTitle:UCLocalize("QUEUE")
6527 style:UIBarButtonItemStyleDone
6528 target:self
6529 action:@selector(queueButtonClicked)
6530 ] autorelease] : [super customButton];
6531 }
6532
6533 - (void) queueStatusDidChange {
6534 [self applyRightButton];
6535 }
6536
6537 - (bool) isLoading {
6538 return !Queuing_ && [super isLoading];
6539 }
6540
6541 @end
6542 /* }}} */
6543
6544 /* Refresh Bar {{{ */
6545 @interface RefreshBar : UINavigationBar {
6546 _H<UIProgressIndicator> indicator_;
6547 _H<UITextLabel> prompt_;
6548 _H<UIProgressBar> progress_;
6549 _H<UINavigationButton> cancel_;
6550 }
6551
6552 @end
6553
6554 @implementation RefreshBar
6555
6556 - (void) positionViews {
6557 CGRect frame = [cancel_ frame];
6558 frame.size = [cancel_ sizeThatFits:frame.size];
6559 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6560 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6561 [cancel_ setFrame:frame];
6562
6563 CGSize prgsize = {75, 100};
6564 CGRect prgrect = {{
6565 [self frame].size.width - prgsize.width - 10,
6566 ([self frame].size.height - prgsize.height) / 2
6567 } , prgsize};
6568 [progress_ setFrame:prgrect];
6569
6570 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6571 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6572 CGRect indrect = {{indoffset, indoffset}, indsize};
6573 [indicator_ setFrame:indrect];
6574
6575 CGSize prmsize = {215, indsize.height + 4};
6576 CGRect prmrect = {{
6577 indoffset * 2 + indsize.width,
6578 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6579 }, prmsize};
6580 [prompt_ setFrame:prmrect];
6581 }
6582
6583 - (void) setFrame:(CGRect)frame {
6584 [super setFrame:frame];
6585 [self positionViews];
6586 }
6587
6588 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6589 if ((self = [super initWithFrame:frame]) != nil) {
6590 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6591
6592 [self setBarStyle:UIBarStyleBlack];
6593
6594 UIBarStyle barstyle([self _barStyle:NO]);
6595 bool ugly(barstyle == UIBarStyleDefault);
6596
6597 UIProgressIndicatorStyle style = ugly ?
6598 UIProgressIndicatorStyleMediumBrown :
6599 UIProgressIndicatorStyleMediumWhite;
6600
6601 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6602 [(UIProgressIndicator *) indicator_ setStyle:style];
6603 [indicator_ startAnimation];
6604 [self addSubview:indicator_];
6605
6606 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6607 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6608 [prompt_ setBackgroundColor:[UIColor clearColor]];
6609 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6610 [self addSubview:prompt_];
6611
6612 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6613 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6614 [(UIProgressBar *) progress_ setStyle:0];
6615 [self addSubview:progress_];
6616
6617 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6618 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6619 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6620 [cancel_ setBarStyle:barstyle];
6621
6622 [self positionViews];
6623 } return self;
6624 }
6625
6626 - (void) setCancellable:(bool)cancellable {
6627 if (cancellable)
6628 [self addSubview:cancel_];
6629 else
6630 [cancel_ removeFromSuperview];
6631 }
6632
6633 - (void) start {
6634 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6635 [progress_ setProgress:0];
6636 }
6637
6638 - (void) stop {
6639 [self setCancellable:NO];
6640 }
6641
6642 - (void) setPrompt:(NSString *)prompt {
6643 [prompt_ setText:prompt];
6644 }
6645
6646 - (void) setProgress:(float)progress {
6647 [progress_ setProgress:progress];
6648 }
6649
6650 @end
6651 /* }}} */
6652
6653 /* Cydia Navigation Controller Interface {{{ */
6654 @interface UINavigationController (Cydia)
6655
6656 - (NSArray *) navigationURLCollection;
6657 - (void) unloadData;
6658
6659 @end
6660 /* }}} */
6661
6662 /* Cydia Tab Bar Controller {{{ */
6663 @interface CYTabBarController : UITabBarController <
6664 UITabBarControllerDelegate,
6665 ProgressDelegate
6666 > {
6667 _transient Database *database_;
6668 _H<RefreshBar, 1> refreshbar_;
6669
6670 bool dropped_;
6671 bool updating_;
6672 // XXX: ok, "updatedelegate_"?...
6673 _transient NSObject<CydiaDelegate> *updatedelegate_;
6674
6675 _H<UIViewController> remembered_;
6676 _transient UIViewController *transient_;
6677 }
6678
6679 - (NSArray *) navigationURLCollection;
6680 - (void) dropBar:(BOOL)animated;
6681 - (void) beginUpdate;
6682 - (void) raiseBar:(BOOL)animated;
6683 - (BOOL) updating;
6684 - (void) unloadData;
6685
6686 @end
6687
6688 @implementation CYTabBarController
6689
6690 - (void) setUnselectedViewController:(UIViewController *)transient {
6691 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6692 if (transient != nil) {
6693 if (transient_ == nil)
6694 remembered_ = [controllers objectAtIndex:0];
6695 transient_ = transient;
6696 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6697 [controllers replaceObjectAtIndex:0 withObject:transient_];
6698 [self setSelectedIndex:0];
6699 [self setViewControllers:controllers];
6700 [self concealTabBarSelection];
6701 } else if (remembered_ != nil) {
6702 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6703 transient_ = transient;
6704 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6705 remembered_ = nil;
6706 [self setViewControllers:controllers];
6707 [self revealTabBarSelection];
6708 }
6709 }
6710
6711 - (UIViewController *) unselectedViewController {
6712 return transient_;
6713 }
6714
6715 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6716 if ([self unselectedViewController])
6717 [self setUnselectedViewController:nil];
6718 }
6719
6720 - (NSArray *) navigationURLCollection {
6721 NSMutableArray *items([NSMutableArray array]);
6722
6723 // XXX: Should this deal with transient view controllers?
6724 for (id navigation in [self viewControllers]) {
6725 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6726 if (stack != nil)
6727 [items addObject:stack];
6728 }
6729
6730 return items;
6731 }
6732
6733 - (void) unloadData {
6734 [super unloadData];
6735
6736 for (UINavigationController *controller in [self viewControllers])
6737 [controller unloadData];
6738
6739 if (UIViewController *selected = [self selectedViewController])
6740 [selected reloadData];
6741
6742 if (UIViewController *unselected = [self unselectedViewController]) {
6743 [unselected unloadData];
6744 [unselected reloadData];
6745 }
6746 }
6747
6748 - (void) dealloc {
6749 [[NSNotificationCenter defaultCenter] removeObserver:self];
6750
6751 [super dealloc];
6752 }
6753
6754 - (id) initWithDatabase:(Database *)database {
6755 if ((self = [super init]) != nil) {
6756 database_ = database;
6757 [self setDelegate:self];
6758
6759 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6760 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6761
6762 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6763 } return self;
6764 }
6765
6766 - (void) setUpdate:(NSDate *)date {
6767 [self beginUpdate];
6768 }
6769
6770 - (void) beginUpdate {
6771 [(RefreshBar *) refreshbar_ start];
6772 [self dropBar:YES];
6773
6774 [updatedelegate_ retainNetworkActivityIndicator];
6775 updating_ = true;
6776
6777 [NSThread
6778 detachNewThreadSelector:@selector(performUpdate)
6779 toTarget:self
6780 withObject:nil
6781 ];
6782 }
6783
6784 - (void) performUpdate {
6785 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6786
6787 Status status;
6788 status.setDelegate(self);
6789 [database_ updateWithStatus:status];
6790
6791 [self
6792 performSelectorOnMainThread:@selector(completeUpdate)
6793 withObject:nil
6794 waitUntilDone:NO
6795 ];
6796
6797 [pool release];
6798 }
6799
6800 - (void) stopUpdateWithSelector:(SEL)selector {
6801 updating_ = false;
6802 [updatedelegate_ releaseNetworkActivityIndicator];
6803
6804 [self raiseBar:YES];
6805 [refreshbar_ stop];
6806
6807 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6808 }
6809
6810 - (void) completeUpdate {
6811 if (!updating_)
6812 return;
6813 [self stopUpdateWithSelector:@selector(reloadData)];
6814 }
6815
6816 - (void) cancelUpdate {
6817 [self stopUpdateWithSelector:@selector(updateData)];
6818 }
6819
6820 - (void) cancelPressed {
6821 [self cancelUpdate];
6822 }
6823
6824 - (BOOL) updating {
6825 return updating_;
6826 }
6827
6828 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6829 [refreshbar_ setPrompt:[event compoundMessage]];
6830 }
6831
6832 - (bool) isProgressCancelled {
6833 return !updating_;
6834 }
6835
6836 - (void) setProgressCancellable:(NSNumber *)cancellable {
6837 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6838 }
6839
6840 - (void) setProgressPercent:(NSNumber *)percent {
6841 [refreshbar_ setProgress:[percent floatValue]];
6842 }
6843
6844 - (void) setProgressStatus:(NSDictionary *)status {
6845 if (status != nil)
6846 [self setProgressPercent:[status objectForKey:@"Percent"]];
6847 }
6848
6849 - (void) setUpdateDelegate:(id)delegate {
6850 updatedelegate_ = delegate;
6851 }
6852
6853 - (UIView *) transitionView {
6854 if ([self respondsToSelector:@selector(_transitionView)])
6855 return [self _transitionView];
6856 else
6857 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6858 }
6859
6860 - (void) dropBar:(BOOL)animated {
6861 if (dropped_)
6862 return;
6863 dropped_ = true;
6864
6865 UIView *transition([self transitionView]);
6866 [[self view] addSubview:refreshbar_];
6867
6868 CGRect barframe([refreshbar_ frame]);
6869
6870 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6871 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6872 else
6873 barframe.origin.y = 0;
6874
6875 [refreshbar_ setFrame:barframe];
6876
6877 if (animated)
6878 [UIView beginAnimations:nil context:NULL];
6879
6880 CGRect viewframe = [transition frame];
6881 viewframe.origin.y += barframe.size.height;
6882 viewframe.size.height -= barframe.size.height;
6883 [transition setFrame:viewframe];
6884
6885 if (animated)
6886 [UIView commitAnimations];
6887
6888 // Ensure bar has the proper width for our view, it might have changed
6889 barframe.size.width = viewframe.size.width;
6890 [refreshbar_ setFrame:barframe];
6891 }
6892
6893 - (void) raiseBar:(BOOL)animated {
6894 if (!dropped_)
6895 return;
6896 dropped_ = false;
6897
6898 UIView *transition([self transitionView]);
6899 [refreshbar_ removeFromSuperview];
6900
6901 CGRect barframe([refreshbar_ frame]);
6902
6903 if (animated)
6904 [UIView beginAnimations:nil context:NULL];
6905
6906 CGRect viewframe = [transition frame];
6907 viewframe.origin.y -= barframe.size.height;
6908 viewframe.size.height += barframe.size.height;
6909 [transition setFrame:viewframe];
6910
6911 if (animated)
6912 [UIView commitAnimations];
6913 }
6914
6915 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6916 bool dropped(dropped_);
6917
6918 if (dropped)
6919 [self raiseBar:NO];
6920
6921 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6922
6923 if (dropped)
6924 [self dropBar:NO];
6925 }
6926
6927 - (void) statusBarFrameChanged:(NSNotification *)notification {
6928 if (dropped_) {
6929 [self raiseBar:NO];
6930 [self dropBar:NO];
6931 }
6932 }
6933
6934 @end
6935 /* }}} */
6936
6937 /* Cydia Navigation Controller Implementation {{{ */
6938 @implementation UINavigationController (Cydia)
6939
6940 - (NSArray *) navigationURLCollection {
6941 NSMutableArray *stack([NSMutableArray array]);
6942
6943 for (CyteViewController *controller in [self viewControllers]) {
6944 NSString *url = [[controller navigationURL] absoluteString];
6945 if (url != nil)
6946 [stack addObject:url];
6947 }
6948
6949 return stack;
6950 }
6951
6952 - (void) reloadData {
6953 [super reloadData];
6954
6955 UIViewController *visible([self visibleViewController]);
6956 if (visible != nil)
6957 [visible reloadData];
6958
6959 // on the iPad, this view controller is ALSO visible. :(
6960 if (IsWildcat_)
6961 if (UIViewController *top = [self topViewController])
6962 if (top != visible)
6963 [top reloadData];
6964 }
6965
6966 - (void) unloadData {
6967 for (CyteViewController *page in [self viewControllers])
6968 [page unloadData];
6969
6970 [super unloadData];
6971 }
6972
6973 @end
6974 /* }}} */
6975
6976 /* Cydia:// Protocol {{{ */
6977 @interface CydiaURLProtocol : NSURLProtocol {
6978 }
6979
6980 @end
6981
6982 @implementation CydiaURLProtocol
6983
6984 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6985 NSURL *url([request URL]);
6986 if (url == nil)
6987 return NO;
6988
6989 NSString *scheme([[url scheme] lowercaseString]);
6990 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6991 return YES;
6992 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6993 return YES;
6994
6995 return NO;
6996 }
6997
6998 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6999 return request;
7000 }
7001
7002 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7003 id<NSURLProtocolClient> client([self client]);
7004 if (icon == nil)
7005 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7006 else {
7007 NSData *data(UIImagePNGRepresentation(icon));
7008
7009 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7010 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7011 [client URLProtocol:self didLoadData:data];
7012 [client URLProtocolDidFinishLoading:self];
7013 }
7014 }
7015
7016 - (void) startLoading {
7017 id<NSURLProtocolClient> client([self client]);
7018 NSURLRequest *request([self request]);
7019
7020 NSURL *url([request URL]);
7021 NSString *href([url absoluteString]);
7022 NSString *scheme([[url scheme] lowercaseString]);
7023
7024 NSString *path;
7025
7026 if ([scheme isEqualToString:@"cydia"])
7027 path = [href substringFromIndex:8];
7028 else if ([scheme isEqualToString:@"about"])
7029 path = [href substringFromIndex:12];
7030 else _assert(false);
7031
7032 NSRange slash([path rangeOfString:@"/"]);
7033
7034 NSString *command;
7035 if (slash.location == NSNotFound) {
7036 command = path;
7037 path = nil;
7038 } else {
7039 command = [path substringToIndex:slash.location];
7040 path = [path substringFromIndex:(slash.location + 1)];
7041 }
7042
7043 Database *database([Database sharedInstance]);
7044
7045 if ([command isEqualToString:@"package-icon"]) {
7046 if (path == nil)
7047 goto fail;
7048 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7049 Package *package([database packageWithName:path]);
7050 if (package == nil)
7051 goto fail;
7052 [package parse];
7053 UIImage *icon([package icon]);
7054 [self _returnPNGWithImage:icon forRequest:request];
7055 } else if ([command isEqualToString:@"source-icon"]) {
7056 if (path == nil)
7057 goto fail;
7058 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7059 NSString *source(Simplify(path));
7060 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7061 if (icon == nil)
7062 icon = [UIImage applicationImageNamed:@"unknown.png"];
7063 [self _returnPNGWithImage:icon forRequest:request];
7064 } else if ([command isEqualToString:@"uikit-image"]) {
7065 if (path == nil)
7066 goto fail;
7067 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7068 UIImage *icon(_UIImageWithName(path));
7069 [self _returnPNGWithImage:icon forRequest:request];
7070 } else if ([command isEqualToString:@"section-icon"]) {
7071 if (path == nil)
7072 goto fail;
7073 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7074 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7075 if (icon == nil)
7076 icon = [UIImage applicationImageNamed:@"unknown.png"];
7077 [self _returnPNGWithImage:icon forRequest:request];
7078 } else fail: {
7079 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7080 }
7081 }
7082
7083 - (void) stopLoading {
7084 }
7085
7086 @end
7087 /* }}} */
7088
7089 /* Section Controller {{{ */
7090 @interface SectionController : FilteredPackageListController {
7091 _H<NSString> section_;
7092 }
7093
7094 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7095
7096 @end
7097
7098 @implementation SectionController
7099
7100 - (NSURL *) navigationURL {
7101 NSString *name = section_;
7102 if (name == nil)
7103 name = @"all";
7104
7105 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7106 }
7107
7108 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7109 NSString *title;
7110 if (name == nil)
7111 title = UCLocalize("ALL_PACKAGES");
7112 else if (![name isEqual:@""])
7113 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7114 else
7115 title = UCLocalize("NO_SECTION");
7116
7117 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7118 section_ = name;
7119 } return self;
7120 }
7121
7122 @end
7123 /* }}} */
7124 /* Sections Controller {{{ */
7125 @interface SectionsController : CyteViewController <
7126 UITableViewDataSource,
7127 UITableViewDelegate
7128 > {
7129 _transient Database *database_;
7130 _H<NSMutableArray> sections_;
7131 _H<NSMutableArray> filtered_;
7132 _H<UITableView, 2> list_;
7133 }
7134
7135 - (id) initWithDatabase:(Database *)database;
7136 - (void) editButtonClicked;
7137
7138 @end
7139
7140 @implementation SectionsController
7141
7142 - (NSURL *) navigationURL {
7143 return [NSURL URLWithString:@"cydia://sections"];
7144 }
7145
7146 - (void) updateNavigationItem {
7147 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7148 if ([sections_ count] == 0) {
7149 [[self navigationItem] setRightBarButtonItem:nil];
7150 } else {
7151 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7152 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7153 target:self
7154 action:@selector(editButtonClicked)
7155 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7156 }
7157 }
7158
7159 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7160 [super setEditing:editing animated:animated];
7161
7162 if (editing)
7163 [list_ reloadData];
7164 else
7165 [delegate_ updateData];
7166
7167 [self updateNavigationItem];
7168 }
7169
7170 - (void) viewDidAppear:(BOOL)animated {
7171 [super viewDidAppear:animated];
7172 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7173 }
7174
7175 - (void) viewWillDisappear:(BOOL)animated {
7176 [super viewWillDisappear:animated];
7177 if ([self isEditing]) [self setEditing:NO];
7178 }
7179
7180 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7181 Section *section = nil;
7182 int index = [indexPath row];
7183 if (![self isEditing]) {
7184 index -= 1;
7185 if (index >= 0)
7186 section = [filtered_ objectAtIndex:index];
7187 } else {
7188 section = [sections_ objectAtIndex:index];
7189 }
7190 return section;
7191 }
7192
7193 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7194 if ([self isEditing])
7195 return [sections_ count];
7196 else
7197 return [filtered_ count] + 1;
7198 }
7199
7200 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7201 return 45.0f;
7202 }*/
7203
7204 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7205 static NSString *reuseIdentifier = @"SectionCell";
7206
7207 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7208 if (cell == nil)
7209 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7210
7211 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7212
7213 return cell;
7214 }
7215
7216 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7217 if ([self isEditing])
7218 return;
7219
7220 Section *section = [self sectionAtIndexPath:indexPath];
7221
7222 SectionController *controller = [[[SectionController alloc]
7223 initWithDatabase:database_
7224 section:[section name]
7225 ] autorelease];
7226 [controller setDelegate:delegate_];
7227
7228 [[self navigationController] pushViewController:controller animated:YES];
7229 }
7230
7231 - (void) loadView {
7232 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7233
7234 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7235 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7236 [list_ setRowHeight:45.0f];
7237 [(UITableView *) list_ setDataSource:self];
7238 [list_ setDelegate:self];
7239 [[self view] addSubview:list_];
7240 }
7241
7242 - (void) viewDidLoad {
7243 [super viewDidLoad];
7244
7245 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7246 }
7247
7248 - (void) releaseSubviews {
7249 list_ = nil;
7250
7251 [super releaseSubviews];
7252 }
7253
7254 - (id) initWithDatabase:(Database *)database {
7255 if ((self = [super init]) != nil) {
7256 database_ = database;
7257
7258 sections_ = [NSMutableArray arrayWithCapacity:16];
7259 filtered_ = [NSMutableArray arrayWithCapacity:16];
7260 } return self;
7261 }
7262
7263 - (void) reloadData {
7264 [super reloadData];
7265
7266 NSArray *packages = [database_ packages];
7267
7268 [sections_ removeAllObjects];
7269 [filtered_ removeAllObjects];
7270
7271 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7272
7273 _trace();
7274 for (Package *package in packages) {
7275 NSString *name([package section]);
7276 NSString *key(name == nil ? @"" : name);
7277
7278 Section *section;
7279
7280 _profile(SectionsView$reloadData$Section)
7281 section = [sections objectForKey:key];
7282 if (section == nil) {
7283 _profile(SectionsView$reloadData$Section$Allocate)
7284 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7285 [sections setObject:section forKey:key];
7286 _end
7287 }
7288 _end
7289
7290 [section addToCount];
7291
7292 _profile(SectionsView$reloadData$Filter)
7293 if (![package valid] || ![package visible])
7294 continue;
7295 _end
7296
7297 [section addToRow];
7298 }
7299 _trace();
7300
7301 [sections_ addObjectsFromArray:[sections allValues]];
7302
7303 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7304
7305 for (Section *section in (id) sections_) {
7306 size_t count([section row]);
7307 if (count == 0)
7308 continue;
7309
7310 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7311 [section setCount:count];
7312 [filtered_ addObject:section];
7313 }
7314
7315 [self updateNavigationItem];
7316 [list_ reloadData];
7317 _trace();
7318 }
7319
7320 - (void) editButtonClicked {
7321 [self setEditing:![self isEditing] animated:YES];
7322 }
7323
7324 @end
7325 /* }}} */
7326
7327 /* Changes Controller {{{ */
7328 @interface ChangesController : CyteViewController <
7329 UITableViewDataSource,
7330 UITableViewDelegate
7331 > {
7332 _transient Database *database_;
7333 unsigned era_;
7334 _H<NSArray> packages_;
7335 _H<NSMutableArray> sections_;
7336 _H<UITableView, 2> list_;
7337 unsigned upgrades_;
7338 }
7339
7340 - (id) initWithDatabase:(Database *)database;
7341
7342 @end
7343
7344 @implementation ChangesController
7345
7346 - (NSURL *) navigationURL {
7347 return [NSURL URLWithString:@"cydia://changes"];
7348 }
7349
7350 - (void) viewDidAppear:(BOOL)animated {
7351 [super viewDidAppear:animated];
7352 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7353 }
7354
7355 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7356 NSInteger count([sections_ count]);
7357 return count == 0 ? 1 : count;
7358 }
7359
7360 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7361 if ([sections_ count] == 0)
7362 return nil;
7363 return [[sections_ objectAtIndex:section] name];
7364 }
7365
7366 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7367 if ([sections_ count] == 0)
7368 return 0;
7369 return [[sections_ objectAtIndex:section] count];
7370 }
7371
7372 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7373 @synchronized (database_) {
7374 if ([database_ era] != era_)
7375 return nil;
7376
7377 NSUInteger sectionIndex([path section]);
7378 if (sectionIndex >= [sections_ count])
7379 return nil;
7380 Section *section([sections_ objectAtIndex:sectionIndex]);
7381 NSInteger row([path row]);
7382 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7383 } }
7384
7385 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7386 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7387 if (cell == nil)
7388 cell = [[[PackageCell alloc] init] autorelease];
7389
7390 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7391 [cell setPackage:package asSummary:false];
7392 return cell;
7393 }
7394
7395 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7396 Package *package([self packageAtIndexPath:path]);
7397 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7398 [view setDelegate:delegate_];
7399 [[self navigationController] pushViewController:view animated:YES];
7400 return path;
7401 }
7402
7403 - (void) refreshButtonClicked {
7404 [delegate_ beginUpdate];
7405 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7406 }
7407
7408 - (void) upgradeButtonClicked {
7409 [delegate_ distUpgrade];
7410 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7411 }
7412
7413 - (void) loadView {
7414 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7415
7416 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7417 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7418 [list_ setRowHeight:73];
7419 [(UITableView *) list_ setDataSource:self];
7420 [list_ setDelegate:self];
7421 [[self view] addSubview:list_];
7422 }
7423
7424 - (void) viewDidLoad {
7425 [super viewDidLoad];
7426
7427 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7428 }
7429
7430 - (void) releaseSubviews {
7431 list_ = nil;
7432
7433 [super releaseSubviews];
7434 }
7435
7436 - (id) initWithDatabase:(Database *)database {
7437 if ((self = [super init]) != nil) {
7438 database_ = database;
7439
7440 packages_ = [NSArray array];
7441 sections_ = [NSMutableArray arrayWithCapacity:16];
7442 } return self;
7443 }
7444
7445 - (NSMutableArray *) _reloadPackages {
7446 @synchronized (database_) {
7447 era_ = [database_ era];
7448 NSArray *packages([database_ packages]);
7449
7450 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7451
7452 _trace();
7453 _profile(ChangesController$_reloadPackages$Filter)
7454 for (Package *package in packages)
7455 if ([package upgradableAndEssential:YES] || [package visible])
7456 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7457 _end
7458 _trace();
7459 _profile(ChangesController$_reloadPackages$radixSort)
7460 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7461 _end
7462 _trace();
7463
7464 return filtered;
7465 } }
7466
7467 - (void) _reloadData {
7468 NSArray *packages;
7469
7470 reload:
7471 if (true) {
7472 UIProgressHUD *hud([delegate_ addProgressHUD]);
7473 [hud setText:UCLocalize("LOADING")];
7474 //NSLog(@"HUD:%@::%@", delegate_, hud);
7475 packages = [self yieldToSelector:@selector(_reloadPackages)];
7476 [delegate_ removeProgressHUD:hud];
7477 } else {
7478 packages = [self _reloadPackages];
7479 }
7480
7481 @synchronized (database_) {
7482 if (era_ != [database_ era])
7483 goto reload;
7484
7485 packages_ = packages;
7486 [sections_ removeAllObjects];
7487
7488 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7489 Section *ignored = nil;
7490 Section *section = nil;
7491 time_t last = 0;
7492
7493 upgrades_ = 0;
7494 bool unseens = false;
7495
7496 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7497
7498 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7499 Package *package = [packages_ objectAtIndex:offset];
7500
7501 BOOL uae = [package upgradableAndEssential:YES];
7502
7503 if (!uae) {
7504 unseens = true;
7505 time_t seen([package seen]);
7506
7507 if (section == nil || last != seen) {
7508 last = seen;
7509
7510 NSString *name;
7511 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7512 [name autorelease];
7513
7514 _profile(ChangesController$reloadData$Allocate)
7515 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7516 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7517 [sections_ addObject:section];
7518 _end
7519 }
7520
7521 [section addToCount];
7522 } else if ([package ignored]) {
7523 if (ignored == nil) {
7524 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7525 }
7526 [ignored addToCount];
7527 } else {
7528 ++upgrades_;
7529 [upgradable addToCount];
7530 }
7531 }
7532 _trace();
7533
7534 CFRelease(formatter);
7535
7536 if (unseens) {
7537 Section *last = [sections_ lastObject];
7538 size_t count = [last count];
7539 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7540 [sections_ removeLastObject];
7541 }
7542
7543 if ([ignored count] != 0)
7544 [sections_ insertObject:ignored atIndex:0];
7545 if (upgrades_ != 0)
7546 [sections_ insertObject:upgradable atIndex:0];
7547
7548 [list_ reloadData];
7549
7550 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7551 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7552 style:UIBarButtonItemStylePlain
7553 target:self
7554 action:@selector(upgradeButtonClicked)
7555 ] autorelease]) animated:YES];
7556
7557 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7558 initWithTitle:UCLocalize("REFRESH")
7559 style:UIBarButtonItemStylePlain
7560 target:self
7561 action:@selector(refreshButtonClicked)
7562 ] autorelease]) animated:YES];
7563
7564 PrintTimes();
7565 } }
7566
7567 - (void) reloadData {
7568 [super reloadData];
7569 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7570 }
7571
7572 @end
7573 /* }}} */
7574 /* Search Controller {{{ */
7575 @interface SearchController : FilteredPackageListController <
7576 UISearchBarDelegate
7577 > {
7578 _H<UISearchBar, 1> search_;
7579 BOOL searchloaded_;
7580 }
7581
7582 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7583 - (void) reloadData;
7584
7585 @end
7586
7587 @implementation SearchController
7588
7589 - (NSURL *) navigationURL {
7590 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7591 return [NSURL URLWithString:@"cydia://search"];
7592 else
7593 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7594 }
7595
7596 - (void) useSearch {
7597 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7598 [self clearData];
7599 [self reloadData];
7600 }
7601
7602 - (void) viewWillAppear:(BOOL)animated {
7603 [super viewWillAppear:animated];
7604
7605 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7606 [self useSearch];
7607 }
7608
7609 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7610 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7611 [self clearData];
7612 [self reloadData];
7613 }
7614
7615 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7616 [search_ resignFirstResponder];
7617 [self useSearch];
7618 }
7619
7620 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7621 [search_ setText:@""];
7622 [self searchBarButtonClicked:searchBar];
7623 }
7624
7625 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7626 [self searchBarButtonClicked:searchBar];
7627 }
7628
7629 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7630 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7631 [self reloadData];
7632 }
7633
7634 - (bool) shouldYield {
7635 return YES;
7636 }
7637
7638 - (bool) shouldBlock {
7639 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7640 }
7641
7642 - (bool) isSummarized {
7643 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7644 }
7645
7646 - (bool) showsSections {
7647 return false;
7648 }
7649
7650 - (NSMutableArray *) _reloadPackages {
7651 NSMutableArray *packages([super _reloadPackages]);
7652 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7653 [packages radixSortUsingSelector:@selector(rank)];
7654 return packages;
7655 }
7656
7657 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7658 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7659 search_ = [[[UISearchBar alloc] init] autorelease];
7660 [search_ setDelegate:self];
7661
7662 if (query != nil)
7663 [search_ setText:query];
7664 } return self;
7665 }
7666
7667 - (void) viewDidAppear:(BOOL)animated {
7668 [super viewDidAppear:animated];
7669
7670 if (!searchloaded_) {
7671 searchloaded_ = YES;
7672 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7673 [search_ layoutSubviews];
7674 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7675
7676 UITextField *textField;
7677 if ([search_ respondsToSelector:@selector(searchField)])
7678 textField = [search_ searchField];
7679 else
7680 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7681
7682 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7683 [textField setEnablesReturnKeyAutomatically:NO];
7684 [[self navigationItem] setTitleView:textField];
7685 }
7686 }
7687
7688 - (void) reloadData {
7689 id object([search_ text]);
7690 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7691 object = [object componentsSeparatedByString:@" "];
7692
7693 [self setObject:object];
7694 [self resetCursor];
7695
7696 [super reloadData];
7697 }
7698
7699 - (void) didSelectPackage:(Package *)package {
7700 [search_ resignFirstResponder];
7701 [super didSelectPackage:package];
7702 }
7703
7704 @end
7705 /* }}} */
7706 /* Package Settings Controller {{{ */
7707 @interface PackageSettingsController : CyteViewController <
7708 UITableViewDataSource,
7709 UITableViewDelegate
7710 > {
7711 _transient Database *database_;
7712 _H<NSString> name_;
7713 _H<Package> package_;
7714 _H<UITableView, 2> table_;
7715 _H<UISwitch> subscribedSwitch_;
7716 _H<UISwitch> ignoredSwitch_;
7717 _H<UITableViewCell> subscribedCell_;
7718 _H<UITableViewCell> ignoredCell_;
7719 }
7720
7721 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7722
7723 @end
7724
7725 @implementation PackageSettingsController
7726
7727 - (NSURL *) navigationURL {
7728 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7729 }
7730
7731 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7732 if (package_ == nil)
7733 return 0;
7734
7735 if ([package_ installed] == nil)
7736 return 1;
7737 else
7738 return 2;
7739 }
7740
7741 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7742 if (package_ == nil)
7743 return 0;
7744
7745 // both sections contain just one item right now.
7746 return 1;
7747 }
7748
7749 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7750 return nil;
7751 }
7752
7753 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7754 if (section == 0)
7755 return UCLocalize("SHOW_ALL_CHANGES_EX");
7756 else
7757 return UCLocalize("IGNORE_UPGRADES_EX");
7758 }
7759
7760 - (void) onSubscribed:(id)control {
7761 bool value([control isOn]);
7762 if (package_ == nil)
7763 return;
7764 if ([package_ setSubscribed:value])
7765 [delegate_ updateData];
7766 }
7767
7768 - (void) _updateIgnored {
7769 const char *package([name_ UTF8String]);
7770 bool on([ignoredSwitch_ isOn]);
7771
7772 pid_t pid(ExecFork());
7773 if (pid == 0) {
7774 FILE *dpkg(popen("dpkg --set-selections", "w"));
7775 fwrite(package, strlen(package), 1, dpkg);
7776
7777 if (on)
7778 fwrite(" hold\n", 6, 1, dpkg);
7779 else
7780 fwrite(" install\n", 9, 1, dpkg);
7781
7782 pclose(dpkg);
7783
7784 exit(0);
7785 _assert(false);
7786 }
7787
7788 _forever {
7789 int status;
7790 int result(waitpid(pid, &status, 0));
7791
7792 if (result != -1) {
7793 _assert(result == pid);
7794 break;
7795 }
7796 }
7797 }
7798
7799 - (void) onIgnored:(id)control {
7800 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7801 [invocation setTarget:self];
7802 [invocation setSelector:@selector(_updateIgnored)];
7803
7804 [delegate_ reloadDataWithInvocation:invocation];
7805 }
7806
7807 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7808 if (package_ == nil)
7809 return nil;
7810
7811 switch ([indexPath section]) {
7812 case 0: return subscribedCell_;
7813 case 1: return ignoredCell_;
7814
7815 _nodefault
7816 }
7817
7818 return nil;
7819 }
7820
7821 - (void) loadView {
7822 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7823
7824 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7825 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7826 [(UITableView *) table_ setDataSource:self];
7827 [table_ setDelegate:self];
7828 [[self view] addSubview:table_];
7829
7830 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7831 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7832 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7833
7834 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7835 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7836 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7837
7838 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7839 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7840 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7841 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7842
7843 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7844 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7845 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7846 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7847 }
7848
7849 - (void) viewDidLoad {
7850 [super viewDidLoad];
7851
7852 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7853 }
7854
7855 - (void) releaseSubviews {
7856 ignoredCell_ = nil;
7857 subscribedCell_ = nil;
7858 table_ = nil;
7859 ignoredSwitch_ = nil;
7860 subscribedSwitch_ = nil;
7861
7862 [super releaseSubviews];
7863 }
7864
7865 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7866 if ((self = [super init]) != nil) {
7867 database_ = database;
7868 name_ = package;
7869 } return self;
7870 }
7871
7872 - (void) reloadData {
7873 [super reloadData];
7874
7875 package_ = [database_ packageWithName:name_];
7876
7877 if (package_ != nil) {
7878 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7879 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7880 } // XXX: what now, G?
7881
7882 [table_ reloadData];
7883 }
7884
7885 @end
7886 /* }}} */
7887
7888 /* Installed Controller {{{ */
7889 @interface InstalledController : FilteredPackageListController {
7890 BOOL expert_;
7891 }
7892
7893 - (id) initWithDatabase:(Database *)database;
7894
7895 - (void) updateRoleButton;
7896 - (void) queueStatusDidChange;
7897
7898 @end
7899
7900 @implementation InstalledController
7901
7902 - (NSURL *) navigationURL {
7903 return [NSURL URLWithString:@"cydia://installed"];
7904 }
7905
7906 - (id) initWithDatabase:(Database *)database {
7907 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7908 [self updateRoleButton];
7909 [self queueStatusDidChange];
7910 } return self;
7911 }
7912
7913 #if !AlwaysReload
7914 - (void) queueButtonClicked {
7915 [delegate_ queue];
7916 }
7917 #endif
7918
7919 - (void) queueStatusDidChange {
7920 #if !AlwaysReload
7921 if (IsWildcat_) {
7922 if (Queuing_) {
7923 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7924 initWithTitle:UCLocalize("QUEUE")
7925 style:UIBarButtonItemStyleDone
7926 target:self
7927 action:@selector(queueButtonClicked)
7928 ] autorelease]];
7929 } else {
7930 [[self navigationItem] setLeftBarButtonItem:nil];
7931 }
7932 }
7933 #endif
7934 }
7935
7936 - (void) updateRoleButton {
7937 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7938 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7939 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7940 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7941 target:self
7942 action:@selector(roleButtonClicked)
7943 ] autorelease]];
7944 }
7945
7946 - (void) roleButtonClicked {
7947 [self setObject:[NSNumber numberWithBool:expert_]];
7948 [self reloadData];
7949 expert_ = !expert_;
7950
7951 [self updateRoleButton];
7952 }
7953
7954 @end
7955 /* }}} */
7956
7957 /* Source Cell {{{ */
7958 @interface SourceCell : CyteTableViewCell <
7959 CyteTableViewCellDelegate
7960 > {
7961 _H<UIImage> icon_;
7962 _H<NSString> origin_;
7963 _H<NSString> label_;
7964 }
7965
7966 - (void) setSource:(Source *)source;
7967
7968 @end
7969
7970 @implementation SourceCell
7971
7972 - (void) _setImage:(UIImage *)image {
7973 icon_ = image;
7974 [content_ setNeedsDisplay];
7975 }
7976
7977 - (void) _setSource:(Source *)source {
7978 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7979
7980 if (NSString *base = [source base])
7981 if ([base length] != 0) {
7982 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7983
7984 if (NSData *data = [NSURLConnection
7985 sendSynchronousRequest:[NSURLRequest
7986 requestWithURL:url
7987 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7988 //timeoutInterval:5
7989 ]
7990
7991 returningResponse:NULL
7992 error:NULL
7993 ])
7994 if (UIImage *image = [UIImage imageWithData:data])
7995 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7996 }
7997
7998 [pool release];
7999 }
8000
8001 - (void) setSource:(Source *)source {
8002 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8003
8004 origin_ = [source name];
8005 label_ = [source uri];
8006
8007 [content_ setNeedsDisplay];
8008
8009 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
8010 }
8011
8012 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8013 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8014 UIView *content([self contentView]);
8015 CGRect bounds([content bounds]);
8016
8017 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8018 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8019 [content_ setBackgroundColor:[UIColor whiteColor]];
8020 [content addSubview:content_];
8021
8022 [content_ setDelegate:self];
8023 [content_ setOpaque:YES];
8024 } return self;
8025 }
8026
8027 - (NSString *) accessibilityLabel {
8028 return label_;
8029 }
8030
8031 - (void) drawContentRect:(CGRect)rect {
8032 bool highlighted(highlighted_);
8033 float width(rect.size.width);
8034
8035 if (icon_ != nil)
8036 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8037
8038 if (highlighted)
8039 UISetColor(White_);
8040
8041 if (!highlighted)
8042 UISetColor(Black_);
8043 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8044
8045 if (!highlighted)
8046 UISetColor(Blue_);
8047 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8048 }
8049
8050 @end
8051 /* }}} */
8052 /* Source Controller {{{ */
8053 @interface SourceController : FilteredPackageListController {
8054 _transient Source *source_;
8055 _H<NSString> key_;
8056 }
8057
8058 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8059
8060 @end
8061
8062 @implementation SourceController
8063
8064 - (NSURL *) navigationURL {
8065 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8066 }
8067
8068 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8069 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8070 source_ = source;
8071 key_ = [source key];
8072 } return self;
8073 }
8074
8075 - (void) reloadData {
8076 source_ = [database_ sourceWithKey:key_];
8077 key_ = [source_ key];
8078 [self setObject:source_];
8079
8080 [[self navigationItem] setTitle:[source_ label]];
8081
8082 [super reloadData];
8083 }
8084
8085 @end
8086 /* }}} */
8087 /* Sources Controller {{{ */
8088 @interface SourcesController : CyteViewController <
8089 UITableViewDataSource,
8090 UITableViewDelegate
8091 > {
8092 _transient Database *database_;
8093 _H<UITableView, 2> list_;
8094 _H<NSMutableArray> sources_;
8095 int offset_;
8096
8097 _H<NSString> href_;
8098 _H<UIProgressHUD> hud_;
8099 _H<NSError> error_;
8100
8101 //NSURLConnection *installer_;
8102 NSURLConnection *trivial_;
8103 NSURLConnection *trivial_bz2_;
8104 NSURLConnection *trivial_gz_;
8105 //NSURLConnection *automatic_;
8106
8107 BOOL cydia_;
8108 }
8109
8110 - (id) initWithDatabase:(Database *)database;
8111 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8112
8113 @end
8114
8115 @implementation SourcesController
8116
8117 - (void) _releaseConnection:(NSURLConnection *)connection {
8118 if (connection != nil) {
8119 [connection cancel];
8120 //[connection setDelegate:nil];
8121 [connection release];
8122 }
8123 }
8124
8125 - (void) dealloc {
8126 //[self _releaseConnection:installer_];
8127 [self _releaseConnection:trivial_];
8128 [self _releaseConnection:trivial_gz_];
8129 [self _releaseConnection:trivial_bz2_];
8130 //[self _releaseConnection:automatic_];
8131
8132 [super dealloc];
8133 }
8134
8135 - (NSURL *) navigationURL {
8136 return [NSURL URLWithString:@"cydia://sources"];
8137 }
8138
8139 - (void) viewDidAppear:(BOOL)animated {
8140 [super viewDidAppear:animated];
8141 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8142 }
8143
8144 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8145 return offset_ == 0 ? 1 : 2;
8146 }
8147
8148 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8149 switch (section + (offset_ == 0 ? 1 : 0)) {
8150 case 0: return UCLocalize("ENTERED_BY_USER");
8151 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8152
8153 _nodefault
8154 }
8155 }
8156
8157 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8158 int count = [sources_ count];
8159 switch (section) {
8160 case 0: return (offset_ == 0 ? count : offset_);
8161 case 1: return count - offset_;
8162
8163 _nodefault
8164 }
8165 }
8166
8167 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8168 unsigned idx = 0;
8169 switch (indexPath.section) {
8170 case 0: idx = indexPath.row; break;
8171 case 1: idx = indexPath.row + offset_; break;
8172
8173 _nodefault
8174 }
8175 return [sources_ objectAtIndex:idx];
8176 }
8177
8178 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8179 static NSString *cellIdentifier = @"SourceCell";
8180
8181 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8182 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8183 [cell setSource:[self sourceAtIndexPath:indexPath]];
8184 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8185
8186 return cell;
8187 }
8188
8189 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8190 Source *source = [self sourceAtIndexPath:indexPath];
8191
8192 SourceController *controller = [[[SourceController alloc]
8193 initWithDatabase:database_
8194 source:source
8195 ] autorelease];
8196
8197 [controller setDelegate:delegate_];
8198
8199 [[self navigationController] pushViewController:controller animated:YES];
8200 }
8201
8202 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8203 Source *source = [self sourceAtIndexPath:indexPath];
8204 return [source record] != nil;
8205 }
8206
8207 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8208 if (editingStyle == UITableViewCellEditingStyleDelete) {
8209 Source *source = [self sourceAtIndexPath:indexPath];
8210 [Sources_ removeObjectForKey:[source key]];
8211 [delegate_ syncData];
8212 }
8213 }
8214
8215 - (void) complete {
8216 [delegate_ addTrivialSource:href_];
8217 [delegate_ syncData];
8218 }
8219
8220 - (NSString *) getWarning {
8221 NSString *href(href_);
8222 NSRange colon([href rangeOfString:@"://"]);
8223 if (colon.location != NSNotFound)
8224 href = [href substringFromIndex:(colon.location + 3)];
8225 href = [href stringByAddingPercentEscapes];
8226 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8227 href = [href stringByCachingURLWithCurrentCDN];
8228
8229 NSURL *url([NSURL URLWithString:href]);
8230
8231 NSStringEncoding encoding;
8232 NSError *error(nil);
8233
8234 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8235 return [warning length] == 0 ? nil : warning;
8236 return nil;
8237 }
8238
8239 - (void) _endConnection:(NSURLConnection *)connection {
8240 // XXX: the memory management in this method is horribly awkward
8241
8242 NSURLConnection **field = NULL;
8243 if (connection == trivial_)
8244 field = &trivial_;
8245 else if (connection == trivial_bz2_)
8246 field = &trivial_bz2_;
8247 else if (connection == trivial_gz_)
8248 field = &trivial_gz_;
8249 _assert(field != NULL);
8250 [connection release];
8251 *field = nil;
8252
8253 if (
8254 trivial_ == nil &&
8255 trivial_bz2_ == nil &&
8256 trivial_gz_ == nil
8257 ) {
8258 [delegate_ releaseNetworkActivityIndicator];
8259
8260 [delegate_ removeProgressHUD:hud_];
8261 hud_ = nil;
8262
8263 bool defer(false);
8264
8265 if (cydia_) {
8266 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8267 defer = true;
8268
8269 UIAlertView *alert = [[[UIAlertView alloc]
8270 initWithTitle:UCLocalize("SOURCE_WARNING")
8271 message:warning
8272 delegate:self
8273 cancelButtonTitle:UCLocalize("CANCEL")
8274 otherButtonTitles:
8275 UCLocalize("ADD_ANYWAY"),
8276 nil
8277 ] autorelease];
8278
8279 [alert setContext:@"warning"];
8280 [alert setNumberOfRows:1];
8281 [alert show];
8282 } else
8283 [self complete];
8284 } else if (error_ != nil) {
8285 UIAlertView *alert = [[[UIAlertView alloc]
8286 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8287 message:[error_ localizedDescription]
8288 delegate:self
8289 cancelButtonTitle:UCLocalize("OK")
8290 otherButtonTitles:nil
8291 ] autorelease];
8292
8293 [alert setContext:@"urlerror"];
8294 [alert show];
8295 } else {
8296 UIAlertView *alert = [[[UIAlertView alloc]
8297 initWithTitle:UCLocalize("NOT_REPOSITORY")
8298 message:UCLocalize("NOT_REPOSITORY_EX")
8299 delegate:self
8300 cancelButtonTitle:UCLocalize("OK")
8301 otherButtonTitles:nil
8302 ] autorelease];
8303
8304 [alert setContext:@"trivial"];
8305 [alert show];
8306 }
8307
8308 href_ = nil;
8309 error_ = nil;
8310 }
8311 }
8312
8313 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8314 switch ([response statusCode]) {
8315 case 200:
8316 cydia_ = YES;
8317 }
8318 }
8319
8320 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8321 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8322 error_ = error;
8323 [self _endConnection:connection];
8324 }
8325
8326 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8327 [self _endConnection:connection];
8328 }
8329
8330 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8331 NSURL *url([NSURL URLWithString:href]);
8332
8333 NSMutableURLRequest *request = [NSMutableURLRequest
8334 requestWithURL:url
8335 cachePolicy:NSURLRequestUseProtocolCachePolicy
8336 timeoutInterval:120.0
8337 ];
8338
8339 [request setHTTPMethod:method];
8340
8341 if (Machine_ != NULL)
8342 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8343
8344 if ([url isCydiaSecure]) {
8345 if (UniqueID_ != nil)
8346 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8347 }
8348
8349 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8350 }
8351
8352 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8353 NSString *context([alert context]);
8354
8355 if ([context isEqualToString:@"source"]) {
8356 switch (button) {
8357 case 1: {
8358 NSString *href = [[alert textField] text];
8359
8360 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8361
8362 if (![href hasSuffix:@"/"])
8363 href_ = [href stringByAppendingString:@"/"];
8364 else
8365 href_ = href;
8366
8367 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8368 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8369 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8370 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8371
8372 cydia_ = false;
8373
8374 // XXX: this is stupid
8375 hud_ = [delegate_ addProgressHUD];
8376 [hud_ setText:UCLocalize("VERIFYING_URL")];
8377 [delegate_ retainNetworkActivityIndicator];
8378 } break;
8379
8380 case 0:
8381 break;
8382
8383 _nodefault
8384 }
8385
8386 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8387 } else if ([context isEqualToString:@"trivial"])
8388 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8389 else if ([context isEqualToString:@"urlerror"])
8390 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8391 else if ([context isEqualToString:@"warning"]) {
8392 switch (button) {
8393 case 1:
8394 [self complete];
8395 break;
8396
8397 case 0:
8398 break;
8399
8400 _nodefault
8401 }
8402
8403 href_ = nil;
8404
8405 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8406 }
8407 }
8408
8409 - (void) loadView {
8410 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8411
8412 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8413 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8414 [list_ setRowHeight:56];
8415 [(UITableView *) list_ setDataSource:self];
8416 [list_ setDelegate:self];
8417 [[self view] addSubview:list_];
8418 }
8419
8420 - (void) viewDidLoad {
8421 [super viewDidLoad];
8422
8423 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8424 [self updateButtonsForEditingStatus:NO animated:NO];
8425 }
8426
8427 - (void) releaseSubviews {
8428 list_ = nil;
8429
8430 [super releaseSubviews];
8431 }
8432
8433 - (id) initWithDatabase:(Database *)database {
8434 if ((self = [super init]) != nil) {
8435 database_ = database;
8436 sources_ = [NSMutableArray arrayWithCapacity:16];
8437 } return self;
8438 }
8439
8440 - (void) reloadData {
8441 [super reloadData];
8442
8443 pkgSourceList list;
8444 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8445 return;
8446
8447 [sources_ removeAllObjects];
8448 [sources_ addObjectsFromArray:[database_ sources]];
8449 _trace();
8450 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8451 _trace();
8452
8453 int count([sources_ count]);
8454 offset_ = 0;
8455 for (int i = 0; i != count; i++) {
8456 if ([[sources_ objectAtIndex:i] record] == nil)
8457 break;
8458 offset_++;
8459 }
8460
8461 [list_ setEditing:NO];
8462 [self updateButtonsForEditingStatus:NO animated:NO];
8463 [list_ reloadData];
8464 }
8465
8466 - (void) showAddSourcePrompt {
8467 UIAlertView *alert = [[[UIAlertView alloc]
8468 initWithTitle:UCLocalize("ENTER_APT_URL")
8469 message:nil
8470 delegate:self
8471 cancelButtonTitle:UCLocalize("CANCEL")
8472 otherButtonTitles:
8473 UCLocalize("ADD_SOURCE"),
8474 nil
8475 ] autorelease];
8476
8477 [alert setContext:@"source"];
8478
8479 [alert setNumberOfRows:1];
8480 [alert addTextFieldWithValue:@"http://" label:@""];
8481
8482 UITextInputTraits *traits = [[alert textField] textInputTraits];
8483 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8484 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8485 [traits setKeyboardType:UIKeyboardTypeURL];
8486 // XXX: UIReturnKeyDone
8487 [traits setReturnKeyType:UIReturnKeyNext];
8488
8489 [alert show];
8490 }
8491
8492 - (void) addButtonClicked {
8493 [self showAddSourcePrompt];
8494 }
8495
8496 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8497 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8498 initWithTitle:UCLocalize("ADD")
8499 style:UIBarButtonItemStylePlain
8500 target:self
8501 action:@selector(addButtonClicked)
8502 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8503
8504 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8505 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8506 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8507 target:self
8508 action:@selector(editButtonClicked)
8509 ] autorelease] animated:animated];
8510
8511 if (IsWildcat_ && !editing)
8512 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8513 initWithTitle:UCLocalize("SETTINGS")
8514 style:UIBarButtonItemStylePlain
8515 target:self
8516 action:@selector(settingsButtonClicked)
8517 ] autorelease]];
8518 }
8519
8520 - (void) settingsButtonClicked {
8521 [delegate_ showSettings];
8522 }
8523
8524 - (void) editButtonClicked {
8525 [list_ setEditing:![list_ isEditing] animated:YES];
8526
8527 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8528 }
8529
8530 @end
8531 /* }}} */
8532
8533 /* Settings Controller {{{ */
8534 @interface SettingsController : CyteViewController <
8535 UITableViewDataSource,
8536 UITableViewDelegate
8537 > {
8538 _transient Database *database_;
8539 // XXX: ok, "roledelegate_"?...
8540 _transient id roledelegate_;
8541 _H<UITableView, 2> table_;
8542 _H<UISegmentedControl> segment_;
8543 _H<UIView> container_;
8544 }
8545
8546 - (void) showDoneButton;
8547 - (void) resizeSegmentedControl;
8548
8549 @end
8550
8551 @implementation SettingsController
8552
8553 - (void) loadView {
8554 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8555
8556 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8557 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8558 [table_ setDelegate:self];
8559 [(UITableView *) table_ setDataSource:self];
8560 [[self view] addSubview:table_];
8561
8562 NSArray *items = [NSArray arrayWithObjects:
8563 UCLocalize("USER"),
8564 UCLocalize("HACKER"),
8565 UCLocalize("DEVELOPER"),
8566 nil];
8567 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8568 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8569 [container_ addSubview:segment_];
8570 }
8571
8572 - (void) viewDidLoad {
8573 [super viewDidLoad];
8574
8575 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8576
8577 int index = -1;
8578 if ([Role_ isEqualToString:@"User"]) index = 0;
8579 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8580 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8581 if (index != -1) {
8582 [segment_ setSelectedSegmentIndex:index];
8583 [self showDoneButton];
8584 }
8585
8586 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8587 [self resizeSegmentedControl];
8588 }
8589
8590 - (void) releaseSubviews {
8591 table_ = nil;
8592 segment_ = nil;
8593 container_ = nil;
8594
8595 [super releaseSubviews];
8596 }
8597
8598 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8599 if ((self = [super init]) != nil) {
8600 database_ = database;
8601 roledelegate_ = delegate;
8602 } return self;
8603 }
8604
8605 - (void) resizeSegmentedControl {
8606 CGFloat width = [[self view] frame].size.width;
8607 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8608 }
8609
8610 - (void) viewWillAppear:(BOOL)animated {
8611 [super viewWillAppear:animated];
8612
8613 [self resizeSegmentedControl];
8614 }
8615
8616 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8617 [self resizeSegmentedControl];
8618 }
8619
8620 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8621 [self resizeSegmentedControl];
8622 }
8623
8624 - (void) save {
8625 NSString *role(nil);
8626
8627 switch ([segment_ selectedSegmentIndex]) {
8628 case 0: role = @"User"; break;
8629 case 1: role = @"Hacker"; break;
8630 case 2: role = @"Developer"; break;
8631
8632 _nodefault
8633 }
8634
8635 if (![role isEqualToString:Role_]) {
8636 bool rolling(Role_ == nil);
8637 Role_ = role;
8638
8639 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8640 Role_, @"Role",
8641 nil];
8642
8643 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8644 Changed_ = true;
8645
8646 if (rolling)
8647 [roledelegate_ loadData];
8648 else
8649 [roledelegate_ updateData];
8650 }
8651 }
8652
8653 - (void) segmentChanged:(UISegmentedControl *)control {
8654 [self showDoneButton];
8655 }
8656
8657 - (void) saveAndClose {
8658 [self save];
8659
8660 [[self navigationItem] setRightBarButtonItem:nil];
8661 [[self navigationController] dismissModalViewControllerAnimated:YES];
8662 }
8663
8664 - (void) doneButtonClicked {
8665 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8666 [spinner startAnimating];
8667 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8668 [[self navigationItem] setRightBarButtonItem:spinItem];
8669
8670 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8671 }
8672
8673 - (void) showDoneButton {
8674 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8675 initWithTitle:UCLocalize("DONE")
8676 style:UIBarButtonItemStyleDone
8677 target:self
8678 action:@selector(doneButtonClicked)
8679 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8680 }
8681
8682 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8683 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8684 return 6;
8685 }
8686
8687 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8688 return 0; // :(
8689 }
8690
8691 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8692 return nil; // This method is required by the protocol.
8693 }
8694
8695 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8696 if (section == 1)
8697 return UCLocalize("ROLE_EX");
8698 if (section == 4)
8699 return [NSString stringWithFormat:
8700 @"%@: %@\n%@: %@\n%@: %@",
8701 UCLocalize("USER"), UCLocalize("USER_EX"),
8702 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8703 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8704 ];
8705 else return nil;
8706 }
8707
8708 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8709 return section == 3 ? 44.0f : 0;
8710 }
8711
8712 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8713 return section == 3 ? container_ : nil;
8714 }
8715
8716 - (void) reloadData {
8717 [super reloadData];
8718
8719 [table_ reloadData];
8720 }
8721
8722 @end
8723 /* }}} */
8724 /* Stash Controller {{{ */
8725 @interface StashController : CyteViewController {
8726 _H<UIActivityIndicatorView> spinner_;
8727 _H<UILabel> status_;
8728 _H<UILabel> caption_;
8729 }
8730
8731 @end
8732
8733 @implementation StashController
8734
8735 - (void) loadView {
8736 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8737 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8738
8739 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8740 CGRect spinrect = [spinner_ frame];
8741 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8742 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8743 [spinner_ setFrame:spinrect];
8744 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8745 [[self view] addSubview:spinner_];
8746 [spinner_ startAnimating];
8747
8748 CGRect captrect;
8749 captrect.size.width = [[self view] frame].size.width;
8750 captrect.size.height = 40.0f;
8751 captrect.origin.x = 0;
8752 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8753 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8754 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8755 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8756 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8757 [caption_ setTextColor:[UIColor whiteColor]];
8758 [caption_ setBackgroundColor:[UIColor clearColor]];
8759 [caption_ setShadowColor:[UIColor blackColor]];
8760 [caption_ setTextAlignment:UITextAlignmentCenter];
8761 [[self view] addSubview:caption_];
8762
8763 CGRect statusrect;
8764 statusrect.size.width = [[self view] frame].size.width;
8765 statusrect.size.height = 30.0f;
8766 statusrect.origin.x = 0;
8767 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8768 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8769 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8770 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8771 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8772 [status_ setTextColor:[UIColor whiteColor]];
8773 [status_ setBackgroundColor:[UIColor clearColor]];
8774 [status_ setShadowColor:[UIColor blackColor]];
8775 [status_ setTextAlignment:UITextAlignmentCenter];
8776 [[self view] addSubview:status_];
8777 }
8778
8779 - (void) releaseSubviews {
8780 spinner_ = nil;
8781 status_ = nil;
8782 caption_ = nil;
8783
8784 [super releaseSubviews];
8785 }
8786
8787 @end
8788 /* }}} */
8789
8790 @interface CYURLCache : SDURLCache {
8791 }
8792
8793 @end
8794
8795 @implementation CYURLCache
8796
8797 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8798 #if !ForRelease
8799 if (false);
8800 else if ([event isEqualToString:@"no-cache"])
8801 event = @"!!!";
8802 else if ([event isEqualToString:@"store"])
8803 event = @">>>";
8804 else if ([event isEqualToString:@"invalid"])
8805 event = @"???";
8806 else if ([event isEqualToString:@"memory"])
8807 event = @"mem";
8808 else if ([event isEqualToString:@"disk"])
8809 event = @"ssd";
8810 else if ([event isEqualToString:@"miss"])
8811 event = @"---";
8812
8813 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8814 #endif
8815 }
8816
8817 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8818 if (NSURLResponse *response = [cached response])
8819 if (NSString *mime = [response MIMEType])
8820 if ([mime isEqualToString:@"text/cache-manifest"]) {
8821 NSURL *url([response URL]);
8822
8823 #if !ForRelease
8824 NSLog(@"###: %@", [url absoluteString]);
8825 #endif
8826
8827 @synchronized (HostConfig_) {
8828 [CachedURLs_ addObject:url];
8829 }
8830 }
8831
8832 [super storeCachedResponse:cached forRequest:request];
8833 }
8834
8835 @end
8836
8837 @interface Cydia : UIApplication <
8838 ConfirmationControllerDelegate,
8839 DatabaseDelegate,
8840 CydiaDelegate,
8841 UINavigationControllerDelegate,
8842 UITabBarControllerDelegate
8843 > {
8844 _H<UIWindow> window_;
8845 _H<CYTabBarController> tabbar_;
8846 _H<CydiaLoadingViewController> emulated_;
8847
8848 _H<NSMutableArray> essential_;
8849 _H<NSMutableArray> broken_;
8850
8851 Database *database_;
8852
8853 _H<NSURL> starturl_;
8854
8855 unsigned locked_;
8856 unsigned activity_;
8857
8858 _H<StashController> stash_;
8859
8860 bool loaded_;
8861 }
8862
8863 - (void) loadData;
8864
8865 @end
8866
8867 @implementation Cydia
8868
8869 - (void) beginUpdate {
8870 [tabbar_ beginUpdate];
8871 }
8872
8873 - (BOOL) updating {
8874 return [tabbar_ updating];
8875 }
8876
8877 - (void) _loaded {
8878 if ([broken_ count] != 0) {
8879 int count = [broken_ count];
8880
8881 UIAlertView *alert = [[[UIAlertView alloc]
8882 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8883 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8884 delegate:self
8885 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8886 otherButtonTitles:
8887 UCLocalize("TEMPORARY_IGNORE"),
8888 nil
8889 ] autorelease];
8890
8891 [alert setContext:@"fixhalf"];
8892 [alert setNumberOfRows:2];
8893 [alert show];
8894 } else if (!Ignored_ && [essential_ count] != 0) {
8895 int count = [essential_ count];
8896
8897 UIAlertView *alert = [[[UIAlertView alloc]
8898 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8899 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8900 delegate:self
8901 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8902 otherButtonTitles:
8903 UCLocalize("UPGRADE_ESSENTIAL"),
8904 UCLocalize("COMPLETE_UPGRADE"),
8905 nil
8906 ] autorelease];
8907
8908 [alert setContext:@"upgrade"];
8909 [alert show];
8910 }
8911 }
8912
8913 - (void) returnToCydia {
8914 [self _loaded];
8915 }
8916
8917 - (void) _saveConfig {
8918 _trace();
8919 MetaFile_.Sync();
8920 _trace();
8921
8922 if (Changed_) {
8923 NSString *error(nil);
8924
8925 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8926 _trace();
8927 NSError *error(nil);
8928 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8929 NSLog(@"failure to save metadata data: %@", error);
8930 _trace();
8931
8932 Changed_ = false;
8933 } else {
8934 NSLog(@"failure to serialize metadata: %@", error);
8935 }
8936 }
8937
8938 WriteSources();
8939 }
8940
8941 // Navigation controller for the queuing badge.
8942 - (UINavigationController *) queueNavigationController {
8943 NSArray *controllers = [tabbar_ viewControllers];
8944 return [controllers objectAtIndex:3];
8945 }
8946
8947 - (void) unloadData {
8948 [tabbar_ unloadData];
8949 }
8950
8951 - (void) _updateData {
8952 [self _saveConfig];
8953 [self unloadData];
8954
8955 UINavigationController *navigation = [self queueNavigationController];
8956
8957 id queuedelegate = nil;
8958 if ([[navigation viewControllers] count] > 0)
8959 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8960
8961 [queuedelegate queueStatusDidChange];
8962 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8963 }
8964
8965 - (void) _refreshIfPossible:(NSDate *)update {
8966 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8967
8968 bool recently = false;
8969 if (update != nil) {
8970 NSTimeInterval interval([update timeIntervalSinceNow]);
8971 if (interval <= 0 && interval > -(15*60))
8972 recently = true;
8973 }
8974
8975 // Don't automatic refresh if:
8976 // - We already refreshed recently.
8977 // - We already auto-refreshed this launch.
8978 // - Auto-refresh is disabled.
8979 if (recently || loaded_ || ManualRefresh) {
8980 // If we are cancelling, we need to make sure it knows it's already loaded.
8981 loaded_ = true;
8982
8983 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8984 } else {
8985 // We are going to load, so remember that.
8986 loaded_ = true;
8987
8988 SCNetworkReachabilityFlags flags; {
8989 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8990 SCNetworkReachabilityGetFlags(reachability, &flags);
8991 CFRelease(reachability);
8992 }
8993
8994 // XXX: this elaborate mess is what Apple is using to determine this? :(
8995 // XXX: do we care if the user has to intervene? maybe that's ok?
8996 bool reachable(
8997 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8998 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8999 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9000 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9001 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9002 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9003 )
9004 );
9005
9006 // If we can reach the server, auto-refresh!
9007 if (reachable)
9008 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9009 }
9010
9011 [pool release];
9012 }
9013
9014 - (void) refreshIfPossible {
9015 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9016 }
9017
9018 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9019 @synchronized (self) {
9020 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9021 [hud setText:UCLocalize("RELOADING_DATA")];
9022
9023 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9024
9025 if (hud != nil)
9026 [self removeProgressHUD:hud];
9027
9028 size_t changes(0);
9029
9030 [essential_ removeAllObjects];
9031 [broken_ removeAllObjects];
9032
9033 NSArray *packages([database_ packages]);
9034 for (Package *package in packages) {
9035 if ([package half])
9036 [broken_ addObject:package];
9037 if ([package upgradableAndEssential:NO]) {
9038 if ([package essential])
9039 [essential_ addObject:package];
9040 ++changes;
9041 }
9042 }
9043
9044 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9045 if (changes != 0) {
9046 _trace();
9047 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9048 [changesItem setBadgeValue:badge];
9049 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9050 [self setApplicationIconBadgeNumber:changes];
9051 } else {
9052 _trace();
9053 [changesItem setBadgeValue:nil];
9054 [changesItem setAnimatedBadge:NO];
9055 [self setApplicationIconBadgeNumber:0];
9056 }
9057
9058 [self _updateData];
9059 } }
9060
9061 - (void) updateData {
9062 [self _updateData];
9063 }
9064
9065 - (void) update_ {
9066 [database_ update];
9067 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9068 }
9069
9070 - (void) disemulate {
9071 if (emulated_ == nil)
9072 return;
9073
9074 [window_ addSubview:[tabbar_ view]];
9075 [[emulated_ view] removeFromSuperview];
9076 emulated_ = nil;
9077 [window_ setUserInteractionEnabled:YES];
9078 }
9079
9080 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9081 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9082 if (IsWildcat_)
9083 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9084
9085 UIViewController *parent;
9086 if (emulated_ == nil)
9087 parent = tabbar_;
9088 else if (!force)
9089 parent = emulated_;
9090 else {
9091 [self disemulate];
9092 parent = tabbar_;
9093 }
9094
9095 [parent presentModalViewController:navigation animated:YES];
9096 }
9097
9098 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9099 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9100
9101 if (navigation != nil)
9102 [navigation pushViewController:progress animated:YES];
9103 else
9104 [self presentModalViewController:progress force:YES];
9105
9106 [progress invoke:invocation withTitle:title];
9107 return progress;
9108 }
9109
9110 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9111 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9112 }
9113
9114 - (void) repairWithInvocation:(NSInvocation *)invocation {
9115 _trace();
9116 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9117 _trace();
9118 }
9119
9120 - (void) repairWithSelector:(SEL)selector {
9121 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9122 }
9123
9124 - (void) reloadData {
9125 [self reloadDataWithInvocation:nil];
9126 if ([database_ progressDelegate] == nil)
9127 [self _loaded];
9128 }
9129
9130 - (void) syncData {
9131 [self _saveConfig];
9132 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9133 }
9134
9135 - (void) addSource:(NSDictionary *) source {
9136 AddSource(source);
9137 }
9138
9139 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9140 AddSource(href, distribution, sections);
9141 }
9142
9143 - (void) addTrivialSource:(NSString *)href {
9144 AddSource(href, @"./");
9145 }
9146
9147 - (void) updateValues {
9148 Changed_ = true;
9149 }
9150
9151 - (void) resolve {
9152 pkgProblemResolver *resolver = [database_ resolver];
9153
9154 resolver->InstallProtect();
9155 if (!resolver->Resolve(true))
9156 _error->Discard();
9157 }
9158
9159 - (bool) perform {
9160 // XXX: this is a really crappy way of doing this.
9161 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9162 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9163 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9164 if ([tabbar_ updating])
9165 [tabbar_ cancelUpdate];
9166
9167 if (![database_ prepare])
9168 return false;
9169
9170 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9171 [page setDelegate:self];
9172 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9173
9174 if (IsWildcat_)
9175 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9176 [tabbar_ presentModalViewController:confirm_ animated:YES];
9177
9178 return true;
9179 }
9180
9181 - (void) queue {
9182 @synchronized (self) {
9183 [self perform];
9184 }
9185 }
9186
9187 - (void) clearPackage:(Package *)package {
9188 @synchronized (self) {
9189 [package clear];
9190 [self resolve];
9191 [self perform];
9192 }
9193 }
9194
9195 - (void) installPackages:(NSArray *)packages {
9196 @synchronized (self) {
9197 for (Package *package in packages)
9198 [package install];
9199 [self resolve];
9200 [self perform];
9201 }
9202 }
9203
9204 - (void) installPackage:(Package *)package {
9205 @synchronized (self) {
9206 [package install];
9207 [self resolve];
9208 [self perform];
9209 }
9210 }
9211
9212 - (void) removePackage:(Package *)package {
9213 @synchronized (self) {
9214 [package remove];
9215 [self resolve];
9216 [self perform];
9217 }
9218 }
9219
9220 - (void) distUpgrade {
9221 @synchronized (self) {
9222 if (![database_ upgrade])
9223 return;
9224 [self perform];
9225 }
9226 }
9227
9228 - (void) perform_ {
9229 [database_ perform];
9230 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9231 }
9232
9233 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9234 Queuing_ = false;
9235 ++locked_;
9236 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9237 --locked_;
9238 [self refreshIfPossible];
9239 }
9240
9241 - (void) showSettings {
9242 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9243 }
9244
9245 - (void) retainNetworkActivityIndicator {
9246 if (activity_++ == 0)
9247 [self setNetworkActivityIndicatorVisible:YES];
9248
9249 #if TraceLogging
9250 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9251 #endif
9252 }
9253
9254 - (void) releaseNetworkActivityIndicator {
9255 if (--activity_ == 0)
9256 [self setNetworkActivityIndicatorVisible:NO];
9257
9258 #if TraceLogging
9259 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9260 #endif
9261
9262 }
9263
9264 - (void) cancelAndClear:(bool)clear {
9265 @synchronized (self) {
9266 if (clear) {
9267 [database_ clear];
9268 Queuing_ = false;
9269 } else {
9270 Queuing_ = true;
9271 }
9272
9273 [self _updateData];
9274 }
9275 }
9276
9277 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9278 NSString *context([alert context]);
9279
9280 if ([context isEqualToString:@"conffile"]) {
9281 FILE *input = [database_ input];
9282 if (button == [alert cancelButtonIndex])
9283 fprintf(input, "N\n");
9284 else if (button == [alert firstOtherButtonIndex])
9285 fprintf(input, "Y\n");
9286 fflush(input);
9287
9288 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9289 } else if ([context isEqualToString:@"fixhalf"]) {
9290 if (button == [alert cancelButtonIndex]) {
9291 @synchronized (self) {
9292 for (Package *broken in (id) broken_) {
9293 [broken remove];
9294
9295 NSString *id = [broken id];
9296 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9297 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9298 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9299 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9300 }
9301
9302 [self resolve];
9303 [self perform];
9304 }
9305 } else if (button == [alert firstOtherButtonIndex]) {
9306 [broken_ removeAllObjects];
9307 [self _loaded];
9308 }
9309
9310 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9311 } else if ([context isEqualToString:@"upgrade"]) {
9312 if (button == [alert firstOtherButtonIndex]) {
9313 @synchronized (self) {
9314 for (Package *essential in (id) essential_)
9315 [essential install];
9316
9317 [self resolve];
9318 [self perform];
9319 }
9320 } else if (button == [alert firstOtherButtonIndex] + 1) {
9321 [self distUpgrade];
9322 } else if (button == [alert cancelButtonIndex]) {
9323 Ignored_ = YES;
9324 }
9325
9326 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9327 }
9328 }
9329
9330 - (void) system:(NSString *)command {
9331 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9332
9333 _trace();
9334 system([command UTF8String]);
9335 _trace();
9336
9337 [pool release];
9338 }
9339
9340 - (void) applicationWillSuspend {
9341 [database_ clean];
9342 [super applicationWillSuspend];
9343 }
9344
9345 - (BOOL) isSafeToSuspend {
9346 if (locked_ != 0) {
9347 #if !ForRelease
9348 NSLog(@"isSafeToSuspend: locked_ != 0");
9349 #endif
9350 return false;
9351 }
9352
9353 // Use external process status API internally.
9354 // This is probably a really bad idea.
9355 // XXX: what is the point of this? does this solve anything at all?
9356 uint64_t status = 0;
9357 int notify_token;
9358 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9359 notify_get_state(notify_token, &status);
9360 notify_cancel(notify_token);
9361 }
9362
9363 if (status != 0) {
9364 #if !ForRelease
9365 NSLog(@"isSafeToSuspend: status != 0");
9366 #endif
9367 return false;
9368 }
9369
9370 #if !ForRelease
9371 NSLog(@"isSafeToSuspend: -> true");
9372 #endif
9373 return true;
9374 }
9375
9376 - (void) applicationSuspend:(__GSEvent *)event {
9377 if ([self isSafeToSuspend])
9378 [super applicationSuspend:event];
9379 }
9380
9381 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9382 if ([self isSafeToSuspend])
9383 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9384 }
9385
9386 - (void) _setSuspended:(BOOL)value {
9387 if ([self isSafeToSuspend])
9388 [super _setSuspended:value];
9389 }
9390
9391 - (UIProgressHUD *) addProgressHUD {
9392 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9393 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9394
9395 [window_ setUserInteractionEnabled:NO];
9396
9397 UIViewController *target(tabbar_);
9398 if (UIViewController *modal = [target modalViewController])
9399 target = modal;
9400
9401 UIView *view([target view]);
9402 [view addSubview:hud];
9403
9404 [hud showInView:[tabbar_ view]];
9405
9406 ++locked_;
9407 return hud;
9408 }
9409
9410 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9411 --locked_;
9412 [hud hide];
9413 [hud removeFromSuperview];
9414 [window_ setUserInteractionEnabled:YES];
9415 }
9416
9417 - (CyteViewController *) pageForPackage:(NSString *)name {
9418 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9419 }
9420
9421 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9422 NSString *scheme([[url scheme] lowercaseString]);
9423 if ([[url absoluteString] length] <= [scheme length] + 3)
9424 return nil;
9425 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9426 NSArray *components([path pathComponents]);
9427
9428 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9429 return [self pageForPackage:[components objectAtIndex:1]];
9430
9431 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9432 return nil;
9433
9434 NSString *base([components objectAtIndex:0]);
9435
9436 CyteViewController *controller = nil;
9437
9438 if ([base isEqualToString:@"url"]) {
9439 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9440 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9441 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9442 } else if (!external && [components count] == 1) {
9443 if ([base isEqualToString:@"manage"]) {
9444 controller = [[[ManageController alloc] init] autorelease];
9445 }
9446
9447 if ([base isEqualToString:@"sources"]) {
9448 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9449 }
9450
9451 if ([base isEqualToString:@"home"]) {
9452 controller = [[[HomeController alloc] init] autorelease];
9453 }
9454
9455 if ([base isEqualToString:@"sections"]) {
9456 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9457 }
9458
9459 if ([base isEqualToString:@"search"]) {
9460 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9461 }
9462
9463 if ([base isEqualToString:@"changes"]) {
9464 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9465 }
9466
9467 if ([base isEqualToString:@"installed"]) {
9468 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9469 }
9470 } else if ([components count] == 2) {
9471 NSString *argument = [components objectAtIndex:1];
9472
9473 if ([base isEqualToString:@"package"]) {
9474 controller = [self pageForPackage:argument];
9475 }
9476
9477 if (!external && [base isEqualToString:@"search"]) {
9478 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9479 }
9480
9481 if (!external && [base isEqualToString:@"sections"]) {
9482 if ([argument isEqualToString:@"all"])
9483 argument = nil;
9484 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9485 }
9486
9487 if (!external && [base isEqualToString:@"sources"]) {
9488 if ([argument isEqualToString:@"add"]) {
9489 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9490 [(SourcesController *)controller showAddSourcePrompt];
9491 } else {
9492 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9493 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9494 }
9495 }
9496
9497 if (!external && [base isEqualToString:@"launch"]) {
9498 [self launchApplicationWithIdentifier:argument suspended:NO];
9499 return nil;
9500 }
9501 } else if (!external && [components count] == 3) {
9502 NSString *arg1 = [components objectAtIndex:1];
9503 NSString *arg2 = [components objectAtIndex:2];
9504
9505 if ([base isEqualToString:@"package"]) {
9506 if ([arg2 isEqualToString:@"settings"]) {
9507 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9508 } else if ([arg2 isEqualToString:@"files"]) {
9509 if (Package *package = [database_ packageWithName:arg1]) {
9510 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9511 [(FileTable *)controller setPackage:package];
9512 }
9513 }
9514 }
9515 }
9516
9517 [controller setDelegate:self];
9518 return controller;
9519 }
9520
9521 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9522 CyteViewController *page([self pageForURL:url forExternal:external]);
9523
9524 if (page != nil) {
9525 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9526 [nav setViewControllers:[NSArray arrayWithObject:page]];
9527 [tabbar_ setUnselectedViewController:nav];
9528 }
9529
9530 return page != nil;
9531 }
9532
9533 - (void) applicationOpenURL:(NSURL *)url {
9534 [super applicationOpenURL:url];
9535
9536 if (!loaded_)
9537 starturl_ = url;
9538 else
9539 [self openCydiaURL:url forExternal:YES];
9540 }
9541
9542 - (void) applicationWillResignActive:(UIApplication *)application {
9543 // Stop refreshing if you get a phone call or lock the device.
9544 if ([tabbar_ updating])
9545 [tabbar_ cancelUpdate];
9546
9547 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9548 [super applicationWillResignActive:application];
9549 }
9550
9551 - (void) saveState {
9552 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9553 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9554 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9555 Changed_ = true;
9556
9557 [self _saveConfig];
9558 }
9559
9560 - (void) applicationWillTerminate:(UIApplication *)application {
9561 [self saveState];
9562 }
9563
9564 - (void) setConfigurationData:(NSString *)data {
9565 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9566
9567 if (!conffile_r(data)) {
9568 lprintf("E:invalid conffile\n");
9569 return;
9570 }
9571
9572 NSString *ofile = conffile_r[1];
9573 //NSString *nfile = conffile_r[2];
9574
9575 UIAlertView *alert = [[[UIAlertView alloc]
9576 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9577 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9578 delegate:self
9579 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9580 otherButtonTitles:
9581 UCLocalize("ACCEPT_NEW_COPY"),
9582 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9583 nil
9584 ] autorelease];
9585
9586 [alert setContext:@"conffile"];
9587 [alert setNumberOfRows:2];
9588 [alert show];
9589 }
9590
9591 - (void) addStashController {
9592 ++locked_;
9593 stash_ = [[[StashController alloc] init] autorelease];
9594 [window_ addSubview:[stash_ view]];
9595 }
9596
9597 - (void) removeStashController {
9598 [[stash_ view] removeFromSuperview];
9599 stash_ = nil;
9600 --locked_;
9601 }
9602
9603 - (void) stash {
9604 [self setIdleTimerDisabled:YES];
9605
9606 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9607 UpdateExternalStatus(1);
9608 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9609 UpdateExternalStatus(0);
9610
9611 [self removeStashController];
9612
9613 if (ExecFork() == 0) {
9614 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9615 perror("launchctl stop");
9616 }
9617 }
9618
9619 - (void) setupViewControllers {
9620 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9621
9622 NSMutableArray *items([NSMutableArray arrayWithObjects:
9623 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9624 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9625 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9626 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9627 nil]);
9628
9629 if (IsWildcat_) {
9630 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9631 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9632 } else {
9633 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9634 }
9635
9636 NSMutableArray *controllers([NSMutableArray array]);
9637 for (UITabBarItem *item in items) {
9638 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9639 [controller setTabBarItem:item];
9640 [controllers addObject:controller];
9641 }
9642 [tabbar_ setViewControllers:controllers];
9643
9644 [tabbar_ setUpdateDelegate:self];
9645 }
9646
9647 - (void) _sendMemoryWarningNotification {
9648 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9649 }
9650
9651 - (void) _sendMemoryWarningNotifications {
9652 while (true) {
9653 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9654 usleep(250000);
9655 }
9656 }
9657
9658 - (void) applicationDidFinishLaunching:(id)unused {
9659 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9660
9661 _trace();
9662 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9663 [self setApplicationSupportsShakeToEdit:NO];
9664
9665 @synchronized (HostConfig_) {
9666 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9667 }
9668
9669 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9670 initWithMemoryCapacity:524288
9671 diskCapacity:10485760
9672 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9673 ] autorelease]];
9674
9675 [CydiaWebViewController _initialize];
9676
9677 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9678
9679 // this would disallow http{,s} URLs from accessing this data
9680 //[WebView registerURLSchemeAsLocal:@"cydia"];
9681
9682 Font12_ = [UIFont systemFontOfSize:12];
9683 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9684 Font14_ = [UIFont systemFontOfSize:14];
9685 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9686 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9687
9688 essential_ = [NSMutableArray arrayWithCapacity:4];
9689 broken_ = [NSMutableArray arrayWithCapacity:4];
9690
9691 // XXX: I really need this thing... like, seriously... I'm sorry
9692 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9693
9694 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9695 [window_ orderFront:self];
9696 [window_ makeKey:self];
9697 [window_ setHidden:NO];
9698
9699 if (
9700 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9701 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9702 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9703 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9704 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9705 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9706 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9707 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9708 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9709 false
9710 ) {
9711 [self addStashController];
9712 // XXX: this would be much cleaner as a yieldToSelector:
9713 // that way the removeStashController could happen right here inline
9714 // we also could no longer require the useless stash_ field anymore
9715 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9716 return;
9717 }
9718
9719 database_ = [Database sharedInstance];
9720 [database_ setDelegate:self];
9721
9722 [window_ setUserInteractionEnabled:NO];
9723 [self setupViewControllers];
9724
9725 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9726 [window_ addSubview:[emulated_ view]];
9727
9728 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9729 _trace();
9730 }
9731
9732 - (NSArray *) defaultStartPages {
9733 NSMutableArray *standard = [NSMutableArray array];
9734 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9735 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9736 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9737 if (!IsWildcat_) {
9738 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9739 } else {
9740 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9741 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9742 }
9743 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9744 return standard;
9745 }
9746
9747 - (void) loadData {
9748 _trace();
9749 if (Role_ == nil) {
9750 [window_ setUserInteractionEnabled:YES];
9751 [self showSettings];
9752 return;
9753 } else {
9754 if ([emulated_ modalViewController] != nil)
9755 [emulated_ dismissModalViewControllerAnimated:YES];
9756 [window_ setUserInteractionEnabled:NO];
9757 }
9758
9759 [self reloadDataWithInvocation:nil];
9760 [self refreshIfPossible];
9761 PrintTimes();
9762
9763 [self disemulate];
9764
9765 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9766 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9767 int standardIndex = 0;
9768 NSArray *standard = [self defaultStartPages];
9769
9770 BOOL valid = YES;
9771
9772 if (saved == nil)
9773 valid = NO;
9774
9775 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9776 if (valid && closed != nil) {
9777 NSTimeInterval interval([closed timeIntervalSinceNow]);
9778 // XXX: Is 15 minutes the optimal time here?
9779 if (interval > 0 && interval <= -(15*60))
9780 valid = NO;
9781 }
9782
9783 if (valid && [saved count] != [standard count])
9784 valid = NO;
9785
9786 if (valid) {
9787 for (unsigned int i = 0; i < [standard count]; i++) {
9788 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9789 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9790 // but it's good enough for now.
9791 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9792 valid = NO;
9793 break;
9794 }
9795 }
9796 }
9797
9798 NSArray *items = nil;
9799 if (valid) {
9800 [tabbar_ setSelectedIndex:savedIndex];
9801 items = saved;
9802 } else {
9803 [tabbar_ setSelectedIndex:standardIndex];
9804 items = standard;
9805 }
9806
9807 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9808 NSArray *stack = [items objectAtIndex:tab];
9809 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9810 NSMutableArray *current = [NSMutableArray array];
9811
9812 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9813 NSString *addr = [stack objectAtIndex:nav];
9814 NSURL *url = [NSURL URLWithString:addr];
9815 CyteViewController *page = [self pageForURL:url forExternal:NO];
9816 if (page != nil)
9817 [current addObject:page];
9818 }
9819
9820 [navigation setViewControllers:current];
9821 }
9822
9823 // (Try to) show the startup URL.
9824 if (starturl_ != nil) {
9825 [self openCydiaURL:starturl_ forExternal:NO];
9826 starturl_ = nil;
9827 }
9828 }
9829
9830 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9831 if (item != nil && IsWildcat_) {
9832 [sheet showFromBarButtonItem:item animated:YES];
9833 } else {
9834 [sheet showInView:window_];
9835 }
9836 }
9837
9838 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9839 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9840 [progress setTitle:task];
9841 [progress addProgressEvent:event];
9842 }
9843
9844 - (void) addProgressEventForTask:(NSArray *)data {
9845 CydiaProgressEvent *event([data objectAtIndex:0]);
9846 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9847 [self addProgressEvent:event forTask:task];
9848 }
9849
9850 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9851 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9852 }
9853
9854 @end
9855
9856 /*IMP alloc_;
9857 id Alloc_(id self, SEL selector) {
9858 id object = alloc_(self, selector);
9859 lprintf("[%s]A-%p\n", self->isa->name, object);
9860 return object;
9861 }*/
9862
9863 /*IMP dealloc_;
9864 id Dealloc_(id self, SEL selector) {
9865 id object = dealloc_(self, selector);
9866 lprintf("[%s]D-%p\n", self->isa->name, object);
9867 return object;
9868 }*/
9869
9870 Class $WebDefaultUIKitDelegate;
9871
9872 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9873 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9874 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9875 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9876 }
9877
9878 static NSSet *MobilizedFiles_;
9879
9880 static NSURL *MobilizeURL(NSURL *url) {
9881 NSString *path([url path]);
9882 if ([path hasPrefix:@"/var/root/"]) {
9883 NSString *file([path substringFromIndex:10]);
9884 if ([MobilizedFiles_ containsObject:file])
9885 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9886 }
9887
9888 return url;
9889 }
9890
9891 Class $CFXPreferencesPropertyListSource;
9892 @class CFXPreferencesPropertyListSource;
9893
9894 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9895 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9896 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9897 url = MobilizeURL(url);
9898 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9899 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9900 url = old;
9901 [pool release];
9902 return value;
9903 }
9904
9905 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9906 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9907 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9908 url = MobilizeURL(url);
9909 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9910 //NSLog(@"%@ %@", [url absoluteString], value);
9911 url = old;
9912 [pool release];
9913 return value;
9914 }
9915
9916 Class $NSURLConnection;
9917
9918 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9919 NSMutableURLRequest *copy([request mutableCopy]);
9920
9921 NSURL *url([copy URL]);
9922
9923 NSString *href([url absoluteString]);
9924 NSString *host([url host]);
9925 NSString *scheme([[url scheme] lowercaseString]);
9926
9927 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9928
9929 @synchronized (HostConfig_) {
9930 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9931 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9932 [copy setHTTPShouldUsePipelining:YES];
9933
9934 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9935 if ([control isEqualToString:@"max-age=0"])
9936 if ([CachedURLs_ containsObject:href]) {
9937 #if !ForRelease
9938 NSLog(@"~~~: %@", href);
9939 #endif
9940
9941 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9942
9943 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9944 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9945 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9946 }
9947 }
9948
9949 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9950 } return self;
9951 }
9952
9953 int main(int argc, char *argv[]) {
9954 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9955
9956 _trace();
9957
9958 UpdateExternalStatus(0);
9959
9960 if (Class $UIDevice = objc_getClass("UIDevice")) {
9961 UIDevice *device([$UIDevice currentDevice]);
9962 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9963 } else
9964 IsWildcat_ = false;
9965
9966 UIScreen *screen([UIScreen mainScreen]);
9967 if ([screen respondsToSelector:@selector(scale)])
9968 ScreenScale_ = [screen scale];
9969 else
9970 ScreenScale_ = 1;
9971
9972 UIDevice *device([UIDevice currentDevice]);
9973 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9974 Idiom_ = @"iphone";
9975 else {
9976 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9977 if (idiom == UIUserInterfaceIdiomPhone)
9978 Idiom_ = @"iphone";
9979 else if (idiom == UIUserInterfaceIdiomPad)
9980 Idiom_ = @"ipad";
9981 else
9982 NSLog(@"unknown UIUserInterfaceIdiom!");
9983 }
9984
9985 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9986
9987 HostConfig_ = [[[NSObject alloc] init] autorelease];
9988 @synchronized (HostConfig_) {
9989 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9990 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9991 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9992 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9993 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9994 }
9995
9996 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9997
9998 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9999
10000 MobilizedFiles_ = [NSMutableSet setWithObjects:
10001 @"Library/Preferences/com.apple.Accessibility.plist",
10002 @"Library/Preferences/com.apple.preferences.sounds.plist",
10003 nil];
10004
10005 /* Library Hacks {{{ */
10006 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10007
10008 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10009
10010 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10011 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10012 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10013 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10014 }
10015
10016 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10017 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10018 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10019 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10020 }
10021
10022 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10023 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10024 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10025 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10026 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10027 }
10028
10029 $NSURLConnection = objc_getClass("NSURLConnection");
10030 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10031 if (NSURLConnection$init$ != NULL) {
10032 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10033 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10034 }
10035 /* }}} */
10036 /* Set Locale {{{ */
10037 Locale_ = CFLocaleCopyCurrent();
10038 Languages_ = [NSLocale preferredLanguages];
10039
10040 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10041 //NSLog(@"%@", [Languages_ description]);
10042
10043 const char *lang;
10044 if (Locale_ != NULL)
10045 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10046 else if (Languages_ != nil && [Languages_ count] != 0)
10047 lang = [[Languages_ objectAtIndex:0] UTF8String];
10048 else
10049 // XXX: consider just setting to C and then falling through?
10050 lang = NULL;
10051
10052 if (lang != NULL) {
10053 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10054 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10055 }
10056
10057 NSLog(@"Setting Language: %s", lang);
10058
10059 if (lang != NULL) {
10060 setenv("LANG", lang, true);
10061 std::setlocale(LC_ALL, lang);
10062 }
10063 /* }}} */
10064
10065 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10066
10067 /* Parse Arguments {{{ */
10068 bool substrate(false);
10069
10070 if (argc != 0) {
10071 char **args(argv);
10072 int arge(1);
10073
10074 for (int argi(1); argi != argc; ++argi)
10075 if (strcmp(argv[argi], "--") == 0) {
10076 arge = argi;
10077 argv[argi] = argv[0];
10078 argv += argi;
10079 argc -= argi;
10080 break;
10081 }
10082
10083 for (int argi(1); argi != arge; ++argi)
10084 if (strcmp(args[argi], "--substrate") == 0)
10085 substrate = true;
10086 else
10087 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10088 }
10089 /* }}} */
10090
10091 App_ = [[NSBundle mainBundle] bundlePath];
10092 Advanced_ = YES;
10093
10094 setuid(0);
10095 setgid(0);
10096
10097 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10098 alloc_ = alloc->method_imp;
10099 alloc->method_imp = (IMP) &Alloc_;*/
10100
10101 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10102 dealloc_ = dealloc->method_imp;
10103 dealloc->method_imp = (IMP) &Dealloc_;*/
10104
10105 /* System Information {{{ */
10106 size_t size;
10107
10108 int maxproc;
10109 size = sizeof(maxproc);
10110 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10111 perror("sysctlbyname(\"kern.maxproc\", ?)");
10112 else if (maxproc < 64) {
10113 maxproc = 64;
10114 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10115 perror("sysctlbyname(\"kern.maxproc\", #)");
10116 }
10117
10118 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10119 char *osversion = new char[size];
10120 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10121 perror("sysctlbyname(\"kern.osversion\", ?)");
10122 else
10123 System_ = [NSString stringWithUTF8String:osversion];
10124
10125 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10126 char *machine = new char[size];
10127 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10128 perror("sysctlbyname(\"hw.machine\", ?)");
10129 else
10130 Machine_ = machine;
10131
10132 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10133 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10134 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10135
10136 UniqueID_ = [device uniqueIdentifier];
10137
10138 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10139 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10140 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10141
10142 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10143 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10144 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10145
10146 if (mcc != NULL && mnc != NULL)
10147 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10148
10149 if (mnc != NULL)
10150 CFRelease(mnc);
10151 if (mcc != NULL)
10152 CFRelease(mcc);
10153
10154 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10155 Build_ = [system objectForKey:@"ProductBuildVersion"];
10156 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10157 Product_ = [info objectForKey:@"SafariProductVersion"];
10158 Safari_ = [info objectForKey:@"CFBundleVersion"];
10159 }
10160 /* }}} */
10161 /* Load Database {{{ */
10162 _trace();
10163 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10164 _trace();
10165 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10166
10167 if (Metadata_ == NULL)
10168 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10169 else {
10170 Settings_ = [Metadata_ objectForKey:@"Settings"];
10171
10172 Packages_ = [Metadata_ objectForKey:@"Packages"];
10173
10174 Values_ = [Metadata_ objectForKey:@"Values"];
10175 Sections_ = [Metadata_ objectForKey:@"Sections"];
10176 Sources_ = [Metadata_ objectForKey:@"Sources"];
10177
10178 Token_ = [Metadata_ objectForKey:@"Token"];
10179
10180 Version_ = [Metadata_ objectForKey:@"Version"];
10181
10182 @synchronized (HostConfig_) {
10183 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10184 }
10185 }
10186
10187 if (Settings_ != nil)
10188 Role_ = [Settings_ objectForKey:@"Role"];
10189
10190 if (Values_ == nil) {
10191 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10192 [Metadata_ setObject:Values_ forKey:@"Values"];
10193 }
10194
10195 if (Sections_ == nil) {
10196 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10197 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10198 }
10199
10200 if (Sources_ == nil) {
10201 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10202 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10203 }
10204
10205 if (Version_ == nil) {
10206 Version_ = [NSNumber numberWithUnsignedInt:0];
10207 [Metadata_ setObject:Version_ forKey:@"Version"];
10208 }
10209
10210 @synchronized (HostConfig_) {
10211 if (CydiaSource_ == nil) {
10212 CydiaSource_ = @"apt.saurik.com";
10213 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10214 }
10215 }
10216
10217 if ([Version_ unsignedIntValue] == 0) {
10218 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10219 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10220 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10221 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10222
10223 Version_ = [NSNumber numberWithUnsignedInt:1];
10224 [Metadata_ setObject:Version_ forKey:@"Version"];
10225
10226 Changed_ = true;
10227 }
10228 /* }}} */
10229
10230 WriteSources();
10231
10232 _trace();
10233 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10234 _trace();
10235
10236 if (Packages_ != nil) {
10237 bool fail(false);
10238 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10239 _trace();
10240
10241 if (!fail) {
10242 [Metadata_ removeObjectForKey:@"Packages"];
10243 Packages_ = nil;
10244 Changed_ = true;
10245 }
10246 }
10247
10248 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10249
10250 #define MobileSubstrate_(name) \
10251 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10252 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10253 if (handle == NULL) \
10254 NSLog(@"%s", dlerror()); \
10255 }
10256
10257 MobileSubstrate_(Activator)
10258 MobileSubstrate_(libstatusbar)
10259 MobileSubstrate_(SimulatedKeyEvents)
10260 MobileSubstrate_(WinterBoard)
10261
10262 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10263 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10264
10265 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10266
10267 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10268 unlink("/tmp/.cydia.fw");
10269 goto firmware;
10270 } else if (access("/User", F_OK) != 0 || version < 4) {
10271 firmware:
10272 _trace();
10273 system("/usr/libexec/cydia/firmware.sh");
10274 _trace();
10275 }
10276
10277 _assert([[NSFileManager defaultManager]
10278 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10279 withIntermediateDirectories:YES
10280 attributes:nil
10281 error:NULL
10282 ]);
10283
10284 if (access("/tmp/cydia.chk", F_OK) == 0) {
10285 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10286 _assert(errno == ENOENT);
10287 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10288 _assert(errno == ENOENT);
10289 }
10290
10291 /* APT Initialization {{{ */
10292 _assert(pkgInitConfig(*_config));
10293 _assert(pkgInitSystem(*_config, _system));
10294
10295 if (lang != NULL)
10296 _config->Set("APT::Acquire::Translation", lang);
10297
10298 // XXX: this timeout might be important :(
10299 //_config->Set("Acquire::http::Timeout", 15);
10300
10301 _config->Set("Acquire::http::MaxParallel", 3);
10302 /* }}} */
10303 /* Color Choices {{{ */
10304 space_ = CGColorSpaceCreateDeviceRGB();
10305
10306 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10307 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10308 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10309 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10310 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10311 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10312 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10313 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10314 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10315
10316 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10317 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10318 /* }}}*/
10319 /* UIKit Configuration {{{ */
10320 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10321 if ($GSFontSetUseLegacyFontMetrics != NULL)
10322 $GSFontSetUseLegacyFontMetrics(YES);
10323
10324 // XXX: I have a feeling this was important
10325 //UIKeyboardDisableAutomaticAppearance();
10326 /* }}} */
10327
10328 Colon_ = UCLocalize("COLON_DELIMITED");
10329 Elision_ = UCLocalize("ELISION");
10330 Error_ = UCLocalize("ERROR");
10331 Warning_ = UCLocalize("WARNING");
10332
10333 _trace();
10334 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10335
10336 CGColorSpaceRelease(space_);
10337 CFRelease(Locale_);
10338
10339 [pool release];
10340 return value;
10341 }