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