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