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