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