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