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