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