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