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