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