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