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