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