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