]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Fix various forms of icon escape encoding.
[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(getMetadataValue:))
3995 return @"getMetadataValue";
3996 else if (selector == @selector(getSessionValue:))
3997 return @"getSessionValue";
3998 else if (selector == @selector(installPackages:))
3999 return @"installPackages";
4000 else if (selector == @selector(localizedStringForKey:value:table:))
4001 return @"localize";
4002 else if (selector == @selector(popViewController:))
4003 return @"popViewController";
4004 else if (selector == @selector(refreshSources))
4005 return @"refreshSources";
4006 else if (selector == @selector(removeButton))
4007 return @"removeButton";
4008 else if (selector == @selector(saveConfig))
4009 return @"saveConfig";
4010 else if (selector == @selector(setCydiaSource:))
4011 return @"setCydiaSource";
4012 else if (selector == @selector(setMetadataValue::))
4013 return @"setMetadataValue";
4014 else if (selector == @selector(setSessionValue::))
4015 return @"setSessionValue";
4016 else if (selector == @selector(substitutePackageNames:))
4017 return @"substitutePackageNames";
4018 else if (selector == @selector(scrollToBottom:))
4019 return @"scrollToBottom";
4020 else if (selector == @selector(setAllowsNavigationAction:))
4021 return @"setAllowsNavigationAction";
4022 else if (selector == @selector(setBadgeValue:))
4023 return @"setBadgeValue";
4024 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4025 return @"setButtonImage";
4026 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4027 return @"setButtonTitle";
4028 else if (selector == @selector(setHidesBackButton:))
4029 return @"setHidesBackButton";
4030 else if (selector == @selector(setHidesNavigationBar:))
4031 return @"setHidesNavigationBar";
4032 else if (selector == @selector(setNavigationBarStyle:))
4033 return @"setNavigationBarStyle";
4034 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4035 return @"setNavigationBarTintColor";
4036 else if (selector == @selector(setPasteboardString:))
4037 return @"setPasteboardString";
4038 else if (selector == @selector(setPasteboardURL:))
4039 return @"setPasteboardURL";
4040 else if (selector == @selector(setToken:))
4041 return @"setToken";
4042 else if (selector == @selector(setViewportWidth:))
4043 return @"setViewportWidth";
4044 else if (selector == @selector(statfs:))
4045 return @"statfs";
4046 else if (selector == @selector(supports:))
4047 return @"supports";
4048 else if (selector == @selector(unload))
4049 return @"unload";
4050 else
4051 return nil;
4052 }
4053
4054 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4055 return [self webScriptNameForSelector:selector] == nil;
4056 }
4057
4058 - (BOOL) supports:(NSString *)feature {
4059 return [feature isEqualToString:@"window.open"];
4060 }
4061
4062 - (void) unload {
4063 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4064 }
4065
4066 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4067 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4068 }
4069
4070 - (NSNumber *) getKernelNumber:(NSString *)name {
4071 const char *string([name UTF8String]);
4072
4073 size_t size;
4074 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4075 return (id) [NSNull null];
4076
4077 if (size != sizeof(int))
4078 return (id) [NSNull null];
4079
4080 int value;
4081 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4082 return (id) [NSNull null];
4083
4084 return [NSNumber numberWithInt:value];
4085 }
4086
4087 - (NSString *) getKernelString:(NSString *)name {
4088 const char *string([name UTF8String]);
4089
4090 size_t size;
4091 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4092 return (id) [NSNull null];
4093
4094 char value[size + 1];
4095 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4096 return (id) [NSNull null];
4097
4098 // XXX: just in case you request something ludicrous
4099 value[size] = '\0';
4100
4101 return [NSString stringWithCString:value];
4102 }
4103
4104 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4105 NSObject *value(CYIOGetValue([path UTF8String], entry));
4106
4107 if (value != nil)
4108 if ([value isKindOfClass:[NSData class]])
4109 value = CYHex((NSData *) value);
4110
4111 return value;
4112 }
4113
4114 - (void) _setCydiaSource:(NSString *)source {
4115 @synchronized (HostConfig_) {
4116 CydiaSource_ = source;
4117 [Metadata_ setObject:source forKey:@"CydiaSource"];
4118 }
4119
4120 Changed_ = true;
4121 }
4122
4123 - (void) setCydiaSource:(NSString *)source {
4124 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4125 }
4126
4127 - (NSString *) cydiaSource {
4128 @synchronized (HostConfig_) {
4129 return (id) CydiaSource_ ?: [NSNull null];
4130 }
4131 }
4132
4133 - (id) getMetadataValue:(NSString *)key {
4134 @synchronized (Values_) {
4135 return [Values_ objectForKey:key];
4136 } }
4137
4138 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4139 @synchronized (Values_) {
4140 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4141 [Values_ removeObjectForKey:key];
4142 else
4143 [Values_ setObject:value forKey:key];
4144
4145 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4146 } }
4147
4148 - (id) getSessionValue:(NSString *)key {
4149 @synchronized (SessionData_) {
4150 return [SessionData_ objectForKey:key];
4151 } }
4152
4153 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4154 @synchronized (SessionData_) {
4155 if (value == (id) [WebUndefined undefined])
4156 [SessionData_ removeObjectForKey:key];
4157 else
4158 [SessionData_ setObject:value forKey:key];
4159 } }
4160
4161 - (void) addBridgedHost:(NSString *)host {
4162 @synchronized (HostConfig_) {
4163 [BridgedHosts_ addObject:host];
4164 } }
4165
4166 - (void) addInsecureHost:(NSString *)host {
4167 @synchronized (HostConfig_) {
4168 [InsecureHosts_ addObject:host];
4169 } }
4170
4171 - (void) addTokenHost:(NSString *)host {
4172 @synchronized (HostConfig_) {
4173 [TokenHosts_ addObject:host];
4174 } }
4175
4176 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4177 @synchronized (HostConfig_) {
4178 if (scheme != (id) [WebUndefined undefined])
4179 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4180
4181 [PipelinedHosts_ addObject:host];
4182 } }
4183
4184 - (void) popViewController:(NSNumber *)value {
4185 if (value == (id) [WebUndefined undefined])
4186 value = [NSNumber numberWithBool:YES];
4187 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4188 }
4189
4190 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4191 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4192
4193 for (NSString *section in sections)
4194 [array addObject:section];
4195
4196 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4197 @"deb", @"Type",
4198 href, @"URI",
4199 distribution, @"Distribution",
4200 array, @"Sections",
4201 nil] waitUntilDone:NO];
4202 }
4203
4204 - (void) addTrivialSource:(NSString *)href {
4205 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4206 }
4207
4208 - (void) refreshSources {
4209 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4210 }
4211
4212 - (void) saveConfig {
4213 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4214 }
4215
4216 - (NSArray *) getAllSources {
4217 return [[Database sharedInstance] sources];
4218 }
4219
4220 - (NSArray *) getInstalledPackages {
4221 Database *database([Database sharedInstance]);
4222 @synchronized (database) {
4223 NSArray *packages([database packages]);
4224 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4225 for (Package *package in packages)
4226 if (![package uninstalled])
4227 [installed addObject:package];
4228 return installed;
4229 } }
4230
4231 - (Package *) getPackageById:(NSString *)id {
4232 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4233 [package parse];
4234 return package;
4235 } else
4236 return (Package *) [NSNull null];
4237 }
4238
4239 - (NSString *) getLocaleIdentifier {
4240 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4241 }
4242
4243 - (NSArray *) getPreferredLanguages {
4244 return Languages_;
4245 }
4246
4247 - (NSArray *) statfs:(NSString *)path {
4248 struct statfs stat;
4249
4250 if (path == nil || statfs([path UTF8String], &stat) == -1)
4251 return nil;
4252
4253 return [NSArray arrayWithObjects:
4254 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4255 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4256 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4257 nil];
4258 }
4259
4260 - (NSNumber *) du:(NSString *)path {
4261 NSNumber *value(nil);
4262
4263 int fds[2];
4264 _assert(pipe(fds) != -1);
4265
4266 pid_t pid(ExecFork());
4267 if (pid == 0) {
4268 _assert(dup2(fds[1], 1) != -1);
4269 _assert(close(fds[0]) != -1);
4270 _assert(close(fds[1]) != -1);
4271 /* XXX: this should probably not use du */
4272 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4273 exit(1);
4274 _assert(false);
4275 }
4276
4277 _assert(close(fds[1]) != -1);
4278
4279 if (FILE *du = fdopen(fds[0], "r")) {
4280 char line[1024];
4281 while (fgets(line, sizeof(line), du) != NULL) {
4282 size_t length(strlen(line));
4283 while (length != 0 && line[length - 1] == '\n')
4284 line[--length] = '\0';
4285 if (char *tab = strchr(line, '\t')) {
4286 *tab = '\0';
4287 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4288 }
4289 }
4290
4291 fclose(du);
4292 } else _assert(close(fds[0]));
4293
4294 int status;
4295 wait:
4296 if (waitpid(pid, &status, 0) == -1)
4297 if (errno == EINTR)
4298 goto wait;
4299 else _assert(false);
4300
4301 return value;
4302 }
4303
4304 - (void) close {
4305 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4306 }
4307
4308 - (void) installPackages:(NSArray *)packages {
4309 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4310 }
4311
4312 - (NSString *) substitutePackageNames:(NSString *)message {
4313 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4314 for (size_t i(0), e([words count]); i != e; ++i) {
4315 NSString *word([words objectAtIndex:i]);
4316 if (Package *package = [[Database sharedInstance] packageWithName:word])
4317 [words replaceObjectAtIndex:i withObject:[package name]];
4318 }
4319
4320 return [words componentsJoinedByString:@" "];
4321 }
4322
4323 - (void) removeButton {
4324 [indirect_ removeButton];
4325 }
4326
4327 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4328 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4329 }
4330
4331 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4332 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4333 }
4334
4335 - (void) setBadgeValue:(id)value {
4336 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4337 }
4338
4339 - (void) setAllowsNavigationAction:(NSString *)value {
4340 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4341 }
4342
4343 - (void) setHidesBackButton:(NSString *)value {
4344 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4345 }
4346
4347 - (void) setHidesNavigationBar:(NSString *)value {
4348 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4349 }
4350
4351 - (void) setNavigationBarStyle:(NSString *)value {
4352 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4353 }
4354
4355 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4356 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4357 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4358 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4359 }
4360
4361 - (void) setPasteboardString:(NSString *)value {
4362 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4363 }
4364
4365 - (void) setPasteboardURL:(NSString *)value {
4366 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4367 }
4368
4369 - (void) _setToken:(NSString *)token {
4370 Token_ = token;
4371
4372 if (token == nil)
4373 [Metadata_ removeObjectForKey:@"Token"];
4374 else
4375 [Metadata_ setObject:Token_ forKey:@"Token"];
4376
4377 Changed_ = true;
4378 }
4379
4380 - (void) setToken:(NSString *)token {
4381 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4382 }
4383
4384 - (void) scrollToBottom:(NSNumber *)animated {
4385 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4386 }
4387
4388 - (void) setViewportWidth:(float)width {
4389 [indirect_ setViewportWidthOnMainThread:width];
4390 }
4391
4392 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4393 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4394 unsigned count([arguments count]);
4395 id values[count];
4396 for (unsigned i(0); i != count; ++i)
4397 values[i] = [arguments objectAtIndex:i];
4398 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4399 }
4400
4401 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4402 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4403 value = nil;
4404 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4405 table = nil;
4406 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4407 }
4408
4409 @end
4410 /* }}} */
4411
4412 @interface NSURL (CydiaSecure)
4413 @end
4414
4415 @implementation NSURL (CydiaSecure)
4416
4417 - (bool) isCydiaSecure {
4418 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4419 return true;
4420
4421 @synchronized (HostConfig_) {
4422 if ([InsecureHosts_ containsObject:[self host]])
4423 return true;
4424 }
4425
4426 return false;
4427 }
4428
4429 @end
4430
4431 /* Cydia Browser Controller {{{ */
4432 @implementation CydiaWebViewController
4433
4434 - (NSURL *) navigationURL {
4435 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4436 }
4437
4438 + (void) initialize {
4439 Diversions_ = [NSMutableSet setWithCapacity:0];
4440 }
4441
4442 + (void) addDiversion:(Diversion *)diversion {
4443 [Diversions_ addObject:diversion];
4444 }
4445
4446 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4447 [super webView:view didClearWindowObject:window forFrame:frame];
4448
4449 WebDataSource *source([frame dataSource]);
4450 NSURLResponse *response([source response]);
4451 NSURL *url([response URL]);
4452 NSString *scheme([[url scheme] lowercaseString]);
4453
4454 bool bridged(false);
4455
4456 @synchronized (HostConfig_) {
4457 if ([scheme isEqualToString:@"file"])
4458 bridged = true;
4459 else if ([scheme isEqualToString:@"https"])
4460 if ([BridgedHosts_ containsObject:[url host]])
4461 bridged = true;
4462 }
4463
4464 if (bridged)
4465 [window setValue:cydia_ forKey:@"cydia"];
4466 }
4467
4468 - (void) _setupMail:(MFMailComposeViewController *)controller {
4469 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4470
4471 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4472 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4473 }
4474
4475 - (NSURL *) URLWithURL:(NSURL *)url {
4476 return [Diversion divertURL:url];
4477 }
4478
4479 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4480 NSURL *url([request URL]);
4481 NSString *host([url host]);
4482
4483 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4484
4485 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4486 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4487 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4488 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4489
4490 bool token;
4491 @synchronized (HostConfig_) {
4492 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4493 }
4494
4495 if ([url isCydiaSecure] && token) {
4496 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4497 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4498 }
4499
4500 return copy;
4501 }
4502
4503 - (void) setDelegate:(id)delegate {
4504 [super setDelegate:delegate];
4505 [cydia_ setDelegate:delegate];
4506 }
4507
4508 - (NSString *) applicationNameForUserAgent {
4509 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4510
4511 if (Safari_ != nil)
4512 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4513 if (Build_ != nil)
4514 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4515 if (Product_ != nil)
4516 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4517
4518 return application;
4519 }
4520
4521 - (id) init {
4522 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4523 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4524 } return self;
4525 }
4526
4527 @end
4528 /* }}} */
4529
4530 // CydiaScript {{{
4531 @interface NSObject (CydiaScript)
4532 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4533 @end
4534
4535 @implementation NSObject (CydiaScript)
4536
4537 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4538 return self;
4539 }
4540
4541 @end
4542
4543 @implementation NSArray (CydiaScript)
4544
4545 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4546 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4547 for (size_t i(0), e([self count]); i != e; ++i)
4548 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4549 return object;
4550 }
4551
4552 @end
4553
4554 @implementation NSDictionary (CydiaScript)
4555
4556 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4557 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4558 for (id i in self)
4559 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4560 return object;
4561 }
4562
4563 @end
4564 // }}}
4565
4566 /* Confirmation Controller {{{ */
4567 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4568 if (!iterator.end())
4569 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4570 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4571 continue;
4572 pkgCache::PkgIterator package(dep.TargetPkg());
4573 if (package.end())
4574 continue;
4575 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4576 return true;
4577 }
4578
4579 return false;
4580 }
4581
4582 @protocol ConfirmationControllerDelegate
4583 - (void) cancelAndClear:(bool)clear;
4584 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4585 - (void) queue;
4586 @end
4587
4588 @interface ConfirmationController : CydiaWebViewController {
4589 _transient Database *database_;
4590
4591 _H<UIAlertView> essential_;
4592
4593 _H<NSDictionary> changes_;
4594 _H<NSMutableArray> issues_;
4595 _H<NSDictionary> sizes_;
4596
4597 BOOL substrate_;
4598 }
4599
4600 - (id) initWithDatabase:(Database *)database;
4601
4602 @end
4603
4604 @implementation ConfirmationController
4605
4606 - (void) complete {
4607 if (substrate_)
4608 RestartSubstrate_ = true;
4609 [delegate_ confirmWithNavigationController:[self navigationController]];
4610 }
4611
4612 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4613 NSString *context([alert context]);
4614
4615 if ([context isEqualToString:@"remove"]) {
4616 if (button == [alert cancelButtonIndex])
4617 [self dismissModalViewControllerAnimated:YES];
4618 else if (button == [alert firstOtherButtonIndex]) {
4619 [self complete];
4620 }
4621
4622 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4623 } else if ([context isEqualToString:@"unable"]) {
4624 [self dismissModalViewControllerAnimated:YES];
4625 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4626 } else {
4627 [super alertView:alert clickedButtonAtIndex:button];
4628 }
4629 }
4630
4631 - (void) _doContinue {
4632 [self dismissModalViewControllerAnimated:YES];
4633 [delegate_ cancelAndClear:NO];
4634 }
4635
4636 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4637 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4638 return nil;
4639 }
4640
4641 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4642 [super webView:view didClearWindowObject:window forFrame:frame];
4643
4644 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4645 (id) changes_, @"changes",
4646 (id) issues_, @"issues",
4647 (id) sizes_, @"sizes",
4648 self, @"queue",
4649 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4650 }
4651
4652 - (id) initWithDatabase:(Database *)database {
4653 if ((self = [super init]) != nil) {
4654 database_ = database;
4655
4656 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4657 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4658 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4659 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4660 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4661
4662 bool remove(false);
4663
4664 pkgCacheFile &cache([database_ cache]);
4665 NSArray *packages([database_ packages]);
4666 pkgDepCache::Policy *policy([database_ policy]);
4667
4668 issues_ = [NSMutableArray arrayWithCapacity:4];
4669
4670 for (Package *package in packages) {
4671 pkgCache::PkgIterator iterator([package iterator]);
4672 NSString *name([package id]);
4673
4674 if ([package broken]) {
4675 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4676
4677 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4678 name, @"package",
4679 reasons, @"reasons",
4680 nil]];
4681
4682 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4683 if (ver.end())
4684 continue;
4685
4686 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4687 pkgCache::DepIterator start;
4688 pkgCache::DepIterator end;
4689 dep.GlobOr(start, end); // ++dep
4690
4691 if (!cache->IsImportantDep(end))
4692 continue;
4693 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4694 continue;
4695
4696 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4697
4698 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4699 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4700 clauses, @"clauses",
4701 nil]];
4702
4703 _forever {
4704 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4705
4706 pkgCache::PkgIterator target(start.TargetPkg());
4707 if (target->ProvidesList != 0)
4708 reason = @"missing";
4709 else {
4710 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4711 if (!ver.end()) {
4712 reason = @"installed";
4713 installed = [NSString stringWithUTF8String:ver.VerStr()];
4714 } else if (!cache[target].CandidateVerIter(cache).end())
4715 reason = @"uninstalled";
4716 else if (target->ProvidesList == 0)
4717 reason = @"uninstallable";
4718 else
4719 reason = @"virtual";
4720 }
4721
4722 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4723 [NSString stringWithUTF8String:start.CompType()], @"operator",
4724 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4725 nil]);
4726
4727 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4728 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4729 version, @"version",
4730 reason, @"reason",
4731 installed, @"installed",
4732 nil]];
4733
4734 // yes, seriously. (wtf?)
4735 if (start == end)
4736 break;
4737 ++start;
4738 }
4739 }
4740 }
4741
4742 pkgDepCache::StateCache &state(cache[iterator]);
4743
4744 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4745
4746 if (state.NewInstall())
4747 [installs addObject:name];
4748 // XXX: else if (state.Install())
4749 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4750 [reinstalls addObject:name];
4751 // XXX: move before previous if
4752 else if (state.Upgrade())
4753 [upgrades addObject:name];
4754 else if (state.Downgrade())
4755 [downgrades addObject:name];
4756 else if (!state.Delete())
4757 // XXX: _assert(state.Keep());
4758 continue;
4759 else if (special_r(name))
4760 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4761 [NSNull null], @"package",
4762 [NSArray arrayWithObjects:
4763 [NSDictionary dictionaryWithObjectsAndKeys:
4764 @"Conflicts", @"relationship",
4765 [NSArray arrayWithObjects:
4766 [NSDictionary dictionaryWithObjectsAndKeys:
4767 name, @"package",
4768 [NSNull null], @"version",
4769 @"installed", @"reason",
4770 nil],
4771 nil], @"clauses",
4772 nil],
4773 nil], @"reasons",
4774 nil]];
4775 else {
4776 if ([package essential])
4777 remove = true;
4778 [removes addObject:name];
4779 }
4780
4781 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4782 substrate_ |= DepSubstrate(iterator.CurrentVer());
4783 }
4784
4785 if (!remove)
4786 essential_ = nil;
4787 else if (Advanced_) {
4788 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4789
4790 essential_ = [[[UIAlertView alloc]
4791 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4792 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4793 delegate:self
4794 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4795 otherButtonTitles:
4796 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4797 nil
4798 ] autorelease];
4799
4800 [essential_ setContext:@"remove"];
4801 } else {
4802 essential_ = [[[UIAlertView alloc]
4803 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4804 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4805 delegate:self
4806 cancelButtonTitle:UCLocalize("OKAY")
4807 otherButtonTitles:nil
4808 ] autorelease];
4809
4810 [essential_ setContext:@"unable"];
4811 }
4812
4813 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4814 installs, @"installs",
4815 reinstalls, @"reinstalls",
4816 upgrades, @"upgrades",
4817 downgrades, @"downgrades",
4818 removes, @"removes",
4819 nil];
4820
4821 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4822 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4823 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4824 nil];
4825
4826 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4827 } return self;
4828 }
4829
4830 - (UIBarButtonItem *) leftButton {
4831 return [[[UIBarButtonItem alloc]
4832 initWithTitle:UCLocalize("CANCEL")
4833 style:UIBarButtonItemStylePlain
4834 target:self
4835 action:@selector(cancelButtonClicked)
4836 ] autorelease];
4837 }
4838
4839 #if !AlwaysReload
4840 - (void) applyRightButton {
4841 if ([issues_ count] == 0 && ![self isLoading])
4842 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4843 initWithTitle:UCLocalize("CONFIRM")
4844 style:UIBarButtonItemStyleDone
4845 target:self
4846 action:@selector(confirmButtonClicked)
4847 ] autorelease]];
4848 else
4849 [[self navigationItem] setRightBarButtonItem:nil];
4850 }
4851 #endif
4852
4853 - (void) cancelButtonClicked {
4854 [self dismissModalViewControllerAnimated:YES];
4855 [delegate_ cancelAndClear:YES];
4856 }
4857
4858 #if !AlwaysReload
4859 - (void) confirmButtonClicked {
4860 if (essential_ != nil)
4861 [essential_ show];
4862 else
4863 [self complete];
4864 }
4865 #endif
4866
4867 @end
4868 /* }}} */
4869
4870 /* Progress Data {{{ */
4871 @interface CydiaProgressData : NSObject {
4872 _transient id delegate_;
4873
4874 bool running_;
4875 float percent_;
4876
4877 float current_;
4878 float total_;
4879 float speed_;
4880
4881 _H<NSMutableArray> events_;
4882 _H<NSString> title_;
4883
4884 _H<NSString> status_;
4885 _H<NSString> finish_;
4886 }
4887
4888 @end
4889
4890 @implementation CydiaProgressData
4891
4892 + (NSArray *) _attributeKeys {
4893 return [NSArray arrayWithObjects:
4894 @"current",
4895 @"events",
4896 @"finish",
4897 @"percent",
4898 @"running",
4899 @"speed",
4900 @"title",
4901 @"total",
4902 nil];
4903 }
4904
4905 - (NSArray *) attributeKeys {
4906 return [[self class] _attributeKeys];
4907 }
4908
4909 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4910 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4911 }
4912
4913 - (id) init {
4914 if ((self = [super init]) != nil) {
4915 events_ = [NSMutableArray arrayWithCapacity:32];
4916 } return self;
4917 }
4918
4919 - (void) setDelegate:(id)delegate {
4920 delegate_ = delegate;
4921 }
4922
4923 - (void) setPercent:(float)value {
4924 percent_ = value;
4925 }
4926
4927 - (NSNumber *) percent {
4928 return [NSNumber numberWithFloat:percent_];
4929 }
4930
4931 - (void) setCurrent:(float)value {
4932 current_ = value;
4933 }
4934
4935 - (NSNumber *) current {
4936 return [NSNumber numberWithFloat:current_];
4937 }
4938
4939 - (void) setTotal:(float)value {
4940 total_ = value;
4941 }
4942
4943 - (NSNumber *) total {
4944 return [NSNumber numberWithFloat:total_];
4945 }
4946
4947 - (void) setSpeed:(float)value {
4948 speed_ = value;
4949 }
4950
4951 - (NSNumber *) speed {
4952 return [NSNumber numberWithFloat:speed_];
4953 }
4954
4955 - (NSArray *) events {
4956 return events_;
4957 }
4958
4959 - (void) removeAllEvents {
4960 [events_ removeAllObjects];
4961 }
4962
4963 - (void) addEvent:(CydiaProgressEvent *)event {
4964 [events_ addObject:event];
4965 }
4966
4967 - (void) setTitle:(NSString *)text {
4968 title_ = text;
4969 }
4970
4971 - (NSString *) title {
4972 return title_;
4973 }
4974
4975 - (void) setFinish:(NSString *)text {
4976 finish_ = text;
4977 }
4978
4979 - (NSString *) finish {
4980 return (id) finish_ ?: [NSNull null];
4981 }
4982
4983 - (void) setRunning:(bool)running {
4984 running_ = running;
4985 }
4986
4987 - (NSNumber *) running {
4988 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4989 }
4990
4991 @end
4992 /* }}} */
4993 /* Progress Controller {{{ */
4994 @interface ProgressController : CydiaWebViewController <
4995 ProgressDelegate
4996 > {
4997 _transient Database *database_;
4998 _H<CydiaProgressData, 1> progress_;
4999 unsigned cancel_;
5000 }
5001
5002 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5003
5004 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5005
5006 - (void) setTitle:(NSString *)title;
5007 - (void) setCancellable:(bool)cancellable;
5008
5009 @end
5010
5011 @implementation ProgressController
5012
5013 - (void) dealloc {
5014 [database_ setProgressDelegate:nil];
5015 [super dealloc];
5016 }
5017
5018 - (UIBarButtonItem *) leftButton {
5019 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5020 initWithTitle:UCLocalize("CANCEL")
5021 style:UIBarButtonItemStylePlain
5022 target:self
5023 action:@selector(cancel)
5024 ] autorelease] : nil;
5025 }
5026
5027 - (void) updateCancel {
5028 [super applyLeftButton];
5029 }
5030
5031 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5032 if ((self = [super init]) != nil) {
5033 database_ = database;
5034 delegate_ = delegate;
5035
5036 [database_ setProgressDelegate:self];
5037
5038 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5039 [progress_ setDelegate:self];
5040
5041 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5042
5043 [scroller_ setBackgroundColor:[UIColor blackColor]];
5044
5045 [[self navigationItem] setHidesBackButton:YES];
5046
5047 [self updateCancel];
5048 } return self;
5049 }
5050
5051 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5052 [super webView:view didClearWindowObject:window forFrame:frame];
5053 [window setValue:progress_ forKey:@"cydiaProgress"];
5054 }
5055
5056 - (void) updateProgress {
5057 [self dispatchEvent:@"CydiaProgressUpdate"];
5058 }
5059
5060 - (void) viewWillAppear:(BOOL)animated {
5061 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5062 [super viewWillAppear:animated];
5063 }
5064
5065 - (void) close {
5066 UpdateExternalStatus(0);
5067
5068 switch (Finish_) {
5069 case 0:
5070 break;
5071
5072 case 1:
5073 [delegate_ terminateWithSuccess];
5074 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5075 [delegate_ suspendWithAnimation:YES];
5076 else
5077 [delegate_ suspend];*/
5078 break;
5079
5080 case 2:
5081 _trace();
5082 goto reload;
5083
5084 case 3:
5085 _trace();
5086 goto reload;
5087
5088 reload:
5089 system("/usr/bin/sbreload");
5090 _trace();
5091 break;
5092
5093 case 4:
5094 _trace();
5095 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5096 SBReboot(SBSSpringBoardServerPort());
5097 else
5098 reboot2(RB_AUTOBOOT);
5099 break;
5100 }
5101
5102 [super close];
5103 }
5104
5105 - (void) setTitle:(NSString *)title {
5106 [progress_ setTitle:title];
5107 [self updateProgress];
5108 }
5109
5110 - (UIBarButtonItem *) rightButton {
5111 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5112 initWithTitle:UCLocalize("CLOSE")
5113 style:UIBarButtonItemStylePlain
5114 target:self
5115 action:@selector(close)
5116 ] autorelease];
5117 }
5118
5119 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5120 UpdateExternalStatus(1);
5121
5122 [progress_ setRunning:true];
5123 [self setTitle:title];
5124 // implicit updateProgress
5125
5126 SHA1SumValue notifyconf; {
5127 FileFd file;
5128 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5129 _error->Discard();
5130 else {
5131 MMap mmap(file, MMap::ReadOnly);
5132 SHA1Summation sha1;
5133 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5134 notifyconf = sha1.Result();
5135 }
5136 }
5137
5138 SHA1SumValue springlist; {
5139 FileFd file;
5140 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5141 _error->Discard();
5142 else {
5143 MMap mmap(file, MMap::ReadOnly);
5144 SHA1Summation sha1;
5145 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5146 springlist = sha1.Result();
5147 }
5148 }
5149
5150 if (invocation != nil) {
5151 [invocation yieldToSelector:@selector(invoke)];
5152 [self setTitle:@"COMPLETE"];
5153 }
5154
5155 if (Finish_ < 4) {
5156 FileFd file;
5157 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5158 _error->Discard();
5159 else {
5160 MMap mmap(file, MMap::ReadOnly);
5161 SHA1Summation sha1;
5162 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5163 if (!(notifyconf == sha1.Result()))
5164 Finish_ = 4;
5165 }
5166 }
5167
5168 if (Finish_ < 3) {
5169 FileFd file;
5170 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5171 _error->Discard();
5172 else {
5173 MMap mmap(file, MMap::ReadOnly);
5174 SHA1Summation sha1;
5175 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5176 if (!(springlist == sha1.Result()))
5177 Finish_ = 3;
5178 }
5179 }
5180
5181 if (Finish_ < 2) {
5182 if (RestartSubstrate_)
5183 Finish_ = 2;
5184 }
5185
5186 RestartSubstrate_ = false;
5187
5188 switch (Finish_) {
5189 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5190 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5191 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5192 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5193 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5194 }
5195
5196 _trace();
5197 system("su -c /usr/bin/uicache mobile");
5198 _trace();
5199
5200 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5201
5202 [progress_ setRunning:false];
5203 [self updateProgress];
5204
5205 [self applyRightButton];
5206 }
5207
5208 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5209 [progress_ addEvent:event];
5210 [self updateProgress];
5211 }
5212
5213 - (bool) isProgressCancelled {
5214 return cancel_ == 2;
5215 }
5216
5217 - (void) cancel {
5218 cancel_ = 2;
5219 [self updateCancel];
5220 }
5221
5222 - (void) setCancellable:(bool)cancellable {
5223 unsigned cancel(cancel_);
5224
5225 if (!cancellable)
5226 cancel_ = 0;
5227 else if (cancel_ == 0)
5228 cancel_ = 1;
5229
5230 if (cancel != cancel_)
5231 [self updateCancel];
5232 }
5233
5234 - (void) setProgressCancellable:(NSNumber *)cancellable {
5235 [self setCancellable:[cancellable boolValue]];
5236 }
5237
5238 - (void) setProgressPercent:(NSNumber *)percent {
5239 [progress_ setPercent:[percent floatValue]];
5240 [self updateProgress];
5241 }
5242
5243 - (void) setProgressStatus:(NSDictionary *)status {
5244 if (status == nil) {
5245 [progress_ setCurrent:0];
5246 [progress_ setTotal:0];
5247 [progress_ setSpeed:0];
5248 } else {
5249 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5250
5251 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5252 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5253 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5254 }
5255
5256 [self updateProgress];
5257 }
5258
5259 @end
5260 /* }}} */
5261
5262 /* Package Cell {{{ */
5263 @interface PackageCell : CyteTableViewCell <
5264 CyteTableViewCellDelegate
5265 > {
5266 _H<UIImage> icon_;
5267 _H<NSString> name_;
5268 _H<NSString> description_;
5269 bool commercial_;
5270 _H<NSString> source_;
5271 _H<UIImage> badge_;
5272 _H<Package> package_;
5273 _H<UIImage> placard_;
5274 bool summarized_;
5275 }
5276
5277 - (PackageCell *) init;
5278 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5279
5280 - (void) drawContentRect:(CGRect)rect;
5281
5282 @end
5283
5284 @implementation PackageCell
5285
5286 - (PackageCell *) init {
5287 CGRect frame(CGRectMake(0, 0, 320, 74));
5288 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5289 UIView *content([self contentView]);
5290 CGRect bounds([content bounds]);
5291
5292 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5293 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5294 [content addSubview:content_];
5295
5296 [content_ setDelegate:self];
5297 [content_ setOpaque:YES];
5298 } return self;
5299 }
5300
5301 - (NSString *) accessibilityLabel {
5302 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5303 }
5304
5305 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5306 summarized_ = summary;
5307
5308 icon_ = nil;
5309 name_ = nil;
5310 description_ = nil;
5311 source_ = nil;
5312 badge_ = nil;
5313 placard_ = nil;
5314 package_ = nil;
5315
5316 [package parse];
5317
5318 Source *source = [package source];
5319
5320 icon_ = [package icon];
5321
5322 if (NSString *name = [package name])
5323 name_ = [NSString stringWithString:name];
5324
5325 NSString *description(nil);
5326
5327 if (description == nil && IsWildcat_)
5328 description = [package longDescription];
5329 if (description == nil)
5330 description = [package shortDescription];
5331
5332 if (description != nil)
5333 description_ = [NSString stringWithString:description];
5334
5335 commercial_ = [package isCommercial];
5336
5337 package_ = package;
5338
5339 NSString *label = nil;
5340 bool trusted = false;
5341
5342 if (source != nil) {
5343 label = [source label];
5344 trusted = [source trusted];
5345 } else if ([[package id] isEqualToString:@"firmware"])
5346 label = UCLocalize("APPLE");
5347 else
5348 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5349
5350 NSString *from(label);
5351
5352 NSString *section = [package simpleSection];
5353 if (section != nil && ![section isEqualToString:label]) {
5354 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5355 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5356 }
5357
5358 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5359
5360 if (NSString *purpose = [package primaryPurpose])
5361 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5362
5363 UIColor *color;
5364 NSString *placard;
5365
5366 if (NSString *mode = [package_ mode]) {
5367 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5368 color = RemovingColor_;
5369 //placard = @"removing";
5370 } else {
5371 color = InstallingColor_;
5372 //placard = @"installing";
5373 }
5374
5375 // XXX: the removing/installing placards are not @2x
5376 placard = nil;
5377 } else {
5378 color = [UIColor whiteColor];
5379
5380 if ([package installed] != nil)
5381 placard = @"installed";
5382 else
5383 placard = nil;
5384 }
5385
5386 [content_ setBackgroundColor:color];
5387
5388 if (placard != nil)
5389 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5390
5391 [self setNeedsDisplay];
5392 [content_ setNeedsDisplay];
5393 }
5394
5395 - (void) drawSummaryContentRect:(CGRect)rect {
5396 bool highlighted(highlighted_);
5397 float width([self bounds].size.width);
5398
5399 if (icon_ != nil) {
5400 CGRect rect;
5401 rect.size = [(UIImage *) icon_ size];
5402
5403 rect.size.width /= 4;
5404 rect.size.height /= 4;
5405
5406 rect.origin.x = 14 - rect.size.width / 4;
5407 rect.origin.y = 14 - rect.size.height / 4;
5408
5409 [icon_ drawInRect:rect];
5410 }
5411
5412 if (badge_ != nil) {
5413 CGRect rect;
5414 rect.size = [(UIImage *) badge_ size];
5415
5416 rect.size.width /= 4;
5417 rect.size.height /= 4;
5418
5419 rect.origin.x = 20 - rect.size.width / 4;
5420 rect.origin.y = 20 - rect.size.height / 4;
5421
5422 [badge_ drawInRect:rect];
5423 }
5424
5425 if (highlighted)
5426 UISetColor(White_);
5427
5428 if (!highlighted)
5429 UISetColor(commercial_ ? Purple_ : Black_);
5430 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5431
5432 if (placard_ != nil)
5433 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5434 }
5435
5436 - (void) drawNormalContentRect:(CGRect)rect {
5437 bool highlighted(highlighted_);
5438 float width([self bounds].size.width);
5439
5440 if (icon_ != nil) {
5441 CGRect rect;
5442 rect.size = [(UIImage *) icon_ size];
5443
5444 rect.size.width /= 2;
5445 rect.size.height /= 2;
5446
5447 rect.origin.x = 25 - rect.size.width / 2;
5448 rect.origin.y = 25 - rect.size.height / 2;
5449
5450 [icon_ drawInRect:rect];
5451 }
5452
5453 if (badge_ != nil) {
5454 CGRect rect;
5455 rect.size = [(UIImage *) badge_ size];
5456
5457 rect.size.width /= 2;
5458 rect.size.height /= 2;
5459
5460 rect.origin.x = 36 - rect.size.width / 2;
5461 rect.origin.y = 36 - rect.size.height / 2;
5462
5463 [badge_ drawInRect:rect];
5464 }
5465
5466 if (highlighted)
5467 UISetColor(White_);
5468
5469 if (!highlighted)
5470 UISetColor(commercial_ ? Purple_ : Black_);
5471 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5472 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5473
5474 if (!highlighted)
5475 UISetColor(commercial_ ? Purplish_ : Gray_);
5476 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5477
5478 if (placard_ != nil)
5479 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5480 }
5481
5482 - (void) drawContentRect:(CGRect)rect {
5483 if (summarized_)
5484 [self drawSummaryContentRect:rect];
5485 else
5486 [self drawNormalContentRect:rect];
5487 }
5488
5489 @end
5490 /* }}} */
5491 /* Section Cell {{{ */
5492 @interface SectionCell : CyteTableViewCell <
5493 CyteTableViewCellDelegate
5494 > {
5495 _H<NSString> basic_;
5496 _H<NSString> section_;
5497 _H<NSString> name_;
5498 _H<NSString> count_;
5499 _H<UIImage> icon_;
5500 _H<UISwitch> switch_;
5501 BOOL editing_;
5502 }
5503
5504 - (void) setSection:(Section *)section editing:(BOOL)editing;
5505
5506 @end
5507
5508 @implementation SectionCell
5509
5510 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5511 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5512 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5513 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5514 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5515
5516 UIView *content([self contentView]);
5517 CGRect bounds([content bounds]);
5518
5519 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5520 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5521 [content addSubview:content_];
5522 [content_ setBackgroundColor:[UIColor whiteColor]];
5523
5524 [content_ setDelegate:self];
5525 } return self;
5526 }
5527
5528 - (void) onSwitch:(id)sender {
5529 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5530 if (metadata == nil) {
5531 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5532 [Sections_ setObject:metadata forKey:basic_];
5533 }
5534
5535 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5536 Changed_ = true;
5537 }
5538
5539 - (void) setSection:(Section *)section editing:(BOOL)editing {
5540 if (editing != editing_) {
5541 if (editing_)
5542 [switch_ removeFromSuperview];
5543 else
5544 [self addSubview:switch_];
5545 editing_ = editing;
5546 }
5547
5548 basic_ = nil;
5549 section_ = nil;
5550 name_ = nil;
5551 count_ = nil;
5552
5553 if (section == nil) {
5554 name_ = UCLocalize("ALL_PACKAGES");
5555 count_ = nil;
5556 } else {
5557 basic_ = [section name];
5558 section_ = [section localized];
5559
5560 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5561 count_ = [NSString stringWithFormat:@"%d", [section count]];
5562
5563 if (editing_)
5564 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5565 }
5566
5567 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5568 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5569
5570 [content_ setNeedsDisplay];
5571 }
5572
5573 - (void) setFrame:(CGRect)frame {
5574 [super setFrame:frame];
5575
5576 CGRect rect([switch_ frame]);
5577 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5578 }
5579
5580 - (NSString *) accessibilityLabel {
5581 return name_;
5582 }
5583
5584 - (void) drawContentRect:(CGRect)rect {
5585 bool highlighted(highlighted_ && !editing_);
5586
5587 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5588
5589 if (highlighted)
5590 UISetColor(White_);
5591
5592 float width(rect.size.width);
5593 if (editing_)
5594 width -= 87;
5595
5596 if (!highlighted)
5597 UISetColor(Black_);
5598 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5599
5600 CGSize size = [count_ sizeWithFont:Font14_];
5601
5602 UISetColor(White_);
5603 if (count_ != nil)
5604 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5605 }
5606
5607 @end
5608 /* }}} */
5609
5610 /* File Table {{{ */
5611 @interface FileTable : CyteViewController <
5612 UITableViewDataSource,
5613 UITableViewDelegate
5614 > {
5615 _transient Database *database_;
5616 _H<Package> package_;
5617 _H<NSString> name_;
5618 _H<NSMutableArray> files_;
5619 _H<UITableView, 2> list_;
5620 }
5621
5622 - (id) initWithDatabase:(Database *)database;
5623 - (void) setPackage:(Package *)package;
5624
5625 @end
5626
5627 @implementation FileTable
5628
5629 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5630 return files_ == nil ? 0 : [files_ count];
5631 }
5632
5633 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5634 return 24.0f;
5635 }*/
5636
5637 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5638 static NSString *reuseIdentifier = @"Cell";
5639
5640 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5641 if (cell == nil) {
5642 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5643 [cell setFont:[UIFont systemFontOfSize:16]];
5644 }
5645 [cell setText:[files_ objectAtIndex:indexPath.row]];
5646 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5647
5648 return cell;
5649 }
5650
5651 - (NSURL *) navigationURL {
5652 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5653 }
5654
5655 - (void) loadView {
5656 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5657
5658 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5659 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5660 [list_ setRowHeight:24.0f];
5661 [(UITableView *) list_ setDataSource:self];
5662 [list_ setDelegate:self];
5663 [[self view] addSubview:list_];
5664 }
5665
5666 - (void) viewDidLoad {
5667 [super viewDidLoad];
5668
5669 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5670 }
5671
5672 - (void) releaseSubviews {
5673 list_ = nil;
5674
5675 [super releaseSubviews];
5676 }
5677
5678 - (id) initWithDatabase:(Database *)database {
5679 if ((self = [super init]) != nil) {
5680 database_ = database;
5681
5682 files_ = [NSMutableArray arrayWithCapacity:32];
5683 } return self;
5684 }
5685
5686 - (void) setPackage:(Package *)package {
5687 package_ = nil;
5688 name_ = nil;
5689
5690 [files_ removeAllObjects];
5691
5692 if (package != nil) {
5693 package_ = package;
5694 name_ = [package id];
5695
5696 if (NSArray *files = [package files])
5697 [files_ addObjectsFromArray:files];
5698
5699 if ([files_ count] != 0) {
5700 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5701 [files_ removeObjectAtIndex:0];
5702 [files_ sortUsingSelector:@selector(compareByPath:)];
5703
5704 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5705 [stack addObject:@"/"];
5706
5707 for (int i(0), e([files_ count]); i != e; ++i) {
5708 NSString *file = [files_ objectAtIndex:i];
5709 while (![file hasPrefix:[stack lastObject]])
5710 [stack removeLastObject];
5711 NSString *directory = [stack lastObject];
5712 [stack addObject:[file stringByAppendingString:@"/"]];
5713 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5714 ([stack count] - 2) * 3, "",
5715 [file substringFromIndex:[directory length]]
5716 ]];
5717 }
5718 }
5719 }
5720
5721 [list_ reloadData];
5722 }
5723
5724 - (void) reloadData {
5725 [super reloadData];
5726
5727 [self setPackage:[database_ packageWithName:name_]];
5728 }
5729
5730 @end
5731 /* }}} */
5732 /* Package Controller {{{ */
5733 @interface CYPackageController : CydiaWebViewController <
5734 UIActionSheetDelegate
5735 > {
5736 _transient Database *database_;
5737 _H<Package> package_;
5738 _H<NSString> name_;
5739 bool commercial_;
5740 _H<NSMutableArray> buttons_;
5741 _H<UIBarButtonItem> button_;
5742 }
5743
5744 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5745
5746 @end
5747
5748 @implementation CYPackageController
5749
5750 - (NSURL *) navigationURL {
5751 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5752 }
5753
5754 /* XXX: this is not safe at all... localization of /fail/ */
5755 - (void) _clickButtonWithName:(NSString *)name {
5756 if ([name isEqualToString:UCLocalize("CLEAR")])
5757 [delegate_ clearPackage:package_];
5758 else if ([name isEqualToString:UCLocalize("INSTALL")])
5759 [delegate_ installPackage:package_];
5760 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5761 [delegate_ installPackage:package_];
5762 else if ([name isEqualToString:UCLocalize("REMOVE")])
5763 [delegate_ removePackage:package_];
5764 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5765 [delegate_ installPackage:package_];
5766 else _assert(false);
5767 }
5768
5769 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5770 NSString *context([sheet context]);
5771
5772 if ([context isEqualToString:@"modify"]) {
5773 if (button != [sheet cancelButtonIndex]) {
5774 NSString *buttonName = [buttons_ objectAtIndex:button];
5775 [self _clickButtonWithName:buttonName];
5776 }
5777
5778 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5779 }
5780 }
5781
5782 - (bool) _allowJavaScriptPanel {
5783 return commercial_;
5784 }
5785
5786 #if !AlwaysReload
5787 - (void) _customButtonClicked {
5788 int count([buttons_ count]);
5789 if (count == 0)
5790 return;
5791
5792 if (count == 1)
5793 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5794 else {
5795 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5796 [buttons addObjectsFromArray:buttons_];
5797
5798 UIActionSheet *sheet = [[[UIActionSheet alloc]
5799 initWithTitle:nil
5800 delegate:self
5801 cancelButtonTitle:nil
5802 destructiveButtonTitle:nil
5803 otherButtonTitles:nil
5804 ] autorelease];
5805
5806 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5807 if (!IsWildcat_) {
5808 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5809 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5810 }
5811 [sheet setContext:@"modify"];
5812
5813 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5814 }
5815 }
5816
5817 // We don't want to allow non-commercial packages to do custom things to the install button,
5818 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5819 - (void) customButtonClicked {
5820 if (commercial_)
5821 [super customButtonClicked];
5822 else
5823 [self _customButtonClicked];
5824 }
5825
5826 - (void) reloadButtonClicked {
5827 // Don't reload a commerical package by tapping the loading button,
5828 // but if it's not an Install button, we should forward it on.
5829 if (![package_ uninstalled])
5830 [self _customButtonClicked];
5831 }
5832
5833 - (void) applyLoadingTitle {
5834 // Don't show "Loading" as the title. Ever.
5835 }
5836
5837 - (UIBarButtonItem *) rightButton {
5838 return button_;
5839 }
5840 #endif
5841
5842 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5843 if ((self = [super init]) != nil) {
5844 database_ = database;
5845 buttons_ = [NSMutableArray arrayWithCapacity:4];
5846 name_ = [NSString stringWithString:name];
5847 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5848 } return self;
5849 }
5850
5851 - (void) reloadData {
5852 [super reloadData];
5853
5854 package_ = [database_ packageWithName:name_];
5855
5856 [buttons_ removeAllObjects];
5857
5858 if (package_ != nil) {
5859 [(Package *) package_ parse];
5860
5861 commercial_ = [package_ isCommercial];
5862
5863 if ([package_ mode] != nil)
5864 [buttons_ addObject:UCLocalize("CLEAR")];
5865 if ([package_ source] == nil);
5866 else if ([package_ upgradableAndEssential:NO])
5867 [buttons_ addObject:UCLocalize("UPGRADE")];
5868 else if ([package_ uninstalled])
5869 [buttons_ addObject:UCLocalize("INSTALL")];
5870 else
5871 [buttons_ addObject:UCLocalize("REINSTALL")];
5872 if (![package_ uninstalled])
5873 [buttons_ addObject:UCLocalize("REMOVE")];
5874 }
5875
5876 NSString *title;
5877 switch ([buttons_ count]) {
5878 case 0: title = nil; break;
5879 case 1: title = [buttons_ objectAtIndex:0]; break;
5880 default: title = UCLocalize("MODIFY"); break;
5881 }
5882
5883 button_ = [[[UIBarButtonItem alloc]
5884 initWithTitle:title
5885 style:UIBarButtonItemStylePlain
5886 target:self
5887 action:@selector(customButtonClicked)
5888 ] autorelease];
5889 }
5890
5891 - (bool) isLoading {
5892 return commercial_ ? [super isLoading] : false;
5893 }
5894
5895 @end
5896 /* }}} */
5897
5898 /* Package List Controller {{{ */
5899 @interface PackageListController : CyteViewController <
5900 UITableViewDataSource,
5901 UITableViewDelegate
5902 > {
5903 _transient Database *database_;
5904 unsigned era_;
5905 _H<NSArray> packages_;
5906 _H<NSMutableArray> sections_;
5907 _H<UITableView, 2> list_;
5908 _H<NSMutableArray> index_;
5909 _H<NSMutableDictionary> indices_;
5910 _H<NSString> title_;
5911 unsigned reloading_;
5912 }
5913
5914 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5915 - (void) setDelegate:(id)delegate;
5916 - (void) resetCursor;
5917 - (void) clearData;
5918
5919 @end
5920
5921 @implementation PackageListController
5922
5923 - (bool) isSummarized {
5924 return false;
5925 }
5926
5927 - (bool) showsSections {
5928 return true;
5929 }
5930
5931 - (void) deselectWithAnimation:(BOOL)animated {
5932 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5933 }
5934
5935 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5936 CGRect base = [[self view] bounds];
5937 base.size.height -= bounds.size.height;
5938 base.origin = [list_ frame].origin;
5939
5940 [UIView beginAnimations:nil context:NULL];
5941 [UIView setAnimationBeginsFromCurrentState:YES];
5942 [UIView setAnimationCurve:curve];
5943 [UIView setAnimationDuration:duration];
5944 [list_ setFrame:base];
5945 [UIView commitAnimations];
5946 }
5947
5948 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5949 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5950 }
5951
5952 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5953 [self resizeForKeyboardBounds:bounds duration:0];
5954 }
5955
5956 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5957 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5958 *curve = UIViewAnimationCurveEaseInOut;
5959 else
5960 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5961
5962 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5963 *duration = 0.3;
5964 else
5965 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5966 }
5967
5968 - (void) keyboardWillShow:(NSNotification *)notification {
5969 CGRect bounds;
5970 CGPoint center;
5971 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5972 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
5973
5974 NSTimeInterval duration;
5975 UIViewAnimationCurve curve;
5976 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5977
5978 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);
5979 UIViewController *base = self;
5980 while ([base parentViewController] != nil)
5981 base = [base parentViewController];
5982 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5983 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5984
5985 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5986 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5987
5988 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5989 }
5990
5991 - (void) keyboardWillHide:(NSNotification *)notification {
5992 NSTimeInterval duration;
5993 UIViewAnimationCurve curve;
5994 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5995
5996 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5997 }
5998
5999 - (void) viewWillAppear:(BOOL)animated {
6000 [super viewWillAppear:animated];
6001
6002 [self resizeForKeyboardBounds:CGRectZero];
6003 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6004 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6005 }
6006
6007 - (void) viewWillDisappear:(BOOL)animated {
6008 [super viewWillDisappear:animated];
6009
6010 [self resizeForKeyboardBounds:CGRectZero];
6011 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6012 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6013 }
6014
6015 - (void) viewDidAppear:(BOOL)animated {
6016 [super viewDidAppear:animated];
6017 [self deselectWithAnimation:animated];
6018 }
6019
6020 - (void) didSelectPackage:(Package *)package {
6021 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6022 [view setDelegate:delegate_];
6023 [[self navigationController] pushViewController:view animated:YES];
6024 }
6025
6026 #if TryIndexedCollation
6027 + (BOOL) hasIndexedCollation {
6028 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6029 }
6030 #endif
6031
6032 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6033 NSInteger count([sections_ count]);
6034 return count == 0 ? 1 : count;
6035 }
6036
6037 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6038 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6039 return nil;
6040 return [[sections_ objectAtIndex:section] name];
6041 }
6042
6043 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6044 if ([sections_ count] == 0)
6045 return 0;
6046 return [[sections_ objectAtIndex:section] count];
6047 }
6048
6049 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6050 @synchronized (database_) {
6051 if ([database_ era] != era_)
6052 return nil;
6053
6054 Section *section([sections_ objectAtIndex:[path section]]);
6055 NSInteger row([path row]);
6056 Package *package([packages_ objectAtIndex:([section row] + row)]);
6057 return [[package retain] autorelease];
6058 } }
6059
6060 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6061 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6062 if (cell == nil)
6063 cell = [[[PackageCell alloc] init] autorelease];
6064 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
6065 return cell;
6066 }
6067
6068 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6069 Package *package([self packageAtIndexPath:path]);
6070 package = [database_ packageWithName:[package id]];
6071 [self didSelectPackage:package];
6072 }
6073
6074 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6075 if (![self showsSections])
6076 return nil;
6077
6078 return index_;
6079 }
6080
6081 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6082 #if TryIndexedCollation
6083 if ([[self class] hasIndexedCollation]) {
6084 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6085 }
6086 #endif
6087
6088 return index;
6089 }
6090
6091 - (void) updateHeight {
6092 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6093 }
6094
6095 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6096 if ((self = [super init]) != nil) {
6097 database_ = database;
6098 title_ = [title copy];
6099 [[self navigationItem] setTitle:title_];
6100
6101 #if TryIndexedCollation
6102 if ([[self class] hasIndexedCollation])
6103 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6104 else
6105 #endif
6106 index_ = [NSMutableArray arrayWithCapacity:32];
6107
6108 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6109
6110 packages_ = [NSArray array];
6111 sections_ = [NSMutableArray arrayWithCapacity:16];
6112 } return self;
6113 }
6114
6115 - (void) loadView {
6116 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6117
6118 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6119 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6120 [[self view] addSubview:list_];
6121
6122 // XXX: is 20 the most optimal number here?
6123 [list_ setSectionIndexMinimumDisplayRowCount:20];
6124
6125 [(UITableView *) list_ setDataSource:self];
6126 [list_ setDelegate:self];
6127
6128 [self updateHeight];
6129 }
6130
6131 - (void) releaseSubviews {
6132 list_ = nil;
6133
6134 [super releaseSubviews];
6135 }
6136
6137 - (void) setDelegate:(id)delegate {
6138 delegate_ = delegate;
6139 }
6140
6141 - (bool) shouldYield {
6142 return false;
6143 }
6144
6145 - (bool) shouldBlock {
6146 return false;
6147 }
6148
6149 - (NSMutableArray *) _reloadPackages {
6150 @synchronized (database_) {
6151 era_ = [database_ era];
6152 NSArray *packages([database_ packages]);
6153
6154 return [NSMutableArray arrayWithArray:packages];
6155 } }
6156
6157 - (void) _reloadData {
6158 if (reloading_ != 0) {
6159 reloading_ = 2;
6160 return;
6161 }
6162
6163 NSArray *packages;
6164
6165 if ([self shouldYield]) {
6166 do {
6167 UIProgressHUD *hud;
6168
6169 if (![self shouldBlock])
6170 hud = nil;
6171 else {
6172 hud = [delegate_ addProgressHUD];
6173 [hud setText:UCLocalize("LOADING")];
6174 }
6175
6176 reloading_ = 1;
6177 packages = [self yieldToSelector:@selector(_reloadPackages)];
6178
6179 if (hud != nil)
6180 [delegate_ removeProgressHUD:hud];
6181 } while (reloading_ == 2);
6182
6183 reloading_ = 0;
6184 } else {
6185 packages = [self _reloadPackages];
6186 }
6187
6188 packages_ = packages;
6189
6190 [indices_ removeAllObjects];
6191 [sections_ removeAllObjects];
6192
6193 Section *section = nil;
6194
6195 #if TryIndexedCollation
6196 if ([[self class] hasIndexedCollation]) {
6197 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6198 NSArray *titles = [collation sectionIndexTitles];
6199 int secidx = -1;
6200
6201 _profile(PackageTable$reloadData$Section)
6202 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6203 Package *package;
6204 int index;
6205
6206 _profile(PackageTable$reloadData$Section$Package)
6207 package = [packages_ objectAtIndex:offset];
6208 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6209 _end
6210
6211 while (secidx < index) {
6212 secidx += 1;
6213
6214 _profile(PackageTable$reloadData$Section$Allocate)
6215 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6216 _end
6217
6218 _profile(PackageTable$reloadData$Section$Add)
6219 [sections_ addObject:section];
6220 _end
6221 }
6222
6223 [section addToCount];
6224 }
6225 _end
6226 } else
6227 #endif
6228 {
6229 [index_ removeAllObjects];
6230
6231 bool sectioned([self showsSections]);
6232 if (!sectioned) {
6233 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6234 [sections_ addObject:section];
6235 }
6236
6237 _profile(PackageTable$reloadData$Section)
6238 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6239 Package *package;
6240 unichar index;
6241
6242 _profile(PackageTable$reloadData$Section$Package)
6243 package = [packages_ objectAtIndex:offset];
6244 index = [package index];
6245 _end
6246
6247 if (sectioned && (section == nil || [section index] != index)) {
6248 _profile(PackageTable$reloadData$Section$Allocate)
6249 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6250 _end
6251
6252 [index_ addObject:[section name]];
6253 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6254
6255 _profile(PackageTable$reloadData$Section$Add)
6256 [sections_ addObject:section];
6257 _end
6258 }
6259
6260 [section addToCount];
6261 }
6262 _end
6263 }
6264
6265 [self updateHeight];
6266
6267 _profile(PackageTable$reloadData$List)
6268 [(UITableView *) list_ setDataSource:self];
6269 [list_ reloadData];
6270 _end
6271 }
6272
6273 - (void) reloadData {
6274 [super reloadData];
6275 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6276 }
6277
6278 - (void) resetCursor {
6279 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6280 }
6281
6282 - (void) clearData {
6283 [self updateHeight];
6284
6285 [list_ setDataSource:nil];
6286 [list_ reloadData];
6287
6288 [self resetCursor];
6289 }
6290
6291 @end
6292 /* }}} */
6293 /* Filtered Package List Controller {{{ */
6294 @interface FilteredPackageListController : PackageListController {
6295 SEL filter_;
6296 IMP imp_;
6297 _H<NSObject> object_;
6298 }
6299
6300 - (void) setObject:(id)object;
6301 - (void) setObject:(id)object forFilter:(SEL)filter;
6302
6303 - (SEL) filter;
6304 - (void) setFilter:(SEL)filter;
6305
6306 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6307
6308 @end
6309
6310 @implementation FilteredPackageListController
6311
6312 - (SEL) filter {
6313 return filter_;
6314 }
6315
6316 - (void) setFilter:(SEL)filter {
6317 @synchronized (self) {
6318 filter_ = filter;
6319
6320 /* XXX: this is an unsafe optimization of doomy hell */
6321 Method method(class_getInstanceMethod([Package class], filter));
6322 _assert(method != NULL);
6323 imp_ = method_getImplementation(method);
6324 _assert(imp_ != NULL);
6325 } }
6326
6327 - (void) setObject:(id)object {
6328 @synchronized (self) {
6329 object_ = object;
6330 } }
6331
6332 - (void) setObject:(id)object forFilter:(SEL)filter {
6333 @synchronized (self) {
6334 [self setFilter:filter];
6335 [self setObject:object];
6336 } }
6337
6338 - (NSMutableArray *) _reloadPackages {
6339 @synchronized (database_) {
6340 era_ = [database_ era];
6341 NSArray *packages([database_ packages]);
6342
6343 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6344
6345 IMP imp;
6346 SEL filter;
6347 _H<NSObject> object;
6348
6349 @synchronized (self) {
6350 imp = imp_;
6351 filter = filter_;
6352 object = object_;
6353 }
6354
6355 _profile(PackageTable$reloadData$Filter)
6356 for (Package *package in packages)
6357 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6358 [filtered addObject:package];
6359 _end
6360
6361 return filtered;
6362 } }
6363
6364 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6365 if ((self = [super initWithDatabase:database title:title]) != nil) {
6366 [self setFilter:filter];
6367 [self setObject:object];
6368 } return self;
6369 }
6370
6371 @end
6372 /* }}} */
6373
6374 /* Home Controller {{{ */
6375 @interface HomeController : CydiaWebViewController {
6376 }
6377
6378 @end
6379
6380 @implementation HomeController
6381
6382 - (id) init {
6383 if ((self = [super init]) != nil) {
6384 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6385 [self reloadData];
6386 } return self;
6387 }
6388
6389 - (NSURL *) navigationURL {
6390 return [NSURL URLWithString:@"cydia://home"];
6391 }
6392
6393 - (void) aboutButtonClicked {
6394 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6395
6396 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6397 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6398 [alert setCancelButtonIndex:0];
6399
6400 [alert setMessage:
6401 @"Copyright \u00a9 2008-2011\n"
6402 "SaurikIT, LLC\n"
6403 "\n"
6404 "Jay Freeman (saurik)\n"
6405 "saurik@saurik.com\n"
6406 "http://www.saurik.com/"
6407 ];
6408
6409 [alert show];
6410 }
6411
6412 - (UIBarButtonItem *) leftButton {
6413 return [[[UIBarButtonItem alloc]
6414 initWithTitle:UCLocalize("ABOUT")
6415 style:UIBarButtonItemStylePlain
6416 target:self
6417 action:@selector(aboutButtonClicked)
6418 ] autorelease];
6419 }
6420
6421 @end
6422 /* }}} */
6423 /* Manage Controller {{{ */
6424 @interface ManageController : CydiaWebViewController {
6425 }
6426
6427 - (void) queueStatusDidChange;
6428
6429 @end
6430
6431 @implementation ManageController
6432
6433 - (id) init {
6434 if ((self = [super init]) != nil) {
6435 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6436 } return self;
6437 }
6438
6439 - (NSURL *) navigationURL {
6440 return [NSURL URLWithString:@"cydia://manage"];
6441 }
6442
6443 - (UIBarButtonItem *) leftButton {
6444 return [[[UIBarButtonItem alloc]
6445 initWithTitle:UCLocalize("SETTINGS")
6446 style:UIBarButtonItemStylePlain
6447 target:self
6448 action:@selector(settingsButtonClicked)
6449 ] autorelease];
6450 }
6451
6452 - (void) settingsButtonClicked {
6453 [delegate_ showSettings];
6454 }
6455
6456 - (void) queueButtonClicked {
6457 [delegate_ queue];
6458 }
6459
6460 - (UIBarButtonItem *) customButton {
6461 return Queuing_ ? [[[UIBarButtonItem alloc]
6462 initWithTitle:UCLocalize("QUEUE")
6463 style:UIBarButtonItemStyleDone
6464 target:self
6465 action:@selector(queueButtonClicked)
6466 ] autorelease] : [super customButton];
6467 }
6468
6469 - (void) queueStatusDidChange {
6470 [self applyRightButton];
6471 }
6472
6473 - (bool) isLoading {
6474 return !Queuing_ && [super isLoading];
6475 }
6476
6477 @end
6478 /* }}} */
6479
6480 /* Refresh Bar {{{ */
6481 @interface RefreshBar : UINavigationBar {
6482 _H<UIProgressIndicator> indicator_;
6483 _H<UITextLabel> prompt_;
6484 _H<UIProgressBar> progress_;
6485 _H<UINavigationButton> cancel_;
6486 }
6487
6488 @end
6489
6490 @implementation RefreshBar
6491
6492 - (void) positionViews {
6493 CGRect frame = [cancel_ frame];
6494 frame.size = [cancel_ sizeThatFits:frame.size];
6495 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6496 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6497 [cancel_ setFrame:frame];
6498
6499 CGSize prgsize = {75, 100};
6500 CGRect prgrect = {{
6501 [self frame].size.width - prgsize.width - 10,
6502 ([self frame].size.height - prgsize.height) / 2
6503 } , prgsize};
6504 [progress_ setFrame:prgrect];
6505
6506 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6507 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6508 CGRect indrect = {{indoffset, indoffset}, indsize};
6509 [indicator_ setFrame:indrect];
6510
6511 CGSize prmsize = {215, indsize.height + 4};
6512 CGRect prmrect = {{
6513 indoffset * 2 + indsize.width,
6514 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6515 }, prmsize};
6516 [prompt_ setFrame:prmrect];
6517 }
6518
6519 - (void) setFrame:(CGRect)frame {
6520 [super setFrame:frame];
6521 [self positionViews];
6522 }
6523
6524 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6525 if ((self = [super initWithFrame:frame]) != nil) {
6526 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6527
6528 [self setBarStyle:UIBarStyleBlack];
6529
6530 UIBarStyle barstyle([self _barStyle:NO]);
6531 bool ugly(barstyle == UIBarStyleDefault);
6532
6533 UIProgressIndicatorStyle style = ugly ?
6534 UIProgressIndicatorStyleMediumBrown :
6535 UIProgressIndicatorStyleMediumWhite;
6536
6537 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6538 [(UIProgressIndicator *) indicator_ setStyle:style];
6539 [indicator_ startAnimation];
6540 [self addSubview:indicator_];
6541
6542 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6543 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6544 [prompt_ setBackgroundColor:[UIColor clearColor]];
6545 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6546 [self addSubview:prompt_];
6547
6548 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6549 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6550 [(UIProgressBar *) progress_ setStyle:0];
6551 [self addSubview:progress_];
6552
6553 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6554 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6555 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6556 [cancel_ setBarStyle:barstyle];
6557
6558 [self positionViews];
6559 } return self;
6560 }
6561
6562 - (void) setCancellable:(bool)cancellable {
6563 if (cancellable)
6564 [self addSubview:cancel_];
6565 else
6566 [cancel_ removeFromSuperview];
6567 }
6568
6569 - (void) start {
6570 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6571 [progress_ setProgress:0];
6572 }
6573
6574 - (void) stop {
6575 [self setCancellable:NO];
6576 }
6577
6578 - (void) setPrompt:(NSString *)prompt {
6579 [prompt_ setText:prompt];
6580 }
6581
6582 - (void) setProgress:(float)progress {
6583 [progress_ setProgress:progress];
6584 }
6585
6586 @end
6587 /* }}} */
6588
6589 /* Cydia Navigation Controller Interface {{{ */
6590 @interface UINavigationController (Cydia)
6591
6592 - (NSArray *) navigationURLCollection;
6593 - (void) unloadData;
6594
6595 @end
6596 /* }}} */
6597
6598 /* Cydia Tab Bar Controller {{{ */
6599 @interface CYTabBarController : UITabBarController <
6600 UITabBarControllerDelegate,
6601 ProgressDelegate
6602 > {
6603 _transient Database *database_;
6604 _H<RefreshBar, 1> refreshbar_;
6605
6606 bool dropped_;
6607 bool updating_;
6608 // XXX: ok, "updatedelegate_"?...
6609 _transient NSObject<CydiaDelegate> *updatedelegate_;
6610
6611 _H<UIViewController> remembered_;
6612 _transient UIViewController *transient_;
6613 }
6614
6615 - (NSArray *) navigationURLCollection;
6616 - (void) dropBar:(BOOL)animated;
6617 - (void) beginUpdate;
6618 - (void) raiseBar:(BOOL)animated;
6619 - (BOOL) updating;
6620 - (void) unloadData;
6621
6622 @end
6623
6624 @implementation CYTabBarController
6625
6626 - (void) setUnselectedViewController:(UIViewController *)transient {
6627 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6628 if (transient != nil) {
6629 if (transient_ == nil)
6630 remembered_ = [controllers objectAtIndex:0];
6631 transient_ = transient;
6632 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6633 [controllers replaceObjectAtIndex:0 withObject:transient_];
6634 [self setSelectedIndex:0];
6635 [self setViewControllers:controllers];
6636 [self concealTabBarSelection];
6637 } else if (remembered_ != nil) {
6638 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6639 transient_ = transient;
6640 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6641 remembered_ = nil;
6642 [self setViewControllers:controllers];
6643 [self revealTabBarSelection];
6644 }
6645 }
6646
6647 - (UIViewController *) unselectedViewController {
6648 return transient_;
6649 }
6650
6651 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6652 if ([self unselectedViewController])
6653 [self setUnselectedViewController:nil];
6654 }
6655
6656 - (NSArray *) navigationURLCollection {
6657 NSMutableArray *items([NSMutableArray array]);
6658
6659 // XXX: Should this deal with transient view controllers?
6660 for (id navigation in [self viewControllers]) {
6661 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6662 if (stack != nil)
6663 [items addObject:stack];
6664 }
6665
6666 return items;
6667 }
6668
6669 - (void) unloadData {
6670 [super unloadData];
6671
6672 for (UINavigationController *controller in [self viewControllers])
6673 [controller unloadData];
6674
6675 if (UIViewController *selected = [self selectedViewController])
6676 [selected reloadData];
6677
6678 if (UIViewController *unselected = [self unselectedViewController]) {
6679 [unselected unloadData];
6680 [unselected reloadData];
6681 }
6682 }
6683
6684 - (void) dealloc {
6685 [[NSNotificationCenter defaultCenter] removeObserver:self];
6686
6687 [super dealloc];
6688 }
6689
6690 - (id) initWithDatabase:(Database *)database {
6691 if ((self = [super init]) != nil) {
6692 database_ = database;
6693 [self setDelegate:self];
6694
6695 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6696 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6697
6698 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6699 } return self;
6700 }
6701
6702 - (void) setUpdate:(NSDate *)date {
6703 [self beginUpdate];
6704 }
6705
6706 - (void) beginUpdate {
6707 [(RefreshBar *) refreshbar_ start];
6708 [self dropBar:YES];
6709
6710 [updatedelegate_ retainNetworkActivityIndicator];
6711 updating_ = true;
6712
6713 [NSThread
6714 detachNewThreadSelector:@selector(performUpdate)
6715 toTarget:self
6716 withObject:nil
6717 ];
6718 }
6719
6720 - (void) performUpdate {
6721 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6722
6723 Status status;
6724 status.setDelegate(self);
6725 [database_ updateWithStatus:status];
6726
6727 [self
6728 performSelectorOnMainThread:@selector(completeUpdate)
6729 withObject:nil
6730 waitUntilDone:NO
6731 ];
6732
6733 [pool release];
6734 }
6735
6736 - (void) stopUpdateWithSelector:(SEL)selector {
6737 updating_ = false;
6738 [updatedelegate_ releaseNetworkActivityIndicator];
6739
6740 [self raiseBar:YES];
6741 [refreshbar_ stop];
6742
6743 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6744 }
6745
6746 - (void) completeUpdate {
6747 if (!updating_)
6748 return;
6749 [self stopUpdateWithSelector:@selector(reloadData)];
6750 }
6751
6752 - (void) cancelUpdate {
6753 [self stopUpdateWithSelector:@selector(updateData)];
6754 }
6755
6756 - (void) cancelPressed {
6757 [self cancelUpdate];
6758 }
6759
6760 - (BOOL) updating {
6761 return updating_;
6762 }
6763
6764 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6765 [refreshbar_ setPrompt:[event compoundMessage]];
6766 }
6767
6768 - (bool) isProgressCancelled {
6769 return !updating_;
6770 }
6771
6772 - (void) setProgressCancellable:(NSNumber *)cancellable {
6773 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6774 }
6775
6776 - (void) setProgressPercent:(NSNumber *)percent {
6777 [refreshbar_ setProgress:[percent floatValue]];
6778 }
6779
6780 - (void) setProgressStatus:(NSDictionary *)status {
6781 if (status != nil)
6782 [self setProgressPercent:[status objectForKey:@"Percent"]];
6783 }
6784
6785 - (void) setUpdateDelegate:(id)delegate {
6786 updatedelegate_ = delegate;
6787 }
6788
6789 - (UIView *) transitionView {
6790 if ([self respondsToSelector:@selector(_transitionView)])
6791 return [self _transitionView];
6792 else
6793 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6794 }
6795
6796 - (void) dropBar:(BOOL)animated {
6797 if (dropped_)
6798 return;
6799 dropped_ = true;
6800
6801 UIView *transition([self transitionView]);
6802 [[self view] addSubview:refreshbar_];
6803
6804 CGRect barframe([refreshbar_ frame]);
6805
6806 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6807 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6808 else
6809 barframe.origin.y = 0;
6810
6811 [refreshbar_ setFrame:barframe];
6812
6813 if (animated)
6814 [UIView beginAnimations:nil context:NULL];
6815
6816 CGRect viewframe = [transition frame];
6817 viewframe.origin.y += barframe.size.height;
6818 viewframe.size.height -= barframe.size.height;
6819 [transition setFrame:viewframe];
6820
6821 if (animated)
6822 [UIView commitAnimations];
6823
6824 // Ensure bar has the proper width for our view, it might have changed
6825 barframe.size.width = viewframe.size.width;
6826 [refreshbar_ setFrame:barframe];
6827 }
6828
6829 - (void) raiseBar:(BOOL)animated {
6830 if (!dropped_)
6831 return;
6832 dropped_ = false;
6833
6834 UIView *transition([self transitionView]);
6835 [refreshbar_ removeFromSuperview];
6836
6837 CGRect barframe([refreshbar_ frame]);
6838
6839 if (animated)
6840 [UIView beginAnimations:nil context:NULL];
6841
6842 CGRect viewframe = [transition frame];
6843 viewframe.origin.y -= barframe.size.height;
6844 viewframe.size.height += barframe.size.height;
6845 [transition setFrame:viewframe];
6846
6847 if (animated)
6848 [UIView commitAnimations];
6849 }
6850
6851 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6852 bool dropped(dropped_);
6853
6854 if (dropped)
6855 [self raiseBar:NO];
6856
6857 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6858
6859 if (dropped)
6860 [self dropBar:NO];
6861 }
6862
6863 - (void) statusBarFrameChanged:(NSNotification *)notification {
6864 if (dropped_) {
6865 [self raiseBar:NO];
6866 [self dropBar:NO];
6867 }
6868 }
6869
6870 @end
6871 /* }}} */
6872
6873 /* Cydia Navigation Controller Implementation {{{ */
6874 @implementation UINavigationController (Cydia)
6875
6876 - (NSArray *) navigationURLCollection {
6877 NSMutableArray *stack([NSMutableArray array]);
6878
6879 for (CyteViewController *controller in [self viewControllers]) {
6880 NSString *url = [[controller navigationURL] absoluteString];
6881 if (url != nil)
6882 [stack addObject:url];
6883 }
6884
6885 return stack;
6886 }
6887
6888 - (void) reloadData {
6889 [super reloadData];
6890
6891 if (UIViewController *visible = [self visibleViewController])
6892 [visible reloadData];
6893 }
6894
6895 - (void) unloadData {
6896 for (CyteViewController *page in [self viewControllers])
6897 [page unloadData];
6898
6899 [super unloadData];
6900 }
6901
6902 @end
6903 /* }}} */
6904
6905 /* Cydia:// Protocol {{{ */
6906 @interface CydiaURLProtocol : NSURLProtocol {
6907 }
6908
6909 @end
6910
6911 @implementation CydiaURLProtocol
6912
6913 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6914 NSURL *url([request URL]);
6915 if (url == nil)
6916 return NO;
6917
6918 NSString *scheme([[url scheme] lowercaseString]);
6919 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6920 return YES;
6921 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6922 return YES;
6923
6924 return NO;
6925 }
6926
6927 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6928 return request;
6929 }
6930
6931 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6932 id<NSURLProtocolClient> client([self client]);
6933 if (icon == nil)
6934 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6935 else {
6936 NSData *data(UIImagePNGRepresentation(icon));
6937
6938 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6939 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6940 [client URLProtocol:self didLoadData:data];
6941 [client URLProtocolDidFinishLoading:self];
6942 }
6943 }
6944
6945 - (void) startLoading {
6946 id<NSURLProtocolClient> client([self client]);
6947 NSURLRequest *request([self request]);
6948
6949 NSURL *url([request URL]);
6950 NSString *href([url absoluteString]);
6951 NSString *scheme([[url scheme] lowercaseString]);
6952
6953 NSString *path;
6954
6955 if ([scheme isEqualToString:@"cydia"])
6956 path = [href substringFromIndex:8];
6957 else if ([scheme isEqualToString:@"about"])
6958 path = [href substringFromIndex:12];
6959 else _assert(false);
6960
6961 NSRange slash([path rangeOfString:@"/"]);
6962
6963 NSString *command;
6964 if (slash.location == NSNotFound) {
6965 command = path;
6966 path = nil;
6967 } else {
6968 command = [path substringToIndex:slash.location];
6969 path = [path substringFromIndex:(slash.location + 1)];
6970 }
6971
6972 Database *database([Database sharedInstance]);
6973
6974 if ([command isEqualToString:@"package-icon"]) {
6975 if (path == nil)
6976 goto fail;
6977 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6978 Package *package([database packageWithName:path]);
6979 if (package == nil)
6980 goto fail;
6981 [package parse];
6982 UIImage *icon([package icon]);
6983 [self _returnPNGWithImage:icon forRequest:request];
6984 } else if ([command isEqualToString:@"source-icon"]) {
6985 if (path == nil)
6986 goto fail;
6987 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6988 NSString *source(Simplify(path));
6989 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6990 if (icon == nil)
6991 icon = [UIImage applicationImageNamed:@"unknown.png"];
6992 [self _returnPNGWithImage:icon forRequest:request];
6993 } else if ([command isEqualToString:@"uikit-image"]) {
6994 if (path == nil)
6995 goto fail;
6996 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6997 UIImage *icon(_UIImageWithName(path));
6998 [self _returnPNGWithImage:icon forRequest:request];
6999 } else if ([command isEqualToString:@"section-icon"]) {
7000 if (path == nil)
7001 goto fail;
7002 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7003 NSString *section(Simplify(path));
7004 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7005 if (icon == nil)
7006 icon = [UIImage applicationImageNamed:@"unknown.png"];
7007 [self _returnPNGWithImage:icon forRequest:request];
7008 } else fail: {
7009 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7010 }
7011 }
7012
7013 - (void) stopLoading {
7014 }
7015
7016 @end
7017 /* }}} */
7018
7019 /* Section Controller {{{ */
7020 @interface SectionController : FilteredPackageListController {
7021 _H<NSString> section_;
7022 }
7023
7024 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7025
7026 @end
7027
7028 @implementation SectionController
7029
7030 - (NSURL *) navigationURL {
7031 NSString *name = section_;
7032 if (name == nil)
7033 name = @"all";
7034
7035 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7036 }
7037
7038 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7039 NSString *title;
7040 if (name == nil)
7041 title = UCLocalize("ALL_PACKAGES");
7042 else if (![name isEqual:@""])
7043 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7044 else
7045 title = UCLocalize("NO_SECTION");
7046
7047 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7048 section_ = name;
7049 } return self;
7050 }
7051
7052 @end
7053 /* }}} */
7054 /* Sections Controller {{{ */
7055 @interface SectionsController : CyteViewController <
7056 UITableViewDataSource,
7057 UITableViewDelegate
7058 > {
7059 _transient Database *database_;
7060 _H<NSMutableArray> sections_;
7061 _H<NSMutableArray> filtered_;
7062 _H<UITableView, 2> list_;
7063 }
7064
7065 - (id) initWithDatabase:(Database *)database;
7066 - (void) editButtonClicked;
7067
7068 @end
7069
7070 @implementation SectionsController
7071
7072 - (NSURL *) navigationURL {
7073 return [NSURL URLWithString:@"cydia://sections"];
7074 }
7075
7076 - (void) updateNavigationItem {
7077 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7078 if ([sections_ count] == 0) {
7079 [[self navigationItem] setRightBarButtonItem:nil];
7080 } else {
7081 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7082 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7083 target:self
7084 action:@selector(editButtonClicked)
7085 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7086 }
7087 }
7088
7089 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7090 [super setEditing:editing animated:animated];
7091
7092 if (editing)
7093 [list_ reloadData];
7094 else
7095 [delegate_ updateData];
7096
7097 [self updateNavigationItem];
7098 }
7099
7100 - (void) viewDidAppear:(BOOL)animated {
7101 [super viewDidAppear:animated];
7102 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7103 }
7104
7105 - (void) viewWillDisappear:(BOOL)animated {
7106 [super viewWillDisappear:animated];
7107 if ([self isEditing]) [self setEditing:NO];
7108 }
7109
7110 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7111 Section *section = nil;
7112 int index = [indexPath row];
7113 if (![self isEditing]) {
7114 index -= 1;
7115 if (index >= 0)
7116 section = [filtered_ objectAtIndex:index];
7117 } else {
7118 section = [sections_ objectAtIndex:index];
7119 }
7120 return section;
7121 }
7122
7123 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7124 if ([self isEditing])
7125 return [sections_ count];
7126 else
7127 return [filtered_ count] + 1;
7128 }
7129
7130 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7131 return 45.0f;
7132 }*/
7133
7134 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7135 static NSString *reuseIdentifier = @"SectionCell";
7136
7137 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7138 if (cell == nil)
7139 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7140
7141 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7142
7143 return cell;
7144 }
7145
7146 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7147 if ([self isEditing])
7148 return;
7149
7150 Section *section = [self sectionAtIndexPath:indexPath];
7151
7152 SectionController *controller = [[[SectionController alloc]
7153 initWithDatabase:database_
7154 section:[section name]
7155 ] autorelease];
7156 [controller setDelegate:delegate_];
7157
7158 [[self navigationController] pushViewController:controller animated:YES];
7159 }
7160
7161 - (void) loadView {
7162 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7163
7164 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7165 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7166 [list_ setRowHeight:45.0f];
7167 [(UITableView *) list_ setDataSource:self];
7168 [list_ setDelegate:self];
7169 [[self view] addSubview:list_];
7170 }
7171
7172 - (void) viewDidLoad {
7173 [super viewDidLoad];
7174
7175 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7176 }
7177
7178 - (void) releaseSubviews {
7179 list_ = nil;
7180
7181 [super releaseSubviews];
7182 }
7183
7184 - (id) initWithDatabase:(Database *)database {
7185 if ((self = [super init]) != nil) {
7186 database_ = database;
7187
7188 sections_ = [NSMutableArray arrayWithCapacity:16];
7189 filtered_ = [NSMutableArray arrayWithCapacity:16];
7190 } return self;
7191 }
7192
7193 - (void) reloadData {
7194 [super reloadData];
7195
7196 NSArray *packages = [database_ packages];
7197
7198 [sections_ removeAllObjects];
7199 [filtered_ removeAllObjects];
7200
7201 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7202
7203 _trace();
7204 for (Package *package in packages) {
7205 NSString *name([package section]);
7206 NSString *key(name == nil ? @"" : name);
7207
7208 Section *section;
7209
7210 _profile(SectionsView$reloadData$Section)
7211 section = [sections objectForKey:key];
7212 if (section == nil) {
7213 _profile(SectionsView$reloadData$Section$Allocate)
7214 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7215 [sections setObject:section forKey:key];
7216 _end
7217 }
7218 _end
7219
7220 [section addToCount];
7221
7222 _profile(SectionsView$reloadData$Filter)
7223 if (![package valid] || ![package visible])
7224 continue;
7225 _end
7226
7227 [section addToRow];
7228 }
7229 _trace();
7230
7231 [sections_ addObjectsFromArray:[sections allValues]];
7232
7233 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7234
7235 for (Section *section in (id) sections_) {
7236 size_t count([section row]);
7237 if (count == 0)
7238 continue;
7239
7240 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7241 [section setCount:count];
7242 [filtered_ addObject:section];
7243 }
7244
7245 [self updateNavigationItem];
7246 [list_ reloadData];
7247 _trace();
7248 }
7249
7250 - (void) editButtonClicked {
7251 [self setEditing:![self isEditing] animated:YES];
7252 }
7253
7254 @end
7255 /* }}} */
7256
7257 /* Changes Controller {{{ */
7258 @interface ChangesController : CyteViewController <
7259 UITableViewDataSource,
7260 UITableViewDelegate
7261 > {
7262 _transient Database *database_;
7263 unsigned era_;
7264 _H<NSArray> packages_;
7265 _H<NSMutableArray> sections_;
7266 _H<UITableView, 2> list_;
7267 unsigned upgrades_;
7268 }
7269
7270 - (id) initWithDatabase:(Database *)database;
7271
7272 @end
7273
7274 @implementation ChangesController
7275
7276 - (NSURL *) navigationURL {
7277 return [NSURL URLWithString:@"cydia://changes"];
7278 }
7279
7280 - (void) viewDidAppear:(BOOL)animated {
7281 [super viewDidAppear:animated];
7282 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7283 }
7284
7285 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7286 NSInteger count([sections_ count]);
7287 return count == 0 ? 1 : count;
7288 }
7289
7290 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7291 if ([sections_ count] == 0)
7292 return nil;
7293 return [[sections_ objectAtIndex:section] name];
7294 }
7295
7296 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7297 if ([sections_ count] == 0)
7298 return 0;
7299 return [[sections_ objectAtIndex:section] count];
7300 }
7301
7302 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7303 @synchronized (database_) {
7304 if ([database_ era] != era_)
7305 return nil;
7306
7307 NSUInteger sectionIndex([path section]);
7308 if (sectionIndex >= [sections_ count])
7309 return nil;
7310 Section *section([sections_ objectAtIndex:sectionIndex]);
7311 NSInteger row([path row]);
7312 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7313 } }
7314
7315 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7316 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7317 if (cell == nil)
7318 cell = [[[PackageCell alloc] init] autorelease];
7319 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7320 return cell;
7321 }
7322
7323 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7324 Package *package([self packageAtIndexPath:path]);
7325 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7326 [view setDelegate:delegate_];
7327 [[self navigationController] pushViewController:view animated:YES];
7328 return path;
7329 }
7330
7331 - (void) refreshButtonClicked {
7332 [delegate_ beginUpdate];
7333 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7334 }
7335
7336 - (void) upgradeButtonClicked {
7337 [delegate_ distUpgrade];
7338 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7339 }
7340
7341 - (void) loadView {
7342 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7343
7344 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7345 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7346 [list_ setRowHeight:73];
7347 [(UITableView *) list_ setDataSource:self];
7348 [list_ setDelegate:self];
7349 [[self view] addSubview:list_];
7350 }
7351
7352 - (void) viewDidLoad {
7353 [super viewDidLoad];
7354
7355 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7356 }
7357
7358 - (void) releaseSubviews {
7359 list_ = nil;
7360
7361 [super releaseSubviews];
7362 }
7363
7364 - (id) initWithDatabase:(Database *)database {
7365 if ((self = [super init]) != nil) {
7366 database_ = database;
7367
7368 packages_ = [NSArray array];
7369 sections_ = [NSMutableArray arrayWithCapacity:16];
7370 } return self;
7371 }
7372
7373 - (NSMutableArray *) _reloadPackages {
7374 @synchronized (database_) {
7375 era_ = [database_ era];
7376 NSArray *packages([database_ packages]);
7377
7378 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7379
7380 _trace();
7381 _profile(ChangesController$_reloadPackages$Filter)
7382 for (Package *package in packages)
7383 if ([package upgradableAndEssential:YES] || [package visible])
7384 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7385 _end
7386 _trace();
7387 _profile(ChangesController$_reloadPackages$radixSort)
7388 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7389 _end
7390 _trace();
7391
7392 return filtered;
7393 } }
7394
7395 - (void) _reloadData {
7396 NSArray *packages;
7397
7398 reload:
7399 if (true) {
7400 UIProgressHUD *hud([delegate_ addProgressHUD]);
7401 [hud setText:UCLocalize("LOADING")];
7402 //NSLog(@"HUD:%@::%@", delegate_, hud);
7403 packages = [self yieldToSelector:@selector(_reloadPackages)];
7404 [delegate_ removeProgressHUD:hud];
7405 } else {
7406 packages = [self _reloadPackages];
7407 }
7408
7409 @synchronized (database_) {
7410 if (era_ != [database_ era])
7411 goto reload;
7412
7413 packages_ = packages;
7414 [sections_ removeAllObjects];
7415
7416 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7417 Section *ignored = nil;
7418 Section *section = nil;
7419 time_t last = 0;
7420
7421 upgrades_ = 0;
7422 bool unseens = false;
7423
7424 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7425
7426 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7427 Package *package = [packages_ objectAtIndex:offset];
7428
7429 BOOL uae = [package upgradableAndEssential:YES];
7430
7431 if (!uae) {
7432 unseens = true;
7433 time_t seen([package seen]);
7434
7435 if (section == nil || last != seen) {
7436 last = seen;
7437
7438 NSString *name;
7439 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7440 [name autorelease];
7441
7442 _profile(ChangesController$reloadData$Allocate)
7443 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7444 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7445 [sections_ addObject:section];
7446 _end
7447 }
7448
7449 [section addToCount];
7450 } else if ([package ignored]) {
7451 if (ignored == nil) {
7452 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7453 }
7454 [ignored addToCount];
7455 } else {
7456 ++upgrades_;
7457 [upgradable addToCount];
7458 }
7459 }
7460 _trace();
7461
7462 CFRelease(formatter);
7463
7464 if (unseens) {
7465 Section *last = [sections_ lastObject];
7466 size_t count = [last count];
7467 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7468 [sections_ removeLastObject];
7469 }
7470
7471 if ([ignored count] != 0)
7472 [sections_ insertObject:ignored atIndex:0];
7473 if (upgrades_ != 0)
7474 [sections_ insertObject:upgradable atIndex:0];
7475
7476 [list_ reloadData];
7477
7478 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7479 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7480 style:UIBarButtonItemStylePlain
7481 target:self
7482 action:@selector(upgradeButtonClicked)
7483 ] autorelease]) animated:YES];
7484
7485 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7486 initWithTitle:UCLocalize("REFRESH")
7487 style:UIBarButtonItemStylePlain
7488 target:self
7489 action:@selector(refreshButtonClicked)
7490 ] autorelease]) animated:YES];
7491
7492 PrintTimes();
7493 } }
7494
7495 - (void) reloadData {
7496 [super reloadData];
7497 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7498 }
7499
7500 @end
7501 /* }}} */
7502 /* Search Controller {{{ */
7503 @interface SearchController : FilteredPackageListController <
7504 UISearchBarDelegate
7505 > {
7506 _H<UISearchBar, 1> search_;
7507 BOOL searchloaded_;
7508 }
7509
7510 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7511 - (void) reloadData;
7512
7513 @end
7514
7515 @implementation SearchController
7516
7517 - (NSURL *) navigationURL {
7518 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7519 return [NSURL URLWithString:@"cydia://search"];
7520 else
7521 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7522 }
7523
7524 - (void) useSearch {
7525 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7526 [self clearData];
7527 [self reloadData];
7528 }
7529
7530 - (void) viewWillAppear:(BOOL)animated {
7531 [super viewWillAppear:animated];
7532
7533 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7534 [self useSearch];
7535 }
7536
7537 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7538 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7539 [self clearData];
7540 [self reloadData];
7541 }
7542
7543 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7544 [search_ resignFirstResponder];
7545 [self useSearch];
7546 }
7547
7548 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7549 [search_ setText:@""];
7550 [self searchBarButtonClicked:searchBar];
7551 }
7552
7553 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7554 [self searchBarButtonClicked:searchBar];
7555 }
7556
7557 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7558 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7559 [self reloadData];
7560 }
7561
7562 - (bool) shouldYield {
7563 return YES;
7564 }
7565
7566 - (bool) shouldBlock {
7567 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7568 }
7569
7570 - (bool) isSummarized {
7571 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7572 }
7573
7574 - (bool) showsSections {
7575 return false;
7576 }
7577
7578 - (NSMutableArray *) _reloadPackages {
7579 NSMutableArray *packages([super _reloadPackages]);
7580 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7581 [packages radixSortUsingSelector:@selector(rank)];
7582 return packages;
7583 }
7584
7585 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7586 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7587 search_ = [[[UISearchBar alloc] init] autorelease];
7588 [search_ setDelegate:self];
7589
7590 if (query != nil)
7591 [search_ setText:query];
7592 } return self;
7593 }
7594
7595 - (void) viewDidAppear:(BOOL)animated {
7596 [super viewDidAppear:animated];
7597
7598 if (!searchloaded_) {
7599 searchloaded_ = YES;
7600 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7601 [search_ layoutSubviews];
7602 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7603
7604 UITextField *textField;
7605 if ([search_ respondsToSelector:@selector(searchField)])
7606 textField = [search_ searchField];
7607 else
7608 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7609
7610 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7611 [textField setEnablesReturnKeyAutomatically:NO];
7612 [[self navigationItem] setTitleView:textField];
7613 }
7614 }
7615
7616 - (void) reloadData {
7617 id object([search_ text]);
7618 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7619 object = [object componentsSeparatedByString:@" "];
7620
7621 [self setObject:object];
7622 [self resetCursor];
7623
7624 [super reloadData];
7625 }
7626
7627 - (void) didSelectPackage:(Package *)package {
7628 [search_ resignFirstResponder];
7629 [super didSelectPackage:package];
7630 }
7631
7632 @end
7633 /* }}} */
7634 /* Package Settings Controller {{{ */
7635 @interface PackageSettingsController : CyteViewController <
7636 UITableViewDataSource,
7637 UITableViewDelegate
7638 > {
7639 _transient Database *database_;
7640 _H<NSString> name_;
7641 _H<Package> package_;
7642 _H<UITableView, 2> table_;
7643 _H<UISwitch> subscribedSwitch_;
7644 _H<UISwitch> ignoredSwitch_;
7645 _H<UITableViewCell> subscribedCell_;
7646 _H<UITableViewCell> ignoredCell_;
7647 }
7648
7649 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7650
7651 @end
7652
7653 @implementation PackageSettingsController
7654
7655 - (NSURL *) navigationURL {
7656 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7657 }
7658
7659 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7660 if (package_ == nil)
7661 return 0;
7662
7663 if ([package_ installed] == nil)
7664 return 1;
7665 else
7666 return 2;
7667 }
7668
7669 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7670 if (package_ == nil)
7671 return 0;
7672
7673 // both sections contain just one item right now.
7674 return 1;
7675 }
7676
7677 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7678 return nil;
7679 }
7680
7681 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7682 if (section == 0)
7683 return UCLocalize("SHOW_ALL_CHANGES_EX");
7684 else
7685 return UCLocalize("IGNORE_UPGRADES_EX");
7686 }
7687
7688 - (void) onSubscribed:(id)control {
7689 bool value([control isOn]);
7690 if (package_ == nil)
7691 return;
7692 if ([package_ setSubscribed:value])
7693 [delegate_ updateData];
7694 }
7695
7696 - (void) _updateIgnored {
7697 const char *package([name_ UTF8String]);
7698 bool on([ignoredSwitch_ isOn]);
7699
7700 pid_t pid(ExecFork());
7701 if (pid == 0) {
7702 FILE *dpkg(popen("dpkg --set-selections", "w"));
7703 fwrite(package, strlen(package), 1, dpkg);
7704
7705 if (on)
7706 fwrite(" hold\n", 6, 1, dpkg);
7707 else
7708 fwrite(" install\n", 9, 1, dpkg);
7709
7710 pclose(dpkg);
7711
7712 exit(0);
7713 _assert(false);
7714 }
7715
7716 _forever {
7717 int status;
7718 int result(waitpid(pid, &status, 0));
7719
7720 if (result != -1) {
7721 _assert(result == pid);
7722 break;
7723 }
7724 }
7725 }
7726
7727 - (void) onIgnored:(id)control {
7728 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7729 [invocation setTarget:self];
7730 [invocation setSelector:@selector(_updateIgnored)];
7731
7732 [delegate_ reloadDataWithInvocation:invocation];
7733 }
7734
7735 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7736 if (package_ == nil)
7737 return nil;
7738
7739 switch ([indexPath section]) {
7740 case 0: return subscribedCell_;
7741 case 1: return ignoredCell_;
7742
7743 _nodefault
7744 }
7745
7746 return nil;
7747 }
7748
7749 - (void) loadView {
7750 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7751
7752 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7753 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7754 [(UITableView *) table_ setDataSource:self];
7755 [table_ setDelegate:self];
7756 [[self view] addSubview:table_];
7757
7758 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7759 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7760 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7761
7762 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7763 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7764 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7765
7766 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7767 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7768 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7769 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7770
7771 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7772 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7773 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7774 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7775 }
7776
7777 - (void) viewDidLoad {
7778 [super viewDidLoad];
7779
7780 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7781 }
7782
7783 - (void) releaseSubviews {
7784 ignoredCell_ = nil;
7785 subscribedCell_ = nil;
7786 table_ = nil;
7787 ignoredSwitch_ = nil;
7788 subscribedSwitch_ = nil;
7789
7790 [super releaseSubviews];
7791 }
7792
7793 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7794 if ((self = [super init]) != nil) {
7795 database_ = database;
7796 name_ = package;
7797 } return self;
7798 }
7799
7800 - (void) reloadData {
7801 [super reloadData];
7802
7803 package_ = [database_ packageWithName:name_];
7804
7805 if (package_ != nil) {
7806 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7807 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7808 } // XXX: what now, G?
7809
7810 [table_ reloadData];
7811 }
7812
7813 @end
7814 /* }}} */
7815
7816 /* Installed Controller {{{ */
7817 @interface InstalledController : FilteredPackageListController {
7818 BOOL expert_;
7819 }
7820
7821 - (id) initWithDatabase:(Database *)database;
7822
7823 - (void) updateRoleButton;
7824 - (void) queueStatusDidChange;
7825
7826 @end
7827
7828 @implementation InstalledController
7829
7830 - (NSURL *) navigationURL {
7831 return [NSURL URLWithString:@"cydia://installed"];
7832 }
7833
7834 - (id) initWithDatabase:(Database *)database {
7835 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7836 [self updateRoleButton];
7837 [self queueStatusDidChange];
7838 } return self;
7839 }
7840
7841 #if !AlwaysReload
7842 - (void) queueButtonClicked {
7843 [delegate_ queue];
7844 }
7845 #endif
7846
7847 - (void) queueStatusDidChange {
7848 #if !AlwaysReload
7849 if (IsWildcat_) {
7850 if (Queuing_) {
7851 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7852 initWithTitle:UCLocalize("QUEUE")
7853 style:UIBarButtonItemStyleDone
7854 target:self
7855 action:@selector(queueButtonClicked)
7856 ] autorelease]];
7857 } else {
7858 [[self navigationItem] setLeftBarButtonItem:nil];
7859 }
7860 }
7861 #endif
7862 }
7863
7864 - (void) updateRoleButton {
7865 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7866 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7867 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7868 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7869 target:self
7870 action:@selector(roleButtonClicked)
7871 ] autorelease]];
7872 }
7873
7874 - (void) roleButtonClicked {
7875 [self setObject:[NSNumber numberWithBool:expert_]];
7876 [self reloadData];
7877 expert_ = !expert_;
7878
7879 [self updateRoleButton];
7880 }
7881
7882 @end
7883 /* }}} */
7884
7885 /* Source Cell {{{ */
7886 @interface SourceCell : CyteTableViewCell <
7887 CyteTableViewCellDelegate
7888 > {
7889 _H<UIImage> icon_;
7890 _H<NSString> origin_;
7891 _H<NSString> label_;
7892 }
7893
7894 - (void) setSource:(Source *)source;
7895
7896 @end
7897
7898 @implementation SourceCell
7899
7900 - (void) _setImage:(UIImage *)image {
7901 icon_ = image;
7902 [content_ setNeedsDisplay];
7903 }
7904
7905 - (void) _setSource:(Source *)source {
7906 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7907
7908 if (NSString *base = [source base])
7909 if ([base length] != 0) {
7910 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7911
7912 if (NSData *data = [NSURLConnection
7913 sendSynchronousRequest:[NSURLRequest
7914 requestWithURL:url
7915 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7916 //timeoutInterval:5
7917 ]
7918
7919 returningResponse:NULL
7920 error:NULL
7921 ])
7922 if (UIImage *image = [UIImage imageWithData:data])
7923 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7924 }
7925
7926 [pool release];
7927 }
7928
7929 - (void) setSource:(Source *)source {
7930 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7931
7932 origin_ = [source name];
7933 label_ = [source uri];
7934
7935 [content_ setNeedsDisplay];
7936
7937 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7938 }
7939
7940 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7941 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7942 UIView *content([self contentView]);
7943 CGRect bounds([content bounds]);
7944
7945 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7946 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7947 [content_ setBackgroundColor:[UIColor whiteColor]];
7948 [content addSubview:content_];
7949
7950 [content_ setDelegate:self];
7951 [content_ setOpaque:YES];
7952 } return self;
7953 }
7954
7955 - (NSString *) accessibilityLabel {
7956 return label_;
7957 }
7958
7959 - (void) drawContentRect:(CGRect)rect {
7960 bool highlighted(highlighted_);
7961 float width(rect.size.width);
7962
7963 if (icon_ != nil)
7964 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7965
7966 if (highlighted)
7967 UISetColor(White_);
7968
7969 if (!highlighted)
7970 UISetColor(Black_);
7971 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7972
7973 if (!highlighted)
7974 UISetColor(Blue_);
7975 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7976 }
7977
7978 @end
7979 /* }}} */
7980 /* Source Controller {{{ */
7981 @interface SourceController : FilteredPackageListController {
7982 _transient Source *source_;
7983 _H<NSString> key_;
7984 }
7985
7986 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7987
7988 @end
7989
7990 @implementation SourceController
7991
7992 - (NSURL *) navigationURL {
7993 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7994 }
7995
7996 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7997 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7998 source_ = source;
7999 key_ = [source key];
8000 } return self;
8001 }
8002
8003 - (void) reloadData {
8004 source_ = [database_ sourceWithKey:key_];
8005 key_ = [source_ key];
8006 [self setObject:source_];
8007
8008 [[self navigationItem] setTitle:[source_ label]];
8009
8010 [super reloadData];
8011 }
8012
8013 @end
8014 /* }}} */
8015 /* Sources Controller {{{ */
8016 @interface SourcesController : CyteViewController <
8017 UITableViewDataSource,
8018 UITableViewDelegate
8019 > {
8020 _transient Database *database_;
8021 _H<UITableView, 2> list_;
8022 _H<NSMutableArray> sources_;
8023 int offset_;
8024
8025 _H<NSString> href_;
8026 _H<UIProgressHUD> hud_;
8027 _H<NSError> error_;
8028
8029 //NSURLConnection *installer_;
8030 NSURLConnection *trivial_;
8031 NSURLConnection *trivial_bz2_;
8032 NSURLConnection *trivial_gz_;
8033 //NSURLConnection *automatic_;
8034
8035 BOOL cydia_;
8036 }
8037
8038 - (id) initWithDatabase:(Database *)database;
8039 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8040
8041 @end
8042
8043 @implementation SourcesController
8044
8045 - (void) _releaseConnection:(NSURLConnection *)connection {
8046 if (connection != nil) {
8047 [connection cancel];
8048 //[connection setDelegate:nil];
8049 [connection release];
8050 }
8051 }
8052
8053 - (void) dealloc {
8054 //[self _releaseConnection:installer_];
8055 [self _releaseConnection:trivial_];
8056 [self _releaseConnection:trivial_gz_];
8057 [self _releaseConnection:trivial_bz2_];
8058 //[self _releaseConnection:automatic_];
8059
8060 [super dealloc];
8061 }
8062
8063 - (NSURL *) navigationURL {
8064 return [NSURL URLWithString:@"cydia://sources"];
8065 }
8066
8067 - (void) viewDidAppear:(BOOL)animated {
8068 [super viewDidAppear:animated];
8069 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8070 }
8071
8072 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8073 return offset_ == 0 ? 1 : 2;
8074 }
8075
8076 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8077 switch (section + (offset_ == 0 ? 1 : 0)) {
8078 case 0: return UCLocalize("ENTERED_BY_USER");
8079 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8080
8081 _nodefault
8082 }
8083 }
8084
8085 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8086 int count = [sources_ count];
8087 switch (section) {
8088 case 0: return (offset_ == 0 ? count : offset_);
8089 case 1: return count - offset_;
8090
8091 _nodefault
8092 }
8093 }
8094
8095 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8096 unsigned idx = 0;
8097 switch (indexPath.section) {
8098 case 0: idx = indexPath.row; break;
8099 case 1: idx = indexPath.row + offset_; break;
8100
8101 _nodefault
8102 }
8103 return [sources_ objectAtIndex:idx];
8104 }
8105
8106 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8107 static NSString *cellIdentifier = @"SourceCell";
8108
8109 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8110 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8111 [cell setSource:[self sourceAtIndexPath:indexPath]];
8112 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8113
8114 return cell;
8115 }
8116
8117 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8118 Source *source = [self sourceAtIndexPath:indexPath];
8119
8120 SourceController *controller = [[[SourceController alloc]
8121 initWithDatabase:database_
8122 source:source
8123 ] autorelease];
8124
8125 [controller setDelegate:delegate_];
8126
8127 [[self navigationController] pushViewController:controller animated:YES];
8128 }
8129
8130 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8131 Source *source = [self sourceAtIndexPath:indexPath];
8132 return [source record] != nil;
8133 }
8134
8135 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8136 if (editingStyle == UITableViewCellEditingStyleDelete) {
8137 Source *source = [self sourceAtIndexPath:indexPath];
8138 [Sources_ removeObjectForKey:[source key]];
8139 [delegate_ syncData];
8140 }
8141 }
8142
8143 - (void) complete {
8144 [delegate_ addTrivialSource:href_];
8145 [delegate_ syncData];
8146 }
8147
8148 - (NSString *) getWarning {
8149 NSString *href(href_);
8150 NSRange colon([href rangeOfString:@"://"]);
8151 if (colon.location != NSNotFound)
8152 href = [href substringFromIndex:(colon.location + 3)];
8153 href = [href stringByAddingPercentEscapes];
8154 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8155 href = [href stringByCachingURLWithCurrentCDN];
8156
8157 NSURL *url([NSURL URLWithString:href]);
8158
8159 NSStringEncoding encoding;
8160 NSError *error(nil);
8161
8162 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8163 return [warning length] == 0 ? nil : warning;
8164 return nil;
8165 }
8166
8167 - (void) _endConnection:(NSURLConnection *)connection {
8168 // XXX: the memory management in this method is horribly awkward
8169
8170 NSURLConnection **field = NULL;
8171 if (connection == trivial_)
8172 field = &trivial_;
8173 else if (connection == trivial_bz2_)
8174 field = &trivial_bz2_;
8175 else if (connection == trivial_gz_)
8176 field = &trivial_gz_;
8177 _assert(field != NULL);
8178 [connection release];
8179 *field = nil;
8180
8181 if (
8182 trivial_ == nil &&
8183 trivial_bz2_ == nil &&
8184 trivial_gz_ == nil
8185 ) {
8186 [delegate_ releaseNetworkActivityIndicator];
8187
8188 [delegate_ removeProgressHUD:hud_];
8189 hud_ = nil;
8190
8191 bool defer(false);
8192
8193 if (cydia_) {
8194 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8195 defer = true;
8196
8197 UIAlertView *alert = [[[UIAlertView alloc]
8198 initWithTitle:UCLocalize("SOURCE_WARNING")
8199 message:warning
8200 delegate:self
8201 cancelButtonTitle:UCLocalize("CANCEL")
8202 otherButtonTitles:
8203 UCLocalize("ADD_ANYWAY"),
8204 nil
8205 ] autorelease];
8206
8207 [alert setContext:@"warning"];
8208 [alert setNumberOfRows:1];
8209 [alert show];
8210 } else
8211 [self complete];
8212 } else if (error_ != nil) {
8213 UIAlertView *alert = [[[UIAlertView alloc]
8214 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8215 message:[error_ localizedDescription]
8216 delegate:self
8217 cancelButtonTitle:UCLocalize("OK")
8218 otherButtonTitles:nil
8219 ] autorelease];
8220
8221 [alert setContext:@"urlerror"];
8222 [alert show];
8223 } else {
8224 UIAlertView *alert = [[[UIAlertView alloc]
8225 initWithTitle:UCLocalize("NOT_REPOSITORY")
8226 message:UCLocalize("NOT_REPOSITORY_EX")
8227 delegate:self
8228 cancelButtonTitle:UCLocalize("OK")
8229 otherButtonTitles:nil
8230 ] autorelease];
8231
8232 [alert setContext:@"trivial"];
8233 [alert show];
8234 }
8235
8236 href_ = nil;
8237 error_ = nil;
8238 }
8239 }
8240
8241 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8242 switch ([response statusCode]) {
8243 case 200:
8244 cydia_ = YES;
8245 }
8246 }
8247
8248 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8249 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8250 error_ = error;
8251 [self _endConnection:connection];
8252 }
8253
8254 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8255 [self _endConnection:connection];
8256 }
8257
8258 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8259 NSURL *url([NSURL URLWithString:href]);
8260
8261 NSMutableURLRequest *request = [NSMutableURLRequest
8262 requestWithURL:url
8263 cachePolicy:NSURLRequestUseProtocolCachePolicy
8264 timeoutInterval:120.0
8265 ];
8266
8267 [request setHTTPMethod:method];
8268
8269 if (Machine_ != NULL)
8270 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8271
8272 if ([url isCydiaSecure]) {
8273 if (UniqueID_ != nil)
8274 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8275 }
8276
8277 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8278 }
8279
8280 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8281 NSString *context([alert context]);
8282
8283 if ([context isEqualToString:@"source"]) {
8284 switch (button) {
8285 case 1: {
8286 NSString *href = [[alert textField] text];
8287
8288 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8289
8290 if (![href hasSuffix:@"/"])
8291 href_ = [href stringByAppendingString:@"/"];
8292 else
8293 href_ = href;
8294
8295 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8296 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8297 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8298 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8299
8300 cydia_ = false;
8301
8302 // XXX: this is stupid
8303 hud_ = [delegate_ addProgressHUD];
8304 [hud_ setText:UCLocalize("VERIFYING_URL")];
8305 [delegate_ retainNetworkActivityIndicator];
8306 } break;
8307
8308 case 0:
8309 break;
8310
8311 _nodefault
8312 }
8313
8314 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8315 } else if ([context isEqualToString:@"trivial"])
8316 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8317 else if ([context isEqualToString:@"urlerror"])
8318 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8319 else if ([context isEqualToString:@"warning"]) {
8320 switch (button) {
8321 case 1:
8322 [self complete];
8323 break;
8324
8325 case 0:
8326 break;
8327
8328 _nodefault
8329 }
8330
8331 href_ = nil;
8332
8333 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8334 }
8335 }
8336
8337 - (void) loadView {
8338 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8339
8340 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8341 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8342 [list_ setRowHeight:56];
8343 [(UITableView *) list_ setDataSource:self];
8344 [list_ setDelegate:self];
8345 [[self view] addSubview:list_];
8346 }
8347
8348 - (void) viewDidLoad {
8349 [super viewDidLoad];
8350
8351 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8352 [self updateButtonsForEditingStatus:NO animated:NO];
8353 }
8354
8355 - (void) releaseSubviews {
8356 list_ = nil;
8357
8358 [super releaseSubviews];
8359 }
8360
8361 - (id) initWithDatabase:(Database *)database {
8362 if ((self = [super init]) != nil) {
8363 database_ = database;
8364 sources_ = [NSMutableArray arrayWithCapacity:16];
8365 } return self;
8366 }
8367
8368 - (void) reloadData {
8369 [super reloadData];
8370
8371 pkgSourceList list;
8372 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8373 return;
8374
8375 [sources_ removeAllObjects];
8376 [sources_ addObjectsFromArray:[database_ sources]];
8377 _trace();
8378 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8379 _trace();
8380
8381 int count([sources_ count]);
8382 offset_ = 0;
8383 for (int i = 0; i != count; i++) {
8384 if ([[sources_ objectAtIndex:i] record] == nil)
8385 break;
8386 offset_++;
8387 }
8388
8389 [list_ setEditing:NO];
8390 [self updateButtonsForEditingStatus:NO animated:NO];
8391 [list_ reloadData];
8392 }
8393
8394 - (void) showAddSourcePrompt {
8395 UIAlertView *alert = [[[UIAlertView alloc]
8396 initWithTitle:UCLocalize("ENTER_APT_URL")
8397 message:nil
8398 delegate:self
8399 cancelButtonTitle:UCLocalize("CANCEL")
8400 otherButtonTitles:
8401 UCLocalize("ADD_SOURCE"),
8402 nil
8403 ] autorelease];
8404
8405 [alert setContext:@"source"];
8406
8407 [alert setNumberOfRows:1];
8408 [alert addTextFieldWithValue:@"http://" label:@""];
8409
8410 UITextInputTraits *traits = [[alert textField] textInputTraits];
8411 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8412 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8413 [traits setKeyboardType:UIKeyboardTypeURL];
8414 // XXX: UIReturnKeyDone
8415 [traits setReturnKeyType:UIReturnKeyNext];
8416
8417 [alert show];
8418 }
8419
8420 - (void) addButtonClicked {
8421 [self showAddSourcePrompt];
8422 }
8423
8424 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8425 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8426 initWithTitle:UCLocalize("ADD")
8427 style:UIBarButtonItemStylePlain
8428 target:self
8429 action:@selector(addButtonClicked)
8430 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8431
8432 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8433 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8434 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8435 target:self
8436 action:@selector(editButtonClicked)
8437 ] autorelease] animated:animated];
8438
8439 if (IsWildcat_ && !editing)
8440 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8441 initWithTitle:UCLocalize("SETTINGS")
8442 style:UIBarButtonItemStylePlain
8443 target:self
8444 action:@selector(settingsButtonClicked)
8445 ] autorelease]];
8446 }
8447
8448 - (void) settingsButtonClicked {
8449 [delegate_ showSettings];
8450 }
8451
8452 - (void) editButtonClicked {
8453 [list_ setEditing:![list_ isEditing] animated:YES];
8454
8455 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8456 }
8457
8458 @end
8459 /* }}} */
8460
8461 /* Settings Controller {{{ */
8462 @interface SettingsController : CyteViewController <
8463 UITableViewDataSource,
8464 UITableViewDelegate
8465 > {
8466 _transient Database *database_;
8467 // XXX: ok, "roledelegate_"?...
8468 _transient id roledelegate_;
8469 _H<UITableView, 2> table_;
8470 _H<UISegmentedControl> segment_;
8471 _H<UIView> container_;
8472 }
8473
8474 - (void) showDoneButton;
8475 - (void) resizeSegmentedControl;
8476
8477 @end
8478
8479 @implementation SettingsController
8480
8481 - (void) loadView {
8482 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8483
8484 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8485 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8486 [table_ setDelegate:self];
8487 [(UITableView *) table_ setDataSource:self];
8488 [[self view] addSubview:table_];
8489
8490 NSArray *items = [NSArray arrayWithObjects:
8491 UCLocalize("USER"),
8492 UCLocalize("HACKER"),
8493 UCLocalize("DEVELOPER"),
8494 nil];
8495 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8496 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8497 [container_ addSubview:segment_];
8498 }
8499
8500 - (void) viewDidLoad {
8501 [super viewDidLoad];
8502
8503 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8504
8505 int index = -1;
8506 if ([Role_ isEqualToString:@"User"]) index = 0;
8507 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8508 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8509 if (index != -1) {
8510 [segment_ setSelectedSegmentIndex:index];
8511 [self showDoneButton];
8512 }
8513
8514 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8515 [self resizeSegmentedControl];
8516 }
8517
8518 - (void) releaseSubviews {
8519 table_ = nil;
8520 segment_ = nil;
8521 container_ = nil;
8522
8523 [super releaseSubviews];
8524 }
8525
8526 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8527 if ((self = [super init]) != nil) {
8528 database_ = database;
8529 roledelegate_ = delegate;
8530 } return self;
8531 }
8532
8533 - (void) resizeSegmentedControl {
8534 CGFloat width = [[self view] frame].size.width;
8535 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8536 }
8537
8538 - (void) viewWillAppear:(BOOL)animated {
8539 [super viewWillAppear:animated];
8540
8541 [self resizeSegmentedControl];
8542 }
8543
8544 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8545 [self resizeSegmentedControl];
8546 }
8547
8548 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8549 [self resizeSegmentedControl];
8550 }
8551
8552 - (void) save {
8553 NSString *role(nil);
8554
8555 switch ([segment_ selectedSegmentIndex]) {
8556 case 0: role = @"User"; break;
8557 case 1: role = @"Hacker"; break;
8558 case 2: role = @"Developer"; break;
8559
8560 _nodefault
8561 }
8562
8563 if (![role isEqualToString:Role_]) {
8564 bool rolling(Role_ == nil);
8565 Role_ = role;
8566
8567 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8568 Role_, @"Role",
8569 nil];
8570
8571 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8572 Changed_ = true;
8573
8574 if (rolling)
8575 [roledelegate_ loadData];
8576 else
8577 [roledelegate_ updateData];
8578 }
8579 }
8580
8581 - (void) segmentChanged:(UISegmentedControl *)control {
8582 [self showDoneButton];
8583 }
8584
8585 - (void) saveAndClose {
8586 [self save];
8587
8588 [[self navigationItem] setRightBarButtonItem:nil];
8589 [[self navigationController] dismissModalViewControllerAnimated:YES];
8590 }
8591
8592 - (void) doneButtonClicked {
8593 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8594 [spinner startAnimating];
8595 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8596 [[self navigationItem] setRightBarButtonItem:spinItem];
8597
8598 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8599 }
8600
8601 - (void) showDoneButton {
8602 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8603 initWithTitle:UCLocalize("DONE")
8604 style:UIBarButtonItemStyleDone
8605 target:self
8606 action:@selector(doneButtonClicked)
8607 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8608 }
8609
8610 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8611 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8612 return 6;
8613 }
8614
8615 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8616 return 0; // :(
8617 }
8618
8619 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8620 return nil; // This method is required by the protocol.
8621 }
8622
8623 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8624 if (section == 1)
8625 return UCLocalize("ROLE_EX");
8626 if (section == 4)
8627 return [NSString stringWithFormat:
8628 @"%@: %@\n%@: %@\n%@: %@",
8629 UCLocalize("USER"), UCLocalize("USER_EX"),
8630 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8631 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8632 ];
8633 else return nil;
8634 }
8635
8636 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8637 return section == 3 ? 44.0f : 0;
8638 }
8639
8640 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8641 return section == 3 ? container_ : nil;
8642 }
8643
8644 - (void) reloadData {
8645 [super reloadData];
8646
8647 [table_ reloadData];
8648 }
8649
8650 @end
8651 /* }}} */
8652 /* Stash Controller {{{ */
8653 @interface StashController : CyteViewController {
8654 _H<UIActivityIndicatorView> spinner_;
8655 _H<UILabel> status_;
8656 _H<UILabel> caption_;
8657 }
8658
8659 @end
8660
8661 @implementation StashController
8662
8663 - (void) loadView {
8664 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8665 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8666
8667 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8668 CGRect spinrect = [spinner_ frame];
8669 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8670 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8671 [spinner_ setFrame:spinrect];
8672 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8673 [[self view] addSubview:spinner_];
8674 [spinner_ startAnimating];
8675
8676 CGRect captrect;
8677 captrect.size.width = [[self view] frame].size.width;
8678 captrect.size.height = 40.0f;
8679 captrect.origin.x = 0;
8680 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8681 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8682 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8683 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8684 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8685 [caption_ setTextColor:[UIColor whiteColor]];
8686 [caption_ setBackgroundColor:[UIColor clearColor]];
8687 [caption_ setShadowColor:[UIColor blackColor]];
8688 [caption_ setTextAlignment:UITextAlignmentCenter];
8689 [[self view] addSubview:caption_];
8690
8691 CGRect statusrect;
8692 statusrect.size.width = [[self view] frame].size.width;
8693 statusrect.size.height = 30.0f;
8694 statusrect.origin.x = 0;
8695 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8696 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8697 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8698 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8699 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8700 [status_ setTextColor:[UIColor whiteColor]];
8701 [status_ setBackgroundColor:[UIColor clearColor]];
8702 [status_ setShadowColor:[UIColor blackColor]];
8703 [status_ setTextAlignment:UITextAlignmentCenter];
8704 [[self view] addSubview:status_];
8705 }
8706
8707 - (void) releaseSubviews {
8708 spinner_ = nil;
8709 status_ = nil;
8710 caption_ = nil;
8711
8712 [super releaseSubviews];
8713 }
8714
8715 @end
8716 /* }}} */
8717
8718 @interface CYURLCache : SDURLCache {
8719 }
8720
8721 @end
8722
8723 @implementation CYURLCache
8724
8725 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8726 #if !ForRelease
8727 if (false);
8728 else if ([event isEqualToString:@"no-cache"])
8729 event = @"!!!";
8730 else if ([event isEqualToString:@"store"])
8731 event = @">>>";
8732 else if ([event isEqualToString:@"invalid"])
8733 event = @"???";
8734 else if ([event isEqualToString:@"memory"])
8735 event = @"mem";
8736 else if ([event isEqualToString:@"disk"])
8737 event = @"ssd";
8738 else if ([event isEqualToString:@"miss"])
8739 event = @"---";
8740
8741 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8742 #endif
8743 }
8744
8745 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8746 if (NSURLResponse *response = [cached response])
8747 if (NSString *mime = [response MIMEType])
8748 if ([mime isEqualToString:@"text/cache-manifest"]) {
8749 NSURL *url([response URL]);
8750
8751 #if !ForRelease
8752 NSLog(@"###: %@", [url absoluteString]);
8753 #endif
8754
8755 @synchronized (HostConfig_) {
8756 [CachedURLs_ addObject:url];
8757 }
8758 }
8759
8760 [super storeCachedResponse:cached forRequest:request];
8761 }
8762
8763 @end
8764
8765 @interface Cydia : UIApplication <
8766 ConfirmationControllerDelegate,
8767 DatabaseDelegate,
8768 CydiaDelegate,
8769 UINavigationControllerDelegate,
8770 UITabBarControllerDelegate
8771 > {
8772 _H<UIWindow> window_;
8773 _H<CYTabBarController> tabbar_;
8774 _H<CydiaLoadingViewController> emulated_;
8775
8776 _H<NSMutableArray> essential_;
8777 _H<NSMutableArray> broken_;
8778
8779 Database *database_;
8780
8781 _H<NSURL> starturl_;
8782
8783 unsigned locked_;
8784 unsigned activity_;
8785
8786 _H<StashController> stash_;
8787
8788 bool loaded_;
8789 }
8790
8791 - (void) loadData;
8792
8793 @end
8794
8795 @implementation Cydia
8796
8797 - (void) beginUpdate {
8798 [tabbar_ beginUpdate];
8799 }
8800
8801 - (BOOL) updating {
8802 return [tabbar_ updating];
8803 }
8804
8805 - (void) _loaded {
8806 if ([broken_ count] != 0) {
8807 int count = [broken_ count];
8808
8809 UIAlertView *alert = [[[UIAlertView alloc]
8810 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8811 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8812 delegate:self
8813 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8814 otherButtonTitles:
8815 UCLocalize("TEMPORARY_IGNORE"),
8816 nil
8817 ] autorelease];
8818
8819 [alert setContext:@"fixhalf"];
8820 [alert setNumberOfRows:2];
8821 [alert show];
8822 } else if (!Ignored_ && [essential_ count] != 0) {
8823 int count = [essential_ count];
8824
8825 UIAlertView *alert = [[[UIAlertView alloc]
8826 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8827 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8828 delegate:self
8829 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8830 otherButtonTitles:
8831 UCLocalize("UPGRADE_ESSENTIAL"),
8832 UCLocalize("COMPLETE_UPGRADE"),
8833 nil
8834 ] autorelease];
8835
8836 [alert setContext:@"upgrade"];
8837 [alert show];
8838 }
8839 }
8840
8841 - (void) _saveConfig {
8842 _trace();
8843 MetaFile_.Sync();
8844 _trace();
8845
8846 if (Changed_) {
8847 NSString *error(nil);
8848
8849 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8850 _trace();
8851 NSError *error(nil);
8852 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8853 NSLog(@"failure to save metadata data: %@", error);
8854 _trace();
8855
8856 Changed_ = false;
8857 } else {
8858 NSLog(@"failure to serialize metadata: %@", error);
8859 }
8860 }
8861
8862 WriteSources();
8863 }
8864
8865 // Navigation controller for the queuing badge.
8866 - (UINavigationController *) queueNavigationController {
8867 NSArray *controllers = [tabbar_ viewControllers];
8868 return [controllers objectAtIndex:3];
8869 }
8870
8871 - (void) unloadData {
8872 [tabbar_ unloadData];
8873 }
8874
8875 - (void) _updateData {
8876 [self _saveConfig];
8877 [self unloadData];
8878
8879 UINavigationController *navigation = [self queueNavigationController];
8880
8881 id queuedelegate = nil;
8882 if ([[navigation viewControllers] count] > 0)
8883 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8884
8885 [queuedelegate queueStatusDidChange];
8886 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8887 }
8888
8889 - (void) _refreshIfPossible:(NSDate *)update {
8890 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8891
8892 bool recently = false;
8893 if (update != nil) {
8894 NSTimeInterval interval([update timeIntervalSinceNow]);
8895 if (interval <= 0 && interval > -(15*60))
8896 recently = true;
8897 }
8898
8899 // Don't automatic refresh if:
8900 // - We already refreshed recently.
8901 // - We already auto-refreshed this launch.
8902 // - Auto-refresh is disabled.
8903 if (recently || loaded_ || ManualRefresh) {
8904 // If we are cancelling, we need to make sure it knows it's already loaded.
8905 loaded_ = true;
8906
8907 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8908 } else {
8909 // We are going to load, so remember that.
8910 loaded_ = true;
8911
8912 SCNetworkReachabilityFlags flags; {
8913 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8914 SCNetworkReachabilityGetFlags(reachability, &flags);
8915 CFRelease(reachability);
8916 }
8917
8918 // XXX: this elaborate mess is what Apple is using to determine this? :(
8919 // XXX: do we care if the user has to intervene? maybe that's ok?
8920 bool reachable(
8921 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8922 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8923 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8924 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8925 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8926 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8927 )
8928 );
8929
8930 // If we can reach the server, auto-refresh!
8931 if (reachable)
8932 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8933 }
8934
8935 [pool release];
8936 }
8937
8938 - (void) refreshIfPossible {
8939 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8940 }
8941
8942 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8943 @synchronized (self) {
8944 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8945 [hud setText:UCLocalize("RELOADING_DATA")];
8946
8947 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8948
8949 if (hud != nil)
8950 [self removeProgressHUD:hud];
8951
8952 size_t changes(0);
8953
8954 [essential_ removeAllObjects];
8955 [broken_ removeAllObjects];
8956
8957 NSArray *packages([database_ packages]);
8958 for (Package *package in packages) {
8959 if ([package half])
8960 [broken_ addObject:package];
8961 if ([package upgradableAndEssential:NO]) {
8962 if ([package essential])
8963 [essential_ addObject:package];
8964 ++changes;
8965 }
8966 }
8967
8968 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8969 if (changes != 0) {
8970 _trace();
8971 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8972 [changesItem setBadgeValue:badge];
8973 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8974 [self setApplicationIconBadgeNumber:changes];
8975 } else {
8976 _trace();
8977 [changesItem setBadgeValue:nil];
8978 [changesItem setAnimatedBadge:NO];
8979 [self setApplicationIconBadgeNumber:0];
8980 }
8981
8982 [self _updateData];
8983
8984 [self refreshIfPossible];
8985 } }
8986
8987 - (void) updateData {
8988 [self _updateData];
8989 }
8990
8991 - (void) update_ {
8992 [database_ update];
8993 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8994 }
8995
8996 - (void) disemulate {
8997 if (emulated_ == nil)
8998 return;
8999
9000 [window_ addSubview:[tabbar_ view]];
9001 [[emulated_ view] removeFromSuperview];
9002 emulated_ = nil;
9003 [window_ setUserInteractionEnabled:YES];
9004 }
9005
9006 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9007 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9008 if (IsWildcat_)
9009 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9010
9011 UIViewController *parent;
9012 if (emulated_ == nil)
9013 parent = tabbar_;
9014 else if (!force)
9015 parent = emulated_;
9016 else {
9017 [self disemulate];
9018 parent = tabbar_;
9019 }
9020
9021 [parent presentModalViewController:navigation animated:YES];
9022 }
9023
9024 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9025 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9026
9027 if (navigation != nil)
9028 [navigation pushViewController:progress animated:YES];
9029 else
9030 [self presentModalViewController:progress force:YES];
9031
9032 [progress invoke:invocation withTitle:title];
9033 return progress;
9034 }
9035
9036 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9037 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9038 }
9039
9040 - (void) repairWithInvocation:(NSInvocation *)invocation {
9041 _trace();
9042 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9043 _trace();
9044 }
9045
9046 - (void) repairWithSelector:(SEL)selector {
9047 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9048 }
9049
9050 - (void) reloadData {
9051 [self reloadDataWithInvocation:nil];
9052 }
9053
9054 - (void) syncData {
9055 [self _saveConfig];
9056 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9057 }
9058
9059 - (void) addSource:(NSDictionary *) source {
9060 AddSource(source);
9061 }
9062
9063 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9064 AddSource(href, distribution, sections);
9065 }
9066
9067 - (void) addTrivialSource:(NSString *)href {
9068 AddSource(href, @"./");
9069 }
9070
9071 - (void) updateValues {
9072 Changed_ = true;
9073 }
9074
9075 - (void) resolve {
9076 pkgProblemResolver *resolver = [database_ resolver];
9077
9078 resolver->InstallProtect();
9079 if (!resolver->Resolve(true))
9080 _error->Discard();
9081 }
9082
9083 - (bool) perform {
9084 // XXX: this is a really crappy way of doing this.
9085 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9086 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9087 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9088 if ([tabbar_ updating])
9089 [tabbar_ cancelUpdate];
9090
9091 if (![database_ prepare])
9092 return false;
9093
9094 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9095 [page setDelegate:self];
9096 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9097
9098 if (IsWildcat_)
9099 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9100 [tabbar_ presentModalViewController:confirm_ animated:YES];
9101
9102 return true;
9103 }
9104
9105 - (void) queue {
9106 @synchronized (self) {
9107 [self perform];
9108 }
9109 }
9110
9111 - (void) clearPackage:(Package *)package {
9112 @synchronized (self) {
9113 [package clear];
9114 [self resolve];
9115 [self perform];
9116 }
9117 }
9118
9119 - (void) installPackages:(NSArray *)packages {
9120 @synchronized (self) {
9121 for (Package *package in packages)
9122 [package install];
9123 [self resolve];
9124 [self perform];
9125 }
9126 }
9127
9128 - (void) installPackage:(Package *)package {
9129 @synchronized (self) {
9130 [package install];
9131 [self resolve];
9132 [self perform];
9133 }
9134 }
9135
9136 - (void) removePackage:(Package *)package {
9137 @synchronized (self) {
9138 [package remove];
9139 [self resolve];
9140 [self perform];
9141 }
9142 }
9143
9144 - (void) distUpgrade {
9145 @synchronized (self) {
9146 if (![database_ upgrade])
9147 return;
9148 [self perform];
9149 }
9150 }
9151
9152 - (void) perform_ {
9153 [database_ perform];
9154 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9155 }
9156
9157 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9158 Queuing_ = false;
9159 ++locked_;
9160 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9161 --locked_;
9162 }
9163
9164 - (void) showSettings {
9165 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9166 }
9167
9168 - (void) retainNetworkActivityIndicator {
9169 if (activity_++ == 0)
9170 [self setNetworkActivityIndicatorVisible:YES];
9171
9172 #if TraceLogging
9173 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9174 #endif
9175 }
9176
9177 - (void) releaseNetworkActivityIndicator {
9178 if (--activity_ == 0)
9179 [self setNetworkActivityIndicatorVisible:NO];
9180
9181 #if TraceLogging
9182 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9183 #endif
9184
9185 }
9186
9187 - (void) cancelAndClear:(bool)clear {
9188 @synchronized (self) {
9189 if (clear) {
9190 [database_ clear];
9191 Queuing_ = false;
9192 } else {
9193 Queuing_ = true;
9194 }
9195
9196 [self _updateData];
9197 }
9198 }
9199
9200 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9201 NSString *context([alert context]);
9202
9203 if ([context isEqualToString:@"conffile"]) {
9204 FILE *input = [database_ input];
9205 if (button == [alert cancelButtonIndex])
9206 fprintf(input, "N\n");
9207 else if (button == [alert firstOtherButtonIndex])
9208 fprintf(input, "Y\n");
9209 fflush(input);
9210
9211 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9212 } else if ([context isEqualToString:@"fixhalf"]) {
9213 if (button == [alert cancelButtonIndex]) {
9214 @synchronized (self) {
9215 for (Package *broken in (id) broken_) {
9216 [broken remove];
9217
9218 NSString *id = [broken id];
9219 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9220 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9221 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9222 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9223 }
9224
9225 [self resolve];
9226 [self perform];
9227 }
9228 } else if (button == [alert firstOtherButtonIndex]) {
9229 [broken_ removeAllObjects];
9230 [self _loaded];
9231 }
9232
9233 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9234 } else if ([context isEqualToString:@"upgrade"]) {
9235 if (button == [alert firstOtherButtonIndex]) {
9236 @synchronized (self) {
9237 for (Package *essential in (id) essential_)
9238 [essential install];
9239
9240 [self resolve];
9241 [self perform];
9242 }
9243 } else if (button == [alert firstOtherButtonIndex] + 1) {
9244 [self distUpgrade];
9245 } else if (button == [alert cancelButtonIndex]) {
9246 Ignored_ = YES;
9247 }
9248
9249 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9250 }
9251 }
9252
9253 - (void) system:(NSString *)command {
9254 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9255
9256 _trace();
9257 system([command UTF8String]);
9258 _trace();
9259
9260 [pool release];
9261 }
9262
9263 - (void) applicationWillSuspend {
9264 [database_ clean];
9265 [super applicationWillSuspend];
9266 }
9267
9268 - (BOOL) isSafeToSuspend {
9269 if (locked_ != 0) {
9270 #if !ForRelease
9271 NSLog(@"isSafeToSuspend: locked_ != 0");
9272 #endif
9273 return false;
9274 }
9275
9276 // Use external process status API internally.
9277 // This is probably a really bad idea.
9278 // XXX: what is the point of this? does this solve anything at all?
9279 uint64_t status = 0;
9280 int notify_token;
9281 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9282 notify_get_state(notify_token, &status);
9283 notify_cancel(notify_token);
9284 }
9285
9286 if (status != 0) {
9287 #if !ForRelease
9288 NSLog(@"isSafeToSuspend: status != 0");
9289 #endif
9290 return false;
9291 }
9292
9293 #if !ForRelease
9294 NSLog(@"isSafeToSuspend: -> true");
9295 #endif
9296 return true;
9297 }
9298
9299 - (void) applicationSuspend:(__GSEvent *)event {
9300 if ([self isSafeToSuspend])
9301 [super applicationSuspend:event];
9302 }
9303
9304 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9305 if ([self isSafeToSuspend])
9306 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9307 }
9308
9309 - (void) _setSuspended:(BOOL)value {
9310 if ([self isSafeToSuspend])
9311 [super _setSuspended:value];
9312 }
9313
9314 - (UIProgressHUD *) addProgressHUD {
9315 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9316 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9317
9318 [window_ setUserInteractionEnabled:NO];
9319
9320 UIViewController *target(tabbar_);
9321 if (UIViewController *modal = [target modalViewController])
9322 target = modal;
9323
9324 UIView *view([target view]);
9325 [view addSubview:hud];
9326
9327 [hud show:YES];
9328
9329 ++locked_;
9330 return hud;
9331 }
9332
9333 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9334 --locked_;
9335 [hud show:NO];
9336 [hud removeFromSuperview];
9337 [window_ setUserInteractionEnabled:YES];
9338 }
9339
9340 - (CyteViewController *) pageForPackage:(NSString *)name {
9341 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9342 }
9343
9344 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9345 NSString *scheme([[url scheme] lowercaseString]);
9346 if ([[url absoluteString] length] <= [scheme length] + 3)
9347 return nil;
9348 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9349 NSArray *components([path pathComponents]);
9350
9351 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9352 return [self pageForPackage:[components objectAtIndex:1]];
9353
9354 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9355 return nil;
9356
9357 NSString *base([components objectAtIndex:0]);
9358
9359 CyteViewController *controller = nil;
9360
9361 if ([base isEqualToString:@"url"]) {
9362 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9363 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9364 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9365 } else if (!external && [components count] == 1) {
9366 if ([base isEqualToString:@"manage"]) {
9367 controller = [[[ManageController alloc] init] autorelease];
9368 }
9369
9370 if ([base isEqualToString:@"sources"]) {
9371 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9372 }
9373
9374 if ([base isEqualToString:@"home"]) {
9375 controller = [[[HomeController alloc] init] autorelease];
9376 }
9377
9378 if ([base isEqualToString:@"sections"]) {
9379 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9380 }
9381
9382 if ([base isEqualToString:@"search"]) {
9383 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9384 }
9385
9386 if ([base isEqualToString:@"changes"]) {
9387 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9388 }
9389
9390 if ([base isEqualToString:@"installed"]) {
9391 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9392 }
9393 } else if ([components count] == 2) {
9394 NSString *argument = [components objectAtIndex:1];
9395
9396 if ([base isEqualToString:@"package"]) {
9397 controller = [self pageForPackage:argument];
9398 }
9399
9400 if (!external && [base isEqualToString:@"search"]) {
9401 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9402 }
9403
9404 if (!external && [base isEqualToString:@"sections"]) {
9405 if ([argument isEqualToString:@"all"])
9406 argument = nil;
9407 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9408 }
9409
9410 if (!external && [base isEqualToString:@"sources"]) {
9411 if ([argument isEqualToString:@"add"]) {
9412 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9413 [(SourcesController *)controller showAddSourcePrompt];
9414 } else {
9415 Source *source = [database_ sourceWithKey:argument];
9416 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9417 }
9418 }
9419
9420 if (!external && [base isEqualToString:@"launch"]) {
9421 [self launchApplicationWithIdentifier:argument suspended:NO];
9422 return nil;
9423 }
9424 } else if (!external && [components count] == 3) {
9425 NSString *arg1 = [components objectAtIndex:1];
9426 NSString *arg2 = [components objectAtIndex:2];
9427
9428 if ([base isEqualToString:@"package"]) {
9429 if ([arg2 isEqualToString:@"settings"]) {
9430 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9431 } else if ([arg2 isEqualToString:@"files"]) {
9432 if (Package *package = [database_ packageWithName:arg1]) {
9433 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9434 [(FileTable *)controller setPackage:package];
9435 }
9436 }
9437 }
9438 }
9439
9440 [controller setDelegate:self];
9441 return controller;
9442 }
9443
9444 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9445 CyteViewController *page([self pageForURL:url forExternal:external]);
9446
9447 if (page != nil) {
9448 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9449 [nav setViewControllers:[NSArray arrayWithObject:page]];
9450 [tabbar_ setUnselectedViewController:nav];
9451 }
9452
9453 return page != nil;
9454 }
9455
9456 - (void) applicationOpenURL:(NSURL *)url {
9457 [super applicationOpenURL:url];
9458
9459 if (!loaded_)
9460 starturl_ = url;
9461 else
9462 [self openCydiaURL:url forExternal:YES];
9463 }
9464
9465 - (void) applicationWillResignActive:(UIApplication *)application {
9466 // Stop refreshing if you get a phone call or lock the device.
9467 if ([tabbar_ updating])
9468 [tabbar_ cancelUpdate];
9469
9470 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9471 [super applicationWillResignActive:application];
9472 }
9473
9474 - (void) applicationWillTerminate:(UIApplication *)application {
9475 Changed_ = true;
9476 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9477 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9478 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9479
9480 [self _saveConfig];
9481 }
9482
9483 - (void) setConfigurationData:(NSString *)data {
9484 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9485
9486 if (!conffile_r(data)) {
9487 lprintf("E:invalid conffile\n");
9488 return;
9489 }
9490
9491 NSString *ofile = conffile_r[1];
9492 //NSString *nfile = conffile_r[2];
9493
9494 UIAlertView *alert = [[[UIAlertView alloc]
9495 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9496 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9497 delegate:self
9498 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9499 otherButtonTitles:
9500 UCLocalize("ACCEPT_NEW_COPY"),
9501 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9502 nil
9503 ] autorelease];
9504
9505 [alert setContext:@"conffile"];
9506 [alert setNumberOfRows:2];
9507 [alert show];
9508 }
9509
9510 - (void) addStashController {
9511 ++locked_;
9512 stash_ = [[[StashController alloc] init] autorelease];
9513 [window_ addSubview:[stash_ view]];
9514 }
9515
9516 - (void) removeStashController {
9517 [[stash_ view] removeFromSuperview];
9518 stash_ = nil;
9519 --locked_;
9520 }
9521
9522 - (void) stash {
9523 [self setIdleTimerDisabled:YES];
9524
9525 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9526 UpdateExternalStatus(1);
9527 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9528 UpdateExternalStatus(0);
9529
9530 [self removeStashController];
9531
9532 if (ExecFork() == 0) {
9533 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9534 perror("launchctl stop");
9535 }
9536 }
9537
9538 - (void) setupViewControllers {
9539 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9540
9541 NSMutableArray *items([NSMutableArray arrayWithObjects:
9542 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9543 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9544 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9545 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9546 nil]);
9547
9548 if (IsWildcat_) {
9549 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9550 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9551 } else {
9552 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9553 }
9554
9555 NSMutableArray *controllers([NSMutableArray array]);
9556 for (UITabBarItem *item in items) {
9557 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9558 [controller setTabBarItem:item];
9559 [controllers addObject:controller];
9560 }
9561 [tabbar_ setViewControllers:controllers];
9562
9563 [tabbar_ setUpdateDelegate:self];
9564 }
9565
9566 - (void) applicationDidFinishLaunching:(id)unused {
9567 _trace();
9568 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9569 [self setApplicationSupportsShakeToEdit:NO];
9570
9571 @synchronized (HostConfig_) {
9572 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9573 }
9574
9575 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9576 initWithMemoryCapacity:524288
9577 diskCapacity:10485760
9578 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9579 ] autorelease]];
9580
9581 [CydiaWebViewController _initialize];
9582
9583 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9584
9585 // this would disallow http{,s} URLs from accessing this data
9586 //[WebView registerURLSchemeAsLocal:@"cydia"];
9587
9588 Font12_ = [UIFont systemFontOfSize:12];
9589 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9590 Font14_ = [UIFont systemFontOfSize:14];
9591 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9592 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9593
9594 essential_ = [NSMutableArray arrayWithCapacity:4];
9595 broken_ = [NSMutableArray arrayWithCapacity:4];
9596
9597 // XXX: I really need this thing... like, seriously... I'm sorry
9598 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9599
9600 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9601 [window_ orderFront:self];
9602 [window_ makeKey:self];
9603 [window_ setHidden:NO];
9604
9605 if (
9606 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9607 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9608 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9609 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9610 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9611 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9612 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9613 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9614 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9615 false
9616 ) {
9617 [self addStashController];
9618 // XXX: this would be much cleaner as a yieldToSelector:
9619 // that way the removeStashController could happen right here inline
9620 // we also could no longer require the useless stash_ field anymore
9621 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9622 return;
9623 }
9624
9625 database_ = [Database sharedInstance];
9626 [database_ setDelegate:self];
9627
9628 [window_ setUserInteractionEnabled:NO];
9629 [self setupViewControllers];
9630
9631 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9632 [window_ addSubview:[emulated_ view]];
9633
9634 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9635 _trace();
9636 }
9637
9638 - (NSArray *) defaultStartPages {
9639 NSMutableArray *standard = [NSMutableArray array];
9640 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9641 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9642 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9643 if (!IsWildcat_) {
9644 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9645 } else {
9646 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9647 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9648 }
9649 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9650 return standard;
9651 }
9652
9653 - (void) loadData {
9654 _trace();
9655 if (Role_ == nil) {
9656 [window_ setUserInteractionEnabled:YES];
9657 [self showSettings];
9658 return;
9659 } else {
9660 if ([emulated_ modalViewController] != nil)
9661 [emulated_ dismissModalViewControllerAnimated:YES];
9662 [window_ setUserInteractionEnabled:NO];
9663 }
9664
9665 [self reloadData];
9666 PrintTimes();
9667
9668 [self disemulate];
9669
9670 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9671 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9672 int standardIndex = 0;
9673 NSArray *standard = [self defaultStartPages];
9674
9675 BOOL valid = YES;
9676
9677 if (saved == nil)
9678 valid = NO;
9679
9680 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9681 if (valid && closed != nil) {
9682 NSTimeInterval interval([closed timeIntervalSinceNow]);
9683 // XXX: Is 15 minutes the optimal time here?
9684 if (interval > 0 && interval <= -(15*60))
9685 valid = NO;
9686 }
9687
9688 if (valid && [saved count] != [standard count])
9689 valid = NO;
9690
9691 if (valid) {
9692 for (unsigned int i = 0; i < [standard count]; i++) {
9693 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9694 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9695 // but it's good enough for now.
9696 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9697 valid = NO;
9698 break;
9699 }
9700 }
9701 }
9702
9703 NSArray *items = nil;
9704 if (valid) {
9705 [tabbar_ setSelectedIndex:savedIndex];
9706 items = saved;
9707 } else {
9708 [tabbar_ setSelectedIndex:standardIndex];
9709 items = standard;
9710 }
9711
9712 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9713 NSArray *stack = [items objectAtIndex:tab];
9714 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9715 NSMutableArray *current = [NSMutableArray array];
9716
9717 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9718 NSString *addr = [stack objectAtIndex:nav];
9719 NSURL *url = [NSURL URLWithString:addr];
9720 CyteViewController *page = [self pageForURL:url forExternal:NO];
9721 if (page != nil)
9722 [current addObject:page];
9723 }
9724
9725 [navigation setViewControllers:current];
9726 }
9727
9728 // (Try to) show the startup URL.
9729 if (starturl_ != nil) {
9730 [self openCydiaURL:starturl_ forExternal:NO];
9731 starturl_ = nil;
9732 }
9733 }
9734
9735 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9736 if (item != nil && IsWildcat_) {
9737 [sheet showFromBarButtonItem:item animated:YES];
9738 } else {
9739 [sheet showInView:window_];
9740 }
9741 }
9742
9743 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9744 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9745 [progress setTitle:task];
9746 [progress addProgressEvent:event];
9747 }
9748
9749 - (void) addProgressEventForTask:(NSArray *)data {
9750 CydiaProgressEvent *event([data objectAtIndex:0]);
9751 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9752 [self addProgressEvent:event forTask:task];
9753 }
9754
9755 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9756 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9757 }
9758
9759 @end
9760
9761 /*IMP alloc_;
9762 id Alloc_(id self, SEL selector) {
9763 id object = alloc_(self, selector);
9764 lprintf("[%s]A-%p\n", self->isa->name, object);
9765 return object;
9766 }*/
9767
9768 /*IMP dealloc_;
9769 id Dealloc_(id self, SEL selector) {
9770 id object = dealloc_(self, selector);
9771 lprintf("[%s]D-%p\n", self->isa->name, object);
9772 return object;
9773 }*/
9774
9775 Class $WebDefaultUIKitDelegate;
9776
9777 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9778 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9779 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9780 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9781 }
9782
9783 static NSSet *MobilizedFiles_;
9784
9785 static NSURL *MobilizeURL(NSURL *url) {
9786 NSString *path([url path]);
9787 if ([path hasPrefix:@"/var/root/"]) {
9788 NSString *file([path substringFromIndex:10]);
9789 if ([MobilizedFiles_ containsObject:file])
9790 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9791 }
9792
9793 return url;
9794 }
9795
9796 Class $CFXPreferencesPropertyListSource;
9797 @class CFXPreferencesPropertyListSource;
9798
9799 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9800 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9801 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9802 url = MobilizeURL(url);
9803 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9804 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9805 url = old;
9806 [pool release];
9807 return value;
9808 }
9809
9810 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9811 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9812 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9813 url = MobilizeURL(url);
9814 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9815 //NSLog(@"%@ %@", [url absoluteString], value);
9816 url = old;
9817 [pool release];
9818 return value;
9819 }
9820
9821 Class $NSURLConnection;
9822
9823 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9824 NSMutableURLRequest *copy([request mutableCopy]);
9825
9826 NSURL *url([copy URL]);
9827
9828 NSString *href([url absoluteString]);
9829 NSString *host([url host]);
9830 NSString *scheme([[url scheme] lowercaseString]);
9831
9832 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9833
9834 @synchronized (HostConfig_) {
9835 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9836 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9837 [copy setHTTPShouldUsePipelining:YES];
9838
9839 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9840 if ([control isEqualToString:@"max-age=0"])
9841 if ([CachedURLs_ containsObject:href]) {
9842 #if !ForRelease
9843 NSLog(@"~~~: %@", href);
9844 #endif
9845
9846 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9847
9848 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9849 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9850 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9851 }
9852 }
9853
9854 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9855 } return self;
9856 }
9857
9858 int main(int argc, char *argv[]) {
9859 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9860
9861 _trace();
9862
9863 UpdateExternalStatus(0);
9864
9865 if (Class $UIDevice = objc_getClass("UIDevice")) {
9866 UIDevice *device([$UIDevice currentDevice]);
9867 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9868 } else
9869 IsWildcat_ = false;
9870
9871 UIScreen *screen([UIScreen mainScreen]);
9872 if ([screen respondsToSelector:@selector(scale)])
9873 ScreenScale_ = [screen scale];
9874 else
9875 ScreenScale_ = 1;
9876
9877 UIDevice *device([UIDevice currentDevice]);
9878 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9879 Idiom_ = @"iphone";
9880 else {
9881 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9882 if (idiom == UIUserInterfaceIdiomPhone)
9883 Idiom_ = @"iphone";
9884 else if (idiom == UIUserInterfaceIdiomPad)
9885 Idiom_ = @"ipad";
9886 else
9887 NSLog(@"unknown UIUserInterfaceIdiom!");
9888 }
9889
9890 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9891
9892 HostConfig_ = [[[NSObject alloc] init] autorelease];
9893 @synchronized (HostConfig_) {
9894 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9895 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9896 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9897 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9898 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9899 }
9900
9901 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9902
9903 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9904
9905 MobilizedFiles_ = [NSMutableSet setWithObjects:
9906 @"Library/Preferences/com.apple.Accessibility.plist",
9907 @"Library/Preferences/com.apple.preferences.sounds.plist",
9908 nil];
9909
9910 /* Library Hacks {{{ */
9911 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9912
9913 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9914
9915 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9916 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9917 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9918 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9919 }
9920
9921 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9922 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9923 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9924 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9925 }
9926
9927 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9928 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9929 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9930 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9931 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9932 }
9933
9934 $NSURLConnection = objc_getClass("NSURLConnection");
9935 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9936 if (NSURLConnection$init$ != NULL) {
9937 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9938 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9939 }
9940 /* }}} */
9941 /* Set Locale {{{ */
9942 Locale_ = CFLocaleCopyCurrent();
9943 Languages_ = [NSLocale preferredLanguages];
9944
9945 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9946 //NSLog(@"%@", [Languages_ description]);
9947
9948 const char *lang;
9949 if (Locale_ != NULL)
9950 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9951 else if (Languages_ != nil && [Languages_ count] != 0)
9952 lang = [[Languages_ objectAtIndex:0] UTF8String];
9953 else
9954 // XXX: consider just setting to C and then falling through?
9955 lang = NULL;
9956
9957 if (lang != NULL) {
9958 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9959 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9960 }
9961
9962 NSLog(@"Setting Language: %s", lang);
9963
9964 if (lang != NULL) {
9965 setenv("LANG", lang, true);
9966 std::setlocale(LC_ALL, lang);
9967 }
9968 /* }}} */
9969
9970 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9971
9972 /* Parse Arguments {{{ */
9973 bool substrate(false);
9974
9975 if (argc != 0) {
9976 char **args(argv);
9977 int arge(1);
9978
9979 for (int argi(1); argi != argc; ++argi)
9980 if (strcmp(argv[argi], "--") == 0) {
9981 arge = argi;
9982 argv[argi] = argv[0];
9983 argv += argi;
9984 argc -= argi;
9985 break;
9986 }
9987
9988 for (int argi(1); argi != arge; ++argi)
9989 if (strcmp(args[argi], "--substrate") == 0)
9990 substrate = true;
9991 else
9992 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9993 }
9994 /* }}} */
9995
9996 App_ = [[NSBundle mainBundle] bundlePath];
9997 Advanced_ = YES;
9998
9999 setuid(0);
10000 setgid(0);
10001
10002 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10003 alloc_ = alloc->method_imp;
10004 alloc->method_imp = (IMP) &Alloc_;*/
10005
10006 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10007 dealloc_ = dealloc->method_imp;
10008 dealloc->method_imp = (IMP) &Dealloc_;*/
10009
10010 /* System Information {{{ */
10011 size_t size;
10012
10013 int maxproc;
10014 size = sizeof(maxproc);
10015 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10016 perror("sysctlbyname(\"kern.maxproc\", ?)");
10017 else if (maxproc < 64) {
10018 maxproc = 64;
10019 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10020 perror("sysctlbyname(\"kern.maxproc\", #)");
10021 }
10022
10023 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10024 char *osversion = new char[size];
10025 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10026 perror("sysctlbyname(\"kern.osversion\", ?)");
10027 else
10028 System_ = [NSString stringWithUTF8String:osversion];
10029
10030 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10031 char *machine = new char[size];
10032 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10033 perror("sysctlbyname(\"hw.machine\", ?)");
10034 else
10035 Machine_ = machine;
10036
10037 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10038 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10039 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10040
10041 UniqueID_ = [device uniqueIdentifier];
10042
10043 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10044 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10045 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10046
10047 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10048 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10049 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10050
10051 if (mcc != NULL && mnc != NULL)
10052 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10053
10054 if (mnc != NULL)
10055 CFRelease(mnc);
10056 if (mcc != NULL)
10057 CFRelease(mcc);
10058
10059 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10060 Build_ = [system objectForKey:@"ProductBuildVersion"];
10061 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10062 Product_ = [info objectForKey:@"SafariProductVersion"];
10063 Safari_ = [info objectForKey:@"CFBundleVersion"];
10064 }
10065 /* }}} */
10066 /* Load Database {{{ */
10067 _trace();
10068 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10069 _trace();
10070 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10071
10072 if (Metadata_ == NULL)
10073 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10074 else {
10075 Settings_ = [Metadata_ objectForKey:@"Settings"];
10076
10077 Packages_ = [Metadata_ objectForKey:@"Packages"];
10078
10079 Values_ = [Metadata_ objectForKey:@"Values"];
10080 Sections_ = [Metadata_ objectForKey:@"Sections"];
10081 Sources_ = [Metadata_ objectForKey:@"Sources"];
10082
10083 Token_ = [Metadata_ objectForKey:@"Token"];
10084
10085 Version_ = [Metadata_ objectForKey:@"Version"];
10086
10087 @synchronized (HostConfig_) {
10088 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10089 }
10090 }
10091
10092 if (Settings_ != nil)
10093 Role_ = [Settings_ objectForKey:@"Role"];
10094
10095 if (Values_ == nil) {
10096 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10097 [Metadata_ setObject:Values_ forKey:@"Values"];
10098 }
10099
10100 if (Sections_ == nil) {
10101 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10102 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10103 }
10104
10105 if (Sources_ == nil) {
10106 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10107 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10108 }
10109
10110 if (Version_ == nil) {
10111 Version_ = [NSNumber numberWithUnsignedInt:0];
10112 [Metadata_ setObject:Version_ forKey:@"Version"];
10113 }
10114
10115 @synchronized (HostConfig_) {
10116 if (CydiaSource_ == nil) {
10117 CydiaSource_ = @"apt.saurik.com";
10118 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10119 }
10120 }
10121
10122 if ([Version_ unsignedIntValue] == 0) {
10123 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10124 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10125 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10126 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10127
10128 Version_ = [NSNumber numberWithUnsignedInt:1];
10129 [Metadata_ setObject:Version_ forKey:@"Version"];
10130
10131 Changed_ = true;
10132 }
10133 /* }}} */
10134
10135 WriteSources();
10136
10137 _trace();
10138 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10139 _trace();
10140
10141 if (Packages_ != nil) {
10142 bool fail(false);
10143 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10144 _trace();
10145
10146 if (!fail) {
10147 [Metadata_ removeObjectForKey:@"Packages"];
10148 Packages_ = nil;
10149 Changed_ = true;
10150 }
10151 }
10152
10153 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10154
10155 #define MobileSubstrate_(name) \
10156 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10157 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10158 if (handle == NULL) \
10159 NSLog(@"%s", dlerror()); \
10160 }
10161
10162 MobileSubstrate_(Activator)
10163 MobileSubstrate_(libstatusbar)
10164 MobileSubstrate_(SimulatedKeyEvents)
10165 MobileSubstrate_(WinterBoard)
10166
10167 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10168 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10169
10170 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10171
10172 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10173 unlink("/tmp/.cydia.fw");
10174 goto firmware;
10175 } else if (access("/User", F_OK) != 0 || version < 4) {
10176 firmware:
10177 _trace();
10178 system("/usr/libexec/cydia/firmware.sh");
10179 _trace();
10180 }
10181
10182 _assert([[NSFileManager defaultManager]
10183 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10184 withIntermediateDirectories:YES
10185 attributes:nil
10186 error:NULL
10187 ]);
10188
10189 if (access("/tmp/cydia.chk", F_OK) == 0) {
10190 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10191 _assert(errno == ENOENT);
10192 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10193 _assert(errno == ENOENT);
10194 }
10195
10196 /* APT Initialization {{{ */
10197 _assert(pkgInitConfig(*_config));
10198 _assert(pkgInitSystem(*_config, _system));
10199
10200 if (lang != NULL)
10201 _config->Set("APT::Acquire::Translation", lang);
10202
10203 // XXX: this timeout might be important :(
10204 //_config->Set("Acquire::http::Timeout", 15);
10205
10206 _config->Set("Acquire::http::MaxParallel", 3);
10207 /* }}} */
10208 /* Color Choices {{{ */
10209 space_ = CGColorSpaceCreateDeviceRGB();
10210
10211 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10212 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10213 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10214 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10215 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10216 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10217 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10218 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10219 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10220
10221 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10222 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10223 /* }}}*/
10224 /* UIKit Configuration {{{ */
10225 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10226 if ($GSFontSetUseLegacyFontMetrics != NULL)
10227 $GSFontSetUseLegacyFontMetrics(YES);
10228
10229 // XXX: I have a feeling this was important
10230 //UIKeyboardDisableAutomaticAppearance();
10231 /* }}} */
10232
10233 Colon_ = UCLocalize("COLON_DELIMITED");
10234 Elision_ = UCLocalize("ELISION");
10235 Error_ = UCLocalize("ERROR");
10236 Warning_ = UCLocalize("WARNING");
10237
10238 _trace();
10239 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10240
10241 CGColorSpaceRelease(space_);
10242 CFRelease(Locale_);
10243
10244 [pool release];
10245 return value;
10246 }