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