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