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