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