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