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