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