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