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