]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
basic_string::_S_construct NULL not valid
[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 [self dismissModalViewControllerAnimated:YES];
4671 [delegate_ cancelAndClear:NO];
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 if (UIViewController *visible = [self visibleViewController])
6931 [visible reloadData];
6932 }
6933
6934 - (void) unloadData {
6935 for (CyteViewController *page in [self viewControllers])
6936 [page unloadData];
6937
6938 [super unloadData];
6939 }
6940
6941 @end
6942 /* }}} */
6943
6944 /* Cydia:// Protocol {{{ */
6945 @interface CydiaURLProtocol : NSURLProtocol {
6946 }
6947
6948 @end
6949
6950 @implementation CydiaURLProtocol
6951
6952 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6953 NSURL *url([request URL]);
6954 if (url == nil)
6955 return NO;
6956
6957 NSString *scheme([[url scheme] lowercaseString]);
6958 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6959 return YES;
6960 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6961 return YES;
6962
6963 return NO;
6964 }
6965
6966 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6967 return request;
6968 }
6969
6970 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6971 id<NSURLProtocolClient> client([self client]);
6972 if (icon == nil)
6973 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6974 else {
6975 NSData *data(UIImagePNGRepresentation(icon));
6976
6977 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6978 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6979 [client URLProtocol:self didLoadData:data];
6980 [client URLProtocolDidFinishLoading:self];
6981 }
6982 }
6983
6984 - (void) startLoading {
6985 id<NSURLProtocolClient> client([self client]);
6986 NSURLRequest *request([self request]);
6987
6988 NSURL *url([request URL]);
6989 NSString *href([url absoluteString]);
6990 NSString *scheme([[url scheme] lowercaseString]);
6991
6992 NSString *path;
6993
6994 if ([scheme isEqualToString:@"cydia"])
6995 path = [href substringFromIndex:8];
6996 else if ([scheme isEqualToString:@"about"])
6997 path = [href substringFromIndex:12];
6998 else _assert(false);
6999
7000 NSRange slash([path rangeOfString:@"/"]);
7001
7002 NSString *command;
7003 if (slash.location == NSNotFound) {
7004 command = path;
7005 path = nil;
7006 } else {
7007 command = [path substringToIndex:slash.location];
7008 path = [path substringFromIndex:(slash.location + 1)];
7009 }
7010
7011 Database *database([Database sharedInstance]);
7012
7013 if ([command isEqualToString:@"package-icon"]) {
7014 if (path == nil)
7015 goto fail;
7016 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7017 Package *package([database packageWithName:path]);
7018 if (package == nil)
7019 goto fail;
7020 [package parse];
7021 UIImage *icon([package icon]);
7022 [self _returnPNGWithImage:icon forRequest:request];
7023 } else if ([command isEqualToString:@"source-icon"]) {
7024 if (path == nil)
7025 goto fail;
7026 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7027 NSString *source(Simplify(path));
7028 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7029 if (icon == nil)
7030 icon = [UIImage applicationImageNamed:@"unknown.png"];
7031 [self _returnPNGWithImage:icon forRequest:request];
7032 } else if ([command isEqualToString:@"uikit-image"]) {
7033 if (path == nil)
7034 goto fail;
7035 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7036 UIImage *icon(_UIImageWithName(path));
7037 [self _returnPNGWithImage:icon forRequest:request];
7038 } else if ([command isEqualToString:@"section-icon"]) {
7039 if (path == nil)
7040 goto fail;
7041 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7042 NSString *section(Simplify(path));
7043 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7044 if (icon == nil)
7045 icon = [UIImage applicationImageNamed:@"unknown.png"];
7046 [self _returnPNGWithImage:icon forRequest:request];
7047 } else fail: {
7048 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7049 }
7050 }
7051
7052 - (void) stopLoading {
7053 }
7054
7055 @end
7056 /* }}} */
7057
7058 /* Section Controller {{{ */
7059 @interface SectionController : FilteredPackageListController {
7060 _H<NSString> section_;
7061 }
7062
7063 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7064
7065 @end
7066
7067 @implementation SectionController
7068
7069 - (NSURL *) navigationURL {
7070 NSString *name = section_;
7071 if (name == nil)
7072 name = @"all";
7073
7074 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7075 }
7076
7077 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7078 NSString *title;
7079 if (name == nil)
7080 title = UCLocalize("ALL_PACKAGES");
7081 else if (![name isEqual:@""])
7082 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7083 else
7084 title = UCLocalize("NO_SECTION");
7085
7086 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7087 section_ = name;
7088 } return self;
7089 }
7090
7091 @end
7092 /* }}} */
7093 /* Sections Controller {{{ */
7094 @interface SectionsController : CyteViewController <
7095 UITableViewDataSource,
7096 UITableViewDelegate
7097 > {
7098 _transient Database *database_;
7099 _H<NSMutableArray> sections_;
7100 _H<NSMutableArray> filtered_;
7101 _H<UITableView, 2> list_;
7102 }
7103
7104 - (id) initWithDatabase:(Database *)database;
7105 - (void) editButtonClicked;
7106
7107 @end
7108
7109 @implementation SectionsController
7110
7111 - (NSURL *) navigationURL {
7112 return [NSURL URLWithString:@"cydia://sections"];
7113 }
7114
7115 - (void) updateNavigationItem {
7116 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7117 if ([sections_ count] == 0) {
7118 [[self navigationItem] setRightBarButtonItem:nil];
7119 } else {
7120 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7121 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7122 target:self
7123 action:@selector(editButtonClicked)
7124 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7125 }
7126 }
7127
7128 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7129 [super setEditing:editing animated:animated];
7130
7131 if (editing)
7132 [list_ reloadData];
7133 else
7134 [delegate_ updateData];
7135
7136 [self updateNavigationItem];
7137 }
7138
7139 - (void) viewDidAppear:(BOOL)animated {
7140 [super viewDidAppear:animated];
7141 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7142 }
7143
7144 - (void) viewWillDisappear:(BOOL)animated {
7145 [super viewWillDisappear:animated];
7146 if ([self isEditing]) [self setEditing:NO];
7147 }
7148
7149 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7150 Section *section = nil;
7151 int index = [indexPath row];
7152 if (![self isEditing]) {
7153 index -= 1;
7154 if (index >= 0)
7155 section = [filtered_ objectAtIndex:index];
7156 } else {
7157 section = [sections_ objectAtIndex:index];
7158 }
7159 return section;
7160 }
7161
7162 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7163 if ([self isEditing])
7164 return [sections_ count];
7165 else
7166 return [filtered_ count] + 1;
7167 }
7168
7169 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7170 return 45.0f;
7171 }*/
7172
7173 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7174 static NSString *reuseIdentifier = @"SectionCell";
7175
7176 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7177 if (cell == nil)
7178 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7179
7180 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7181
7182 return cell;
7183 }
7184
7185 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7186 if ([self isEditing])
7187 return;
7188
7189 Section *section = [self sectionAtIndexPath:indexPath];
7190
7191 SectionController *controller = [[[SectionController alloc]
7192 initWithDatabase:database_
7193 section:[section name]
7194 ] autorelease];
7195 [controller setDelegate:delegate_];
7196
7197 [[self navigationController] pushViewController:controller animated:YES];
7198 }
7199
7200 - (void) loadView {
7201 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7202
7203 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7204 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7205 [list_ setRowHeight:45.0f];
7206 [(UITableView *) list_ setDataSource:self];
7207 [list_ setDelegate:self];
7208 [[self view] addSubview:list_];
7209 }
7210
7211 - (void) viewDidLoad {
7212 [super viewDidLoad];
7213
7214 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7215 }
7216
7217 - (void) releaseSubviews {
7218 list_ = nil;
7219
7220 [super releaseSubviews];
7221 }
7222
7223 - (id) initWithDatabase:(Database *)database {
7224 if ((self = [super init]) != nil) {
7225 database_ = database;
7226
7227 sections_ = [NSMutableArray arrayWithCapacity:16];
7228 filtered_ = [NSMutableArray arrayWithCapacity:16];
7229 } return self;
7230 }
7231
7232 - (void) reloadData {
7233 [super reloadData];
7234
7235 NSArray *packages = [database_ packages];
7236
7237 [sections_ removeAllObjects];
7238 [filtered_ removeAllObjects];
7239
7240 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7241
7242 _trace();
7243 for (Package *package in packages) {
7244 NSString *name([package section]);
7245 NSString *key(name == nil ? @"" : name);
7246
7247 Section *section;
7248
7249 _profile(SectionsView$reloadData$Section)
7250 section = [sections objectForKey:key];
7251 if (section == nil) {
7252 _profile(SectionsView$reloadData$Section$Allocate)
7253 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7254 [sections setObject:section forKey:key];
7255 _end
7256 }
7257 _end
7258
7259 [section addToCount];
7260
7261 _profile(SectionsView$reloadData$Filter)
7262 if (![package valid] || ![package visible])
7263 continue;
7264 _end
7265
7266 [section addToRow];
7267 }
7268 _trace();
7269
7270 [sections_ addObjectsFromArray:[sections allValues]];
7271
7272 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7273
7274 for (Section *section in (id) sections_) {
7275 size_t count([section row]);
7276 if (count == 0)
7277 continue;
7278
7279 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7280 [section setCount:count];
7281 [filtered_ addObject:section];
7282 }
7283
7284 [self updateNavigationItem];
7285 [list_ reloadData];
7286 _trace();
7287 }
7288
7289 - (void) editButtonClicked {
7290 [self setEditing:![self isEditing] animated:YES];
7291 }
7292
7293 @end
7294 /* }}} */
7295
7296 /* Changes Controller {{{ */
7297 @interface ChangesController : CyteViewController <
7298 UITableViewDataSource,
7299 UITableViewDelegate
7300 > {
7301 _transient Database *database_;
7302 unsigned era_;
7303 _H<NSArray> packages_;
7304 _H<NSMutableArray> sections_;
7305 _H<UITableView, 2> list_;
7306 unsigned upgrades_;
7307 }
7308
7309 - (id) initWithDatabase:(Database *)database;
7310
7311 @end
7312
7313 @implementation ChangesController
7314
7315 - (NSURL *) navigationURL {
7316 return [NSURL URLWithString:@"cydia://changes"];
7317 }
7318
7319 - (void) viewDidAppear:(BOOL)animated {
7320 [super viewDidAppear:animated];
7321 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7322 }
7323
7324 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7325 NSInteger count([sections_ count]);
7326 return count == 0 ? 1 : count;
7327 }
7328
7329 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7330 if ([sections_ count] == 0)
7331 return nil;
7332 return [[sections_ objectAtIndex:section] name];
7333 }
7334
7335 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7336 if ([sections_ count] == 0)
7337 return 0;
7338 return [[sections_ objectAtIndex:section] count];
7339 }
7340
7341 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7342 @synchronized (database_) {
7343 if ([database_ era] != era_)
7344 return nil;
7345
7346 NSUInteger sectionIndex([path section]);
7347 if (sectionIndex >= [sections_ count])
7348 return nil;
7349 Section *section([sections_ objectAtIndex:sectionIndex]);
7350 NSInteger row([path row]);
7351 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7352 } }
7353
7354 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7355 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7356 if (cell == nil)
7357 cell = [[[PackageCell alloc] init] autorelease];
7358
7359 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7360 [cell setPackage:package asSummary:false];
7361 return cell;
7362 }
7363
7364 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7365 Package *package([self packageAtIndexPath:path]);
7366 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7367 [view setDelegate:delegate_];
7368 [[self navigationController] pushViewController:view animated:YES];
7369 return path;
7370 }
7371
7372 - (void) refreshButtonClicked {
7373 [delegate_ beginUpdate];
7374 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7375 }
7376
7377 - (void) upgradeButtonClicked {
7378 [delegate_ distUpgrade];
7379 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7380 }
7381
7382 - (void) loadView {
7383 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7384
7385 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7386 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7387 [list_ setRowHeight:73];
7388 [(UITableView *) list_ setDataSource:self];
7389 [list_ setDelegate:self];
7390 [[self view] addSubview:list_];
7391 }
7392
7393 - (void) viewDidLoad {
7394 [super viewDidLoad];
7395
7396 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7397 }
7398
7399 - (void) releaseSubviews {
7400 list_ = nil;
7401
7402 [super releaseSubviews];
7403 }
7404
7405 - (id) initWithDatabase:(Database *)database {
7406 if ((self = [super init]) != nil) {
7407 database_ = database;
7408
7409 packages_ = [NSArray array];
7410 sections_ = [NSMutableArray arrayWithCapacity:16];
7411 } return self;
7412 }
7413
7414 - (NSMutableArray *) _reloadPackages {
7415 @synchronized (database_) {
7416 era_ = [database_ era];
7417 NSArray *packages([database_ packages]);
7418
7419 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7420
7421 _trace();
7422 _profile(ChangesController$_reloadPackages$Filter)
7423 for (Package *package in packages)
7424 if ([package upgradableAndEssential:YES] || [package visible])
7425 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7426 _end
7427 _trace();
7428 _profile(ChangesController$_reloadPackages$radixSort)
7429 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7430 _end
7431 _trace();
7432
7433 return filtered;
7434 } }
7435
7436 - (void) _reloadData {
7437 NSArray *packages;
7438
7439 reload:
7440 if (true) {
7441 UIProgressHUD *hud([delegate_ addProgressHUD]);
7442 [hud setText:UCLocalize("LOADING")];
7443 //NSLog(@"HUD:%@::%@", delegate_, hud);
7444 packages = [self yieldToSelector:@selector(_reloadPackages)];
7445 [delegate_ removeProgressHUD:hud];
7446 } else {
7447 packages = [self _reloadPackages];
7448 }
7449
7450 @synchronized (database_) {
7451 if (era_ != [database_ era])
7452 goto reload;
7453
7454 packages_ = packages;
7455 [sections_ removeAllObjects];
7456
7457 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7458 Section *ignored = nil;
7459 Section *section = nil;
7460 time_t last = 0;
7461
7462 upgrades_ = 0;
7463 bool unseens = false;
7464
7465 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7466
7467 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7468 Package *package = [packages_ objectAtIndex:offset];
7469
7470 BOOL uae = [package upgradableAndEssential:YES];
7471
7472 if (!uae) {
7473 unseens = true;
7474 time_t seen([package seen]);
7475
7476 if (section == nil || last != seen) {
7477 last = seen;
7478
7479 NSString *name;
7480 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7481 [name autorelease];
7482
7483 _profile(ChangesController$reloadData$Allocate)
7484 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7485 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7486 [sections_ addObject:section];
7487 _end
7488 }
7489
7490 [section addToCount];
7491 } else if ([package ignored]) {
7492 if (ignored == nil) {
7493 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7494 }
7495 [ignored addToCount];
7496 } else {
7497 ++upgrades_;
7498 [upgradable addToCount];
7499 }
7500 }
7501 _trace();
7502
7503 CFRelease(formatter);
7504
7505 if (unseens) {
7506 Section *last = [sections_ lastObject];
7507 size_t count = [last count];
7508 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7509 [sections_ removeLastObject];
7510 }
7511
7512 if ([ignored count] != 0)
7513 [sections_ insertObject:ignored atIndex:0];
7514 if (upgrades_ != 0)
7515 [sections_ insertObject:upgradable atIndex:0];
7516
7517 [list_ reloadData];
7518
7519 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7520 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7521 style:UIBarButtonItemStylePlain
7522 target:self
7523 action:@selector(upgradeButtonClicked)
7524 ] autorelease]) animated:YES];
7525
7526 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7527 initWithTitle:UCLocalize("REFRESH")
7528 style:UIBarButtonItemStylePlain
7529 target:self
7530 action:@selector(refreshButtonClicked)
7531 ] autorelease]) animated:YES];
7532
7533 PrintTimes();
7534 } }
7535
7536 - (void) reloadData {
7537 [super reloadData];
7538 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7539 }
7540
7541 @end
7542 /* }}} */
7543 /* Search Controller {{{ */
7544 @interface SearchController : FilteredPackageListController <
7545 UISearchBarDelegate
7546 > {
7547 _H<UISearchBar, 1> search_;
7548 BOOL searchloaded_;
7549 }
7550
7551 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7552 - (void) reloadData;
7553
7554 @end
7555
7556 @implementation SearchController
7557
7558 - (NSURL *) navigationURL {
7559 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7560 return [NSURL URLWithString:@"cydia://search"];
7561 else
7562 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7563 }
7564
7565 - (void) useSearch {
7566 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7567 [self clearData];
7568 [self reloadData];
7569 }
7570
7571 - (void) viewWillAppear:(BOOL)animated {
7572 [super viewWillAppear:animated];
7573
7574 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7575 [self useSearch];
7576 }
7577
7578 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7579 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7580 [self clearData];
7581 [self reloadData];
7582 }
7583
7584 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7585 [search_ resignFirstResponder];
7586 [self useSearch];
7587 }
7588
7589 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7590 [search_ setText:@""];
7591 [self searchBarButtonClicked:searchBar];
7592 }
7593
7594 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7595 [self searchBarButtonClicked:searchBar];
7596 }
7597
7598 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7599 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7600 [self reloadData];
7601 }
7602
7603 - (bool) shouldYield {
7604 return YES;
7605 }
7606
7607 - (bool) shouldBlock {
7608 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7609 }
7610
7611 - (bool) isSummarized {
7612 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7613 }
7614
7615 - (bool) showsSections {
7616 return false;
7617 }
7618
7619 - (NSMutableArray *) _reloadPackages {
7620 NSMutableArray *packages([super _reloadPackages]);
7621 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7622 [packages radixSortUsingSelector:@selector(rank)];
7623 return packages;
7624 }
7625
7626 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7627 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7628 search_ = [[[UISearchBar alloc] init] autorelease];
7629 [search_ setDelegate:self];
7630
7631 if (query != nil)
7632 [search_ setText:query];
7633 } return self;
7634 }
7635
7636 - (void) viewDidAppear:(BOOL)animated {
7637 [super viewDidAppear:animated];
7638
7639 if (!searchloaded_) {
7640 searchloaded_ = YES;
7641 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7642 [search_ layoutSubviews];
7643 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7644
7645 UITextField *textField;
7646 if ([search_ respondsToSelector:@selector(searchField)])
7647 textField = [search_ searchField];
7648 else
7649 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7650
7651 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7652 [textField setEnablesReturnKeyAutomatically:NO];
7653 [[self navigationItem] setTitleView:textField];
7654 }
7655 }
7656
7657 - (void) reloadData {
7658 id object([search_ text]);
7659 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7660 object = [object componentsSeparatedByString:@" "];
7661
7662 [self setObject:object];
7663 [self resetCursor];
7664
7665 [super reloadData];
7666 }
7667
7668 - (void) didSelectPackage:(Package *)package {
7669 [search_ resignFirstResponder];
7670 [super didSelectPackage:package];
7671 }
7672
7673 @end
7674 /* }}} */
7675 /* Package Settings Controller {{{ */
7676 @interface PackageSettingsController : CyteViewController <
7677 UITableViewDataSource,
7678 UITableViewDelegate
7679 > {
7680 _transient Database *database_;
7681 _H<NSString> name_;
7682 _H<Package> package_;
7683 _H<UITableView, 2> table_;
7684 _H<UISwitch> subscribedSwitch_;
7685 _H<UISwitch> ignoredSwitch_;
7686 _H<UITableViewCell> subscribedCell_;
7687 _H<UITableViewCell> ignoredCell_;
7688 }
7689
7690 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7691
7692 @end
7693
7694 @implementation PackageSettingsController
7695
7696 - (NSURL *) navigationURL {
7697 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7698 }
7699
7700 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7701 if (package_ == nil)
7702 return 0;
7703
7704 if ([package_ installed] == nil)
7705 return 1;
7706 else
7707 return 2;
7708 }
7709
7710 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7711 if (package_ == nil)
7712 return 0;
7713
7714 // both sections contain just one item right now.
7715 return 1;
7716 }
7717
7718 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7719 return nil;
7720 }
7721
7722 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7723 if (section == 0)
7724 return UCLocalize("SHOW_ALL_CHANGES_EX");
7725 else
7726 return UCLocalize("IGNORE_UPGRADES_EX");
7727 }
7728
7729 - (void) onSubscribed:(id)control {
7730 bool value([control isOn]);
7731 if (package_ == nil)
7732 return;
7733 if ([package_ setSubscribed:value])
7734 [delegate_ updateData];
7735 }
7736
7737 - (void) _updateIgnored {
7738 const char *package([name_ UTF8String]);
7739 bool on([ignoredSwitch_ isOn]);
7740
7741 pid_t pid(ExecFork());
7742 if (pid == 0) {
7743 FILE *dpkg(popen("dpkg --set-selections", "w"));
7744 fwrite(package, strlen(package), 1, dpkg);
7745
7746 if (on)
7747 fwrite(" hold\n", 6, 1, dpkg);
7748 else
7749 fwrite(" install\n", 9, 1, dpkg);
7750
7751 pclose(dpkg);
7752
7753 exit(0);
7754 _assert(false);
7755 }
7756
7757 _forever {
7758 int status;
7759 int result(waitpid(pid, &status, 0));
7760
7761 if (result != -1) {
7762 _assert(result == pid);
7763 break;
7764 }
7765 }
7766 }
7767
7768 - (void) onIgnored:(id)control {
7769 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7770 [invocation setTarget:self];
7771 [invocation setSelector:@selector(_updateIgnored)];
7772
7773 [delegate_ reloadDataWithInvocation:invocation];
7774 }
7775
7776 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7777 if (package_ == nil)
7778 return nil;
7779
7780 switch ([indexPath section]) {
7781 case 0: return subscribedCell_;
7782 case 1: return ignoredCell_;
7783
7784 _nodefault
7785 }
7786
7787 return nil;
7788 }
7789
7790 - (void) loadView {
7791 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7792
7793 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7794 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7795 [(UITableView *) table_ setDataSource:self];
7796 [table_ setDelegate:self];
7797 [[self view] addSubview:table_];
7798
7799 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7800 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7801 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7802
7803 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7804 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7805 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7806
7807 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7808 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7809 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7810 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7811
7812 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7813 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7814 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7815 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7816 }
7817
7818 - (void) viewDidLoad {
7819 [super viewDidLoad];
7820
7821 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7822 }
7823
7824 - (void) releaseSubviews {
7825 ignoredCell_ = nil;
7826 subscribedCell_ = nil;
7827 table_ = nil;
7828 ignoredSwitch_ = nil;
7829 subscribedSwitch_ = nil;
7830
7831 [super releaseSubviews];
7832 }
7833
7834 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7835 if ((self = [super init]) != nil) {
7836 database_ = database;
7837 name_ = package;
7838 } return self;
7839 }
7840
7841 - (void) reloadData {
7842 [super reloadData];
7843
7844 package_ = [database_ packageWithName:name_];
7845
7846 if (package_ != nil) {
7847 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7848 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7849 } // XXX: what now, G?
7850
7851 [table_ reloadData];
7852 }
7853
7854 @end
7855 /* }}} */
7856
7857 /* Installed Controller {{{ */
7858 @interface InstalledController : FilteredPackageListController {
7859 BOOL expert_;
7860 }
7861
7862 - (id) initWithDatabase:(Database *)database;
7863
7864 - (void) updateRoleButton;
7865 - (void) queueStatusDidChange;
7866
7867 @end
7868
7869 @implementation InstalledController
7870
7871 - (NSURL *) navigationURL {
7872 return [NSURL URLWithString:@"cydia://installed"];
7873 }
7874
7875 - (id) initWithDatabase:(Database *)database {
7876 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7877 [self updateRoleButton];
7878 [self queueStatusDidChange];
7879 } return self;
7880 }
7881
7882 #if !AlwaysReload
7883 - (void) queueButtonClicked {
7884 [delegate_ queue];
7885 }
7886 #endif
7887
7888 - (void) queueStatusDidChange {
7889 #if !AlwaysReload
7890 if (IsWildcat_) {
7891 if (Queuing_) {
7892 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7893 initWithTitle:UCLocalize("QUEUE")
7894 style:UIBarButtonItemStyleDone
7895 target:self
7896 action:@selector(queueButtonClicked)
7897 ] autorelease]];
7898 } else {
7899 [[self navigationItem] setLeftBarButtonItem:nil];
7900 }
7901 }
7902 #endif
7903 }
7904
7905 - (void) updateRoleButton {
7906 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7907 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7908 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7909 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7910 target:self
7911 action:@selector(roleButtonClicked)
7912 ] autorelease]];
7913 }
7914
7915 - (void) roleButtonClicked {
7916 [self setObject:[NSNumber numberWithBool:expert_]];
7917 [self reloadData];
7918 expert_ = !expert_;
7919
7920 [self updateRoleButton];
7921 }
7922
7923 @end
7924 /* }}} */
7925
7926 /* Source Cell {{{ */
7927 @interface SourceCell : CyteTableViewCell <
7928 CyteTableViewCellDelegate
7929 > {
7930 _H<UIImage> icon_;
7931 _H<NSString> origin_;
7932 _H<NSString> label_;
7933 }
7934
7935 - (void) setSource:(Source *)source;
7936
7937 @end
7938
7939 @implementation SourceCell
7940
7941 - (void) _setImage:(UIImage *)image {
7942 icon_ = image;
7943 [content_ setNeedsDisplay];
7944 }
7945
7946 - (void) _setSource:(Source *)source {
7947 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7948
7949 if (NSString *base = [source base])
7950 if ([base length] != 0) {
7951 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7952
7953 if (NSData *data = [NSURLConnection
7954 sendSynchronousRequest:[NSURLRequest
7955 requestWithURL:url
7956 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7957 //timeoutInterval:5
7958 ]
7959
7960 returningResponse:NULL
7961 error:NULL
7962 ])
7963 if (UIImage *image = [UIImage imageWithData:data])
7964 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7965 }
7966
7967 [pool release];
7968 }
7969
7970 - (void) setSource:(Source *)source {
7971 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7972
7973 origin_ = [source name];
7974 label_ = [source uri];
7975
7976 [content_ setNeedsDisplay];
7977
7978 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7979 }
7980
7981 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7982 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7983 UIView *content([self contentView]);
7984 CGRect bounds([content bounds]);
7985
7986 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7987 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7988 [content_ setBackgroundColor:[UIColor whiteColor]];
7989 [content addSubview:content_];
7990
7991 [content_ setDelegate:self];
7992 [content_ setOpaque:YES];
7993 } return self;
7994 }
7995
7996 - (NSString *) accessibilityLabel {
7997 return label_;
7998 }
7999
8000 - (void) drawContentRect:(CGRect)rect {
8001 bool highlighted(highlighted_);
8002 float width(rect.size.width);
8003
8004 if (icon_ != nil)
8005 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8006
8007 if (highlighted)
8008 UISetColor(White_);
8009
8010 if (!highlighted)
8011 UISetColor(Black_);
8012 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8013
8014 if (!highlighted)
8015 UISetColor(Blue_);
8016 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8017 }
8018
8019 @end
8020 /* }}} */
8021 /* Source Controller {{{ */
8022 @interface SourceController : FilteredPackageListController {
8023 _transient Source *source_;
8024 _H<NSString> key_;
8025 }
8026
8027 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8028
8029 @end
8030
8031 @implementation SourceController
8032
8033 - (NSURL *) navigationURL {
8034 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8035 }
8036
8037 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8038 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8039 source_ = source;
8040 key_ = [source key];
8041 } return self;
8042 }
8043
8044 - (void) reloadData {
8045 source_ = [database_ sourceWithKey:key_];
8046 key_ = [source_ key];
8047 [self setObject:source_];
8048
8049 [[self navigationItem] setTitle:[source_ label]];
8050
8051 [super reloadData];
8052 }
8053
8054 @end
8055 /* }}} */
8056 /* Sources Controller {{{ */
8057 @interface SourcesController : CyteViewController <
8058 UITableViewDataSource,
8059 UITableViewDelegate
8060 > {
8061 _transient Database *database_;
8062 _H<UITableView, 2> list_;
8063 _H<NSMutableArray> sources_;
8064 int offset_;
8065
8066 _H<NSString> href_;
8067 _H<UIProgressHUD> hud_;
8068 _H<NSError> error_;
8069
8070 //NSURLConnection *installer_;
8071 NSURLConnection *trivial_;
8072 NSURLConnection *trivial_bz2_;
8073 NSURLConnection *trivial_gz_;
8074 //NSURLConnection *automatic_;
8075
8076 BOOL cydia_;
8077 }
8078
8079 - (id) initWithDatabase:(Database *)database;
8080 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8081
8082 @end
8083
8084 @implementation SourcesController
8085
8086 - (void) _releaseConnection:(NSURLConnection *)connection {
8087 if (connection != nil) {
8088 [connection cancel];
8089 //[connection setDelegate:nil];
8090 [connection release];
8091 }
8092 }
8093
8094 - (void) dealloc {
8095 //[self _releaseConnection:installer_];
8096 [self _releaseConnection:trivial_];
8097 [self _releaseConnection:trivial_gz_];
8098 [self _releaseConnection:trivial_bz2_];
8099 //[self _releaseConnection:automatic_];
8100
8101 [super dealloc];
8102 }
8103
8104 - (NSURL *) navigationURL {
8105 return [NSURL URLWithString:@"cydia://sources"];
8106 }
8107
8108 - (void) viewDidAppear:(BOOL)animated {
8109 [super viewDidAppear:animated];
8110 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8111 }
8112
8113 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8114 return offset_ == 0 ? 1 : 2;
8115 }
8116
8117 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8118 switch (section + (offset_ == 0 ? 1 : 0)) {
8119 case 0: return UCLocalize("ENTERED_BY_USER");
8120 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8121
8122 _nodefault
8123 }
8124 }
8125
8126 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8127 int count = [sources_ count];
8128 switch (section) {
8129 case 0: return (offset_ == 0 ? count : offset_);
8130 case 1: return count - offset_;
8131
8132 _nodefault
8133 }
8134 }
8135
8136 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8137 unsigned idx = 0;
8138 switch (indexPath.section) {
8139 case 0: idx = indexPath.row; break;
8140 case 1: idx = indexPath.row + offset_; break;
8141
8142 _nodefault
8143 }
8144 return [sources_ objectAtIndex:idx];
8145 }
8146
8147 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8148 static NSString *cellIdentifier = @"SourceCell";
8149
8150 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8151 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8152 [cell setSource:[self sourceAtIndexPath:indexPath]];
8153 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8154
8155 return cell;
8156 }
8157
8158 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8159 Source *source = [self sourceAtIndexPath:indexPath];
8160
8161 SourceController *controller = [[[SourceController alloc]
8162 initWithDatabase:database_
8163 source:source
8164 ] autorelease];
8165
8166 [controller setDelegate:delegate_];
8167
8168 [[self navigationController] pushViewController:controller animated:YES];
8169 }
8170
8171 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8172 Source *source = [self sourceAtIndexPath:indexPath];
8173 return [source record] != nil;
8174 }
8175
8176 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8177 if (editingStyle == UITableViewCellEditingStyleDelete) {
8178 Source *source = [self sourceAtIndexPath:indexPath];
8179 [Sources_ removeObjectForKey:[source key]];
8180 [delegate_ syncData];
8181 }
8182 }
8183
8184 - (void) complete {
8185 [delegate_ addTrivialSource:href_];
8186 [delegate_ syncData];
8187 }
8188
8189 - (NSString *) getWarning {
8190 NSString *href(href_);
8191 NSRange colon([href rangeOfString:@"://"]);
8192 if (colon.location != NSNotFound)
8193 href = [href substringFromIndex:(colon.location + 3)];
8194 href = [href stringByAddingPercentEscapes];
8195 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8196 href = [href stringByCachingURLWithCurrentCDN];
8197
8198 NSURL *url([NSURL URLWithString:href]);
8199
8200 NSStringEncoding encoding;
8201 NSError *error(nil);
8202
8203 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8204 return [warning length] == 0 ? nil : warning;
8205 return nil;
8206 }
8207
8208 - (void) _endConnection:(NSURLConnection *)connection {
8209 // XXX: the memory management in this method is horribly awkward
8210
8211 NSURLConnection **field = NULL;
8212 if (connection == trivial_)
8213 field = &trivial_;
8214 else if (connection == trivial_bz2_)
8215 field = &trivial_bz2_;
8216 else if (connection == trivial_gz_)
8217 field = &trivial_gz_;
8218 _assert(field != NULL);
8219 [connection release];
8220 *field = nil;
8221
8222 if (
8223 trivial_ == nil &&
8224 trivial_bz2_ == nil &&
8225 trivial_gz_ == nil
8226 ) {
8227 [delegate_ releaseNetworkActivityIndicator];
8228
8229 [delegate_ removeProgressHUD:hud_];
8230 hud_ = nil;
8231
8232 bool defer(false);
8233
8234 if (cydia_) {
8235 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8236 defer = true;
8237
8238 UIAlertView *alert = [[[UIAlertView alloc]
8239 initWithTitle:UCLocalize("SOURCE_WARNING")
8240 message:warning
8241 delegate:self
8242 cancelButtonTitle:UCLocalize("CANCEL")
8243 otherButtonTitles:
8244 UCLocalize("ADD_ANYWAY"),
8245 nil
8246 ] autorelease];
8247
8248 [alert setContext:@"warning"];
8249 [alert setNumberOfRows:1];
8250 [alert show];
8251 } else
8252 [self complete];
8253 } else if (error_ != nil) {
8254 UIAlertView *alert = [[[UIAlertView alloc]
8255 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8256 message:[error_ localizedDescription]
8257 delegate:self
8258 cancelButtonTitle:UCLocalize("OK")
8259 otherButtonTitles:nil
8260 ] autorelease];
8261
8262 [alert setContext:@"urlerror"];
8263 [alert show];
8264 } else {
8265 UIAlertView *alert = [[[UIAlertView alloc]
8266 initWithTitle:UCLocalize("NOT_REPOSITORY")
8267 message:UCLocalize("NOT_REPOSITORY_EX")
8268 delegate:self
8269 cancelButtonTitle:UCLocalize("OK")
8270 otherButtonTitles:nil
8271 ] autorelease];
8272
8273 [alert setContext:@"trivial"];
8274 [alert show];
8275 }
8276
8277 href_ = nil;
8278 error_ = nil;
8279 }
8280 }
8281
8282 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8283 switch ([response statusCode]) {
8284 case 200:
8285 cydia_ = YES;
8286 }
8287 }
8288
8289 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8290 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8291 error_ = error;
8292 [self _endConnection:connection];
8293 }
8294
8295 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8296 [self _endConnection:connection];
8297 }
8298
8299 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8300 NSURL *url([NSURL URLWithString:href]);
8301
8302 NSMutableURLRequest *request = [NSMutableURLRequest
8303 requestWithURL:url
8304 cachePolicy:NSURLRequestUseProtocolCachePolicy
8305 timeoutInterval:120.0
8306 ];
8307
8308 [request setHTTPMethod:method];
8309
8310 if (Machine_ != NULL)
8311 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8312
8313 if ([url isCydiaSecure]) {
8314 if (UniqueID_ != nil)
8315 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8316 }
8317
8318 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8319 }
8320
8321 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8322 NSString *context([alert context]);
8323
8324 if ([context isEqualToString:@"source"]) {
8325 switch (button) {
8326 case 1: {
8327 NSString *href = [[alert textField] text];
8328
8329 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8330
8331 if (![href hasSuffix:@"/"])
8332 href_ = [href stringByAppendingString:@"/"];
8333 else
8334 href_ = href;
8335
8336 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8337 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8338 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8339 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8340
8341 cydia_ = false;
8342
8343 // XXX: this is stupid
8344 hud_ = [delegate_ addProgressHUD];
8345 [hud_ setText:UCLocalize("VERIFYING_URL")];
8346 [delegate_ retainNetworkActivityIndicator];
8347 } break;
8348
8349 case 0:
8350 break;
8351
8352 _nodefault
8353 }
8354
8355 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8356 } else if ([context isEqualToString:@"trivial"])
8357 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8358 else if ([context isEqualToString:@"urlerror"])
8359 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8360 else if ([context isEqualToString:@"warning"]) {
8361 switch (button) {
8362 case 1:
8363 [self complete];
8364 break;
8365
8366 case 0:
8367 break;
8368
8369 _nodefault
8370 }
8371
8372 href_ = nil;
8373
8374 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8375 }
8376 }
8377
8378 - (void) loadView {
8379 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8380
8381 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8382 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8383 [list_ setRowHeight:56];
8384 [(UITableView *) list_ setDataSource:self];
8385 [list_ setDelegate:self];
8386 [[self view] addSubview:list_];
8387 }
8388
8389 - (void) viewDidLoad {
8390 [super viewDidLoad];
8391
8392 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8393 [self updateButtonsForEditingStatus:NO animated:NO];
8394 }
8395
8396 - (void) releaseSubviews {
8397 list_ = nil;
8398
8399 [super releaseSubviews];
8400 }
8401
8402 - (id) initWithDatabase:(Database *)database {
8403 if ((self = [super init]) != nil) {
8404 database_ = database;
8405 sources_ = [NSMutableArray arrayWithCapacity:16];
8406 } return self;
8407 }
8408
8409 - (void) reloadData {
8410 [super reloadData];
8411
8412 pkgSourceList list;
8413 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8414 return;
8415
8416 [sources_ removeAllObjects];
8417 [sources_ addObjectsFromArray:[database_ sources]];
8418 _trace();
8419 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8420 _trace();
8421
8422 int count([sources_ count]);
8423 offset_ = 0;
8424 for (int i = 0; i != count; i++) {
8425 if ([[sources_ objectAtIndex:i] record] == nil)
8426 break;
8427 offset_++;
8428 }
8429
8430 [list_ setEditing:NO];
8431 [self updateButtonsForEditingStatus:NO animated:NO];
8432 [list_ reloadData];
8433 }
8434
8435 - (void) showAddSourcePrompt {
8436 UIAlertView *alert = [[[UIAlertView alloc]
8437 initWithTitle:UCLocalize("ENTER_APT_URL")
8438 message:nil
8439 delegate:self
8440 cancelButtonTitle:UCLocalize("CANCEL")
8441 otherButtonTitles:
8442 UCLocalize("ADD_SOURCE"),
8443 nil
8444 ] autorelease];
8445
8446 [alert setContext:@"source"];
8447
8448 [alert setNumberOfRows:1];
8449 [alert addTextFieldWithValue:@"http://" label:@""];
8450
8451 UITextInputTraits *traits = [[alert textField] textInputTraits];
8452 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8453 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8454 [traits setKeyboardType:UIKeyboardTypeURL];
8455 // XXX: UIReturnKeyDone
8456 [traits setReturnKeyType:UIReturnKeyNext];
8457
8458 [alert show];
8459 }
8460
8461 - (void) addButtonClicked {
8462 [self showAddSourcePrompt];
8463 }
8464
8465 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8466 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8467 initWithTitle:UCLocalize("ADD")
8468 style:UIBarButtonItemStylePlain
8469 target:self
8470 action:@selector(addButtonClicked)
8471 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8472
8473 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8474 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8475 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8476 target:self
8477 action:@selector(editButtonClicked)
8478 ] autorelease] animated:animated];
8479
8480 if (IsWildcat_ && !editing)
8481 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8482 initWithTitle:UCLocalize("SETTINGS")
8483 style:UIBarButtonItemStylePlain
8484 target:self
8485 action:@selector(settingsButtonClicked)
8486 ] autorelease]];
8487 }
8488
8489 - (void) settingsButtonClicked {
8490 [delegate_ showSettings];
8491 }
8492
8493 - (void) editButtonClicked {
8494 [list_ setEditing:![list_ isEditing] animated:YES];
8495
8496 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8497 }
8498
8499 @end
8500 /* }}} */
8501
8502 /* Settings Controller {{{ */
8503 @interface SettingsController : CyteViewController <
8504 UITableViewDataSource,
8505 UITableViewDelegate
8506 > {
8507 _transient Database *database_;
8508 // XXX: ok, "roledelegate_"?...
8509 _transient id roledelegate_;
8510 _H<UITableView, 2> table_;
8511 _H<UISegmentedControl> segment_;
8512 _H<UIView> container_;
8513 }
8514
8515 - (void) showDoneButton;
8516 - (void) resizeSegmentedControl;
8517
8518 @end
8519
8520 @implementation SettingsController
8521
8522 - (void) loadView {
8523 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8524
8525 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8526 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8527 [table_ setDelegate:self];
8528 [(UITableView *) table_ setDataSource:self];
8529 [[self view] addSubview:table_];
8530
8531 NSArray *items = [NSArray arrayWithObjects:
8532 UCLocalize("USER"),
8533 UCLocalize("HACKER"),
8534 UCLocalize("DEVELOPER"),
8535 nil];
8536 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8537 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8538 [container_ addSubview:segment_];
8539 }
8540
8541 - (void) viewDidLoad {
8542 [super viewDidLoad];
8543
8544 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8545
8546 int index = -1;
8547 if ([Role_ isEqualToString:@"User"]) index = 0;
8548 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8549 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8550 if (index != -1) {
8551 [segment_ setSelectedSegmentIndex:index];
8552 [self showDoneButton];
8553 }
8554
8555 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8556 [self resizeSegmentedControl];
8557 }
8558
8559 - (void) releaseSubviews {
8560 table_ = nil;
8561 segment_ = nil;
8562 container_ = nil;
8563
8564 [super releaseSubviews];
8565 }
8566
8567 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8568 if ((self = [super init]) != nil) {
8569 database_ = database;
8570 roledelegate_ = delegate;
8571 } return self;
8572 }
8573
8574 - (void) resizeSegmentedControl {
8575 CGFloat width = [[self view] frame].size.width;
8576 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8577 }
8578
8579 - (void) viewWillAppear:(BOOL)animated {
8580 [super viewWillAppear:animated];
8581
8582 [self resizeSegmentedControl];
8583 }
8584
8585 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8586 [self resizeSegmentedControl];
8587 }
8588
8589 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8590 [self resizeSegmentedControl];
8591 }
8592
8593 - (void) save {
8594 NSString *role(nil);
8595
8596 switch ([segment_ selectedSegmentIndex]) {
8597 case 0: role = @"User"; break;
8598 case 1: role = @"Hacker"; break;
8599 case 2: role = @"Developer"; break;
8600
8601 _nodefault
8602 }
8603
8604 if (![role isEqualToString:Role_]) {
8605 bool rolling(Role_ == nil);
8606 Role_ = role;
8607
8608 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8609 Role_, @"Role",
8610 nil];
8611
8612 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8613 Changed_ = true;
8614
8615 if (rolling)
8616 [roledelegate_ loadData];
8617 else
8618 [roledelegate_ updateData];
8619 }
8620 }
8621
8622 - (void) segmentChanged:(UISegmentedControl *)control {
8623 [self showDoneButton];
8624 }
8625
8626 - (void) saveAndClose {
8627 [self save];
8628
8629 [[self navigationItem] setRightBarButtonItem:nil];
8630 [[self navigationController] dismissModalViewControllerAnimated:YES];
8631 }
8632
8633 - (void) doneButtonClicked {
8634 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8635 [spinner startAnimating];
8636 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8637 [[self navigationItem] setRightBarButtonItem:spinItem];
8638
8639 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8640 }
8641
8642 - (void) showDoneButton {
8643 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8644 initWithTitle:UCLocalize("DONE")
8645 style:UIBarButtonItemStyleDone
8646 target:self
8647 action:@selector(doneButtonClicked)
8648 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8649 }
8650
8651 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8652 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8653 return 6;
8654 }
8655
8656 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8657 return 0; // :(
8658 }
8659
8660 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8661 return nil; // This method is required by the protocol.
8662 }
8663
8664 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8665 if (section == 1)
8666 return UCLocalize("ROLE_EX");
8667 if (section == 4)
8668 return [NSString stringWithFormat:
8669 @"%@: %@\n%@: %@\n%@: %@",
8670 UCLocalize("USER"), UCLocalize("USER_EX"),
8671 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8672 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8673 ];
8674 else return nil;
8675 }
8676
8677 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8678 return section == 3 ? 44.0f : 0;
8679 }
8680
8681 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8682 return section == 3 ? container_ : nil;
8683 }
8684
8685 - (void) reloadData {
8686 [super reloadData];
8687
8688 [table_ reloadData];
8689 }
8690
8691 @end
8692 /* }}} */
8693 /* Stash Controller {{{ */
8694 @interface StashController : CyteViewController {
8695 _H<UIActivityIndicatorView> spinner_;
8696 _H<UILabel> status_;
8697 _H<UILabel> caption_;
8698 }
8699
8700 @end
8701
8702 @implementation StashController
8703
8704 - (void) loadView {
8705 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8706 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8707
8708 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8709 CGRect spinrect = [spinner_ frame];
8710 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8711 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8712 [spinner_ setFrame:spinrect];
8713 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8714 [[self view] addSubview:spinner_];
8715 [spinner_ startAnimating];
8716
8717 CGRect captrect;
8718 captrect.size.width = [[self view] frame].size.width;
8719 captrect.size.height = 40.0f;
8720 captrect.origin.x = 0;
8721 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8722 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8723 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8724 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8725 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8726 [caption_ setTextColor:[UIColor whiteColor]];
8727 [caption_ setBackgroundColor:[UIColor clearColor]];
8728 [caption_ setShadowColor:[UIColor blackColor]];
8729 [caption_ setTextAlignment:UITextAlignmentCenter];
8730 [[self view] addSubview:caption_];
8731
8732 CGRect statusrect;
8733 statusrect.size.width = [[self view] frame].size.width;
8734 statusrect.size.height = 30.0f;
8735 statusrect.origin.x = 0;
8736 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8737 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8738 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8739 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8740 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8741 [status_ setTextColor:[UIColor whiteColor]];
8742 [status_ setBackgroundColor:[UIColor clearColor]];
8743 [status_ setShadowColor:[UIColor blackColor]];
8744 [status_ setTextAlignment:UITextAlignmentCenter];
8745 [[self view] addSubview:status_];
8746 }
8747
8748 - (void) releaseSubviews {
8749 spinner_ = nil;
8750 status_ = nil;
8751 caption_ = nil;
8752
8753 [super releaseSubviews];
8754 }
8755
8756 @end
8757 /* }}} */
8758
8759 @interface CYURLCache : SDURLCache {
8760 }
8761
8762 @end
8763
8764 @implementation CYURLCache
8765
8766 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8767 #if !ForRelease
8768 if (false);
8769 else if ([event isEqualToString:@"no-cache"])
8770 event = @"!!!";
8771 else if ([event isEqualToString:@"store"])
8772 event = @">>>";
8773 else if ([event isEqualToString:@"invalid"])
8774 event = @"???";
8775 else if ([event isEqualToString:@"memory"])
8776 event = @"mem";
8777 else if ([event isEqualToString:@"disk"])
8778 event = @"ssd";
8779 else if ([event isEqualToString:@"miss"])
8780 event = @"---";
8781
8782 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8783 #endif
8784 }
8785
8786 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8787 if (NSURLResponse *response = [cached response])
8788 if (NSString *mime = [response MIMEType])
8789 if ([mime isEqualToString:@"text/cache-manifest"]) {
8790 NSURL *url([response URL]);
8791
8792 #if !ForRelease
8793 NSLog(@"###: %@", [url absoluteString]);
8794 #endif
8795
8796 @synchronized (HostConfig_) {
8797 [CachedURLs_ addObject:url];
8798 }
8799 }
8800
8801 [super storeCachedResponse:cached forRequest:request];
8802 }
8803
8804 @end
8805
8806 @interface Cydia : UIApplication <
8807 ConfirmationControllerDelegate,
8808 DatabaseDelegate,
8809 CydiaDelegate,
8810 UINavigationControllerDelegate,
8811 UITabBarControllerDelegate
8812 > {
8813 _H<UIWindow> window_;
8814 _H<CYTabBarController> tabbar_;
8815 _H<CydiaLoadingViewController> emulated_;
8816
8817 _H<NSMutableArray> essential_;
8818 _H<NSMutableArray> broken_;
8819
8820 Database *database_;
8821
8822 _H<NSURL> starturl_;
8823
8824 unsigned locked_;
8825 unsigned activity_;
8826
8827 _H<StashController> stash_;
8828
8829 bool loaded_;
8830 }
8831
8832 - (void) loadData;
8833
8834 @end
8835
8836 @implementation Cydia
8837
8838 - (void) beginUpdate {
8839 [tabbar_ beginUpdate];
8840 }
8841
8842 - (BOOL) updating {
8843 return [tabbar_ updating];
8844 }
8845
8846 - (void) _loaded {
8847 if ([broken_ count] != 0) {
8848 int count = [broken_ count];
8849
8850 UIAlertView *alert = [[[UIAlertView alloc]
8851 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8852 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8853 delegate:self
8854 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8855 otherButtonTitles:
8856 UCLocalize("TEMPORARY_IGNORE"),
8857 nil
8858 ] autorelease];
8859
8860 [alert setContext:@"fixhalf"];
8861 [alert setNumberOfRows:2];
8862 [alert show];
8863 } else if (!Ignored_ && [essential_ count] != 0) {
8864 int count = [essential_ count];
8865
8866 UIAlertView *alert = [[[UIAlertView alloc]
8867 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8868 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8869 delegate:self
8870 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8871 otherButtonTitles:
8872 UCLocalize("UPGRADE_ESSENTIAL"),
8873 UCLocalize("COMPLETE_UPGRADE"),
8874 nil
8875 ] autorelease];
8876
8877 [alert setContext:@"upgrade"];
8878 [alert show];
8879 }
8880 }
8881
8882 - (void) _saveConfig {
8883 _trace();
8884 MetaFile_.Sync();
8885 _trace();
8886
8887 if (Changed_) {
8888 NSString *error(nil);
8889
8890 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8891 _trace();
8892 NSError *error(nil);
8893 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8894 NSLog(@"failure to save metadata data: %@", error);
8895 _trace();
8896
8897 Changed_ = false;
8898 } else {
8899 NSLog(@"failure to serialize metadata: %@", error);
8900 }
8901 }
8902
8903 WriteSources();
8904 }
8905
8906 // Navigation controller for the queuing badge.
8907 - (UINavigationController *) queueNavigationController {
8908 NSArray *controllers = [tabbar_ viewControllers];
8909 return [controllers objectAtIndex:3];
8910 }
8911
8912 - (void) unloadData {
8913 [tabbar_ unloadData];
8914 }
8915
8916 - (void) _updateData {
8917 [self _saveConfig];
8918 [self unloadData];
8919
8920 UINavigationController *navigation = [self queueNavigationController];
8921
8922 id queuedelegate = nil;
8923 if ([[navigation viewControllers] count] > 0)
8924 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8925
8926 [queuedelegate queueStatusDidChange];
8927 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8928 }
8929
8930 - (void) _refreshIfPossible:(NSDate *)update {
8931 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8932
8933 bool recently = false;
8934 if (update != nil) {
8935 NSTimeInterval interval([update timeIntervalSinceNow]);
8936 if (interval <= 0 && interval > -(15*60))
8937 recently = true;
8938 }
8939
8940 // Don't automatic refresh if:
8941 // - We already refreshed recently.
8942 // - We already auto-refreshed this launch.
8943 // - Auto-refresh is disabled.
8944 if (recently || loaded_ || ManualRefresh) {
8945 // If we are cancelling, we need to make sure it knows it's already loaded.
8946 loaded_ = true;
8947
8948 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8949 } else {
8950 // We are going to load, so remember that.
8951 loaded_ = true;
8952
8953 SCNetworkReachabilityFlags flags; {
8954 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8955 SCNetworkReachabilityGetFlags(reachability, &flags);
8956 CFRelease(reachability);
8957 }
8958
8959 // XXX: this elaborate mess is what Apple is using to determine this? :(
8960 // XXX: do we care if the user has to intervene? maybe that's ok?
8961 bool reachable(
8962 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8963 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8964 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8965 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8966 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8967 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8968 )
8969 );
8970
8971 // If we can reach the server, auto-refresh!
8972 if (reachable)
8973 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8974 }
8975
8976 [pool release];
8977 }
8978
8979 - (void) refreshIfPossible {
8980 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8981 }
8982
8983 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8984 @synchronized (self) {
8985 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8986 [hud setText:UCLocalize("RELOADING_DATA")];
8987
8988 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8989
8990 if (hud != nil)
8991 [self removeProgressHUD:hud];
8992
8993 size_t changes(0);
8994
8995 [essential_ removeAllObjects];
8996 [broken_ removeAllObjects];
8997
8998 NSArray *packages([database_ packages]);
8999 for (Package *package in packages) {
9000 if ([package half])
9001 [broken_ addObject:package];
9002 if ([package upgradableAndEssential:NO]) {
9003 if ([package essential])
9004 [essential_ addObject:package];
9005 ++changes;
9006 }
9007 }
9008
9009 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9010 if (changes != 0) {
9011 _trace();
9012 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9013 [changesItem setBadgeValue:badge];
9014 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9015 [self setApplicationIconBadgeNumber:changes];
9016 } else {
9017 _trace();
9018 [changesItem setBadgeValue:nil];
9019 [changesItem setAnimatedBadge:NO];
9020 [self setApplicationIconBadgeNumber:0];
9021 }
9022
9023 [self _updateData];
9024
9025 [self refreshIfPossible];
9026 } }
9027
9028 - (void) updateData {
9029 [self _updateData];
9030 }
9031
9032 - (void) update_ {
9033 [database_ update];
9034 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9035 }
9036
9037 - (void) disemulate {
9038 if (emulated_ == nil)
9039 return;
9040
9041 [window_ addSubview:[tabbar_ view]];
9042 [[emulated_ view] removeFromSuperview];
9043 emulated_ = nil;
9044 [window_ setUserInteractionEnabled:YES];
9045 }
9046
9047 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9048 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9049 if (IsWildcat_)
9050 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9051
9052 UIViewController *parent;
9053 if (emulated_ == nil)
9054 parent = tabbar_;
9055 else if (!force)
9056 parent = emulated_;
9057 else {
9058 [self disemulate];
9059 parent = tabbar_;
9060 }
9061
9062 [parent presentModalViewController:navigation animated:YES];
9063 }
9064
9065 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9066 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9067
9068 if (navigation != nil)
9069 [navigation pushViewController:progress animated:YES];
9070 else
9071 [self presentModalViewController:progress force:YES];
9072
9073 [progress invoke:invocation withTitle:title];
9074 return progress;
9075 }
9076
9077 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9078 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9079 }
9080
9081 - (void) repairWithInvocation:(NSInvocation *)invocation {
9082 _trace();
9083 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9084 _trace();
9085 }
9086
9087 - (void) repairWithSelector:(SEL)selector {
9088 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9089 }
9090
9091 - (void) reloadData {
9092 [self reloadDataWithInvocation:nil];
9093 }
9094
9095 - (void) syncData {
9096 [self _saveConfig];
9097 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9098 }
9099
9100 - (void) addSource:(NSDictionary *) source {
9101 AddSource(source);
9102 }
9103
9104 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9105 AddSource(href, distribution, sections);
9106 }
9107
9108 - (void) addTrivialSource:(NSString *)href {
9109 AddSource(href, @"./");
9110 }
9111
9112 - (void) updateValues {
9113 Changed_ = true;
9114 }
9115
9116 - (void) resolve {
9117 pkgProblemResolver *resolver = [database_ resolver];
9118
9119 resolver->InstallProtect();
9120 if (!resolver->Resolve(true))
9121 _error->Discard();
9122 }
9123
9124 - (bool) perform {
9125 // XXX: this is a really crappy way of doing this.
9126 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9127 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9128 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9129 if ([tabbar_ updating])
9130 [tabbar_ cancelUpdate];
9131
9132 if (![database_ prepare])
9133 return false;
9134
9135 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9136 [page setDelegate:self];
9137 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9138
9139 if (IsWildcat_)
9140 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9141 [tabbar_ presentModalViewController:confirm_ animated:YES];
9142
9143 return true;
9144 }
9145
9146 - (void) queue {
9147 @synchronized (self) {
9148 [self perform];
9149 }
9150 }
9151
9152 - (void) clearPackage:(Package *)package {
9153 @synchronized (self) {
9154 [package clear];
9155 [self resolve];
9156 [self perform];
9157 }
9158 }
9159
9160 - (void) installPackages:(NSArray *)packages {
9161 @synchronized (self) {
9162 for (Package *package in packages)
9163 [package install];
9164 [self resolve];
9165 [self perform];
9166 }
9167 }
9168
9169 - (void) installPackage:(Package *)package {
9170 @synchronized (self) {
9171 [package install];
9172 [self resolve];
9173 [self perform];
9174 }
9175 }
9176
9177 - (void) removePackage:(Package *)package {
9178 @synchronized (self) {
9179 [package remove];
9180 [self resolve];
9181 [self perform];
9182 }
9183 }
9184
9185 - (void) distUpgrade {
9186 @synchronized (self) {
9187 if (![database_ upgrade])
9188 return;
9189 [self perform];
9190 }
9191 }
9192
9193 - (void) perform_ {
9194 [database_ perform];
9195 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9196 }
9197
9198 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9199 Queuing_ = false;
9200 ++locked_;
9201 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9202 --locked_;
9203 }
9204
9205 - (void) showSettings {
9206 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9207 }
9208
9209 - (void) retainNetworkActivityIndicator {
9210 if (activity_++ == 0)
9211 [self setNetworkActivityIndicatorVisible:YES];
9212
9213 #if TraceLogging
9214 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9215 #endif
9216 }
9217
9218 - (void) releaseNetworkActivityIndicator {
9219 if (--activity_ == 0)
9220 [self setNetworkActivityIndicatorVisible:NO];
9221
9222 #if TraceLogging
9223 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9224 #endif
9225
9226 }
9227
9228 - (void) cancelAndClear:(bool)clear {
9229 @synchronized (self) {
9230 if (clear) {
9231 [database_ clear];
9232 Queuing_ = false;
9233 } else {
9234 Queuing_ = true;
9235 }
9236
9237 [self _updateData];
9238 }
9239 }
9240
9241 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9242 NSString *context([alert context]);
9243
9244 if ([context isEqualToString:@"conffile"]) {
9245 FILE *input = [database_ input];
9246 if (button == [alert cancelButtonIndex])
9247 fprintf(input, "N\n");
9248 else if (button == [alert firstOtherButtonIndex])
9249 fprintf(input, "Y\n");
9250 fflush(input);
9251
9252 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9253 } else if ([context isEqualToString:@"fixhalf"]) {
9254 if (button == [alert cancelButtonIndex]) {
9255 @synchronized (self) {
9256 for (Package *broken in (id) broken_) {
9257 [broken remove];
9258
9259 NSString *id = [broken id];
9260 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9261 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9262 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9263 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9264 }
9265
9266 [self resolve];
9267 [self perform];
9268 }
9269 } else if (button == [alert firstOtherButtonIndex]) {
9270 [broken_ removeAllObjects];
9271 [self _loaded];
9272 }
9273
9274 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9275 } else if ([context isEqualToString:@"upgrade"]) {
9276 if (button == [alert firstOtherButtonIndex]) {
9277 @synchronized (self) {
9278 for (Package *essential in (id) essential_)
9279 [essential install];
9280
9281 [self resolve];
9282 [self perform];
9283 }
9284 } else if (button == [alert firstOtherButtonIndex] + 1) {
9285 [self distUpgrade];
9286 } else if (button == [alert cancelButtonIndex]) {
9287 Ignored_ = YES;
9288 }
9289
9290 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9291 }
9292 }
9293
9294 - (void) system:(NSString *)command {
9295 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9296
9297 _trace();
9298 system([command UTF8String]);
9299 _trace();
9300
9301 [pool release];
9302 }
9303
9304 - (void) applicationWillSuspend {
9305 [database_ clean];
9306 [super applicationWillSuspend];
9307 }
9308
9309 - (BOOL) isSafeToSuspend {
9310 if (locked_ != 0) {
9311 #if !ForRelease
9312 NSLog(@"isSafeToSuspend: locked_ != 0");
9313 #endif
9314 return false;
9315 }
9316
9317 // Use external process status API internally.
9318 // This is probably a really bad idea.
9319 // XXX: what is the point of this? does this solve anything at all?
9320 uint64_t status = 0;
9321 int notify_token;
9322 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9323 notify_get_state(notify_token, &status);
9324 notify_cancel(notify_token);
9325 }
9326
9327 if (status != 0) {
9328 #if !ForRelease
9329 NSLog(@"isSafeToSuspend: status != 0");
9330 #endif
9331 return false;
9332 }
9333
9334 #if !ForRelease
9335 NSLog(@"isSafeToSuspend: -> true");
9336 #endif
9337 return true;
9338 }
9339
9340 - (void) applicationSuspend:(__GSEvent *)event {
9341 if ([self isSafeToSuspend])
9342 [super applicationSuspend:event];
9343 }
9344
9345 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9346 if ([self isSafeToSuspend])
9347 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9348 }
9349
9350 - (void) _setSuspended:(BOOL)value {
9351 if ([self isSafeToSuspend])
9352 [super _setSuspended:value];
9353 }
9354
9355 - (UIProgressHUD *) addProgressHUD {
9356 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9357 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9358
9359 [window_ setUserInteractionEnabled:NO];
9360
9361 UIViewController *target(tabbar_);
9362 if (UIViewController *modal = [target modalViewController])
9363 target = modal;
9364
9365 UIView *view([target view]);
9366 [view addSubview:hud];
9367
9368 [hud show:YES];
9369
9370 ++locked_;
9371 return hud;
9372 }
9373
9374 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9375 --locked_;
9376 [hud show:NO];
9377 [hud removeFromSuperview];
9378 [window_ setUserInteractionEnabled:YES];
9379 }
9380
9381 - (CyteViewController *) pageForPackage:(NSString *)name {
9382 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9383 }
9384
9385 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9386 NSString *scheme([[url scheme] lowercaseString]);
9387 if ([[url absoluteString] length] <= [scheme length] + 3)
9388 return nil;
9389 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9390 NSArray *components([path pathComponents]);
9391
9392 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9393 return [self pageForPackage:[components objectAtIndex:1]];
9394
9395 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9396 return nil;
9397
9398 NSString *base([components objectAtIndex:0]);
9399
9400 CyteViewController *controller = nil;
9401
9402 if ([base isEqualToString:@"url"]) {
9403 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9404 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9405 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9406 } else if (!external && [components count] == 1) {
9407 if ([base isEqualToString:@"manage"]) {
9408 controller = [[[ManageController alloc] init] autorelease];
9409 }
9410
9411 if ([base isEqualToString:@"sources"]) {
9412 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9413 }
9414
9415 if ([base isEqualToString:@"home"]) {
9416 controller = [[[HomeController alloc] init] autorelease];
9417 }
9418
9419 if ([base isEqualToString:@"sections"]) {
9420 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9421 }
9422
9423 if ([base isEqualToString:@"search"]) {
9424 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9425 }
9426
9427 if ([base isEqualToString:@"changes"]) {
9428 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9429 }
9430
9431 if ([base isEqualToString:@"installed"]) {
9432 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9433 }
9434 } else if ([components count] == 2) {
9435 NSString *argument = [components objectAtIndex:1];
9436
9437 if ([base isEqualToString:@"package"]) {
9438 controller = [self pageForPackage:argument];
9439 }
9440
9441 if (!external && [base isEqualToString:@"search"]) {
9442 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9443 }
9444
9445 if (!external && [base isEqualToString:@"sections"]) {
9446 if ([argument isEqualToString:@"all"])
9447 argument = nil;
9448 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9449 }
9450
9451 if (!external && [base isEqualToString:@"sources"]) {
9452 if ([argument isEqualToString:@"add"]) {
9453 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9454 [(SourcesController *)controller showAddSourcePrompt];
9455 } else {
9456 Source *source = [database_ sourceWithKey:argument];
9457 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9458 }
9459 }
9460
9461 if (!external && [base isEqualToString:@"launch"]) {
9462 [self launchApplicationWithIdentifier:argument suspended:NO];
9463 return nil;
9464 }
9465 } else if (!external && [components count] == 3) {
9466 NSString *arg1 = [components objectAtIndex:1];
9467 NSString *arg2 = [components objectAtIndex:2];
9468
9469 if ([base isEqualToString:@"package"]) {
9470 if ([arg2 isEqualToString:@"settings"]) {
9471 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9472 } else if ([arg2 isEqualToString:@"files"]) {
9473 if (Package *package = [database_ packageWithName:arg1]) {
9474 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9475 [(FileTable *)controller setPackage:package];
9476 }
9477 }
9478 }
9479 }
9480
9481 [controller setDelegate:self];
9482 return controller;
9483 }
9484
9485 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9486 CyteViewController *page([self pageForURL:url forExternal:external]);
9487
9488 if (page != nil) {
9489 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9490 [nav setViewControllers:[NSArray arrayWithObject:page]];
9491 [tabbar_ setUnselectedViewController:nav];
9492 }
9493
9494 return page != nil;
9495 }
9496
9497 - (void) applicationOpenURL:(NSURL *)url {
9498 [super applicationOpenURL:url];
9499
9500 if (!loaded_)
9501 starturl_ = url;
9502 else
9503 [self openCydiaURL:url forExternal:YES];
9504 }
9505
9506 - (void) applicationWillResignActive:(UIApplication *)application {
9507 // Stop refreshing if you get a phone call or lock the device.
9508 if ([tabbar_ updating])
9509 [tabbar_ cancelUpdate];
9510
9511 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9512 [super applicationWillResignActive:application];
9513 }
9514
9515 - (void) saveState {
9516 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9517 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9518 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9519 Changed_ = true;
9520
9521 [self _saveConfig];
9522 }
9523
9524 - (void) applicationWillTerminate:(UIApplication *)application {
9525 [self saveState];
9526 }
9527
9528 - (void) setConfigurationData:(NSString *)data {
9529 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9530
9531 if (!conffile_r(data)) {
9532 lprintf("E:invalid conffile\n");
9533 return;
9534 }
9535
9536 NSString *ofile = conffile_r[1];
9537 //NSString *nfile = conffile_r[2];
9538
9539 UIAlertView *alert = [[[UIAlertView alloc]
9540 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9541 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9542 delegate:self
9543 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9544 otherButtonTitles:
9545 UCLocalize("ACCEPT_NEW_COPY"),
9546 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9547 nil
9548 ] autorelease];
9549
9550 [alert setContext:@"conffile"];
9551 [alert setNumberOfRows:2];
9552 [alert show];
9553 }
9554
9555 - (void) addStashController {
9556 ++locked_;
9557 stash_ = [[[StashController alloc] init] autorelease];
9558 [window_ addSubview:[stash_ view]];
9559 }
9560
9561 - (void) removeStashController {
9562 [[stash_ view] removeFromSuperview];
9563 stash_ = nil;
9564 --locked_;
9565 }
9566
9567 - (void) stash {
9568 [self setIdleTimerDisabled:YES];
9569
9570 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9571 UpdateExternalStatus(1);
9572 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9573 UpdateExternalStatus(0);
9574
9575 [self removeStashController];
9576
9577 if (ExecFork() == 0) {
9578 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9579 perror("launchctl stop");
9580 }
9581 }
9582
9583 - (void) setupViewControllers {
9584 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9585
9586 NSMutableArray *items([NSMutableArray arrayWithObjects:
9587 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9588 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9589 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9590 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9591 nil]);
9592
9593 if (IsWildcat_) {
9594 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9595 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9596 } else {
9597 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9598 }
9599
9600 NSMutableArray *controllers([NSMutableArray array]);
9601 for (UITabBarItem *item in items) {
9602 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9603 [controller setTabBarItem:item];
9604 [controllers addObject:controller];
9605 }
9606 [tabbar_ setViewControllers:controllers];
9607
9608 [tabbar_ setUpdateDelegate:self];
9609 }
9610
9611 - (void) applicationDidFinishLaunching:(id)unused {
9612 _trace();
9613 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9614 [self setApplicationSupportsShakeToEdit:NO];
9615
9616 @synchronized (HostConfig_) {
9617 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9618 }
9619
9620 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9621 initWithMemoryCapacity:524288
9622 diskCapacity:10485760
9623 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9624 ] autorelease]];
9625
9626 [CydiaWebViewController _initialize];
9627
9628 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9629
9630 // this would disallow http{,s} URLs from accessing this data
9631 //[WebView registerURLSchemeAsLocal:@"cydia"];
9632
9633 Font12_ = [UIFont systemFontOfSize:12];
9634 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9635 Font14_ = [UIFont systemFontOfSize:14];
9636 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9637 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9638
9639 essential_ = [NSMutableArray arrayWithCapacity:4];
9640 broken_ = [NSMutableArray arrayWithCapacity:4];
9641
9642 // XXX: I really need this thing... like, seriously... I'm sorry
9643 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9644
9645 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9646 [window_ orderFront:self];
9647 [window_ makeKey:self];
9648 [window_ setHidden:NO];
9649
9650 if (
9651 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9652 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9653 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9654 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9655 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9656 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9657 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9658 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9659 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9660 false
9661 ) {
9662 [self addStashController];
9663 // XXX: this would be much cleaner as a yieldToSelector:
9664 // that way the removeStashController could happen right here inline
9665 // we also could no longer require the useless stash_ field anymore
9666 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9667 return;
9668 }
9669
9670 database_ = [Database sharedInstance];
9671 [database_ setDelegate:self];
9672
9673 [window_ setUserInteractionEnabled:NO];
9674 [self setupViewControllers];
9675
9676 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9677 [window_ addSubview:[emulated_ view]];
9678
9679 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9680 _trace();
9681 }
9682
9683 - (NSArray *) defaultStartPages {
9684 NSMutableArray *standard = [NSMutableArray array];
9685 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9686 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9687 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9688 if (!IsWildcat_) {
9689 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9690 } else {
9691 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9692 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9693 }
9694 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9695 return standard;
9696 }
9697
9698 - (void) loadData {
9699 _trace();
9700 if (Role_ == nil) {
9701 [window_ setUserInteractionEnabled:YES];
9702 [self showSettings];
9703 return;
9704 } else {
9705 if ([emulated_ modalViewController] != nil)
9706 [emulated_ dismissModalViewControllerAnimated:YES];
9707 [window_ setUserInteractionEnabled:NO];
9708 }
9709
9710 [self reloadData];
9711 PrintTimes();
9712
9713 [self disemulate];
9714
9715 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9716 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9717 int standardIndex = 0;
9718 NSArray *standard = [self defaultStartPages];
9719
9720 BOOL valid = YES;
9721
9722 if (saved == nil)
9723 valid = NO;
9724
9725 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9726 if (valid && closed != nil) {
9727 NSTimeInterval interval([closed timeIntervalSinceNow]);
9728 // XXX: Is 15 minutes the optimal time here?
9729 if (interval > 0 && interval <= -(15*60))
9730 valid = NO;
9731 }
9732
9733 if (valid && [saved count] != [standard count])
9734 valid = NO;
9735
9736 if (valid) {
9737 for (unsigned int i = 0; i < [standard count]; i++) {
9738 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9739 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9740 // but it's good enough for now.
9741 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9742 valid = NO;
9743 break;
9744 }
9745 }
9746 }
9747
9748 NSArray *items = nil;
9749 if (valid) {
9750 [tabbar_ setSelectedIndex:savedIndex];
9751 items = saved;
9752 } else {
9753 [tabbar_ setSelectedIndex:standardIndex];
9754 items = standard;
9755 }
9756
9757 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9758 NSArray *stack = [items objectAtIndex:tab];
9759 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9760 NSMutableArray *current = [NSMutableArray array];
9761
9762 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9763 NSString *addr = [stack objectAtIndex:nav];
9764 NSURL *url = [NSURL URLWithString:addr];
9765 CyteViewController *page = [self pageForURL:url forExternal:NO];
9766 if (page != nil)
9767 [current addObject:page];
9768 }
9769
9770 [navigation setViewControllers:current];
9771 }
9772
9773 // (Try to) show the startup URL.
9774 if (starturl_ != nil) {
9775 [self openCydiaURL:starturl_ forExternal:NO];
9776 starturl_ = nil;
9777 }
9778 }
9779
9780 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9781 if (item != nil && IsWildcat_) {
9782 [sheet showFromBarButtonItem:item animated:YES];
9783 } else {
9784 [sheet showInView:window_];
9785 }
9786 }
9787
9788 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9789 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9790 [progress setTitle:task];
9791 [progress addProgressEvent:event];
9792 }
9793
9794 - (void) addProgressEventForTask:(NSArray *)data {
9795 CydiaProgressEvent *event([data objectAtIndex:0]);
9796 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9797 [self addProgressEvent:event forTask:task];
9798 }
9799
9800 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9801 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9802 }
9803
9804 @end
9805
9806 /*IMP alloc_;
9807 id Alloc_(id self, SEL selector) {
9808 id object = alloc_(self, selector);
9809 lprintf("[%s]A-%p\n", self->isa->name, object);
9810 return object;
9811 }*/
9812
9813 /*IMP dealloc_;
9814 id Dealloc_(id self, SEL selector) {
9815 id object = dealloc_(self, selector);
9816 lprintf("[%s]D-%p\n", self->isa->name, object);
9817 return object;
9818 }*/
9819
9820 Class $WebDefaultUIKitDelegate;
9821
9822 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9823 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9824 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9825 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9826 }
9827
9828 static NSSet *MobilizedFiles_;
9829
9830 static NSURL *MobilizeURL(NSURL *url) {
9831 NSString *path([url path]);
9832 if ([path hasPrefix:@"/var/root/"]) {
9833 NSString *file([path substringFromIndex:10]);
9834 if ([MobilizedFiles_ containsObject:file])
9835 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9836 }
9837
9838 return url;
9839 }
9840
9841 Class $CFXPreferencesPropertyListSource;
9842 @class CFXPreferencesPropertyListSource;
9843
9844 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9845 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9846 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9847 url = MobilizeURL(url);
9848 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9849 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9850 url = old;
9851 [pool release];
9852 return value;
9853 }
9854
9855 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9856 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9857 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9858 url = MobilizeURL(url);
9859 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9860 //NSLog(@"%@ %@", [url absoluteString], value);
9861 url = old;
9862 [pool release];
9863 return value;
9864 }
9865
9866 Class $NSURLConnection;
9867
9868 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9869 NSMutableURLRequest *copy([request mutableCopy]);
9870
9871 NSURL *url([copy URL]);
9872
9873 NSString *href([url absoluteString]);
9874 NSString *host([url host]);
9875 NSString *scheme([[url scheme] lowercaseString]);
9876
9877 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9878
9879 @synchronized (HostConfig_) {
9880 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9881 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9882 [copy setHTTPShouldUsePipelining:YES];
9883
9884 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9885 if ([control isEqualToString:@"max-age=0"])
9886 if ([CachedURLs_ containsObject:href]) {
9887 #if !ForRelease
9888 NSLog(@"~~~: %@", href);
9889 #endif
9890
9891 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9892
9893 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9894 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9895 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9896 }
9897 }
9898
9899 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9900 } return self;
9901 }
9902
9903 int main(int argc, char *argv[]) {
9904 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9905
9906 _trace();
9907
9908 UpdateExternalStatus(0);
9909
9910 if (Class $UIDevice = objc_getClass("UIDevice")) {
9911 UIDevice *device([$UIDevice currentDevice]);
9912 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9913 } else
9914 IsWildcat_ = false;
9915
9916 UIScreen *screen([UIScreen mainScreen]);
9917 if ([screen respondsToSelector:@selector(scale)])
9918 ScreenScale_ = [screen scale];
9919 else
9920 ScreenScale_ = 1;
9921
9922 UIDevice *device([UIDevice currentDevice]);
9923 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9924 Idiom_ = @"iphone";
9925 else {
9926 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9927 if (idiom == UIUserInterfaceIdiomPhone)
9928 Idiom_ = @"iphone";
9929 else if (idiom == UIUserInterfaceIdiomPad)
9930 Idiom_ = @"ipad";
9931 else
9932 NSLog(@"unknown UIUserInterfaceIdiom!");
9933 }
9934
9935 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9936
9937 HostConfig_ = [[[NSObject alloc] init] autorelease];
9938 @synchronized (HostConfig_) {
9939 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9940 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9941 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9942 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9943 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9944 }
9945
9946 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9947
9948 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9949
9950 MobilizedFiles_ = [NSMutableSet setWithObjects:
9951 @"Library/Preferences/com.apple.Accessibility.plist",
9952 @"Library/Preferences/com.apple.preferences.sounds.plist",
9953 nil];
9954
9955 /* Library Hacks {{{ */
9956 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9957
9958 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9959
9960 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9961 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9962 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9963 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9964 }
9965
9966 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9967 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9968 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9969 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9970 }
9971
9972 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9973 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9974 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9975 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9976 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9977 }
9978
9979 $NSURLConnection = objc_getClass("NSURLConnection");
9980 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9981 if (NSURLConnection$init$ != NULL) {
9982 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9983 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9984 }
9985 /* }}} */
9986 /* Set Locale {{{ */
9987 Locale_ = CFLocaleCopyCurrent();
9988 Languages_ = [NSLocale preferredLanguages];
9989
9990 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9991 //NSLog(@"%@", [Languages_ description]);
9992
9993 const char *lang;
9994 if (Locale_ != NULL)
9995 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9996 else if (Languages_ != nil && [Languages_ count] != 0)
9997 lang = [[Languages_ objectAtIndex:0] UTF8String];
9998 else
9999 // XXX: consider just setting to C and then falling through?
10000 lang = NULL;
10001
10002 if (lang != NULL) {
10003 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10004 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10005 }
10006
10007 NSLog(@"Setting Language: %s", lang);
10008
10009 if (lang != NULL) {
10010 setenv("LANG", lang, true);
10011 std::setlocale(LC_ALL, lang);
10012 }
10013 /* }}} */
10014
10015 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10016
10017 /* Parse Arguments {{{ */
10018 bool substrate(false);
10019
10020 if (argc != 0) {
10021 char **args(argv);
10022 int arge(1);
10023
10024 for (int argi(1); argi != argc; ++argi)
10025 if (strcmp(argv[argi], "--") == 0) {
10026 arge = argi;
10027 argv[argi] = argv[0];
10028 argv += argi;
10029 argc -= argi;
10030 break;
10031 }
10032
10033 for (int argi(1); argi != arge; ++argi)
10034 if (strcmp(args[argi], "--substrate") == 0)
10035 substrate = true;
10036 else
10037 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10038 }
10039 /* }}} */
10040
10041 App_ = [[NSBundle mainBundle] bundlePath];
10042 Advanced_ = YES;
10043
10044 setuid(0);
10045 setgid(0);
10046
10047 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10048 alloc_ = alloc->method_imp;
10049 alloc->method_imp = (IMP) &Alloc_;*/
10050
10051 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10052 dealloc_ = dealloc->method_imp;
10053 dealloc->method_imp = (IMP) &Dealloc_;*/
10054
10055 /* System Information {{{ */
10056 size_t size;
10057
10058 int maxproc;
10059 size = sizeof(maxproc);
10060 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10061 perror("sysctlbyname(\"kern.maxproc\", ?)");
10062 else if (maxproc < 64) {
10063 maxproc = 64;
10064 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10065 perror("sysctlbyname(\"kern.maxproc\", #)");
10066 }
10067
10068 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10069 char *osversion = new char[size];
10070 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10071 perror("sysctlbyname(\"kern.osversion\", ?)");
10072 else
10073 System_ = [NSString stringWithUTF8String:osversion];
10074
10075 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10076 char *machine = new char[size];
10077 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10078 perror("sysctlbyname(\"hw.machine\", ?)");
10079 else
10080 Machine_ = machine;
10081
10082 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10083 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10084 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10085
10086 UniqueID_ = [device uniqueIdentifier];
10087
10088 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10089 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10090 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10091
10092 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10093 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10094 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10095
10096 if (mcc != NULL && mnc != NULL)
10097 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10098
10099 if (mnc != NULL)
10100 CFRelease(mnc);
10101 if (mcc != NULL)
10102 CFRelease(mcc);
10103
10104 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10105 Build_ = [system objectForKey:@"ProductBuildVersion"];
10106 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10107 Product_ = [info objectForKey:@"SafariProductVersion"];
10108 Safari_ = [info objectForKey:@"CFBundleVersion"];
10109 }
10110 /* }}} */
10111 /* Load Database {{{ */
10112 _trace();
10113 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10114 _trace();
10115 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10116
10117 if (Metadata_ == NULL)
10118 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10119 else {
10120 Settings_ = [Metadata_ objectForKey:@"Settings"];
10121
10122 Packages_ = [Metadata_ objectForKey:@"Packages"];
10123
10124 Values_ = [Metadata_ objectForKey:@"Values"];
10125 Sections_ = [Metadata_ objectForKey:@"Sections"];
10126 Sources_ = [Metadata_ objectForKey:@"Sources"];
10127
10128 Token_ = [Metadata_ objectForKey:@"Token"];
10129
10130 Version_ = [Metadata_ objectForKey:@"Version"];
10131
10132 @synchronized (HostConfig_) {
10133 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10134 }
10135 }
10136
10137 if (Settings_ != nil)
10138 Role_ = [Settings_ objectForKey:@"Role"];
10139
10140 if (Values_ == nil) {
10141 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10142 [Metadata_ setObject:Values_ forKey:@"Values"];
10143 }
10144
10145 if (Sections_ == nil) {
10146 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10147 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10148 }
10149
10150 if (Sources_ == nil) {
10151 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10152 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10153 }
10154
10155 if (Version_ == nil) {
10156 Version_ = [NSNumber numberWithUnsignedInt:0];
10157 [Metadata_ setObject:Version_ forKey:@"Version"];
10158 }
10159
10160 @synchronized (HostConfig_) {
10161 if (CydiaSource_ == nil) {
10162 CydiaSource_ = @"apt.saurik.com";
10163 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10164 }
10165 }
10166
10167 if ([Version_ unsignedIntValue] == 0) {
10168 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10169 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10170 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10171 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10172
10173 Version_ = [NSNumber numberWithUnsignedInt:1];
10174 [Metadata_ setObject:Version_ forKey:@"Version"];
10175
10176 Changed_ = true;
10177 }
10178 /* }}} */
10179
10180 WriteSources();
10181
10182 _trace();
10183 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10184 _trace();
10185
10186 if (Packages_ != nil) {
10187 bool fail(false);
10188 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10189 _trace();
10190
10191 if (!fail) {
10192 [Metadata_ removeObjectForKey:@"Packages"];
10193 Packages_ = nil;
10194 Changed_ = true;
10195 }
10196 }
10197
10198 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10199
10200 #define MobileSubstrate_(name) \
10201 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10202 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10203 if (handle == NULL) \
10204 NSLog(@"%s", dlerror()); \
10205 }
10206
10207 MobileSubstrate_(Activator)
10208 MobileSubstrate_(libstatusbar)
10209 MobileSubstrate_(SimulatedKeyEvents)
10210 MobileSubstrate_(WinterBoard)
10211
10212 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10213 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10214
10215 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10216
10217 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10218 unlink("/tmp/.cydia.fw");
10219 goto firmware;
10220 } else if (access("/User", F_OK) != 0 || version < 4) {
10221 firmware:
10222 _trace();
10223 system("/usr/libexec/cydia/firmware.sh");
10224 _trace();
10225 }
10226
10227 _assert([[NSFileManager defaultManager]
10228 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10229 withIntermediateDirectories:YES
10230 attributes:nil
10231 error:NULL
10232 ]);
10233
10234 if (access("/tmp/cydia.chk", F_OK) == 0) {
10235 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10236 _assert(errno == ENOENT);
10237 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10238 _assert(errno == ENOENT);
10239 }
10240
10241 /* APT Initialization {{{ */
10242 _assert(pkgInitConfig(*_config));
10243 _assert(pkgInitSystem(*_config, _system));
10244
10245 if (lang != NULL)
10246 _config->Set("APT::Acquire::Translation", lang);
10247
10248 // XXX: this timeout might be important :(
10249 //_config->Set("Acquire::http::Timeout", 15);
10250
10251 _config->Set("Acquire::http::MaxParallel", 3);
10252 /* }}} */
10253 /* Color Choices {{{ */
10254 space_ = CGColorSpaceCreateDeviceRGB();
10255
10256 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10257 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10258 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10259 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10260 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10261 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10262 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10263 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10264 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10265
10266 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10267 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10268 /* }}}*/
10269 /* UIKit Configuration {{{ */
10270 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10271 if ($GSFontSetUseLegacyFontMetrics != NULL)
10272 $GSFontSetUseLegacyFontMetrics(YES);
10273
10274 // XXX: I have a feeling this was important
10275 //UIKeyboardDisableAutomaticAppearance();
10276 /* }}} */
10277
10278 Colon_ = UCLocalize("COLON_DELIMITED");
10279 Elision_ = UCLocalize("ELISION");
10280 Error_ = UCLocalize("ERROR");
10281 Warning_ = UCLocalize("WARNING");
10282
10283 _trace();
10284 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10285
10286 CGColorSpaceRelease(space_);
10287 CFRelease(Locale_);
10288
10289 [pool release];
10290 return value;
10291 }