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