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