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