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