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