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