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