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