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