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