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