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