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