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