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