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