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