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