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