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