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