]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Create a lame helper for clearWindowObject.
[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 @class CydiaObject;
3936
3937 @interface CydiaWebViewController : CyteWebViewController {
3938 _H<CydiaObject> cydia_;
3939 }
3940
3941 + (void) addDiversion:(Diversion *)diversion;
3942 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3943 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3944 - (void) setDelegate:(id)delegate;
3945
3946 @end
3947
3948 /* Web Scripting {{{ */
3949 @implementation CydiaObject
3950
3951 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3952 if ((self = [super init]) != nil) {
3953 indirect_ = indirect;
3954 } return self;
3955 }
3956
3957 - (void) setDelegate:(id)delegate {
3958 delegate_ = delegate;
3959 }
3960
3961 + (NSArray *) _attributeKeys {
3962 return [NSArray arrayWithObjects:
3963 @"bbsnum",
3964 @"build",
3965 @"coreFoundationVersionNumber",
3966 @"device",
3967 @"ecid",
3968 @"firmware",
3969 @"hostname",
3970 @"idiom",
3971 @"mcc",
3972 @"mnc",
3973 @"model",
3974 @"operator",
3975 @"role",
3976 @"serial",
3977 @"token",
3978 @"version",
3979 nil];
3980 }
3981
3982 - (NSArray *) attributeKeys {
3983 return [[self class] _attributeKeys];
3984 }
3985
3986 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3987 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3988 }
3989
3990 - (NSString *) version {
3991 return Cydia_;
3992 }
3993
3994 - (NSString *) build {
3995 return System_;
3996 }
3997
3998 - (NSString *) coreFoundationVersionNumber {
3999 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4000 }
4001
4002 - (NSString *) device {
4003 return [[UIDevice currentDevice] uniqueIdentifier];
4004 }
4005
4006 - (NSString *) firmware {
4007 return [[UIDevice currentDevice] systemVersion];
4008 }
4009
4010 - (NSString *) hostname {
4011 return [[UIDevice currentDevice] name];
4012 }
4013
4014 - (NSString *) idiom {
4015 return (id) Idiom_ ?: [NSNull null];
4016 }
4017
4018 - (NSString *) mcc {
4019 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4020 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4021 return nil;
4022 }
4023
4024 - (NSString *) mnc {
4025 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4026 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4027 return nil;
4028 }
4029
4030 - (NSString *) operator {
4031 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4032 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4033 return nil;
4034 }
4035
4036 - (NSString *) bbsnum {
4037 return (id) BBSNum_ ?: [NSNull null];
4038 }
4039
4040 - (NSString *) ecid {
4041 return (id) ChipID_ ?: [NSNull null];
4042 }
4043
4044 - (NSString *) serial {
4045 return SerialNumber_;
4046 }
4047
4048 - (NSString *) role {
4049 return (id) Role_ ?: [NSNull null];
4050 }
4051
4052 - (NSString *) model {
4053 return [NSString stringWithUTF8String:Machine_];
4054 }
4055
4056 - (NSString *) token {
4057 return (id) Token_ ?: [NSNull null];
4058 }
4059
4060 + (NSString *) webScriptNameForSelector:(SEL)selector {
4061 if (false);
4062 else if (selector == @selector(addBridgedHost:))
4063 return @"addBridgedHost";
4064 else if (selector == @selector(addInsecureHost:))
4065 return @"addInsecureHost";
4066 else if (selector == @selector(addInternalRedirect::))
4067 return @"addInternalRedirect";
4068 else if (selector == @selector(addPipelinedHost:scheme:))
4069 return @"addPipelinedHost";
4070 else if (selector == @selector(addSource:::))
4071 return @"addSource";
4072 else if (selector == @selector(addTokenHost:))
4073 return @"addTokenHost";
4074 else if (selector == @selector(addTrivialSource:))
4075 return @"addTrivialSource";
4076 else if (selector == @selector(close))
4077 return @"close";
4078 else if (selector == @selector(du:))
4079 return @"du";
4080 else if (selector == @selector(stringWithFormat:arguments:))
4081 return @"format";
4082 else if (selector == @selector(getAllSources))
4083 return @"getAllSourcs";
4084 else if (selector == @selector(getKernelNumber:))
4085 return @"getKernelNumber";
4086 else if (selector == @selector(getKernelString:))
4087 return @"getKernelString";
4088 else if (selector == @selector(getInstalledPackages))
4089 return @"getInstalledPackages";
4090 else if (selector == @selector(getIORegistryEntry::))
4091 return @"getIORegistryEntry";
4092 else if (selector == @selector(getLocaleIdentifier))
4093 return @"getLocaleIdentifier";
4094 else if (selector == @selector(getPreferredLanguages))
4095 return @"getPreferredLanguages";
4096 else if (selector == @selector(getPackageById:))
4097 return @"getPackageById";
4098 else if (selector == @selector(getMetadataKeys))
4099 return @"getMetadataKeys";
4100 else if (selector == @selector(getMetadataValue:))
4101 return @"getMetadataValue";
4102 else if (selector == @selector(getSessionValue:))
4103 return @"getSessionValue";
4104 else if (selector == @selector(installPackages:))
4105 return @"installPackages";
4106 else if (selector == @selector(localizedStringForKey:value:table:))
4107 return @"localize";
4108 else if (selector == @selector(popViewController:))
4109 return @"popViewController";
4110 else if (selector == @selector(refreshSources))
4111 return @"refreshSources";
4112 else if (selector == @selector(removeButton))
4113 return @"removeButton";
4114 else if (selector == @selector(saveConfig))
4115 return @"saveConfig";
4116 else if (selector == @selector(setMetadataValue::))
4117 return @"setMetadataValue";
4118 else if (selector == @selector(setSessionValue::))
4119 return @"setSessionValue";
4120 else if (selector == @selector(substitutePackageNames:))
4121 return @"substitutePackageNames";
4122 else if (selector == @selector(scrollToBottom:))
4123 return @"scrollToBottom";
4124 else if (selector == @selector(setAllowsNavigationAction:))
4125 return @"setAllowsNavigationAction";
4126 else if (selector == @selector(setBadgeValue:))
4127 return @"setBadgeValue";
4128 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4129 return @"setButtonImage";
4130 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4131 return @"setButtonTitle";
4132 else if (selector == @selector(setHidesBackButton:))
4133 return @"setHidesBackButton";
4134 else if (selector == @selector(setHidesNavigationBar:))
4135 return @"setHidesNavigationBar";
4136 else if (selector == @selector(setNavigationBarStyle:))
4137 return @"setNavigationBarStyle";
4138 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4139 return @"setNavigationBarTintColor";
4140 else if (selector == @selector(setPasteboardString:))
4141 return @"setPasteboardString";
4142 else if (selector == @selector(setPasteboardURL:))
4143 return @"setPasteboardURL";
4144 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4145 return @"setScrollAlwaysBounceVertical";
4146 else if (selector == @selector(setScrollIndicatorStyle:))
4147 return @"setScrollIndicatorStyle";
4148 else if (selector == @selector(setToken:))
4149 return @"setToken";
4150 else if (selector == @selector(setViewportWidth:))
4151 return @"setViewportWidth";
4152 else if (selector == @selector(statfs:))
4153 return @"statfs";
4154 else if (selector == @selector(supports:))
4155 return @"supports";
4156 else if (selector == @selector(unload))
4157 return @"unload";
4158 else
4159 return nil;
4160 }
4161
4162 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4163 return [self webScriptNameForSelector:selector] == nil;
4164 }
4165
4166 - (BOOL) supports:(NSString *)feature {
4167 return [feature isEqualToString:@"window.open"];
4168 }
4169
4170 - (void) unload {
4171 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4172 }
4173
4174 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4175 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4176 }
4177
4178 - (void) setScrollIndicatorStyle:(NSString *)style {
4179 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4180 }
4181
4182 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4183 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4184 }
4185
4186 - (NSNumber *) getKernelNumber:(NSString *)name {
4187 const char *string([name UTF8String]);
4188
4189 size_t size;
4190 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4191 return (id) [NSNull null];
4192
4193 if (size != sizeof(int))
4194 return (id) [NSNull null];
4195
4196 int value;
4197 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4198 return (id) [NSNull null];
4199
4200 return [NSNumber numberWithInt:value];
4201 }
4202
4203 - (NSString *) getKernelString:(NSString *)name {
4204 const char *string([name UTF8String]);
4205
4206 size_t size;
4207 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4208 return (id) [NSNull null];
4209
4210 char value[size + 1];
4211 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4212 return (id) [NSNull null];
4213
4214 // XXX: just in case you request something ludicrous
4215 value[size] = '\0';
4216
4217 return [NSString stringWithCString:value];
4218 }
4219
4220 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4221 NSObject *value(CYIOGetValue([path UTF8String], entry));
4222
4223 if (value != nil)
4224 if ([value isKindOfClass:[NSData class]])
4225 value = CYHex((NSData *) value);
4226
4227 return value;
4228 }
4229
4230 - (NSArray *) getMetadataKeys {
4231 @synchronized (Values_) {
4232 return [Values_ allKeys];
4233 } }
4234
4235 - (id) getMetadataValue:(NSString *)key {
4236 @synchronized (Values_) {
4237 return [Values_ objectForKey:key];
4238 } }
4239
4240 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4241 @synchronized (Values_) {
4242 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4243 [Values_ removeObjectForKey:key];
4244 else
4245 [Values_ setObject:value forKey:key];
4246
4247 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4248 } }
4249
4250 - (id) getSessionValue:(NSString *)key {
4251 @synchronized (SessionData_) {
4252 return [SessionData_ objectForKey:key];
4253 } }
4254
4255 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4256 @synchronized (SessionData_) {
4257 if (value == (id) [WebUndefined undefined])
4258 [SessionData_ removeObjectForKey:key];
4259 else
4260 [SessionData_ setObject:value forKey:key];
4261 } }
4262
4263 - (void) addBridgedHost:(NSString *)host {
4264 @synchronized (HostConfig_) {
4265 [BridgedHosts_ addObject:host];
4266 } }
4267
4268 - (void) addInsecureHost:(NSString *)host {
4269 @synchronized (HostConfig_) {
4270 [InsecureHosts_ addObject:host];
4271 } }
4272
4273 - (void) addTokenHost:(NSString *)host {
4274 @synchronized (HostConfig_) {
4275 [TokenHosts_ addObject:host];
4276 } }
4277
4278 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4279 @synchronized (HostConfig_) {
4280 if (scheme != (id) [WebUndefined undefined])
4281 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4282
4283 [PipelinedHosts_ addObject:host];
4284 } }
4285
4286 - (void) popViewController:(NSNumber *)value {
4287 if (value == (id) [WebUndefined undefined])
4288 value = [NSNumber numberWithBool:YES];
4289 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4290 }
4291
4292 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4293 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4294
4295 for (NSString *section in sections)
4296 [array addObject:section];
4297
4298 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4299 @"deb", @"Type",
4300 href, @"URI",
4301 distribution, @"Distribution",
4302 array, @"Sections",
4303 nil] waitUntilDone:NO];
4304 }
4305
4306 - (void) addTrivialSource:(NSString *)href {
4307 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4308 }
4309
4310 - (void) refreshSources {
4311 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4312 }
4313
4314 - (void) saveConfig {
4315 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4316 }
4317
4318 - (NSArray *) getAllSources {
4319 return [[Database sharedInstance] sources];
4320 }
4321
4322 - (NSArray *) getInstalledPackages {
4323 Database *database([Database sharedInstance]);
4324 @synchronized (database) {
4325 NSArray *packages([database packages]);
4326 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4327 for (Package *package in packages)
4328 if (![package uninstalled])
4329 [installed addObject:package];
4330 return installed;
4331 } }
4332
4333 - (Package *) getPackageById:(NSString *)id {
4334 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4335 [package parse];
4336 return package;
4337 } else
4338 return (Package *) [NSNull null];
4339 }
4340
4341 - (NSString *) getLocaleIdentifier {
4342 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4343 }
4344
4345 - (NSArray *) getPreferredLanguages {
4346 return Languages_;
4347 }
4348
4349 - (NSArray *) statfs:(NSString *)path {
4350 struct statfs stat;
4351
4352 if (path == nil || statfs([path UTF8String], &stat) == -1)
4353 return nil;
4354
4355 return [NSArray arrayWithObjects:
4356 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4357 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4358 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4359 nil];
4360 }
4361
4362 - (NSNumber *) du:(NSString *)path {
4363 NSNumber *value(nil);
4364
4365 int fds[2];
4366 _assert(pipe(fds) != -1);
4367
4368 pid_t pid(ExecFork());
4369 if (pid == 0) {
4370 _assert(dup2(fds[1], 1) != -1);
4371 _assert(close(fds[0]) != -1);
4372 _assert(close(fds[1]) != -1);
4373 /* XXX: this should probably not use du */
4374 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4375 exit(1);
4376 _assert(false);
4377 }
4378
4379 _assert(close(fds[1]) != -1);
4380
4381 if (FILE *du = fdopen(fds[0], "r")) {
4382 char line[1024];
4383 while (fgets(line, sizeof(line), du) != NULL) {
4384 size_t length(strlen(line));
4385 while (length != 0 && line[length - 1] == '\n')
4386 line[--length] = '\0';
4387 if (char *tab = strchr(line, '\t')) {
4388 *tab = '\0';
4389 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4390 }
4391 }
4392
4393 fclose(du);
4394 } else _assert(close(fds[0]));
4395
4396 ReapZombie(pid);
4397
4398 return value;
4399 }
4400
4401 - (void) close {
4402 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4403 }
4404
4405 - (void) installPackages:(NSArray *)packages {
4406 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4407 }
4408
4409 - (NSString *) substitutePackageNames:(NSString *)message {
4410 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4411 for (size_t i(0), e([words count]); i != e; ++i) {
4412 NSString *word([words objectAtIndex:i]);
4413 if (Package *package = [[Database sharedInstance] packageWithName:word])
4414 [words replaceObjectAtIndex:i withObject:[package name]];
4415 }
4416
4417 return [words componentsJoinedByString:@" "];
4418 }
4419
4420 - (void) removeButton {
4421 [indirect_ removeButton];
4422 }
4423
4424 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4425 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4426 }
4427
4428 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4429 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4430 }
4431
4432 - (void) setBadgeValue:(id)value {
4433 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4434 }
4435
4436 - (void) setAllowsNavigationAction:(NSString *)value {
4437 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4438 }
4439
4440 - (void) setHidesBackButton:(NSString *)value {
4441 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4442 }
4443
4444 - (void) setHidesNavigationBar:(NSString *)value {
4445 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4446 }
4447
4448 - (void) setNavigationBarStyle:(NSString *)value {
4449 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4450 }
4451
4452 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4453 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4454 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4455 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4456 }
4457
4458 - (void) setPasteboardString:(NSString *)value {
4459 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4460 }
4461
4462 - (void) setPasteboardURL:(NSString *)value {
4463 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4464 }
4465
4466 - (void) _setToken:(NSString *)token {
4467 Token_ = token;
4468
4469 if (token == nil)
4470 [Metadata_ removeObjectForKey:@"Token"];
4471 else
4472 [Metadata_ setObject:Token_ forKey:@"Token"];
4473
4474 Changed_ = true;
4475 }
4476
4477 - (void) setToken:(NSString *)token {
4478 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4479 }
4480
4481 - (void) scrollToBottom:(NSNumber *)animated {
4482 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4483 }
4484
4485 - (void) setViewportWidth:(float)width {
4486 [indirect_ setViewportWidthOnMainThread:width];
4487 }
4488
4489 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4490 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4491 unsigned count([arguments count]);
4492 id values[count];
4493 for (unsigned i(0); i != count; ++i)
4494 values[i] = [arguments objectAtIndex:i];
4495 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4496 }
4497
4498 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4499 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4500 value = nil;
4501 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4502 table = nil;
4503 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4504 }
4505
4506 @end
4507 /* }}} */
4508
4509 @interface NSURL (CydiaSecure)
4510 @end
4511
4512 @implementation NSURL (CydiaSecure)
4513
4514 - (bool) isCydiaSecure {
4515 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4516 return true;
4517
4518 @synchronized (HostConfig_) {
4519 if ([InsecureHosts_ containsObject:[self host]])
4520 return true;
4521 }
4522
4523 return false;
4524 }
4525
4526 @end
4527
4528 /* Cydia Browser Controller {{{ */
4529 @implementation CydiaWebViewController
4530
4531 - (NSURL *) navigationURL {
4532 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4533 }
4534
4535 + (void) _initialize {
4536 [super _initialize];
4537
4538 Diversions_ = [NSMutableSet setWithCapacity:0];
4539 }
4540
4541 + (void) addDiversion:(Diversion *)diversion {
4542 [Diversions_ addObject:diversion];
4543 }
4544
4545 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4546 [super webView:view didClearWindowObject:window forFrame:frame];
4547 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4548 }
4549
4550 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4551 WebDataSource *source([frame dataSource]);
4552 NSURLResponse *response([source response]);
4553 NSURL *url([response URL]);
4554 NSString *scheme([[url scheme] lowercaseString]);
4555
4556 bool bridged(false);
4557
4558 @synchronized (HostConfig_) {
4559 if ([scheme isEqualToString:@"file"])
4560 bridged = true;
4561 else if ([scheme isEqualToString:@"https"])
4562 if ([BridgedHosts_ containsObject:[url host]])
4563 bridged = true;
4564 }
4565
4566 if (bridged)
4567 [window setValue:cydia forKey:@"cydia"];
4568 }
4569
4570 - (void) _setupMail:(MFMailComposeViewController *)controller {
4571 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4572
4573 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4574 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4575 }
4576
4577 - (NSURL *) URLWithURL:(NSURL *)url {
4578 return [Diversion divertURL:url];
4579 }
4580
4581 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4582 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4583 }
4584
4585 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4586 NSMutableURLRequest *copy([request mutableCopy]);
4587
4588 NSURL *url([copy URL]);
4589 NSString *host([url host]);
4590
4591 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf-Version"] == nil)
4592 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf-Version"];
4593 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4594 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4595
4596 bool bridged;
4597 bool token;
4598
4599 @synchronized (HostConfig_) {
4600 bridged = [BridgedHosts_ containsObject:host];
4601 token = [TokenHosts_ containsObject:host];
4602 }
4603
4604 if ([url isCydiaSecure]) {
4605 if (bridged) {
4606 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4607 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4608 } else if (token) {
4609 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4610 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4611 }
4612 }
4613
4614 return copy;
4615 }
4616
4617 - (void) setDelegate:(id)delegate {
4618 [super setDelegate:delegate];
4619 [cydia_ setDelegate:delegate];
4620 }
4621
4622 - (NSString *) applicationNameForUserAgent {
4623 return UserAgent_;
4624 }
4625
4626 - (id) init {
4627 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4628 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4629 } return self;
4630 }
4631
4632 @end
4633
4634 @interface AppCacheController : CydiaWebViewController {
4635 }
4636
4637 @end
4638
4639 @implementation AppCacheController
4640
4641 - (void) didReceiveMemoryWarning {
4642 // XXX: this doesn't work
4643 }
4644
4645 - (bool) retainsNetworkActivityIndicator {
4646 return false;
4647 }
4648
4649 @end
4650 /* }}} */
4651
4652 // CydiaScript {{{
4653 @interface NSObject (CydiaScript)
4654 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4655 @end
4656
4657 @implementation NSObject (CydiaScript)
4658
4659 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4660 return self;
4661 }
4662
4663 @end
4664
4665 @implementation NSArray (CydiaScript)
4666
4667 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4668 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4669 for (size_t i(0), e([self count]); i != e; ++i)
4670 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4671 return object;
4672 }
4673
4674 @end
4675
4676 @implementation NSDictionary (CydiaScript)
4677
4678 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4679 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4680 for (id i in self)
4681 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4682 return object;
4683 }
4684
4685 @end
4686 // }}}
4687
4688 /* Confirmation Controller {{{ */
4689 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4690 if (!iterator.end())
4691 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4692 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4693 continue;
4694 pkgCache::PkgIterator package(dep.TargetPkg());
4695 if (package.end())
4696 continue;
4697 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4698 return true;
4699 }
4700
4701 return false;
4702 }
4703
4704 @protocol ConfirmationControllerDelegate
4705 - (void) cancelAndClear:(bool)clear;
4706 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4707 - (void) queue;
4708 @end
4709
4710 @interface ConfirmationController : CydiaWebViewController {
4711 _transient Database *database_;
4712
4713 _H<UIAlertView> essential_;
4714
4715 _H<NSDictionary> changes_;
4716 _H<NSMutableArray> issues_;
4717 _H<NSDictionary> sizes_;
4718
4719 BOOL substrate_;
4720 }
4721
4722 - (id) initWithDatabase:(Database *)database;
4723
4724 @end
4725
4726 @implementation ConfirmationController
4727
4728 - (void) complete {
4729 if (substrate_)
4730 RestartSubstrate_ = true;
4731 [delegate_ confirmWithNavigationController:[self navigationController]];
4732 }
4733
4734 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4735 NSString *context([alert context]);
4736
4737 if ([context isEqualToString:@"remove"]) {
4738 if (button == [alert cancelButtonIndex])
4739 [self dismissModalViewControllerAnimated:YES];
4740 else if (button == [alert firstOtherButtonIndex]) {
4741 [self complete];
4742 }
4743
4744 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4745 } else if ([context isEqualToString:@"unable"]) {
4746 [self dismissModalViewControllerAnimated:YES];
4747 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4748 } else {
4749 [super alertView:alert clickedButtonAtIndex:button];
4750 }
4751 }
4752
4753 - (void) _doContinue {
4754 [delegate_ cancelAndClear:NO];
4755 [self dismissModalViewControllerAnimated:YES];
4756 }
4757
4758 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4759 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4760 return nil;
4761 }
4762
4763 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4764 [super webView:view didClearWindowObject:window forFrame:frame];
4765
4766 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4767 (id) changes_, @"changes",
4768 (id) issues_, @"issues",
4769 (id) sizes_, @"sizes",
4770 self, @"queue",
4771 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4772 }
4773
4774 - (id) initWithDatabase:(Database *)database {
4775 if ((self = [super init]) != nil) {
4776 database_ = database;
4777
4778 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4779 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4780 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4781 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4782 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4783
4784 bool remove(false);
4785
4786 pkgCacheFile &cache([database_ cache]);
4787 NSArray *packages([database_ packages]);
4788 pkgDepCache::Policy *policy([database_ policy]);
4789
4790 issues_ = [NSMutableArray arrayWithCapacity:4];
4791
4792 for (Package *package in packages) {
4793 pkgCache::PkgIterator iterator([package iterator]);
4794 NSString *name([package id]);
4795
4796 if ([package broken]) {
4797 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4798
4799 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4800 name, @"package",
4801 reasons, @"reasons",
4802 nil]];
4803
4804 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4805 if (ver.end())
4806 continue;
4807
4808 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4809 pkgCache::DepIterator start;
4810 pkgCache::DepIterator end;
4811 dep.GlobOr(start, end); // ++dep
4812
4813 if (!cache->IsImportantDep(end))
4814 continue;
4815 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4816 continue;
4817
4818 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4819
4820 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4821 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4822 clauses, @"clauses",
4823 nil]];
4824
4825 _forever {
4826 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4827
4828 pkgCache::PkgIterator target(start.TargetPkg());
4829 if (target->ProvidesList != 0)
4830 reason = @"missing";
4831 else {
4832 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4833 if (!ver.end()) {
4834 reason = @"installed";
4835 installed = [NSString stringWithUTF8String:ver.VerStr()];
4836 } else if (!cache[target].CandidateVerIter(cache).end())
4837 reason = @"uninstalled";
4838 else if (target->ProvidesList == 0)
4839 reason = @"uninstallable";
4840 else
4841 reason = @"virtual";
4842 }
4843
4844 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4845 [NSString stringWithUTF8String:start.CompType()], @"operator",
4846 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4847 nil]);
4848
4849 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4850 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4851 version, @"version",
4852 reason, @"reason",
4853 installed, @"installed",
4854 nil]];
4855
4856 // yes, seriously. (wtf?)
4857 if (start == end)
4858 break;
4859 ++start;
4860 }
4861 }
4862 }
4863
4864 pkgDepCache::StateCache &state(cache[iterator]);
4865
4866 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4867
4868 if (state.NewInstall())
4869 [installs addObject:name];
4870 // XXX: else if (state.Install())
4871 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4872 [reinstalls addObject:name];
4873 // XXX: move before previous if
4874 else if (state.Upgrade())
4875 [upgrades addObject:name];
4876 else if (state.Downgrade())
4877 [downgrades addObject:name];
4878 else if (!state.Delete())
4879 // XXX: _assert(state.Keep());
4880 continue;
4881 else if (special_r(name))
4882 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4883 [NSNull null], @"package",
4884 [NSArray arrayWithObjects:
4885 [NSDictionary dictionaryWithObjectsAndKeys:
4886 @"Conflicts", @"relationship",
4887 [NSArray arrayWithObjects:
4888 [NSDictionary dictionaryWithObjectsAndKeys:
4889 name, @"package",
4890 [NSNull null], @"version",
4891 @"installed", @"reason",
4892 nil],
4893 nil], @"clauses",
4894 nil],
4895 nil], @"reasons",
4896 nil]];
4897 else {
4898 if ([package essential])
4899 remove = true;
4900 [removes addObject:name];
4901 }
4902
4903 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4904 substrate_ |= DepSubstrate(iterator.CurrentVer());
4905 }
4906
4907 if (!remove)
4908 essential_ = nil;
4909 else if (Advanced_) {
4910 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4911
4912 essential_ = [[[UIAlertView alloc]
4913 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4914 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4915 delegate:self
4916 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4917 otherButtonTitles:
4918 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4919 nil
4920 ] autorelease];
4921
4922 [essential_ setContext:@"remove"];
4923 } else {
4924 essential_ = [[[UIAlertView alloc]
4925 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4926 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4927 delegate:self
4928 cancelButtonTitle:UCLocalize("OKAY")
4929 otherButtonTitles:nil
4930 ] autorelease];
4931
4932 [essential_ setContext:@"unable"];
4933 }
4934
4935 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4936 installs, @"installs",
4937 reinstalls, @"reinstalls",
4938 upgrades, @"upgrades",
4939 downgrades, @"downgrades",
4940 removes, @"removes",
4941 nil];
4942
4943 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4944 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4945 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4946 nil];
4947
4948 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4949 } return self;
4950 }
4951
4952 - (UIBarButtonItem *) leftButton {
4953 return [[[UIBarButtonItem alloc]
4954 initWithTitle:UCLocalize("CANCEL")
4955 style:UIBarButtonItemStylePlain
4956 target:self
4957 action:@selector(cancelButtonClicked)
4958 ] autorelease];
4959 }
4960
4961 #if !AlwaysReload
4962 - (void) applyRightButton {
4963 if ([issues_ count] == 0 && ![self isLoading])
4964 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4965 initWithTitle:UCLocalize("CONFIRM")
4966 style:UIBarButtonItemStyleDone
4967 target:self
4968 action:@selector(confirmButtonClicked)
4969 ] autorelease]];
4970 else
4971 [[self navigationItem] setRightBarButtonItem:nil];
4972 }
4973 #endif
4974
4975 - (void) cancelButtonClicked {
4976 [self dismissModalViewControllerAnimated:YES];
4977 [delegate_ cancelAndClear:YES];
4978 }
4979
4980 #if !AlwaysReload
4981 - (void) confirmButtonClicked {
4982 if (essential_ != nil)
4983 [essential_ show];
4984 else
4985 [self complete];
4986 }
4987 #endif
4988
4989 @end
4990 /* }}} */
4991
4992 /* Progress Data {{{ */
4993 @interface CydiaProgressData : NSObject {
4994 _transient id delegate_;
4995
4996 bool running_;
4997 float percent_;
4998
4999 float current_;
5000 float total_;
5001 float speed_;
5002
5003 _H<NSMutableArray> events_;
5004 _H<NSString> title_;
5005
5006 _H<NSString> status_;
5007 _H<NSString> finish_;
5008 }
5009
5010 @end
5011
5012 @implementation CydiaProgressData
5013
5014 + (NSArray *) _attributeKeys {
5015 return [NSArray arrayWithObjects:
5016 @"current",
5017 @"events",
5018 @"finish",
5019 @"percent",
5020 @"running",
5021 @"speed",
5022 @"title",
5023 @"total",
5024 nil];
5025 }
5026
5027 - (NSArray *) attributeKeys {
5028 return [[self class] _attributeKeys];
5029 }
5030
5031 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5032 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5033 }
5034
5035 - (id) init {
5036 if ((self = [super init]) != nil) {
5037 events_ = [NSMutableArray arrayWithCapacity:32];
5038 } return self;
5039 }
5040
5041 - (void) setDelegate:(id)delegate {
5042 delegate_ = delegate;
5043 }
5044
5045 - (void) setPercent:(float)value {
5046 percent_ = value;
5047 }
5048
5049 - (NSNumber *) percent {
5050 return [NSNumber numberWithFloat:percent_];
5051 }
5052
5053 - (void) setCurrent:(float)value {
5054 current_ = value;
5055 }
5056
5057 - (NSNumber *) current {
5058 return [NSNumber numberWithFloat:current_];
5059 }
5060
5061 - (void) setTotal:(float)value {
5062 total_ = value;
5063 }
5064
5065 - (NSNumber *) total {
5066 return [NSNumber numberWithFloat:total_];
5067 }
5068
5069 - (void) setSpeed:(float)value {
5070 speed_ = value;
5071 }
5072
5073 - (NSNumber *) speed {
5074 return [NSNumber numberWithFloat:speed_];
5075 }
5076
5077 - (NSArray *) events {
5078 return events_;
5079 }
5080
5081 - (void) removeAllEvents {
5082 [events_ removeAllObjects];
5083 }
5084
5085 - (void) addEvent:(CydiaProgressEvent *)event {
5086 [events_ addObject:event];
5087 }
5088
5089 - (void) setTitle:(NSString *)text {
5090 title_ = text;
5091 }
5092
5093 - (NSString *) title {
5094 return title_;
5095 }
5096
5097 - (void) setFinish:(NSString *)text {
5098 finish_ = text;
5099 }
5100
5101 - (NSString *) finish {
5102 return (id) finish_ ?: [NSNull null];
5103 }
5104
5105 - (void) setRunning:(bool)running {
5106 running_ = running;
5107 }
5108
5109 - (NSNumber *) running {
5110 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5111 }
5112
5113 @end
5114 /* }}} */
5115 /* Progress Controller {{{ */
5116 @interface ProgressController : CydiaWebViewController <
5117 ProgressDelegate
5118 > {
5119 _transient Database *database_;
5120 _H<CydiaProgressData, 1> progress_;
5121 unsigned cancel_;
5122 }
5123
5124 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5125
5126 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5127
5128 - (void) setTitle:(NSString *)title;
5129 - (void) setCancellable:(bool)cancellable;
5130
5131 @end
5132
5133 @implementation ProgressController
5134
5135 - (void) dealloc {
5136 [database_ setProgressDelegate:nil];
5137 [super dealloc];
5138 }
5139
5140 - (UIBarButtonItem *) leftButton {
5141 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5142 initWithTitle:UCLocalize("CANCEL")
5143 style:UIBarButtonItemStylePlain
5144 target:self
5145 action:@selector(cancel)
5146 ] autorelease] : nil;
5147 }
5148
5149 - (void) updateCancel {
5150 [super applyLeftButton];
5151 }
5152
5153 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5154 if ((self = [super init]) != nil) {
5155 database_ = database;
5156 delegate_ = delegate;
5157
5158 [database_ setProgressDelegate:self];
5159
5160 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5161 [progress_ setDelegate:self];
5162
5163 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5164
5165 [scroller_ setBackgroundColor:[UIColor blackColor]];
5166
5167 [[self navigationItem] setHidesBackButton:YES];
5168
5169 [self updateCancel];
5170 } return self;
5171 }
5172
5173 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5174 [super webView:view didClearWindowObject:window forFrame:frame];
5175 [window setValue:progress_ forKey:@"cydiaProgress"];
5176 }
5177
5178 - (void) updateProgress {
5179 [self dispatchEvent:@"CydiaProgressUpdate"];
5180 }
5181
5182 - (void) viewWillAppear:(BOOL)animated {
5183 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5184 [super viewWillAppear:animated];
5185 }
5186
5187 - (void) close {
5188 UpdateExternalStatus(0);
5189
5190 if (Finish_ > 1)
5191 [delegate_ saveState];
5192
5193 switch (Finish_) {
5194 case 0:
5195 [delegate_ returnToCydia];
5196 break;
5197
5198 case 1:
5199 [delegate_ terminateWithSuccess];
5200 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5201 [delegate_ suspendWithAnimation:YES];
5202 else
5203 [delegate_ suspend];*/
5204 break;
5205
5206 case 2:
5207 _trace();
5208 goto reload;
5209
5210 case 3:
5211 _trace();
5212 goto reload;
5213
5214 reload:
5215 system("/usr/bin/sbreload");
5216 _trace();
5217 break;
5218
5219 case 4:
5220 _trace();
5221 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5222 SBReboot(SBSSpringBoardServerPort());
5223 else
5224 reboot2(RB_AUTOBOOT);
5225 break;
5226 }
5227
5228 [super close];
5229 }
5230
5231 - (void) setTitle:(NSString *)title {
5232 [progress_ setTitle:title];
5233 [self updateProgress];
5234 }
5235
5236 - (UIBarButtonItem *) rightButton {
5237 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5238 initWithTitle:UCLocalize("CLOSE")
5239 style:UIBarButtonItemStylePlain
5240 target:self
5241 action:@selector(close)
5242 ] autorelease];
5243 }
5244
5245 - (void) uicache {
5246 _trace();
5247 system("su -c /usr/bin/uicache mobile");
5248 _trace();
5249 }
5250
5251 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5252 UpdateExternalStatus(1);
5253
5254 [progress_ setRunning:true];
5255 [self setTitle:title];
5256 // implicit updateProgress
5257
5258 SHA1SumValue notifyconf; {
5259 FileFd file;
5260 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5261 _error->Discard();
5262 else {
5263 MMap mmap(file, MMap::ReadOnly);
5264 SHA1Summation sha1;
5265 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5266 notifyconf = sha1.Result();
5267 }
5268 }
5269
5270 SHA1SumValue springlist; {
5271 FileFd file;
5272 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5273 _error->Discard();
5274 else {
5275 MMap mmap(file, MMap::ReadOnly);
5276 SHA1Summation sha1;
5277 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5278 springlist = sha1.Result();
5279 }
5280 }
5281
5282 if (invocation != nil) {
5283 [invocation yieldToSelector:@selector(invoke)];
5284 [self setTitle:@"COMPLETE"];
5285 }
5286
5287 if (Finish_ < 4) {
5288 FileFd file;
5289 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5290 _error->Discard();
5291 else {
5292 MMap mmap(file, MMap::ReadOnly);
5293 SHA1Summation sha1;
5294 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5295 if (!(notifyconf == sha1.Result()))
5296 Finish_ = 4;
5297 }
5298 }
5299
5300 if (Finish_ < 3) {
5301 FileFd file;
5302 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5303 _error->Discard();
5304 else {
5305 MMap mmap(file, MMap::ReadOnly);
5306 SHA1Summation sha1;
5307 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5308 if (!(springlist == sha1.Result()))
5309 Finish_ = 3;
5310 }
5311 }
5312
5313 if (Finish_ < 2) {
5314 if (RestartSubstrate_)
5315 Finish_ = 2;
5316 }
5317
5318 RestartSubstrate_ = false;
5319
5320 switch (Finish_) {
5321 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5322 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5323 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5324 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5325 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5326 }
5327
5328 UIProgressHUD *hud([delegate_ addProgressHUD]);
5329 [hud setText:UCLocalize("LOADING")];
5330 [self yieldToSelector:@selector(uicache)];
5331 [delegate_ removeProgressHUD:hud];
5332
5333 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5334
5335 [progress_ setRunning:false];
5336 [self updateProgress];
5337
5338 [self applyRightButton];
5339 }
5340
5341 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5342 [progress_ addEvent:event];
5343 [self updateProgress];
5344 }
5345
5346 - (bool) isProgressCancelled {
5347 return cancel_ == 2;
5348 }
5349
5350 - (void) cancel {
5351 cancel_ = 2;
5352 [self updateCancel];
5353 }
5354
5355 - (void) setCancellable:(bool)cancellable {
5356 unsigned cancel(cancel_);
5357
5358 if (!cancellable)
5359 cancel_ = 0;
5360 else if (cancel_ == 0)
5361 cancel_ = 1;
5362
5363 if (cancel != cancel_)
5364 [self updateCancel];
5365 }
5366
5367 - (void) setProgressCancellable:(NSNumber *)cancellable {
5368 [self setCancellable:[cancellable boolValue]];
5369 }
5370
5371 - (void) setProgressPercent:(NSNumber *)percent {
5372 [progress_ setPercent:[percent floatValue]];
5373 [self updateProgress];
5374 }
5375
5376 - (void) setProgressStatus:(NSDictionary *)status {
5377 if (status == nil) {
5378 [progress_ setCurrent:0];
5379 [progress_ setTotal:0];
5380 [progress_ setSpeed:0];
5381 } else {
5382 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5383
5384 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5385 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5386 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5387 }
5388
5389 [self updateProgress];
5390 }
5391
5392 @end
5393 /* }}} */
5394
5395 /* Package Cell {{{ */
5396 @interface PackageCell : CyteTableViewCell <
5397 CyteTableViewCellDelegate
5398 > {
5399 _H<UIImage> icon_;
5400 _H<NSString> name_;
5401 _H<NSString> description_;
5402 bool commercial_;
5403 _H<NSString> source_;
5404 _H<UIImage> badge_;
5405 _H<UIImage> placard_;
5406 bool summarized_;
5407 }
5408
5409 - (PackageCell *) init;
5410 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5411
5412 - (void) drawContentRect:(CGRect)rect;
5413
5414 @end
5415
5416 @implementation PackageCell
5417
5418 - (PackageCell *) init {
5419 CGRect frame(CGRectMake(0, 0, 320, 74));
5420 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5421 UIView *content([self contentView]);
5422 CGRect bounds([content bounds]);
5423
5424 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5425 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5426 [content addSubview:content_];
5427
5428 [content_ setDelegate:self];
5429 [content_ setOpaque:YES];
5430 } return self;
5431 }
5432
5433 - (NSString *) accessibilityLabel {
5434 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5435 }
5436
5437 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5438 summarized_ = summary;
5439
5440 icon_ = nil;
5441 name_ = nil;
5442 description_ = nil;
5443 source_ = nil;
5444 badge_ = nil;
5445 placard_ = nil;
5446
5447 if (package == nil)
5448 [content_ setBackgroundColor:[UIColor whiteColor]];
5449 else {
5450 [package parse];
5451
5452 Source *source = [package source];
5453
5454 icon_ = [package icon];
5455
5456 if (NSString *name = [package name])
5457 name_ = [NSString stringWithString:name];
5458
5459 NSString *description(nil);
5460
5461 if (description == nil && IsWildcat_)
5462 description = [package longDescription];
5463 if (description == nil)
5464 description = [package shortDescription];
5465
5466 if (description != nil)
5467 description_ = [NSString stringWithString:description];
5468
5469 commercial_ = [package isCommercial];
5470
5471 NSString *label = nil;
5472 bool trusted = false;
5473
5474 if (source != nil) {
5475 label = [source label];
5476 trusted = [source trusted];
5477 } else if ([[package id] isEqualToString:@"firmware"])
5478 label = UCLocalize("APPLE");
5479 else
5480 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5481
5482 NSString *from(label);
5483
5484 NSString *section = [package simpleSection];
5485 if (section != nil && ![section isEqualToString:label]) {
5486 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5487 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5488 }
5489
5490 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5491
5492 if (NSString *purpose = [package primaryPurpose])
5493 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5494
5495 UIColor *color;
5496 NSString *placard;
5497
5498 if (NSString *mode = [package mode]) {
5499 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5500 color = RemovingColor_;
5501 //placard = @"removing";
5502 } else {
5503 color = InstallingColor_;
5504 //placard = @"installing";
5505 }
5506
5507 // XXX: the removing/installing placards are not @2x
5508 placard = nil;
5509 } else {
5510 color = [UIColor whiteColor];
5511
5512 if ([package installed] != nil)
5513 placard = @"installed";
5514 else
5515 placard = nil;
5516 }
5517
5518 [content_ setBackgroundColor:color];
5519
5520 if (placard != nil)
5521 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5522 }
5523
5524 [self setNeedsDisplay];
5525 [content_ setNeedsDisplay];
5526 }
5527
5528 - (void) drawSummaryContentRect:(CGRect)rect {
5529 bool highlighted(highlighted_);
5530 float width([self bounds].size.width);
5531
5532 if (icon_ != nil) {
5533 CGRect rect;
5534 rect.size = [(UIImage *) icon_ size];
5535
5536 while (rect.size.width > 16 || rect.size.height > 16) {
5537 rect.size.width /= 2;
5538 rect.size.height /= 2;
5539 }
5540
5541 rect.origin.x = 18 - rect.size.width / 2;
5542 rect.origin.y = 18 - rect.size.height / 2;
5543
5544 [icon_ drawInRect:rect];
5545 }
5546
5547 if (badge_ != nil) {
5548 CGRect rect;
5549 rect.size = [(UIImage *) badge_ size];
5550
5551 rect.size.width /= 4;
5552 rect.size.height /= 4;
5553
5554 rect.origin.x = 23 - rect.size.width / 2;
5555 rect.origin.y = 23 - rect.size.height / 2;
5556
5557 [badge_ drawInRect:rect];
5558 }
5559
5560 if (highlighted)
5561 UISetColor(White_);
5562
5563 if (!highlighted)
5564 UISetColor(commercial_ ? Purple_ : Black_);
5565 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5566
5567 if (placard_ != nil)
5568 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5569 }
5570
5571 - (void) drawNormalContentRect:(CGRect)rect {
5572 bool highlighted(highlighted_);
5573 float width([self bounds].size.width);
5574
5575 if (icon_ != nil) {
5576 CGRect rect;
5577 rect.size = [(UIImage *) icon_ size];
5578
5579 while (rect.size.width > 32 || rect.size.height > 32) {
5580 rect.size.width /= 2;
5581 rect.size.height /= 2;
5582 }
5583
5584 rect.origin.x = 25 - rect.size.width / 2;
5585 rect.origin.y = 25 - rect.size.height / 2;
5586
5587 [icon_ drawInRect:rect];
5588 }
5589
5590 if (badge_ != nil) {
5591 CGRect rect;
5592 rect.size = [(UIImage *) badge_ size];
5593
5594 rect.size.width /= 2;
5595 rect.size.height /= 2;
5596
5597 rect.origin.x = 36 - rect.size.width / 2;
5598 rect.origin.y = 36 - rect.size.height / 2;
5599
5600 [badge_ drawInRect:rect];
5601 }
5602
5603 if (highlighted)
5604 UISetColor(White_);
5605
5606 if (!highlighted)
5607 UISetColor(commercial_ ? Purple_ : Black_);
5608 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5609 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5610
5611 if (!highlighted)
5612 UISetColor(commercial_ ? Purplish_ : Gray_);
5613 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5614
5615 if (placard_ != nil)
5616 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5617 }
5618
5619 - (void) drawContentRect:(CGRect)rect {
5620 if (summarized_)
5621 [self drawSummaryContentRect:rect];
5622 else
5623 [self drawNormalContentRect:rect];
5624 }
5625
5626 @end
5627 /* }}} */
5628 /* Section Cell {{{ */
5629 @interface SectionCell : CyteTableViewCell <
5630 CyteTableViewCellDelegate
5631 > {
5632 _H<NSString> basic_;
5633 _H<NSString> section_;
5634 _H<NSString> name_;
5635 _H<NSString> count_;
5636 _H<UIImage> icon_;
5637 _H<UISwitch> switch_;
5638 BOOL editing_;
5639 }
5640
5641 - (void) setSection:(Section *)section editing:(BOOL)editing;
5642
5643 @end
5644
5645 @implementation SectionCell
5646
5647 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5648 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5649 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5650 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5651 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5652
5653 UIView *content([self contentView]);
5654 CGRect bounds([content bounds]);
5655
5656 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5657 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5658 [content addSubview:content_];
5659 [content_ setBackgroundColor:[UIColor whiteColor]];
5660
5661 [content_ setDelegate:self];
5662 } return self;
5663 }
5664
5665 - (void) onSwitch:(id)sender {
5666 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5667 if (metadata == nil) {
5668 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5669 [Sections_ setObject:metadata forKey:basic_];
5670 }
5671
5672 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5673 Changed_ = true;
5674 }
5675
5676 - (void) setSection:(Section *)section editing:(BOOL)editing {
5677 if (editing != editing_) {
5678 if (editing_)
5679 [switch_ removeFromSuperview];
5680 else
5681 [self addSubview:switch_];
5682 editing_ = editing;
5683 }
5684
5685 basic_ = nil;
5686 section_ = nil;
5687 name_ = nil;
5688 count_ = nil;
5689
5690 if (section == nil) {
5691 name_ = UCLocalize("ALL_PACKAGES");
5692 count_ = nil;
5693 } else {
5694 basic_ = [section name];
5695 section_ = [section localized];
5696
5697 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5698 count_ = [NSString stringWithFormat:@"%d", [section count]];
5699
5700 if (editing_)
5701 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5702 }
5703
5704 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5705 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5706
5707 [content_ setNeedsDisplay];
5708 }
5709
5710 - (void) setFrame:(CGRect)frame {
5711 [super setFrame:frame];
5712
5713 CGRect rect([switch_ frame]);
5714 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5715 }
5716
5717 - (NSString *) accessibilityLabel {
5718 return name_;
5719 }
5720
5721 - (void) drawContentRect:(CGRect)rect {
5722 bool highlighted(highlighted_ && !editing_);
5723
5724 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5725
5726 if (highlighted)
5727 UISetColor(White_);
5728
5729 float width(rect.size.width);
5730 if (editing_)
5731 width -= 87;
5732
5733 if (!highlighted)
5734 UISetColor(Black_);
5735 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5736
5737 CGSize size = [count_ sizeWithFont:Font14_];
5738
5739 UISetColor(White_);
5740 if (count_ != nil)
5741 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5742 }
5743
5744 @end
5745 /* }}} */
5746
5747 /* File Table {{{ */
5748 @interface FileTable : CyteViewController <
5749 UITableViewDataSource,
5750 UITableViewDelegate
5751 > {
5752 _transient Database *database_;
5753 _H<Package> package_;
5754 _H<NSString> name_;
5755 _H<NSMutableArray> files_;
5756 _H<UITableView, 2> list_;
5757 }
5758
5759 - (id) initWithDatabase:(Database *)database;
5760 - (void) setPackage:(Package *)package;
5761
5762 @end
5763
5764 @implementation FileTable
5765
5766 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5767 return files_ == nil ? 0 : [files_ count];
5768 }
5769
5770 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5771 return 24.0f;
5772 }*/
5773
5774 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5775 static NSString *reuseIdentifier = @"Cell";
5776
5777 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5778 if (cell == nil) {
5779 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5780 [cell setFont:[UIFont systemFontOfSize:16]];
5781 }
5782 [cell setText:[files_ objectAtIndex:indexPath.row]];
5783 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5784
5785 return cell;
5786 }
5787
5788 - (NSURL *) navigationURL {
5789 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5790 }
5791
5792 - (void) loadView {
5793 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5794 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5795 [list_ setRowHeight:24.0f];
5796 [(UITableView *) list_ setDataSource:self];
5797 [list_ setDelegate:self];
5798 [self setView:list_];
5799 }
5800
5801 - (void) viewDidLoad {
5802 [super viewDidLoad];
5803
5804 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5805 }
5806
5807 - (void) releaseSubviews {
5808 list_ = nil;
5809
5810 package_ = nil;
5811 files_ = nil;
5812
5813 [super releaseSubviews];
5814 }
5815
5816 - (id) initWithDatabase:(Database *)database {
5817 if ((self = [super init]) != nil) {
5818 database_ = database;
5819 } return self;
5820 }
5821
5822 - (void) setPackage:(Package *)package {
5823 package_ = nil;
5824 name_ = nil;
5825
5826 files_ = [NSMutableArray arrayWithCapacity:32];
5827
5828 if (package != nil) {
5829 package_ = package;
5830 name_ = [package id];
5831
5832 if (NSArray *files = [package files])
5833 [files_ addObjectsFromArray:files];
5834
5835 if ([files_ count] != 0) {
5836 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5837 [files_ removeObjectAtIndex:0];
5838 [files_ sortUsingSelector:@selector(compareByPath:)];
5839
5840 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5841 [stack addObject:@"/"];
5842
5843 for (int i(0), e([files_ count]); i != e; ++i) {
5844 NSString *file = [files_ objectAtIndex:i];
5845 while (![file hasPrefix:[stack lastObject]])
5846 [stack removeLastObject];
5847 NSString *directory = [stack lastObject];
5848 [stack addObject:[file stringByAppendingString:@"/"]];
5849 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5850 ([stack count] - 2) * 3, "",
5851 [file substringFromIndex:[directory length]]
5852 ]];
5853 }
5854 }
5855 }
5856
5857 [list_ reloadData];
5858 }
5859
5860 - (void) reloadData {
5861 [super reloadData];
5862
5863 [self setPackage:[database_ packageWithName:name_]];
5864 }
5865
5866 @end
5867 /* }}} */
5868 /* Package Controller {{{ */
5869 @interface CYPackageController : CydiaWebViewController <
5870 UIActionSheetDelegate
5871 > {
5872 _transient Database *database_;
5873 _H<Package> package_;
5874 _H<NSString> name_;
5875 bool commercial_;
5876 _H<NSMutableArray> buttons_;
5877 _H<UIBarButtonItem> button_;
5878 }
5879
5880 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5881
5882 @end
5883
5884 @implementation CYPackageController
5885
5886 - (NSURL *) navigationURL {
5887 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5888 }
5889
5890 /* XXX: this is not safe at all... localization of /fail/ */
5891 - (void) _clickButtonWithName:(NSString *)name {
5892 if ([name isEqualToString:UCLocalize("CLEAR")])
5893 [delegate_ clearPackage:package_];
5894 else if ([name isEqualToString:UCLocalize("INSTALL")])
5895 [delegate_ installPackage:package_];
5896 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5897 [delegate_ installPackage:package_];
5898 else if ([name isEqualToString:UCLocalize("REMOVE")])
5899 [delegate_ removePackage:package_];
5900 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5901 [delegate_ installPackage:package_];
5902 else _assert(false);
5903 }
5904
5905 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5906 NSString *context([sheet context]);
5907
5908 if ([context isEqualToString:@"modify"]) {
5909 if (button != [sheet cancelButtonIndex]) {
5910 NSString *buttonName = [buttons_ objectAtIndex:button];
5911 [self _clickButtonWithName:buttonName];
5912 }
5913
5914 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5915 }
5916 }
5917
5918 - (bool) _allowJavaScriptPanel {
5919 return commercial_;
5920 }
5921
5922 #if !AlwaysReload
5923 - (void) _customButtonClicked {
5924 int count([buttons_ count]);
5925 if (count == 0)
5926 return;
5927
5928 if (count == 1)
5929 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5930 else {
5931 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5932 [buttons addObjectsFromArray:buttons_];
5933
5934 UIActionSheet *sheet = [[[UIActionSheet alloc]
5935 initWithTitle:nil
5936 delegate:self
5937 cancelButtonTitle:nil
5938 destructiveButtonTitle:nil
5939 otherButtonTitles:nil
5940 ] autorelease];
5941
5942 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5943 if (!IsWildcat_) {
5944 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5945 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5946 }
5947 [sheet setContext:@"modify"];
5948
5949 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5950 }
5951 }
5952
5953 // We don't want to allow non-commercial packages to do custom things to the install button,
5954 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5955 - (void) customButtonClicked {
5956 if (commercial_)
5957 [super customButtonClicked];
5958 else
5959 [self _customButtonClicked];
5960 }
5961
5962 - (void) reloadButtonClicked {
5963 // Don't reload a commerical package by tapping the loading button,
5964 // but if it's not an Install button, we should forward it on.
5965 if (![package_ uninstalled])
5966 [self _customButtonClicked];
5967 }
5968
5969 - (void) applyLoadingTitle {
5970 // Don't show "Loading" as the title. Ever.
5971 }
5972
5973 - (UIBarButtonItem *) rightButton {
5974 return button_;
5975 }
5976 #endif
5977
5978 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5979 if ((self = [super init]) != nil) {
5980 database_ = database;
5981 buttons_ = [NSMutableArray arrayWithCapacity:4];
5982 name_ = name == nil ? @"" : [NSString stringWithString:name];
5983 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5984 } return self;
5985 }
5986
5987 - (void) reloadData {
5988 [super reloadData];
5989
5990 package_ = [database_ packageWithName:name_];
5991
5992 [buttons_ removeAllObjects];
5993
5994 if (package_ != nil) {
5995 [(Package *) package_ parse];
5996
5997 commercial_ = [package_ isCommercial];
5998
5999 if ([package_ mode] != nil)
6000 [buttons_ addObject:UCLocalize("CLEAR")];
6001 if ([package_ source] == nil);
6002 else if ([package_ upgradableAndEssential:NO])
6003 [buttons_ addObject:UCLocalize("UPGRADE")];
6004 else if ([package_ uninstalled])
6005 [buttons_ addObject:UCLocalize("INSTALL")];
6006 else
6007 [buttons_ addObject:UCLocalize("REINSTALL")];
6008 if (![package_ uninstalled])
6009 [buttons_ addObject:UCLocalize("REMOVE")];
6010 }
6011
6012 NSString *title;
6013 switch ([buttons_ count]) {
6014 case 0: title = nil; break;
6015 case 1: title = [buttons_ objectAtIndex:0]; break;
6016 default: title = UCLocalize("MODIFY"); break;
6017 }
6018
6019 button_ = [[[UIBarButtonItem alloc]
6020 initWithTitle:title
6021 style:UIBarButtonItemStylePlain
6022 target:self
6023 action:@selector(customButtonClicked)
6024 ] autorelease];
6025 }
6026
6027 - (bool) isLoading {
6028 return commercial_ ? [super isLoading] : false;
6029 }
6030
6031 @end
6032 /* }}} */
6033
6034 /* Package List Controller {{{ */
6035 @interface PackageListController : CyteViewController <
6036 UITableViewDataSource,
6037 UITableViewDelegate
6038 > {
6039 _transient Database *database_;
6040 unsigned era_;
6041 _H<NSArray> packages_;
6042 _H<NSMutableArray> sections_;
6043 _H<UITableView, 2> list_;
6044 _H<NSMutableArray> index_;
6045 _H<NSMutableDictionary> indices_;
6046 _H<NSString> title_;
6047 unsigned reloading_;
6048 }
6049
6050 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6051 - (void) setDelegate:(id)delegate;
6052 - (void) resetCursor;
6053 - (void) clearData;
6054
6055 @end
6056
6057 @implementation PackageListController
6058
6059 - (bool) isSummarized {
6060 return false;
6061 }
6062
6063 - (bool) showsSections {
6064 return true;
6065 }
6066
6067 - (void) deselectWithAnimation:(BOOL)animated {
6068 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6069 }
6070
6071 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6072 CGRect base = [[self view] bounds];
6073 base.size.height -= bounds.size.height;
6074 base.origin = [list_ frame].origin;
6075
6076 [UIView beginAnimations:nil context:NULL];
6077 [UIView setAnimationBeginsFromCurrentState:YES];
6078 [UIView setAnimationCurve:curve];
6079 [UIView setAnimationDuration:duration];
6080 [list_ setFrame:base];
6081 [UIView commitAnimations];
6082 }
6083
6084 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6085 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6086 }
6087
6088 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6089 [self resizeForKeyboardBounds:bounds duration:0];
6090 }
6091
6092 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6093 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6094 *curve = UIViewAnimationCurveEaseInOut;
6095 else
6096 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6097
6098 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6099 *duration = 0.3;
6100 else
6101 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6102 }
6103
6104 - (void) keyboardWillShow:(NSNotification *)notification {
6105 CGRect bounds;
6106 CGPoint center;
6107 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6108 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6109
6110 NSTimeInterval duration;
6111 UIViewAnimationCurve curve;
6112 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6113
6114 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);
6115 UIViewController *base = self;
6116 while ([base parentViewController] != nil)
6117 base = [base parentViewController];
6118 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6119 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6120
6121 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6122 intersection.size.height += CYStatusBarHeight();
6123
6124 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6125 }
6126
6127 - (void) keyboardWillHide:(NSNotification *)notification {
6128 NSTimeInterval duration;
6129 UIViewAnimationCurve curve;
6130 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6131
6132 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6133 }
6134
6135 - (void) viewWillAppear:(BOOL)animated {
6136 [super viewWillAppear:animated];
6137
6138 [self resizeForKeyboardBounds:CGRectZero];
6139 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6140 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6141 }
6142
6143 - (void) viewWillDisappear:(BOOL)animated {
6144 [super viewWillDisappear:animated];
6145
6146 [self resizeForKeyboardBounds:CGRectZero];
6147 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6148 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6149 }
6150
6151 - (void) viewDidAppear:(BOOL)animated {
6152 [super viewDidAppear:animated];
6153 [self deselectWithAnimation:animated];
6154 }
6155
6156 - (void) didSelectPackage:(Package *)package {
6157 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6158 [view setDelegate:delegate_];
6159 [[self navigationController] pushViewController:view animated:YES];
6160 }
6161
6162 #if TryIndexedCollation
6163 + (BOOL) hasIndexedCollation {
6164 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6165 }
6166 #endif
6167
6168 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6169 NSInteger count([sections_ count]);
6170 return count == 0 ? 1 : count;
6171 }
6172
6173 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6174 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6175 return nil;
6176 return [[sections_ objectAtIndex:section] name];
6177 }
6178
6179 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6180 if ([sections_ count] == 0)
6181 return 0;
6182 return [[sections_ objectAtIndex:section] count];
6183 }
6184
6185 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6186 @synchronized (database_) {
6187 if ([database_ era] != era_)
6188 return nil;
6189
6190 Section *section([sections_ objectAtIndex:[path section]]);
6191 NSInteger row([path row]);
6192 Package *package([packages_ objectAtIndex:([section row] + row)]);
6193 return [[package retain] autorelease];
6194 } }
6195
6196 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6197 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6198 if (cell == nil)
6199 cell = [[[PackageCell alloc] init] autorelease];
6200
6201 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6202 [cell setPackage:package asSummary:[self isSummarized]];
6203 return cell;
6204 }
6205
6206 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6207 Package *package([self packageAtIndexPath:path]);
6208 package = [database_ packageWithName:[package id]];
6209 [self didSelectPackage:package];
6210 }
6211
6212 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6213 if (![self showsSections])
6214 return nil;
6215
6216 return index_;
6217 }
6218
6219 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6220 #if TryIndexedCollation
6221 if ([[self class] hasIndexedCollation]) {
6222 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6223 }
6224 #endif
6225
6226 return index;
6227 }
6228
6229 - (void) updateHeight {
6230 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6231 }
6232
6233 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6234 if ((self = [super init]) != nil) {
6235 database_ = database;
6236 title_ = [title copy];
6237 [[self navigationItem] setTitle:title_];
6238 } return self;
6239 }
6240
6241 - (void) loadView {
6242 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6243 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6244 [self setView:view];
6245
6246 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6247 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6248 [view addSubview:list_];
6249
6250 // XXX: is 20 the most optimal number here?
6251 [list_ setSectionIndexMinimumDisplayRowCount:20];
6252
6253 [(UITableView *) list_ setDataSource:self];
6254 [list_ setDelegate:self];
6255
6256 [self updateHeight];
6257 }
6258
6259 - (void) releaseSubviews {
6260 list_ = nil;
6261
6262 packages_ = nil;
6263 sections_ = nil;
6264 index_ = nil;
6265 indices_ = nil;
6266
6267 [super releaseSubviews];
6268 }
6269
6270 - (void) setDelegate:(id)delegate {
6271 delegate_ = delegate;
6272 }
6273
6274 - (bool) shouldYield {
6275 return false;
6276 }
6277
6278 - (bool) shouldBlock {
6279 return false;
6280 }
6281
6282 - (NSMutableArray *) _reloadPackages {
6283 @synchronized (database_) {
6284 era_ = [database_ era];
6285 NSArray *packages([database_ packages]);
6286
6287 return [NSMutableArray arrayWithArray:packages];
6288 } }
6289
6290 - (void) _reloadData {
6291 if (reloading_ != 0) {
6292 reloading_ = 2;
6293 return;
6294 }
6295
6296 NSArray *packages;
6297
6298 reload:
6299 if ([self shouldYield]) {
6300 do {
6301 UIProgressHUD *hud;
6302
6303 if (![self shouldBlock])
6304 hud = nil;
6305 else {
6306 hud = [delegate_ addProgressHUD];
6307 [hud setText:UCLocalize("LOADING")];
6308 }
6309
6310 reloading_ = 1;
6311 packages = [self yieldToSelector:@selector(_reloadPackages)];
6312
6313 if (hud != nil)
6314 [delegate_ removeProgressHUD:hud];
6315 } while (reloading_ == 2);
6316 } else {
6317 packages = [self _reloadPackages];
6318 }
6319
6320 @synchronized (database_) {
6321 if (era_ != [database_ era])
6322 goto reload;
6323 reloading_ = 0;
6324
6325 packages_ = packages;
6326
6327 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6328 sections_ = [NSMutableArray arrayWithCapacity:16];
6329
6330 Section *section = nil;
6331
6332 #if TryIndexedCollation
6333 if ([[self class] hasIndexedCollation]) {
6334 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6335
6336 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6337 NSArray *titles = [collation sectionIndexTitles];
6338 int secidx = -1;
6339
6340 _profile(PackageTable$reloadData$Section)
6341 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6342 Package *package;
6343 int index;
6344
6345 _profile(PackageTable$reloadData$Section$Package)
6346 package = [packages_ objectAtIndex:offset];
6347 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6348 _end
6349
6350 while (secidx < index) {
6351 secidx += 1;
6352
6353 _profile(PackageTable$reloadData$Section$Allocate)
6354 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6355 _end
6356
6357 _profile(PackageTable$reloadData$Section$Add)
6358 [sections_ addObject:section];
6359 _end
6360 }
6361
6362 [section addToCount];
6363 }
6364 _end
6365 } else
6366 #endif
6367 {
6368 index_ = [NSMutableArray arrayWithCapacity:32];
6369
6370 bool sectioned([self showsSections]);
6371 if (!sectioned) {
6372 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6373 [sections_ addObject:section];
6374 }
6375
6376 _profile(PackageTable$reloadData$Section)
6377 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6378 Package *package;
6379 unichar index;
6380
6381 _profile(PackageTable$reloadData$Section$Package)
6382 package = [packages_ objectAtIndex:offset];
6383 index = [package index];
6384 _end
6385
6386 if (sectioned && (section == nil || [section index] != index)) {
6387 _profile(PackageTable$reloadData$Section$Allocate)
6388 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6389 _end
6390
6391 [index_ addObject:[section name]];
6392 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6393
6394 _profile(PackageTable$reloadData$Section$Add)
6395 [sections_ addObject:section];
6396 _end
6397 }
6398
6399 [section addToCount];
6400 }
6401 _end
6402 }
6403
6404 [self updateHeight];
6405
6406 _profile(PackageTable$reloadData$List)
6407 [(UITableView *) list_ setDataSource:self];
6408 [list_ reloadData];
6409 _end
6410 } }
6411
6412 - (void) reloadData {
6413 [super reloadData];
6414
6415 if ([self shouldYield])
6416 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6417 else
6418 [self _reloadData];
6419 }
6420
6421 - (void) resetCursor {
6422 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6423 }
6424
6425 - (void) clearData {
6426 [self updateHeight];
6427
6428 [list_ setDataSource:nil];
6429 [list_ reloadData];
6430
6431 [self resetCursor];
6432 }
6433
6434 @end
6435 /* }}} */
6436 /* Filtered Package List Controller {{{ */
6437 @interface FilteredPackageListController : PackageListController {
6438 SEL filter_;
6439 IMP imp_;
6440 _H<NSObject> object_;
6441 }
6442
6443 - (void) setObject:(id)object;
6444 - (void) setObject:(id)object forFilter:(SEL)filter;
6445
6446 - (SEL) filter;
6447 - (void) setFilter:(SEL)filter;
6448
6449 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6450
6451 @end
6452
6453 @implementation FilteredPackageListController
6454
6455 - (SEL) filter {
6456 return filter_;
6457 }
6458
6459 - (void) setFilter:(SEL)filter {
6460 @synchronized (self) {
6461 filter_ = filter;
6462
6463 /* XXX: this is an unsafe optimization of doomy hell */
6464 Method method(class_getInstanceMethod([Package class], filter));
6465 _assert(method != NULL);
6466 imp_ = method_getImplementation(method);
6467 _assert(imp_ != NULL);
6468 } }
6469
6470 - (void) setObject:(id)object {
6471 @synchronized (self) {
6472 object_ = object;
6473 } }
6474
6475 - (void) setObject:(id)object forFilter:(SEL)filter {
6476 @synchronized (self) {
6477 [self setFilter:filter];
6478 [self setObject:object];
6479 } }
6480
6481 - (NSMutableArray *) _reloadPackages {
6482 @synchronized (database_) {
6483 era_ = [database_ era];
6484 NSArray *packages([database_ packages]);
6485
6486 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6487
6488 IMP imp;
6489 SEL filter;
6490 _H<NSObject> object;
6491
6492 @synchronized (self) {
6493 imp = imp_;
6494 filter = filter_;
6495 object = object_;
6496 }
6497
6498 _profile(PackageTable$reloadData$Filter)
6499 for (Package *package in packages)
6500 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6501 [filtered addObject:package];
6502 _end
6503
6504 return filtered;
6505 } }
6506
6507 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6508 if ((self = [super initWithDatabase:database title:title]) != nil) {
6509 [self setFilter:filter];
6510 [self setObject:object];
6511 } return self;
6512 }
6513
6514 @end
6515 /* }}} */
6516
6517 /* Home Controller {{{ */
6518 @interface HomeController : CydiaWebViewController {
6519 }
6520
6521 @end
6522
6523 @implementation HomeController
6524
6525 - (id) init {
6526 if ((self = [super init]) != nil) {
6527 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6528 [self reloadData];
6529 } return self;
6530 }
6531
6532 - (NSURL *) navigationURL {
6533 return [NSURL URLWithString:@"cydia://home"];
6534 }
6535
6536 - (void) aboutButtonClicked {
6537 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6538
6539 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6540 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6541 [alert setCancelButtonIndex:0];
6542
6543 [alert setMessage:
6544 @"Copyright \u00a9 2008-2011\n"
6545 "SaurikIT, LLC\n"
6546 "\n"
6547 "Jay Freeman (saurik)\n"
6548 "saurik@saurik.com\n"
6549 "http://www.saurik.com/"
6550 ];
6551
6552 [alert show];
6553 }
6554
6555 - (UIBarButtonItem *) leftButton {
6556 return [[[UIBarButtonItem alloc]
6557 initWithTitle:UCLocalize("ABOUT")
6558 style:UIBarButtonItemStylePlain
6559 target:self
6560 action:@selector(aboutButtonClicked)
6561 ] autorelease];
6562 }
6563
6564 @end
6565 /* }}} */
6566 /* Manage Controller {{{ */
6567 @interface ManageController : CydiaWebViewController {
6568 }
6569
6570 - (void) queueStatusDidChange;
6571
6572 @end
6573
6574 @implementation ManageController
6575
6576 - (id) init {
6577 if ((self = [super init]) != nil) {
6578 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6579 } return self;
6580 }
6581
6582 - (NSURL *) navigationURL {
6583 return [NSURL URLWithString:@"cydia://manage"];
6584 }
6585
6586 - (UIBarButtonItem *) leftButton {
6587 return [[[UIBarButtonItem alloc]
6588 initWithTitle:UCLocalize("SETTINGS")
6589 style:UIBarButtonItemStylePlain
6590 target:self
6591 action:@selector(settingsButtonClicked)
6592 ] autorelease];
6593 }
6594
6595 - (void) settingsButtonClicked {
6596 [delegate_ showSettings];
6597 }
6598
6599 - (void) queueButtonClicked {
6600 [delegate_ queue];
6601 }
6602
6603 - (UIBarButtonItem *) rightButton {
6604 return Queuing_ ? [[[UIBarButtonItem alloc]
6605 initWithTitle:UCLocalize("QUEUE")
6606 style:UIBarButtonItemStyleDone
6607 target:self
6608 action:@selector(queueButtonClicked)
6609 ] autorelease] : nil;
6610 }
6611
6612 - (void) queueStatusDidChange {
6613 [self applyRightButton];
6614 }
6615
6616 - (bool) isLoading {
6617 return !Queuing_ && [super isLoading];
6618 }
6619
6620 @end
6621 /* }}} */
6622
6623 /* Refresh Bar {{{ */
6624 @interface RefreshBar : UINavigationBar {
6625 _H<UIProgressIndicator> indicator_;
6626 _H<UITextLabel> prompt_;
6627 _H<UIProgressBar> progress_;
6628 _H<UINavigationButton> cancel_;
6629 }
6630
6631 @end
6632
6633 @implementation RefreshBar
6634
6635 - (void) positionViews {
6636 CGRect frame = [cancel_ frame];
6637 frame.size = [cancel_ sizeThatFits:frame.size];
6638 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6639 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6640 [cancel_ setFrame:frame];
6641
6642 CGSize prgsize = {75, 100};
6643 CGRect prgrect = {{
6644 [self frame].size.width - prgsize.width - 10,
6645 ([self frame].size.height - prgsize.height) / 2
6646 } , prgsize};
6647 [progress_ setFrame:prgrect];
6648
6649 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6650 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6651 CGRect indrect = {{indoffset, indoffset}, indsize};
6652 [indicator_ setFrame:indrect];
6653
6654 CGSize prmsize = {215, indsize.height + 4};
6655 CGRect prmrect = {{
6656 indoffset * 2 + indsize.width,
6657 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6658 }, prmsize};
6659 [prompt_ setFrame:prmrect];
6660 }
6661
6662 - (void) setFrame:(CGRect)frame {
6663 [super setFrame:frame];
6664 [self positionViews];
6665 }
6666
6667 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6668 if ((self = [super initWithFrame:frame]) != nil) {
6669 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6670
6671 [self setBarStyle:UIBarStyleBlack];
6672
6673 UIBarStyle barstyle([self _barStyle:NO]);
6674 bool ugly(barstyle == UIBarStyleDefault);
6675
6676 UIProgressIndicatorStyle style = ugly ?
6677 UIProgressIndicatorStyleMediumBrown :
6678 UIProgressIndicatorStyleMediumWhite;
6679
6680 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6681 [(UIProgressIndicator *) indicator_ setStyle:style];
6682 [indicator_ startAnimation];
6683 [self addSubview:indicator_];
6684
6685 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6686 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6687 [prompt_ setBackgroundColor:[UIColor clearColor]];
6688 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6689 [self addSubview:prompt_];
6690
6691 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6692 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6693 [(UIProgressBar *) progress_ setStyle:0];
6694 [self addSubview:progress_];
6695
6696 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6697 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6698 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6699 [cancel_ setBarStyle:barstyle];
6700
6701 [self positionViews];
6702 } return self;
6703 }
6704
6705 - (void) setCancellable:(bool)cancellable {
6706 if (cancellable)
6707 [self addSubview:cancel_];
6708 else
6709 [cancel_ removeFromSuperview];
6710 }
6711
6712 - (void) start {
6713 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6714 [progress_ setProgress:0];
6715 }
6716
6717 - (void) stop {
6718 [self setCancellable:NO];
6719 }
6720
6721 - (void) setPrompt:(NSString *)prompt {
6722 [prompt_ setText:prompt];
6723 }
6724
6725 - (void) setProgress:(float)progress {
6726 [progress_ setProgress:progress];
6727 }
6728
6729 @end
6730 /* }}} */
6731
6732 /* Cydia Navigation Controller Interface {{{ */
6733 @interface UINavigationController (Cydia)
6734
6735 - (NSArray *) navigationURLCollection;
6736 - (void) unloadData;
6737
6738 @end
6739 /* }}} */
6740
6741 /* Cydia Tab Bar Controller {{{ */
6742 @interface CYTabBarController : UITabBarController <
6743 UITabBarControllerDelegate,
6744 ProgressDelegate
6745 > {
6746 _transient Database *database_;
6747 _H<RefreshBar, 1> refreshbar_;
6748
6749 bool dropped_;
6750 bool updating_;
6751 // XXX: ok, "updatedelegate_"?...
6752 _transient NSObject<CydiaDelegate> *updatedelegate_;
6753
6754 _H<UIViewController> remembered_;
6755 _transient UIViewController *transient_;
6756 }
6757
6758 - (NSArray *) navigationURLCollection;
6759 - (void) dropBar:(BOOL)animated;
6760 - (void) beginUpdate;
6761 - (void) raiseBar:(BOOL)animated;
6762 - (BOOL) updating;
6763 - (void) unloadData;
6764
6765 @end
6766
6767 @implementation CYTabBarController
6768
6769 - (void) didReceiveMemoryWarning {
6770 [super didReceiveMemoryWarning];
6771
6772 // presenting a UINavigationController on 2.x does not update its transitionView
6773 // it thereby will not allow its topViewController to be unloaded by memory pressure
6774 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6775 UIViewController *selected([self selectedViewController]);
6776 for (UINavigationController *controller in [self viewControllers])
6777 if (controller != selected)
6778 if (UIViewController *top = [controller topViewController])
6779 [top unloadView];
6780 }
6781 }
6782
6783 - (void) setUnselectedViewController:(UIViewController *)transient {
6784 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6785 if (transient != nil) {
6786 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6787 [self setSelectedIndex:0];
6788 } return;
6789 }
6790
6791 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6792 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6793 transient = navigation;
6794
6795 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6796 if (transient != nil) {
6797 if (transient_ == nil)
6798 remembered_ = [controllers objectAtIndex:0];
6799 transient_ = transient;
6800 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6801 [controllers replaceObjectAtIndex:0 withObject:transient_];
6802 [self setSelectedIndex:0];
6803 [self setViewControllers:controllers];
6804 [self concealTabBarSelection];
6805 } else if (remembered_ != nil) {
6806 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6807 transient_ = transient;
6808 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6809 remembered_ = nil;
6810 [self setViewControllers:controllers];
6811 [self revealTabBarSelection];
6812 }
6813 }
6814
6815 - (UIViewController *) unselectedViewController {
6816 return transient_;
6817 }
6818
6819 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6820 if ([self unselectedViewController])
6821 [self setUnselectedViewController:nil];
6822
6823 // presenting a UINavigationController on 2.x does not update its transitionView
6824 // if this view was unloaded, the tranitionView may currently be presenting nothing
6825 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6826 UINavigationController *navigation((UINavigationController *) viewController);
6827 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6828 [navigation popViewControllerAnimated:NO];
6829 }
6830 }
6831
6832 - (NSArray *) navigationURLCollection {
6833 NSMutableArray *items([NSMutableArray array]);
6834
6835 // XXX: Should this deal with transient view controllers?
6836 for (id navigation in [self viewControllers]) {
6837 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6838 if (stack != nil)
6839 [items addObject:stack];
6840 }
6841
6842 return items;
6843 }
6844
6845 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6846 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6847 [self setUnselectedViewController:nil];
6848 else
6849 [super dismissModalViewControllerAnimated:YES];
6850 }
6851
6852 - (void) unloadData {
6853 [super unloadData];
6854
6855 for (UINavigationController *controller in [self viewControllers])
6856 [controller unloadData];
6857
6858 if (UIViewController *selected = [self selectedViewController])
6859 [selected reloadData];
6860
6861 if (UIViewController *unselected = [self unselectedViewController]) {
6862 [unselected unloadData];
6863 [unselected reloadData];
6864 }
6865 }
6866
6867 - (void) dealloc {
6868 [[NSNotificationCenter defaultCenter] removeObserver:self];
6869
6870 [super dealloc];
6871 }
6872
6873 - (id) initWithDatabase:(Database *)database {
6874 if ((self = [super init]) != nil) {
6875 database_ = database;
6876 [self setDelegate:self];
6877
6878 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6879 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6880
6881 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6882 } return self;
6883 }
6884
6885 - (void) setUpdate:(NSDate *)date {
6886 [self beginUpdate];
6887 }
6888
6889 - (void) beginUpdate {
6890 [(RefreshBar *) refreshbar_ start];
6891 [self dropBar:YES];
6892
6893 [updatedelegate_ retainNetworkActivityIndicator];
6894 updating_ = true;
6895
6896 [NSThread
6897 detachNewThreadSelector:@selector(performUpdate)
6898 toTarget:self
6899 withObject:nil
6900 ];
6901 }
6902
6903 - (void) performUpdate {
6904 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6905
6906 Status status;
6907 status.setDelegate(self);
6908 [database_ updateWithStatus:status];
6909
6910 [self
6911 performSelectorOnMainThread:@selector(completeUpdate)
6912 withObject:nil
6913 waitUntilDone:NO
6914 ];
6915
6916 [pool release];
6917 }
6918
6919 - (void) stopUpdateWithSelector:(SEL)selector {
6920 updating_ = false;
6921 [updatedelegate_ releaseNetworkActivityIndicator];
6922
6923 [self raiseBar:YES];
6924 [refreshbar_ stop];
6925
6926 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6927 }
6928
6929 - (void) completeUpdate {
6930 if (!updating_)
6931 return;
6932 [self stopUpdateWithSelector:@selector(reloadData)];
6933 }
6934
6935 - (void) cancelUpdate {
6936 [self stopUpdateWithSelector:@selector(updateData)];
6937 }
6938
6939 - (void) cancelPressed {
6940 [self cancelUpdate];
6941 }
6942
6943 - (BOOL) updating {
6944 return updating_;
6945 }
6946
6947 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6948 [refreshbar_ setPrompt:[event compoundMessage]];
6949 }
6950
6951 - (bool) isProgressCancelled {
6952 return !updating_;
6953 }
6954
6955 - (void) setProgressCancellable:(NSNumber *)cancellable {
6956 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6957 }
6958
6959 - (void) setProgressPercent:(NSNumber *)percent {
6960 [refreshbar_ setProgress:[percent floatValue]];
6961 }
6962
6963 - (void) setProgressStatus:(NSDictionary *)status {
6964 if (status != nil)
6965 [self setProgressPercent:[status objectForKey:@"Percent"]];
6966 }
6967
6968 - (void) setUpdateDelegate:(id)delegate {
6969 updatedelegate_ = delegate;
6970 }
6971
6972 - (UIView *) transitionView {
6973 if ([self respondsToSelector:@selector(_transitionView)])
6974 return [self _transitionView];
6975 else
6976 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6977 }
6978
6979 - (void) dropBar:(BOOL)animated {
6980 if (dropped_)
6981 return;
6982 dropped_ = true;
6983
6984 UIView *transition([self transitionView]);
6985 [[self view] addSubview:refreshbar_];
6986
6987 CGRect barframe([refreshbar_ frame]);
6988
6989 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6990 barframe.origin.y = CYStatusBarHeight();
6991 else
6992 barframe.origin.y = 0;
6993
6994 [refreshbar_ setFrame:barframe];
6995
6996 if (animated)
6997 [UIView beginAnimations:nil context:NULL];
6998
6999 CGRect viewframe = [transition frame];
7000 viewframe.origin.y += barframe.size.height;
7001 viewframe.size.height -= barframe.size.height;
7002 [transition setFrame:viewframe];
7003
7004 if (animated)
7005 [UIView commitAnimations];
7006
7007 // Ensure bar has the proper width for our view, it might have changed
7008 barframe.size.width = viewframe.size.width;
7009 [refreshbar_ setFrame:barframe];
7010 }
7011
7012 - (void) raiseBar:(BOOL)animated {
7013 if (!dropped_)
7014 return;
7015 dropped_ = false;
7016
7017 UIView *transition([self transitionView]);
7018 [refreshbar_ removeFromSuperview];
7019
7020 CGRect barframe([refreshbar_ frame]);
7021
7022 if (animated)
7023 [UIView beginAnimations:nil context:NULL];
7024
7025 CGRect viewframe = [transition frame];
7026 viewframe.origin.y -= barframe.size.height;
7027 viewframe.size.height += barframe.size.height;
7028 [transition setFrame:viewframe];
7029
7030 if (animated)
7031 [UIView commitAnimations];
7032 }
7033
7034 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7035 bool dropped(dropped_);
7036
7037 if (dropped)
7038 [self raiseBar:NO];
7039
7040 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7041
7042 if (dropped)
7043 [self dropBar:NO];
7044 }
7045
7046 - (void) statusBarFrameChanged:(NSNotification *)notification {
7047 if (dropped_) {
7048 [self raiseBar:NO];
7049 [self dropBar:NO];
7050 }
7051 }
7052
7053 @end
7054 /* }}} */
7055
7056 /* Cydia Navigation Controller Implementation {{{ */
7057 @implementation UINavigationController (Cydia)
7058
7059 - (NSArray *) navigationURLCollection {
7060 NSMutableArray *stack([NSMutableArray array]);
7061
7062 for (CyteViewController *controller in [self viewControllers]) {
7063 NSString *url = [[controller navigationURL] absoluteString];
7064 if (url != nil)
7065 [stack addObject:url];
7066 }
7067
7068 return stack;
7069 }
7070
7071 - (void) reloadData {
7072 [super reloadData];
7073
7074 UIViewController *visible([self visibleViewController]);
7075 if (visible != nil)
7076 [visible reloadData];
7077
7078 // on the iPad, this view controller is ALSO visible. :(
7079 if (IsWildcat_)
7080 if (UIViewController *top = [self topViewController])
7081 if (top != visible)
7082 [top reloadData];
7083 }
7084
7085 - (void) unloadData {
7086 for (CyteViewController *page in [self viewControllers])
7087 [page unloadData];
7088
7089 [super unloadData];
7090 }
7091
7092 @end
7093 /* }}} */
7094
7095 /* Cydia:// Protocol {{{ */
7096 @interface CydiaURLProtocol : NSURLProtocol {
7097 }
7098
7099 @end
7100
7101 @implementation CydiaURLProtocol
7102
7103 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7104 NSURL *url([request URL]);
7105 if (url == nil)
7106 return NO;
7107
7108 NSString *scheme([[url scheme] lowercaseString]);
7109 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7110 return YES;
7111 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7112 return YES;
7113
7114 return NO;
7115 }
7116
7117 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7118 return request;
7119 }
7120
7121 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7122 id<NSURLProtocolClient> client([self client]);
7123 if (icon == nil)
7124 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7125 else {
7126 NSData *data(UIImagePNGRepresentation(icon));
7127
7128 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7129 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7130 [client URLProtocol:self didLoadData:data];
7131 [client URLProtocolDidFinishLoading:self];
7132 }
7133 }
7134
7135 - (void) startLoading {
7136 id<NSURLProtocolClient> client([self client]);
7137 NSURLRequest *request([self request]);
7138
7139 NSURL *url([request URL]);
7140 NSString *href([url absoluteString]);
7141 NSString *scheme([[url scheme] lowercaseString]);
7142
7143 NSString *path;
7144
7145 if ([scheme isEqualToString:@"cydia"])
7146 path = [href substringFromIndex:8];
7147 else if ([scheme isEqualToString:@"about"])
7148 path = [href substringFromIndex:12];
7149 else _assert(false);
7150
7151 NSRange slash([path rangeOfString:@"/"]);
7152
7153 NSString *command;
7154 if (slash.location == NSNotFound) {
7155 command = path;
7156 path = nil;
7157 } else {
7158 command = [path substringToIndex:slash.location];
7159 path = [path substringFromIndex:(slash.location + 1)];
7160 }
7161
7162 Database *database([Database sharedInstance]);
7163
7164 if ([command isEqualToString:@"package-icon"]) {
7165 if (path == nil)
7166 goto fail;
7167 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7168 Package *package([database packageWithName:path]);
7169 if (package == nil)
7170 goto fail;
7171 [package parse];
7172 UIImage *icon([package icon]);
7173 [self _returnPNGWithImage:icon forRequest:request];
7174 } else if ([command isEqualToString:@"uikit-image"]) {
7175 if (path == nil)
7176 goto fail;
7177 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7178 UIImage *icon(_UIImageWithName(path));
7179 [self _returnPNGWithImage:icon forRequest:request];
7180 } else if ([command isEqualToString:@"section-icon"]) {
7181 if (path == nil)
7182 goto fail;
7183 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7184 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7185 if (icon == nil)
7186 icon = [UIImage applicationImageNamed:@"unknown.png"];
7187 [self _returnPNGWithImage:icon forRequest:request];
7188 } else fail: {
7189 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7190 }
7191 }
7192
7193 - (void) stopLoading {
7194 }
7195
7196 @end
7197 /* }}} */
7198
7199 /* Section Controller {{{ */
7200 @interface SectionController : FilteredPackageListController {
7201 _H<NSString> section_;
7202 }
7203
7204 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7205
7206 @end
7207
7208 @implementation SectionController
7209
7210 - (NSURL *) navigationURL {
7211 NSString *name = section_;
7212 if (name == nil)
7213 name = @"all";
7214
7215 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7216 }
7217
7218 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7219 NSString *title;
7220 if (name == nil)
7221 title = UCLocalize("ALL_PACKAGES");
7222 else if (![name isEqual:@""])
7223 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7224 else
7225 title = UCLocalize("NO_SECTION");
7226
7227 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7228 section_ = name;
7229 } return self;
7230 }
7231
7232 @end
7233 /* }}} */
7234 /* Sections Controller {{{ */
7235 @interface SectionsController : CyteViewController <
7236 UITableViewDataSource,
7237 UITableViewDelegate
7238 > {
7239 _transient Database *database_;
7240 _H<NSMutableArray> sections_;
7241 _H<NSMutableArray> filtered_;
7242 _H<UITableView, 2> list_;
7243 }
7244
7245 - (id) initWithDatabase:(Database *)database;
7246 - (void) editButtonClicked;
7247
7248 @end
7249
7250 @implementation SectionsController
7251
7252 - (NSURL *) navigationURL {
7253 return [NSURL URLWithString:@"cydia://sections"];
7254 }
7255
7256 - (void) updateNavigationItem {
7257 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7258 if ([sections_ count] == 0) {
7259 [[self navigationItem] setRightBarButtonItem:nil];
7260 } else {
7261 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7262 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7263 target:self
7264 action:@selector(editButtonClicked)
7265 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7266 }
7267 }
7268
7269 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7270 [super setEditing:editing animated:animated];
7271
7272 if (editing)
7273 [list_ reloadData];
7274 else
7275 [delegate_ updateData];
7276
7277 [self updateNavigationItem];
7278 }
7279
7280 - (void) viewDidAppear:(BOOL)animated {
7281 [super viewDidAppear:animated];
7282 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7283 }
7284
7285 - (void) viewWillDisappear:(BOOL)animated {
7286 [super viewWillDisappear:animated];
7287 if ([self isEditing]) [self setEditing:NO];
7288 }
7289
7290 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7291 Section *section = nil;
7292 int index = [indexPath row];
7293 if (![self isEditing]) {
7294 index -= 1;
7295 if (index >= 0)
7296 section = [filtered_ objectAtIndex:index];
7297 } else {
7298 section = [sections_ objectAtIndex:index];
7299 }
7300 return section;
7301 }
7302
7303 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7304 if ([self isEditing])
7305 return [sections_ count];
7306 else
7307 return [filtered_ count] + 1;
7308 }
7309
7310 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7311 return 45.0f;
7312 }*/
7313
7314 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7315 static NSString *reuseIdentifier = @"SectionCell";
7316
7317 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7318 if (cell == nil)
7319 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7320
7321 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7322
7323 return cell;
7324 }
7325
7326 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7327 if ([self isEditing])
7328 return;
7329
7330 Section *section = [self sectionAtIndexPath:indexPath];
7331
7332 SectionController *controller = [[[SectionController alloc]
7333 initWithDatabase:database_
7334 section:[section name]
7335 ] autorelease];
7336 [controller setDelegate:delegate_];
7337
7338 [[self navigationController] pushViewController:controller animated:YES];
7339 }
7340
7341 - (void) loadView {
7342 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7343 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7344 [list_ setRowHeight:45.0f];
7345 [(UITableView *) list_ setDataSource:self];
7346 [list_ setDelegate:self];
7347 [self setView:list_];
7348 }
7349
7350 - (void) viewDidLoad {
7351 [super viewDidLoad];
7352
7353 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7354 }
7355
7356 - (void) releaseSubviews {
7357 list_ = nil;
7358
7359 sections_ = nil;
7360 filtered_ = nil;
7361
7362 [super releaseSubviews];
7363 }
7364
7365 - (id) initWithDatabase:(Database *)database {
7366 if ((self = [super init]) != nil) {
7367 database_ = database;
7368 } return self;
7369 }
7370
7371 - (void) reloadData {
7372 [super reloadData];
7373
7374 NSArray *packages = [database_ packages];
7375
7376 sections_ = [NSMutableArray arrayWithCapacity:16];
7377 filtered_ = [NSMutableArray arrayWithCapacity:16];
7378
7379 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7380
7381 _trace();
7382 for (Package *package in packages) {
7383 NSString *name([package section]);
7384 NSString *key(name == nil ? @"" : name);
7385
7386 Section *section;
7387
7388 _profile(SectionsView$reloadData$Section)
7389 section = [sections objectForKey:key];
7390 if (section == nil) {
7391 _profile(SectionsView$reloadData$Section$Allocate)
7392 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7393 [sections setObject:section forKey:key];
7394 _end
7395 }
7396 _end
7397
7398 [section addToCount];
7399
7400 _profile(SectionsView$reloadData$Filter)
7401 if (![package valid] || ![package visible])
7402 continue;
7403 _end
7404
7405 [section addToRow];
7406 }
7407 _trace();
7408
7409 [sections_ addObjectsFromArray:[sections allValues]];
7410
7411 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7412
7413 for (Section *section in (id) sections_) {
7414 size_t count([section row]);
7415 if (count == 0)
7416 continue;
7417
7418 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7419 [section setCount:count];
7420 [filtered_ addObject:section];
7421 }
7422
7423 [self updateNavigationItem];
7424 [list_ reloadData];
7425 _trace();
7426 }
7427
7428 - (void) editButtonClicked {
7429 [self setEditing:![self isEditing] animated:YES];
7430 }
7431
7432 @end
7433 /* }}} */
7434
7435 /* Changes Controller {{{ */
7436 @interface ChangesController : CyteViewController <
7437 UITableViewDataSource,
7438 UITableViewDelegate
7439 > {
7440 _transient Database *database_;
7441 unsigned era_;
7442 _H<NSArray> packages_;
7443 _H<NSMutableArray> sections_;
7444 _H<UITableView, 2> list_;
7445 _H<CyteWebView, 1> dickbar_;
7446 unsigned upgrades_;
7447 _H<IndirectDelegate, 1> indirect_;
7448 _H<CydiaObject> cydia_;
7449 }
7450
7451 - (id) initWithDatabase:(Database *)database;
7452
7453 @end
7454
7455 @implementation ChangesController
7456
7457 - (NSURL *) navigationURL {
7458 return [NSURL URLWithString:@"cydia://changes"];
7459 }
7460
7461 - (void) viewDidAppear:(BOOL)animated {
7462 [super viewDidAppear:animated];
7463 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7464 }
7465
7466 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7467 NSInteger count([sections_ count]);
7468 return count == 0 ? 1 : count;
7469 }
7470
7471 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7472 if ([sections_ count] == 0)
7473 return nil;
7474 return [[sections_ objectAtIndex:section] name];
7475 }
7476
7477 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7478 if ([sections_ count] == 0)
7479 return 0;
7480 return [[sections_ objectAtIndex:section] count];
7481 }
7482
7483 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7484 @synchronized (database_) {
7485 if ([database_ era] != era_)
7486 return nil;
7487
7488 NSUInteger sectionIndex([path section]);
7489 if (sectionIndex >= [sections_ count])
7490 return nil;
7491 Section *section([sections_ objectAtIndex:sectionIndex]);
7492 NSInteger row([path row]);
7493 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7494 } }
7495
7496 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7497 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7498 if (cell == nil)
7499 cell = [[[PackageCell alloc] init] autorelease];
7500
7501 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7502 [cell setPackage:package asSummary:false];
7503 return cell;
7504 }
7505
7506 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7507 Package *package([self packageAtIndexPath:path]);
7508 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7509 [view setDelegate:delegate_];
7510 [[self navigationController] pushViewController:view animated:YES];
7511 return path;
7512 }
7513
7514 - (void) refreshButtonClicked {
7515 [delegate_ beginUpdate];
7516 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7517 }
7518
7519 - (void) upgradeButtonClicked {
7520 [delegate_ distUpgrade];
7521 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7522 }
7523
7524 - (void) loadView {
7525 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7526 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7527 [self setView:view];
7528
7529 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7530 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7531 [list_ setRowHeight:73];
7532 [(UITableView *) list_ setDataSource:self];
7533 [list_ setDelegate:self];
7534 [view addSubview:list_];
7535
7536 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7537 CGRect dickframe([view bounds]);
7538 dickframe.size.height = 44;
7539
7540 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7541 [dickbar_ setDelegate:self];
7542 [view addSubview:dickbar_];
7543
7544 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7545 [dickbar_ setScalesPageToFit:YES];
7546
7547 UIWebDocumentView *document([dickbar_ _documentView]);
7548 [document setBackgroundColor:[UIColor clearColor]];
7549 [document setDrawsBackground:NO];
7550
7551 WebView *webview([document webView]);
7552 [webview setShouldUpdateWhileOffscreen:NO];
7553
7554 UIScrollView *scroller([dickbar_ scrollView]);
7555 [scroller setScrollingEnabled:NO];
7556 [scroller setFixedBackgroundPattern:YES];
7557 [scroller setBackgroundColor:[UIColor clearColor]];
7558
7559 WebPreferences *preferences([webview preferences]);
7560 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7561 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7562 [preferences setOfflineWebApplicationCacheEnabled:YES];
7563
7564 [dickbar_ loadRequest:[NSURLRequest
7565 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7566 cachePolicy:NSURLRequestUseProtocolCachePolicy
7567 timeoutInterval:120
7568 ]];
7569
7570 UIEdgeInsets inset = {44, 0, 0, 0};
7571 [list_ setContentInset:inset];
7572
7573 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7574 }
7575 }
7576
7577 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7578 NSURL *url([request URL]);
7579 if (url == nil)
7580 return;
7581
7582 if ([frame isEqualToString:@"_open"])
7583 [delegate_ openURL:url];
7584 else {
7585 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7586 [controller setDelegate:delegate_];
7587 [[self navigationController] pushViewController:controller animated:YES];
7588 }
7589
7590 [listener ignore];
7591 }
7592
7593 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7594 return [CydiaWebViewController requestWithHeaders:request];
7595 }
7596
7597 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7598 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7599 }
7600
7601 - (void) setDelegate:(id)delegate {
7602 [super setDelegate:delegate];
7603 [cydia_ setDelegate:delegate];
7604 }
7605
7606 - (void) viewDidLoad {
7607 [super viewDidLoad];
7608
7609 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7610 }
7611
7612 - (void) releaseSubviews {
7613 list_ = nil;
7614
7615 packages_ = nil;
7616 sections_ = nil;
7617 dickbar_ = nil;
7618
7619 [super releaseSubviews];
7620 }
7621
7622 - (id) initWithDatabase:(Database *)database {
7623 if ((self = [super init]) != nil) {
7624 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7625 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7626 database_ = database;
7627 } return self;
7628 }
7629
7630 - (NSMutableArray *) _reloadPackages {
7631 @synchronized (database_) {
7632 era_ = [database_ era];
7633 NSArray *packages([database_ packages]);
7634
7635 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7636
7637 _trace();
7638 _profile(ChangesController$_reloadPackages$Filter)
7639 for (Package *package in packages)
7640 if ([package upgradableAndEssential:YES] || [package visible])
7641 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7642 _end
7643 _trace();
7644 _profile(ChangesController$_reloadPackages$radixSort)
7645 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7646 _end
7647 _trace();
7648
7649 return filtered;
7650 } }
7651
7652 - (void) _reloadData {
7653 NSArray *packages;
7654
7655 reload:
7656 if (true) {
7657 UIProgressHUD *hud([delegate_ addProgressHUD]);
7658 [hud setText:UCLocalize("LOADING")];
7659 //NSLog(@"HUD:%@::%@", delegate_, hud);
7660 packages = [self yieldToSelector:@selector(_reloadPackages)];
7661 [delegate_ removeProgressHUD:hud];
7662 } else {
7663 packages = [self _reloadPackages];
7664 }
7665
7666 @synchronized (database_) {
7667 if (era_ != [database_ era])
7668 goto reload;
7669
7670 packages_ = packages;
7671 sections_ = [NSMutableArray arrayWithCapacity:16];
7672
7673 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7674 Section *ignored = nil;
7675 Section *section = nil;
7676 time_t last = 0;
7677
7678 upgrades_ = 0;
7679 bool unseens = false;
7680
7681 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7682
7683 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7684 Package *package = [packages_ objectAtIndex:offset];
7685
7686 BOOL uae = [package upgradableAndEssential:YES];
7687
7688 if (!uae) {
7689 unseens = true;
7690 time_t seen([package seen]);
7691
7692 if (section == nil || last != seen) {
7693 last = seen;
7694
7695 NSString *name;
7696 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7697 [name autorelease];
7698
7699 _profile(ChangesController$reloadData$Allocate)
7700 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7701 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7702 [sections_ addObject:section];
7703 _end
7704 }
7705
7706 [section addToCount];
7707 } else if ([package ignored]) {
7708 if (ignored == nil) {
7709 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7710 }
7711 [ignored addToCount];
7712 } else {
7713 ++upgrades_;
7714 [upgradable addToCount];
7715 }
7716 }
7717 _trace();
7718
7719 CFRelease(formatter);
7720
7721 if (unseens) {
7722 Section *last = [sections_ lastObject];
7723 size_t count = [last count];
7724 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7725 [sections_ removeLastObject];
7726 }
7727
7728 if ([ignored count] != 0)
7729 [sections_ insertObject:ignored atIndex:0];
7730 if (upgrades_ != 0)
7731 [sections_ insertObject:upgradable atIndex:0];
7732
7733 [list_ reloadData];
7734
7735 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7736 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7737 style:UIBarButtonItemStylePlain
7738 target:self
7739 action:@selector(upgradeButtonClicked)
7740 ] autorelease]) animated:YES];
7741
7742 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7743 initWithTitle:UCLocalize("REFRESH")
7744 style:UIBarButtonItemStylePlain
7745 target:self
7746 action:@selector(refreshButtonClicked)
7747 ] autorelease]) animated:YES];
7748
7749 PrintTimes();
7750 } }
7751
7752 - (void) reloadData {
7753 [super reloadData];
7754 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7755 }
7756
7757 @end
7758 /* }}} */
7759 /* Search Controller {{{ */
7760 @interface SearchController : FilteredPackageListController <
7761 UISearchBarDelegate
7762 > {
7763 _H<UISearchBar, 1> search_;
7764 BOOL searchloaded_;
7765 }
7766
7767 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7768 - (void) reloadData;
7769
7770 @end
7771
7772 @implementation SearchController
7773
7774 - (NSURL *) navigationURL {
7775 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7776 return [NSURL URLWithString:@"cydia://search"];
7777 else
7778 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7779 }
7780
7781 - (void) useSearch {
7782 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7783 [self clearData];
7784 [self reloadData];
7785 }
7786
7787 - (void) viewWillAppear:(BOOL)animated {
7788 [super viewWillAppear:animated];
7789
7790 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7791 [self useSearch];
7792 }
7793
7794 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7795 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7796 [self clearData];
7797 [self reloadData];
7798 }
7799
7800 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7801 [search_ resignFirstResponder];
7802 [self useSearch];
7803 }
7804
7805 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7806 [search_ setText:@""];
7807 [self searchBarButtonClicked:searchBar];
7808 }
7809
7810 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7811 [self searchBarButtonClicked:searchBar];
7812 }
7813
7814 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7815 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7816 [self reloadData];
7817 }
7818
7819 - (bool) shouldYield {
7820 return YES;
7821 }
7822
7823 - (bool) shouldBlock {
7824 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7825 }
7826
7827 - (bool) isSummarized {
7828 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7829 }
7830
7831 - (bool) showsSections {
7832 return false;
7833 }
7834
7835 - (NSMutableArray *) _reloadPackages {
7836 NSMutableArray *packages([super _reloadPackages]);
7837 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7838 [packages radixSortUsingSelector:@selector(rank)];
7839 return packages;
7840 }
7841
7842 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7843 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7844 search_ = [[[UISearchBar alloc] init] autorelease];
7845 [search_ setDelegate:self];
7846
7847 if (query != nil)
7848 [search_ setText:query];
7849 } return self;
7850 }
7851
7852 - (void) viewDidAppear:(BOOL)animated {
7853 [super viewDidAppear:animated];
7854
7855 if (!searchloaded_) {
7856 searchloaded_ = YES;
7857 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7858 [search_ layoutSubviews];
7859 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7860
7861 UITextField *textField;
7862 if ([search_ respondsToSelector:@selector(searchField)])
7863 textField = [search_ searchField];
7864 else
7865 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7866
7867 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7868 [textField setEnablesReturnKeyAutomatically:NO];
7869 [[self navigationItem] setTitleView:textField];
7870 }
7871 }
7872
7873 - (void) reloadData {
7874 id object([search_ text]);
7875 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7876 object = [object componentsSeparatedByString:@" "];
7877
7878 [self setObject:object];
7879 [self resetCursor];
7880
7881 [super reloadData];
7882 }
7883
7884 - (void) didSelectPackage:(Package *)package {
7885 [search_ resignFirstResponder];
7886 [super didSelectPackage:package];
7887 }
7888
7889 @end
7890 /* }}} */
7891 /* Package Settings Controller {{{ */
7892 @interface PackageSettingsController : CyteViewController <
7893 UITableViewDataSource,
7894 UITableViewDelegate
7895 > {
7896 _transient Database *database_;
7897 _H<NSString> name_;
7898 _H<Package> package_;
7899 _H<UITableView, 2> table_;
7900 _H<UISwitch> subscribedSwitch_;
7901 _H<UISwitch> ignoredSwitch_;
7902 _H<UITableViewCell> subscribedCell_;
7903 _H<UITableViewCell> ignoredCell_;
7904 }
7905
7906 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7907
7908 @end
7909
7910 @implementation PackageSettingsController
7911
7912 - (NSURL *) navigationURL {
7913 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7914 }
7915
7916 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7917 if (package_ == nil)
7918 return 0;
7919
7920 if ([package_ installed] == nil)
7921 return 1;
7922 else
7923 return 2;
7924 }
7925
7926 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7927 if (package_ == nil)
7928 return 0;
7929
7930 // both sections contain just one item right now.
7931 return 1;
7932 }
7933
7934 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7935 return nil;
7936 }
7937
7938 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7939 if (section == 0)
7940 return UCLocalize("SHOW_ALL_CHANGES_EX");
7941 else
7942 return UCLocalize("IGNORE_UPGRADES_EX");
7943 }
7944
7945 - (void) onSubscribed:(id)control {
7946 bool value([control isOn]);
7947 if (package_ == nil)
7948 return;
7949 if ([package_ setSubscribed:value])
7950 [delegate_ updateData];
7951 }
7952
7953 - (void) _updateIgnored {
7954 const char *package([name_ UTF8String]);
7955 bool on([ignoredSwitch_ isOn]);
7956
7957 pid_t pid(ExecFork());
7958 if (pid == 0) {
7959 FILE *dpkg(popen("dpkg --set-selections", "w"));
7960 fwrite(package, strlen(package), 1, dpkg);
7961
7962 if (on)
7963 fwrite(" hold\n", 6, 1, dpkg);
7964 else
7965 fwrite(" install\n", 9, 1, dpkg);
7966
7967 pclose(dpkg);
7968
7969 exit(0);
7970 _assert(false);
7971 }
7972
7973 ReapZombie(pid);
7974 }
7975
7976 - (void) onIgnored:(id)control {
7977 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7978 [invocation setTarget:self];
7979 [invocation setSelector:@selector(_updateIgnored)];
7980
7981 [delegate_ reloadDataWithInvocation:invocation];
7982 }
7983
7984 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7985 if (package_ == nil)
7986 return nil;
7987
7988 switch ([indexPath section]) {
7989 case 0: return subscribedCell_;
7990 case 1: return ignoredCell_;
7991
7992 _nodefault
7993 }
7994
7995 return nil;
7996 }
7997
7998 - (void) loadView {
7999 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8000 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8001 [self setView:view];
8002
8003 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8004 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8005 [(UITableView *) table_ setDataSource:self];
8006 [table_ setDelegate:self];
8007 [view addSubview:table_];
8008
8009 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8010 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8011 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8012
8013 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8014 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8015 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8016
8017 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8018 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8019 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8020 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8021
8022 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8023 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8024 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8025 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8026 }
8027
8028 - (void) viewDidLoad {
8029 [super viewDidLoad];
8030
8031 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8032 }
8033
8034 - (void) releaseSubviews {
8035 ignoredCell_ = nil;
8036 subscribedCell_ = nil;
8037 table_ = nil;
8038 ignoredSwitch_ = nil;
8039 subscribedSwitch_ = nil;
8040
8041 [super releaseSubviews];
8042 }
8043
8044 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8045 if ((self = [super init]) != nil) {
8046 database_ = database;
8047 name_ = package;
8048 } return self;
8049 }
8050
8051 - (void) reloadData {
8052 [super reloadData];
8053
8054 package_ = [database_ packageWithName:name_];
8055
8056 if (package_ != nil) {
8057 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8058 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8059 } // XXX: what now, G?
8060
8061 [table_ reloadData];
8062 }
8063
8064 @end
8065 /* }}} */
8066
8067 /* Installed Controller {{{ */
8068 @interface InstalledController : FilteredPackageListController {
8069 BOOL expert_;
8070 }
8071
8072 - (id) initWithDatabase:(Database *)database;
8073
8074 - (void) updateRoleButton;
8075 - (void) queueStatusDidChange;
8076
8077 @end
8078
8079 @implementation InstalledController
8080
8081 - (NSURL *) navigationURL {
8082 return [NSURL URLWithString:@"cydia://installed"];
8083 }
8084
8085 - (id) initWithDatabase:(Database *)database {
8086 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8087 [self updateRoleButton];
8088 [self queueStatusDidChange];
8089 } return self;
8090 }
8091
8092 #if !AlwaysReload
8093 - (void) queueButtonClicked {
8094 [delegate_ queue];
8095 }
8096 #endif
8097
8098 - (void) queueStatusDidChange {
8099 #if !AlwaysReload
8100 if (IsWildcat_) {
8101 if (Queuing_) {
8102 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8103 initWithTitle:UCLocalize("QUEUE")
8104 style:UIBarButtonItemStyleDone
8105 target:self
8106 action:@selector(queueButtonClicked)
8107 ] autorelease]];
8108 } else {
8109 [[self navigationItem] setLeftBarButtonItem:nil];
8110 }
8111 }
8112 #endif
8113 }
8114
8115 - (void) updateRoleButton {
8116 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8117 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8118 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8119 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8120 target:self
8121 action:@selector(roleButtonClicked)
8122 ] autorelease]];
8123 }
8124
8125 - (void) roleButtonClicked {
8126 [self setObject:[NSNumber numberWithBool:expert_]];
8127 [self reloadData];
8128 expert_ = !expert_;
8129
8130 [self updateRoleButton];
8131 }
8132
8133 @end
8134 /* }}} */
8135
8136 /* Source Cell {{{ */
8137 @interface SourceCell : CyteTableViewCell <
8138 CyteTableViewCellDelegate
8139 > {
8140 _H<NSURL> url_;
8141 _H<UIImage> icon_;
8142 _H<NSString> origin_;
8143 _H<NSString> label_;
8144 }
8145
8146 - (void) setSource:(Source *)source;
8147
8148 @end
8149
8150 @implementation SourceCell
8151
8152 - (void) _setImage:(NSArray *)data {
8153 if ([url_ isEqual:[data objectAtIndex:0]]) {
8154 icon_ = [data objectAtIndex:1];
8155 [content_ setNeedsDisplay];
8156 }
8157 }
8158
8159 - (void) _setSource:(NSURL *) url {
8160 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8161
8162 if (NSData *data = [NSURLConnection
8163 sendSynchronousRequest:[NSURLRequest
8164 requestWithURL:url
8165 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8166 //timeoutInterval:5
8167 ]
8168
8169 returningResponse:NULL
8170 error:NULL
8171 ])
8172 if (UIImage *image = [UIImage imageWithData:data])
8173 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8174
8175 [pool release];
8176 }
8177
8178 - (void) setSource:(Source *)source {
8179 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8180
8181 origin_ = [source name];
8182 label_ = [source rooturi];
8183
8184 [content_ setNeedsDisplay];
8185
8186 url_ = [source iconURL];
8187 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8188 }
8189
8190 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8191 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8192 UIView *content([self contentView]);
8193 CGRect bounds([content bounds]);
8194
8195 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8196 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8197 [content_ setBackgroundColor:[UIColor whiteColor]];
8198 [content addSubview:content_];
8199
8200 [content_ setDelegate:self];
8201 [content_ setOpaque:YES];
8202
8203 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8204 } return self;
8205 }
8206
8207 - (NSString *) accessibilityLabel {
8208 return label_;
8209 }
8210
8211 - (void) drawContentRect:(CGRect)rect {
8212 bool highlighted(highlighted_);
8213 float width(rect.size.width);
8214
8215 if (icon_ != nil) {
8216 CGRect rect;
8217 rect.size = [(UIImage *) icon_ size];
8218
8219 while (rect.size.width > 32 || rect.size.height > 32) {
8220 rect.size.width /= 2;
8221 rect.size.height /= 2;
8222 }
8223
8224 rect.origin.x = 25 - rect.size.width / 2;
8225 rect.origin.y = 25 - rect.size.height / 2;
8226
8227 [icon_ drawInRect:rect];
8228 }
8229
8230 if (highlighted)
8231 UISetColor(White_);
8232
8233 if (!highlighted)
8234 UISetColor(Black_);
8235 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8236
8237 if (!highlighted)
8238 UISetColor(Gray_);
8239 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8240 }
8241
8242 @end
8243 /* }}} */
8244 /* Source Controller {{{ */
8245 @interface SourceController : FilteredPackageListController {
8246 _transient Source *source_;
8247 _H<NSString> key_;
8248 }
8249
8250 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8251
8252 @end
8253
8254 @implementation SourceController
8255
8256 - (NSURL *) navigationURL {
8257 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8258 }
8259
8260 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8261 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8262 source_ = source;
8263 key_ = [source key];
8264 } return self;
8265 }
8266
8267 - (void) reloadData {
8268 source_ = [database_ sourceWithKey:key_];
8269 key_ = [source_ key];
8270 [self setObject:source_];
8271
8272 [[self navigationItem] setTitle:[source_ label]];
8273
8274 [super reloadData];
8275 }
8276
8277 @end
8278 /* }}} */
8279 /* Sources Controller {{{ */
8280 @interface SourcesController : CyteViewController <
8281 UITableViewDataSource,
8282 UITableViewDelegate
8283 > {
8284 _transient Database *database_;
8285 unsigned era_;
8286
8287 _H<UITableView, 2> list_;
8288 _H<NSMutableArray> sources_;
8289 int offset_;
8290
8291 _H<NSString> href_;
8292 _H<UIProgressHUD> hud_;
8293 _H<NSError> error_;
8294
8295 //NSURLConnection *installer_;
8296 NSURLConnection *trivial_;
8297 NSURLConnection *trivial_bz2_;
8298 NSURLConnection *trivial_gz_;
8299 //NSURLConnection *automatic_;
8300
8301 BOOL cydia_;
8302 }
8303
8304 - (id) initWithDatabase:(Database *)database;
8305 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8306
8307 @end
8308
8309 @implementation SourcesController
8310
8311 - (void) _releaseConnection:(NSURLConnection *)connection {
8312 if (connection != nil) {
8313 [connection cancel];
8314 //[connection setDelegate:nil];
8315 [connection release];
8316 }
8317 }
8318
8319 - (void) dealloc {
8320 //[self _releaseConnection:installer_];
8321 [self _releaseConnection:trivial_];
8322 [self _releaseConnection:trivial_gz_];
8323 [self _releaseConnection:trivial_bz2_];
8324 //[self _releaseConnection:automatic_];
8325
8326 [super dealloc];
8327 }
8328
8329 - (NSURL *) navigationURL {
8330 return [NSURL URLWithString:@"cydia://sources"];
8331 }
8332
8333 - (void) viewDidAppear:(BOOL)animated {
8334 [super viewDidAppear:animated];
8335 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8336 }
8337
8338 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8339 return 1;
8340 }
8341
8342 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8343 return nil;
8344 }
8345
8346 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8347 return [sources_ count];
8348 }
8349
8350 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8351 @synchronized (database_) {
8352 if ([database_ era] != era_)
8353 return nil;
8354
8355 return [sources_ objectAtIndex:[indexPath row]];
8356 } }
8357
8358 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8359 static NSString *cellIdentifier = @"SourceCell";
8360
8361 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8362 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8363 [cell setSource:[self sourceAtIndexPath:indexPath]];
8364 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8365
8366 return cell;
8367 }
8368
8369 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8370 Source *source = [self sourceAtIndexPath:indexPath];
8371
8372 SourceController *controller = [[[SourceController alloc]
8373 initWithDatabase:database_
8374 source:source
8375 ] autorelease];
8376
8377 [controller setDelegate:delegate_];
8378
8379 [[self navigationController] pushViewController:controller animated:YES];
8380 }
8381
8382 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8383 Source *source = [self sourceAtIndexPath:indexPath];
8384 return [source record] != nil;
8385 }
8386
8387 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8388 if (editingStyle == UITableViewCellEditingStyleDelete) {
8389 Source *source = [self sourceAtIndexPath:indexPath];
8390 [Sources_ removeObjectForKey:[source key]];
8391 [delegate_ syncData];
8392 }
8393 }
8394
8395 - (void) complete {
8396 [delegate_ addTrivialSource:href_];
8397 href_ = nil;
8398
8399 [delegate_ syncData];
8400 }
8401
8402 - (NSString *) getWarning {
8403 NSString *href(href_);
8404 NSRange colon([href rangeOfString:@"://"]);
8405 if (colon.location != NSNotFound)
8406 href = [href substringFromIndex:(colon.location + 3)];
8407 href = [href stringByAddingPercentEscapes];
8408 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8409
8410 NSURL *url([NSURL URLWithString:href]);
8411
8412 NSStringEncoding encoding;
8413 NSError *error(nil);
8414
8415 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8416 return [warning length] == 0 ? nil : warning;
8417 return nil;
8418 }
8419
8420 - (void) _endConnection:(NSURLConnection *)connection {
8421 // XXX: the memory management in this method is horribly awkward
8422
8423 NSURLConnection **field = NULL;
8424 if (connection == trivial_)
8425 field = &trivial_;
8426 else if (connection == trivial_bz2_)
8427 field = &trivial_bz2_;
8428 else if (connection == trivial_gz_)
8429 field = &trivial_gz_;
8430 _assert(field != NULL);
8431 [connection release];
8432 *field = nil;
8433
8434 if (
8435 trivial_ == nil &&
8436 trivial_bz2_ == nil &&
8437 trivial_gz_ == nil
8438 ) {
8439 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8440
8441 [delegate_ releaseNetworkActivityIndicator];
8442
8443 [delegate_ removeProgressHUD:hud_];
8444 hud_ = nil;
8445
8446 if (cydia_) {
8447 if (warning != nil) {
8448 UIAlertView *alert = [[[UIAlertView alloc]
8449 initWithTitle:UCLocalize("SOURCE_WARNING")
8450 message:warning
8451 delegate:self
8452 cancelButtonTitle:UCLocalize("CANCEL")
8453 otherButtonTitles:
8454 UCLocalize("ADD_ANYWAY"),
8455 nil
8456 ] autorelease];
8457
8458 [alert setContext:@"warning"];
8459 [alert setNumberOfRows:1];
8460 [alert show];
8461
8462 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8463 error_ = nil;
8464 return;
8465 }
8466
8467 [self complete];
8468 } else if (error_ != nil) {
8469 UIAlertView *alert = [[[UIAlertView alloc]
8470 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8471 message:[error_ localizedDescription]
8472 delegate:self
8473 cancelButtonTitle:UCLocalize("OK")
8474 otherButtonTitles:nil
8475 ] autorelease];
8476
8477 [alert setContext:@"urlerror"];
8478 [alert show];
8479
8480 href_ = nil;
8481 } else {
8482 UIAlertView *alert = [[[UIAlertView alloc]
8483 initWithTitle:UCLocalize("NOT_REPOSITORY")
8484 message:UCLocalize("NOT_REPOSITORY_EX")
8485 delegate:self
8486 cancelButtonTitle:UCLocalize("OK")
8487 otherButtonTitles:nil
8488 ] autorelease];
8489
8490 [alert setContext:@"trivial"];
8491 [alert show];
8492
8493 href_ = nil;
8494 }
8495
8496 error_ = nil;
8497 }
8498 }
8499
8500 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8501 switch ([response statusCode]) {
8502 case 200:
8503 cydia_ = YES;
8504 }
8505 }
8506
8507 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8508 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8509 error_ = error;
8510 [self _endConnection:connection];
8511 }
8512
8513 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8514 [self _endConnection:connection];
8515 }
8516
8517 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8518 NSURL *url([NSURL URLWithString:href]);
8519
8520 NSMutableURLRequest *request = [NSMutableURLRequest
8521 requestWithURL:url
8522 cachePolicy:NSURLRequestUseProtocolCachePolicy
8523 timeoutInterval:120.0
8524 ];
8525
8526 [request setHTTPMethod:method];
8527
8528 if (Machine_ != NULL)
8529 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8530
8531 if ([url isCydiaSecure]) {
8532 if (UniqueID_ != nil) {
8533 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8534 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8535 }
8536 }
8537
8538 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8539 }
8540
8541 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8542 NSString *context([alert context]);
8543
8544 if ([context isEqualToString:@"source"]) {
8545 switch (button) {
8546 case 1: {
8547 NSString *href = [[alert textField] text];
8548
8549 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8550
8551 if (![href hasSuffix:@"/"])
8552 href_ = [href stringByAppendingString:@"/"];
8553 else
8554 href_ = href;
8555
8556 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8557 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8558 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8559 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8560
8561 cydia_ = false;
8562
8563 // XXX: this is stupid
8564 hud_ = [delegate_ addProgressHUD];
8565 [hud_ setText:UCLocalize("VERIFYING_URL")];
8566 [delegate_ retainNetworkActivityIndicator];
8567 } break;
8568
8569 case 0:
8570 break;
8571
8572 _nodefault
8573 }
8574
8575 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8576 } else if ([context isEqualToString:@"trivial"])
8577 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8578 else if ([context isEqualToString:@"urlerror"])
8579 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8580 else if ([context isEqualToString:@"warning"]) {
8581 switch (button) {
8582 case 1:
8583 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8584 break;
8585
8586 case 0:
8587 break;
8588
8589 _nodefault
8590 }
8591
8592 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8593 }
8594 }
8595
8596 - (void) loadView {
8597 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8598 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8599 [list_ setRowHeight:53];
8600 [(UITableView *) list_ setDataSource:self];
8601 [list_ setDelegate:self];
8602 [self setView:list_];
8603 }
8604
8605 - (void) viewDidLoad {
8606 [super viewDidLoad];
8607
8608 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8609 [self updateButtonsForEditingStatus:NO animated:NO];
8610 }
8611
8612 - (void) releaseSubviews {
8613 list_ = nil;
8614
8615 sources_ = nil;
8616
8617 [super releaseSubviews];
8618 }
8619
8620 - (id) initWithDatabase:(Database *)database {
8621 if ((self = [super init]) != nil) {
8622 database_ = database;
8623 } return self;
8624 }
8625
8626 - (void) reloadData {
8627 [super reloadData];
8628
8629 @synchronized (database_) {
8630 era_ = [database_ era];
8631
8632 pkgSourceList list;
8633 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8634 return;
8635
8636 sources_ = [NSMutableArray arrayWithCapacity:16];
8637 [sources_ addObjectsFromArray:[database_ sources]];
8638 _trace();
8639 [sources_ sortUsingSelector:@selector(compareByName:)];
8640 _trace();
8641
8642 int count([sources_ count]);
8643 offset_ = 0;
8644 for (int i = 0; i != count; i++) {
8645 if ([[sources_ objectAtIndex:i] record] == nil)
8646 break;
8647 offset_++;
8648 }
8649
8650 [list_ setEditing:NO];
8651 [self updateButtonsForEditingStatus:NO animated:NO];
8652 [list_ reloadData];
8653 } }
8654
8655 - (void) showAddSourcePrompt {
8656 UIAlertView *alert = [[[UIAlertView alloc]
8657 initWithTitle:UCLocalize("ENTER_APT_URL")
8658 message:nil
8659 delegate:self
8660 cancelButtonTitle:UCLocalize("CANCEL")
8661 otherButtonTitles:
8662 UCLocalize("ADD_SOURCE"),
8663 nil
8664 ] autorelease];
8665
8666 [alert setContext:@"source"];
8667
8668 [alert setNumberOfRows:1];
8669 [alert addTextFieldWithValue:@"http://" label:@""];
8670
8671 UITextInputTraits *traits = [[alert textField] textInputTraits];
8672 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8673 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8674 [traits setKeyboardType:UIKeyboardTypeURL];
8675 // XXX: UIReturnKeyDone
8676 [traits setReturnKeyType:UIReturnKeyNext];
8677
8678 [alert show];
8679 }
8680
8681 - (void) addButtonClicked {
8682 [self showAddSourcePrompt];
8683 }
8684
8685 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8686 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8687 initWithTitle:UCLocalize("ADD")
8688 style:UIBarButtonItemStylePlain
8689 target:self
8690 action:@selector(addButtonClicked)
8691 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8692
8693 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8694 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8695 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8696 target:self
8697 action:@selector(editButtonClicked)
8698 ] autorelease] animated:animated];
8699
8700 if (IsWildcat_ && !editing)
8701 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8702 initWithTitle:UCLocalize("SETTINGS")
8703 style:UIBarButtonItemStylePlain
8704 target:self
8705 action:@selector(settingsButtonClicked)
8706 ] autorelease]];
8707 }
8708
8709 - (void) settingsButtonClicked {
8710 [delegate_ showSettings];
8711 }
8712
8713 - (void) editButtonClicked {
8714 [list_ setEditing:![list_ isEditing] animated:YES];
8715
8716 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8717 }
8718
8719 @end
8720 /* }}} */
8721
8722 /* Settings Controller {{{ */
8723 @interface SettingsController : CyteViewController <
8724 UITableViewDataSource,
8725 UITableViewDelegate
8726 > {
8727 _transient Database *database_;
8728 // XXX: ok, "roledelegate_"?...
8729 _transient id roledelegate_;
8730 _H<UITableView, 2> table_;
8731 _H<UISegmentedControl> segment_;
8732 _H<UIView> container_;
8733 }
8734
8735 - (void) showDoneButton;
8736 - (void) resizeSegmentedControl;
8737
8738 @end
8739
8740 @implementation SettingsController
8741
8742 - (void) loadView {
8743 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8744 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8745 [table_ setDelegate:self];
8746 [(UITableView *) table_ setDataSource:self];
8747 [self setView:table_];
8748
8749 NSArray *items = [NSArray arrayWithObjects:
8750 UCLocalize("USER"),
8751 UCLocalize("HACKER"),
8752 UCLocalize("DEVELOPER"),
8753 nil];
8754 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8755 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8756 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8757 [container_ addSubview:segment_];
8758 }
8759
8760 - (void) viewDidLoad {
8761 [super viewDidLoad];
8762
8763 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8764
8765 int index = -1;
8766 if ([Role_ isEqualToString:@"User"]) index = 0;
8767 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8768 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8769 if (index != -1) {
8770 [segment_ setSelectedSegmentIndex:index];
8771 [self showDoneButton];
8772 }
8773
8774 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8775 [self resizeSegmentedControl];
8776 }
8777
8778 - (void) releaseSubviews {
8779 table_ = nil;
8780 segment_ = nil;
8781 container_ = nil;
8782
8783 [super releaseSubviews];
8784 }
8785
8786 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8787 if ((self = [super init]) != nil) {
8788 database_ = database;
8789 roledelegate_ = delegate;
8790 } return self;
8791 }
8792
8793 - (void) resizeSegmentedControl {
8794 CGFloat width = [[self view] frame].size.width;
8795 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8796 }
8797
8798 - (void) viewWillAppear:(BOOL)animated {
8799 [super viewWillAppear:animated];
8800
8801 [self resizeSegmentedControl];
8802 }
8803
8804 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8805 [self resizeSegmentedControl];
8806 }
8807
8808 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8809 [self resizeSegmentedControl];
8810 }
8811
8812 - (void) save {
8813 NSString *role(nil);
8814
8815 switch ([segment_ selectedSegmentIndex]) {
8816 case 0: role = @"User"; break;
8817 case 1: role = @"Hacker"; break;
8818 case 2: role = @"Developer"; break;
8819
8820 _nodefault
8821 }
8822
8823 if (![role isEqualToString:Role_]) {
8824 bool rolling(Role_ == nil);
8825 Role_ = role;
8826
8827 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8828 Role_, @"Role",
8829 nil];
8830
8831 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8832 Changed_ = true;
8833
8834 if (rolling)
8835 [roledelegate_ loadData];
8836 else
8837 [roledelegate_ updateData];
8838 }
8839 }
8840
8841 - (void) segmentChanged:(UISegmentedControl *)control {
8842 [self showDoneButton];
8843 }
8844
8845 - (void) saveAndClose {
8846 [self save];
8847
8848 [[self navigationItem] setRightBarButtonItem:nil];
8849 [[self navigationController] dismissModalViewControllerAnimated:YES];
8850 }
8851
8852 - (void) doneButtonClicked {
8853 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8854 [spinner startAnimating];
8855 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8856 [[self navigationItem] setRightBarButtonItem:spinItem];
8857
8858 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8859 }
8860
8861 - (void) showDoneButton {
8862 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8863 initWithTitle:UCLocalize("DONE")
8864 style:UIBarButtonItemStyleDone
8865 target:self
8866 action:@selector(doneButtonClicked)
8867 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8868 }
8869
8870 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8871 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8872 return 6;
8873 }
8874
8875 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8876 return 0; // :(
8877 }
8878
8879 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8880 return nil; // This method is required by the protocol.
8881 }
8882
8883 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8884 if (section == 1)
8885 return UCLocalize("ROLE_EX");
8886 if (section == 4)
8887 return [NSString stringWithFormat:
8888 @"%@: %@\n%@: %@\n%@: %@",
8889 UCLocalize("USER"), UCLocalize("USER_EX"),
8890 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8891 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8892 ];
8893 else return nil;
8894 }
8895
8896 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8897 return section == 3 ? 44.0f : 0;
8898 }
8899
8900 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8901 return section == 3 ? container_ : nil;
8902 }
8903
8904 - (void) reloadData {
8905 [super reloadData];
8906
8907 [table_ reloadData];
8908 }
8909
8910 @end
8911 /* }}} */
8912 /* Stash Controller {{{ */
8913 @interface StashController : CyteViewController {
8914 _H<UIActivityIndicatorView> spinner_;
8915 _H<UILabel> status_;
8916 _H<UILabel> caption_;
8917 }
8918
8919 @end
8920
8921 @implementation StashController
8922
8923 - (void) loadView {
8924 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8925 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8926 [self setView:view];
8927
8928 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8929
8930 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8931 CGRect spinrect = [spinner_ frame];
8932 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8933 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8934 [spinner_ setFrame:spinrect];
8935 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8936 [view addSubview:spinner_];
8937 [spinner_ startAnimating];
8938
8939 CGRect captrect;
8940 captrect.size.width = [[self view] frame].size.width;
8941 captrect.size.height = 40.0f;
8942 captrect.origin.x = 0;
8943 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8944 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8945 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8946 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8947 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8948 [caption_ setTextColor:[UIColor whiteColor]];
8949 [caption_ setBackgroundColor:[UIColor clearColor]];
8950 [caption_ setShadowColor:[UIColor blackColor]];
8951 [caption_ setTextAlignment:UITextAlignmentCenter];
8952 [view addSubview:caption_];
8953
8954 CGRect statusrect;
8955 statusrect.size.width = [[self view] frame].size.width;
8956 statusrect.size.height = 30.0f;
8957 statusrect.origin.x = 0;
8958 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8959 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8960 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8961 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8962 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8963 [status_ setTextColor:[UIColor whiteColor]];
8964 [status_ setBackgroundColor:[UIColor clearColor]];
8965 [status_ setShadowColor:[UIColor blackColor]];
8966 [status_ setTextAlignment:UITextAlignmentCenter];
8967 [view addSubview:status_];
8968 }
8969
8970 - (void) releaseSubviews {
8971 spinner_ = nil;
8972 status_ = nil;
8973 caption_ = nil;
8974
8975 [super releaseSubviews];
8976 }
8977
8978 @end
8979 /* }}} */
8980
8981 @interface CYURLCache : SDURLCache {
8982 }
8983
8984 @end
8985
8986 @implementation CYURLCache
8987
8988 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8989 #if !ForRelease
8990 if (false);
8991 else if ([event isEqualToString:@"no-cache"])
8992 event = @"!!!";
8993 else if ([event isEqualToString:@"store"])
8994 event = @">>>";
8995 else if ([event isEqualToString:@"invalid"])
8996 event = @"???";
8997 else if ([event isEqualToString:@"memory"])
8998 event = @"mem";
8999 else if ([event isEqualToString:@"disk"])
9000 event = @"ssd";
9001 else if ([event isEqualToString:@"miss"])
9002 event = @"---";
9003
9004 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9005 #endif
9006 }
9007
9008 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9009 if (NSURLResponse *response = [cached response])
9010 if (NSString *mime = [response MIMEType])
9011 if ([mime isEqualToString:@"text/cache-manifest"]) {
9012 NSURL *url([response URL]);
9013
9014 #if !ForRelease
9015 NSLog(@"###: %@", [url absoluteString]);
9016 #endif
9017
9018 @synchronized (HostConfig_) {
9019 [CachedURLs_ addObject:url];
9020 }
9021 }
9022
9023 [super storeCachedResponse:cached forRequest:request];
9024 }
9025
9026 @end
9027
9028 @interface Cydia : UIApplication <
9029 ConfirmationControllerDelegate,
9030 DatabaseDelegate,
9031 CydiaDelegate,
9032 UINavigationControllerDelegate,
9033 UITabBarControllerDelegate
9034 > {
9035 _H<UIWindow> window_;
9036 _H<CYTabBarController> tabbar_;
9037 _H<CydiaLoadingViewController> emulated_;
9038
9039 _H<NSMutableArray> essential_;
9040 _H<NSMutableArray> broken_;
9041
9042 Database *database_;
9043
9044 _H<NSURL> starturl_;
9045
9046 unsigned locked_;
9047 unsigned activity_;
9048
9049 _H<StashController> stash_;
9050
9051 bool loaded_;
9052 }
9053
9054 - (void) loadData;
9055
9056 @end
9057
9058 @implementation Cydia
9059
9060 - (void) beginUpdate {
9061 [tabbar_ beginUpdate];
9062 }
9063
9064 - (BOOL) updating {
9065 return [tabbar_ updating];
9066 }
9067
9068 - (void) _loaded {
9069 if ([broken_ count] != 0) {
9070 int count = [broken_ count];
9071
9072 UIAlertView *alert = [[[UIAlertView alloc]
9073 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9074 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9075 delegate:self
9076 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9077 otherButtonTitles:
9078 UCLocalize("TEMPORARY_IGNORE"),
9079 nil
9080 ] autorelease];
9081
9082 [alert setContext:@"fixhalf"];
9083 [alert setNumberOfRows:2];
9084 [alert show];
9085 } else if (!Ignored_ && [essential_ count] != 0) {
9086 int count = [essential_ count];
9087
9088 UIAlertView *alert = [[[UIAlertView alloc]
9089 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9090 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9091 delegate:self
9092 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9093 otherButtonTitles:
9094 UCLocalize("UPGRADE_ESSENTIAL"),
9095 UCLocalize("COMPLETE_UPGRADE"),
9096 nil
9097 ] autorelease];
9098
9099 [alert setContext:@"upgrade"];
9100 [alert show];
9101 }
9102 }
9103
9104 - (void) returnToCydia {
9105 [self _loaded];
9106 }
9107
9108 - (void) _saveConfig {
9109 @synchronized (database_) {
9110 _trace();
9111 MetaFile_.Sync();
9112 _trace();
9113 }
9114
9115 if (Changed_) {
9116 NSString *error(nil);
9117
9118 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9119 _trace();
9120 NSError *error(nil);
9121 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9122 NSLog(@"failure to save metadata data: %@", error);
9123 _trace();
9124
9125 Changed_ = false;
9126 } else {
9127 NSLog(@"failure to serialize metadata: %@", error);
9128 }
9129 }
9130
9131 CydiaWriteSources();
9132 }
9133
9134 // Navigation controller for the queuing badge.
9135 - (UINavigationController *) queueNavigationController {
9136 NSArray *controllers = [tabbar_ viewControllers];
9137 return [controllers objectAtIndex:3];
9138 }
9139
9140 - (void) unloadData {
9141 [tabbar_ unloadData];
9142 }
9143
9144 - (void) _updateData {
9145 [self _saveConfig];
9146 [self unloadData];
9147
9148 UINavigationController *navigation = [self queueNavigationController];
9149
9150 id queuedelegate = nil;
9151 if ([[navigation viewControllers] count] > 0)
9152 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9153
9154 [queuedelegate queueStatusDidChange];
9155 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9156 }
9157
9158 - (void) _refreshIfPossible:(NSDate *)update {
9159 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9160
9161 bool recently = false;
9162 if (update != nil) {
9163 NSTimeInterval interval([update timeIntervalSinceNow]);
9164 if (interval <= 0 && interval > -(15*60))
9165 recently = true;
9166 }
9167
9168 // Don't automatic refresh if:
9169 // - We already refreshed recently.
9170 // - We already auto-refreshed this launch.
9171 // - Auto-refresh is disabled.
9172 if (recently || loaded_ || ManualRefresh) {
9173 // If we are cancelling, we need to make sure it knows it's already loaded.
9174 loaded_ = true;
9175
9176 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9177 } else {
9178 // We are going to load, so remember that.
9179 loaded_ = true;
9180
9181 SCNetworkReachabilityFlags flags; {
9182 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9183 SCNetworkReachabilityGetFlags(reachability, &flags);
9184 CFRelease(reachability);
9185 }
9186
9187 // XXX: this elaborate mess is what Apple is using to determine this? :(
9188 // XXX: do we care if the user has to intervene? maybe that's ok?
9189 bool reachable(
9190 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9191 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9192 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9193 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9194 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9195 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9196 )
9197 );
9198
9199 // If we can reach the server, auto-refresh!
9200 if (reachable)
9201 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9202 }
9203
9204 [pool release];
9205 }
9206
9207 - (void) refreshIfPossible {
9208 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9209 }
9210
9211 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9212 @synchronized (self) {
9213 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9214 [hud setText:UCLocalize("RELOADING_DATA")];
9215
9216 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9217
9218 size_t changes(0);
9219
9220 [essential_ removeAllObjects];
9221 [broken_ removeAllObjects];
9222
9223 NSArray *packages([database_ packages]);
9224 for (Package *package in packages) {
9225 if ([package half])
9226 [broken_ addObject:package];
9227 if ([package upgradableAndEssential:NO]) {
9228 if ([package essential])
9229 [essential_ addObject:package];
9230 ++changes;
9231 }
9232 }
9233
9234 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9235 if (changes != 0) {
9236 _trace();
9237 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9238 [changesItem setBadgeValue:badge];
9239 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9240 [self setApplicationIconBadgeNumber:changes];
9241 } else {
9242 _trace();
9243 [changesItem setBadgeValue:nil];
9244 [changesItem setAnimatedBadge:NO];
9245 [self setApplicationIconBadgeNumber:0];
9246 }
9247
9248 [self _updateData];
9249
9250 if (hud != nil)
9251 [self removeProgressHUD:hud];
9252 } }
9253
9254 - (void) updateData {
9255 [self _updateData];
9256 }
9257
9258 - (void) update_ {
9259 [database_ update];
9260 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9261 }
9262
9263 - (void) disemulate {
9264 if (emulated_ == nil)
9265 return;
9266
9267 [window_ addSubview:[tabbar_ view]];
9268 [[emulated_ view] removeFromSuperview];
9269 emulated_ = nil;
9270 [window_ setUserInteractionEnabled:YES];
9271 }
9272
9273 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9274 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9275 if (IsWildcat_)
9276 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9277
9278 UIViewController *parent;
9279 if (emulated_ == nil)
9280 parent = tabbar_;
9281 else if (!force)
9282 parent = emulated_;
9283 else {
9284 [self disemulate];
9285 parent = tabbar_;
9286 }
9287
9288 [parent presentModalViewController:navigation animated:YES];
9289 }
9290
9291 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9292 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9293
9294 if (navigation != nil)
9295 [navigation pushViewController:progress animated:YES];
9296 else
9297 [self presentModalViewController:progress force:YES];
9298
9299 [progress invoke:invocation withTitle:title];
9300 return progress;
9301 }
9302
9303 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9304 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9305 }
9306
9307 - (void) repairWithInvocation:(NSInvocation *)invocation {
9308 _trace();
9309 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9310 _trace();
9311 }
9312
9313 - (void) repairWithSelector:(SEL)selector {
9314 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9315 }
9316
9317 - (void) reloadData {
9318 [self reloadDataWithInvocation:nil];
9319 if ([database_ progressDelegate] == nil)
9320 [self _loaded];
9321 }
9322
9323 - (void) syncData {
9324 [self _saveConfig];
9325 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9326 }
9327
9328 - (void) addSource:(NSDictionary *) source {
9329 CydiaAddSource(source);
9330 }
9331
9332 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9333 CydiaAddSource(href, distribution, sections);
9334 }
9335
9336 - (void) addTrivialSource:(NSString *)href {
9337 CydiaAddSource(href, @"./");
9338 }
9339
9340 - (void) updateValues {
9341 Changed_ = true;
9342 }
9343
9344 - (void) resolve {
9345 pkgProblemResolver *resolver = [database_ resolver];
9346
9347 resolver->InstallProtect();
9348 if (!resolver->Resolve(true))
9349 _error->Discard();
9350 }
9351
9352 - (bool) perform {
9353 // XXX: this is a really crappy way of doing this.
9354 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9355 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9356 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9357 if ([tabbar_ updating])
9358 [tabbar_ cancelUpdate];
9359
9360 if (![database_ prepare])
9361 return false;
9362
9363 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9364 [page setDelegate:self];
9365 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9366
9367 if (IsWildcat_)
9368 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9369 [tabbar_ presentModalViewController:confirm_ animated:YES];
9370
9371 return true;
9372 }
9373
9374 - (void) queue {
9375 @synchronized (self) {
9376 [self perform];
9377 }
9378 }
9379
9380 - (void) clearPackage:(Package *)package {
9381 @synchronized (self) {
9382 [package clear];
9383 [self resolve];
9384 [self perform];
9385 }
9386 }
9387
9388 - (void) installPackages:(NSArray *)packages {
9389 @synchronized (self) {
9390 for (Package *package in packages)
9391 [package install];
9392 [self resolve];
9393 [self perform];
9394 }
9395 }
9396
9397 - (void) installPackage:(Package *)package {
9398 @synchronized (self) {
9399 [package install];
9400 [self resolve];
9401 [self perform];
9402 }
9403 }
9404
9405 - (void) removePackage:(Package *)package {
9406 @synchronized (self) {
9407 [package remove];
9408 [self resolve];
9409 [self perform];
9410 }
9411 }
9412
9413 - (void) distUpgrade {
9414 @synchronized (self) {
9415 if (![database_ upgrade])
9416 return;
9417 [self perform];
9418 }
9419 }
9420
9421 - (void) perform_ {
9422 [database_ perform];
9423 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9424 }
9425
9426 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9427 Queuing_ = false;
9428 ++locked_;
9429 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9430 --locked_;
9431 [self refreshIfPossible];
9432 }
9433
9434 - (void) showSettings {
9435 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9436 }
9437
9438 - (void) retainNetworkActivityIndicator {
9439 if (activity_++ == 0)
9440 [self setNetworkActivityIndicatorVisible:YES];
9441
9442 #if TraceLogging
9443 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9444 #endif
9445 }
9446
9447 - (void) releaseNetworkActivityIndicator {
9448 if (--activity_ == 0)
9449 [self setNetworkActivityIndicatorVisible:NO];
9450
9451 #if TraceLogging
9452 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9453 #endif
9454
9455 }
9456
9457 - (void) cancelAndClear:(bool)clear {
9458 @synchronized (self) {
9459 if (clear) {
9460 [database_ clear];
9461 Queuing_ = false;
9462 } else {
9463 Queuing_ = true;
9464 }
9465
9466 [self _updateData];
9467 }
9468 }
9469
9470 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9471 NSString *context([alert context]);
9472
9473 if ([context isEqualToString:@"conffile"]) {
9474 FILE *input = [database_ input];
9475 if (button == [alert cancelButtonIndex])
9476 fprintf(input, "N\n");
9477 else if (button == [alert firstOtherButtonIndex])
9478 fprintf(input, "Y\n");
9479 fflush(input);
9480
9481 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9482 } else if ([context isEqualToString:@"fixhalf"]) {
9483 if (button == [alert cancelButtonIndex]) {
9484 @synchronized (self) {
9485 for (Package *broken in (id) broken_) {
9486 [broken remove];
9487
9488 NSString *id = [broken id];
9489 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9490 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9491 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9492 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9493 }
9494
9495 [self resolve];
9496 [self perform];
9497 }
9498 } else if (button == [alert firstOtherButtonIndex]) {
9499 [broken_ removeAllObjects];
9500 [self _loaded];
9501 }
9502
9503 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9504 } else if ([context isEqualToString:@"upgrade"]) {
9505 if (button == [alert firstOtherButtonIndex]) {
9506 @synchronized (self) {
9507 for (Package *essential in (id) essential_)
9508 [essential install];
9509
9510 [self resolve];
9511 [self perform];
9512 }
9513 } else if (button == [alert firstOtherButtonIndex] + 1) {
9514 [self distUpgrade];
9515 } else if (button == [alert cancelButtonIndex]) {
9516 Ignored_ = YES;
9517 }
9518
9519 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9520 }
9521 }
9522
9523 - (void) system:(NSString *)command {
9524 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9525
9526 _trace();
9527 system([command UTF8String]);
9528 _trace();
9529
9530 [pool release];
9531 }
9532
9533 - (void) applicationWillSuspend {
9534 [database_ clean];
9535 [super applicationWillSuspend];
9536 }
9537
9538 - (BOOL) isSafeToSuspend {
9539 if (locked_ != 0) {
9540 #if !ForRelease
9541 NSLog(@"isSafeToSuspend: locked_ != 0");
9542 #endif
9543 return false;
9544 }
9545
9546 // Use external process status API internally.
9547 // This is probably a really bad idea.
9548 // XXX: what is the point of this? does this solve anything at all?
9549 uint64_t status = 0;
9550 int notify_token;
9551 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9552 notify_get_state(notify_token, &status);
9553 notify_cancel(notify_token);
9554 }
9555
9556 if (status != 0) {
9557 #if !ForRelease
9558 NSLog(@"isSafeToSuspend: status != 0");
9559 #endif
9560 return false;
9561 }
9562
9563 #if !ForRelease
9564 NSLog(@"isSafeToSuspend: -> true");
9565 #endif
9566 return true;
9567 }
9568
9569 - (void) applicationSuspend:(__GSEvent *)event {
9570 if ([self isSafeToSuspend])
9571 [super applicationSuspend:event];
9572 }
9573
9574 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9575 if ([self isSafeToSuspend])
9576 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9577 }
9578
9579 - (void) _setSuspended:(BOOL)value {
9580 if ([self isSafeToSuspend])
9581 [super _setSuspended:value];
9582 }
9583
9584 - (UIProgressHUD *) addProgressHUD {
9585 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9586 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9587
9588 [window_ setUserInteractionEnabled:NO];
9589
9590 UIViewController *target(tabbar_);
9591 if (UIViewController *modal = [target modalViewController])
9592 target = modal;
9593
9594 [hud showInView:[target view]];
9595
9596 ++locked_;
9597 return hud;
9598 }
9599
9600 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9601 --locked_;
9602 [hud hide];
9603 [hud removeFromSuperview];
9604 [window_ setUserInteractionEnabled:YES];
9605 }
9606
9607 - (CyteViewController *) pageForPackage:(NSString *)name {
9608 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9609 }
9610
9611 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9612 NSString *scheme([[url scheme] lowercaseString]);
9613 if ([[url absoluteString] length] <= [scheme length] + 3)
9614 return nil;
9615 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9616 NSArray *components([path componentsSeparatedByString:@"/"]);
9617
9618 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9619 return [self pageForPackage:[components objectAtIndex:1]];
9620
9621 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9622 return nil;
9623
9624 NSString *base([components objectAtIndex:0]);
9625
9626 CyteViewController *controller = nil;
9627
9628 if ([base isEqualToString:@"url"]) {
9629 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9630 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9631 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9632 } else if (!external && [components count] == 1) {
9633 if ([base isEqualToString:@"manage"]) {
9634 controller = [[[ManageController alloc] init] autorelease];
9635 }
9636
9637 if ([base isEqualToString:@"storage"]) {
9638 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9639 }
9640
9641 if ([base isEqualToString:@"sources"]) {
9642 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9643 }
9644
9645 if ([base isEqualToString:@"home"]) {
9646 controller = [[[HomeController alloc] init] autorelease];
9647 }
9648
9649 if ([base isEqualToString:@"sections"]) {
9650 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9651 }
9652
9653 if ([base isEqualToString:@"search"]) {
9654 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9655 }
9656
9657 if ([base isEqualToString:@"changes"]) {
9658 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9659 }
9660
9661 if ([base isEqualToString:@"installed"]) {
9662 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9663 }
9664 } else if ([components count] == 2) {
9665 NSString *argument = [components objectAtIndex:1];
9666
9667 if ([base isEqualToString:@"package"]) {
9668 controller = [self pageForPackage:argument];
9669 }
9670
9671 if (!external && [base isEqualToString:@"search"]) {
9672 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9673 }
9674
9675 if (!external && [base isEqualToString:@"sections"]) {
9676 if ([argument isEqualToString:@"all"])
9677 argument = nil;
9678 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9679 }
9680
9681 if (!external && [base isEqualToString:@"sources"]) {
9682 if ([argument isEqualToString:@"add"]) {
9683 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9684 [(SourcesController *)controller showAddSourcePrompt];
9685 } else {
9686 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9687 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9688 }
9689 }
9690
9691 if (!external && [base isEqualToString:@"launch"]) {
9692 [self launchApplicationWithIdentifier:argument suspended:NO];
9693 return nil;
9694 }
9695 } else if (!external && [components count] == 3) {
9696 NSString *arg1 = [components objectAtIndex:1];
9697 NSString *arg2 = [components objectAtIndex:2];
9698
9699 if ([base isEqualToString:@"package"]) {
9700 if ([arg2 isEqualToString:@"settings"]) {
9701 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9702 } else if ([arg2 isEqualToString:@"files"]) {
9703 if (Package *package = [database_ packageWithName:arg1]) {
9704 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9705 [(FileTable *)controller setPackage:package];
9706 }
9707 }
9708 }
9709 }
9710
9711 [controller setDelegate:self];
9712 return controller;
9713 }
9714
9715 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9716 CyteViewController *page([self pageForURL:url forExternal:external]);
9717
9718 if (page != nil)
9719 [tabbar_ setUnselectedViewController:page];
9720
9721 return page != nil;
9722 }
9723
9724 - (void) applicationOpenURL:(NSURL *)url {
9725 [super applicationOpenURL:url];
9726
9727 if (!loaded_)
9728 starturl_ = url;
9729 else
9730 [self openCydiaURL:url forExternal:YES];
9731 }
9732
9733 - (void) applicationWillResignActive:(UIApplication *)application {
9734 // Stop refreshing if you get a phone call or lock the device.
9735 if ([tabbar_ updating])
9736 [tabbar_ cancelUpdate];
9737
9738 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9739 [super applicationWillResignActive:application];
9740 }
9741
9742 - (void) saveState {
9743 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9744 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9745 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9746 Changed_ = true;
9747
9748 [self _saveConfig];
9749 }
9750
9751 - (void) applicationWillTerminate:(UIApplication *)application {
9752 [self saveState];
9753 }
9754
9755 - (void) setConfigurationData:(NSString *)data {
9756 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9757
9758 if (!conffile_r(data)) {
9759 lprintf("E:invalid conffile\n");
9760 return;
9761 }
9762
9763 NSString *ofile = conffile_r[1];
9764 //NSString *nfile = conffile_r[2];
9765
9766 UIAlertView *alert = [[[UIAlertView alloc]
9767 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9768 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9769 delegate:self
9770 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9771 otherButtonTitles:
9772 UCLocalize("ACCEPT_NEW_COPY"),
9773 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9774 nil
9775 ] autorelease];
9776
9777 [alert setContext:@"conffile"];
9778 [alert setNumberOfRows:2];
9779 [alert show];
9780 }
9781
9782 - (void) addStashController {
9783 ++locked_;
9784 stash_ = [[[StashController alloc] init] autorelease];
9785 [window_ addSubview:[stash_ view]];
9786 }
9787
9788 - (void) removeStashController {
9789 [[stash_ view] removeFromSuperview];
9790 stash_ = nil;
9791 --locked_;
9792 }
9793
9794 - (void) stash {
9795 [self setIdleTimerDisabled:YES];
9796
9797 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9798 UpdateExternalStatus(1);
9799 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9800 UpdateExternalStatus(0);
9801
9802 [self removeStashController];
9803
9804 pid_t pid(ExecFork());
9805 if (pid == 0) {
9806 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9807 perror("launchctl stop");
9808 exit(0);
9809 }
9810
9811 ReapZombie(pid);
9812 }
9813
9814 - (void) setupViewControllers {
9815 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9816
9817 NSMutableArray *items([NSMutableArray arrayWithObjects:
9818 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9819 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9820 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9821 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9822 nil]);
9823
9824 if (IsWildcat_) {
9825 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9826 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9827 } else {
9828 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9829 }
9830
9831 NSMutableArray *controllers([NSMutableArray array]);
9832 for (UITabBarItem *item in items) {
9833 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9834 [controller setTabBarItem:item];
9835 [controllers addObject:controller];
9836 }
9837 [tabbar_ setViewControllers:controllers];
9838
9839 [tabbar_ setUpdateDelegate:self];
9840 }
9841
9842 - (void) _sendMemoryWarningNotification {
9843 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9844 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9845 else
9846 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9847 }
9848
9849 - (void) _sendMemoryWarningNotifications {
9850 while (true) {
9851 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9852 sleep(2);
9853 //usleep(2000000);
9854 }
9855 }
9856
9857 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9858 NSLog(@"--");
9859 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9860 }
9861
9862 - (void) applicationDidFinishLaunching:(id)unused {
9863 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9864
9865 _trace();
9866 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9867 [self setApplicationSupportsShakeToEdit:NO];
9868
9869 @synchronized (HostConfig_) {
9870 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9871 }
9872
9873 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9874 initWithMemoryCapacity:524288
9875 diskCapacity:10485760
9876 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9877 ] autorelease]];
9878
9879 [CydiaWebViewController _initialize];
9880
9881 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9882
9883 // this would disallow http{,s} URLs from accessing this data
9884 //[WebView registerURLSchemeAsLocal:@"cydia"];
9885
9886 Font12_ = [UIFont systemFontOfSize:12];
9887 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9888 Font14_ = [UIFont systemFontOfSize:14];
9889 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9890 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9891
9892 essential_ = [NSMutableArray arrayWithCapacity:4];
9893 broken_ = [NSMutableArray arrayWithCapacity:4];
9894
9895 // XXX: I really need this thing... like, seriously... I'm sorry
9896 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9897
9898 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9899 [window_ orderFront:self];
9900 [window_ makeKey:self];
9901 [window_ setHidden:NO];
9902
9903 if (
9904 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9905 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9906 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9907 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9908 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9909 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9910 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9911 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9912 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9913 false
9914 ) {
9915 [self addStashController];
9916 // XXX: this would be much cleaner as a yieldToSelector:
9917 // that way the removeStashController could happen right here inline
9918 // we also could no longer require the useless stash_ field anymore
9919 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9920 return;
9921 }
9922
9923 database_ = [Database sharedInstance];
9924 [database_ setDelegate:self];
9925
9926 [window_ setUserInteractionEnabled:NO];
9927 [self setupViewControllers];
9928
9929 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9930 [window_ addSubview:[emulated_ view]];
9931
9932 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9933 _trace();
9934 }
9935
9936 - (NSArray *) defaultStartPages {
9937 NSMutableArray *standard = [NSMutableArray array];
9938 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9939 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9940 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9941 if (!IsWildcat_) {
9942 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9943 } else {
9944 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9945 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9946 }
9947 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9948 return standard;
9949 }
9950
9951 - (void) loadData {
9952 _trace();
9953 if (Role_ == nil) {
9954 [window_ setUserInteractionEnabled:YES];
9955 [self showSettings];
9956 return;
9957 } else {
9958 if ([emulated_ modalViewController] != nil)
9959 [emulated_ dismissModalViewControllerAnimated:YES];
9960 [window_ setUserInteractionEnabled:NO];
9961 }
9962
9963 [self reloadDataWithInvocation:nil];
9964 [self refreshIfPossible];
9965 PrintTimes();
9966
9967 [self disemulate];
9968
9969 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9970 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9971 int standardIndex = 0;
9972 NSArray *standard = [self defaultStartPages];
9973
9974 BOOL valid = YES;
9975
9976 if (saved == nil)
9977 valid = NO;
9978
9979 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9980 if (valid && closed != nil) {
9981 NSTimeInterval interval([closed timeIntervalSinceNow]);
9982 // XXX: Is 30 minutes the optimal time here?
9983 if (interval <= -(30*60))
9984 valid = NO;
9985 }
9986
9987 if (valid && [saved count] != [standard count])
9988 valid = NO;
9989
9990 if (valid) {
9991 for (unsigned int i = 0; i < [standard count]; i++) {
9992 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9993 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9994 // but it's good enough for now.
9995 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9996 valid = NO;
9997 break;
9998 }
9999 }
10000 }
10001
10002 NSArray *items = nil;
10003 if (valid) {
10004 [tabbar_ setSelectedIndex:savedIndex];
10005 items = saved;
10006 } else {
10007 [tabbar_ setSelectedIndex:standardIndex];
10008 items = standard;
10009 }
10010
10011 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10012 NSArray *stack = [items objectAtIndex:tab];
10013 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10014 NSMutableArray *current = [NSMutableArray array];
10015
10016 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10017 NSString *addr = [stack objectAtIndex:nav];
10018 NSURL *url = [NSURL URLWithString:addr];
10019 CyteViewController *page = [self pageForURL:url forExternal:NO];
10020 if (page != nil)
10021 [current addObject:page];
10022 }
10023
10024 [navigation setViewControllers:current];
10025 }
10026
10027 // (Try to) show the startup URL.
10028 if (starturl_ != nil) {
10029 [self openCydiaURL:starturl_ forExternal:NO];
10030 starturl_ = nil;
10031 }
10032 }
10033
10034 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10035 if (item != nil && IsWildcat_) {
10036 [sheet showFromBarButtonItem:item animated:YES];
10037 } else {
10038 [sheet showInView:window_];
10039 }
10040 }
10041
10042 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10043 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10044 [progress setTitle:task];
10045 [progress addProgressEvent:event];
10046 }
10047
10048 - (void) addProgressEventForTask:(NSArray *)data {
10049 CydiaProgressEvent *event([data objectAtIndex:0]);
10050 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10051 [self addProgressEvent:event forTask:task];
10052 }
10053
10054 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10055 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10056 }
10057
10058 @end
10059
10060 /*IMP alloc_;
10061 id Alloc_(id self, SEL selector) {
10062 id object = alloc_(self, selector);
10063 lprintf("[%s]A-%p\n", self->isa->name, object);
10064 return object;
10065 }*/
10066
10067 /*IMP dealloc_;
10068 id Dealloc_(id self, SEL selector) {
10069 id object = dealloc_(self, selector);
10070 lprintf("[%s]D-%p\n", self->isa->name, object);
10071 return object;
10072 }*/
10073
10074 Class $WebDefaultUIKitDelegate;
10075
10076 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10077 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10078 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10079 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10080 }
10081
10082 static NSSet *MobilizedFiles_;
10083
10084 static NSURL *MobilizeURL(NSURL *url) {
10085 NSString *path([url path]);
10086 if ([path hasPrefix:@"/var/root/"]) {
10087 NSString *file([path substringFromIndex:10]);
10088 if ([MobilizedFiles_ containsObject:file])
10089 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10090 }
10091
10092 return url;
10093 }
10094
10095 Class $CFXPreferencesPropertyListSource;
10096 @class CFXPreferencesPropertyListSource;
10097
10098 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10099 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10100 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10101 url = MobilizeURL(url);
10102 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10103 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10104 url = old;
10105 [pool release];
10106 return value;
10107 }
10108
10109 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10110 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10111 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10112 url = MobilizeURL(url);
10113 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10114 //NSLog(@"%@ %@", [url absoluteString], value);
10115 url = old;
10116 [pool release];
10117 return value;
10118 }
10119
10120 Class $NSURLConnection;
10121
10122 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10123 NSMutableURLRequest *copy([request mutableCopy]);
10124
10125 NSURL *url([copy URL]);
10126
10127 NSString *host([url host]);
10128 NSString *scheme([[url scheme] lowercaseString]);
10129
10130 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10131
10132 @synchronized (HostConfig_) {
10133 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10134 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10135 [copy setHTTPShouldUsePipelining:YES];
10136
10137 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10138 if ([control isEqualToString:@"max-age=0"])
10139 if ([CachedURLs_ containsObject:url]) {
10140 #if !ForRelease
10141 NSLog(@"~~~: %@", url);
10142 #endif
10143
10144 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10145
10146 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10147 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10148 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10149 }
10150 }
10151
10152 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10153 } return self;
10154 }
10155
10156 int main(int argc, char *argv[]) {
10157 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10158
10159 _trace();
10160
10161 UpdateExternalStatus(0);
10162
10163 if (Class $UIDevice = objc_getClass("UIDevice")) {
10164 UIDevice *device([$UIDevice currentDevice]);
10165 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10166 } else
10167 IsWildcat_ = false;
10168
10169 UIScreen *screen([UIScreen mainScreen]);
10170 if ([screen respondsToSelector:@selector(scale)])
10171 ScreenScale_ = [screen scale];
10172 else
10173 ScreenScale_ = 1;
10174
10175 UIDevice *device([UIDevice currentDevice]);
10176 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10177 Idiom_ = @"iphone";
10178 else {
10179 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10180 if (idiom == UIUserInterfaceIdiomPhone)
10181 Idiom_ = @"iphone";
10182 else if (idiom == UIUserInterfaceIdiomPad)
10183 Idiom_ = @"ipad";
10184 else
10185 NSLog(@"unknown UIUserInterfaceIdiom!");
10186 }
10187
10188 Pcre pattern("^([0-9]+\\.[0-9]+)");
10189
10190 if (pattern([device systemVersion]))
10191 Firmware_ = pattern[1];
10192 if (pattern(Cydia_))
10193 Major_ = pattern[1];
10194
10195 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10196
10197 HostConfig_ = [[[NSObject alloc] init] autorelease];
10198 @synchronized (HostConfig_) {
10199 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10200 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10201 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10202 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10203 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10204 }
10205
10206 NSString *ui(@"ui/ios");
10207 if (Idiom_ != nil)
10208 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10209 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10210 UI_ = CydiaURL(ui);
10211
10212 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10213
10214 MobilizedFiles_ = [NSMutableSet setWithObjects:
10215 @"Library/Preferences/com.apple.Accessibility.plist",
10216 @"Library/Preferences/com.apple.preferences.sounds.plist",
10217 nil];
10218
10219 /* Library Hacks {{{ */
10220 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10221
10222 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10223
10224 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10225 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10226 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10227 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10228 }
10229
10230 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10231 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10232 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10233 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10234 }
10235
10236 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10237 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10238 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10239 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10240 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10241 }
10242
10243 $NSURLConnection = objc_getClass("NSURLConnection");
10244 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10245 if (NSURLConnection$init$ != NULL) {
10246 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10247 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10248 }
10249 /* }}} */
10250 /* Set Locale {{{ */
10251 Locale_ = CFLocaleCopyCurrent();
10252 Languages_ = [NSLocale preferredLanguages];
10253
10254 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10255 //NSLog(@"%@", [Languages_ description]);
10256
10257 const char *lang;
10258 if (Locale_ != NULL)
10259 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10260 else if (Languages_ != nil && [Languages_ count] != 0)
10261 lang = [[Languages_ objectAtIndex:0] UTF8String];
10262 else
10263 // XXX: consider just setting to C and then falling through?
10264 lang = NULL;
10265
10266 if (lang != NULL) {
10267 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10268 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10269 }
10270
10271 NSLog(@"Setting Language: %s", lang);
10272
10273 if (lang != NULL) {
10274 setenv("LANG", lang, true);
10275 std::setlocale(LC_ALL, lang);
10276 }
10277 /* }}} */
10278
10279 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10280
10281 /* Parse Arguments {{{ */
10282 bool substrate(false);
10283
10284 if (argc != 0) {
10285 char **args(argv);
10286 int arge(1);
10287
10288 for (int argi(1); argi != argc; ++argi)
10289 if (strcmp(argv[argi], "--") == 0) {
10290 arge = argi;
10291 argv[argi] = argv[0];
10292 argv += argi;
10293 argc -= argi;
10294 break;
10295 }
10296
10297 for (int argi(1); argi != arge; ++argi)
10298 if (strcmp(args[argi], "--substrate") == 0)
10299 substrate = true;
10300 else
10301 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10302 }
10303 /* }}} */
10304
10305 App_ = [[NSBundle mainBundle] bundlePath];
10306 Advanced_ = YES;
10307
10308 setuid(0);
10309 setgid(0);
10310
10311 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10312 alloc_ = alloc->method_imp;
10313 alloc->method_imp = (IMP) &Alloc_;*/
10314
10315 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10316 dealloc_ = dealloc->method_imp;
10317 dealloc->method_imp = (IMP) &Dealloc_;*/
10318
10319 /* System Information {{{ */
10320 size_t size;
10321
10322 int maxproc;
10323 size = sizeof(maxproc);
10324 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10325 perror("sysctlbyname(\"kern.maxproc\", ?)");
10326 else if (maxproc < 64) {
10327 maxproc = 64;
10328 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10329 perror("sysctlbyname(\"kern.maxproc\", #)");
10330 }
10331
10332 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10333 char *osversion = new char[size];
10334 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10335 perror("sysctlbyname(\"kern.osversion\", ?)");
10336 else
10337 System_ = [NSString stringWithUTF8String:osversion];
10338
10339 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10340 char *machine = new char[size];
10341 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10342 perror("sysctlbyname(\"hw.machine\", ?)");
10343 else
10344 Machine_ = machine;
10345
10346 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10347 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10348 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10349
10350 UniqueID_ = [device uniqueIdentifier];
10351
10352 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10353 Product_ = [info objectForKey:@"SafariProductVersion"];
10354 Safari_ = [info objectForKey:@"CFBundleVersion"];
10355 }
10356
10357 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10358
10359 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10360 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10361 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10362 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10363 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10364 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10365
10366 UserAgent_ = agent;
10367 /* }}} */
10368 /* Load Database {{{ */
10369 _trace();
10370 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10371 _trace();
10372 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10373
10374 if (Metadata_ == NULL)
10375 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10376 else {
10377 Settings_ = [Metadata_ objectForKey:@"Settings"];
10378
10379 Packages_ = [Metadata_ objectForKey:@"Packages"];
10380
10381 Values_ = [Metadata_ objectForKey:@"Values"];
10382 Sections_ = [Metadata_ objectForKey:@"Sections"];
10383 Sources_ = [Metadata_ objectForKey:@"Sources"];
10384
10385 Token_ = [Metadata_ objectForKey:@"Token"];
10386
10387 Version_ = [Metadata_ objectForKey:@"Version"];
10388 }
10389
10390 if (Settings_ != nil)
10391 Role_ = [Settings_ objectForKey:@"Role"];
10392
10393 if (Values_ == nil) {
10394 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10395 [Metadata_ setObject:Values_ forKey:@"Values"];
10396 }
10397
10398 if (Sections_ == nil) {
10399 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10400 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10401 }
10402
10403 if (Sources_ == nil) {
10404 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10405 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10406 }
10407
10408 if (Version_ == nil) {
10409 Version_ = [NSNumber numberWithUnsignedInt:0];
10410 [Metadata_ setObject:Version_ forKey:@"Version"];
10411 }
10412
10413 if ([Version_ unsignedIntValue] == 0) {
10414 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10415 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10416 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10417 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10418
10419 Version_ = [NSNumber numberWithUnsignedInt:1];
10420 [Metadata_ setObject:Version_ forKey:@"Version"];
10421
10422 [Metadata_ removeObjectForKey:@"LastUpdate"];
10423
10424 Changed_ = true;
10425 }
10426 /* }}} */
10427
10428 CydiaWriteSources();
10429
10430 _trace();
10431 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10432 _trace();
10433
10434 if (Packages_ != nil) {
10435 bool fail(false);
10436 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10437 _trace();
10438
10439 if (!fail) {
10440 [Metadata_ removeObjectForKey:@"Packages"];
10441 Packages_ = nil;
10442 Changed_ = true;
10443 }
10444 }
10445
10446 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10447
10448 #define MobileSubstrate_(name) \
10449 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10450 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10451 if (handle == NULL) \
10452 NSLog(@"%s", dlerror()); \
10453 }
10454
10455 MobileSubstrate_(Activator)
10456 MobileSubstrate_(libstatusbar)
10457 MobileSubstrate_(SimulatedKeyEvents)
10458 MobileSubstrate_(WinterBoard)
10459
10460 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10461 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10462
10463 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10464
10465 if (access("/User", F_OK) != 0 || version != 5) {
10466 _trace();
10467 system("/usr/libexec/cydia/firmware.sh");
10468 _trace();
10469 }
10470
10471 _assert([[NSFileManager defaultManager]
10472 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10473 withIntermediateDirectories:YES
10474 attributes:nil
10475 error:NULL
10476 ]);
10477
10478 if (access("/tmp/cydia.chk", F_OK) == 0) {
10479 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10480 _assert(errno == ENOENT);
10481 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10482 _assert(errno == ENOENT);
10483 }
10484
10485 /* APT Initialization {{{ */
10486 _assert(pkgInitConfig(*_config));
10487 _assert(pkgInitSystem(*_config, _system));
10488
10489 if (lang != NULL)
10490 _config->Set("APT::Acquire::Translation", lang);
10491
10492 // XXX: this timeout might be important :(
10493 //_config->Set("Acquire::http::Timeout", 15);
10494
10495 _config->Set("Acquire::http::MaxParallel", 3);
10496 /* }}} */
10497 /* Color Choices {{{ */
10498 space_ = CGColorSpaceCreateDeviceRGB();
10499
10500 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10501 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10502 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10503 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10504 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10505 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10506 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10507 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10508 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10509
10510 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10511 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10512 /* }}}*/
10513 /* UIKit Configuration {{{ */
10514 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10515 if ($GSFontSetUseLegacyFontMetrics != NULL)
10516 $GSFontSetUseLegacyFontMetrics(YES);
10517
10518 // XXX: I have a feeling this was important
10519 //UIKeyboardDisableAutomaticAppearance();
10520 /* }}} */
10521
10522 Colon_ = UCLocalize("COLON_DELIMITED");
10523 Elision_ = UCLocalize("ELISION");
10524 Error_ = UCLocalize("ERROR");
10525 Warning_ = UCLocalize("WARNING");
10526
10527 #if !ForRelease
10528 AprilFools_ = true;
10529 #else
10530 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10531 AprilFools_ = date.month == 4 && date.day == 1;
10532 #endif
10533
10534 _trace();
10535 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10536
10537 CGColorSpaceRelease(space_);
10538 CFRelease(Locale_);
10539
10540 [pool release];
10541 return value;
10542 }