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