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