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