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