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