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