]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
I apparently lost this rotation commit somewhere.
[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 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3137 const char *name(iterator_.Name());
3138
3139 size_t length(strlen(name));
3140 if (length < 2) invalid:
3141 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3142 else for (size_t i(0); i != length; ++i)
3143 if (
3144 /* XXX: technically this is not allowed */
3145 (name[i] < 'A' || name[i] > 'Z') &&
3146 (name[i] < 'a' || name[i] > 'z') &&
3147 (name[i] < '0' || name[i] > '9') &&
3148 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3149 ) goto invalid;
3150
3151 if (strcmp(name, "cydia") != 0) {
3152 bool cydia = false;
3153 bool user = false;
3154 bool _private = false;
3155 bool stash = false;
3156 bool dsstore = false;
3157
3158 bool repository = [[self section] isEqualToString:@"Repositories"];
3159
3160 if (NSArray *files = [self files])
3161 for (NSString *file in files)
3162 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3163 cydia = true;
3164 else if (!user && [file isEqualToString:@"/User"])
3165 user = true;
3166 else if (!_private && [file isEqualToString:@"/private"])
3167 _private = true;
3168 else if (!stash && [file isEqualToString:@"/var/stash"])
3169 stash = true;
3170 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3171 dsstore = true;
3172
3173 /* XXX: this is not sensitive enough. only some folders are valid. */
3174 if (cydia && !repository)
3175 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3176 if (user)
3177 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3178 if (_private)
3179 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3180 if (stash)
3181 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3182 if (dsstore)
3183 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3184 }
3185
3186 return [warnings count] == 0 ? nil : warnings;
3187 }
3188
3189 - (NSArray *) applications {
3190 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3191
3192 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3193
3194 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3195 if (NSArray *files = [self files])
3196 for (NSString *file in files)
3197 if (application_r(file)) {
3198 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3199 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3200 if ([id isEqualToString:me])
3201 continue;
3202
3203 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3204 if (display == nil)
3205 display = application_r[1];
3206
3207 NSString *bundle([file stringByDeletingLastPathComponent]);
3208 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3209 // XXX: maybe this should check if this is really a string, not just for length
3210 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3211 icon = @"icon.png";
3212 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3213
3214 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3215 [applications addObject:application];
3216
3217 [application addObject:id];
3218 [application addObject:display];
3219 [application addObject:url];
3220 }
3221
3222 return [applications count] == 0 ? nil : applications;
3223 }
3224
3225 - (Source *) source {
3226 if (source_ == nil) {
3227 @synchronized (database_) {
3228 if ([database_ era] != era_ || file_.end())
3229 source_ = (Source *) [NSNull null];
3230 else
3231 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3232 }
3233 }
3234
3235 return source_ == (Source *) [NSNull null] ? nil : source_;
3236 }
3237
3238 - (time_t) upgraded {
3239 return upgraded_;
3240 }
3241
3242 - (uint32_t) recent {
3243 return std::numeric_limits<uint32_t>::max() - upgraded_;
3244 }
3245
3246 - (uint32_t) rank {
3247 return rank_;
3248 }
3249
3250 - (BOOL) matches:(NSArray *)query {
3251 if (query == nil || [query count] == 0)
3252 return NO;
3253
3254 rank_ = 0;
3255
3256 NSString *string;
3257 NSRange range;
3258 NSUInteger length;
3259
3260 string = [self name];
3261 length = [string length];
3262
3263 if (length != 0)
3264 for (NSString *term in query) {
3265 range = [string rangeOfString:term options:MatchCompareOptions_];
3266 if (range.location != NSNotFound)
3267 rank_ -= 6 * 1000000 / length;
3268 }
3269
3270 if (rank_ == 0) {
3271 string = [self id];
3272 length = [string length];
3273
3274 if (length != 0)
3275 for (NSString *term in query) {
3276 range = [string rangeOfString:term options:MatchCompareOptions_];
3277 if (range.location != NSNotFound)
3278 rank_ -= 6 * 1000000 / length;
3279 }
3280 }
3281
3282 string = [self shortDescription];
3283 length = [string length];
3284 NSUInteger stop(std::min<NSUInteger>(length, 200));
3285
3286 if (length != 0)
3287 for (NSString *term in query) {
3288 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3289 if (range.location != NSNotFound)
3290 rank_ -= 2 * 100000;
3291 }
3292
3293 return rank_ != 0;
3294 }
3295
3296 - (NSArray *) tags {
3297 return tags_;
3298 }
3299
3300 - (BOOL) hasTag:(NSString *)tag {
3301 return tags_ == nil ? NO : [tags_ containsObject:tag];
3302 }
3303
3304 - (NSString *) primaryPurpose {
3305 for (NSString *tag in (NSArray *) tags_)
3306 if ([tag hasPrefix:@"purpose::"])
3307 return [tag substringFromIndex:9];
3308 return nil;
3309 }
3310
3311 - (NSArray *) purposes {
3312 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3313 for (NSString *tag in (NSArray *) tags_)
3314 if ([tag hasPrefix:@"purpose::"])
3315 [purposes addObject:[tag substringFromIndex:9]];
3316 return [purposes count] == 0 ? nil : purposes;
3317 }
3318
3319 - (bool) isCommercial {
3320 return [self hasTag:@"cydia::commercial"];
3321 }
3322
3323 - (void) setIndex:(size_t)index {
3324 if (metadata_->index_ != index)
3325 metadata_->index_ = index;
3326 }
3327
3328 - (CYString &) cyname {
3329 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3330 }
3331
3332 - (uint32_t) compareBySection:(NSArray *)sections {
3333 NSString *section([self section]);
3334 for (size_t i(0), e([sections count]); i != e; ++i) {
3335 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3336 return i;
3337 }
3338
3339 return _not(uint32_t);
3340 }
3341
3342 - (void) clear {
3343 @synchronized (database_) {
3344 pkgProblemResolver *resolver = [database_ resolver];
3345 resolver->Clear(iterator_);
3346
3347 pkgCacheFile &cache([database_ cache]);
3348 cache->SetReInstall(iterator_, false);
3349 cache->MarkKeep(iterator_, false);
3350 } }
3351
3352 - (void) install {
3353 @synchronized (database_) {
3354 pkgProblemResolver *resolver = [database_ resolver];
3355 resolver->Clear(iterator_);
3356 resolver->Protect(iterator_);
3357
3358 pkgCacheFile &cache([database_ cache]);
3359 cache->SetReInstall(iterator_, false);
3360 cache->MarkInstall(iterator_, false);
3361
3362 pkgDepCache::StateCache &state((*cache)[iterator_]);
3363 if (!state.Install())
3364 cache->SetReInstall(iterator_, true);
3365 } }
3366
3367 - (void) remove {
3368 @synchronized (database_) {
3369 pkgProblemResolver *resolver = [database_ resolver];
3370 resolver->Clear(iterator_);
3371 resolver->Remove(iterator_);
3372 resolver->Protect(iterator_);
3373
3374 pkgCacheFile &cache([database_ cache]);
3375 cache->SetReInstall(iterator_, false);
3376 cache->MarkDelete(iterator_, true);
3377 } }
3378
3379 @end
3380 /* }}} */
3381 /* Section Class {{{ */
3382 @interface Section : NSObject {
3383 _H<NSString> name_;
3384 size_t row_;
3385 size_t count_;
3386 _H<NSString> localized_;
3387 }
3388
3389 - (NSComparisonResult) compareByLocalized:(Section *)section;
3390 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3391 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3392 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3393
3394 - (NSString *) name;
3395 - (void) setName:(NSString *)name;
3396
3397 - (size_t) row;
3398 - (size_t) count;
3399
3400 - (void) addToRow;
3401 - (void) addToCount;
3402
3403 - (void) setCount:(size_t)count;
3404 - (NSString *) localized;
3405
3406 @end
3407
3408 @implementation Section
3409
3410 - (NSComparisonResult) compareByLocalized:(Section *)section {
3411 NSString *lhs(localized_);
3412 NSString *rhs([section localized]);
3413
3414 /*if ([lhs length] != 0 && [rhs length] != 0) {
3415 unichar lhc = [lhs characterAtIndex:0];
3416 unichar rhc = [rhs characterAtIndex:0];
3417
3418 if (isalpha(lhc) && !isalpha(rhc))
3419 return NSOrderedAscending;
3420 else if (!isalpha(lhc) && isalpha(rhc))
3421 return NSOrderedDescending;
3422 }*/
3423
3424 return [lhs compare:rhs options:LaxCompareOptions_];
3425 }
3426
3427 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3428 if ((self = [self initWithName:name localize:NO]) != nil) {
3429 if (localized != nil)
3430 localized_ = localized;
3431 } return self;
3432 }
3433
3434 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3435 return [self initWithName:name row:0 localize:localize];
3436 }
3437
3438 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3439 if ((self = [super init]) != nil) {
3440 name_ = name;
3441 row_ = row;
3442 if (localize)
3443 localized_ = LocalizeSection(name_);
3444 } return self;
3445 }
3446
3447 - (NSString *) name {
3448 return name_;
3449 }
3450
3451 - (void) setName:(NSString *)name {
3452 name_ = name;
3453 }
3454
3455 - (size_t) row {
3456 return row_;
3457 }
3458
3459 - (size_t) count {
3460 return count_;
3461 }
3462
3463 - (void) addToRow {
3464 ++row_;
3465 }
3466
3467 - (void) addToCount {
3468 ++count_;
3469 }
3470
3471 - (void) setCount:(size_t)count {
3472 count_ = count;
3473 }
3474
3475 - (NSString *) localized {
3476 return localized_;
3477 }
3478
3479 @end
3480 /* }}} */
3481
3482 class CydiaLogCleaner :
3483 public pkgArchiveCleaner
3484 {
3485 protected:
3486 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3487 unlink(File);
3488 }
3489 };
3490
3491 /* Database Implementation {{{ */
3492 @implementation Database
3493
3494 + (Database *) sharedInstance {
3495 static _H<Database> instance;
3496 if (instance == nil)
3497 instance = [[[Database alloc] init] autorelease];
3498 return instance;
3499 }
3500
3501 - (unsigned) era {
3502 return era_;
3503 }
3504
3505 - (void) releasePackages {
3506 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3507 CFArrayRemoveAllValues(packages_);
3508 }
3509
3510 - (void) dealloc {
3511 // XXX: actually implement this thing
3512 _assert(false);
3513 [self releasePackages];
3514 apr_pool_destroy(pool_);
3515 NSRecycleZone(zone_);
3516 [super dealloc];
3517 }
3518
3519 - (void) _readCydia:(NSNumber *)fd {
3520 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3521 std::istream is(&ib);
3522 std::string line;
3523
3524 static Pcre finish_r("^finish:([^:]*)$");
3525
3526 while (std::getline(is, line)) {
3527 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3528
3529 const char *data(line.c_str());
3530 size_t size = line.size();
3531 lprintf("C:%s\n", data);
3532
3533 if (finish_r(data, size)) {
3534 NSString *finish = finish_r[1];
3535 int index = [Finishes_ indexOfObject:finish];
3536 if (index != INT_MAX && index > Finish_)
3537 Finish_ = index;
3538 }
3539
3540 [pool release];
3541 }
3542
3543 _assume(false);
3544 }
3545
3546 - (void) _readStatus:(NSNumber *)fd {
3547 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3548 std::istream is(&ib);
3549 std::string line;
3550
3551 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3552 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3553
3554 while (std::getline(is, line)) {
3555 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3556
3557 const char *data(line.c_str());
3558 size_t size(line.size());
3559 lprintf("S:%s\n", data);
3560
3561 if (conffile_r(data, size)) {
3562 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3563 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3564 } else if (strncmp(data, "status: ", 8) == 0) {
3565 // status: <package>: {unpacked,half-configured,installed}
3566 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3567 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3568 } else if (strncmp(data, "processing: ", 12) == 0) {
3569 // processing: configure: config-test
3570 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3571 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3572 } else if (pmstatus_r(data, size)) {
3573 std::string type([pmstatus_r[1] UTF8String]);
3574
3575 NSString *package = pmstatus_r[2];
3576 if ([package isEqualToString:@"dpkg-exec"])
3577 package = nil;
3578
3579 float percent([pmstatus_r[3] floatValue]);
3580 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3581
3582 NSString *string = pmstatus_r[4];
3583
3584 if (type == "pmerror") {
3585 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3586 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3587 } else if (type == "pmstatus") {
3588 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3589 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3590 } else if (type == "pmconffile")
3591 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3592 else
3593 lprintf("E:unknown pmstatus\n");
3594 } else
3595 lprintf("E:unknown status\n");
3596
3597 [pool release];
3598 }
3599
3600 _assume(false);
3601 }
3602
3603 - (void) _readOutput:(NSNumber *)fd {
3604 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3605 std::istream is(&ib);
3606 std::string line;
3607
3608 while (std::getline(is, line)) {
3609 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3610
3611 lprintf("O:%s\n", line.c_str());
3612
3613 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3614 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3615
3616 [pool release];
3617 }
3618
3619 _assume(false);
3620 }
3621
3622 - (FILE *) input {
3623 return input_;
3624 }
3625
3626 - (Package *) packageWithName:(NSString *)name {
3627 if (name == nil)
3628 return nil;
3629 @synchronized (self) {
3630 if (static_cast<pkgDepCache *>(cache_) == NULL)
3631 return nil;
3632 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3633 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3634 } }
3635
3636 - (id) init {
3637 if ((self = [super init]) != nil) {
3638 policy_ = NULL;
3639 records_ = NULL;
3640 resolver_ = NULL;
3641 fetcher_ = NULL;
3642 lock_ = NULL;
3643
3644 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3645 apr_pool_create(&pool_, NULL);
3646
3647 size_t capacity(MetaFile_->active_);
3648 if (capacity == 0)
3649 capacity = 16384;
3650 else
3651 capacity += 1024;
3652
3653 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3654 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3655
3656 int fds[2];
3657
3658 _assert(pipe(fds) != -1);
3659 cydiafd_ = fds[1];
3660
3661 _config->Set("APT::Keep-Fds::", cydiafd_);
3662 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3663
3664 [NSThread
3665 detachNewThreadSelector:@selector(_readCydia:)
3666 toTarget:self
3667 withObject:[NSNumber numberWithInt:fds[0]]
3668 ];
3669
3670 _assert(pipe(fds) != -1);
3671 statusfd_ = fds[1];
3672
3673 [NSThread
3674 detachNewThreadSelector:@selector(_readStatus:)
3675 toTarget:self
3676 withObject:[NSNumber numberWithInt:fds[0]]
3677 ];
3678
3679 _assert(pipe(fds) != -1);
3680 _assert(dup2(fds[0], 0) != -1);
3681 _assert(close(fds[0]) != -1);
3682
3683 input_ = fdopen(fds[1], "a");
3684
3685 _assert(pipe(fds) != -1);
3686 _assert(dup2(fds[1], 1) != -1);
3687 _assert(close(fds[1]) != -1);
3688
3689 [NSThread
3690 detachNewThreadSelector:@selector(_readOutput:)
3691 toTarget:self
3692 withObject:[NSNumber numberWithInt:fds[0]]
3693 ];
3694 } return self;
3695 }
3696
3697 - (pkgCacheFile &) cache {
3698 return cache_;
3699 }
3700
3701 - (pkgDepCache::Policy *) policy {
3702 return policy_;
3703 }
3704
3705 - (pkgRecords *) records {
3706 return records_;
3707 }
3708
3709 - (pkgProblemResolver *) resolver {
3710 return resolver_;
3711 }
3712
3713 - (pkgAcquire &) fetcher {
3714 return *fetcher_;
3715 }
3716
3717 - (pkgSourceList &) list {
3718 return *list_;
3719 }
3720
3721 - (NSArray *) packages {
3722 return (NSArray *) packages_;
3723 }
3724
3725 - (NSArray *) sources {
3726 return sourceList_;
3727 }
3728
3729 - (Source *) sourceWithKey:(NSString *)key {
3730 for (Source *source in [self sources]) {
3731 if ([[source key] isEqualToString:key])
3732 return source;
3733 } return nil;
3734 }
3735
3736 - (bool) popErrorWithTitle:(NSString *)title {
3737 bool fatal(false);
3738
3739 while (!_error->empty()) {
3740 std::string error;
3741 bool warning(!_error->PopMessage(error));
3742 if (!warning)
3743 fatal = true;
3744
3745 for (;;) {
3746 size_t size(error.size());
3747 if (size == 0 || error[size - 1] != '\n')
3748 break;
3749 error.resize(size - 1);
3750 }
3751
3752 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3753
3754 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3755 if (warning && no_pubkey(error.c_str()))
3756 continue;
3757
3758 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3759 }
3760
3761 return fatal;
3762 }
3763
3764 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3765 return [self popErrorWithTitle:title] || !success;
3766 }
3767
3768 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3769 @synchronized (self) {
3770 ++era_;
3771
3772 [self releasePackages];
3773
3774 sourceMap_.clear();
3775 [sourceList_ removeAllObjects];
3776
3777 _error->Discard();
3778
3779 delete list_;
3780 list_ = NULL;
3781 manager_ = NULL;
3782 delete lock_;
3783 lock_ = NULL;
3784 delete fetcher_;
3785 fetcher_ = NULL;
3786 delete resolver_;
3787 resolver_ = NULL;
3788 delete records_;
3789 records_ = NULL;
3790 delete policy_;
3791 policy_ = NULL;
3792
3793 cache_.Close();
3794
3795 apr_pool_clear(pool_);
3796
3797 NSRecycleZone(zone_);
3798 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3799
3800 int chk(creat("/tmp/cydia.chk", 0644));
3801 if (chk != -1)
3802 close(chk);
3803
3804 if (invocation != nil)
3805 [invocation invoke];
3806
3807 NSString *title(UCLocalize("DATABASE"));
3808
3809 list_ = new pkgSourceList();
3810 _profile(reloadDataWithInvocation$ReadMainList)
3811 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3812 return;
3813 _end
3814
3815 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3816 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3817 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3818 [sourceList_ addObject:object];
3819 }
3820 _end
3821
3822 _root(_system->Lock());
3823
3824 _trace();
3825 OpProgress progress;
3826 bool opened;
3827 open:
3828 _profile(reloadDataWithInvocation$pkgCacheFile)
3829 opened = cache_.Open(progress, false);
3830 _end
3831 if (!opened) {
3832 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3833 while (!_error->empty()) {
3834 std::string error;
3835 bool warning(!_error->PopMessage(error));
3836
3837 lprintf("cache_.Open():[%s]\n", error.c_str());
3838
3839 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3840
3841 SEL repair(NULL);
3842 if (false);
3843 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3844 repair = @selector(configure);
3845 //else if (error == "The package lists or status file could not be parsed or opened.")
3846 // repair = @selector(update);
3847 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3848 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3849 // else if (error == "Malformed Status line")
3850 // else if (error == "The list of sources could not be read.")
3851
3852 if (repair != NULL) {
3853 _error->Discard();
3854 [delegate_ repairWithSelector:repair];
3855 goto open;
3856 }
3857 }
3858
3859 _system->UnLock();
3860 return;
3861 }
3862 _trace();
3863
3864 unlink("/tmp/cydia.chk");
3865
3866 now_ = [[NSDate date] timeIntervalSince1970];
3867
3868 policy_ = new pkgDepCache::Policy();
3869 records_ = new pkgRecords(cache_);
3870 resolver_ = new pkgProblemResolver(cache_);
3871 fetcher_ = new pkgAcquire(&status_);
3872 lock_ = NULL;
3873
3874 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3875 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3876 return;
3877 }
3878
3879 _profile(reloadDataWithInvocation$pkgApplyStatus)
3880 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3881 return;
3882 _end
3883
3884 if (cache_->BrokenCount() != 0) {
3885 _profile(pkgApplyStatus$pkgFixBroken)
3886 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3887 return;
3888 _end
3889
3890 if (cache_->BrokenCount() != 0) {
3891 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3892 return;
3893 }
3894
3895 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3896 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3897 return;
3898 _end
3899 }
3900
3901 for (Source *object in (id) sourceList_) {
3902 metaIndex *source([object metaIndex]);
3903 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3904 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3905 // XXX: this could be more intelligent
3906 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3907 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3908 if (!cached.end())
3909 sourceMap_[cached->ID] = object;
3910 }
3911 }
3912
3913 {
3914 /*std::vector<Package *> packages;
3915 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3916 packages_ = nil;*/
3917
3918 _profile(reloadDataWithInvocation$packageWithIterator)
3919 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3920 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3921 //packages.push_back(package);
3922 CFArrayAppendValue(packages_, CFRetain(package));
3923 _end
3924
3925
3926 /*if (packages.empty())
3927 packages_ = [[NSArray alloc] init];
3928 else
3929 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3930 _trace();*/
3931
3932 _profile(reloadDataWithInvocation$radix$8)
3933 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3934 _end
3935
3936 _profile(reloadDataWithInvocation$radix$4)
3937 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3938 _end
3939
3940 _profile(reloadDataWithInvocation$radix$0)
3941 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3942 _end
3943
3944 _profile(reloadDataWithInvocation$insertion)
3945 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3946 _end
3947
3948 /*_profile(reloadDataWithInvocation$CFQSortArray)
3949 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3950 _end*/
3951
3952 /*_profile(reloadDataWithInvocation$stdsort)
3953 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3954 _end*/
3955
3956 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3957 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3958 _end*/
3959
3960 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3961 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3962 _end*/
3963
3964
3965 size_t count(CFArrayGetCount(packages_));
3966 MetaFile_->active_ = count;
3967 for (size_t index(0); index != count; ++index)
3968 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3969 }
3970 } }
3971
3972 - (void) clear {
3973 @synchronized (self) {
3974 delete resolver_;
3975 resolver_ = new pkgProblemResolver(cache_);
3976
3977 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3978 if (!cache_[iterator].Keep())
3979 cache_->MarkKeep(iterator, false);
3980 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3981 cache_->SetReInstall(iterator, false);
3982 } }
3983
3984 - (void) configure {
3985 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3986 _trace();
3987 _root(system([dpkg UTF8String]));
3988 _trace();
3989 }
3990
3991 - (bool) clean {
3992 @synchronized (self) {
3993 // XXX: I don't remember this condition
3994 if (lock_ != NULL)
3995 return false;
3996
3997 FileFd Lock;
3998 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3999
4000 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4001
4002 if ([self popErrorWithTitle:title])
4003 return false;
4004
4005 pkgAcquire fetcher;
4006 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4007
4008 CydiaLogCleaner cleaner;
4009 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4010 return false;
4011
4012 return true;
4013 } }
4014
4015 - (bool) prepare {
4016 fetcher_->Shutdown();
4017
4018 pkgRecords records(cache_);
4019
4020 lock_ = new FileFd();
4021 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4022
4023 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4024
4025 if ([self popErrorWithTitle:title])
4026 return false;
4027
4028 pkgSourceList list;
4029 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4030 return false;
4031
4032 manager_ = (_system->CreatePM(cache_));
4033 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4034 return false;
4035
4036 return true;
4037 }
4038
4039 - (void) perform {
4040 bool substrate(RestartSubstrate_);
4041 RestartSubstrate_ = false;
4042
4043 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4044
4045 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4046 pkgSourceList list;
4047 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4048 return;
4049 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4050 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4051 }
4052
4053 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4054
4055 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4056 _trace();
4057 [self popErrorWithTitle:title];
4058 return;
4059 }
4060
4061 bool failed = false;
4062 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4063 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4064 continue;
4065 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4066 continue;
4067
4068 std::string uri = (*item)->DescURI();
4069 std::string error = (*item)->ErrorText;
4070
4071 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4072 failed = true;
4073
4074 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4075 [delegate_ addProgressEventOnMainThread:event forTask:title];
4076 }
4077
4078 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4079
4080 if (failed) {
4081 _trace();
4082 return;
4083 }
4084
4085 if (substrate)
4086 RestartSubstrate_ = true;
4087
4088 _system->UnLock();
4089 pkgPackageManager::OrderResult result(_root(manager_->DoInstall(statusfd_)));
4090 if ([self popErrorWithTitle:title])
4091 return;
4092
4093 if (result == pkgPackageManager::Failed) {
4094 _trace();
4095 return;
4096 }
4097
4098 if (result != pkgPackageManager::Completed) {
4099 _trace();
4100 return;
4101 }
4102
4103 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4104 pkgSourceList list;
4105 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4106 return;
4107 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4108 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4109 }
4110
4111 if (![before isEqualToArray:after])
4112 [self update];
4113 }
4114
4115 - (bool) upgrade {
4116 NSString *title(UCLocalize("UPGRADE"));
4117 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4118 return false;
4119 return true;
4120 }
4121
4122 - (void) update {
4123 [self updateWithStatus:status_];
4124 }
4125
4126 - (void) updateWithStatus:(CancelStatus &)status {
4127 NSString *title(UCLocalize("REFRESHING_DATA"));
4128
4129 pkgSourceList list;
4130 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4131 return;
4132
4133 FileFd lock;
4134 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4135 if ([self popErrorWithTitle:title])
4136 return;
4137
4138 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4139
4140 bool success(ListUpdate(status, list, PulseInterval_));
4141 if (status.WasCancelled())
4142 _error->Discard();
4143 else {
4144 [self popErrorWithTitle:title forOperation:success];
4145 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4146 Changed_ = true;
4147 }
4148
4149 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4150 }
4151
4152 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4153 delegate_ = delegate;
4154 }
4155
4156 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4157 progress_ = delegate;
4158 status_.setDelegate(delegate);
4159 }
4160
4161 - (NSObject<ProgressDelegate> *) progressDelegate {
4162 return progress_;
4163 }
4164
4165 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4166 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4167 return i == sourceMap_.end() ? nil : i->second;
4168 }
4169
4170 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4171 for (Source *source in (id) sourceList_)
4172 [source setFetch:fetch forURI:uri];
4173 }
4174
4175 - (void) resetFetch {
4176 for (Source *source in (id) sourceList_)
4177 [source resetFetch];
4178 }
4179
4180 - (NSString *) mappedSectionForPointer:(const char *)section {
4181 _H<NSString> *mapped;
4182
4183 _profile(Database$mappedSectionForPointer$Cache)
4184 mapped = &sections_[section];
4185 _end
4186
4187 if (*mapped == NULL) {
4188 size_t length(strlen(section));
4189 char spaced[length + 1];
4190
4191 _profile(Database$mappedSectionForPointer$Replace)
4192 for (size_t index(0); index != length; ++index)
4193 spaced[index] = section[index] == '_' ? ' ' : section[index];
4194 spaced[length] = '\0';
4195 _end
4196
4197 NSString *string;
4198
4199 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4200 string = [NSString stringWithUTF8String:spaced];
4201 _end
4202
4203 _profile(Database$mappedSectionForPointer$Map)
4204 string = [SectionMap_ objectForKey:string] ?: string;
4205 _end
4206
4207 *mapped = string;
4208 } return *mapped;
4209 }
4210
4211 @end
4212 /* }}} */
4213
4214 static _H<NSMutableSet> Diversions_;
4215
4216 @interface Diversion : NSObject {
4217 Pcre pattern_;
4218 _H<NSString> key_;
4219 _H<NSString> format_;
4220 }
4221
4222 @end
4223
4224 @implementation Diversion
4225
4226 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4227 if ((self = [super init]) != nil) {
4228 pattern_ = [from UTF8String];
4229 key_ = from;
4230 format_ = to;
4231 } return self;
4232 }
4233
4234 - (NSString *) divert:(NSString *)url {
4235 return !pattern_(url) ? nil : pattern_->*format_;
4236 }
4237
4238 + (NSURL *) divertURL:(NSURL *)url {
4239 divert:
4240 NSString *href([url absoluteString]);
4241
4242 for (Diversion *diversion in (id) Diversions_)
4243 if (NSString *diverted = [diversion divert:href]) {
4244 #if !ForRelease
4245 NSLog(@"div: %@", diverted);
4246 #endif
4247 url = [NSURL URLWithString:diverted];
4248 goto divert;
4249 }
4250
4251 return url;
4252 }
4253
4254 - (NSString *) key {
4255 return key_;
4256 }
4257
4258 - (NSUInteger) hash {
4259 return [key_ hash];
4260 }
4261
4262 - (BOOL) isEqual:(Diversion *)object {
4263 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4264 }
4265
4266 @end
4267
4268 @interface CydiaObject : NSObject {
4269 _H<CyteWebViewController> indirect_;
4270 _transient id delegate_;
4271 }
4272
4273 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4274
4275 @end
4276
4277 @class CydiaObject;
4278
4279 @interface CydiaWebViewController : CyteWebViewController {
4280 _H<CydiaObject> cydia_;
4281 }
4282
4283 + (void) addDiversion:(Diversion *)diversion;
4284 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4285 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4286 - (void) setDelegate:(id)delegate;
4287
4288 @end
4289
4290 /* Web Scripting {{{ */
4291 @implementation CydiaObject
4292
4293 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4294 if ((self = [super init]) != nil) {
4295 indirect_ = (CyteWebViewController *) indirect;
4296 } return self;
4297 }
4298
4299 - (void) setDelegate:(id)delegate {
4300 delegate_ = delegate;
4301 }
4302
4303 + (NSArray *) _attributeKeys {
4304 return [NSArray arrayWithObjects:
4305 @"bbsnum",
4306 @"build",
4307 @"coreFoundationVersionNumber",
4308 @"device",
4309 @"ecid",
4310 @"firmware",
4311 @"hostname",
4312 @"idiom",
4313 @"mcc",
4314 @"mnc",
4315 @"model",
4316 @"operator",
4317 @"role",
4318 @"serial",
4319 @"token",
4320 @"version",
4321 nil];
4322 }
4323
4324 - (NSArray *) attributeKeys {
4325 return [[self class] _attributeKeys];
4326 }
4327
4328 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4329 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4330 }
4331
4332 - (NSString *) version {
4333 return Cydia_;
4334 }
4335
4336 - (NSString *) build {
4337 return System_;
4338 }
4339
4340 - (NSString *) coreFoundationVersionNumber {
4341 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4342 }
4343
4344 - (NSString *) device {
4345 return UniqueIdentifier();
4346 }
4347
4348 - (NSString *) firmware {
4349 return [[UIDevice currentDevice] systemVersion];
4350 }
4351
4352 - (NSString *) hostname {
4353 return [[UIDevice currentDevice] name];
4354 }
4355
4356 - (NSString *) idiom {
4357 return (id) Idiom_ ?: [NSNull null];
4358 }
4359
4360 - (NSString *) mcc {
4361 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4362 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4363 return nil;
4364 }
4365
4366 - (NSString *) mnc {
4367 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4368 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4369 return nil;
4370 }
4371
4372 - (NSString *) operator {
4373 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4374 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4375 return nil;
4376 }
4377
4378 - (NSString *) bbsnum {
4379 return (id) BBSNum_ ?: [NSNull null];
4380 }
4381
4382 - (NSString *) ecid {
4383 return (id) ChipID_ ?: [NSNull null];
4384 }
4385
4386 - (NSString *) serial {
4387 return SerialNumber_;
4388 }
4389
4390 - (NSString *) role {
4391 return (id) [NSNull null];
4392 }
4393
4394 - (NSString *) model {
4395 return [NSString stringWithUTF8String:Machine_];
4396 }
4397
4398 - (NSString *) token {
4399 return (id) Token_ ?: [NSNull null];
4400 }
4401
4402 + (NSString *) webScriptNameForSelector:(SEL)selector {
4403 if (false);
4404 else if (selector == @selector(addBridgedHost:))
4405 return @"addBridgedHost";
4406 else if (selector == @selector(addInsecureHost:))
4407 return @"addInsecureHost";
4408 else if (selector == @selector(addInternalRedirect::))
4409 return @"addInternalRedirect";
4410 else if (selector == @selector(addPipelinedHost:scheme:))
4411 return @"addPipelinedHost";
4412 else if (selector == @selector(addSource:::))
4413 return @"addSource";
4414 else if (selector == @selector(addTokenHost:))
4415 return @"addTokenHost";
4416 else if (selector == @selector(addTrivialSource:))
4417 return @"addTrivialSource";
4418 else if (selector == @selector(close))
4419 return @"close";
4420 else if (selector == @selector(du:))
4421 return @"du";
4422 else if (selector == @selector(stringWithFormat:arguments:))
4423 return @"format";
4424 else if (selector == @selector(getAllSources))
4425 return @"getAllSources";
4426 else if (selector == @selector(getApplicationInfo:value:))
4427 return @"getApplicationInfoValue";
4428 else if (selector == @selector(getKernelNumber:))
4429 return @"getKernelNumber";
4430 else if (selector == @selector(getKernelString:))
4431 return @"getKernelString";
4432 else if (selector == @selector(getInstalledPackages))
4433 return @"getInstalledPackages";
4434 else if (selector == @selector(getIORegistryEntry::))
4435 return @"getIORegistryEntry";
4436 else if (selector == @selector(getLocaleIdentifier))
4437 return @"getLocaleIdentifier";
4438 else if (selector == @selector(getPreferredLanguages))
4439 return @"getPreferredLanguages";
4440 else if (selector == @selector(getPackageById:))
4441 return @"getPackageById";
4442 else if (selector == @selector(getMetadataKeys))
4443 return @"getMetadataKeys";
4444 else if (selector == @selector(getMetadataValue:))
4445 return @"getMetadataValue";
4446 else if (selector == @selector(getSessionValue:))
4447 return @"getSessionValue";
4448 else if (selector == @selector(installPackages:))
4449 return @"installPackages";
4450 else if (selector == @selector(isReachable:))
4451 return @"isReachable";
4452 else if (selector == @selector(localizedStringForKey:value:table:))
4453 return @"localize";
4454 else if (selector == @selector(popViewController:))
4455 return @"popViewController";
4456 else if (selector == @selector(refreshSources))
4457 return @"refreshSources";
4458 else if (selector == @selector(registerFrame:))
4459 return @"registerFrame";
4460 else if (selector == @selector(removeButton))
4461 return @"removeButton";
4462 else if (selector == @selector(saveConfig))
4463 return @"saveConfig";
4464 else if (selector == @selector(setMetadataValue::))
4465 return @"setMetadataValue";
4466 else if (selector == @selector(setSessionValue::))
4467 return @"setSessionValue";
4468 else if (selector == @selector(substitutePackageNames:))
4469 return @"substitutePackageNames";
4470 else if (selector == @selector(scrollToBottom:))
4471 return @"scrollToBottom";
4472 else if (selector == @selector(setAllowsNavigationAction:))
4473 return @"setAllowsNavigationAction";
4474 else if (selector == @selector(setBadgeValue:))
4475 return @"setBadgeValue";
4476 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4477 return @"setButtonImage";
4478 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4479 return @"setButtonTitle";
4480 else if (selector == @selector(setHidesBackButton:))
4481 return @"setHidesBackButton";
4482 else if (selector == @selector(setHidesNavigationBar:))
4483 return @"setHidesNavigationBar";
4484 else if (selector == @selector(setNavigationBarStyle:))
4485 return @"setNavigationBarStyle";
4486 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4487 return @"setNavigationBarTintColor";
4488 else if (selector == @selector(setPasteboardString:))
4489 return @"setPasteboardString";
4490 else if (selector == @selector(setPasteboardURL:))
4491 return @"setPasteboardURL";
4492 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4493 return @"setScrollAlwaysBounceVertical";
4494 else if (selector == @selector(setScrollIndicatorStyle:))
4495 return @"setScrollIndicatorStyle";
4496 else if (selector == @selector(setToken:))
4497 return @"setToken";
4498 else if (selector == @selector(setViewportWidth:))
4499 return @"setViewportWidth";
4500 else if (selector == @selector(statfs:))
4501 return @"statfs";
4502 else if (selector == @selector(supports:))
4503 return @"supports";
4504 else if (selector == @selector(unload))
4505 return @"unload";
4506 else
4507 return nil;
4508 }
4509
4510 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4511 return [self webScriptNameForSelector:selector] == nil;
4512 }
4513
4514 - (BOOL) supports:(NSString *)feature {
4515 return [feature isEqualToString:@"window.open"];
4516 }
4517
4518 - (void) unload {
4519 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4520 }
4521
4522 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4523 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4524 }
4525
4526 - (void) setScrollIndicatorStyle:(NSString *)style {
4527 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4528 }
4529
4530 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4531 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4532 }
4533
4534 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4535 char path[1024];
4536 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4537 return (id) [NSNull null];
4538 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4539 if (info == nil)
4540 return (id) [NSNull null];
4541 return [info objectForKey:key];
4542 }
4543
4544 - (NSNumber *) getKernelNumber:(NSString *)name {
4545 const char *string([name UTF8String]);
4546
4547 size_t size;
4548 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4549 return (id) [NSNull null];
4550
4551 if (size != sizeof(int))
4552 return (id) [NSNull null];
4553
4554 int value;
4555 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4556 return (id) [NSNull null];
4557
4558 return [NSNumber numberWithInt:value];
4559 }
4560
4561 - (NSString *) getKernelString:(NSString *)name {
4562 const char *string([name UTF8String]);
4563
4564 size_t size;
4565 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4566 return (id) [NSNull null];
4567
4568 char value[size + 1];
4569 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4570 return (id) [NSNull null];
4571
4572 // XXX: just in case you request something ludicrous
4573 value[size] = '\0';
4574
4575 return [NSString stringWithCString:value];
4576 }
4577
4578 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4579 NSObject *value(CYIOGetValue([path UTF8String], entry));
4580
4581 if (value != nil)
4582 if ([value isKindOfClass:[NSData class]])
4583 value = CYHex((NSData *) value);
4584
4585 return value;
4586 }
4587
4588 - (NSArray *) getMetadataKeys {
4589 @synchronized (Values_) {
4590 return [Values_ allKeys];
4591 } }
4592
4593 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4594 WebFrame *frame([iframe contentFrame]);
4595 [indirect_ registerFrame:frame];
4596 }
4597
4598 - (id) getMetadataValue:(NSString *)key {
4599 @synchronized (Values_) {
4600 return [Values_ objectForKey:key];
4601 } }
4602
4603 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4604 @synchronized (Values_) {
4605 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4606 [Values_ removeObjectForKey:key];
4607 else
4608 [Values_ setObject:value forKey:key];
4609
4610 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4611 } }
4612
4613 - (id) getSessionValue:(NSString *)key {
4614 @synchronized (SessionData_) {
4615 return [SessionData_ objectForKey:key];
4616 } }
4617
4618 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4619 @synchronized (SessionData_) {
4620 if (value == (id) [WebUndefined undefined])
4621 [SessionData_ removeObjectForKey:key];
4622 else
4623 [SessionData_ setObject:value forKey:key];
4624 } }
4625
4626 - (void) addBridgedHost:(NSString *)host {
4627 @synchronized (HostConfig_) {
4628 [BridgedHosts_ addObject:host];
4629 } }
4630
4631 - (void) addInsecureHost:(NSString *)host {
4632 @synchronized (HostConfig_) {
4633 [InsecureHosts_ addObject:host];
4634 } }
4635
4636 - (void) addTokenHost:(NSString *)host {
4637 @synchronized (HostConfig_) {
4638 [TokenHosts_ addObject:host];
4639 } }
4640
4641 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4642 @synchronized (HostConfig_) {
4643 if (scheme != (id) [WebUndefined undefined])
4644 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4645
4646 [PipelinedHosts_ addObject:host];
4647 } }
4648
4649 - (void) popViewController:(NSNumber *)value {
4650 if (value == (id) [WebUndefined undefined])
4651 value = [NSNumber numberWithBool:YES];
4652 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4653 }
4654
4655 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4656 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4657
4658 for (NSString *section in sections)
4659 [array addObject:section];
4660
4661 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4662 @"deb", @"Type",
4663 href, @"URI",
4664 distribution, @"Distribution",
4665 array, @"Sections",
4666 nil] waitUntilDone:NO];
4667 }
4668
4669 - (void) addTrivialSource:(NSString *)href {
4670 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4671 }
4672
4673 - (void) refreshSources {
4674 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4675 }
4676
4677 - (void) saveConfig {
4678 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4679 }
4680
4681 - (NSArray *) getAllSources {
4682 return [[Database sharedInstance] sources];
4683 }
4684
4685 - (NSArray *) getInstalledPackages {
4686 Database *database([Database sharedInstance]);
4687 @synchronized (database) {
4688 NSArray *packages([database packages]);
4689 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4690 for (Package *package in packages)
4691 if (![package uninstalled])
4692 [installed addObject:package];
4693 return installed;
4694 } }
4695
4696 - (Package *) getPackageById:(NSString *)id {
4697 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4698 [package parse];
4699 return package;
4700 } else
4701 return (Package *) [NSNull null];
4702 }
4703
4704 - (NSString *) getLocaleIdentifier {
4705 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4706 }
4707
4708 - (NSArray *) getPreferredLanguages {
4709 return Languages_;
4710 }
4711
4712 - (NSArray *) statfs:(NSString *)path {
4713 struct statfs stat;
4714
4715 if (path == nil || statfs([path UTF8String], &stat) == -1)
4716 return nil;
4717
4718 return [NSArray arrayWithObjects:
4719 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4720 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4721 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4722 nil];
4723 }
4724
4725 - (NSNumber *) du:(NSString *)path {
4726 NSNumber *value(nil);
4727
4728 int fds[2];
4729 _assert(pipe(fds) != -1);
4730
4731 pid_t pid(ExecFork());
4732 if (pid == 0) {
4733 _assert(dup2(fds[1], 1) != -1);
4734 _assert(close(fds[0]) != -1);
4735 _assert(close(fds[1]) != -1);
4736 /* XXX: this should probably not use du */
4737 _root(execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL));
4738 exit(1);
4739 } else {
4740 _assert(close(fds[1]) != -1);
4741
4742 if (FILE *du = fdopen(fds[0], "r")) {
4743 char line[1024];
4744 while (fgets(line, sizeof(line), du) != NULL) {
4745 size_t length(strlen(line));
4746 while (length != 0 && line[length - 1] == '\n')
4747 line[--length] = '\0';
4748 if (char *tab = strchr(line, '\t')) {
4749 *tab = '\0';
4750 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4751 }
4752 }
4753
4754 fclose(du);
4755 } else
4756 _assert(close(fds[0]) != -1);
4757 } ReapZombie(pid);
4758
4759 return value;
4760 }
4761
4762 - (void) close {
4763 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4764 }
4765
4766 - (NSNumber *) isReachable:(NSString *)name {
4767 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4768 }
4769
4770 - (void) installPackages:(NSArray *)packages {
4771 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4772 }
4773
4774 - (NSString *) substitutePackageNames:(NSString *)message {
4775 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4776 for (size_t i(0), e([words count]); i != e; ++i) {
4777 NSString *word([words objectAtIndex:i]);
4778 if (Package *package = [[Database sharedInstance] packageWithName:word])
4779 [words replaceObjectAtIndex:i withObject:[package name]];
4780 }
4781
4782 return [words componentsJoinedByString:@" "];
4783 }
4784
4785 - (void) removeButton {
4786 [indirect_ removeButton];
4787 }
4788
4789 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4790 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4791 }
4792
4793 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4794 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4795 }
4796
4797 - (void) setBadgeValue:(id)value {
4798 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4799 }
4800
4801 - (void) setAllowsNavigationAction:(NSString *)value {
4802 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4803 }
4804
4805 - (void) setHidesBackButton:(NSString *)value {
4806 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4807 }
4808
4809 - (void) setHidesNavigationBar:(NSString *)value {
4810 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4811 }
4812
4813 - (void) setNavigationBarStyle:(NSString *)value {
4814 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4815 }
4816
4817 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4818 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4819 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4820 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4821 }
4822
4823 - (void) setPasteboardString:(NSString *)value {
4824 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4825 }
4826
4827 - (void) setPasteboardURL:(NSString *)value {
4828 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4829 }
4830
4831 - (void) _setToken:(NSString *)token {
4832 Token_ = token;
4833
4834 if (token == nil)
4835 [Metadata_ removeObjectForKey:@"Token"];
4836 else
4837 [Metadata_ setObject:Token_ forKey:@"Token"];
4838
4839 Changed_ = true;
4840 }
4841
4842 - (void) setToken:(NSString *)token {
4843 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4844 }
4845
4846 - (void) scrollToBottom:(NSNumber *)animated {
4847 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4848 }
4849
4850 - (void) setViewportWidth:(float)width {
4851 [indirect_ setViewportWidthOnMainThread:width];
4852 }
4853
4854 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4855 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4856 unsigned count([arguments count]);
4857 id values[count];
4858 for (unsigned i(0); i != count; ++i)
4859 values[i] = [arguments objectAtIndex:i];
4860 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4861 }
4862
4863 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4864 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4865 value = nil;
4866 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4867 table = nil;
4868 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4869 }
4870
4871 @end
4872 /* }}} */
4873
4874 @interface NSURL (CydiaSecure)
4875 @end
4876
4877 @implementation NSURL (CydiaSecure)
4878
4879 - (bool) isCydiaSecure {
4880 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4881 return true;
4882
4883 @synchronized (HostConfig_) {
4884 if ([InsecureHosts_ containsObject:[self host]])
4885 return true;
4886 }
4887
4888 return false;
4889 }
4890
4891 @end
4892
4893 /* Cydia Browser Controller {{{ */
4894 @implementation CydiaWebViewController
4895
4896 - (NSURL *) navigationURL {
4897 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4898 }
4899
4900 + (void) _initialize {
4901 [super _initialize];
4902
4903 Diversions_ = [NSMutableSet setWithCapacity:0];
4904 }
4905
4906 + (void) addDiversion:(Diversion *)diversion {
4907 [Diversions_ addObject:diversion];
4908 }
4909
4910 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4911 [super webView:view didClearWindowObject:window forFrame:frame];
4912 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4913 }
4914
4915 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4916 WebDataSource *source([frame dataSource]);
4917 NSURLResponse *response([source response]);
4918 NSURL *url([response URL]);
4919 NSString *scheme([[url scheme] lowercaseString]);
4920
4921 bool bridged(false);
4922
4923 @synchronized (HostConfig_) {
4924 if ([scheme isEqualToString:@"file"])
4925 bridged = true;
4926 else if ([scheme isEqualToString:@"https"])
4927 if ([BridgedHosts_ containsObject:[url host]])
4928 bridged = true;
4929 }
4930
4931 if (bridged)
4932 [window setValue:cydia forKey:@"cydia"];
4933 }
4934
4935 - (void) _setupMail:(MFMailComposeViewController *)controller {
4936 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4937
4938 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4939 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4940 }
4941
4942 - (NSURL *) URLWithURL:(NSURL *)url {
4943 return [Diversion divertURL:url];
4944 }
4945
4946 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4947 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4948 }
4949
4950 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4951 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4952
4953 NSURL *url([copy URL]);
4954 NSString *href([url absoluteString]);
4955 NSString *host([url host]);
4956
4957 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4958 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4959 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4960 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4961 }
4962
4963 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4964 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4965
4966 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4967 return copy;
4968 }
4969
4970 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4971 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4972 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4973 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4974
4975 bool bridged;
4976 bool token;
4977
4978 @synchronized (HostConfig_) {
4979 bridged = [BridgedHosts_ containsObject:host];
4980 token = [TokenHosts_ containsObject:host];
4981 }
4982
4983 if ([url isCydiaSecure]) {
4984 if (bridged) {
4985 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4986 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4987 } else if (token) {
4988 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4989 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4990 }
4991 }
4992
4993 return copy;
4994 }
4995
4996 - (void) setDelegate:(id)delegate {
4997 [super setDelegate:delegate];
4998 [cydia_ setDelegate:delegate];
4999 }
5000
5001 - (NSString *) applicationNameForUserAgent {
5002 return UserAgent_;
5003 }
5004
5005 - (id) init {
5006 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5007 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5008 } return self;
5009 }
5010
5011 @end
5012
5013 @interface AppCacheController : CydiaWebViewController {
5014 }
5015
5016 @end
5017
5018 @implementation AppCacheController
5019
5020 - (void) didReceiveMemoryWarning {
5021 // XXX: this doesn't work
5022 }
5023
5024 - (bool) retainsNetworkActivityIndicator {
5025 return false;
5026 }
5027
5028 @end
5029 /* }}} */
5030
5031 // CydiaScript {{{
5032 @interface NSObject (CydiaScript)
5033 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5034 @end
5035
5036 @implementation NSObject (CydiaScript)
5037
5038 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5039 return self;
5040 }
5041
5042 @end
5043
5044 @implementation NSArray (CydiaScript)
5045
5046 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5047 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5048 for (size_t i(0), e([self count]); i != e; ++i)
5049 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5050 return object;
5051 }
5052
5053 @end
5054
5055 @implementation NSDictionary (CydiaScript)
5056
5057 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5058 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5059 for (id i in self)
5060 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5061 return object;
5062 }
5063
5064 @end
5065 // }}}
5066
5067 /* Confirmation Controller {{{ */
5068 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5069 if (!iterator.end())
5070 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5071 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5072 continue;
5073 pkgCache::PkgIterator package(dep.TargetPkg());
5074 if (package.end())
5075 continue;
5076 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5077 return true;
5078 }
5079
5080 return false;
5081 }
5082
5083 @protocol ConfirmationControllerDelegate
5084 - (void) cancelAndClear:(bool)clear;
5085 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5086 - (void) queue;
5087 @end
5088
5089 @interface ConfirmationController : CydiaWebViewController {
5090 _transient Database *database_;
5091
5092 _H<UIAlertView> essential_;
5093
5094 _H<NSDictionary> changes_;
5095 _H<NSMutableArray> issues_;
5096 _H<NSDictionary> sizes_;
5097
5098 BOOL substrate_;
5099 }
5100
5101 - (id) initWithDatabase:(Database *)database;
5102
5103 @end
5104
5105 @implementation ConfirmationController
5106
5107 - (void) complete {
5108 if (substrate_)
5109 RestartSubstrate_ = true;
5110 [delegate_ confirmWithNavigationController:[self navigationController]];
5111 }
5112
5113 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5114 NSString *context([alert context]);
5115
5116 if ([context isEqualToString:@"remove"]) {
5117 if (button == [alert cancelButtonIndex])
5118 [self _doContinue];
5119 else if (button == [alert firstOtherButtonIndex]) {
5120 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5121 }
5122
5123 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5124 } else if ([context isEqualToString:@"unable"]) {
5125 [self dismissModalViewControllerAnimated:YES];
5126 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5127 } else {
5128 [super alertView:alert clickedButtonAtIndex:button];
5129 }
5130 }
5131
5132 - (void) _doContinue {
5133 [delegate_ cancelAndClear:NO];
5134 [self dismissModalViewControllerAnimated:YES];
5135 }
5136
5137 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5138 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5139 return nil;
5140 }
5141
5142 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5143 [super webView:view didClearWindowObject:window forFrame:frame];
5144
5145 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5146 (id) changes_, @"changes",
5147 (id) issues_, @"issues",
5148 (id) sizes_, @"sizes",
5149 self, @"queue",
5150 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5151 }
5152
5153 - (id) initWithDatabase:(Database *)database {
5154 if ((self = [super init]) != nil) {
5155 database_ = database;
5156
5157 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5158 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5159 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5160 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5161 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5162
5163 bool remove(false);
5164
5165 pkgCacheFile &cache([database_ cache]);
5166 NSArray *packages([database_ packages]);
5167 pkgDepCache::Policy *policy([database_ policy]);
5168
5169 issues_ = [NSMutableArray arrayWithCapacity:4];
5170
5171 UpgradeCydia_ = false;
5172
5173 for (Package *package in packages) {
5174 pkgCache::PkgIterator iterator([package iterator]);
5175 NSString *name([package id]);
5176
5177 if ([package broken]) {
5178 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5179
5180 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5181 name, @"package",
5182 reasons, @"reasons",
5183 nil]];
5184
5185 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5186 if (ver.end())
5187 continue;
5188
5189 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5190 pkgCache::DepIterator start;
5191 pkgCache::DepIterator end;
5192 dep.GlobOr(start, end); // ++dep
5193
5194 if (!cache->IsImportantDep(end))
5195 continue;
5196 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5197 continue;
5198
5199 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5200
5201 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5202 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5203 clauses, @"clauses",
5204 nil]];
5205
5206 _forever {
5207 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5208
5209 pkgCache::PkgIterator target(start.TargetPkg());
5210 if (target->ProvidesList != 0)
5211 reason = @"missing";
5212 else {
5213 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5214 if (!ver.end()) {
5215 reason = @"installed";
5216 installed = [NSString stringWithUTF8String:ver.VerStr()];
5217 } else if (!cache[target].CandidateVerIter(cache).end())
5218 reason = @"uninstalled";
5219 else if (target->ProvidesList == 0)
5220 reason = @"uninstallable";
5221 else
5222 reason = @"virtual";
5223 }
5224
5225 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5226 [NSString stringWithUTF8String:start.CompType()], @"operator",
5227 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5228 nil]);
5229
5230 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5231 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5232 version, @"version",
5233 reason, @"reason",
5234 installed, @"installed",
5235 nil]];
5236
5237 // yes, seriously. (wtf?)
5238 if (start == end)
5239 break;
5240 ++start;
5241 }
5242 }
5243 }
5244
5245 pkgDepCache::StateCache &state(cache[iterator]);
5246
5247 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5248
5249 if (state.NewInstall())
5250 [installs addObject:name];
5251 // XXX: else if (state.Install())
5252 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5253 [reinstalls addObject:name];
5254 // XXX: move before previous if
5255 else if (state.Upgrade())
5256 [upgrades addObject:name];
5257 else if (state.Downgrade())
5258 [downgrades addObject:name];
5259 else if (!state.Delete())
5260 // XXX: _assert(state.Keep());
5261 continue;
5262 else if (special_r(name))
5263 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5264 [NSNull null], @"package",
5265 [NSArray arrayWithObjects:
5266 [NSDictionary dictionaryWithObjectsAndKeys:
5267 @"Conflicts", @"relationship",
5268 [NSArray arrayWithObjects:
5269 [NSDictionary dictionaryWithObjectsAndKeys:
5270 name, @"package",
5271 [NSNull null], @"version",
5272 @"installed", @"reason",
5273 nil],
5274 nil], @"clauses",
5275 nil],
5276 nil], @"reasons",
5277 nil]];
5278 else {
5279 if ([package essential])
5280 remove = true;
5281 [removes addObject:name];
5282 }
5283
5284 if ([name isEqualToString:@"cydia"])
5285 UpgradeCydia_ = true;
5286
5287 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5288 substrate_ |= DepSubstrate(iterator.CurrentVer());
5289 }
5290
5291 if (!remove)
5292 essential_ = nil;
5293 else if (Advanced_) {
5294 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5295
5296 essential_ = [[[UIAlertView alloc]
5297 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5298 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5299 delegate:self
5300 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5301 otherButtonTitles:
5302 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5303 nil
5304 ] autorelease];
5305
5306 [essential_ setContext:@"remove"];
5307 [essential_ setNumberOfRows:2];
5308 } else {
5309 essential_ = [[[UIAlertView alloc]
5310 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5311 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5312 delegate:self
5313 cancelButtonTitle:UCLocalize("OKAY")
5314 otherButtonTitles:nil
5315 ] autorelease];
5316
5317 [essential_ setContext:@"unable"];
5318 }
5319
5320 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5321 installs, @"installs",
5322 reinstalls, @"reinstalls",
5323 upgrades, @"upgrades",
5324 downgrades, @"downgrades",
5325 removes, @"removes",
5326 nil];
5327
5328 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5329 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5330 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5331 nil];
5332
5333 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5334 } return self;
5335 }
5336
5337 - (UIBarButtonItem *) leftButton {
5338 return [[[UIBarButtonItem alloc]
5339 initWithTitle:UCLocalize("CANCEL")
5340 style:UIBarButtonItemStylePlain
5341 target:self
5342 action:@selector(cancelButtonClicked)
5343 ] autorelease];
5344 }
5345
5346 #if !AlwaysReload
5347 - (void) applyRightButton {
5348 if ([issues_ count] == 0 && ![self isLoading])
5349 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5350 initWithTitle:UCLocalize("CONFIRM")
5351 style:UIBarButtonItemStyleDone
5352 target:self
5353 action:@selector(confirmButtonClicked)
5354 ] autorelease]];
5355 else
5356 [[self navigationItem] setRightBarButtonItem:nil];
5357 }
5358 #endif
5359
5360 - (void) cancelButtonClicked {
5361 [delegate_ cancelAndClear:YES];
5362 [self dismissModalViewControllerAnimated:YES];
5363 }
5364
5365 #if !AlwaysReload
5366 - (void) confirmButtonClicked {
5367 if (essential_ != nil)
5368 [essential_ show];
5369 else
5370 [self complete];
5371 }
5372 #endif
5373
5374 @end
5375 /* }}} */
5376
5377 /* Progress Data {{{ */
5378 @interface CydiaProgressData : NSObject {
5379 _transient id delegate_;
5380
5381 bool running_;
5382 float percent_;
5383
5384 float current_;
5385 float total_;
5386 float speed_;
5387
5388 _H<NSMutableArray> events_;
5389 _H<NSString> title_;
5390
5391 _H<NSString> status_;
5392 _H<NSString> finish_;
5393 }
5394
5395 @end
5396
5397 @implementation CydiaProgressData
5398
5399 + (NSArray *) _attributeKeys {
5400 return [NSArray arrayWithObjects:
5401 @"current",
5402 @"events",
5403 @"finish",
5404 @"percent",
5405 @"running",
5406 @"speed",
5407 @"title",
5408 @"total",
5409 nil];
5410 }
5411
5412 - (NSArray *) attributeKeys {
5413 return [[self class] _attributeKeys];
5414 }
5415
5416 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5417 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5418 }
5419
5420 - (id) init {
5421 if ((self = [super init]) != nil) {
5422 events_ = [NSMutableArray arrayWithCapacity:32];
5423 } return self;
5424 }
5425
5426 - (id) delegate {
5427 return delegate_;
5428 }
5429
5430 - (void) setDelegate:(id)delegate {
5431 delegate_ = delegate;
5432 }
5433
5434 - (void) setPercent:(float)value {
5435 percent_ = value;
5436 }
5437
5438 - (NSNumber *) percent {
5439 return [NSNumber numberWithFloat:percent_];
5440 }
5441
5442 - (void) setCurrent:(float)value {
5443 current_ = value;
5444 }
5445
5446 - (NSNumber *) current {
5447 return [NSNumber numberWithFloat:current_];
5448 }
5449
5450 - (void) setTotal:(float)value {
5451 total_ = value;
5452 }
5453
5454 - (NSNumber *) total {
5455 return [NSNumber numberWithFloat:total_];
5456 }
5457
5458 - (void) setSpeed:(float)value {
5459 speed_ = value;
5460 }
5461
5462 - (NSNumber *) speed {
5463 return [NSNumber numberWithFloat:speed_];
5464 }
5465
5466 - (NSArray *) events {
5467 return events_;
5468 }
5469
5470 - (void) removeAllEvents {
5471 [events_ removeAllObjects];
5472 }
5473
5474 - (void) addEvent:(CydiaProgressEvent *)event {
5475 [events_ addObject:event];
5476 }
5477
5478 - (void) setTitle:(NSString *)text {
5479 title_ = text;
5480 }
5481
5482 - (NSString *) title {
5483 return title_;
5484 }
5485
5486 - (void) setFinish:(NSString *)text {
5487 finish_ = text;
5488 }
5489
5490 - (NSString *) finish {
5491 return (id) finish_ ?: [NSNull null];
5492 }
5493
5494 - (void) setRunning:(bool)running {
5495 running_ = running;
5496 }
5497
5498 - (NSNumber *) running {
5499 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5500 }
5501
5502 @end
5503 /* }}} */
5504 /* Progress Controller {{{ */
5505 @interface ProgressController : CydiaWebViewController <
5506 ProgressDelegate
5507 > {
5508 _transient Database *database_;
5509 _H<CydiaProgressData, 1> progress_;
5510 unsigned cancel_;
5511 }
5512
5513 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5514
5515 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5516
5517 - (void) setTitle:(NSString *)title;
5518 - (void) setCancellable:(bool)cancellable;
5519
5520 @end
5521
5522 @implementation ProgressController
5523
5524 - (void) dealloc {
5525 [database_ setProgressDelegate:nil];
5526 [super dealloc];
5527 }
5528
5529 - (UIBarButtonItem *) leftButton {
5530 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5531 initWithTitle:UCLocalize("CANCEL")
5532 style:UIBarButtonItemStylePlain
5533 target:self
5534 action:@selector(cancel)
5535 ] autorelease] : nil;
5536 }
5537
5538 - (void) updateCancel {
5539 [super applyLeftButton];
5540 }
5541
5542 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5543 if ((self = [super init]) != nil) {
5544 database_ = database;
5545 delegate_ = delegate;
5546
5547 [database_ setProgressDelegate:self];
5548
5549 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5550 [progress_ setDelegate:self];
5551
5552 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5553
5554 [scroller_ setBackgroundColor:[UIColor blackColor]];
5555
5556 [[self navigationItem] setHidesBackButton:YES];
5557
5558 [self updateCancel];
5559 } return self;
5560 }
5561
5562 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5563 [super webView:view didClearWindowObject:window forFrame:frame];
5564 [window setValue:progress_ forKey:@"cydiaProgress"];
5565 }
5566
5567 - (void) updateProgress {
5568 [self dispatchEvent:@"CydiaProgressUpdate"];
5569 }
5570
5571 - (void) viewWillAppear:(BOOL)animated {
5572 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5573 [super viewWillAppear:animated];
5574 }
5575
5576 - (void) reloadSpringBoard {
5577 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5578 system("/bin/launchctl stop com.apple.backboardd");
5579 sleep(15);
5580 system("/usr/bin/killall backboardd SpringBoard sbreload");
5581 return;
5582 }
5583
5584 pid_t pid(ExecFork());
5585 if (pid == 0) {
5586 if (setsid() == -1)
5587 perror("setsid");
5588
5589 pid_t pid(ExecFork());
5590 if (pid == 0) {
5591 _root(execl("/usr/bin/sbreload", "sbreload", NULL));
5592 perror("sbreload");
5593
5594 exit(0);
5595 } ReapZombie(pid);
5596
5597 exit(0);
5598 } ReapZombie(pid);
5599
5600 sleep(15);
5601 system("/usr/bin/killall backboardd SpringBoard sbreload");
5602 }
5603
5604 - (void) close {
5605 UpdateExternalStatus(0);
5606
5607 if (Finish_ > 1)
5608 [delegate_ saveState];
5609
5610 switch (Finish_) {
5611 case 0:
5612 [delegate_ returnToCydia];
5613 break;
5614
5615 case 1:
5616 [delegate_ terminateWithSuccess];
5617 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5618 [delegate_ suspendWithAnimation:YES];
5619 else
5620 [delegate_ suspend];*/
5621 break;
5622
5623 case 2:
5624 _trace();
5625 goto reload;
5626
5627 case 3:
5628 _trace();
5629 goto reload;
5630
5631 reload: {
5632 UIProgressHUD *hud([delegate_ addProgressHUD]);
5633 [hud setText:UCLocalize("LOADING")];
5634 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5635 return;
5636 }
5637
5638 case 4:
5639 _trace();
5640 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5641 SBReboot(SBSSpringBoardServerPort());
5642 else
5643 reboot2(RB_AUTOBOOT);
5644 break;
5645 }
5646
5647 [super close];
5648 }
5649
5650 - (void) setTitle:(NSString *)title {
5651 [progress_ setTitle:title];
5652 [self updateProgress];
5653 }
5654
5655 - (UIBarButtonItem *) rightButton {
5656 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5657 initWithTitle:UCLocalize("CLOSE")
5658 style:UIBarButtonItemStylePlain
5659 target:self
5660 action:@selector(close)
5661 ] autorelease];
5662 }
5663
5664 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5665 UpdateExternalStatus(1);
5666
5667 [progress_ setRunning:true];
5668 [self setTitle:title];
5669 // implicit updateProgress
5670
5671 SHA1SumValue notifyconf; {
5672 FileFd file;
5673 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5674 _error->Discard();
5675 else {
5676 MMap mmap(file, MMap::ReadOnly);
5677 SHA1Summation sha1;
5678 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5679 notifyconf = sha1.Result();
5680 }
5681 }
5682
5683 SHA1SumValue springlist; {
5684 FileFd file;
5685 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5686 _error->Discard();
5687 else {
5688 MMap mmap(file, MMap::ReadOnly);
5689 SHA1Summation sha1;
5690 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5691 springlist = sha1.Result();
5692 }
5693 }
5694
5695 if (invocation != nil) {
5696 [invocation yieldToSelector:@selector(invoke)];
5697 [self setTitle:@"COMPLETE"];
5698 }
5699
5700 if (Finish_ < 4) {
5701 FileFd file;
5702 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5703 _error->Discard();
5704 else {
5705 MMap mmap(file, MMap::ReadOnly);
5706 SHA1Summation sha1;
5707 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5708 if (!(notifyconf == sha1.Result()))
5709 Finish_ = 4;
5710 }
5711 }
5712
5713 if (Finish_ < 3) {
5714 FileFd file;
5715 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5716 _error->Discard();
5717 else {
5718 MMap mmap(file, MMap::ReadOnly);
5719 SHA1Summation sha1;
5720 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5721 if (!(springlist == sha1.Result()))
5722 Finish_ = 3;
5723 }
5724 }
5725
5726 if (Finish_ < 2) {
5727 if (RestartSubstrate_)
5728 Finish_ = 2;
5729 }
5730
5731 RestartSubstrate_ = false;
5732
5733 switch (Finish_) {
5734 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5735 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5736 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5737 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5738 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5739 }
5740
5741 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5742
5743 [progress_ setRunning:false];
5744 [self updateProgress];
5745
5746 [self applyRightButton];
5747 }
5748
5749 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5750 [progress_ addEvent:event];
5751 [self updateProgress];
5752 }
5753
5754 - (bool) isProgressCancelled {
5755 return cancel_ == 2;
5756 }
5757
5758 - (void) cancel {
5759 cancel_ = 2;
5760 [self updateCancel];
5761 }
5762
5763 - (void) setCancellable:(bool)cancellable {
5764 unsigned cancel(cancel_);
5765
5766 if (!cancellable)
5767 cancel_ = 0;
5768 else if (cancel_ == 0)
5769 cancel_ = 1;
5770
5771 if (cancel != cancel_)
5772 [self updateCancel];
5773 }
5774
5775 - (void) setProgressCancellable:(NSNumber *)cancellable {
5776 [self setCancellable:[cancellable boolValue]];
5777 }
5778
5779 - (void) setProgressPercent:(NSNumber *)percent {
5780 [progress_ setPercent:[percent floatValue]];
5781 [self updateProgress];
5782 }
5783
5784 - (void) setProgressStatus:(NSDictionary *)status {
5785 if (status == nil) {
5786 [progress_ setCurrent:0];
5787 [progress_ setTotal:0];
5788 [progress_ setSpeed:0];
5789 } else {
5790 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5791
5792 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5793 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5794 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5795 }
5796
5797 [self updateProgress];
5798 }
5799
5800 @end
5801 /* }}} */
5802
5803 /* Package Cell {{{ */
5804 @interface PackageCell : CyteTableViewCell <
5805 CyteTableViewCellDelegate
5806 > {
5807 _H<UIImage> icon_;
5808 _H<NSString> name_;
5809 _H<NSString> description_;
5810 bool commercial_;
5811 _H<NSString> source_;
5812 _H<UIImage> badge_;
5813 _H<UIImage> placard_;
5814 bool summarized_;
5815 }
5816
5817 - (PackageCell *) init;
5818 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5819
5820 - (void) drawContentRect:(CGRect)rect;
5821
5822 @end
5823
5824 @implementation PackageCell
5825
5826 - (PackageCell *) init {
5827 CGRect frame(CGRectMake(0, 0, 320, 74));
5828 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5829 UIView *content([self contentView]);
5830 CGRect bounds([content bounds]);
5831
5832 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5833 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5834 [content addSubview:content_];
5835
5836 [content_ setDelegate:self];
5837 [content_ setOpaque:YES];
5838 } return self;
5839 }
5840
5841 - (NSString *) accessibilityLabel {
5842 return name_;
5843 }
5844
5845 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5846 summarized_ = summary;
5847
5848 icon_ = nil;
5849 name_ = nil;
5850 description_ = nil;
5851 source_ = nil;
5852 badge_ = nil;
5853 placard_ = nil;
5854
5855 if (package == nil)
5856 [content_ setBackgroundColor:[UIColor whiteColor]];
5857 else {
5858 [package parse];
5859
5860 Source *source = [package source];
5861
5862 icon_ = [package icon];
5863
5864 if (NSString *name = [package name])
5865 name_ = [NSString stringWithString:name];
5866
5867 if (NSString *description = [package shortDescription])
5868 description_ = [NSString stringWithString:description];
5869
5870 commercial_ = [package isCommercial];
5871
5872 NSString *label = nil;
5873 bool trusted = false;
5874
5875 if (source != nil) {
5876 label = [source label];
5877 trusted = [source trusted];
5878 } else if ([[package id] isEqualToString:@"firmware"])
5879 label = UCLocalize("APPLE");
5880 else
5881 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5882
5883 NSString *from(label);
5884
5885 NSString *section = [package simpleSection];
5886 if (section != nil && ![section isEqualToString:label]) {
5887 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5888 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5889 }
5890
5891 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5892
5893 if (NSString *purpose = [package primaryPurpose])
5894 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5895
5896 UIColor *color;
5897 NSString *placard;
5898
5899 if (NSString *mode = [package mode]) {
5900 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5901 color = RemovingColor_;
5902 placard = @"removing";
5903 } else {
5904 color = InstallingColor_;
5905 placard = @"installing";
5906 }
5907 } else {
5908 color = [UIColor whiteColor];
5909
5910 if ([package installed] != nil)
5911 placard = @"installed";
5912 else
5913 placard = nil;
5914 }
5915
5916 [content_ setBackgroundColor:color];
5917
5918 if (placard != nil)
5919 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5920 }
5921
5922 [self setNeedsDisplay];
5923 [content_ setNeedsDisplay];
5924 }
5925
5926 - (void) drawSummaryContentRect:(CGRect)rect {
5927 bool highlighted(highlighted_);
5928 float width([self bounds].size.width);
5929
5930 if (icon_ != nil) {
5931 CGRect rect;
5932 rect.size = [(UIImage *) icon_ size];
5933
5934 while (rect.size.width > 16 || rect.size.height > 16) {
5935 rect.size.width /= 2;
5936 rect.size.height /= 2;
5937 }
5938
5939 rect.origin.x = 19 - rect.size.width / 2;
5940 rect.origin.y = 19 - rect.size.height / 2;
5941
5942 [icon_ drawInRect:Retina(rect)];
5943 }
5944
5945 if (badge_ != nil) {
5946 CGRect rect;
5947 rect.size = [(UIImage *) badge_ size];
5948
5949 rect.size.width /= 4;
5950 rect.size.height /= 4;
5951
5952 rect.origin.x = 25 - rect.size.width / 2;
5953 rect.origin.y = 25 - rect.size.height / 2;
5954
5955 [badge_ drawInRect:Retina(rect)];
5956 }
5957
5958 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5959 UISetColor(White_);
5960
5961 if (!highlighted)
5962 UISetColor(commercial_ ? Purple_ : Black_);
5963 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5964
5965 if (placard_ != nil)
5966 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5967 }
5968
5969 - (void) drawNormalContentRect:(CGRect)rect {
5970 bool highlighted(highlighted_);
5971 float width([self bounds].size.width);
5972
5973 if (icon_ != nil) {
5974 CGRect rect;
5975 rect.size = [(UIImage *) icon_ size];
5976
5977 while (rect.size.width > 32 || rect.size.height > 32) {
5978 rect.size.width /= 2;
5979 rect.size.height /= 2;
5980 }
5981
5982 rect.origin.x = 25 - rect.size.width / 2;
5983 rect.origin.y = 25 - rect.size.height / 2;
5984
5985 [icon_ drawInRect:Retina(rect)];
5986 }
5987
5988 if (badge_ != nil) {
5989 CGRect rect;
5990 rect.size = [(UIImage *) badge_ size];
5991
5992 rect.size.width /= 2;
5993 rect.size.height /= 2;
5994
5995 rect.origin.x = 36 - rect.size.width / 2;
5996 rect.origin.y = 36 - rect.size.height / 2;
5997
5998 [badge_ drawInRect:Retina(rect)];
5999 }
6000
6001 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6002 UISetColor(White_);
6003
6004 if (!highlighted)
6005 UISetColor(commercial_ ? Purple_ : Black_);
6006 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6007 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6008
6009 if (!highlighted)
6010 UISetColor(commercial_ ? Purplish_ : Gray_);
6011 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6012
6013 if (placard_ != nil)
6014 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6015 }
6016
6017 - (void) drawContentRect:(CGRect)rect {
6018 if (summarized_)
6019 [self drawSummaryContentRect:rect];
6020 else
6021 [self drawNormalContentRect:rect];
6022 }
6023
6024 @end
6025 /* }}} */
6026 /* Section Cell {{{ */
6027 @interface SectionCell : CyteTableViewCell <
6028 CyteTableViewCellDelegate
6029 > {
6030 _H<NSString> basic_;
6031 _H<NSString> section_;
6032 _H<NSString> name_;
6033 _H<NSString> count_;
6034 _H<UIImage> icon_;
6035 _H<UISwitch> switch_;
6036 BOOL editing_;
6037 }
6038
6039 - (void) setSection:(Section *)section editing:(BOOL)editing;
6040
6041 @end
6042
6043 @implementation SectionCell
6044
6045 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6046 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6047 icon_ = [UIImage imageNamed:@"folder.png"];
6048 // XXX: this initial frame is wrong, but is fixed later
6049 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6050 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6051
6052 UIView *content([self contentView]);
6053 CGRect bounds([content bounds]);
6054
6055 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6056 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6057 [content addSubview:content_];
6058 [content_ setBackgroundColor:[UIColor whiteColor]];
6059
6060 [content_ setDelegate:self];
6061 } return self;
6062 }
6063
6064 - (void) onSwitch:(id)sender {
6065 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6066 if (metadata == nil) {
6067 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6068 [Sections_ setObject:metadata forKey:basic_];
6069 }
6070
6071 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6072 Changed_ = true;
6073 }
6074
6075 - (void) setSection:(Section *)section editing:(BOOL)editing {
6076 if (editing != editing_) {
6077 if (editing_)
6078 [switch_ removeFromSuperview];
6079 else
6080 [self addSubview:switch_];
6081 editing_ = editing;
6082 }
6083
6084 basic_ = nil;
6085 section_ = nil;
6086 name_ = nil;
6087 count_ = nil;
6088
6089 if (section == nil) {
6090 name_ = UCLocalize("ALL_PACKAGES");
6091 count_ = nil;
6092 } else {
6093 basic_ = [section name];
6094 section_ = [section localized];
6095
6096 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6097 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6098
6099 if (editing_)
6100 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6101 }
6102
6103 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6104 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6105
6106 [content_ setNeedsDisplay];
6107 }
6108
6109 - (void) setFrame:(CGRect)frame {
6110 [super setFrame:frame];
6111
6112 CGRect rect([switch_ frame]);
6113 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6114 }
6115
6116 - (NSString *) accessibilityLabel {
6117 return name_;
6118 }
6119
6120 - (void) drawContentRect:(CGRect)rect {
6121 bool highlighted(highlighted_ && !editing_);
6122
6123 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6124
6125 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6126 UISetColor(White_);
6127
6128 float width(rect.size.width);
6129 if (editing_)
6130 width -= 9 + [switch_ frame].size.width;
6131
6132 if (!highlighted)
6133 UISetColor(Black_);
6134 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6135
6136 CGSize size = [count_ sizeWithFont:Font14_];
6137
6138 UISetColor(Folder_);
6139 if (count_ != nil)
6140 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6141 }
6142
6143 @end
6144 /* }}} */
6145
6146 /* File Table {{{ */
6147 @interface FileTable : CyteViewController <
6148 UITableViewDataSource,
6149 UITableViewDelegate
6150 > {
6151 _transient Database *database_;
6152 _H<Package> package_;
6153 _H<NSString> name_;
6154 _H<NSMutableArray> files_;
6155 _H<UITableView, 2> list_;
6156 }
6157
6158 - (id) initWithDatabase:(Database *)database;
6159 - (void) setPackage:(Package *)package;
6160
6161 @end
6162
6163 @implementation FileTable
6164
6165 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6166 return files_ == nil ? 0 : [files_ count];
6167 }
6168
6169 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6170 return 24.0f;
6171 }*/
6172
6173 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6174 static NSString *reuseIdentifier = @"Cell";
6175
6176 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6177 if (cell == nil) {
6178 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6179 [cell setFont:[UIFont systemFontOfSize:16]];
6180 }
6181 [cell setText:[files_ objectAtIndex:indexPath.row]];
6182 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6183
6184 return cell;
6185 }
6186
6187 - (NSURL *) navigationURL {
6188 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6189 }
6190
6191 - (void) loadView {
6192 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6193 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6194 [list_ setRowHeight:24.0f];
6195 [(UITableView *) list_ setDataSource:self];
6196 [list_ setDelegate:self];
6197 [self setView:list_];
6198 }
6199
6200 - (void) viewDidLoad {
6201 [super viewDidLoad];
6202
6203 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6204 }
6205
6206 - (void) releaseSubviews {
6207 list_ = nil;
6208
6209 package_ = nil;
6210 files_ = nil;
6211
6212 [super releaseSubviews];
6213 }
6214
6215 - (id) initWithDatabase:(Database *)database {
6216 if ((self = [super init]) != nil) {
6217 database_ = database;
6218 } return self;
6219 }
6220
6221 - (void) setPackage:(Package *)package {
6222 package_ = nil;
6223 name_ = nil;
6224
6225 files_ = [NSMutableArray arrayWithCapacity:32];
6226
6227 if (package != nil) {
6228 package_ = package;
6229 name_ = [package id];
6230
6231 if (NSArray *files = [package files])
6232 [files_ addObjectsFromArray:files];
6233
6234 if ([files_ count] != 0) {
6235 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6236 [files_ removeObjectAtIndex:0];
6237 [files_ sortUsingSelector:@selector(compareByPath:)];
6238
6239 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6240 [stack addObject:@"/"];
6241
6242 for (int i(0), e([files_ count]); i != e; ++i) {
6243 NSString *file = [files_ objectAtIndex:i];
6244 while (![file hasPrefix:[stack lastObject]])
6245 [stack removeLastObject];
6246 NSString *directory = [stack lastObject];
6247 [stack addObject:[file stringByAppendingString:@"/"]];
6248 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6249 ([stack count] - 2) * 3, "",
6250 [file substringFromIndex:[directory length]]
6251 ]];
6252 }
6253 }
6254 }
6255
6256 [list_ reloadData];
6257 }
6258
6259 - (void) reloadData {
6260 [super reloadData];
6261
6262 [self setPackage:[database_ packageWithName:name_]];
6263 }
6264
6265 @end
6266 /* }}} */
6267 /* Package Controller {{{ */
6268 @interface CYPackageController : CydiaWebViewController <
6269 UIActionSheetDelegate
6270 > {
6271 _transient Database *database_;
6272 _H<Package> package_;
6273 _H<NSString> name_;
6274 bool commercial_;
6275 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6276 _H<UIBarButtonItem> button_;
6277 }
6278
6279 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6280
6281 @end
6282
6283 @implementation CYPackageController
6284
6285 - (NSURL *) navigationURL {
6286 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6287 }
6288
6289 - (void) _clickButtonWithName:(NSString *)name {
6290 if ([name isEqualToString:@"CLEAR"])
6291 [delegate_ clearPackage:package_];
6292 else if ([name isEqualToString:@"INSTALL"])
6293 [delegate_ installPackage:package_];
6294 else if ([name isEqualToString:@"REINSTALL"])
6295 [delegate_ installPackage:package_];
6296 else if ([name isEqualToString:@"REMOVE"])
6297 [delegate_ removePackage:package_];
6298 else if ([name isEqualToString:@"UPGRADE"])
6299 [delegate_ installPackage:package_];
6300 else _assert(false);
6301 }
6302
6303 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6304 NSString *context([sheet context]);
6305
6306 if ([context isEqualToString:@"modify"]) {
6307 if (button != [sheet cancelButtonIndex]) {
6308 if (IsWildcat_)
6309 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6310 else
6311 [self _clickButtonWithName:buttons_[button].first];
6312 }
6313
6314 [sheet dismissWithClickedButtonIndex:button animated:YES];
6315 }
6316 }
6317
6318 - (bool) _allowJavaScriptPanel {
6319 return commercial_;
6320 }
6321
6322 #if !AlwaysReload
6323 - (void) _customButtonClicked {
6324 size_t count(buttons_.size());
6325 if (count == 0)
6326 return;
6327
6328 if (count == 1)
6329 [self _clickButtonWithName:buttons_[0].first];
6330 else {
6331 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6332 for (const auto &button : buttons_)
6333 [buttons addObject:button.second];
6334
6335 UIActionSheet *sheet = [[[UIActionSheet alloc]
6336 initWithTitle:nil
6337 delegate:self
6338 cancelButtonTitle:nil
6339 destructiveButtonTitle:nil
6340 otherButtonTitles:nil
6341 ] autorelease];
6342
6343 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6344 if (!IsWildcat_) {
6345 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6346 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6347 }
6348 [sheet setContext:@"modify"];
6349
6350 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6351 }
6352 }
6353
6354 - (void) reloadButtonClicked {
6355 if (commercial_ && function_ == nil && [package_ uninstalled])
6356 return;
6357 [self customButtonClicked];
6358 }
6359
6360 - (void) applyLoadingTitle {
6361 // Don't show "Loading" as the title. Ever.
6362 }
6363
6364 - (UIBarButtonItem *) rightButton {
6365 return button_;
6366 }
6367 #endif
6368
6369 - (void) setPageColor:(UIColor *)color {
6370 return [super setPageColor:nil];
6371 }
6372
6373 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6374 if ((self = [super init]) != nil) {
6375 database_ = database;
6376 name_ = name == nil ? @"" : [NSString stringWithString:name];
6377 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6378 } return self;
6379 }
6380
6381 - (void) reloadData {
6382 [super reloadData];
6383
6384 package_ = [database_ packageWithName:name_];
6385
6386 buttons_.clear();
6387
6388 if (package_ != nil) {
6389 [(Package *) package_ parse];
6390
6391 commercial_ = [package_ isCommercial];
6392
6393 if ([package_ mode] != nil)
6394 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6395 if ([package_ source] == nil);
6396 else if ([package_ upgradableAndEssential:NO])
6397 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6398 else if ([package_ uninstalled])
6399 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6400 else
6401 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6402 if (![package_ uninstalled])
6403 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6404 }
6405
6406 NSString *title;
6407 switch (buttons_.size()) {
6408 case 0: title = nil; break;
6409 case 1: title = buttons_[0].second; break;
6410 default: title = UCLocalize("MODIFY"); break;
6411 }
6412
6413 button_ = [[[UIBarButtonItem alloc]
6414 initWithTitle:title
6415 style:UIBarButtonItemStylePlain
6416 target:self
6417 action:@selector(customButtonClicked)
6418 ] autorelease];
6419 }
6420
6421 - (bool) isLoading {
6422 return commercial_ ? [super isLoading] : false;
6423 }
6424
6425 @end
6426 /* }}} */
6427
6428 /* Package List Controller {{{ */
6429 @interface PackageListController : CyteViewController <
6430 UITableViewDataSource,
6431 UITableViewDelegate
6432 > {
6433 _transient Database *database_;
6434 unsigned era_;
6435 _H<NSArray> packages_;
6436 _H<NSArray> sections_;
6437 _H<UITableView, 2> list_;
6438
6439 _H<NSArray> thumbs_;
6440 std::vector<NSInteger> offset_;
6441
6442 _H<NSString> title_;
6443 unsigned reloading_;
6444 }
6445
6446 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6447 - (void) setDelegate:(id)delegate;
6448 - (void) resetCursor;
6449 - (void) clearData;
6450
6451 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6452
6453 @end
6454
6455 @implementation PackageListController
6456
6457 - (NSURL *) referrerURL {
6458 return [self navigationURL];
6459 }
6460
6461 - (bool) isSummarized {
6462 return false;
6463 }
6464
6465 - (bool) showsSections {
6466 return true;
6467 }
6468
6469 - (void) deselectWithAnimation:(BOOL)animated {
6470 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6471 }
6472
6473 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6474 CGRect base = [[self view] bounds];
6475 base.size.height -= bounds.size.height;
6476 base.origin = [list_ frame].origin;
6477
6478 [UIView beginAnimations:nil context:NULL];
6479 [UIView setAnimationBeginsFromCurrentState:YES];
6480 [UIView setAnimationCurve:curve];
6481 [UIView setAnimationDuration:duration];
6482 [list_ setFrame:base];
6483 [UIView commitAnimations];
6484 }
6485
6486 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6487 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6488 }
6489
6490 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6491 [self resizeForKeyboardBounds:bounds duration:0];
6492 }
6493
6494 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6495 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6496 *curve = UIViewAnimationCurveEaseInOut;
6497 else
6498 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6499
6500 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6501 *duration = 0.3;
6502 else
6503 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6504 }
6505
6506 - (void) keyboardWillShow:(NSNotification *)notification {
6507 CGRect bounds;
6508 CGPoint center;
6509 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6510 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6511
6512 NSTimeInterval duration;
6513 UIViewAnimationCurve curve;
6514 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6515
6516 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6517 UIViewController *base = self;
6518 while ([base parentOrPresentingViewController] != nil)
6519 base = [base parentOrPresentingViewController];
6520 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6521 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6522
6523 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6524 intersection.size.height += CYStatusBarHeight();
6525
6526 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6527 }
6528
6529 - (void) keyboardWillHide:(NSNotification *)notification {
6530 NSTimeInterval duration;
6531 UIViewAnimationCurve curve;
6532 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6533
6534 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6535 }
6536
6537 - (void) viewWillAppear:(BOOL)animated {
6538 [super viewWillAppear:animated];
6539
6540 [self resizeForKeyboardBounds:CGRectZero];
6541 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6542 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6543 }
6544
6545 - (void) viewWillDisappear:(BOOL)animated {
6546 [super viewWillDisappear:animated];
6547
6548 [self resizeForKeyboardBounds:CGRectZero];
6549 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6550 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6551 }
6552
6553 - (void) viewDidAppear:(BOOL)animated {
6554 [super viewDidAppear:animated];
6555 [self deselectWithAnimation:animated];
6556 }
6557
6558 - (void) didSelectPackage:(Package *)package {
6559 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6560 [view setDelegate:delegate_];
6561 [[self navigationController] pushViewController:view animated:YES];
6562 }
6563
6564 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6565 NSInteger count([sections_ count]);
6566 return count == 0 ? 1 : count;
6567 }
6568
6569 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6570 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6571 return nil;
6572 return [[sections_ objectAtIndex:section] name];
6573 }
6574
6575 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6576 if ([sections_ count] == 0)
6577 return 0;
6578 return [[sections_ objectAtIndex:section] count];
6579 }
6580
6581 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6582 @synchronized (database_) {
6583 if ([database_ era] != era_)
6584 return nil;
6585
6586 Section *section([sections_ objectAtIndex:[path section]]);
6587 NSInteger row([path row]);
6588 Package *package([packages_ objectAtIndex:([section row] + row)]);
6589 return [[package retain] autorelease];
6590 } }
6591
6592 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6593 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6594 if (cell == nil)
6595 cell = [[[PackageCell alloc] init] autorelease];
6596
6597 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6598 [cell setPackage:package asSummary:[self isSummarized]];
6599 return cell;
6600 }
6601
6602 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6603 Package *package([self packageAtIndexPath:path]);
6604 package = [database_ packageWithName:[package id]];
6605 [self didSelectPackage:package];
6606 }
6607
6608 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6609 return thumbs_;
6610 }
6611
6612 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6613 return offset_[index];
6614 }
6615
6616 - (void) updateHeight {
6617 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6618 }
6619
6620 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6621 if ((self = [super init]) != nil) {
6622 database_ = database;
6623 title_ = [title copy];
6624 [[self navigationItem] setTitle:title_];
6625 } return self;
6626 }
6627
6628 - (void) loadView {
6629 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6630 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6631 [self setView:view];
6632
6633 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6634 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6635 [view addSubview:list_];
6636
6637 // XXX: is 20 the most optimal number here?
6638 [list_ setSectionIndexMinimumDisplayRowCount:20];
6639
6640 [(UITableView *) list_ setDataSource:self];
6641 [list_ setDelegate:self];
6642
6643 [self updateHeight];
6644 }
6645
6646 - (void) releaseSubviews {
6647 list_ = nil;
6648
6649 packages_ = nil;
6650 sections_ = nil;
6651
6652 thumbs_ = nil;
6653 offset_.clear();
6654
6655 [super releaseSubviews];
6656 }
6657
6658 - (void) setDelegate:(id)delegate {
6659 delegate_ = delegate;
6660 }
6661
6662 - (bool) shouldYield {
6663 return false;
6664 }
6665
6666 - (bool) shouldBlock {
6667 return false;
6668 }
6669
6670 - (NSMutableArray *) _reloadPackages {
6671 @synchronized (database_) {
6672 era_ = [database_ era];
6673 NSArray *packages([database_ packages]);
6674
6675 return [NSMutableArray arrayWithArray:packages];
6676 } }
6677
6678 - (void) _reloadData {
6679 if (reloading_ != 0) {
6680 reloading_ = 2;
6681 return;
6682 }
6683
6684 NSMutableArray *packages;
6685
6686 reload:
6687 if ([self shouldYield]) {
6688 do {
6689 UIProgressHUD *hud;
6690
6691 if (![self shouldBlock])
6692 hud = nil;
6693 else {
6694 hud = [delegate_ addProgressHUD];
6695 [hud setText:UCLocalize("LOADING")];
6696 }
6697
6698 reloading_ = 1;
6699 packages = [self yieldToSelector:@selector(_reloadPackages)];
6700
6701 if (hud != nil)
6702 [delegate_ removeProgressHUD:hud];
6703 } while (reloading_ == 2);
6704 } else {
6705 packages = [self _reloadPackages];
6706 }
6707
6708 @synchronized (database_) {
6709 if (era_ != [database_ era])
6710 goto reload;
6711 reloading_ = 0;
6712
6713 thumbs_ = nil;
6714 offset_.clear();
6715
6716 packages_ = packages;
6717
6718 if ([self showsSections])
6719 sections_ = [self sectionsForPackages:packages];
6720 else {
6721 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6722 [section setCount:[packages_ count]];
6723 sections_ = [NSArray arrayWithObject:section];
6724 }
6725
6726 [self updateHeight];
6727
6728 _profile(PackageTable$reloadData$List)
6729 [(UITableView *) list_ setDataSource:self];
6730 [list_ reloadData];
6731 _end
6732 }
6733
6734 PrintTimes();
6735 }
6736
6737 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6738 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6739 size_t end([packages count]);
6740
6741 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6742 Section *section(prefix);
6743
6744 thumbs_ = CollationThumbs_;
6745 offset_ = CollationOffset_;
6746
6747 size_t offset(0);
6748 size_t offsets([CollationStarts_ count]);
6749
6750 NSString *start([CollationStarts_ objectAtIndex:offset]);
6751 size_t length([start length]);
6752
6753 for (size_t index(0); index != end; ++index) {
6754 if (start != nil) {
6755 Package *package([packages objectAtIndex:index]);
6756 NSString *name(PackageName(package, @selector(cyname)));
6757
6758 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6759 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6760 NSString *title([CollationTitles_ objectAtIndex:offset]);
6761 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6762 [sections addObject:section];
6763
6764 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6765 if (start == nil)
6766 break;
6767 length = [start length];
6768 }
6769 }
6770
6771 [section addToCount];
6772 }
6773
6774 for (; offset != offsets; ++offset) {
6775 NSString *title([CollationTitles_ objectAtIndex:offset]);
6776 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6777 [sections addObject:section];
6778 }
6779
6780 if ([prefix count] != 0) {
6781 Section *suffix([sections lastObject]);
6782 [prefix setName:[suffix name]];
6783 [suffix setName:nil];
6784 [sections insertObject:prefix atIndex:(offsets - 1)];
6785 }
6786
6787 return sections;
6788 }
6789
6790 - (void) reloadData {
6791 [super reloadData];
6792
6793 if ([self shouldYield])
6794 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6795 else
6796 [self _reloadData];
6797 }
6798
6799 - (void) resetCursor {
6800 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6801 }
6802
6803 - (void) clearData {
6804 [self updateHeight];
6805
6806 [list_ setDataSource:nil];
6807 [list_ reloadData];
6808
6809 [self resetCursor];
6810 }
6811
6812 @end
6813 /* }}} */
6814 /* Filtered Package List Controller {{{ */
6815 typedef Function<bool, Package *> PackageFilter;
6816 typedef Function<void, NSMutableArray *> PackageSorter;
6817 @interface FilteredPackageListController : PackageListController {
6818 PackageFilter filter_;
6819 PackageSorter sorter_;
6820 }
6821
6822 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6823
6824 - (void) setFilter:(PackageFilter)filter;
6825 - (void) setSorter:(PackageSorter)sorter;
6826
6827 @end
6828
6829 @implementation FilteredPackageListController
6830
6831 - (void) setFilter:(PackageFilter)filter {
6832 @synchronized (self) {
6833 filter_ = filter;
6834 } }
6835
6836 - (void) setSorter:(PackageSorter)sorter {
6837 @synchronized (self) {
6838 sorter_ = sorter;
6839 } }
6840
6841 - (NSMutableArray *) _reloadPackages {
6842 @synchronized (database_) {
6843 era_ = [database_ era];
6844
6845 NSArray *packages([database_ packages]);
6846 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6847
6848 PackageFilter filter;
6849 PackageSorter sorter;
6850
6851 @synchronized (self) {
6852 filter = filter_;
6853 sorter = sorter_;
6854 }
6855
6856 _profile(PackageTable$reloadData$Filter)
6857 for (Package *package in packages)
6858 if ([package valid] && filter(package))
6859 [filtered addObject:package];
6860 _end
6861
6862 if (sorter)
6863 sorter(filtered);
6864 return filtered;
6865 } }
6866
6867 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6868 if ((self = [super initWithDatabase:database title:title]) != nil) {
6869 [self setFilter:filter];
6870 } return self;
6871 }
6872
6873 @end
6874 /* }}} */
6875
6876 /* Home Controller {{{ */
6877 @interface HomeController : CydiaWebViewController {
6878 CFRunLoopRef runloop_;
6879 SCNetworkReachabilityRef reachability_;
6880 }
6881
6882 @end
6883
6884 @implementation HomeController
6885
6886 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6887 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6888 }
6889
6890 - (id) init {
6891 if ((self = [super init]) != nil) {
6892 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6893 [self reloadData];
6894
6895 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6896 if (reachability_ != NULL) {
6897 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6898 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6899
6900 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6901 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6902 runloop_ = runloop;
6903 }
6904 } return self;
6905 }
6906
6907 - (void) dealloc {
6908 if (reachability_ != NULL && runloop_ != NULL)
6909 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6910 [super dealloc];
6911 }
6912
6913 - (NSURL *) navigationURL {
6914 return [NSURL URLWithString:@"cydia://home"];
6915 }
6916
6917 - (void) aboutButtonClicked {
6918 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6919
6920 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6921 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6922 [alert setCancelButtonIndex:0];
6923
6924 [alert setMessage:
6925 @"Copyright \u00a9 2008-2014\n"
6926 "SaurikIT, LLC\n"
6927 "\n"
6928 "Jay Freeman (saurik)\n"
6929 "saurik@saurik.com\n"
6930 "http://www.saurik.com/"
6931 ];
6932
6933 [alert show];
6934 }
6935
6936 - (UIBarButtonItem *) leftButton {
6937 return [[[UIBarButtonItem alloc]
6938 initWithTitle:UCLocalize("ABOUT")
6939 style:UIBarButtonItemStylePlain
6940 target:self
6941 action:@selector(aboutButtonClicked)
6942 ] autorelease];
6943 }
6944
6945 @end
6946 /* }}} */
6947
6948 /* Cydia Navigation Controller Interface {{{ */
6949 @interface UINavigationController (Cydia)
6950
6951 - (NSArray *) navigationURLCollection;
6952 - (void) unloadData;
6953
6954 @end
6955 /* }}} */
6956
6957 /* Cydia Tab Bar Controller {{{ */
6958 @interface CydiaTabBarController : CyteTabBarController <
6959 UITabBarControllerDelegate,
6960 FetchDelegate
6961 > {
6962 _transient Database *database_;
6963
6964 _H<UIActivityIndicatorView> indicator_;
6965
6966 bool updating_;
6967 // XXX: ok, "updatedelegate_"?...
6968 _transient NSObject<CydiaDelegate> *updatedelegate_;
6969 }
6970
6971 - (NSArray *) navigationURLCollection;
6972 - (void) beginUpdate;
6973 - (BOOL) updating;
6974
6975 @end
6976
6977 @implementation CydiaTabBarController
6978
6979 - (NSArray *) navigationURLCollection {
6980 NSMutableArray *items([NSMutableArray array]);
6981
6982 // XXX: Should this deal with transient view controllers?
6983 for (id navigation in [self viewControllers]) {
6984 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6985 if (stack != nil)
6986 [items addObject:stack];
6987 }
6988
6989 return items;
6990 }
6991
6992 - (id) initWithDatabase:(Database *)database {
6993 if ((self = [super init]) != nil) {
6994 database_ = database;
6995 [self setDelegate:self];
6996
6997 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6998 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6999
7000 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7001 } return self;
7002 }
7003
7004 - (void) setUpdate:(NSDate *)date {
7005 [self beginUpdate];
7006 }
7007
7008 - (void) beginUpdate {
7009 if (updating_)
7010 return;
7011
7012 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7013 UITabBarItem *item([controller tabBarItem]);
7014
7015 [item setBadgeValue:@""];
7016 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7017
7018 [indicator_ startAnimating];
7019 [badge addSubview:indicator_];
7020
7021 [updatedelegate_ retainNetworkActivityIndicator];
7022 updating_ = true;
7023
7024 [NSThread
7025 detachNewThreadSelector:@selector(performUpdate)
7026 toTarget:self
7027 withObject:nil
7028 ];
7029 }
7030
7031 - (void) performUpdate {
7032 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7033
7034 SourceStatus status(self, database_);
7035 [database_ updateWithStatus:status];
7036
7037 [self
7038 performSelectorOnMainThread:@selector(completeUpdate)
7039 withObject:nil
7040 waitUntilDone:NO
7041 ];
7042
7043 [pool release];
7044 }
7045
7046 - (void) stopUpdateWithSelector:(SEL)selector {
7047 updating_ = false;
7048 [updatedelegate_ releaseNetworkActivityIndicator];
7049
7050 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7051 [[controller tabBarItem] setBadgeValue:nil];
7052
7053 [indicator_ removeFromSuperview];
7054 [indicator_ stopAnimating];
7055
7056 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7057 }
7058
7059 - (void) completeUpdate {
7060 if (!updating_)
7061 return;
7062 [self stopUpdateWithSelector:@selector(reloadData)];
7063 }
7064
7065 - (void) cancelUpdate {
7066 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7067 }
7068
7069 - (void) cancelPressed {
7070 [self cancelUpdate];
7071 }
7072
7073 - (BOOL) updating {
7074 return updating_;
7075 }
7076
7077 - (bool) isSourceCancelled {
7078 return !updating_;
7079 }
7080
7081 - (void) startSourceFetch:(NSString *)uri {
7082 }
7083
7084 - (void) stopSourceFetch:(NSString *)uri {
7085 }
7086
7087 - (void) setUpdateDelegate:(id)delegate {
7088 updatedelegate_ = delegate;
7089 }
7090
7091 @end
7092 /* }}} */
7093
7094 /* Cydia Navigation Controller Implementation {{{ */
7095 @implementation UINavigationController (Cydia)
7096
7097 - (NSArray *) navigationURLCollection {
7098 NSMutableArray *stack([NSMutableArray array]);
7099
7100 for (CyteViewController *controller in [self viewControllers]) {
7101 NSString *url = [[controller navigationURL] absoluteString];
7102 if (url != nil)
7103 [stack addObject:url];
7104 }
7105
7106 return stack;
7107 }
7108
7109 - (void) reloadData {
7110 [super reloadData];
7111
7112 UIViewController *visible([self visibleViewController]);
7113 if (visible != nil)
7114 [visible reloadData];
7115
7116 // on the iPad, this view controller is ALSO visible. :(
7117 if (IsWildcat_)
7118 if (UIViewController *top = [self topViewController])
7119 if (top != visible)
7120 [top reloadData];
7121 }
7122
7123 - (void) unloadData {
7124 for (CyteViewController *page in [self viewControllers])
7125 [page unloadData];
7126
7127 [super unloadData];
7128 }
7129
7130 @end
7131 /* }}} */
7132
7133 /* Cydia:// Protocol {{{ */
7134 @interface CydiaURLProtocol : NSURLProtocol {
7135 }
7136
7137 @end
7138
7139 @implementation CydiaURLProtocol
7140
7141 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7142 NSURL *url([request URL]);
7143 if (url == nil)
7144 return NO;
7145
7146 NSString *scheme([[url scheme] lowercaseString]);
7147 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7148 return YES;
7149 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7150 return YES;
7151
7152 return NO;
7153 }
7154
7155 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7156 return request;
7157 }
7158
7159 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7160 id<NSURLProtocolClient> client([self client]);
7161 if (icon == nil)
7162 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7163 else {
7164 NSData *data(UIImagePNGRepresentation(icon));
7165
7166 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7167 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7168 [client URLProtocol:self didLoadData:data];
7169 [client URLProtocolDidFinishLoading:self];
7170 }
7171 }
7172
7173 - (void) startLoading {
7174 id<NSURLProtocolClient> client([self client]);
7175 NSURLRequest *request([self request]);
7176
7177 NSURL *url([request URL]);
7178 NSString *href([url absoluteString]);
7179 NSString *scheme([[url scheme] lowercaseString]);
7180
7181 NSString *path;
7182
7183 if ([scheme isEqualToString:@"cydia"])
7184 path = [href substringFromIndex:8];
7185 else if ([scheme isEqualToString:@"about"])
7186 path = [href substringFromIndex:12];
7187 else _assert(false);
7188
7189 NSRange slash([path rangeOfString:@"/"]);
7190
7191 NSString *command;
7192 if (slash.location == NSNotFound) {
7193 command = path;
7194 path = nil;
7195 } else {
7196 command = [path substringToIndex:slash.location];
7197 path = [path substringFromIndex:(slash.location + 1)];
7198 }
7199
7200 Database *database([Database sharedInstance]);
7201
7202 if ([command isEqualToString:@"package-icon"]) {
7203 if (path == nil)
7204 goto fail;
7205 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7206 Package *package([database packageWithName:path]);
7207 if (package == nil)
7208 goto fail;
7209 [package parse];
7210 UIImage *icon([package icon]);
7211 [self _returnPNGWithImage:icon forRequest:request];
7212 } else if ([command isEqualToString:@"uikit-image"]) {
7213 if (path == nil)
7214 goto fail;
7215 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7216 UIImage *icon(_UIImageWithName(path));
7217 [self _returnPNGWithImage:icon forRequest:request];
7218 } else if ([command isEqualToString:@"section-icon"]) {
7219 if (path == nil)
7220 goto fail;
7221 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7222 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7223 if (icon == nil)
7224 icon = [UIImage imageNamed:@"unknown.png"];
7225 [self _returnPNGWithImage:icon forRequest:request];
7226 } else fail: {
7227 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7228 }
7229 }
7230
7231 - (void) stopLoading {
7232 }
7233
7234 @end
7235 /* }}} */
7236
7237 /* Section Controller {{{ */
7238 @interface SectionController : FilteredPackageListController {
7239 _H<NSString> key_;
7240 _H<NSString> section_;
7241 }
7242
7243 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7244
7245 @end
7246
7247 @implementation SectionController
7248
7249 - (NSURL *) referrerURL {
7250 NSString *name(section_);
7251 name = name ?: @"*";
7252 NSString *key(key_);
7253 key = key ?: @"*";
7254 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7255 }
7256
7257 - (NSURL *) navigationURL {
7258 NSString *name(section_);
7259 name = name ?: @"*";
7260 NSString *key(key_);
7261 key = key ?: @"*";
7262 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7263 }
7264
7265 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7266 NSString *title;
7267 if (section == nil)
7268 title = UCLocalize("ALL_PACKAGES");
7269 else if (![section isEqual:@""])
7270 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7271 else
7272 title = UCLocalize("NO_SECTION");
7273
7274 if ((self = [super initWithDatabase:database title:title]) != nil) {
7275 key_ = [source key];
7276 section_ = section;
7277 } return self;
7278 }
7279
7280 - (void) reloadData {
7281 Source *source([database_ sourceWithKey:key_]);
7282 _H<NSString> name(section_);
7283
7284 [self setFilter:[=](Package *package) {
7285 NSString *section([package section]);
7286
7287 return (
7288 name == nil ||
7289 section == nil && [name length] == 0 ||
7290 [name isEqualToString:section]
7291 ) && (
7292 source == nil ||
7293 [package source] == source
7294 ) && [package visible];
7295 }];
7296
7297 [super reloadData];
7298 }
7299
7300 @end
7301 /* }}} */
7302 /* Sections Controller {{{ */
7303 @interface SectionsController : CyteViewController <
7304 UITableViewDataSource,
7305 UITableViewDelegate
7306 > {
7307 _transient Database *database_;
7308 _H<NSString> key_;
7309 _H<NSMutableArray> sections_;
7310 _H<NSMutableArray> filtered_;
7311 _H<UITableView, 2> list_;
7312 }
7313
7314 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7315 - (void) editButtonClicked;
7316
7317 @end
7318
7319 @implementation SectionsController
7320
7321 - (NSURL *) navigationURL {
7322 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7323 }
7324
7325 - (Source *) source {
7326 if (key_ == nil)
7327 return nil;
7328 return [database_ sourceWithKey:key_];
7329 }
7330
7331 - (void) updateNavigationItem {
7332 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7333 if ([sections_ count] == 0) {
7334 [[self navigationItem] setRightBarButtonItem:nil];
7335 } else {
7336 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7337 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7338 target:self
7339 action:@selector(editButtonClicked)
7340 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7341 }
7342 }
7343
7344 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7345 [super setEditing:editing animated:animated];
7346
7347 if (editing)
7348 [list_ reloadData];
7349 else
7350 [delegate_ updateData];
7351
7352 [self updateNavigationItem];
7353 }
7354
7355 - (void) viewDidAppear:(BOOL)animated {
7356 [super viewDidAppear:animated];
7357 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7358 }
7359
7360 - (void) viewWillDisappear:(BOOL)animated {
7361 [super viewWillDisappear:animated];
7362 [self setEditing:NO];
7363 }
7364
7365 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7366 Section *section = nil;
7367 int index = [indexPath row];
7368 if (![self isEditing]) {
7369 index -= 1;
7370 if (index >= 0)
7371 section = [filtered_ objectAtIndex:index];
7372 } else {
7373 section = [sections_ objectAtIndex:index];
7374 }
7375 return section;
7376 }
7377
7378 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7379 if ([self isEditing])
7380 return [sections_ count];
7381 else
7382 return [filtered_ count] + 1;
7383 }
7384
7385 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7386 return 45.0f;
7387 }*/
7388
7389 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7390 static NSString *reuseIdentifier = @"SectionCell";
7391
7392 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7393 if (cell == nil)
7394 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7395
7396 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7397
7398 return cell;
7399 }
7400
7401 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7402 if ([self isEditing])
7403 return;
7404
7405 Section *section = [self sectionAtIndexPath:indexPath];
7406
7407 SectionController *controller = [[[SectionController alloc]
7408 initWithDatabase:database_
7409 source:[self source]
7410 section:[section name]
7411 ] autorelease];
7412 [controller setDelegate:delegate_];
7413
7414 [[self navigationController] pushViewController:controller animated:YES];
7415 }
7416
7417 - (void) loadView {
7418 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7419 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7420 [list_ setRowHeight:46];
7421 [(UITableView *) list_ setDataSource:self];
7422 [list_ setDelegate:self];
7423 [self setView:list_];
7424 }
7425
7426 - (void) viewDidLoad {
7427 [super viewDidLoad];
7428
7429 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7430 }
7431
7432 - (void) releaseSubviews {
7433 list_ = nil;
7434
7435 sections_ = nil;
7436 filtered_ = nil;
7437
7438 [super releaseSubviews];
7439 }
7440
7441 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7442 if ((self = [super init]) != nil) {
7443 database_ = database;
7444 key_ = [source key];
7445 } return self;
7446 }
7447
7448 - (void) reloadData {
7449 [super reloadData];
7450
7451 NSArray *packages = [database_ packages];
7452
7453 sections_ = [NSMutableArray arrayWithCapacity:16];
7454 filtered_ = [NSMutableArray arrayWithCapacity:16];
7455
7456 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7457
7458 Source *source([self source]);
7459
7460 _trace();
7461 for (Package *package in packages) {
7462 if (source != nil && [package source] != source)
7463 continue;
7464
7465 NSString *name([package section]);
7466 NSString *key(name == nil ? @"" : name);
7467
7468 Section *section;
7469
7470 _profile(SectionsView$reloadData$Section)
7471 section = [sections objectForKey:key];
7472 if (section == nil) {
7473 _profile(SectionsView$reloadData$Section$Allocate)
7474 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7475 [sections setObject:section forKey:key];
7476 _end
7477 }
7478 _end
7479
7480 [section addToCount];
7481
7482 _profile(SectionsView$reloadData$Filter)
7483 if (![package valid] || ![package visible])
7484 continue;
7485 _end
7486
7487 [section addToRow];
7488 }
7489 _trace();
7490
7491 [sections_ addObjectsFromArray:[sections allValues]];
7492
7493 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7494
7495 for (Section *section in (id) sections_) {
7496 size_t count([section row]);
7497 if (count == 0)
7498 continue;
7499
7500 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7501 [section setCount:count];
7502 [filtered_ addObject:section];
7503 }
7504
7505 [self updateNavigationItem];
7506 [list_ reloadData];
7507 _trace();
7508 }
7509
7510 - (void) editButtonClicked {
7511 [self setEditing:![self isEditing] animated:YES];
7512 }
7513
7514 @end
7515 /* }}} */
7516
7517 /* Changes Controller {{{ */
7518 @interface ChangesController : FilteredPackageListController {
7519 unsigned upgrades_;
7520 }
7521
7522 - (id) initWithDatabase:(Database *)database;
7523
7524 @end
7525
7526 @implementation ChangesController
7527
7528 - (NSURL *) referrerURL {
7529 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7530 }
7531
7532 - (NSURL *) navigationURL {
7533 return [NSURL URLWithString:@"cydia://changes"];
7534 }
7535
7536 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7537 @synchronized (database_) {
7538 if ([database_ era] != era_)
7539 return nil;
7540
7541 NSUInteger sectionIndex([path section]);
7542 if (sectionIndex >= [sections_ count])
7543 return nil;
7544 Section *section([sections_ objectAtIndex:sectionIndex]);
7545 NSInteger row([path row]);
7546 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7547 } }
7548
7549 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7550 NSString *context([alert context]);
7551
7552 if ([context isEqualToString:@"norefresh"])
7553 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7554 }
7555
7556 - (void) setLeftBarButtonItem {
7557 if ([delegate_ updating])
7558 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7559 initWithTitle:UCLocalize("CANCEL")
7560 style:UIBarButtonItemStyleDone
7561 target:self
7562 action:@selector(cancelButtonClicked)
7563 ] autorelease] animated:YES];
7564 else
7565 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7566 initWithTitle:UCLocalize("REFRESH")
7567 style:UIBarButtonItemStylePlain
7568 target:self
7569 action:@selector(refreshButtonClicked)
7570 ] autorelease] animated:YES];
7571 }
7572
7573 - (void) refreshButtonClicked {
7574 if ([delegate_ requestUpdate])
7575 [self setLeftBarButtonItem];
7576 }
7577
7578 - (void) cancelButtonClicked {
7579 [delegate_ cancelUpdate];
7580 }
7581
7582 - (void) upgradeButtonClicked {
7583 [delegate_ distUpgrade];
7584 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7585 }
7586
7587 - (bool) shouldYield {
7588 return true;
7589 }
7590
7591 - (bool) shouldBlock {
7592 return true;
7593 }
7594
7595 - (void) useFilter {
7596 @synchronized (self) {
7597 [self setFilter:[](Package *package) {
7598 return [package upgradableAndEssential:YES] || [package visible];
7599 }];
7600
7601 [self setSorter:[](NSMutableArray *packages) {
7602 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7603 }];
7604 } }
7605
7606 - (id) initWithDatabase:(Database *)database {
7607 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7608 [self useFilter];
7609 } return self;
7610 }
7611
7612 - (void) viewDidLoad {
7613 [super viewDidLoad];
7614 [self setLeftBarButtonItem];
7615 }
7616
7617 - (void) viewWillAppear:(BOOL)animated {
7618 [super viewWillAppear:animated];
7619 [self setLeftBarButtonItem];
7620 }
7621
7622 - (void) reloadData {
7623 [self setLeftBarButtonItem];
7624 [super reloadData];
7625 }
7626
7627 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7628 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7629
7630 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7631 Section *ignored = nil;
7632 Section *section = nil;
7633 time_t last = 0;
7634
7635 upgrades_ = 0;
7636 bool unseens = false;
7637
7638 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7639
7640 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7641 Package *package = [packages objectAtIndex:offset];
7642
7643 BOOL uae = [package upgradableAndEssential:YES];
7644
7645 if (!uae) {
7646 unseens = true;
7647 time_t seen([package seen]);
7648
7649 if (section == nil || last != seen) {
7650 last = seen;
7651
7652 NSString *name;
7653 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7654 [name autorelease];
7655
7656 _profile(ChangesController$reloadData$Allocate)
7657 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7658 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7659 [sections addObject:section];
7660 _end
7661 }
7662
7663 [section addToCount];
7664 } else if ([package ignored]) {
7665 if (ignored == nil) {
7666 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7667 }
7668 [ignored addToCount];
7669 } else {
7670 ++upgrades_;
7671 [upgradable addToCount];
7672 }
7673 }
7674 _trace();
7675
7676 CFRelease(formatter);
7677
7678 if (unseens) {
7679 Section *last = [sections lastObject];
7680 size_t count = [last count];
7681 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7682 [sections removeLastObject];
7683 }
7684
7685 if ([ignored count] != 0)
7686 [sections insertObject:ignored atIndex:0];
7687 if (upgrades_ != 0)
7688 [sections insertObject:upgradable atIndex:0];
7689
7690 [list_ reloadData];
7691
7692 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7693 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7694 style:UIBarButtonItemStylePlain
7695 target:self
7696 action:@selector(upgradeButtonClicked)
7697 ] autorelease]) animated:YES];
7698
7699 return sections;
7700 }
7701
7702 @end
7703 /* }}} */
7704 /* Search Controller {{{ */
7705 @interface SearchController : FilteredPackageListController <
7706 UISearchBarDelegate
7707 > {
7708 _H<UISearchBar, 1> search_;
7709 BOOL searchloaded_;
7710 bool summary_;
7711 }
7712
7713 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7714 - (void) reloadData;
7715
7716 @end
7717
7718 @implementation SearchController
7719
7720 - (NSURL *) referrerURL {
7721 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7722 }
7723
7724 - (NSURL *) navigationURL {
7725 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7726 return [NSURL URLWithString:@"cydia://search"];
7727 else
7728 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7729 }
7730
7731 - (NSArray *) termsForQuery:(NSString *)query {
7732 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7733 for (NSString *component in [query componentsSeparatedByString:@" "])
7734 if ([component length] != 0)
7735 [terms addObject:component];
7736
7737 return terms;
7738 }
7739
7740 - (void) useSearch {
7741 _H<NSArray> query([self termsForQuery:[search_ text]]);
7742 summary_ = false;
7743
7744 @synchronized (self) {
7745 [self setFilter:[=](Package *package) {
7746 if (![package unfiltered])
7747 return false;
7748 if (![package matches:query])
7749 return false;
7750 return true;
7751 }];
7752
7753 [self setSorter:[](NSMutableArray *packages) {
7754 [packages radixSortUsingSelector:@selector(rank)];
7755 }];
7756 }
7757
7758 [self clearData];
7759 [self reloadData];
7760 }
7761
7762 - (void) usePrefix:(NSString *)prefix {
7763 _H<NSString> query(prefix);
7764 summary_ = true;
7765
7766 @synchronized (self) {
7767 [self setFilter:[=](Package *package) {
7768 if ([query length] == 0)
7769 return false;
7770 if (![package unfiltered])
7771 return false;
7772 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7773 return false;
7774 return true;
7775 }];
7776
7777 [self setSorter:nullptr];
7778 }
7779
7780 [self reloadData];
7781 }
7782
7783 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7784 [self clearData];
7785 [self usePrefix:[search_ text]];
7786 }
7787
7788 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7789 [search_ resignFirstResponder];
7790 [self useSearch];
7791 }
7792
7793 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7794 [search_ setText:@""];
7795 [self searchBarButtonClicked:searchBar];
7796 }
7797
7798 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7799 [self searchBarButtonClicked:searchBar];
7800 }
7801
7802 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7803 [self usePrefix:text];
7804 }
7805
7806 - (bool) shouldYield {
7807 return YES;
7808 }
7809
7810 - (bool) shouldBlock {
7811 return !summary_;
7812 }
7813
7814 - (bool) isSummarized {
7815 return summary_;
7816 }
7817
7818 - (bool) showsSections {
7819 return false;
7820 }
7821
7822 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7823 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7824 search_ = [[[UISearchBar alloc] init] autorelease];
7825 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7826 [search_ setDelegate:self];
7827
7828 UITextField *textField;
7829 if ([search_ respondsToSelector:@selector(searchField)])
7830 textField = [search_ searchField];
7831 else
7832 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7833
7834 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7835 [textField setEnablesReturnKeyAutomatically:NO];
7836 [[self navigationItem] setTitleView:textField];
7837
7838 if (query != nil)
7839 [search_ setText:query];
7840 [self useSearch];
7841 } return self;
7842 }
7843
7844 - (void) viewDidAppear:(BOOL)animated {
7845 [super viewDidAppear:animated];
7846
7847 if (!searchloaded_) {
7848 searchloaded_ = YES;
7849 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7850 [search_ layoutSubviews];
7851 }
7852
7853 if ([self isSummarized])
7854 [search_ becomeFirstResponder];
7855 }
7856
7857 - (void) reloadData {
7858 [self resetCursor];
7859 [super reloadData];
7860 }
7861
7862 - (void) didSelectPackage:(Package *)package {
7863 [search_ resignFirstResponder];
7864 [super didSelectPackage:package];
7865 }
7866
7867 @end
7868 /* }}} */
7869 /* Package Settings Controller {{{ */
7870 @interface PackageSettingsController : CyteViewController <
7871 UITableViewDataSource,
7872 UITableViewDelegate
7873 > {
7874 _transient Database *database_;
7875 _H<NSString> name_;
7876 _H<Package> package_;
7877 _H<UITableView, 2> table_;
7878 _H<UISwitch> subscribedSwitch_;
7879 _H<UISwitch> ignoredSwitch_;
7880 _H<UITableViewCell> subscribedCell_;
7881 _H<UITableViewCell> ignoredCell_;
7882 }
7883
7884 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7885
7886 @end
7887
7888 @implementation PackageSettingsController
7889
7890 - (NSURL *) navigationURL {
7891 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7892 }
7893
7894 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7895 if (package_ == nil)
7896 return 0;
7897
7898 if ([package_ installed] == nil)
7899 return 1;
7900 else
7901 return 2;
7902 }
7903
7904 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7905 if (package_ == nil)
7906 return 0;
7907
7908 // both sections contain just one item right now.
7909 return 1;
7910 }
7911
7912 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7913 return nil;
7914 }
7915
7916 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7917 if (section == 0)
7918 return UCLocalize("SHOW_ALL_CHANGES_EX");
7919 else
7920 return UCLocalize("IGNORE_UPGRADES_EX");
7921 }
7922
7923 - (void) onSubscribed:(id)control {
7924 bool value([control isOn]);
7925 if (package_ == nil)
7926 return;
7927 if ([package_ setSubscribed:value])
7928 [delegate_ updateData];
7929 }
7930
7931 - (void) _updateIgnored {
7932 const char *package([name_ UTF8String]);
7933 bool on([ignoredSwitch_ isOn]);
7934
7935 pid_t pid(ExecFork());
7936 if (pid == 0) {
7937 FILE *dpkg(_root(popen("dpkg --set-selections", "w")));
7938 fwrite(package, strlen(package), 1, dpkg);
7939
7940 if (on)
7941 fwrite(" hold\n", 6, 1, dpkg);
7942 else
7943 fwrite(" install\n", 9, 1, dpkg);
7944
7945 pclose(dpkg);
7946
7947 exit(0);
7948 } ReapZombie(pid);
7949 }
7950
7951 - (void) onIgnored:(id)control {
7952 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7953 [invocation setTarget:self];
7954 [invocation setSelector:@selector(_updateIgnored)];
7955
7956 [delegate_ reloadDataWithInvocation:invocation];
7957 }
7958
7959 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7960 if (package_ == nil)
7961 return nil;
7962
7963 switch ([indexPath section]) {
7964 case 0: return subscribedCell_;
7965 case 1: return ignoredCell_;
7966
7967 _nodefault
7968 }
7969
7970 return nil;
7971 }
7972
7973 - (void) loadView {
7974 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7975 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7976 [self setView:view];
7977
7978 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7979 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7980 [(UITableView *) table_ setDataSource:self];
7981 [table_ setDelegate:self];
7982 [view addSubview:table_];
7983
7984 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7985 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7986 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7987
7988 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7989 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7990 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7991
7992 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7993 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7994 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7995 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7996
7997 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7998 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7999 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8000 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8001 }
8002
8003 - (void) viewDidLoad {
8004 [super viewDidLoad];
8005
8006 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8007 }
8008
8009 - (void) releaseSubviews {
8010 ignoredCell_ = nil;
8011 subscribedCell_ = nil;
8012 table_ = nil;
8013 ignoredSwitch_ = nil;
8014 subscribedSwitch_ = nil;
8015
8016 [super releaseSubviews];
8017 }
8018
8019 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8020 if ((self = [super init]) != nil) {
8021 database_ = database;
8022 name_ = package;
8023 } return self;
8024 }
8025
8026 - (void) reloadData {
8027 [super reloadData];
8028
8029 package_ = [database_ packageWithName:name_];
8030
8031 if (package_ != nil) {
8032 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8033 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8034 } // XXX: what now, G?
8035
8036 [table_ reloadData];
8037 }
8038
8039 @end
8040 /* }}} */
8041
8042 /* Installed Controller {{{ */
8043 @interface InstalledController : FilteredPackageListController {
8044 bool sectioned_;
8045 }
8046
8047 - (id) initWithDatabase:(Database *)database;
8048 - (void) queueStatusDidChange;
8049
8050 @end
8051
8052 @implementation InstalledController
8053
8054 - (NSURL *) referrerURL {
8055 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8056 }
8057
8058 - (NSURL *) navigationURL {
8059 return [NSURL URLWithString:@"cydia://installed"];
8060 }
8061
8062 - (void) useRecent {
8063 sectioned_ = false;
8064
8065 @synchronized (self) {
8066 [self setFilter:[](Package *package) {
8067 return ![package uninstalled] && package->role_ < 7;
8068 }];
8069
8070 [self setSorter:[](NSMutableArray *packages) {
8071 [packages radixSortUsingSelector:@selector(recent)];
8072 }];
8073 } }
8074
8075 - (void) useFilter:(UISegmentedControl *)segmented {
8076 NSInteger selected([segmented selectedSegmentIndex]);
8077 if (selected == 2)
8078 return [self useRecent];
8079 bool simple(selected == 0);
8080 sectioned_ = true;
8081
8082 @synchronized (self) {
8083 [self setFilter:[=](Package *package) {
8084 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8085 }];
8086
8087 [self setSorter:nullptr];
8088 } }
8089
8090 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8091 if (sectioned_)
8092 return [super sectionsForPackages:packages];
8093
8094 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8095
8096 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8097 Section *section(nil);
8098 time_t last(0);
8099
8100 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8101 Package *package([packages objectAtIndex:offset]);
8102
8103 time_t upgraded([package upgraded]);
8104 if (upgraded < 1168364520)
8105 upgraded = 0;
8106 else
8107 upgraded -= upgraded % (60 * 60 * 24);
8108
8109 if (section == nil || upgraded != last) {
8110 last = upgraded;
8111
8112 NSString *name;
8113 if (upgraded == 0)
8114 continue; // XXX: name = UCLocalize("...");
8115 else {
8116 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8117 [name autorelease];
8118 }
8119
8120 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8121 [sections addObject:section];
8122 }
8123
8124 [section addToCount];
8125 }
8126
8127 CFRelease(formatter);
8128 return sections;
8129 }
8130
8131 - (id) initWithDatabase:(Database *)database {
8132 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8133 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8134 [segmented setSelectedSegmentIndex:0];
8135 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8136 [[self navigationItem] setTitleView:segmented];
8137
8138 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8139 [self useFilter:segmented];
8140
8141 [self queueStatusDidChange];
8142 } return self;
8143 }
8144
8145 #if !AlwaysReload
8146 - (void) queueButtonClicked {
8147 [delegate_ queue];
8148 }
8149 #endif
8150
8151 - (void) queueStatusDidChange {
8152 #if !AlwaysReload
8153 if (Queuing_) {
8154 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8155 initWithTitle:UCLocalize("QUEUE")
8156 style:UIBarButtonItemStyleDone
8157 target:self
8158 action:@selector(queueButtonClicked)
8159 ] autorelease]];
8160 } else {
8161 [[self navigationItem] setRightBarButtonItem:nil];
8162 }
8163 #endif
8164 }
8165
8166 - (void) modeChanged:(UISegmentedControl *)segmented {
8167 [self useFilter:segmented];
8168 [self reloadData];
8169 }
8170
8171 @end
8172 /* }}} */
8173
8174 /* Source Cell {{{ */
8175 @interface SourceCell : CyteTableViewCell <
8176 CyteTableViewCellDelegate,
8177 SourceDelegate
8178 > {
8179 _H<Source, 1> source_;
8180 _H<NSURL> url_;
8181 _H<UIImage> icon_;
8182 _H<NSString> origin_;
8183 _H<NSString> label_;
8184 _H<UIActivityIndicatorView> indicator_;
8185 }
8186
8187 - (void) setSource:(Source *)source;
8188 - (void) setFetch:(NSNumber *)fetch;
8189
8190 @end
8191
8192 @implementation SourceCell
8193
8194 - (void) _setImage:(NSArray *)data {
8195 if ([url_ isEqual:[data objectAtIndex:0]]) {
8196 icon_ = [data objectAtIndex:1];
8197 [content_ setNeedsDisplay];
8198 }
8199 }
8200
8201 - (void) _setSource:(NSURL *) url {
8202 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8203
8204 if (NSData *data = [NSURLConnection
8205 sendSynchronousRequest:[NSURLRequest
8206 requestWithURL:url
8207 cachePolicy:NSURLRequestUseProtocolCachePolicy
8208 timeoutInterval:10
8209 ]
8210
8211 returningResponse:NULL
8212 error:NULL
8213 ])
8214 if (UIImage *image = [UIImage imageWithData:data])
8215 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8216
8217 [pool release];
8218 }
8219
8220 - (void) setSource:(Source *)source {
8221 source_ = source;
8222 [source_ setDelegate:self];
8223
8224 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8225
8226 icon_ = [UIImage imageNamed:@"unknown.png"];
8227
8228 origin_ = [source name];
8229 label_ = [source rooturi];
8230
8231 [content_ setNeedsDisplay];
8232
8233 url_ = [source iconURL];
8234 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8235 }
8236
8237 - (void) setAllSource {
8238 source_ = nil;
8239 [indicator_ stopAnimating];
8240
8241 icon_ = [UIImage imageNamed:@"folder.png"];
8242 origin_ = UCLocalize("ALL_SOURCES");
8243 label_ = UCLocalize("ALL_SOURCES_EX");
8244 [content_ setNeedsDisplay];
8245 }
8246
8247 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8248 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8249 UIView *content([self contentView]);
8250 CGRect bounds([content bounds]);
8251
8252 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8253 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8254 [content_ setBackgroundColor:[UIColor whiteColor]];
8255 [content addSubview:content_];
8256
8257 [content_ setDelegate:self];
8258 [content_ setOpaque:YES];
8259
8260 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8261 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8262 [content addSubview:indicator_];
8263
8264 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8265 } return self;
8266 }
8267
8268 - (void) layoutSubviews {
8269 [super layoutSubviews];
8270
8271 UIView *content([self contentView]);
8272 CGRect bounds([content bounds]);
8273
8274 CGRect frame([indicator_ frame]);
8275 frame.origin.x = bounds.size.width - frame.size.width;
8276 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8277
8278 if (kCFCoreFoundationVersionNumber < 800)
8279 frame.origin.x -= 8;
8280 [indicator_ setFrame:frame];
8281 }
8282
8283 - (NSString *) accessibilityLabel {
8284 return origin_;
8285 }
8286
8287 - (void) drawContentRect:(CGRect)rect {
8288 bool highlighted(highlighted_);
8289 float width(rect.size.width);
8290
8291 if (icon_ != nil) {
8292 CGRect rect;
8293 rect.size = [(UIImage *) icon_ size];
8294
8295 while (rect.size.width > 32 || rect.size.height > 32) {
8296 rect.size.width /= 2;
8297 rect.size.height /= 2;
8298 }
8299
8300 rect.origin.x = 26 - rect.size.width / 2;
8301 rect.origin.y = 26 - rect.size.height / 2;
8302
8303 [icon_ drawInRect:Retina(rect)];
8304 }
8305
8306 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8307 UISetColor(White_);
8308
8309 if (!highlighted)
8310 UISetColor(Black_);
8311 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8312
8313 if (!highlighted)
8314 UISetColor(Gray_);
8315 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8316 }
8317
8318 - (void) setFetch:(NSNumber *)fetch {
8319 if ([fetch boolValue])
8320 [indicator_ startAnimating];
8321 else
8322 [indicator_ stopAnimating];
8323 }
8324
8325 @end
8326 /* }}} */
8327 /* Sources Controller {{{ */
8328 @interface SourcesController : CyteViewController <
8329 UITableViewDataSource,
8330 UITableViewDelegate
8331 > {
8332 _transient Database *database_;
8333 unsigned era_;
8334
8335 _H<UITableView, 2> list_;
8336 _H<NSMutableArray> sources_;
8337 int offset_;
8338
8339 _H<NSString> href_;
8340 _H<UIProgressHUD> hud_;
8341 _H<NSError> error_;
8342
8343 NSURLConnection *trivial_bz2_;
8344 NSURLConnection *trivial_gz_;
8345
8346 BOOL cydia_;
8347 }
8348
8349 - (id) initWithDatabase:(Database *)database;
8350 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8351
8352 @end
8353
8354 @implementation SourcesController
8355
8356 - (void) _releaseConnection:(NSURLConnection *)connection {
8357 if (connection != nil) {
8358 [connection cancel];
8359 //[connection setDelegate:nil];
8360 [connection release];
8361 }
8362 }
8363
8364 - (void) dealloc {
8365 [self _releaseConnection:trivial_gz_];
8366 [self _releaseConnection:trivial_bz2_];
8367
8368 [super dealloc];
8369 }
8370
8371 - (NSURL *) navigationURL {
8372 return [NSURL URLWithString:@"cydia://sources"];
8373 }
8374
8375 - (void) viewDidAppear:(BOOL)animated {
8376 [super viewDidAppear:animated];
8377 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8378 }
8379
8380 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8381 return 2;
8382 }
8383
8384 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8385 if (section == 1)
8386 return UCLocalize("INDIVIDUAL_SOURCES");
8387 return nil;
8388 }
8389
8390 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8391 switch (section) {
8392 case 0: return 1;
8393 case 1: return [sources_ count];
8394 default: return 0;
8395 }
8396 }
8397
8398 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8399 @synchronized (database_) {
8400 if ([database_ era] != era_)
8401 return nil;
8402 if ([indexPath section] != 1)
8403 return nil;
8404 NSUInteger index([indexPath row]);
8405 if (index >= [sources_ count])
8406 return nil;
8407 return [sources_ objectAtIndex:index];
8408 } }
8409
8410 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8411 static NSString *cellIdentifier = @"SourceCell";
8412
8413 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8414 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8415 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8416
8417 Source *source([self sourceAtIndexPath:indexPath]);
8418 if (source == nil)
8419 [cell setAllSource];
8420 else
8421 [cell setSource:source];
8422
8423 return cell;
8424 }
8425
8426 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8427 SectionsController *controller([[[SectionsController alloc]
8428 initWithDatabase:database_
8429 source:[self sourceAtIndexPath:indexPath]
8430 ] autorelease]);
8431
8432 [controller setDelegate:delegate_];
8433 [[self navigationController] pushViewController:controller animated:YES];
8434 }
8435
8436 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8437 if ([indexPath section] != 1)
8438 return false;
8439 Source *source = [self sourceAtIndexPath:indexPath];
8440 return [source record] != nil;
8441 }
8442
8443 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8444 _assert([indexPath section] == 1);
8445 if (editingStyle == UITableViewCellEditingStyleDelete) {
8446 Source *source = [self sourceAtIndexPath:indexPath];
8447 if (source == nil) return;
8448
8449 [Sources_ removeObjectForKey:[source key]];
8450 Changed_ = true;
8451
8452 [delegate_ _saveConfig];
8453 [delegate_ reloadDataWithInvocation:nil];
8454 }
8455 }
8456
8457 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8458 [self updateButtonsForEditingStatusAnimated:YES];
8459 }
8460
8461 - (void) complete {
8462 [delegate_ addTrivialSource:href_];
8463 href_ = nil;
8464
8465 [delegate_ syncData];
8466 }
8467
8468 - (NSString *) getWarning {
8469 NSString *href(href_);
8470 NSRange colon([href rangeOfString:@"://"]);
8471 if (colon.location != NSNotFound)
8472 href = [href substringFromIndex:(colon.location + 3)];
8473 href = [href stringByAddingPercentEscapes];
8474 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8475
8476 NSURL *url([NSURL URLWithString:href]);
8477
8478 NSStringEncoding encoding;
8479 NSError *error(nil);
8480
8481 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8482 return [warning length] == 0 ? nil : warning;
8483 return nil;
8484 }
8485
8486 - (void) _endConnection:(NSURLConnection *)connection {
8487 // XXX: the memory management in this method is horribly awkward
8488
8489 NSURLConnection **field = NULL;
8490 if (connection == trivial_bz2_)
8491 field = &trivial_bz2_;
8492 else if (connection == trivial_gz_)
8493 field = &trivial_gz_;
8494 _assert(field != NULL);
8495 [connection release];
8496 *field = nil;
8497
8498 if (
8499 trivial_bz2_ == nil &&
8500 trivial_gz_ == nil
8501 ) {
8502 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8503
8504 [delegate_ releaseNetworkActivityIndicator];
8505
8506 [delegate_ removeProgressHUD:hud_];
8507 hud_ = nil;
8508
8509 if (cydia_) {
8510 if (warning != nil) {
8511 UIAlertView *alert = [[[UIAlertView alloc]
8512 initWithTitle:UCLocalize("SOURCE_WARNING")
8513 message:warning
8514 delegate:self
8515 cancelButtonTitle:UCLocalize("CANCEL")
8516 otherButtonTitles:
8517 UCLocalize("ADD_ANYWAY"),
8518 nil
8519 ] autorelease];
8520
8521 [alert setContext:@"warning"];
8522 [alert setNumberOfRows:1];
8523 [alert show];
8524
8525 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8526 error_ = nil;
8527 return;
8528 }
8529
8530 [self complete];
8531 } else if (error_ != nil) {
8532 UIAlertView *alert = [[[UIAlertView alloc]
8533 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8534 message:[error_ localizedDescription]
8535 delegate:self
8536 cancelButtonTitle:UCLocalize("OK")
8537 otherButtonTitles:nil
8538 ] autorelease];
8539
8540 [alert setContext:@"urlerror"];
8541 [alert show];
8542
8543 href_ = nil;
8544 } else {
8545 UIAlertView *alert = [[[UIAlertView alloc]
8546 initWithTitle:UCLocalize("NOT_REPOSITORY")
8547 message:UCLocalize("NOT_REPOSITORY_EX")
8548 delegate:self
8549 cancelButtonTitle:UCLocalize("OK")
8550 otherButtonTitles:nil
8551 ] autorelease];
8552
8553 [alert setContext:@"trivial"];
8554 [alert show];
8555
8556 href_ = nil;
8557 }
8558
8559 error_ = nil;
8560 }
8561 }
8562
8563 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8564 switch ([response statusCode]) {
8565 case 200:
8566 cydia_ = YES;
8567 }
8568 }
8569
8570 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8571 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8572 error_ = error;
8573 [self _endConnection:connection];
8574 }
8575
8576 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8577 [self _endConnection:connection];
8578 }
8579
8580 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8581 NSURL *url([NSURL URLWithString:href]);
8582
8583 NSMutableURLRequest *request = [NSMutableURLRequest
8584 requestWithURL:url
8585 cachePolicy:NSURLRequestUseProtocolCachePolicy
8586 timeoutInterval:10
8587 ];
8588
8589 [request setHTTPMethod:method];
8590
8591 if (Machine_ != NULL)
8592 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8593
8594 if (UniqueID_ != nil)
8595 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8596
8597 if ([url isCydiaSecure]) {
8598 if (UniqueID_ != nil)
8599 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8600 }
8601
8602 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8603 }
8604
8605 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8606 NSString *context([alert context]);
8607
8608 if ([context isEqualToString:@"source"]) {
8609 switch (button) {
8610 case 1: {
8611 NSString *href = [[alert textField] text];
8612
8613 static Pcre href_r("^http(s?)://[^# ]*$");
8614 if (!href_r(href)) {
8615 UIAlertView *alert = [[[UIAlertView alloc]
8616 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8617 message:UCLocalize("INVALID_URL_EX")
8618 delegate:self
8619 cancelButtonTitle:UCLocalize("OK")
8620 otherButtonTitles:nil
8621 ] autorelease];
8622
8623 [alert setContext:@"badurl"];
8624 [alert show];
8625
8626 break;
8627 }
8628
8629 if (![href hasSuffix:@"/"])
8630 href_ = [href stringByAppendingString:@"/"];
8631 else
8632 href_ = href;
8633
8634 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8635 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8636
8637 cydia_ = false;
8638
8639 // XXX: this is stupid
8640 hud_ = [delegate_ addProgressHUD];
8641 [hud_ setText:UCLocalize("VERIFYING_URL")];
8642 [delegate_ retainNetworkActivityIndicator];
8643 } break;
8644
8645 case 0:
8646 break;
8647
8648 _nodefault
8649 }
8650
8651 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8652 } else if ([context isEqualToString:@"trivial"])
8653 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8654 else if ([context isEqualToString:@"urlerror"])
8655 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8656 else if ([context isEqualToString:@"warning"]) {
8657 switch (button) {
8658 case 1:
8659 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8660 break;
8661
8662 case 0:
8663 break;
8664
8665 _nodefault
8666 }
8667
8668 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8669 }
8670 }
8671
8672 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8673 BOOL editing([list_ isEditing]);
8674
8675 if (editing)
8676 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8677 initWithTitle:UCLocalize("ADD")
8678 style:UIBarButtonItemStylePlain
8679 target:self
8680 action:@selector(addButtonClicked)
8681 ] autorelease] animated:animated];
8682 else if ([delegate_ updating])
8683 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8684 initWithTitle:UCLocalize("CANCEL")
8685 style:UIBarButtonItemStyleDone
8686 target:self
8687 action:@selector(cancelButtonClicked)
8688 ] autorelease] animated:animated];
8689 else
8690 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8691 initWithTitle:UCLocalize("REFRESH")
8692 style:UIBarButtonItemStylePlain
8693 target:self
8694 action:@selector(refreshButtonClicked)
8695 ] autorelease] animated:animated];
8696
8697 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8698 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8699 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8700 target:self
8701 action:@selector(editButtonClicked)
8702 ] autorelease] animated:animated];
8703 }
8704
8705 - (void) loadView {
8706 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8707 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8708 [list_ setRowHeight:53];
8709 [(UITableView *) list_ setDataSource:self];
8710 [list_ setDelegate:self];
8711 [self setView:list_];
8712 }
8713
8714 - (void) viewDidLoad {
8715 [super viewDidLoad];
8716
8717 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8718 [self updateButtonsForEditingStatusAnimated:NO];
8719 }
8720
8721 - (void) viewWillAppear:(BOOL)animated {
8722 [super viewWillAppear:animated];
8723
8724 [list_ setEditing:NO];
8725 [self updateButtonsForEditingStatusAnimated:NO];
8726 }
8727
8728 - (void) releaseSubviews {
8729 list_ = nil;
8730
8731 sources_ = nil;
8732
8733 [super releaseSubviews];
8734 }
8735
8736 - (id) initWithDatabase:(Database *)database {
8737 if ((self = [super init]) != nil) {
8738 database_ = database;
8739 } return self;
8740 }
8741
8742 - (void) reloadData {
8743 [super reloadData];
8744 [self updateButtonsForEditingStatusAnimated:YES];
8745
8746 @synchronized (database_) {
8747 era_ = [database_ era];
8748
8749 sources_ = [NSMutableArray arrayWithCapacity:16];
8750 [sources_ addObjectsFromArray:[database_ sources]];
8751 _trace();
8752 [sources_ sortUsingSelector:@selector(compareByName:)];
8753 _trace();
8754
8755 int count([sources_ count]);
8756 offset_ = 0;
8757 for (int i = 0; i != count; i++) {
8758 if ([[sources_ objectAtIndex:i] record] == nil)
8759 break;
8760 offset_++;
8761 }
8762
8763 [list_ reloadData];
8764 } }
8765
8766 - (void) showAddSourcePrompt {
8767 UIAlertView *alert = [[[UIAlertView alloc]
8768 initWithTitle:UCLocalize("ENTER_APT_URL")
8769 message:nil
8770 delegate:self
8771 cancelButtonTitle:UCLocalize("CANCEL")
8772 otherButtonTitles:
8773 UCLocalize("ADD_SOURCE"),
8774 nil
8775 ] autorelease];
8776
8777 [alert setContext:@"source"];
8778
8779 [alert setNumberOfRows:1];
8780 [alert addTextFieldWithValue:@"http://" label:@""];
8781
8782 UITextInputTraits *traits = [[alert textField] textInputTraits];
8783 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8784 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8785 [traits setKeyboardType:UIKeyboardTypeURL];
8786 // XXX: UIReturnKeyDone
8787 [traits setReturnKeyType:UIReturnKeyNext];
8788
8789 [alert show];
8790 }
8791
8792 - (void) addButtonClicked {
8793 [self showAddSourcePrompt];
8794 }
8795
8796 - (void) refreshButtonClicked {
8797 if ([delegate_ requestUpdate])
8798 [self updateButtonsForEditingStatusAnimated:YES];
8799 }
8800
8801 - (void) cancelButtonClicked {
8802 [delegate_ cancelUpdate];
8803 }
8804
8805 - (void) editButtonClicked {
8806 [list_ setEditing:![list_ isEditing] animated:YES];
8807 [self updateButtonsForEditingStatusAnimated:YES];
8808 }
8809
8810 @end
8811 /* }}} */
8812
8813 /* Stash Controller {{{ */
8814 @interface StashController : CyteViewController {
8815 _H<UIActivityIndicatorView> spinner_;
8816 _H<UILabel> status_;
8817 _H<UILabel> caption_;
8818 }
8819
8820 @end
8821
8822 @implementation StashController
8823
8824 - (void) loadView {
8825 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8826 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8827 [self setView:view];
8828
8829 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8830
8831 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8832 CGRect spinrect = [spinner_ frame];
8833 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8834 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8835 [spinner_ setFrame:spinrect];
8836 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8837 [view addSubview:spinner_];
8838 [spinner_ startAnimating];
8839
8840 CGRect captrect;
8841 captrect.size.width = [[self view] frame].size.width;
8842 captrect.size.height = 40.0f;
8843 captrect.origin.x = 0;
8844 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8845 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8846 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8847 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8848 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8849 [caption_ setTextColor:[UIColor whiteColor]];
8850 [caption_ setBackgroundColor:[UIColor clearColor]];
8851 [caption_ setShadowColor:[UIColor blackColor]];
8852 [caption_ setTextAlignment:NSTextAlignmentCenter];
8853 [view addSubview:caption_];
8854
8855 CGRect statusrect;
8856 statusrect.size.width = [[self view] frame].size.width;
8857 statusrect.size.height = 30.0f;
8858 statusrect.origin.x = 0;
8859 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8860 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8861 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8862 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8863 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8864 [status_ setTextColor:[UIColor whiteColor]];
8865 [status_ setBackgroundColor:[UIColor clearColor]];
8866 [status_ setShadowColor:[UIColor blackColor]];
8867 [status_ setTextAlignment:NSTextAlignmentCenter];
8868 [view addSubview:status_];
8869 }
8870
8871 - (void) releaseSubviews {
8872 spinner_ = nil;
8873 status_ = nil;
8874 caption_ = nil;
8875
8876 [super releaseSubviews];
8877 }
8878
8879 @end
8880 /* }}} */
8881
8882 @interface CYURLCache : SDURLCache {
8883 }
8884
8885 @end
8886
8887 @implementation CYURLCache
8888
8889 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8890 #if !ForRelease
8891 if (false);
8892 else if ([event isEqualToString:@"no-cache"])
8893 event = @"!!!";
8894 else if ([event isEqualToString:@"store"])
8895 event = @">>>";
8896 else if ([event isEqualToString:@"invalid"])
8897 event = @"???";
8898 else if ([event isEqualToString:@"memory"])
8899 event = @"mem";
8900 else if ([event isEqualToString:@"disk"])
8901 event = @"ssd";
8902 else if ([event isEqualToString:@"miss"])
8903 event = @"---";
8904
8905 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8906 #endif
8907 }
8908
8909 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8910 if (NSURLResponse *response = [cached response])
8911 if (NSString *mime = [response MIMEType])
8912 if ([mime isEqualToString:@"text/cache-manifest"]) {
8913 NSURL *url([response URL]);
8914
8915 #if !ForRelease
8916 NSLog(@"###: %@", [url absoluteString]);
8917 #endif
8918
8919 @synchronized (HostConfig_) {
8920 [CachedURLs_ addObject:url];
8921 }
8922 }
8923
8924 [super storeCachedResponse:cached forRequest:request];
8925 }
8926
8927 - (void) createDiskCachePath {
8928 [super createDiskCachePath];
8929 _root(chown([[self diskCachePath] UTF8String], 501, 501));
8930 }
8931
8932 @end
8933
8934 @interface Cydia : UIApplication <
8935 ConfirmationControllerDelegate,
8936 DatabaseDelegate,
8937 CydiaDelegate
8938 > {
8939 _H<UIWindow> window_;
8940 _H<CydiaTabBarController> tabbar_;
8941 _H<CyteTabBarController> emulated_;
8942 _H<AppCacheController> appcache_;
8943
8944 _H<NSMutableArray> essential_;
8945 _H<NSMutableArray> broken_;
8946
8947 Database *database_;
8948
8949 _H<NSURL> starturl_;
8950
8951 unsigned locked_;
8952 unsigned activity_;
8953
8954 _H<StashController> stash_;
8955
8956 bool loaded_;
8957 }
8958
8959 - (void) loadData;
8960
8961 @end
8962
8963 @implementation Cydia
8964
8965 - (void) lockSuspend {
8966 if (locked_++ == 0) {
8967 if ($SBSSetInterceptsMenuButtonForever != NULL)
8968 (*$SBSSetInterceptsMenuButtonForever)(true);
8969
8970 [self setIdleTimerDisabled:YES];
8971 }
8972 }
8973
8974 - (void) unlockSuspend {
8975 if (--locked_ == 0) {
8976 [self setIdleTimerDisabled:NO];
8977
8978 if ($SBSSetInterceptsMenuButtonForever != NULL)
8979 (*$SBSSetInterceptsMenuButtonForever)(false);
8980 }
8981 }
8982
8983 - (void) beginUpdate {
8984 [tabbar_ beginUpdate];
8985 }
8986
8987 - (void) cancelUpdate {
8988 [tabbar_ cancelUpdate];
8989 }
8990
8991 - (bool) requestUpdate {
8992 if (IsReachable("cydia.saurik.com")) {
8993 [self beginUpdate];
8994 return true;
8995 } else {
8996 UIAlertView *alert = [[[UIAlertView alloc]
8997 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8998 message:@"Host Unreachable" // XXX: Localize
8999 delegate:self
9000 cancelButtonTitle:UCLocalize("OK")
9001 otherButtonTitles:nil
9002 ] autorelease];
9003
9004 [alert setContext:@"norefresh"];
9005 [alert show];
9006
9007 return false;
9008 }
9009 }
9010
9011 - (BOOL) updating {
9012 return [tabbar_ updating];
9013 }
9014
9015 - (void) _loaded {
9016 if ([broken_ count] != 0) {
9017 int count = [broken_ count];
9018
9019 UIAlertView *alert = [[[UIAlertView alloc]
9020 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9021 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9022 delegate:self
9023 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9024 otherButtonTitles:
9025 UCLocalize("TEMPORARY_IGNORE"),
9026 nil
9027 ] autorelease];
9028
9029 [alert setContext:@"fixhalf"];
9030 [alert setNumberOfRows:2];
9031 [alert show];
9032 } else if (!Ignored_ && [essential_ count] != 0) {
9033 int count = [essential_ count];
9034
9035 UIAlertView *alert = [[[UIAlertView alloc]
9036 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9037 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9038 delegate:self
9039 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9040 otherButtonTitles:
9041 UCLocalize("UPGRADE_ESSENTIAL"),
9042 UCLocalize("COMPLETE_UPGRADE"),
9043 nil
9044 ] autorelease];
9045
9046 [alert setContext:@"upgrade"];
9047 [alert show];
9048 }
9049 }
9050
9051 - (void) returnToCydia {
9052 [self _loaded];
9053 }
9054
9055 - (void) _saveConfig {
9056 @synchronized (database_) {
9057 _trace();
9058 MetaFile_.Sync();
9059 _trace();
9060 }
9061
9062 if (Changed_) {
9063 NSString *error(nil);
9064
9065 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9066 _trace();
9067 NSError *error(nil);
9068 if (!_root([data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error]))
9069 NSLog(@"failure to save metadata data: %@", error);
9070 _trace();
9071
9072 Changed_ = false;
9073 } else {
9074 NSLog(@"failure to serialize metadata: %@", error);
9075 }
9076 }
9077
9078 _root(CydiaWriteSources());
9079 }
9080
9081 // Navigation controller for the queuing badge.
9082 - (UINavigationController *) queueNavigationController {
9083 NSArray *controllers = [tabbar_ viewControllers];
9084 return [controllers objectAtIndex:3];
9085 }
9086
9087 - (void) unloadData {
9088 [tabbar_ unloadData];
9089 }
9090
9091 - (void) _updateData {
9092 [self _saveConfig];
9093 [self unloadData];
9094
9095 UINavigationController *navigation = [self queueNavigationController];
9096
9097 id queuedelegate = nil;
9098 if ([[navigation viewControllers] count] > 0)
9099 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9100
9101 [queuedelegate queueStatusDidChange];
9102 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9103 }
9104
9105 - (void) _refreshIfPossible:(NSDate *)update {
9106 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9107
9108 bool recently = false;
9109 if (update != nil) {
9110 NSTimeInterval interval([update timeIntervalSinceNow]);
9111 if (interval > -(15*60))
9112 recently = true;
9113 }
9114
9115 // Don't automatic refresh if:
9116 // - We already refreshed recently.
9117 // - We already auto-refreshed this launch.
9118 // - Auto-refresh is disabled.
9119 // - Cydia's server is not reachable
9120 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9121 // If we are cancelling, we need to make sure it knows it's already loaded.
9122 loaded_ = true;
9123
9124 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9125 } else {
9126 // We are going to load, so remember that.
9127 loaded_ = true;
9128
9129 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9130 }
9131
9132 [pool release];
9133 }
9134
9135 - (void) refreshIfPossible {
9136 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9137 }
9138
9139 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9140 _profile(reloadDataWithInvocation)
9141 @synchronized (self) {
9142 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9143 if (hud != nil)
9144 [hud setText:UCLocalize("RELOADING_DATA")];
9145
9146 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9147
9148 size_t changes(0);
9149
9150 [essential_ removeAllObjects];
9151 [broken_ removeAllObjects];
9152
9153 _profile(reloadDataWithInvocation$Essential)
9154 NSArray *packages([database_ packages]);
9155 for (Package *package in packages) {
9156 if ([package half])
9157 [broken_ addObject:package];
9158 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9159 if ([package essential] && [package installed] != nil)
9160 [essential_ addObject:package];
9161 ++changes;
9162 }
9163 }
9164 _end
9165
9166 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9167 if (changes != 0) {
9168 _trace();
9169 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9170 [changesItem setBadgeValue:badge];
9171 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9172 [self setApplicationIconBadgeNumber:changes];
9173 } else {
9174 _trace();
9175 [changesItem setBadgeValue:nil];
9176 [changesItem setAnimatedBadge:NO];
9177 [self setApplicationIconBadgeNumber:0];
9178 }
9179
9180 Queuing_ = false;
9181 [self _updateData];
9182
9183 if (hud != nil)
9184 [self removeProgressHUD:hud];
9185 }
9186 _end
9187
9188 PrintTimes();
9189 }
9190
9191 - (void) updateData {
9192 [self _updateData];
9193 }
9194
9195 - (void) updateDataAndLoad {
9196 [self _updateData];
9197 if ([database_ progressDelegate] == nil)
9198 [self _loaded];
9199 }
9200
9201 - (void) update_ {
9202 [database_ update];
9203 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9204 }
9205
9206 - (void) disemulate {
9207 if (emulated_ == nil)
9208 return;
9209
9210 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9211 [window_ setRootViewController:tabbar_];
9212 else {
9213 [window_ addSubview:[tabbar_ view]];
9214 [[emulated_ view] removeFromSuperview];
9215 }
9216
9217 emulated_ = nil;
9218 [window_ setUserInteractionEnabled:YES];
9219 }
9220
9221 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9222 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9223 if (IsWildcat_)
9224 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9225
9226 UIViewController *parent;
9227 if (emulated_ == nil)
9228 parent = tabbar_;
9229 else if (!force)
9230 parent = emulated_;
9231 else {
9232 [self disemulate];
9233 parent = tabbar_;
9234 }
9235
9236 [parent presentModalViewController:navigation animated:YES];
9237 }
9238
9239 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9240 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9241
9242 if (navigation != nil)
9243 [navigation pushViewController:progress animated:YES];
9244 else
9245 [self presentModalViewController:progress force:YES];
9246
9247 [progress invoke:invocation withTitle:title];
9248 return progress;
9249 }
9250
9251 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9252 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9253 }
9254
9255 - (void) repairWithInvocation:(NSInvocation *)invocation {
9256 _trace();
9257 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9258 _trace();
9259 }
9260
9261 - (void) repairWithSelector:(SEL)selector {
9262 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9263 }
9264
9265 - (void) reloadData {
9266 [self reloadDataWithInvocation:nil];
9267 if ([database_ progressDelegate] == nil)
9268 [self _loaded];
9269 }
9270
9271 - (void) syncData {
9272 [self _saveConfig];
9273 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9274 }
9275
9276 - (void) addSource:(NSDictionary *) source {
9277 CydiaAddSource(source);
9278 }
9279
9280 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9281 CydiaAddSource(href, distribution, sections);
9282 }
9283
9284 - (void) addTrivialSource:(NSString *)href {
9285 CydiaAddSource(href, @"./");
9286 }
9287
9288 - (void) updateValues {
9289 Changed_ = true;
9290 }
9291
9292 - (void) resolve {
9293 pkgProblemResolver *resolver = [database_ resolver];
9294
9295 resolver->InstallProtect();
9296 if (!resolver->Resolve(true))
9297 _error->Discard();
9298 }
9299
9300 - (bool) perform {
9301 // XXX: this is a really crappy way of doing this.
9302 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9303 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9304 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9305 if ([tabbar_ updating])
9306 [tabbar_ cancelUpdate];
9307
9308 if (![database_ prepare])
9309 return false;
9310
9311 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9312 [page setDelegate:self];
9313 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9314
9315 if (IsWildcat_)
9316 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9317 [tabbar_ presentModalViewController:confirm_ animated:YES];
9318
9319 return true;
9320 }
9321
9322 - (void) queue {
9323 @synchronized (self) {
9324 [self perform];
9325 }
9326 }
9327
9328 - (void) clearPackage:(Package *)package {
9329 @synchronized (self) {
9330 [package clear];
9331 [self resolve];
9332 [self perform];
9333 }
9334 }
9335
9336 - (void) installPackages:(NSArray *)packages {
9337 @synchronized (self) {
9338 for (Package *package in packages)
9339 [package install];
9340 [self resolve];
9341 [self perform];
9342 }
9343 }
9344
9345 - (void) installPackage:(Package *)package {
9346 @synchronized (self) {
9347 [package install];
9348 [self resolve];
9349 [self perform];
9350 }
9351 }
9352
9353 - (void) removePackage:(Package *)package {
9354 @synchronized (self) {
9355 [package remove];
9356 [self resolve];
9357 [self perform];
9358 }
9359 }
9360
9361 - (void) distUpgrade {
9362 @synchronized (self) {
9363 if (![database_ upgrade])
9364 return;
9365 [self perform];
9366 }
9367 }
9368
9369 - (void) _uicache {
9370 _trace();
9371
9372 if (UpgradeCydia_ && Finish_ > 0) {
9373 setreugid(0, 0);
9374 system("su -c /usr/bin/uicache mobile");
9375 } else {
9376 system("/usr/bin/uicache");
9377 }
9378
9379 _trace();
9380 }
9381
9382 - (void) uicache {
9383 UIProgressHUD *hud([self addProgressHUD]);
9384 [hud setText:UCLocalize("LOADING")];
9385 [self yieldToSelector:@selector(_uicache)];
9386 [self removeProgressHUD:hud];
9387 }
9388
9389 - (void) perform_ {
9390 [database_ perform];
9391 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9392 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9393 }
9394
9395 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9396 Queuing_ = false;
9397 [self lockSuspend];
9398 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9399 [self unlockSuspend];
9400 }
9401
9402 - (void) retainNetworkActivityIndicator {
9403 if (activity_++ == 0)
9404 [self setNetworkActivityIndicatorVisible:YES];
9405
9406 #if TraceLogging
9407 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9408 #endif
9409 }
9410
9411 - (void) releaseNetworkActivityIndicator {
9412 if (--activity_ == 0)
9413 [self setNetworkActivityIndicatorVisible:NO];
9414
9415 #if TraceLogging
9416 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9417 #endif
9418
9419 }
9420
9421 - (void) cancelAndClear:(bool)clear {
9422 @synchronized (self) {
9423 if (clear) {
9424 [database_ clear];
9425 Queuing_ = false;
9426 } else {
9427 Queuing_ = true;
9428 }
9429
9430 [self _updateData];
9431 }
9432 }
9433
9434 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9435 NSString *context([alert context]);
9436
9437 if ([context isEqualToString:@"conffile"]) {
9438 FILE *input = [database_ input];
9439 if (button == [alert cancelButtonIndex])
9440 fprintf(input, "N\n");
9441 else if (button == [alert firstOtherButtonIndex])
9442 fprintf(input, "Y\n");
9443 fflush(input);
9444
9445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9446 } else if ([context isEqualToString:@"fixhalf"]) {
9447 if (button == [alert cancelButtonIndex]) {
9448 @synchronized (self) {
9449 for (Package *broken in (id) broken_) {
9450 [broken remove];
9451 NSString *id = [broken id];
9452
9453 _root({
9454 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9455 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9456 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9457 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9458 });
9459 }
9460
9461 [self resolve];
9462 [self perform];
9463 }
9464 } else if (button == [alert firstOtherButtonIndex]) {
9465 [broken_ removeAllObjects];
9466 [self _loaded];
9467 }
9468
9469 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9470 } else if ([context isEqualToString:@"upgrade"]) {
9471 if (button == [alert firstOtherButtonIndex]) {
9472 @synchronized (self) {
9473 for (Package *essential in (id) essential_)
9474 [essential install];
9475
9476 [self resolve];
9477 [self perform];
9478 }
9479 } else if (button == [alert firstOtherButtonIndex] + 1) {
9480 [self distUpgrade];
9481 } else if (button == [alert cancelButtonIndex]) {
9482 Ignored_ = YES;
9483 }
9484
9485 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9486 }
9487 }
9488
9489 - (void) system:(NSString *)command {
9490 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9491
9492 _trace();
9493 _root(system([command UTF8String]));
9494 _trace();
9495
9496 [pool release];
9497 }
9498
9499 - (void) applicationWillSuspend {
9500 [database_ clean];
9501 [super applicationWillSuspend];
9502 }
9503
9504 - (BOOL) isSafeToSuspend {
9505 if (locked_ != 0) {
9506 #if !ForRelease
9507 NSLog(@"isSafeToSuspend: locked_ != 0");
9508 #endif
9509 return false;
9510 }
9511
9512 if ([tabbar_ modalViewController] != nil)
9513 return false;
9514
9515 // Use external process status API internally.
9516 // This is probably a really bad idea.
9517 // XXX: what is the point of this? does this solve anything at all?
9518 uint64_t status = 0;
9519 int notify_token;
9520 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9521 notify_get_state(notify_token, &status);
9522 notify_cancel(notify_token);
9523 }
9524
9525 if (status != 0) {
9526 #if !ForRelease
9527 NSLog(@"isSafeToSuspend: status != 0");
9528 #endif
9529 return false;
9530 }
9531
9532 #if !ForRelease
9533 NSLog(@"isSafeToSuspend: -> true");
9534 #endif
9535 return true;
9536 }
9537
9538 - (void) suspendReturningToLastApp:(BOOL)returning {
9539 if ([self isSafeToSuspend])
9540 [super suspendReturningToLastApp:returning];
9541 }
9542
9543 - (void) suspend {
9544 if ([self isSafeToSuspend])
9545 [super suspend];
9546 }
9547
9548 - (void) applicationSuspend {
9549 if ([self isSafeToSuspend])
9550 [super applicationSuspend];
9551 }
9552
9553 - (void) applicationSuspend:(__GSEvent *)event {
9554 if ([self isSafeToSuspend])
9555 [super applicationSuspend:event];
9556 }
9557
9558 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9559 if ([self isSafeToSuspend])
9560 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9561 }
9562
9563 - (void) _setSuspended:(BOOL)value {
9564 if ([self isSafeToSuspend])
9565 [super _setSuspended:value];
9566 }
9567
9568 - (UIProgressHUD *) addProgressHUD {
9569 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9570 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9571
9572 [window_ setUserInteractionEnabled:NO];
9573
9574 UIViewController *target(tabbar_);
9575 if (UIViewController *modal = [target modalViewController])
9576 target = modal;
9577
9578 [hud showInView:[target view]];
9579
9580 [self lockSuspend];
9581 return hud;
9582 }
9583
9584 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9585 [self unlockSuspend];
9586 [hud hide];
9587 [hud removeFromSuperview];
9588 [window_ setUserInteractionEnabled:YES];
9589 }
9590
9591 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9592 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9593 }
9594
9595 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9596 NSString *scheme([[url scheme] lowercaseString]);
9597 if ([[url absoluteString] length] <= [scheme length] + 3)
9598 return nil;
9599 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9600 NSArray *components([path componentsSeparatedByString:@"/"]);
9601
9602 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9603 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9604 if (controller != nil)
9605 [controller setDelegate:self];
9606 return controller;
9607 }
9608
9609 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9610 return nil;
9611
9612 NSString *base([components objectAtIndex:0]);
9613
9614 CyteViewController *controller = nil;
9615
9616 if ([base isEqualToString:@"url"]) {
9617 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9618 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9619 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9620 } else if (!external && [components count] == 1) {
9621 if ([base isEqualToString:@"sources"]) {
9622 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9623 }
9624
9625 if ([base isEqualToString:@"home"]) {
9626 controller = [[[HomeController alloc] init] autorelease];
9627 }
9628
9629 if ([base isEqualToString:@"sections"]) {
9630 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9631 }
9632
9633 if ([base isEqualToString:@"search"]) {
9634 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9635 }
9636
9637 if ([base isEqualToString:@"changes"]) {
9638 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9639 }
9640
9641 if ([base isEqualToString:@"installed"]) {
9642 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9643 }
9644 } else if ([components count] == 2) {
9645 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9646
9647 if ([base isEqualToString:@"package"]) {
9648 controller = [self pageForPackage:argument withReferrer:referrer];
9649 }
9650
9651 if (!external && [base isEqualToString:@"search"]) {
9652 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9653 }
9654
9655 if (!external && [base isEqualToString:@"sections"]) {
9656 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9657 argument = nil;
9658 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9659 }
9660
9661 if (!external && [base isEqualToString:@"sources"]) {
9662 if ([argument isEqualToString:@"add"]) {
9663 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9664 [(SourcesController *)controller showAddSourcePrompt];
9665 } else {
9666 Source *source([database_ sourceWithKey:argument]);
9667 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9668 }
9669 }
9670
9671 if (!external && [base isEqualToString:@"launch"]) {
9672 [self launchApplicationWithIdentifier:argument suspended:NO];
9673 return nil;
9674 }
9675 } else if (!external && [components count] == 3) {
9676 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9677 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9678
9679 if ([base isEqualToString:@"package"]) {
9680 if ([arg2 isEqualToString:@"settings"]) {
9681 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9682 } else if ([arg2 isEqualToString:@"files"]) {
9683 if (Package *package = [database_ packageWithName:arg1]) {
9684 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9685 [(FileTable *)controller setPackage:package];
9686 }
9687 }
9688 }
9689
9690 if ([base isEqualToString:@"sections"]) {
9691 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9692 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9693 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9694 }
9695 }
9696
9697 [controller setDelegate:self];
9698 return controller;
9699 }
9700
9701 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9702 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9703
9704 if (page != nil)
9705 [tabbar_ setUnselectedViewController:page];
9706
9707 return page != nil;
9708 }
9709
9710 - (void) applicationOpenURL:(NSURL *)url {
9711 [super applicationOpenURL:url];
9712
9713 if (!loaded_)
9714 starturl_ = url;
9715 else
9716 [self openCydiaURL:url forExternal:YES];
9717 }
9718
9719 - (void) applicationWillResignActive:(UIApplication *)application {
9720 // Stop refreshing if you get a phone call or lock the device.
9721 if ([tabbar_ updating])
9722 [tabbar_ cancelUpdate];
9723
9724 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9725 [super applicationWillResignActive:application];
9726 }
9727
9728 - (void) saveState {
9729 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9730 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9731 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9732 Changed_ = true;
9733
9734 [self _saveConfig];
9735 }
9736
9737 - (void) applicationWillTerminate:(UIApplication *)application {
9738 [self saveState];
9739 }
9740
9741 - (void) applicationDidEnterBackground:(UIApplication *)application {
9742 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9743 return [self terminateWithSuccess];
9744 [self saveState];
9745 }
9746
9747 - (void) applicationWillEnterForeground:(UIApplication *)application {
9748 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9749 if (closed == nil)
9750 return;
9751
9752 NSTimeInterval interval([closed timeIntervalSinceNow]);
9753
9754 if (interval <= -(30)) {
9755 [tabbar_ setSelectedIndex:0];
9756 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9757 }
9758
9759 if (interval <= -(15)) {
9760 if (IsReachable("cydia.saurik.com")) {
9761 [tabbar_ beginUpdate];
9762 [appcache_ reloadURLWithCache:YES];
9763 }
9764 }
9765 }
9766
9767 - (void) setConfigurationData:(NSString *)data {
9768 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9769
9770 if (!conffile_r(data)) {
9771 lprintf("E:invalid conffile\n");
9772 return;
9773 }
9774
9775 NSString *ofile = conffile_r[1];
9776 //NSString *nfile = conffile_r[2];
9777
9778 UIAlertView *alert = [[[UIAlertView alloc]
9779 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9780 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9781 delegate:self
9782 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9783 otherButtonTitles:
9784 UCLocalize("ACCEPT_NEW_COPY"),
9785 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9786 nil
9787 ] autorelease];
9788
9789 [alert setContext:@"conffile"];
9790 [alert setNumberOfRows:2];
9791 [alert show];
9792 }
9793
9794 - (void) addStashController {
9795 [self lockSuspend];
9796 stash_ = [[[StashController alloc] init] autorelease];
9797 [window_ addSubview:[stash_ view]];
9798 }
9799
9800 - (void) removeStashController {
9801 [[stash_ view] removeFromSuperview];
9802 stash_ = nil;
9803 [self unlockSuspend];
9804 }
9805
9806 - (void) stash {
9807 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9808 UpdateExternalStatus(1);
9809 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9810 UpdateExternalStatus(0);
9811
9812 [self removeStashController];
9813
9814 pid_t pid(ExecFork());
9815 if (pid == 0) {
9816 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9817 perror("launchctl stop");
9818
9819 exit(0);
9820 } ReapZombie(pid);
9821 }
9822
9823 - (void) setupViewControllers {
9824 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9825
9826 NSMutableArray *items;
9827 if (kCFCoreFoundationVersionNumber < 800) {
9828 items = [NSMutableArray arrayWithObjects:
9829 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9830 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9831 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9832 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9833 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9834 nil];
9835 } else {
9836 items = [NSMutableArray arrayWithObjects:
9837 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9838 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9839 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9840 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9841 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9842 nil];
9843 }
9844
9845 NSMutableArray *controllers([NSMutableArray array]);
9846 for (UITabBarItem *item in items) {
9847 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9848 [controller setTabBarItem:item];
9849 [controllers addObject:controller];
9850 }
9851 [tabbar_ setViewControllers:controllers];
9852
9853 [tabbar_ setUpdateDelegate:self];
9854 }
9855
9856 - (void) _sendMemoryWarningNotification {
9857 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9858 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9859 else
9860 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9861 }
9862
9863 - (void) _sendMemoryWarningNotifications {
9864 while (true) {
9865 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9866 sleep(2);
9867 //usleep(2000000);
9868 }
9869 }
9870
9871 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9872 NSLog(@"--");
9873 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9874 }
9875
9876 - (void) applicationDidFinishLaunching:(id)unused {
9877 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9878
9879 _trace();
9880 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9881 [self setApplicationSupportsShakeToEdit:NO];
9882
9883 @synchronized (HostConfig_) {
9884 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9885 }
9886
9887 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9888 initWithMemoryCapacity:524288
9889 diskCapacity:10485760
9890 diskPath:Cache("SDURLCache")
9891 ] autorelease]];
9892
9893 [CydiaWebViewController _initialize];
9894
9895 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9896
9897 // this would disallow http{,s} URLs from accessing this data
9898 //[WebView registerURLSchemeAsLocal:@"cydia"];
9899
9900 Font12_ = [UIFont systemFontOfSize:12];
9901 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9902 Font14_ = [UIFont systemFontOfSize:14];
9903 Font18_ = [UIFont systemFontOfSize:18];
9904 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9905 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9906
9907 essential_ = [NSMutableArray arrayWithCapacity:4];
9908 broken_ = [NSMutableArray arrayWithCapacity:4];
9909
9910 // XXX: I really need this thing... like, seriously... I'm sorry
9911 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9912 [appcache_ reloadData];
9913
9914 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9915 [window_ orderFront:self];
9916 [window_ makeKey:self];
9917 [window_ setHidden:NO];
9918
9919 if (false) stash: {
9920 [self addStashController];
9921 // XXX: this would be much cleaner as a yieldToSelector:
9922 // that way the removeStashController could happen right here inline
9923 // we also could no longer require the useless stash_ field anymore
9924 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9925 return;
9926 }
9927
9928 struct stat root;
9929 int error(stat("/", &root));
9930 _assert(error != -1);
9931
9932 #define Stash_(path) do { \
9933 struct stat folder; \
9934 int error(lstat((path), &folder)); \
9935 if (error != -1 && ( \
9936 folder.st_dev == root.st_dev && \
9937 S_ISDIR(folder.st_mode) \
9938 ) || error == -1 && ( \
9939 errno == ENOENT || \
9940 errno == ENOTDIR \
9941 )) goto stash; \
9942 } while (false)
9943
9944 Stash_("/Applications");
9945 Stash_("/Library/Ringtones");
9946 Stash_("/Library/Wallpaper");
9947 //Stash_("/usr/bin");
9948 Stash_("/usr/include");
9949 Stash_("/usr/lib/pam");
9950 Stash_("/usr/share");
9951 //Stash_("/var/lib");
9952
9953 database_ = [Database sharedInstance];
9954 [database_ setDelegate:self];
9955
9956 [window_ setUserInteractionEnabled:NO];
9957 [self setupViewControllers];
9958
9959 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9960 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9961 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9962
9963 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9964 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9965 [emulated_ setSelectedIndex:0];
9966
9967 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9968 [emulated_ concealTabBarSelection];
9969
9970 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9971 [window_ setRootViewController:emulated_];
9972 else
9973 [window_ addSubview:[emulated_ view]];
9974
9975 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9976 _trace();
9977 }
9978
9979 - (NSArray *) defaultStartPages {
9980 NSMutableArray *standard = [NSMutableArray array];
9981 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9982 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9983 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9984 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9985 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9986 return standard;
9987 }
9988
9989 - (void) loadData {
9990 _trace();
9991 if ([emulated_ modalViewController] != nil)
9992 [emulated_ dismissModalViewControllerAnimated:YES];
9993 [window_ setUserInteractionEnabled:NO];
9994
9995 [self reloadDataWithInvocation:nil];
9996 [self refreshIfPossible];
9997 [self disemulate];
9998
9999 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10000 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10001 int standardIndex = 0;
10002 NSArray *standard = [self defaultStartPages];
10003
10004 BOOL valid = YES;
10005
10006 if (saved == nil)
10007 valid = NO;
10008
10009 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10010 if (valid && closed != nil) {
10011 NSTimeInterval interval([closed timeIntervalSinceNow]);
10012 if (interval <= -(30*60))
10013 valid = NO;
10014 }
10015
10016 if (valid && [saved count] != [standard count])
10017 valid = NO;
10018
10019 if (valid) {
10020 for (unsigned int i = 0; i < [standard count]; i++) {
10021 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10022 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10023 // but it's good enough for now.
10024 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10025 valid = NO;
10026 break;
10027 }
10028 }
10029 }
10030
10031 NSArray *items = nil;
10032 if (valid) {
10033 [tabbar_ setSelectedIndex:savedIndex];
10034 items = saved;
10035 } else {
10036 [tabbar_ setSelectedIndex:standardIndex];
10037 items = standard;
10038 }
10039
10040 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10041 NSArray *stack = [items objectAtIndex:tab];
10042 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10043 NSMutableArray *current = [NSMutableArray array];
10044
10045 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10046 NSString *addr = [stack objectAtIndex:nav];
10047 NSURL *url = [NSURL URLWithString:addr];
10048 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10049 if (page != nil)
10050 [current addObject:page];
10051 }
10052
10053 [navigation setViewControllers:current];
10054 }
10055
10056 // (Try to) show the startup URL.
10057 if (starturl_ != nil) {
10058 [self openCydiaURL:starturl_ forExternal:YES];
10059 starturl_ = nil;
10060 }
10061 }
10062
10063 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10064 if (item != nil && IsWildcat_) {
10065 [sheet showFromBarButtonItem:item animated:YES];
10066 } else {
10067 [sheet showInView:window_];
10068 }
10069 }
10070
10071 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10072 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10073 [progress setTitle:task];
10074 [progress addProgressEvent:event];
10075 }
10076
10077 - (void) addProgressEventForTask:(NSArray *)data {
10078 CydiaProgressEvent *event([data objectAtIndex:0]);
10079 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10080 [self addProgressEvent:event forTask:task];
10081 }
10082
10083 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10084 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10085 }
10086
10087 @end
10088
10089 /*IMP alloc_;
10090 id Alloc_(id self, SEL selector) {
10091 id object = alloc_(self, selector);
10092 lprintf("[%s]A-%p\n", self->isa->name, object);
10093 return object;
10094 }*/
10095
10096 /*IMP dealloc_;
10097 id Dealloc_(id self, SEL selector) {
10098 id object = dealloc_(self, selector);
10099 lprintf("[%s]D-%p\n", self->isa->name, object);
10100 return object;
10101 }*/
10102
10103 Class $NSURLConnection;
10104
10105 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10106 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10107
10108 NSURL *url([copy URL]);
10109
10110 NSString *host([url host]);
10111 NSString *scheme([[url scheme] lowercaseString]);
10112
10113 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10114
10115 @synchronized (HostConfig_) {
10116 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10117 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10118 [copy setHTTPShouldUsePipelining:YES];
10119
10120 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10121 if ([control isEqualToString:@"max-age=0"])
10122 if ([CachedURLs_ containsObject:url]) {
10123 #if !ForRelease
10124 NSLog(@"~~~: %@", url);
10125 #endif
10126
10127 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10128
10129 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10130 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10131 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10132 }
10133 }
10134
10135 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10136 } return self;
10137 }
10138
10139 Class $WAKWindow;
10140
10141 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10142 CGSize size([[UIScreen mainScreen] bounds].size);
10143 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10144 if ([$WAKWindow hasLandscapeOrientation])
10145 std::swap(size.width, size.height);*/
10146 return size;
10147 }
10148
10149 Class $NSUserDefaults;
10150
10151 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10152 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10153 return Cache("LocalStorage");
10154 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10155 }
10156
10157 int main(int argc, char *argv[]) {
10158 setreugid(501, 501);
10159
10160 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10161
10162 _trace();
10163
10164 UpdateExternalStatus(0);
10165
10166 UIScreen *screen([UIScreen mainScreen]);
10167 if ([screen respondsToSelector:@selector(scale)])
10168 ScreenScale_ = [screen scale];
10169 else
10170 ScreenScale_ = 1;
10171
10172 UIDevice *device([UIDevice currentDevice]);
10173 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10174 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10175 if (idiom == UIUserInterfaceIdiomPad)
10176 IsWildcat_ = true;
10177 }
10178
10179 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10180
10181 Pcre pattern("^([0-9]+\\.[0-9]+)");
10182
10183 if (pattern([device systemVersion]))
10184 Firmware_ = pattern[1];
10185 if (pattern(Cydia_))
10186 Major_ = pattern[1];
10187
10188 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10189
10190 HostConfig_ = [[[NSObject alloc] init] autorelease];
10191 @synchronized (HostConfig_) {
10192 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10193 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10194 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10195 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10196 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10197 }
10198
10199 NSString *ui(@"ui/ios");
10200 if (Idiom_ != nil)
10201 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10202 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10203 UI_ = CydiaURL(ui);
10204
10205 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10206
10207 /* Library Hacks {{{ */
10208 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10209
10210 $WAKWindow = objc_getClass("WAKWindow");
10211 if ($WAKWindow != NULL)
10212 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10213 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10214
10215 $NSURLConnection = objc_getClass("NSURLConnection");
10216 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10217 if (NSURLConnection$init$ != NULL) {
10218 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10219 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10220 }
10221
10222 $NSUserDefaults = objc_getClass("NSUserDefaults");
10223 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10224 if (NSUserDefaults$objectForKey$ != NULL) {
10225 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10226 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10227 }
10228 /* }}} */
10229 /* Set Locale {{{ */
10230 Locale_ = CFLocaleCopyCurrent();
10231 Languages_ = [NSLocale preferredLanguages];
10232
10233 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10234 //NSLog(@"%@", [Languages_ description]);
10235
10236 const char *lang;
10237 if (Locale_ != NULL)
10238 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10239 else if (Languages_ != nil && [Languages_ count] != 0)
10240 lang = [[Languages_ objectAtIndex:0] UTF8String];
10241 else
10242 // XXX: consider just setting to C and then falling through?
10243 lang = NULL;
10244
10245 if (lang != NULL) {
10246 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10247 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10248 }
10249
10250 NSLog(@"Setting Language: %s", lang);
10251
10252 if (lang != NULL) {
10253 setenv("LANG", lang, true);
10254 std::setlocale(LC_ALL, lang);
10255 }
10256 /* }}} */
10257 /* Index Collation {{{ */
10258 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10259 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10260 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10261 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10262 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10263 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10264
10265 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10266
10267 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10268 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10269 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})
10270 CollationOffset_.push_back(offset);
10271 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];
10272 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];
10273 } else {
10274
10275 CollationThumbs_ = [collation sectionIndexTitles];
10276 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10277 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10278
10279 CollationTitles_ = [collation sectionTitles];
10280 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10281
10282 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10283 if (&transform != NULL && transform != nil) {
10284 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10285 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10286 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10287 UErrorCode code(U_ZERO_ERROR);
10288 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10289 if (!U_SUCCESS(code))
10290 NSLog(@"%s", u_errorName(code));
10291 }
10292
10293 }
10294 } @catch (NSException *e) {
10295 NSLog(@"%@", e);
10296 goto hard;
10297 } } else hard: {
10298 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10299
10300 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];
10301 for (NSInteger offset(0); offset != 28; ++offset)
10302 CollationOffset_.push_back(offset);
10303
10304 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];
10305 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];
10306 }
10307 /* }}} */
10308
10309 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10310
10311 /* Parse Arguments {{{ */
10312 bool substrate(false);
10313
10314 if (argc != 0) {
10315 char **args(argv);
10316 int arge(1);
10317
10318 for (int argi(1); argi != argc; ++argi)
10319 if (strcmp(argv[argi], "--") == 0) {
10320 arge = argi;
10321 argv[argi] = argv[0];
10322 argv += argi;
10323 argc -= argi;
10324 break;
10325 }
10326
10327 for (int argi(1); argi != arge; ++argi)
10328 if (strcmp(args[argi], "--substrate") == 0)
10329 substrate = true;
10330 else
10331 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10332 }
10333 /* }}} */
10334
10335 App_ = [[NSBundle mainBundle] bundlePath];
10336 Advanced_ = YES;
10337
10338 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10339
10340 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10341 alloc_ = alloc->method_imp;
10342 alloc->method_imp = (IMP) &Alloc_;*/
10343
10344 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10345 dealloc_ = dealloc->method_imp;
10346 dealloc->method_imp = (IMP) &Dealloc_;*/
10347
10348 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10349 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10350
10351 /* System Information {{{ */
10352 size_t size;
10353
10354 int maxproc;
10355 size = sizeof(maxproc);
10356 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10357 perror("sysctlbyname(\"kern.maxproc\", ?)");
10358 else if (maxproc < 64) {
10359 maxproc = 64;
10360 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10361 perror("sysctlbyname(\"kern.maxproc\", #)");
10362 }
10363
10364 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10365 char *osversion = new char[size];
10366 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10367 perror("sysctlbyname(\"kern.osversion\", ?)");
10368 else
10369 System_ = [NSString stringWithUTF8String:osversion];
10370
10371 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10372 char *machine = new char[size];
10373 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10374 perror("sysctlbyname(\"hw.machine\", ?)");
10375 else
10376 Machine_ = machine;
10377
10378 int64_t usermem(0);
10379 size = sizeof(usermem);
10380 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10381 usermem = 0;
10382
10383 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10384 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10385 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10386
10387 UniqueID_ = UniqueIdentifier(device);
10388
10389 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10390 Product_ = [info objectForKey:@"SafariProductVersion"];
10391 Safari_ = [info objectForKey:@"CFBundleVersion"];
10392 }
10393
10394 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10395
10396 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10397 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10398 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10399 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10400 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10401 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10402
10403 UserAgent_ = agent;
10404 /* }}} */
10405 /* Load Database {{{ */
10406 _trace();
10407 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10408 _trace();
10409 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10410
10411 if (Metadata_ == NULL)
10412 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10413 else {
10414 Settings_ = [Metadata_ objectForKey:@"Settings"];
10415
10416 Packages_ = [Metadata_ objectForKey:@"Packages"];
10417
10418 Values_ = [Metadata_ objectForKey:@"Values"];
10419 Sections_ = [Metadata_ objectForKey:@"Sections"];
10420 Sources_ = [Metadata_ objectForKey:@"Sources"];
10421
10422 Token_ = [Metadata_ objectForKey:@"Token"];
10423
10424 Version_ = [Metadata_ objectForKey:@"Version"];
10425 }
10426
10427 if (Values_ == nil) {
10428 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10429 [Metadata_ setObject:Values_ forKey:@"Values"];
10430 }
10431
10432 if (Sections_ == nil) {
10433 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10434 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10435 }
10436
10437 if (Sources_ == nil) {
10438 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10439 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10440 }
10441
10442 if (Version_ == nil) {
10443 Version_ = [NSNumber numberWithUnsignedInt:0];
10444 [Metadata_ setObject:Version_ forKey:@"Version"];
10445 }
10446
10447 if ([Version_ unsignedIntValue] == 0) {
10448 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10449 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10450 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10451 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10452
10453 Version_ = [NSNumber numberWithUnsignedInt:1];
10454 [Metadata_ setObject:Version_ forKey:@"Version"];
10455
10456 [Metadata_ removeObjectForKey:@"LastUpdate"];
10457
10458 Changed_ = true;
10459 }
10460
10461 _H<NSMutableArray> broken([NSMutableArray array]);
10462 for (NSString *key in (id) Sources_)
10463 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10464 [broken addObject:key];
10465 if ([broken count] != 0) {
10466 for (NSString *key in (id) broken)
10467 [Sources_ removeObjectForKey:key];
10468 Changed_ = true;
10469 } broken = nil;
10470 /* }}} */
10471
10472 _root(CydiaWriteSources());
10473
10474 _trace();
10475 MetaFile_.Open([Cache("metadata.cb0") UTF8String]);
10476 _trace();
10477
10478 if (Packages_ != nil) {
10479 bool fail(false);
10480 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10481 _trace();
10482
10483 if (!fail) {
10484 [Metadata_ removeObjectForKey:@"Packages"];
10485 Packages_ = nil;
10486 Changed_ = true;
10487 }
10488 }
10489
10490 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10491
10492 #define MobileSubstrate_(name) \
10493 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10494 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10495 if (handle == NULL) \
10496 NSLog(@"%s", dlerror()); \
10497 }
10498
10499 MobileSubstrate_(Activator)
10500 MobileSubstrate_(libstatusbar)
10501 MobileSubstrate_(SimulatedKeyEvents)
10502 MobileSubstrate_(WinterBoard)
10503
10504 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10505 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10506
10507 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10508
10509 if (access("/User", F_OK) != 0 || version != 6) {
10510 _trace();
10511 _root(system("/usr/libexec/cydia/firmware.sh"));
10512 _trace();
10513 }
10514
10515 if (access("/tmp/cydia.chk", F_OK) == 0) {
10516 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10517 _assert(errno == ENOENT);
10518 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10519 _assert(errno == ENOENT);
10520 }
10521
10522 /* APT Initialization {{{ */
10523 _assert(pkgInitConfig(*_config));
10524 _assert(pkgInitSystem(*_config, _system));
10525
10526 if (lang != NULL)
10527 _config->Set("APT::Acquire::Translation", lang);
10528
10529 // XXX: this timeout might be important :(
10530 //_config->Set("Acquire::http::Timeout", 15);
10531
10532 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10533
10534 mkdir([Cache_ UTF8String], 0755);
10535 mkdir([Cache("archives") UTF8String], 0755);
10536 mkdir([Cache("archives/partial") UTF8String], 0755);
10537 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10538
10539 mkdir([Cache("lists") UTF8String], 0755);
10540 mkdir([Cache("lists/partial") UTF8String], 0755);
10541 mkdir([Cache("periodic") UTF8String], 0755);
10542 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10543 /* }}} */
10544 /* Color Choices {{{ */
10545 space_ = CGColorSpaceCreateDeviceRGB();
10546
10547 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10548 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10549 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10550 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10551 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10552 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10553 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10554 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10555 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10556 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10557
10558 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10559 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10560 /* }}}*/
10561 /* UIKit Configuration {{{ */
10562 // XXX: I have a feeling this was important
10563 //UIKeyboardDisableAutomaticAppearance();
10564 /* }}} */
10565
10566 _root({
10567 chown([Cache("ApplicationCache.db") UTF8String], 501, 501);
10568 chown([Cache("Cache.db") UTF8String], 501, 501);
10569 chown([Cache("Cache.db-shm") UTF8String], 501, 501);
10570 chown([Cache("Cache.db-wal") UTF8String], 501, 501);
10571 });
10572
10573 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10574
10575 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10576 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10577 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10578
10579 PulseInterval_ = fast ? 50000 : 500000;
10580
10581 Colon_ = UCLocalize("COLON_DELIMITED");
10582 Elision_ = UCLocalize("ELISION");
10583 Error_ = UCLocalize("ERROR");
10584 Warning_ = UCLocalize("WARNING");
10585
10586 _trace();
10587 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10588
10589 CGColorSpaceRelease(space_);
10590 CFRelease(Locale_);
10591
10592 [pool release];
10593 return value;
10594 }