1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
126 #include <CydiaSubstrate/CydiaSubstrate.h>
127 #include "Menes/Menes.h"
129 #include "CyteKit/PerlCompatibleRegEx.hpp"
130 #include "CyteKit/TableViewCell.h"
131 #include "CyteKit/WebScriptObject-Cyte.h"
132 #include "CyteKit/WebViewController.h"
133 #include "CyteKit/stringWithUTF8Bytes.h"
135 #include "Cydia/MIMEAddress.h"
136 #include "Cydia/LoadingViewController.h"
137 #include "Cydia/ProgressEvent.h"
139 #include "SDURLCache/SDURLCache.h"
146 #define _timestamp ({ \
148 gettimeofday(&tv, NULL); \
149 tv.tv_sec * 1000000 + tv.tv_usec; \
152 typedef std::vector<class ProfileTime *> TimeList;
162 ProfileTime(const char *name) :
166 times_.push_back(this);
169 void AddTime(uint64_t time) {
176 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
188 ProfileTimer(ProfileTime &time) :
195 time_.AddTime(_timestamp - start_);
200 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
202 std::cerr << "========" << std::endl;
205 #define _profile(name) { \
206 static ProfileTime name(#name); \
207 ProfileTimer _ ## name(name);
212 extern NSString *Cydia_;
214 #define lprintf(args...) fprintf(stderr, args)
217 #define TraceLogging (1 && !ForRelease)
218 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
219 #define ProfileTimes (0 && !ForRelease)
220 #define ForSaurik (0 && !ForRelease)
221 #define LogBrowser (0 && !ForRelease)
222 #define TrackResize (0 && !ForRelease)
223 #define ManualRefresh (1 && !ForRelease)
224 #define ShowInternals (0 && !ForRelease)
225 #define AlwaysReload (0 && !ForRelease)
226 #define TryIndexedCollation (0 && !ForRelease)
230 #define _trace(args...)
235 #define _profile(name) {
238 #define PrintTimes() do {} while (false)
241 // Hash Functions/Structures {{{
242 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
250 static NSString *Colon_;
252 static NSString *Error_;
253 static NSString *Warning_;
255 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
257 static _finline NSString *CydiaURL(NSString *path) {
259 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
260 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
261 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
262 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
263 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
265 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
268 static void ReapZombie(pid_t pid) {
271 if (waitpid(pid, &status, 0) == -1)
277 static _finline void UpdateExternalStatus(uint64_t newStatus) {
279 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
280 notify_set_state(notify_token, newStatus);
281 notify_cancel(notify_token);
283 notify_post("com.saurik.Cydia.status");
286 static CGFloat CYStatusBarHeight() {
287 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
288 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
291 /* NSForcedOrderingSearch doesn't work on the iPhone */
292 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
293 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
294 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
296 /* Insertion Sort {{{ */
298 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
299 const char *ptr = (const char *)list;
301 CFIndex half = count / 2;
302 const char *probe = ptr + elementSize * half;
303 CFComparisonResult cr = comparator(element, probe, context);
304 if (0 == cr) return (probe - (const char *)list) / elementSize;
305 ptr = (cr < 0) ? ptr : probe + elementSize;
306 count = (cr < 0) ? half : (half + (count & 1) - 1);
308 return (ptr - (const char *)list) / elementSize;
311 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
312 const char *ptr = (const char *)list;
314 CFIndex half = count / 2;
315 const char *probe = ptr + elementSize * half;
316 CFComparisonResult cr = comparator(element, probe, context);
317 if (0 == cr) return (probe - (const char *)list) / elementSize;
318 ptr = (cr < 0) ? ptr : probe + elementSize;
319 count = (cr < 0) ? half : (half + (count & 1) - 1);
321 return (ptr - (const char *)list) / elementSize;
324 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
325 if (range.length == 0)
327 const void **values(new const void *[range.length]);
328 CFArrayGetValues(array, range, values);
330 #if HistogramInsertionSort > 0
331 uint32_t total(0), *offsets(new uint32_t[range.length]);
334 for (CFIndex index(1); index != range.length; ++index) {
335 const void *value(values[index]);
336 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
337 CFIndex correct(index);
338 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
339 #if HistogramInsertionSort > 1
340 NSLog(@"%@ < %@", value, values[correct - 1]);
345 if (correct != index) {
346 size_t offset(index - correct);
347 #if HistogramInsertionSort
351 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
353 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
354 values[correct] = value;
358 CFArrayReplaceValues(array, range, values, range.length);
361 #if HistogramInsertionSort > 0
362 for (CFIndex index(0); index != range.length; ++index)
363 if (offsets[index] != 0)
364 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
365 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
372 /* Apple Bug Fixes {{{ */
373 @implementation UIWebDocumentView (Cydia)
375 - (void) _setScrollerOffset:(CGPoint)offset {
376 UIScroller *scroller([self _scroller]);
378 CGSize size([scroller contentSize]);
379 CGSize bounds([scroller bounds].size);
382 max.x = size.width - bounds.width;
383 max.y = size.height - bounds.height;
391 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
392 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
394 [scroller setOffset:offset];
400 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
401 size_t length([self length] - state->state);
404 else if (length > count)
406 for (size_t i(0); i != length; ++i)
407 objects[i] = [self item:state->state++];
408 state->itemsPtr = objects;
409 state->mutationsPtr = (unsigned long *) self;
413 /* Cydia NSString Additions {{{ */
414 @interface NSString (Cydia)
415 - (NSComparisonResult) compareByPath:(NSString *)other;
416 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
419 @implementation NSString (Cydia)
421 - (NSComparisonResult) compareByPath:(NSString *)other {
422 NSString *prefix = [self commonPrefixWithString:other options:0];
423 size_t length = [prefix length];
425 NSRange lrange = NSMakeRange(length, [self length] - length);
426 NSRange rrange = NSMakeRange(length, [other length] - length);
428 lrange = [self rangeOfString:@"/" options:0 range:lrange];
429 rrange = [other rangeOfString:@"/" options:0 range:rrange];
431 NSComparisonResult value;
433 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
434 value = NSOrderedSame;
435 else if (lrange.location == NSNotFound)
436 value = NSOrderedAscending;
437 else if (rrange.location == NSNotFound)
438 value = NSOrderedDescending;
440 value = NSOrderedSame;
442 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
443 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
444 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
445 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
447 NSComparisonResult result = [lpath compare:rpath];
448 return result == NSOrderedSame ? value : result;
451 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
452 return [(id)CFURLCreateStringByAddingPercentEscapes(
457 kCFStringEncodingUTF8
464 /* C++ NSString Wrapper Cache {{{ */
465 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
466 return size == 0 ? NULL :
467 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
468 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
471 static _finline CFStringRef CYStringCreate(const char *data) {
472 return CYStringCreate(data, strlen(data));
481 _finline void clear_() {
482 if (cache_ != NULL) {
489 _finline bool empty() const {
493 _finline size_t size() const {
497 _finline char *data() const {
501 _finline void clear() {
506 _finline CYString() :
513 _finline ~CYString() {
517 void operator =(const CYString &rhs) {
521 if (rhs.cache_ == nil)
524 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
527 void copy(apr_pool_t *pool) {
528 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
529 memcpy(temp, data_, size_);
534 void set(apr_pool_t *pool, const char *data, size_t size) {
540 data_ = const_cast<char *>(data);
548 _finline void set(apr_pool_t *pool, const char *data) {
549 set(pool, data, data == NULL ? 0 : strlen(data));
552 _finline void set(apr_pool_t *pool, const std::string &rhs) {
553 set(pool, rhs.data(), rhs.size());
556 bool operator ==(const CYString &rhs) const {
557 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
560 _finline operator CFStringRef() {
562 cache_ = CYStringCreate(data_, size_);
566 _finline operator id() {
567 return (NSString *) static_cast<CFStringRef>(*this);
570 _finline operator const char *() {
571 return reinterpret_cast<const char *>(data_);
575 /* C++ NSString Algorithm Adapters {{{ */
577 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
580 struct NSStringMapHash :
581 std::unary_function<NSString *, size_t>
583 _finline size_t operator ()(NSString *value) const {
584 return CFStringHashNSString((CFStringRef) value);
588 struct NSStringMapLess :
589 std::binary_function<NSString *, NSString *, bool>
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return [lhs compare:rhs] == NSOrderedAscending;
596 struct NSStringMapEqual :
597 std::binary_function<NSString *, NSString *, bool>
599 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
600 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
601 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
602 //[lhs isEqualToString:rhs];
607 /* CoreGraphics Primitives {{{ */
612 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
613 CGFloat color[] = {red, green, blue, alpha};
614 return CGColorCreate(space, color);
623 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
624 color_(Create_(space, red, green, blue, alpha))
626 Set(space, red, green, blue, alpha);
631 CGColorRelease(color_);
638 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
640 color_ = Create_(space, red, green, blue, alpha);
643 operator CGColorRef() {
649 /* Random Global Variables {{{ */
650 static const int PulseInterval_ = 50000;
652 static const NSString *UI_;
655 static bool RestartSubstrate_;
656 static NSArray *Finishes_;
658 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
659 #define NotifyConfig_ "/etc/notify.conf"
661 static bool Queuing_;
663 static CYColor Blue_;
664 static CYColor Blueish_;
665 static CYColor Black_;
667 static CYColor White_;
668 static CYColor Gray_;
669 static CYColor Green_;
670 static CYColor Purple_;
671 static CYColor Purplish_;
673 static UIColor *InstallingColor_;
674 static UIColor *RemovingColor_;
676 static NSString *App_;
678 static BOOL Advanced_;
679 static BOOL Ignored_;
681 static _H<UIFont> Font12_;
682 static _H<UIFont> Font12Bold_;
683 static _H<UIFont> Font14_;
684 static _H<UIFont> Font18Bold_;
685 static _H<UIFont> Font22Bold_;
687 static const char *Machine_ = NULL;
688 static NSString *System_ = nil;
689 static NSString *SerialNumber_ = nil;
690 static NSString *ChipID_ = nil;
691 static NSString *BBSNum_ = nil;
692 static _H<NSString> Token_;
693 static NSString *UniqueID_ = nil;
694 static NSString *Build_ = nil;
695 static NSString *Product_ = nil;
696 static NSString *Safari_ = nil;
698 static CFLocaleRef Locale_;
699 static NSArray *Languages_;
700 static CGColorSpaceRef space_;
702 static NSDictionary *SectionMap_;
703 static NSMutableDictionary *Metadata_;
704 static _transient NSMutableDictionary *Settings_;
705 static _transient NSString *Role_;
706 static _transient NSMutableDictionary *Packages_;
707 static _transient NSMutableDictionary *Values_;
708 static _transient NSMutableDictionary *Sections_;
709 _H<NSMutableDictionary> Sources_;
710 static _transient NSNumber *Version_;
711 _H<NSString> CydiaSource_;
716 static CGFloat ScreenScale_;
717 static NSString *Idiom_;
718 _H<NSString> Firmware_;
719 static NSString *Major_;
721 static _H<NSMutableDictionary> SessionData_;
722 static _H<NSObject> HostConfig_;
723 static _H<NSMutableSet> BridgedHosts_;
724 static _H<NSMutableSet> TokenHosts_;
725 static _H<NSMutableSet> InsecureHosts_;
726 static _H<NSMutableSet> PipelinedHosts_;
727 static _H<NSMutableSet> CachedURLs_;
729 static NSString *kCydiaProgressEventTypeError = @"Error";
730 static NSString *kCydiaProgressEventTypeInformation = @"Information";
731 static NSString *kCydiaProgressEventTypeStatus = @"Status";
732 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
735 /* Display Helpers {{{ */
736 inline float Interpolate(float begin, float end, float fraction) {
737 return (end - begin) * fraction + begin;
740 static _finline const char *StripVersion_(const char *version) {
741 const char *colon(strchr(version, ':'));
742 return colon == NULL ? version : colon + 1;
745 NSString *LocalizeSection(NSString *section) {
746 static Pcre title_r("^(.*?) \\((.*)\\)$");
747 if (title_r(section)) {
748 NSString *parent(title_r[1]);
749 NSString *child(title_r[2]);
751 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
752 LocalizeSection(parent),
753 LocalizeSection(child)
757 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
760 NSString *Simplify(NSString *title) {
761 const char *data = [title UTF8String];
762 size_t size = [title length];
764 static Pcre square_r("^\\[(.*)\\]$");
765 if (square_r(data, size))
766 return Simplify(square_r[1]);
768 static Pcre paren_r("^\\((.*)\\)$");
769 if (paren_r(data, size))
770 return Simplify(paren_r[1]);
772 static Pcre title_r("^(.*?) \\((.*)\\)$");
773 if (title_r(data, size))
774 return Simplify(title_r[1]);
780 NSString *GetLastUpdate() {
781 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
784 return UCLocalize("NEVER_OR_UNKNOWN");
786 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
787 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
789 CFRelease(formatter);
791 return [(NSString *) formatted autorelease];
794 bool isSectionVisible(NSString *section) {
795 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
796 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
797 return hidden == nil || ![hidden boolValue];
800 static NSObject *CYIOGetValue(const char *path, NSString *property) {
801 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
802 if (entry == MACH_PORT_NULL)
805 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
806 IOObjectRelease(entry);
810 return [(id) value autorelease];
813 static NSString *CYHex(NSData *data, bool reverse = false) {
817 size_t length([data length]);
818 uint8_t bytes[length];
819 [data getBytes:bytes];
821 char string[length * 2 + 1];
822 for (size_t i(0); i != length; ++i)
823 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
825 return [NSString stringWithUTF8String:string];
830 /* Delegate Prototypes {{{ */
833 @class CydiaProgressEvent;
835 @protocol DatabaseDelegate
836 - (void) repairWithSelector:(SEL)selector;
837 - (void) setConfigurationData:(NSString *)data;
838 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
841 @class CYPackageController;
843 @protocol CydiaDelegate
844 - (void) returnToCydia;
846 - (void) retainNetworkActivityIndicator;
847 - (void) releaseNetworkActivityIndicator;
848 - (void) clearPackage:(Package *)package;
849 - (void) installPackage:(Package *)package;
850 - (void) installPackages:(NSArray *)packages;
851 - (void) removePackage:(Package *)package;
852 - (void) beginUpdate;
854 - (void) distUpgrade;
858 - (void) addSource:(NSDictionary *)source;
859 - (void) addTrivialSource:(NSString *)href;
860 - (void) showSettings;
861 - (UIProgressHUD *) addProgressHUD;
862 - (void) removeProgressHUD:(UIProgressHUD *)hud;
863 - (CyteViewController *) pageForPackage:(NSString *)name;
864 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
865 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
869 /* Status Delegation {{{ */
871 public pkgAcquireStatus
874 _transient NSObject<ProgressDelegate> *delegate_;
884 void setDelegate(NSObject<ProgressDelegate> *delegate) {
885 delegate_ = delegate;
888 NSObject<ProgressDelegate> *getDelegate() const {
892 virtual bool MediaChange(std::string media, std::string drive) {
896 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
900 virtual void Fetch(pkgAcquire::ItemDesc &item) {
901 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
902 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
903 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
906 virtual void Done(pkgAcquire::ItemDesc &item) {
907 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
908 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
909 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
912 virtual void Fail(pkgAcquire::ItemDesc &item) {
914 item.Owner->Status == pkgAcquire::Item::StatIdle ||
915 item.Owner->Status == pkgAcquire::Item::StatDone
919 std::string &error(item.Owner->ErrorText);
923 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
924 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
927 virtual bool Pulse(pkgAcquire *Owner) {
928 bool value = pkgAcquireStatus::Pulse(Owner);
931 double(CurrentBytes + CurrentItems) /
932 double(TotalBytes + TotalItems)
935 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
936 [NSNumber numberWithDouble:percent], @"Percent",
938 [NSNumber numberWithDouble:CurrentBytes], @"Current",
939 [NSNumber numberWithDouble:TotalBytes], @"Total",
940 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
941 nil] waitUntilDone:YES];
943 if (value && ![delegate_ isProgressCancelled])
951 _finline bool WasCancelled() const {
955 virtual void Start() {
956 pkgAcquireStatus::Start();
957 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
960 virtual void Stop() {
961 pkgAcquireStatus::Stop();
962 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
963 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
967 /* Database Interface {{{ */
968 typedef std::map< unsigned long, _H<Source> > SourceMap;
970 @interface Database : NSObject {
977 pkgDepCache::Policy *policy_;
978 pkgRecords *records_;
979 pkgProblemResolver *resolver_;
980 pkgAcquire *fetcher_;
982 SPtr<pkgPackageManager> manager_;
983 pkgSourceList *list_;
985 SourceMap sourceMap_;
986 _H<NSMutableArray> sourceList_;
988 CFMutableArrayRef packages_;
990 _transient NSObject<DatabaseDelegate> *delegate_;
991 _transient NSObject<ProgressDelegate> *progress_;
999 std::map<const char *, _H<NSString> > sections_;
1002 + (Database *) sharedInstance;
1005 - (void) _readCydia:(NSNumber *)fd;
1006 - (void) _readStatus:(NSNumber *)fd;
1007 - (void) _readOutput:(NSNumber *)fd;
1011 - (Package *) packageWithName:(NSString *)name;
1013 - (pkgCacheFile &) cache;
1014 - (pkgDepCache::Policy *) policy;
1015 - (pkgRecords *) records;
1016 - (pkgProblemResolver *) resolver;
1017 - (pkgAcquire &) fetcher;
1018 - (pkgSourceList &) list;
1019 - (NSArray *) packages;
1020 - (NSArray *) sources;
1021 - (Source *) sourceWithKey:(NSString *)key;
1022 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1030 - (void) updateWithStatus:(Status &)status;
1032 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1034 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1035 - (NSObject<ProgressDelegate> *) progressDelegate;
1037 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1039 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1043 /* ProgressEvent Implementation {{{ */
1044 @implementation CydiaProgressEvent
1046 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1047 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1050 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1051 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1052 [event setPackage:package];
1056 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1057 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1059 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1060 NSArray *fields([description componentsSeparatedByString:@" "]);
1061 [event setItem:fields];
1063 if ([fields count] > 3) {
1064 [event setPackage:[fields objectAtIndex:2]];
1065 [event setVersion:[fields objectAtIndex:3]];
1068 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1073 + (NSArray *) _attributeKeys {
1074 return [NSArray arrayWithObjects:
1084 - (NSArray *) attributeKeys {
1085 return [[self class] _attributeKeys];
1088 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1089 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1092 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1093 if ((self = [super init]) != nil) {
1099 - (NSString *) message {
1103 - (NSString *) type {
1107 - (NSArray *) item {
1108 return (id) item_ ?: [NSNull null];
1111 - (void) setItem:(NSArray *)item {
1115 - (NSString *) package {
1116 return (id) package_ ?: [NSNull null];
1119 - (void) setPackage:(NSString *)package {
1123 - (NSString *) url {
1124 return (id) url_ ?: [NSNull null];
1127 - (void) setURL:(NSString *)url {
1131 - (void) setVersion:(NSString *)version {
1135 - (NSString *) version {
1136 return (id) version_ ?: [NSNull null];
1139 - (NSString *) compound:(NSString *)value {
1141 NSString *mode(nil); {
1142 NSString *type([self type]);
1143 if ([type isEqualToString:kCydiaProgressEventTypeError])
1144 mode = UCLocalize("ERROR");
1145 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1146 mode = UCLocalize("WARNING");
1150 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1156 - (NSString *) compoundMessage {
1157 return [self compound:[self message]];
1160 - (NSString *) compoundTitle {
1163 if (package_ == nil)
1165 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1166 title = [package name];
1170 return [self compound:title];
1176 // Cytore Definitions {{{
1177 struct PackageValue :
1180 Cytore::Offset<PackageValue> next_;
1182 uint32_t index_ : 23;
1183 uint32_t subscribed_ : 1;
1200 Cytore::Offset<PackageValue> packages_[1 << 16];
1203 static Cytore::File<MetaValue> MetaFile_;
1205 // Cytore Helper Functions {{{
1206 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1207 SplitHash nhash = { hashlittle(name, length) };
1209 PackageValue *metadata;
1211 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1212 offset: if (offset->IsNull()) {
1213 *offset = MetaFile_.New<PackageValue>(length + 1);
1214 metadata = &MetaFile_.Get(*offset);
1216 if (metadata == NULL) {
1220 metadata = new PackageValue();
1221 memset(metadata, 0, sizeof(*metadata));
1224 memcpy(metadata->name_, name, length + 1);
1225 metadata->nhash_ = nhash.u16[1];
1227 metadata = &MetaFile_.Get(*offset);
1229 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1230 offset = &metadata->next_;
1238 static void PackageImport(const void *key, const void *value, void *context) {
1239 bool &fail(*reinterpret_cast<bool *>(context));
1242 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1243 NSLog(@"failed to import package %@", key);
1247 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1248 NSDictionary *package((NSDictionary *) value);
1250 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1251 if ([subscribed boolValue] && !metadata->subscribed_)
1252 metadata->subscribed_ = true;
1254 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1255 time_t time([date timeIntervalSince1970]);
1256 if (metadata->first_ > time || metadata->first_ == 0)
1257 metadata->first_ = time;
1260 NSDate *date([package objectForKey:@"LastSeen"]);
1261 NSString *version([package objectForKey:@"LastVersion"]);
1263 if (date != nil && version != nil) {
1264 time_t time([date timeIntervalSince1970]);
1265 if (metadata->last_ < time || metadata->last_ == 0)
1266 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1267 size_t length(strlen(buffer));
1268 uint16_t vhash(hashlittle(buffer, length));
1270 size_t capped(std::min<size_t>(8, length));
1271 char *latest(buffer + length - capped);
1273 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1274 metadata->vhash_ = vhash;
1276 metadata->last_ = time;
1282 /* Source Class {{{ */
1283 @interface Source : NSObject {
1285 Database *database_;
1288 CYString depiction_;
1289 CYString description_;
1295 CYString distribution_;
1301 _H<NSString> authority_;
1303 CYString defaultIcon_;
1305 _H<NSDictionary> record_;
1309 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1311 - (NSComparisonResult) compareByName:(Source *)source;
1313 - (NSString *) depictionForPackage:(NSString *)package;
1314 - (NSString *) supportForPackage:(NSString *)package;
1316 - (NSDictionary *) record;
1319 - (NSString *) rooturi;
1320 - (NSString *) distribution;
1321 - (NSString *) type;
1324 - (NSString *) host;
1326 - (NSString *) name;
1327 - (NSString *) shortDescription;
1328 - (NSString *) label;
1329 - (NSString *) origin;
1330 - (NSString *) version;
1332 - (NSString *) defaultIcon;
1333 - (NSURL *) iconURL;
1337 @implementation Source
1341 distribution_.clear();
1346 description_.clear();
1352 defaultIcon_.clear();
1359 + (NSString *) webScriptNameForSelector:(SEL)selector {
1361 else if (selector == @selector(addSection:))
1362 return @"addSection";
1363 else if (selector == @selector(getField:))
1365 else if (selector == @selector(removeSection:))
1366 return @"removeSection";
1367 else if (selector == @selector(remove))
1373 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1374 return [self webScriptNameForSelector:selector] == nil;
1377 + (NSArray *) _attributeKeys {
1378 return [NSArray arrayWithObjects:
1389 @"shortDescription",
1396 - (NSArray *) attributeKeys {
1397 return [[self class] _attributeKeys];
1400 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1401 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1404 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1407 trusted_ = index->IsTrusted();
1409 uri_.set(pool, index->GetURI());
1410 distribution_.set(pool, index->GetDist());
1411 type_.set(pool, index->GetType());
1413 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1414 if (dindex != NULL) {
1415 base_.set(pool, dindex->MetaIndexURI(""));
1418 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1421 pkgTagFile tags(&fd);
1423 pkgTagSection section;
1430 {"default-icon", &defaultIcon_},
1431 {"depiction", &depiction_},
1432 {"description", &description_},
1434 {"origin", &origin_},
1435 {"support", &support_},
1436 {"version", &version_},
1439 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1440 const char *start, *end;
1442 if (section.Find(names[i].name_, start, end)) {
1443 CYString &value(*names[i].value_);
1444 value.set(pool, start, end - start);
1450 record_ = [Sources_ objectForKey:[self key]];
1452 NSURL *url([NSURL URLWithString:uri_]);
1456 host_ = [host_ lowercaseString];
1461 authority_ = [url path];
1464 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1465 if ((self = [super init]) != nil) {
1466 era_ = [database era];
1467 database_ = database;
1470 [self setMetaIndex:index inPool:pool];
1474 - (NSString *) getField:(NSString *)name {
1475 @synchronized (database_) {
1476 if ([database_ era] != era_ || index_ == NULL)
1479 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1484 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1489 pkgTagFile tags(&fd);
1491 pkgTagSection section;
1494 const char *start, *end;
1495 if (!section.Find([name UTF8String], start, end))
1496 return (NSString *) [NSNull null];
1498 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1501 - (NSComparisonResult) compareByName:(Source *)source {
1502 NSString *lhs = [self name];
1503 NSString *rhs = [source name];
1505 if ([lhs length] != 0 && [rhs length] != 0) {
1506 unichar lhc = [lhs characterAtIndex:0];
1507 unichar rhc = [rhs characterAtIndex:0];
1509 if (isalpha(lhc) && !isalpha(rhc))
1510 return NSOrderedAscending;
1511 else if (!isalpha(lhc) && isalpha(rhc))
1512 return NSOrderedDescending;
1515 return [lhs compare:rhs options:LaxCompareOptions_];
1518 - (NSString *) depictionForPackage:(NSString *)package {
1519 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1522 - (NSString *) supportForPackage:(NSString *)package {
1523 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1526 - (NSArray *) sections {
1527 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1530 - (void) _addSection:(NSString *)section {
1533 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1534 if (![sections containsObject:section]) {
1535 [sections addObject:section];
1539 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1544 - (bool) addSection:(NSString *)section {
1548 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1552 - (void) _removeSection:(NSString *)section {
1556 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1557 if ([sections containsObject:section]) {
1558 [sections removeObject:section];
1563 - (bool) removeSection:(NSString *)section {
1567 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1572 [Sources_ removeObjectForKey:[self key]];
1577 bool value(record_ != nil);
1578 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1582 - (NSDictionary *) record {
1590 - (NSString *) rooturi {
1594 - (NSString *) distribution {
1595 return distribution_;
1598 - (NSString *) type {
1602 - (NSString *) baseuri {
1603 return base_.empty() ? nil : (id) base_;
1606 - (NSString *) iconuri {
1607 if (NSString *base = [self baseuri])
1608 return [base stringByAppendingString:@"CydiaIcon.png"];
1613 - (NSURL *) iconURL {
1614 if (NSString *uri = [self iconuri])
1615 return [NSURL URLWithString:uri];
1619 - (NSString *) key {
1620 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1623 - (NSString *) host {
1627 - (NSString *) name {
1628 return origin_.empty() ? (id) authority_ : origin_;
1631 - (NSString *) shortDescription {
1632 return description_;
1635 - (NSString *) label {
1636 return label_.empty() ? (id) authority_ : label_;
1639 - (NSString *) origin {
1643 - (NSString *) version {
1647 - (NSString *) defaultIcon {
1648 return defaultIcon_;
1653 /* CydiaOperation Class {{{ */
1654 @interface CydiaOperation : NSObject {
1655 _H<NSString> operator_;
1656 _H<NSString> value_;
1659 - (NSString *) operator;
1660 - (NSString *) value;
1664 @implementation CydiaOperation
1666 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1667 if ((self = [super init]) != nil) {
1668 operator_ = [NSString stringWithUTF8String:_operator];
1669 value_ = [NSString stringWithUTF8String:value];
1673 + (NSArray *) _attributeKeys {
1674 return [NSArray arrayWithObjects:
1680 - (NSArray *) attributeKeys {
1681 return [[self class] _attributeKeys];
1684 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1685 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1688 - (NSString *) operator {
1692 - (NSString *) value {
1698 /* CydiaClause Class {{{ */
1699 @interface CydiaClause : NSObject {
1700 _H<NSString> package_;
1701 _H<CydiaOperation> version_;
1704 - (NSString *) package;
1705 - (CydiaOperation *) version;
1709 @implementation CydiaClause
1711 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1712 if ((self = [super init]) != nil) {
1713 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1715 if (const char *version = dep.TargetVer())
1716 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1718 version_ = (id) [NSNull null];
1722 + (NSArray *) _attributeKeys {
1723 return [NSArray arrayWithObjects:
1729 - (NSArray *) attributeKeys {
1730 return [[self class] _attributeKeys];
1733 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1734 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1737 - (NSString *) package {
1741 - (CydiaOperation *) version {
1747 /* CydiaRelation Class {{{ */
1748 @interface CydiaRelation : NSObject {
1749 _H<NSString> relationship_;
1750 _H<NSMutableArray> clauses_;
1753 - (NSString *) relationship;
1754 - (NSArray *) clauses;
1758 @implementation CydiaRelation
1760 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1761 if ((self = [super init]) != nil) {
1762 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1763 clauses_ = [NSMutableArray arrayWithCapacity:8];
1765 pkgCache::DepIterator start;
1766 pkgCache::DepIterator end;
1767 dep.GlobOr(start, end); // ++dep
1770 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1772 // yes, seriously. (wtf?)
1780 + (NSArray *) _attributeKeys {
1781 return [NSArray arrayWithObjects:
1787 - (NSArray *) attributeKeys {
1788 return [[self class] _attributeKeys];
1791 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1792 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1795 - (NSString *) relationship {
1796 return relationship_;
1799 - (NSArray *) clauses {
1803 - (void) addClause:(CydiaClause *)clause {
1804 [clauses_ addObject:clause];
1809 /* Package Class {{{ */
1810 struct ParsedPackage {
1814 CYString architecture_;
1817 CYString depiction_;
1827 @interface Package : NSObject {
1830 uint32_t essential_ : 1;
1831 uint32_t obsolete_ : 1;
1832 uint32_t ignored_ : 1;
1833 uint32_t pooled_ : 1;
1839 _transient Database *database_;
1841 pkgCache::VerIterator version_;
1842 pkgCache::PkgIterator iterator_;
1843 pkgCache::VerFileIterator file_;
1849 CYString installed_;
1851 const char *section_;
1852 _transient NSString *section$_;
1856 PackageValue *metadata_;
1857 ParsedPackage *parsed_;
1859 _H<NSMutableArray> tags_;
1862 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1863 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 - (pkgCache::PkgIterator) iterator;
1868 - (NSString *) section;
1869 - (NSString *) simpleSection;
1871 - (NSString *) longSection;
1872 - (NSString *) shortSection;
1876 - (MIMEAddress *) maintainer;
1878 - (NSString *) longDescription;
1879 - (NSString *) shortDescription;
1882 - (PackageValue *) metadata;
1885 - (bool) subscribed;
1886 - (bool) setSubscribed:(bool)subscribed;
1890 - (NSString *) latest;
1891 - (NSString *) installed;
1892 - (BOOL) uninstalled;
1895 - (BOOL) upgradableAndEssential:(BOOL)essential;
1898 - (BOOL) unfiltered;
1902 - (BOOL) halfConfigured;
1903 - (BOOL) halfInstalled;
1905 - (NSString *) mode;
1908 - (NSString *) name;
1910 - (NSString *) homepage;
1911 - (NSString *) depiction;
1912 - (MIMEAddress *) author;
1914 - (NSString *) support;
1916 - (NSArray *) files;
1917 - (NSArray *) warnings;
1918 - (NSArray *) applications;
1920 - (Source *) source;
1923 - (BOOL) matches:(NSArray *)query;
1925 - (bool) hasSupportingRole;
1926 - (BOOL) hasTag:(NSString *)tag;
1927 - (NSString *) primaryPurpose;
1928 - (NSArray *) purposes;
1929 - (bool) isCommercial;
1931 - (void) setIndex:(size_t)index;
1933 - (CYString &) cyname;
1935 - (uint32_t) compareBySection:(NSArray *)sections;
1940 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1941 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1942 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1943 - (bool) isVisibleInSection:(NSString *)section;
1944 - (bool) isVisibleInSource:(Source *)source;
1948 uint32_t PackageChangesRadix(Package *self, void *) {
1953 uint32_t timestamp : 30;
1954 uint32_t ignored : 1;
1955 uint32_t upgradable : 1;
1959 bool upgradable([self upgradableAndEssential:YES]);
1960 value.bits.upgradable = upgradable ? 1 : 0;
1963 value.bits.timestamp = 0;
1964 value.bits.ignored = [self ignored] ? 0 : 1;
1965 value.bits.upgradable = 1;
1967 value.bits.timestamp = [self seen] >> 2;
1968 value.bits.ignored = 0;
1969 value.bits.upgradable = 0;
1972 return _not(uint32_t) - value.key;
1975 uint32_t PackagePrefixRadix(Package *self, void *context) {
1976 size_t offset(reinterpret_cast<size_t>(context));
1977 CYString &name([self cyname]);
1979 size_t size(name.size());
1982 char *text(name.data());
1985 if (!isdigit(text[0]))
1989 while (size != digits && isdigit(text[digits]))
1997 if (offset == 0 && zeros != 0) {
1998 memset(data, '0', zeros);
1999 memcpy(data + zeros, text, 4 - zeros);
2001 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2002 if (size <= offset - zeros)
2005 text += offset - zeros;
2006 size -= offset - zeros;
2009 memcpy(data, text, 4);
2011 memcpy(data, text, size);
2012 memset(data + size, 0, 4 - size);
2015 for (size_t i(0); i != 4; ++i)
2016 if (isalpha(data[i]))
2024 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2026 /* XXX: ntohl may be more honest */
2027 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2030 CYString &(*PackageName)(Package *self, SEL sel);
2032 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2033 _profile(PackageNameCompare)
2034 CYString &lhi(PackageName(lhs, @selector(cyname)));
2035 CYString &rhi(PackageName(rhs, @selector(cyname)));
2036 CFStringRef lhn(lhi), rhn(rhi);
2039 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2040 else if (rhn == NULL)
2041 return NSOrderedDescending;
2043 _profile(PackageNameCompare$NumbersLast)
2044 if (!lhi.empty() && !rhi.empty()) {
2045 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2046 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2047 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2048 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2049 return lha ? NSOrderedAscending : NSOrderedDescending;
2053 CFIndex length = CFStringGetLength(lhn);
2055 _profile(PackageNameCompare$Compare)
2056 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2061 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2062 return PackageNameCompare(*lhs, *rhs, context);
2065 struct PackageNameOrdering :
2066 std::binary_function<Package *, Package *, bool>
2068 _finline bool operator ()(Package *lhs, Package *rhs) const {
2069 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2073 @implementation Package
2075 - (NSString *) description {
2076 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2081 apr_pool_destroy(pool_);
2082 if (parsed_ != NULL)
2087 + (NSString *) webScriptNameForSelector:(SEL)selector {
2089 else if (selector == @selector(clear))
2091 else if (selector == @selector(getField:))
2093 else if (selector == @selector(hasTag:))
2095 else if (selector == @selector(install))
2097 else if (selector == @selector(remove))
2103 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2104 return [self webScriptNameForSelector:selector] == nil;
2107 + (NSArray *) _attributeKeys {
2108 return [NSArray arrayWithObjects:
2129 @"shortDescription",
2142 - (NSArray *) attributeKeys {
2143 return [[self class] _attributeKeys];
2146 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2147 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2150 - (NSArray *) relations {
2151 @synchronized (database_) {
2152 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2153 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2154 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2158 - (NSString *) architecture {
2160 @synchronized (database_) {
2161 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2164 - (NSString *) getField:(NSString *)name {
2165 @synchronized (database_) {
2166 if ([database_ era] != era_ || file_.end())
2169 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2171 const char *start, *end;
2172 if (!parser.Find([name UTF8String], start, end))
2173 return (NSString *) [NSNull null];
2175 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2179 if (parsed_ != NULL)
2181 @synchronized (database_) {
2182 if ([database_ era] != era_ || file_.end())
2185 ParsedPackage *parsed(new ParsedPackage);
2188 _profile(Package$parse)
2189 pkgRecords::Parser *parser;
2191 _profile(Package$parse$Lookup)
2192 parser = &[database_ records]->Lookup(file_);
2197 _profile(Package$parse$Find)
2202 {"architecture", &parsed->architecture_},
2203 {"icon", &parsed->icon_},
2204 {"depiction", &parsed->depiction_},
2205 {"homepage", &parsed->homepage_},
2206 {"website", &website},
2207 {"bugs", &parsed->bugs_},
2208 {"support", &parsed->support_},
2209 {"sponsor", &parsed->sponsor_},
2210 {"author", &parsed->author_},
2211 {"md5sum", &parsed->md5sum_},
2214 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2215 const char *start, *end;
2217 if (parser->Find(names[i].name_, start, end)) {
2218 CYString &value(*names[i].value_);
2219 _profile(Package$parse$Value)
2220 value.set(pool_, start, end - start);
2226 _profile(Package$parse$Tagline)
2227 const char *start, *end;
2228 if (parser->ShortDesc(start, end)) {
2229 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2232 while (stop != start && stop[-1] == '\r')
2234 parsed->tagline_.set(pool_, start, stop - start);
2238 _profile(Package$parse$Retain)
2239 if (parsed->homepage_.empty())
2240 parsed->homepage_ = website;
2241 if (parsed->homepage_ == parsed->depiction_)
2242 parsed->homepage_.clear();
2247 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2248 if ((self = [super init]) != nil) {
2249 _profile(Package$initWithVersion)
2251 apr_pool_create(&pool_, NULL);
2257 database_ = database;
2258 era_ = [database era];
2262 pkgCache::PkgIterator iterator(version.ParentPkg());
2263 iterator_ = iterator;
2265 _profile(Package$initWithVersion$Version)
2266 if (!version_.end())
2267 file_ = version_.FileList();
2269 pkgCache &cache([database_ cache]);
2270 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2274 _profile(Package$initWithVersion$Cache)
2275 name_.set(NULL, iterator.Display());
2277 latest_.set(NULL, StripVersion_(version_.VerStr()));
2279 pkgCache::VerIterator current(iterator.CurrentVer());
2281 installed_.set(NULL, StripVersion_(current.VerStr()));
2284 _profile(Package$initWithVersion$Tags)
2285 pkgCache::TagIterator tag(iterator.TagList());
2287 tags_ = [NSMutableArray arrayWithCapacity:8];
2289 const char *name(tag.Name());
2290 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2292 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2293 if (strcmp(name + 6, "enduser") == 0)
2295 else if (strcmp(name + 6, "hacker") == 0)
2297 else if (strcmp(name + 6, "developer") == 0)
2299 else if (strcmp(name + 6, "cydia") == 0)
2305 if (strncmp(name, "cydia::", 7) == 0) {
2306 if (strcmp(name + 7, "essential") == 0)
2308 else if (strcmp(name + 7, "obsolete") == 0)
2313 } while (!tag.end());
2317 _profile(Package$initWithVersion$Metadata)
2318 const char *mixed(iterator.Name());
2319 size_t size(strlen(mixed));
2320 char lower[size + 1];
2322 for (size_t i(0); i != size; ++i)
2323 lower[i] = mixed[i] | 0x20;
2326 PackageValue *metadata(PackageFind(lower, size));
2327 metadata_ = metadata;
2329 id_.set(NULL, metadata->name_, size);
2331 const char *latest(version_.VerStr());
2332 size_t length(strlen(latest));
2334 uint16_t vhash(hashlittle(latest, length));
2336 size_t capped(std::min<size_t>(8, length));
2337 latest = latest + length - capped;
2339 if (metadata->first_ == 0)
2340 metadata->first_ = now_;
2342 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2343 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2344 metadata->vhash_ = vhash;
2345 metadata->last_ = now_;
2346 } else if (metadata->last_ == 0)
2347 metadata->last_ = metadata->first_;
2350 _profile(Package$initWithVersion$Section)
2351 section_ = iterator.Section();
2354 _profile(Package$initWithVersion$Flags)
2355 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2356 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2361 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2362 pkgCache::VerIterator version;
2364 _profile(Package$packageWithIterator$GetCandidateVer)
2365 version = [database policy]->GetCandidateVer(iterator);
2373 _profile(Package$packageWithIterator$Allocate)
2374 package = [Package allocWithZone:zone];
2377 _profile(Package$packageWithIterator$Initialize)
2379 initWithVersion:version
2386 _profile(Package$packageWithIterator$Autorelease)
2387 package = [package autorelease];
2393 - (pkgCache::PkgIterator) iterator {
2397 - (NSString *) section {
2398 if (section$_ == nil) {
2399 if (section_ == NULL)
2402 _profile(Package$section$mappedSectionForPointer)
2403 section$_ = [database_ mappedSectionForPointer:section_];
2408 - (NSString *) simpleSection {
2409 if (NSString *section = [self section])
2410 return Simplify(section);
2415 - (NSString *) longSection {
2416 return LocalizeSection([self section]);
2419 - (NSString *) shortSection {
2420 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2423 - (NSString *) uri {
2426 pkgIndexFile *index;
2427 pkgCache::PkgFileIterator file(file_.File());
2428 if (![database_ list].FindIndex(file, index))
2430 return [NSString stringWithUTF8String:iterator_->Path];
2431 //return [NSString stringWithUTF8String:file.Site()];
2432 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2436 - (MIMEAddress *) maintainer {
2437 @synchronized (database_) {
2438 if ([database_ era] != era_ || file_.end())
2441 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2442 const std::string &maintainer(parser->Maintainer());
2443 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2446 - (NSString *) md5sum {
2447 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2451 @synchronized (database_) {
2452 if ([database_ era] != era_ || version_.end())
2455 return version_->InstalledSize;
2458 - (NSString *) longDescription {
2459 @synchronized (database_) {
2460 if ([database_ era] != era_ || file_.end())
2463 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2464 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2466 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2467 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2468 if ([lines count] < 2)
2471 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2472 for (size_t i(1), e([lines count]); i != e; ++i) {
2473 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2474 [trimmed addObject:trim];
2477 return [trimmed componentsJoinedByString:@"\n"];
2480 - (NSString *) shortDescription {
2481 if (parsed_ != NULL)
2482 return static_cast<NSString *>(parsed_->tagline_);
2484 @synchronized (database_) {
2485 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2487 const char *start, *end;
2488 if (!parser.ShortDesc(start, end))
2491 if (end - start > 200)
2495 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2498 while (end != start && end[-1] == '\r')
2502 return [(id) CYStringCreate(start, end - start) autorelease];
2506 _profile(Package$index)
2507 CFStringRef name((CFStringRef) [self name]);
2508 if (CFStringGetLength(name) == 0)
2510 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2511 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2513 return toupper(character);
2517 - (PackageValue *) metadata {
2522 PackageValue *metadata([self metadata]);
2523 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2526 - (bool) subscribed {
2527 return [self metadata]->subscribed_;
2530 - (bool) setSubscribed:(bool)subscribed {
2531 PackageValue *metadata([self metadata]);
2532 if (metadata->subscribed_ == subscribed)
2534 metadata->subscribed_ = subscribed;
2542 - (NSString *) latest {
2546 - (NSString *) installed {
2550 - (BOOL) uninstalled {
2551 return installed_.empty();
2555 return !version_.end();
2558 - (BOOL) upgradableAndEssential:(BOOL)essential {
2559 _profile(Package$upgradableAndEssential)
2560 pkgCache::VerIterator current(iterator_.CurrentVer());
2562 return essential && essential_;
2564 return !version_.end() && version_ != current;
2568 - (BOOL) essential {
2573 return [database_ cache][iterator_].InstBroken();
2576 - (BOOL) unfiltered {
2577 _profile(Package$unfiltered$obsolete)
2578 if (_unlikely(obsolete_))
2582 _profile(Package$unfiltered$hasSupportingRole)
2583 if (_unlikely(![self hasSupportingRole]))
2591 if (![self unfiltered])
2596 _profile(Package$visible$section)
2597 section = [self section];
2600 _profile(Package$visible$isSectionVisible)
2601 if (!isSectionVisible(section))
2609 unsigned char current(iterator_->CurrentState);
2610 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2613 - (BOOL) halfConfigured {
2614 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2617 - (BOOL) halfInstalled {
2618 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2622 @synchronized (database_) {
2623 if ([database_ era] != era_ || iterator_.end())
2626 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2627 return state.Mode != pkgDepCache::ModeKeep;
2630 - (NSString *) mode {
2631 @synchronized (database_) {
2632 if ([database_ era] != era_ || iterator_.end())
2635 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2637 switch (state.Mode) {
2638 case pkgDepCache::ModeDelete:
2639 if ((state.iFlags & pkgDepCache::Purge) != 0)
2643 case pkgDepCache::ModeKeep:
2644 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2645 return @"REINSTALL";
2646 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2650 case pkgDepCache::ModeInstall:
2651 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2652 return @"REINSTALL";
2653 else*/ switch (state.Status) {
2655 return @"DOWNGRADE";
2661 return @"NEW_INSTALL";
2672 - (NSString *) name {
2673 return name_.empty() ? id_ : name_;
2676 - (UIImage *) icon {
2677 NSString *section = [self simpleSection];
2680 if (parsed_ != NULL)
2681 if (NSString *href = parsed_->icon_)
2682 if ([href hasPrefix:@"file:///"])
2683 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2684 if (icon == nil) if (section != nil)
2685 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2686 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2687 if ([dicon hasPrefix:@"file:///"])
2688 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2690 icon = [UIImage applicationImageNamed:@"unknown.png"];
2694 - (NSString *) homepage {
2695 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2698 - (NSString *) depiction {
2699 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2702 - (MIMEAddress *) sponsor {
2703 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2706 - (MIMEAddress *) author {
2707 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2710 - (NSString *) support {
2711 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2714 - (NSArray *) files {
2715 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2716 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2719 fin.open([path UTF8String]);
2724 while (std::getline(fin, line))
2725 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2730 - (NSString *) state {
2731 @synchronized (database_) {
2732 if ([database_ era] != era_ || file_.end())
2735 switch (iterator_->CurrentState) {
2736 case pkgCache::State::NotInstalled:
2737 return @"NotInstalled";
2738 case pkgCache::State::UnPacked:
2740 case pkgCache::State::HalfConfigured:
2741 return @"HalfConfigured";
2742 case pkgCache::State::HalfInstalled:
2743 return @"HalfInstalled";
2744 case pkgCache::State::ConfigFiles:
2745 return @"ConfigFiles";
2746 case pkgCache::State::Installed:
2747 return @"Installed";
2748 case pkgCache::State::TriggersAwaited:
2749 return @"TriggersAwaited";
2750 case pkgCache::State::TriggersPending:
2751 return @"TriggersPending";
2754 return (NSString *) [NSNull null];
2757 - (NSString *) selection {
2758 @synchronized (database_) {
2759 if ([database_ era] != era_ || file_.end())
2762 switch (iterator_->SelectedState) {
2763 case pkgCache::State::Unknown:
2765 case pkgCache::State::Install:
2767 case pkgCache::State::Hold:
2769 case pkgCache::State::DeInstall:
2770 return @"DeInstall";
2771 case pkgCache::State::Purge:
2775 return (NSString *) [NSNull null];
2778 - (NSArray *) warnings {
2779 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2780 const char *name(iterator_.Name());
2782 size_t length(strlen(name));
2783 if (length < 2) invalid:
2784 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2785 else for (size_t i(0); i != length; ++i)
2787 /* XXX: technically this is not allowed */
2788 (name[i] < 'A' || name[i] > 'Z') &&
2789 (name[i] < 'a' || name[i] > 'z') &&
2790 (name[i] < '0' || name[i] > '9') &&
2791 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2794 if (strcmp(name, "cydia") != 0) {
2797 bool _private = false;
2800 bool repository = [[self section] isEqualToString:@"Repositories"];
2802 if (NSArray *files = [self files])
2803 for (NSString *file in files)
2804 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2806 else if (!user && [file isEqualToString:@"/User"])
2808 else if (!_private && [file isEqualToString:@"/private"])
2810 else if (!stash && [file isEqualToString:@"/var/stash"])
2813 /* XXX: this is not sensitive enough. only some folders are valid. */
2814 if (cydia && !repository)
2815 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2817 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2819 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2821 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2824 return [warnings count] == 0 ? nil : warnings;
2827 - (NSArray *) applications {
2828 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2830 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2832 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2833 if (NSArray *files = [self files])
2834 for (NSString *file in files)
2835 if (application_r(file)) {
2836 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2837 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2838 if ([id isEqualToString:me])
2841 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2843 display = application_r[1];
2845 NSString *bundle([file stringByDeletingLastPathComponent]);
2846 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2847 if (icon == nil || [icon length] == 0)
2849 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2851 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2852 [applications addObject:application];
2854 [application addObject:id];
2855 [application addObject:display];
2856 [application addObject:url];
2859 return [applications count] == 0 ? nil : applications;
2862 - (Source *) source {
2863 if (source_ == nil) {
2864 @synchronized (database_) {
2865 if ([database_ era] != era_ || file_.end())
2866 source_ = (Source *) [NSNull null];
2868 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2872 return source_ == (Source *) [NSNull null] ? nil : source_;
2879 - (BOOL) matches:(NSArray *)query {
2880 if (query == nil || [query count] == 0)
2889 string = [self name];
2890 length = [string length];
2892 for (NSString *term in query) {
2893 range = [string rangeOfString:term options:MatchCompareOptions_];
2894 if (range.location != NSNotFound)
2895 rank_ -= 6 * 1000000 / length;
2900 length = [string length];
2902 for (NSString *term in query) {
2903 range = [string rangeOfString:term options:MatchCompareOptions_];
2904 if (range.location != NSNotFound)
2905 rank_ -= 6 * 1000000 / length;
2909 string = [self shortDescription];
2910 length = [string length];
2911 NSUInteger stop(std::min<NSUInteger>(length, 200));
2913 for (NSString *term in query) {
2914 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2915 if (range.location != NSNotFound)
2916 rank_ -= 2 * 100000;
2922 - (bool) hasSupportingRole {
2927 if ([Role_ isEqualToString:@"User"])
2931 if ([Role_ isEqualToString:@"Hacker"])
2935 if ([Role_ isEqualToString:@"Developer"])
2940 - (NSArray *) tags {
2944 - (BOOL) hasTag:(NSString *)tag {
2945 return tags_ == nil ? NO : [tags_ containsObject:tag];
2948 - (NSString *) primaryPurpose {
2949 for (NSString *tag in (NSArray *) tags_)
2950 if ([tag hasPrefix:@"purpose::"])
2951 return [tag substringFromIndex:9];
2955 - (NSArray *) purposes {
2956 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2957 for (NSString *tag in (NSArray *) tags_)
2958 if ([tag hasPrefix:@"purpose::"])
2959 [purposes addObject:[tag substringFromIndex:9]];
2960 return [purposes count] == 0 ? nil : purposes;
2963 - (bool) isCommercial {
2964 return [self hasTag:@"cydia::commercial"];
2967 - (void) setIndex:(size_t)index {
2968 if (metadata_->index_ != index)
2969 metadata_->index_ = index;
2972 - (CYString &) cyname {
2973 return name_.empty() ? id_ : name_;
2976 - (uint32_t) compareBySection:(NSArray *)sections {
2977 NSString *section([self section]);
2978 for (size_t i(0), e([sections count]); i != e; ++i) {
2979 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2983 return _not(uint32_t);
2987 @synchronized (database_) {
2988 pkgProblemResolver *resolver = [database_ resolver];
2989 resolver->Clear(iterator_);
2991 pkgCacheFile &cache([database_ cache]);
2992 cache->SetReInstall(iterator_, false);
2993 cache->MarkKeep(iterator_, false);
2997 @synchronized (database_) {
2998 pkgProblemResolver *resolver = [database_ resolver];
2999 resolver->Clear(iterator_);
3000 resolver->Protect(iterator_);
3002 pkgCacheFile &cache([database_ cache]);
3003 cache->SetReInstall(iterator_, false);
3004 cache->MarkInstall(iterator_, false);
3006 pkgDepCache::StateCache &state((*cache)[iterator_]);
3007 if (!state.Install())
3008 cache->SetReInstall(iterator_, true);
3012 @synchronized (database_) {
3013 pkgProblemResolver *resolver = [database_ resolver];
3014 resolver->Clear(iterator_);
3015 resolver->Remove(iterator_);
3016 resolver->Protect(iterator_);
3018 pkgCacheFile &cache([database_ cache]);
3019 cache->SetReInstall(iterator_, false);
3020 cache->MarkDelete(iterator_, true);
3023 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3024 _profile(Package$isUnfilteredAndSearchedForBy)
3027 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3028 value &= [self unfiltered];
3031 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3032 value &= [self matches:query];
3039 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3040 if ([search length] == 0)
3043 _profile(Package$isUnfilteredAndSelectedForBy)
3046 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3047 value &= [self unfiltered];
3050 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3051 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3058 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3059 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3062 - (bool) isVisibleInSection:(NSString *)name {
3063 NSString *section([self section]);
3067 section == nil && [name length] == 0 ||
3068 [name isEqualToString:section]
3069 ) && [self visible];
3072 - (bool) isVisibleInSource:(Source *)source {
3073 return [self source] == source && [self visible];
3078 /* Section Class {{{ */
3079 @interface Section : NSObject {
3084 _H<NSString> localized_;
3087 - (NSComparisonResult) compareByLocalized:(Section *)section;
3088 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3089 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3090 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3091 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3092 - (NSString *) name;
3099 - (void) addToCount;
3101 - (void) setCount:(size_t)count;
3102 - (NSString *) localized;
3106 @implementation Section
3108 - (NSComparisonResult) compareByLocalized:(Section *)section {
3109 NSString *lhs(localized_);
3110 NSString *rhs([section localized]);
3112 /*if ([lhs length] != 0 && [rhs length] != 0) {
3113 unichar lhc = [lhs characterAtIndex:0];
3114 unichar rhc = [rhs characterAtIndex:0];
3116 if (isalpha(lhc) && !isalpha(rhc))
3117 return NSOrderedAscending;
3118 else if (!isalpha(lhc) && isalpha(rhc))
3119 return NSOrderedDescending;
3122 return [lhs compare:rhs options:LaxCompareOptions_];
3125 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3126 if ((self = [self initWithName:name localize:NO]) != nil) {
3127 if (localized != nil)
3128 localized_ = localized;
3132 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3133 return [self initWithName:name row:0 localize:localize];
3136 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3137 if ((self = [super init]) != nil) {
3142 localized_ = LocalizeSection(name_);
3146 /* XXX: localize the index thingees */
3147 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3148 if ((self = [super init]) != nil) {
3149 name_ = [NSString stringWithCharacters:&index length:1];
3155 - (NSString *) name {
3175 - (void) addToCount {
3179 - (void) setCount:(size_t)count {
3183 - (NSString *) localized {
3190 class CydiaLogCleaner :
3191 public pkgArchiveCleaner
3194 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3199 /* Database Implementation {{{ */
3200 @implementation Database
3202 + (Database *) sharedInstance {
3203 static _H<Database> instance;
3204 if (instance == nil)
3205 instance = [[[Database alloc] init] autorelease];
3213 - (void) releasePackages {
3214 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3215 CFArrayRemoveAllValues(packages_);
3219 // XXX: actually implement this thing
3221 [self releasePackages];
3222 apr_pool_destroy(pool_);
3223 NSRecycleZone(zone_);
3227 - (void) _readCydia:(NSNumber *)fd {
3228 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3229 std::istream is(&ib);
3232 static Pcre finish_r("^finish:([^:]*)$");
3234 while (std::getline(is, line)) {
3235 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3237 const char *data(line.c_str());
3238 size_t size = line.size();
3239 lprintf("C:%s\n", data);
3241 if (finish_r(data, size)) {
3242 NSString *finish = finish_r[1];
3243 int index = [Finishes_ indexOfObject:finish];
3244 if (index != INT_MAX && index > Finish_)
3254 - (void) _readStatus:(NSNumber *)fd {
3255 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3256 std::istream is(&ib);
3259 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3260 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3262 while (std::getline(is, line)) {
3263 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3265 const char *data(line.c_str());
3266 size_t size(line.size());
3267 lprintf("S:%s\n", data);
3269 if (conffile_r(data, size)) {
3270 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3271 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3272 } else if (strncmp(data, "status: ", 8) == 0) {
3273 // status: <package>: {unpacked,half-configured,installed}
3274 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3275 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3276 } else if (strncmp(data, "processing: ", 12) == 0) {
3277 // processing: configure: config-test
3278 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3279 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3280 } else if (pmstatus_r(data, size)) {
3281 std::string type([pmstatus_r[1] UTF8String]);
3283 NSString *package = pmstatus_r[2];
3284 if ([package isEqualToString:@"dpkg-exec"])
3287 float percent([pmstatus_r[3] floatValue]);
3288 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3290 NSString *string = pmstatus_r[4];
3292 if (type == "pmerror") {
3293 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3294 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3295 } else if (type == "pmstatus") {
3296 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3297 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3298 } else if (type == "pmconffile")
3299 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3301 lprintf("E:unknown pmstatus\n");
3303 lprintf("E:unknown status\n");
3311 - (void) _readOutput:(NSNumber *)fd {
3312 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3313 std::istream is(&ib);
3316 while (std::getline(is, line)) {
3317 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3319 lprintf("O:%s\n", line.c_str());
3321 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3322 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3334 - (Package *) packageWithName:(NSString *)name {
3337 @synchronized (self) {
3338 if (static_cast<pkgDepCache *>(cache_) == NULL)
3340 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3341 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3345 if ((self = [super init]) != nil) {
3352 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3353 apr_pool_create(&pool_, NULL);
3355 size_t capacity(MetaFile_->active_);
3361 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3362 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3366 _assert(pipe(fds) != -1);
3369 _config->Set("APT::Keep-Fds::", cydiafd_);
3370 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3373 detachNewThreadSelector:@selector(_readCydia:)
3375 withObject:[NSNumber numberWithInt:fds[0]]
3378 _assert(pipe(fds) != -1);
3382 detachNewThreadSelector:@selector(_readStatus:)
3384 withObject:[NSNumber numberWithInt:fds[0]]
3387 _assert(pipe(fds) != -1);
3388 _assert(dup2(fds[0], 0) != -1);
3389 _assert(close(fds[0]) != -1);
3391 input_ = fdopen(fds[1], "a");
3393 _assert(pipe(fds) != -1);
3394 _assert(dup2(fds[1], 1) != -1);
3395 _assert(close(fds[1]) != -1);
3398 detachNewThreadSelector:@selector(_readOutput:)
3400 withObject:[NSNumber numberWithInt:fds[0]]
3405 - (pkgCacheFile &) cache {
3409 - (pkgDepCache::Policy *) policy {
3413 - (pkgRecords *) records {
3417 - (pkgProblemResolver *) resolver {
3421 - (pkgAcquire &) fetcher {
3425 - (pkgSourceList &) list {
3429 - (NSArray *) packages {
3430 return (NSArray *) packages_;
3433 - (NSArray *) sources {
3437 - (Source *) sourceWithKey:(NSString *)key {
3438 for (Source *source in [self sources]) {
3439 if ([[source key] isEqualToString:key])
3444 - (bool) popErrorWithTitle:(NSString *)title {
3447 while (!_error->empty()) {
3449 bool warning(!_error->PopMessage(error));
3454 size_t size(error.size());
3455 if (size == 0 || error[size - 1] != '\n')
3457 error.resize(size - 1);
3460 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3462 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3463 if (warning && no_pubkey(error.c_str()))
3466 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3472 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3473 return [self popErrorWithTitle:title] || !success;
3476 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3477 @synchronized (self) {
3480 [self releasePackages];
3483 [sourceList_ removeAllObjects];
3503 apr_pool_clear(pool_);
3505 NSRecycleZone(zone_);
3506 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3508 int chk(creat("/tmp/cydia.chk", 0644));
3512 if (invocation != nil)
3513 [invocation invoke];
3515 NSString *title(UCLocalize("DATABASE"));
3518 OpProgress progress;
3519 while (!cache_.Open(progress, true)) { pop:
3521 bool warning(!_error->PopMessage(error));
3522 lprintf("cache_.Open():[%s]\n", error.c_str());
3524 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3525 [delegate_ repairWithSelector:@selector(configure)];
3526 else if (error == "The package lists or status file could not be parsed or opened.")
3527 [delegate_ repairWithSelector:@selector(update)];
3528 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3529 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3530 // else if (error == "Malformed Status line")
3531 // else if (error == "The list of sources could not be read.")
3533 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3543 unlink("/tmp/cydia.chk");
3545 now_ = [[NSDate date] timeIntervalSince1970];
3547 policy_ = new pkgDepCache::Policy();
3548 records_ = new pkgRecords(cache_);
3549 resolver_ = new pkgProblemResolver(cache_);
3550 fetcher_ = new pkgAcquire(&status_);
3553 list_ = new pkgSourceList();
3554 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3557 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3558 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3562 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3565 if (cache_->BrokenCount() != 0) {
3566 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3569 if (cache_->BrokenCount() != 0) {
3570 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3574 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3578 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3579 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3580 [sourceList_ addObject:object];
3582 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3583 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3584 // XXX: this could be more intelligent
3585 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3586 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3588 sourceMap_[cached->ID] = object;
3593 /*std::vector<Package *> packages;
3594 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3599 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3600 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3601 //packages.push_back(package);
3602 CFArrayAppendValue(packages_, CFRetain(package));
3606 /*if (packages.empty())
3607 packages_ = [[NSArray alloc] init];
3609 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3612 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3613 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3614 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3622 /*if (!packages.empty())
3623 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3624 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3626 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3628 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3630 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3634 size_t count(CFArrayGetCount(packages_));
3635 MetaFile_->active_ = count;
3637 for (size_t index(0); index != count; ++index)
3638 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3645 @synchronized (self) {
3647 resolver_ = new pkgProblemResolver(cache_);
3649 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3650 if (!cache_[iterator].Keep())
3651 cache_->MarkKeep(iterator, false);
3652 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3653 cache_->SetReInstall(iterator, false);
3656 - (void) configure {
3657 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3659 system([dpkg UTF8String]);
3664 // XXX: I don't remember this condition
3669 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3671 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3673 if ([self popErrorWithTitle:title])
3677 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3679 CydiaLogCleaner cleaner;
3680 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3687 fetcher_->Shutdown();
3689 pkgRecords records(cache_);
3691 lock_ = new FileFd();
3692 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3694 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3696 if ([self popErrorWithTitle:title])
3700 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3703 manager_ = (_system->CreatePM(cache_));
3704 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3711 bool substrate(RestartSubstrate_);
3712 RestartSubstrate_ = false;
3714 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3716 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3718 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3720 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3721 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3724 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3726 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3728 [self popErrorWithTitle:title];
3732 bool failed = false;
3733 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3734 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3736 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3742 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3750 RestartSubstrate_ = true;
3753 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3755 if (_error->PendingError()) {
3760 if (result == pkgPackageManager::Failed) {
3765 if (result != pkgPackageManager::Completed) {
3770 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3772 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3774 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3775 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3778 if (![before isEqualToArray:after])
3783 NSString *title(UCLocalize("UPGRADE"));
3784 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3790 [self updateWithStatus:status_];
3793 - (void) updateWithStatus:(Status &)status {
3794 NSString *title(UCLocalize("REFRESHING_DATA"));
3797 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3801 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3802 if ([self popErrorWithTitle:title])
3805 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3807 bool success(ListUpdate(status, list, PulseInterval_));
3808 if (status.WasCancelled())
3811 [self popErrorWithTitle:title forOperation:success];
3812 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3816 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3819 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3820 delegate_ = delegate;
3823 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3824 progress_ = delegate;
3825 status_.setDelegate(delegate);
3828 - (NSObject<ProgressDelegate> *) progressDelegate {
3832 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3833 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3834 return i == sourceMap_.end() ? nil : i->second;
3837 - (NSString *) mappedSectionForPointer:(const char *)section {
3838 _H<NSString> *mapped;
3840 _profile(Database$mappedSectionForPointer$Cache)
3841 mapped = §ions_[section];
3844 if (*mapped == NULL) {
3845 size_t length(strlen(section));
3846 char spaced[length + 1];
3848 _profile(Database$mappedSectionForPointer$Replace)
3849 for (size_t index(0); index != length; ++index)
3850 spaced[index] = section[index] == '_' ? ' ' : section[index];
3851 spaced[length] = '\0';
3856 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3857 string = [NSString stringWithUTF8String:spaced];
3860 _profile(Database$mappedSectionForPointer$Map)
3861 string = [SectionMap_ objectForKey:string] ?: string;
3871 static _H<NSMutableSet> Diversions_;
3873 @interface Diversion : NSObject {
3876 _H<NSString> format_;
3881 @implementation Diversion
3883 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3884 if ((self = [super init]) != nil) {
3885 pattern_ = [from UTF8String];
3891 - (NSString *) divert:(NSString *)url {
3892 return !pattern_(url) ? nil : pattern_->*format_;
3895 + (NSURL *) divertURL:(NSURL *)url {
3897 NSString *href([url absoluteString]);
3899 for (Diversion *diversion in (id) Diversions_)
3900 if (NSString *diverted = [diversion divert:href]) {
3902 NSLog(@"div: %@", diverted);
3904 url = [NSURL URLWithString:diverted];
3911 - (NSString *) key {
3915 - (NSUInteger) hash {
3919 - (BOOL) isEqual:(Diversion *)object {
3920 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3925 @interface CydiaObject : NSObject {
3926 _H<IndirectDelegate> indirect_;
3927 _transient id delegate_;
3930 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3934 @interface CydiaWebViewController : CyteWebViewController {
3935 _H<CydiaObject> cydia_;
3938 + (void) addDiversion:(Diversion *)diversion;
3942 /* Web Scripting {{{ */
3943 @implementation CydiaObject
3945 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3946 if ((self = [super init]) != nil) {
3947 indirect_ = indirect;
3951 - (void) setDelegate:(id)delegate {
3952 delegate_ = delegate;
3955 + (NSArray *) _attributeKeys {
3956 return [NSArray arrayWithObjects:
3974 - (NSArray *) attributeKeys {
3975 return [[self class] _attributeKeys];
3978 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3979 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3982 - (NSString *) version {
3986 - (NSString *) device {
3987 return [[UIDevice currentDevice] uniqueIdentifier];
3990 - (NSString *) firmware {
3991 return [[UIDevice currentDevice] systemVersion];
3994 - (NSString *) hostname {
3995 return [[UIDevice currentDevice] name];
3998 - (NSString *) idiom {
3999 return (id) Idiom_ ?: [NSNull null];
4002 - (NSString *) mcc {
4003 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4004 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4008 - (NSString *) mnc {
4009 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4010 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4014 - (NSString *) bbsnum {
4015 return (id) BBSNum_ ?: [NSNull null];
4018 - (NSString *) ecid {
4019 return (id) ChipID_ ?: [NSNull null];
4022 - (NSString *) serial {
4023 return SerialNumber_;
4026 - (NSString *) role {
4027 return (id) Role_ ?: [NSNull null];
4030 - (NSString *) model {
4031 return [NSString stringWithUTF8String:Machine_];
4034 - (NSString *) token {
4035 return (id) Token_ ?: [NSNull null];
4038 + (NSString *) webScriptNameForSelector:(SEL)selector {
4040 else if (selector == @selector(addBridgedHost:))
4041 return @"addBridgedHost";
4042 else if (selector == @selector(addInsecureHost:))
4043 return @"addInsecureHost";
4044 else if (selector == @selector(addInternalRedirect::))
4045 return @"addInternalRedirect";
4046 else if (selector == @selector(addPipelinedHost:scheme:))
4047 return @"addPipelinedHost";
4048 else if (selector == @selector(addSource:::))
4049 return @"addSource";
4050 else if (selector == @selector(addTokenHost:))
4051 return @"addTokenHost";
4052 else if (selector == @selector(addTrivialSource:))
4053 return @"addTrivialSource";
4054 else if (selector == @selector(close))
4056 else if (selector == @selector(du:))
4058 else if (selector == @selector(stringWithFormat:arguments:))
4060 else if (selector == @selector(getAllSources))
4061 return @"getAllSourcs";
4062 else if (selector == @selector(getKernelNumber:))
4063 return @"getKernelNumber";
4064 else if (selector == @selector(getKernelString:))
4065 return @"getKernelString";
4066 else if (selector == @selector(getInstalledPackages))
4067 return @"getInstalledPackages";
4068 else if (selector == @selector(getIORegistryEntry::))
4069 return @"getIORegistryEntry";
4070 else if (selector == @selector(getLocaleIdentifier))
4071 return @"getLocaleIdentifier";
4072 else if (selector == @selector(getPreferredLanguages))
4073 return @"getPreferredLanguages";
4074 else if (selector == @selector(getPackageById:))
4075 return @"getPackageById";
4076 else if (selector == @selector(getMetadataKeys))
4077 return @"getMetadataKeys";
4078 else if (selector == @selector(getMetadataValue:))
4079 return @"getMetadataValue";
4080 else if (selector == @selector(getSessionValue:))
4081 return @"getSessionValue";
4082 else if (selector == @selector(installPackages:))
4083 return @"installPackages";
4084 else if (selector == @selector(localizedStringForKey:value:table:))
4086 else if (selector == @selector(popViewController:))
4087 return @"popViewController";
4088 else if (selector == @selector(refreshSources))
4089 return @"refreshSources";
4090 else if (selector == @selector(removeButton))
4091 return @"removeButton";
4092 else if (selector == @selector(saveConfig))
4093 return @"saveConfig";
4094 else if (selector == @selector(setCydiaSource:))
4095 return @"setCydiaSource";
4096 else if (selector == @selector(setMetadataValue::))
4097 return @"setMetadataValue";
4098 else if (selector == @selector(setSessionValue::))
4099 return @"setSessionValue";
4100 else if (selector == @selector(substitutePackageNames:))
4101 return @"substitutePackageNames";
4102 else if (selector == @selector(scrollToBottom:))
4103 return @"scrollToBottom";
4104 else if (selector == @selector(setAllowsNavigationAction:))
4105 return @"setAllowsNavigationAction";
4106 else if (selector == @selector(setBadgeValue:))
4107 return @"setBadgeValue";
4108 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4109 return @"setButtonImage";
4110 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4111 return @"setButtonTitle";
4112 else if (selector == @selector(setHidesBackButton:))
4113 return @"setHidesBackButton";
4114 else if (selector == @selector(setHidesNavigationBar:))
4115 return @"setHidesNavigationBar";
4116 else if (selector == @selector(setNavigationBarStyle:))
4117 return @"setNavigationBarStyle";
4118 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4119 return @"setNavigationBarTintColor";
4120 else if (selector == @selector(setPasteboardString:))
4121 return @"setPasteboardString";
4122 else if (selector == @selector(setPasteboardURL:))
4123 return @"setPasteboardURL";
4124 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4125 return @"setScrollAlwaysBounceVertical";
4126 else if (selector == @selector(setScrollIndicatorStyle:))
4127 return @"setScrollIndicatorStyle";
4128 else if (selector == @selector(setToken:))
4130 else if (selector == @selector(setViewportWidth:))
4131 return @"setViewportWidth";
4132 else if (selector == @selector(statfs:))
4134 else if (selector == @selector(supports:))
4136 else if (selector == @selector(unload))
4142 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4143 return [self webScriptNameForSelector:selector] == nil;
4146 - (BOOL) supports:(NSString *)feature {
4147 return [feature isEqualToString:@"window.open"];
4151 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4154 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4155 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4158 - (void) setScrollIndicatorStyle:(NSString *)style {
4159 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4162 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4163 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4166 - (NSNumber *) getKernelNumber:(NSString *)name {
4167 const char *string([name UTF8String]);
4170 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4171 return (id) [NSNull null];
4173 if (size != sizeof(int))
4174 return (id) [NSNull null];
4177 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4178 return (id) [NSNull null];
4180 return [NSNumber numberWithInt:value];
4183 - (NSString *) getKernelString:(NSString *)name {
4184 const char *string([name UTF8String]);
4187 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4188 return (id) [NSNull null];
4190 char value[size + 1];
4191 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4192 return (id) [NSNull null];
4194 // XXX: just in case you request something ludicrous
4197 return [NSString stringWithCString:value];
4200 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4201 NSObject *value(CYIOGetValue([path UTF8String], entry));
4204 if ([value isKindOfClass:[NSData class]])
4205 value = CYHex((NSData *) value);
4210 - (void) _setCydiaSource:(NSString *)source {
4211 @synchronized (HostConfig_) {
4212 CydiaSource_ = source;
4213 [Metadata_ setObject:source forKey:@"CydiaSource"];
4219 - (void) setCydiaSource:(NSString *)source {
4220 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4223 - (NSString *) cydiaSource {
4224 @synchronized (HostConfig_) {
4225 return (id) CydiaSource_ ?: [NSNull null];
4229 - (NSArray *) getMetadataKeys {
4230 @synchronized (Values_) {
4231 return [Values_ allKeys];
4234 - (id) getMetadataValue:(NSString *)key {
4235 @synchronized (Values_) {
4236 return [Values_ objectForKey:key];
4239 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4240 @synchronized (Values_) {
4241 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4242 [Values_ removeObjectForKey:key];
4244 [Values_ setObject:value forKey:key];
4246 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4249 - (id) getSessionValue:(NSString *)key {
4250 @synchronized (SessionData_) {
4251 return [SessionData_ objectForKey:key];
4254 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4255 @synchronized (SessionData_) {
4256 if (value == (id) [WebUndefined undefined])
4257 [SessionData_ removeObjectForKey:key];
4259 [SessionData_ setObject:value forKey:key];
4262 - (void) addBridgedHost:(NSString *)host {
4263 @synchronized (HostConfig_) {
4264 [BridgedHosts_ addObject:host];
4267 - (void) addInsecureHost:(NSString *)host {
4268 @synchronized (HostConfig_) {
4269 [InsecureHosts_ addObject:host];
4272 - (void) addTokenHost:(NSString *)host {
4273 @synchronized (HostConfig_) {
4274 [TokenHosts_ addObject:host];
4277 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4278 @synchronized (HostConfig_) {
4279 if (scheme != (id) [WebUndefined undefined])
4280 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4282 [PipelinedHosts_ addObject:host];
4285 - (void) popViewController:(NSNumber *)value {
4286 if (value == (id) [WebUndefined undefined])
4287 value = [NSNumber numberWithBool:YES];
4288 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4291 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4292 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4294 for (NSString *section in sections)
4295 [array addObject:section];
4297 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4300 distribution, @"Distribution",
4302 nil] waitUntilDone:NO];
4305 - (void) addTrivialSource:(NSString *)href {
4306 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4309 - (void) refreshSources {
4310 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4313 - (void) saveConfig {
4314 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4317 - (NSArray *) getAllSources {
4318 return [[Database sharedInstance] sources];
4321 - (NSArray *) getInstalledPackages {
4322 Database *database([Database sharedInstance]);
4323 @synchronized (database) {
4324 NSArray *packages([database packages]);
4325 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4326 for (Package *package in packages)
4327 if (![package uninstalled])
4328 [installed addObject:package];
4332 - (Package *) getPackageById:(NSString *)id {
4333 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4337 return (Package *) [NSNull null];
4340 - (NSString *) getLocaleIdentifier {
4341 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4344 - (NSArray *) getPreferredLanguages {
4348 - (NSArray *) statfs:(NSString *)path {
4351 if (path == nil || statfs([path UTF8String], &stat) == -1)
4354 return [NSArray arrayWithObjects:
4355 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4356 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4357 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4361 - (NSNumber *) du:(NSString *)path {
4362 NSNumber *value(nil);
4365 _assert(pipe(fds) != -1);
4367 pid_t pid(ExecFork());
4369 _assert(dup2(fds[1], 1) != -1);
4370 _assert(close(fds[0]) != -1);
4371 _assert(close(fds[1]) != -1);
4372 /* XXX: this should probably not use du */
4373 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4378 _assert(close(fds[1]) != -1);
4380 if (FILE *du = fdopen(fds[0], "r")) {
4382 while (fgets(line, sizeof(line), du) != NULL) {
4383 size_t length(strlen(line));
4384 while (length != 0 && line[length - 1] == '\n')
4385 line[--length] = '\0';
4386 if (char *tab = strchr(line, '\t')) {
4388 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4393 } else _assert(close(fds[0]));
4401 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4404 - (void) installPackages:(NSArray *)packages {
4405 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4408 - (NSString *) substitutePackageNames:(NSString *)message {
4409 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4410 for (size_t i(0), e([words count]); i != e; ++i) {
4411 NSString *word([words objectAtIndex:i]);
4412 if (Package *package = [[Database sharedInstance] packageWithName:word])
4413 [words replaceObjectAtIndex:i withObject:[package name]];
4416 return [words componentsJoinedByString:@" "];
4419 - (void) removeButton {
4420 [indirect_ removeButton];
4423 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4424 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4427 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4428 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4431 - (void) setBadgeValue:(id)value {
4432 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4435 - (void) setAllowsNavigationAction:(NSString *)value {
4436 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4439 - (void) setHidesBackButton:(NSString *)value {
4440 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4443 - (void) setHidesNavigationBar:(NSString *)value {
4444 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4447 - (void) setNavigationBarStyle:(NSString *)value {
4448 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4451 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4452 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4453 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4454 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4457 - (void) setPasteboardString:(NSString *)value {
4458 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4461 - (void) setPasteboardURL:(NSString *)value {
4462 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4465 - (void) _setToken:(NSString *)token {
4469 [Metadata_ removeObjectForKey:@"Token"];
4471 [Metadata_ setObject:Token_ forKey:@"Token"];
4476 - (void) setToken:(NSString *)token {
4477 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4480 - (void) scrollToBottom:(NSNumber *)animated {
4481 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4484 - (void) setViewportWidth:(float)width {
4485 [indirect_ setViewportWidthOnMainThread:width];
4488 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4489 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4490 unsigned count([arguments count]);
4492 for (unsigned i(0); i != count; ++i)
4493 values[i] = [arguments objectAtIndex:i];
4494 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4497 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4498 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4500 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4502 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4508 @interface NSURL (CydiaSecure)
4511 @implementation NSURL (CydiaSecure)
4513 - (bool) isCydiaSecure {
4514 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4517 @synchronized (HostConfig_) {
4518 if ([InsecureHosts_ containsObject:[self host]])
4527 /* Cydia Browser Controller {{{ */
4528 @implementation CydiaWebViewController
4530 - (NSURL *) navigationURL {
4531 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4534 + (void) _initialize {
4535 [super _initialize];
4537 Diversions_ = [NSMutableSet setWithCapacity:0];
4540 + (void) addDiversion:(Diversion *)diversion {
4541 [Diversions_ addObject:diversion];
4544 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4545 [super webView:view didClearWindowObject:window forFrame:frame];
4547 WebDataSource *source([frame dataSource]);
4548 NSURLResponse *response([source response]);
4549 NSURL *url([response URL]);
4550 NSString *scheme([[url scheme] lowercaseString]);
4552 bool bridged(false);
4554 @synchronized (HostConfig_) {
4555 if ([scheme isEqualToString:@"file"])
4557 else if ([scheme isEqualToString:@"https"])
4558 if ([BridgedHosts_ containsObject:[url host]])
4563 [window setValue:cydia_ forKey:@"cydia"];
4566 - (void) _setupMail:(MFMailComposeViewController *)controller {
4567 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4569 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4570 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4573 - (NSURL *) URLWithURL:(NSURL *)url {
4574 return [Diversion divertURL:url];
4577 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4578 NSURL *url([request URL]);
4579 NSString *host([url host]);
4581 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4583 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4584 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4585 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4586 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4591 @synchronized (HostConfig_) {
4592 bridged = [BridgedHosts_ containsObject:host];
4593 token = [TokenHosts_ containsObject:host];
4596 if ([url isCydiaSecure]) {
4598 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4599 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4601 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4602 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4609 - (void) setDelegate:(id)delegate {
4610 [super setDelegate:delegate];
4611 [cydia_ setDelegate:delegate];
4614 - (NSString *) applicationNameForUserAgent {
4615 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4618 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4620 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4621 if (Product_ != nil)
4622 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4628 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4629 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4635 @interface AppCacheController : CydiaWebViewController {
4640 @implementation AppCacheController
4642 - (void) didReceiveMemoryWarning {
4649 @interface NSObject (CydiaScript)
4650 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4653 @implementation NSObject (CydiaScript)
4655 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4661 @implementation NSArray (CydiaScript)
4663 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4664 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4665 for (size_t i(0), e([self count]); i != e; ++i)
4666 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4672 @implementation NSDictionary (CydiaScript)
4674 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4675 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4677 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4684 /* Confirmation Controller {{{ */
4685 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4686 if (!iterator.end())
4687 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4688 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4690 pkgCache::PkgIterator package(dep.TargetPkg());
4693 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4700 @protocol ConfirmationControllerDelegate
4701 - (void) cancelAndClear:(bool)clear;
4702 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4706 @interface ConfirmationController : CydiaWebViewController {
4707 _transient Database *database_;
4709 _H<UIAlertView> essential_;
4711 _H<NSDictionary> changes_;
4712 _H<NSMutableArray> issues_;
4713 _H<NSDictionary> sizes_;
4718 - (id) initWithDatabase:(Database *)database;
4722 @implementation ConfirmationController
4726 RestartSubstrate_ = true;
4727 [delegate_ confirmWithNavigationController:[self navigationController]];
4730 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4731 NSString *context([alert context]);
4733 if ([context isEqualToString:@"remove"]) {
4734 if (button == [alert cancelButtonIndex])
4735 [self dismissModalViewControllerAnimated:YES];
4736 else if (button == [alert firstOtherButtonIndex]) {
4740 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4741 } else if ([context isEqualToString:@"unable"]) {
4742 [self dismissModalViewControllerAnimated:YES];
4743 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4745 [super alertView:alert clickedButtonAtIndex:button];
4749 - (void) _doContinue {
4750 [delegate_ cancelAndClear:NO];
4751 [self dismissModalViewControllerAnimated:YES];
4754 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4755 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4759 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4760 [super webView:view didClearWindowObject:window forFrame:frame];
4762 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4763 (id) changes_, @"changes",
4764 (id) issues_, @"issues",
4765 (id) sizes_, @"sizes",
4767 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4770 - (id) initWithDatabase:(Database *)database {
4771 if ((self = [super init]) != nil) {
4772 database_ = database;
4774 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4775 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4776 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4777 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4778 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4782 pkgCacheFile &cache([database_ cache]);
4783 NSArray *packages([database_ packages]);
4784 pkgDepCache::Policy *policy([database_ policy]);
4786 issues_ = [NSMutableArray arrayWithCapacity:4];
4788 for (Package *package in packages) {
4789 pkgCache::PkgIterator iterator([package iterator]);
4790 NSString *name([package id]);
4792 if ([package broken]) {
4793 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4795 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4797 reasons, @"reasons",
4800 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4804 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4805 pkgCache::DepIterator start;
4806 pkgCache::DepIterator end;
4807 dep.GlobOr(start, end); // ++dep
4809 if (!cache->IsImportantDep(end))
4811 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4814 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4816 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4817 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4818 clauses, @"clauses",
4822 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4824 pkgCache::PkgIterator target(start.TargetPkg());
4825 if (target->ProvidesList != 0)
4826 reason = @"missing";
4828 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4830 reason = @"installed";
4831 installed = [NSString stringWithUTF8String:ver.VerStr()];
4832 } else if (!cache[target].CandidateVerIter(cache).end())
4833 reason = @"uninstalled";
4834 else if (target->ProvidesList == 0)
4835 reason = @"uninstallable";
4837 reason = @"virtual";
4840 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4841 [NSString stringWithUTF8String:start.CompType()], @"operator",
4842 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4845 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4846 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4847 version, @"version",
4849 installed, @"installed",
4852 // yes, seriously. (wtf?)
4860 pkgDepCache::StateCache &state(cache[iterator]);
4862 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4864 if (state.NewInstall())
4865 [installs addObject:name];
4866 // XXX: else if (state.Install())
4867 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4868 [reinstalls addObject:name];
4869 // XXX: move before previous if
4870 else if (state.Upgrade())
4871 [upgrades addObject:name];
4872 else if (state.Downgrade())
4873 [downgrades addObject:name];
4874 else if (!state.Delete())
4875 // XXX: _assert(state.Keep());
4877 else if (special_r(name))
4878 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4879 [NSNull null], @"package",
4880 [NSArray arrayWithObjects:
4881 [NSDictionary dictionaryWithObjectsAndKeys:
4882 @"Conflicts", @"relationship",
4883 [NSArray arrayWithObjects:
4884 [NSDictionary dictionaryWithObjectsAndKeys:
4886 [NSNull null], @"version",
4887 @"installed", @"reason",
4894 if ([package essential])
4896 [removes addObject:name];
4899 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4900 substrate_ |= DepSubstrate(iterator.CurrentVer());
4905 else if (Advanced_) {
4906 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4908 essential_ = [[[UIAlertView alloc]
4909 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4910 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4912 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4914 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4918 [essential_ setContext:@"remove"];
4920 essential_ = [[[UIAlertView alloc]
4921 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4922 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4924 cancelButtonTitle:UCLocalize("OKAY")
4925 otherButtonTitles:nil
4928 [essential_ setContext:@"unable"];
4931 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4932 installs, @"installs",
4933 reinstalls, @"reinstalls",
4934 upgrades, @"upgrades",
4935 downgrades, @"downgrades",
4936 removes, @"removes",
4939 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4940 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4941 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4944 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4948 - (UIBarButtonItem *) leftButton {
4949 return [[[UIBarButtonItem alloc]
4950 initWithTitle:UCLocalize("CANCEL")
4951 style:UIBarButtonItemStylePlain
4953 action:@selector(cancelButtonClicked)
4958 - (void) applyRightButton {
4959 if ([issues_ count] == 0 && ![self isLoading])
4960 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4961 initWithTitle:UCLocalize("CONFIRM")
4962 style:UIBarButtonItemStyleDone
4964 action:@selector(confirmButtonClicked)
4967 [[self navigationItem] setRightBarButtonItem:nil];
4971 - (void) cancelButtonClicked {
4972 [self dismissModalViewControllerAnimated:YES];
4973 [delegate_ cancelAndClear:YES];
4977 - (void) confirmButtonClicked {
4978 if (essential_ != nil)
4988 /* Progress Data {{{ */
4989 @interface CydiaProgressData : NSObject {
4990 _transient id delegate_;
4999 _H<NSMutableArray> events_;
5000 _H<NSString> title_;
5002 _H<NSString> status_;
5003 _H<NSString> finish_;
5008 @implementation CydiaProgressData
5010 + (NSArray *) _attributeKeys {
5011 return [NSArray arrayWithObjects:
5023 - (NSArray *) attributeKeys {
5024 return [[self class] _attributeKeys];
5027 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5028 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5032 if ((self = [super init]) != nil) {
5033 events_ = [NSMutableArray arrayWithCapacity:32];
5037 - (void) setDelegate:(id)delegate {
5038 delegate_ = delegate;
5041 - (void) setPercent:(float)value {
5045 - (NSNumber *) percent {
5046 return [NSNumber numberWithFloat:percent_];
5049 - (void) setCurrent:(float)value {
5053 - (NSNumber *) current {
5054 return [NSNumber numberWithFloat:current_];
5057 - (void) setTotal:(float)value {
5061 - (NSNumber *) total {
5062 return [NSNumber numberWithFloat:total_];
5065 - (void) setSpeed:(float)value {
5069 - (NSNumber *) speed {
5070 return [NSNumber numberWithFloat:speed_];
5073 - (NSArray *) events {
5077 - (void) removeAllEvents {
5078 [events_ removeAllObjects];
5081 - (void) addEvent:(CydiaProgressEvent *)event {
5082 [events_ addObject:event];
5085 - (void) setTitle:(NSString *)text {
5089 - (NSString *) title {
5093 - (void) setFinish:(NSString *)text {
5097 - (NSString *) finish {
5098 return (id) finish_ ?: [NSNull null];
5101 - (void) setRunning:(bool)running {
5105 - (NSNumber *) running {
5106 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5111 /* Progress Controller {{{ */
5112 @interface ProgressController : CydiaWebViewController <
5115 _transient Database *database_;
5116 _H<CydiaProgressData, 1> progress_;
5120 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5122 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5124 - (void) setTitle:(NSString *)title;
5125 - (void) setCancellable:(bool)cancellable;
5129 @implementation ProgressController
5132 [database_ setProgressDelegate:nil];
5136 - (UIBarButtonItem *) leftButton {
5137 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5138 initWithTitle:UCLocalize("CANCEL")
5139 style:UIBarButtonItemStylePlain
5141 action:@selector(cancel)
5142 ] autorelease] : nil;
5145 - (void) updateCancel {
5146 [super applyLeftButton];
5149 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5150 if ((self = [super init]) != nil) {
5151 database_ = database;
5152 delegate_ = delegate;
5154 [database_ setProgressDelegate:self];
5156 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5157 [progress_ setDelegate:self];
5159 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5161 [scroller_ setBackgroundColor:[UIColor blackColor]];
5163 [[self navigationItem] setHidesBackButton:YES];
5165 [self updateCancel];
5169 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5170 [super webView:view didClearWindowObject:window forFrame:frame];
5171 [window setValue:progress_ forKey:@"cydiaProgress"];
5174 - (void) updateProgress {
5175 [self dispatchEvent:@"CydiaProgressUpdate"];
5178 - (void) viewWillAppear:(BOOL)animated {
5179 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5180 [super viewWillAppear:animated];
5184 UpdateExternalStatus(0);
5187 [delegate_ saveState];
5191 [delegate_ returnToCydia];
5195 [delegate_ terminateWithSuccess];
5196 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5197 [delegate_ suspendWithAnimation:YES];
5199 [delegate_ suspend];*/
5211 system("/usr/bin/sbreload");
5217 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5218 SBReboot(SBSSpringBoardServerPort());
5220 reboot2(RB_AUTOBOOT);
5227 - (void) setTitle:(NSString *)title {
5228 [progress_ setTitle:title];
5229 [self updateProgress];
5232 - (UIBarButtonItem *) rightButton {
5233 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5234 initWithTitle:UCLocalize("CLOSE")
5235 style:UIBarButtonItemStylePlain
5237 action:@selector(close)
5243 system("su -c /usr/bin/uicache mobile");
5247 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5248 UpdateExternalStatus(1);
5250 [progress_ setRunning:true];
5251 [self setTitle:title];
5252 // implicit updateProgress
5254 SHA1SumValue notifyconf; {
5256 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5259 MMap mmap(file, MMap::ReadOnly);
5261 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5262 notifyconf = sha1.Result();
5266 SHA1SumValue springlist; {
5268 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5271 MMap mmap(file, MMap::ReadOnly);
5273 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5274 springlist = sha1.Result();
5278 if (invocation != nil) {
5279 [invocation yieldToSelector:@selector(invoke)];
5280 [self setTitle:@"COMPLETE"];
5285 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5288 MMap mmap(file, MMap::ReadOnly);
5290 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5291 if (!(notifyconf == sha1.Result()))
5298 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5301 MMap mmap(file, MMap::ReadOnly);
5303 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5304 if (!(springlist == sha1.Result()))
5310 if (RestartSubstrate_)
5314 RestartSubstrate_ = false;
5317 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5318 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5319 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5320 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5321 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5324 UIProgressHUD *hud([delegate_ addProgressHUD]);
5325 [hud setText:UCLocalize("LOADING")];
5326 [self yieldToSelector:@selector(uicache)];
5327 [delegate_ removeProgressHUD:hud];
5329 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5331 [progress_ setRunning:false];
5332 [self updateProgress];
5334 [self applyRightButton];
5337 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5338 [progress_ addEvent:event];
5339 [self updateProgress];
5342 - (bool) isProgressCancelled {
5343 return cancel_ == 2;
5348 [self updateCancel];
5351 - (void) setCancellable:(bool)cancellable {
5352 unsigned cancel(cancel_);
5356 else if (cancel_ == 0)
5359 if (cancel != cancel_)
5360 [self updateCancel];
5363 - (void) setProgressCancellable:(NSNumber *)cancellable {
5364 [self setCancellable:[cancellable boolValue]];
5367 - (void) setProgressPercent:(NSNumber *)percent {
5368 [progress_ setPercent:[percent floatValue]];
5369 [self updateProgress];
5372 - (void) setProgressStatus:(NSDictionary *)status {
5373 if (status == nil) {
5374 [progress_ setCurrent:0];
5375 [progress_ setTotal:0];
5376 [progress_ setSpeed:0];
5378 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5380 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5381 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5382 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5385 [self updateProgress];
5391 /* Package Cell {{{ */
5392 @interface PackageCell : CyteTableViewCell <
5393 CyteTableViewCellDelegate
5397 _H<NSString> description_;
5399 _H<NSString> source_;
5401 _H<UIImage> placard_;
5405 - (PackageCell *) init;
5406 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5408 - (void) drawContentRect:(CGRect)rect;
5412 @implementation PackageCell
5414 - (PackageCell *) init {
5415 CGRect frame(CGRectMake(0, 0, 320, 74));
5416 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5417 UIView *content([self contentView]);
5418 CGRect bounds([content bounds]);
5420 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5421 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5422 [content addSubview:content_];
5424 [content_ setDelegate:self];
5425 [content_ setOpaque:YES];
5429 - (NSString *) accessibilityLabel {
5430 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5433 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5434 summarized_ = summary;
5444 [content_ setBackgroundColor:[UIColor whiteColor]];
5448 Source *source = [package source];
5450 icon_ = [package icon];
5452 if (NSString *name = [package name])
5453 name_ = [NSString stringWithString:name];
5455 NSString *description(nil);
5457 if (description == nil && IsWildcat_)
5458 description = [package longDescription];
5459 if (description == nil)
5460 description = [package shortDescription];
5462 if (description != nil)
5463 description_ = [NSString stringWithString:description];
5465 commercial_ = [package isCommercial];
5467 NSString *label = nil;
5468 bool trusted = false;
5470 if (source != nil) {
5471 label = [source label];
5472 trusted = [source trusted];
5473 } else if ([[package id] isEqualToString:@"firmware"])
5474 label = UCLocalize("APPLE");
5476 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5478 NSString *from(label);
5480 NSString *section = [package simpleSection];
5481 if (section != nil && ![section isEqualToString:label]) {
5482 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5483 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5486 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5488 if (NSString *purpose = [package primaryPurpose])
5489 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5494 if (NSString *mode = [package mode]) {
5495 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5496 color = RemovingColor_;
5497 //placard = @"removing";
5499 color = InstallingColor_;
5500 //placard = @"installing";
5503 // XXX: the removing/installing placards are not @2x
5506 color = [UIColor whiteColor];
5508 if ([package installed] != nil)
5509 placard = @"installed";
5514 [content_ setBackgroundColor:color];
5517 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5520 [self setNeedsDisplay];
5521 [content_ setNeedsDisplay];
5524 - (void) drawSummaryContentRect:(CGRect)rect {
5525 bool highlighted(highlighted_);
5526 float width([self bounds].size.width);
5530 rect.size = [(UIImage *) icon_ size];
5532 while (rect.size.width > 16 || rect.size.height > 16) {
5533 rect.size.width /= 2;
5534 rect.size.height /= 2;
5537 rect.origin.x = 18 - rect.size.width / 2;
5538 rect.origin.y = 18 - rect.size.height / 2;
5540 [icon_ drawInRect:rect];
5543 if (badge_ != nil) {
5545 rect.size = [(UIImage *) badge_ size];
5547 rect.size.width /= 4;
5548 rect.size.height /= 4;
5550 rect.origin.x = 23 - rect.size.width / 2;
5551 rect.origin.y = 23 - rect.size.height / 2;
5553 [badge_ drawInRect:rect];
5560 UISetColor(commercial_ ? Purple_ : Black_);
5561 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5563 if (placard_ != nil)
5564 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5567 - (void) drawNormalContentRect:(CGRect)rect {
5568 bool highlighted(highlighted_);
5569 float width([self bounds].size.width);
5573 rect.size = [(UIImage *) icon_ size];
5575 while (rect.size.width > 32 || rect.size.height > 32) {
5576 rect.size.width /= 2;
5577 rect.size.height /= 2;
5580 rect.origin.x = 25 - rect.size.width / 2;
5581 rect.origin.y = 25 - rect.size.height / 2;
5583 [icon_ drawInRect:rect];
5586 if (badge_ != nil) {
5588 rect.size = [(UIImage *) badge_ size];
5590 rect.size.width /= 2;
5591 rect.size.height /= 2;
5593 rect.origin.x = 36 - rect.size.width / 2;
5594 rect.origin.y = 36 - rect.size.height / 2;
5596 [badge_ drawInRect:rect];
5603 UISetColor(commercial_ ? Purple_ : Black_);
5604 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5605 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5608 UISetColor(commercial_ ? Purplish_ : Gray_);
5609 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5611 if (placard_ != nil)
5612 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5615 - (void) drawContentRect:(CGRect)rect {
5617 [self drawSummaryContentRect:rect];
5619 [self drawNormalContentRect:rect];
5624 /* Section Cell {{{ */
5625 @interface SectionCell : CyteTableViewCell <
5626 CyteTableViewCellDelegate
5628 _H<NSString> basic_;
5629 _H<NSString> section_;
5631 _H<NSString> count_;
5633 _H<UISwitch> switch_;
5637 - (void) setSection:(Section *)section editing:(BOOL)editing;
5641 @implementation SectionCell
5643 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5644 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5645 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5646 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5647 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5649 UIView *content([self contentView]);
5650 CGRect bounds([content bounds]);
5652 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5653 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5654 [content addSubview:content_];
5655 [content_ setBackgroundColor:[UIColor whiteColor]];
5657 [content_ setDelegate:self];
5661 - (void) onSwitch:(id)sender {
5662 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5663 if (metadata == nil) {
5664 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5665 [Sections_ setObject:metadata forKey:basic_];
5668 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5672 - (void) setSection:(Section *)section editing:(BOOL)editing {
5673 if (editing != editing_) {
5675 [switch_ removeFromSuperview];
5677 [self addSubview:switch_];
5686 if (section == nil) {
5687 name_ = UCLocalize("ALL_PACKAGES");
5690 basic_ = [section name];
5691 section_ = [section localized];
5693 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5694 count_ = [NSString stringWithFormat:@"%d", [section count]];
5697 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5700 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5701 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5703 [content_ setNeedsDisplay];
5706 - (void) setFrame:(CGRect)frame {
5707 [super setFrame:frame];
5709 CGRect rect([switch_ frame]);
5710 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5713 - (NSString *) accessibilityLabel {
5717 - (void) drawContentRect:(CGRect)rect {
5718 bool highlighted(highlighted_ && !editing_);
5720 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5725 float width(rect.size.width);
5731 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5733 CGSize size = [count_ sizeWithFont:Font14_];
5737 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5743 /* File Table {{{ */
5744 @interface FileTable : CyteViewController <
5745 UITableViewDataSource,
5748 _transient Database *database_;
5749 _H<Package> package_;
5751 _H<NSMutableArray> files_;
5752 _H<UITableView, 2> list_;
5755 - (id) initWithDatabase:(Database *)database;
5756 - (void) setPackage:(Package *)package;
5760 @implementation FileTable
5762 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5763 return files_ == nil ? 0 : [files_ count];
5766 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5770 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5771 static NSString *reuseIdentifier = @"Cell";
5773 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5775 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5776 [cell setFont:[UIFont systemFontOfSize:16]];
5778 [cell setText:[files_ objectAtIndex:indexPath.row]];
5779 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5784 - (NSURL *) navigationURL {
5785 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5789 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5791 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5792 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5793 [list_ setRowHeight:24.0f];
5794 [(UITableView *) list_ setDataSource:self];
5795 [list_ setDelegate:self];
5796 [[self view] addSubview:list_];
5799 - (void) viewDidLoad {
5800 [super viewDidLoad];
5802 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5805 - (void) releaseSubviews {
5811 [super releaseSubviews];
5814 - (id) initWithDatabase:(Database *)database {
5815 if ((self = [super init]) != nil) {
5816 database_ = database;
5820 - (void) setPackage:(Package *)package {
5824 files_ = [NSMutableArray arrayWithCapacity:32];
5826 if (package != nil) {
5828 name_ = [package id];
5830 if (NSArray *files = [package files])
5831 [files_ addObjectsFromArray:files];
5833 if ([files_ count] != 0) {
5834 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5835 [files_ removeObjectAtIndex:0];
5836 [files_ sortUsingSelector:@selector(compareByPath:)];
5838 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5839 [stack addObject:@"/"];
5841 for (int i(0), e([files_ count]); i != e; ++i) {
5842 NSString *file = [files_ objectAtIndex:i];
5843 while (![file hasPrefix:[stack lastObject]])
5844 [stack removeLastObject];
5845 NSString *directory = [stack lastObject];
5846 [stack addObject:[file stringByAppendingString:@"/"]];
5847 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5848 ([stack count] - 2) * 3, "",
5849 [file substringFromIndex:[directory length]]
5858 - (void) reloadData {
5861 [self setPackage:[database_ packageWithName:name_]];
5866 /* Package Controller {{{ */
5867 @interface CYPackageController : CydiaWebViewController <
5868 UIActionSheetDelegate
5870 _transient Database *database_;
5871 _H<Package> package_;
5874 _H<NSMutableArray> buttons_;
5875 _H<UIBarButtonItem> button_;
5878 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5882 @implementation CYPackageController
5884 - (NSURL *) navigationURL {
5885 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5888 /* XXX: this is not safe at all... localization of /fail/ */
5889 - (void) _clickButtonWithName:(NSString *)name {
5890 if ([name isEqualToString:UCLocalize("CLEAR")])
5891 [delegate_ clearPackage:package_];
5892 else if ([name isEqualToString:UCLocalize("INSTALL")])
5893 [delegate_ installPackage:package_];
5894 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5895 [delegate_ installPackage:package_];
5896 else if ([name isEqualToString:UCLocalize("REMOVE")])
5897 [delegate_ removePackage:package_];
5898 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5899 [delegate_ installPackage:package_];
5900 else _assert(false);
5903 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5904 NSString *context([sheet context]);
5906 if ([context isEqualToString:@"modify"]) {
5907 if (button != [sheet cancelButtonIndex]) {
5908 NSString *buttonName = [buttons_ objectAtIndex:button];
5909 [self _clickButtonWithName:buttonName];
5912 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5916 - (bool) _allowJavaScriptPanel {
5921 - (void) _customButtonClicked {
5922 int count([buttons_ count]);
5927 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5929 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5930 [buttons addObjectsFromArray:buttons_];
5932 UIActionSheet *sheet = [[[UIActionSheet alloc]
5935 cancelButtonTitle:nil
5936 destructiveButtonTitle:nil
5937 otherButtonTitles:nil
5940 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5942 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5943 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5945 [sheet setContext:@"modify"];
5947 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5951 // We don't want to allow non-commercial packages to do custom things to the install button,
5952 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5953 - (void) customButtonClicked {
5955 [super customButtonClicked];
5957 [self _customButtonClicked];
5960 - (void) reloadButtonClicked {
5961 // Don't reload a commerical package by tapping the loading button,
5962 // but if it's not an Install button, we should forward it on.
5963 if (![package_ uninstalled])
5964 [self _customButtonClicked];
5967 - (void) applyLoadingTitle {
5968 // Don't show "Loading" as the title. Ever.
5971 - (UIBarButtonItem *) rightButton {
5976 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5977 if ((self = [super init]) != nil) {
5978 database_ = database;
5979 buttons_ = [NSMutableArray arrayWithCapacity:4];
5980 name_ = name == nil ? @"" : [NSString stringWithString:name];
5981 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5985 - (void) reloadData {
5988 package_ = [database_ packageWithName:name_];
5990 [buttons_ removeAllObjects];
5992 if (package_ != nil) {
5993 [(Package *) package_ parse];
5995 commercial_ = [package_ isCommercial];
5997 if ([package_ mode] != nil)
5998 [buttons_ addObject:UCLocalize("CLEAR")];
5999 if ([package_ source] == nil);
6000 else if ([package_ upgradableAndEssential:NO])
6001 [buttons_ addObject:UCLocalize("UPGRADE")];
6002 else if ([package_ uninstalled])
6003 [buttons_ addObject:UCLocalize("INSTALL")];
6005 [buttons_ addObject:UCLocalize("REINSTALL")];
6006 if (![package_ uninstalled])
6007 [buttons_ addObject:UCLocalize("REMOVE")];
6011 switch ([buttons_ count]) {
6012 case 0: title = nil; break;
6013 case 1: title = [buttons_ objectAtIndex:0]; break;
6014 default: title = UCLocalize("MODIFY"); break;
6017 button_ = [[[UIBarButtonItem alloc]
6019 style:UIBarButtonItemStylePlain
6021 action:@selector(customButtonClicked)
6025 - (bool) isLoading {
6026 return commercial_ ? [super isLoading] : false;
6032 /* Package List Controller {{{ */
6033 @interface PackageListController : CyteViewController <
6034 UITableViewDataSource,
6037 _transient Database *database_;
6039 _H<NSArray> packages_;
6040 _H<NSMutableArray> sections_;
6041 _H<UITableView, 2> list_;
6042 _H<NSMutableArray> index_;
6043 _H<NSMutableDictionary> indices_;
6044 _H<NSString> title_;
6045 unsigned reloading_;
6048 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6049 - (void) setDelegate:(id)delegate;
6050 - (void) resetCursor;
6055 @implementation PackageListController
6057 - (bool) isSummarized {
6061 - (bool) showsSections {
6065 - (void) deselectWithAnimation:(BOOL)animated {
6066 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6069 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6070 CGRect base = [[self view] bounds];
6071 base.size.height -= bounds.size.height;
6072 base.origin = [list_ frame].origin;
6074 [UIView beginAnimations:nil context:NULL];
6075 [UIView setAnimationBeginsFromCurrentState:YES];
6076 [UIView setAnimationCurve:curve];
6077 [UIView setAnimationDuration:duration];
6078 [list_ setFrame:base];
6079 [UIView commitAnimations];
6082 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6083 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6086 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6087 [self resizeForKeyboardBounds:bounds duration:0];
6090 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6091 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6092 *curve = UIViewAnimationCurveEaseInOut;
6094 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6096 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6099 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6102 - (void) keyboardWillShow:(NSNotification *)notification {
6105 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6106 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6108 NSTimeInterval duration;
6109 UIViewAnimationCurve curve;
6110 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6112 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);
6113 UIViewController *base = self;
6114 while ([base parentViewController] != nil)
6115 base = [base parentViewController];
6116 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6117 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6119 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6120 intersection.size.height += CYStatusBarHeight();
6122 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6125 - (void) keyboardWillHide:(NSNotification *)notification {
6126 NSTimeInterval duration;
6127 UIViewAnimationCurve curve;
6128 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6130 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6133 - (void) viewWillAppear:(BOOL)animated {
6134 [super viewWillAppear:animated];
6136 [self resizeForKeyboardBounds:CGRectZero];
6137 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6138 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6141 - (void) viewWillDisappear:(BOOL)animated {
6142 [super viewWillDisappear:animated];
6144 [self resizeForKeyboardBounds:CGRectZero];
6145 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6146 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6149 - (void) viewDidAppear:(BOOL)animated {
6150 [super viewDidAppear:animated];
6151 [self deselectWithAnimation:animated];
6154 - (void) didSelectPackage:(Package *)package {
6155 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6156 [view setDelegate:delegate_];
6157 [[self navigationController] pushViewController:view animated:YES];
6160 #if TryIndexedCollation
6161 + (BOOL) hasIndexedCollation {
6162 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6166 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6167 NSInteger count([sections_ count]);
6168 return count == 0 ? 1 : count;
6171 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6172 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6174 return [[sections_ objectAtIndex:section] name];
6177 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6178 if ([sections_ count] == 0)
6180 return [[sections_ objectAtIndex:section] count];
6183 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6184 @synchronized (database_) {
6185 if ([database_ era] != era_)
6188 Section *section([sections_ objectAtIndex:[path section]]);
6189 NSInteger row([path row]);
6190 Package *package([packages_ objectAtIndex:([section row] + row)]);
6191 return [[package retain] autorelease];
6194 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6195 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6197 cell = [[[PackageCell alloc] init] autorelease];
6199 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6200 [cell setPackage:package asSummary:[self isSummarized]];
6204 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6205 Package *package([self packageAtIndexPath:path]);
6206 package = [database_ packageWithName:[package id]];
6207 [self didSelectPackage:package];
6210 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6211 if (![self showsSections])
6217 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6218 #if TryIndexedCollation
6219 if ([[self class] hasIndexedCollation]) {
6220 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6227 - (void) updateHeight {
6228 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6231 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6232 if ((self = [super init]) != nil) {
6233 database_ = database;
6234 title_ = [title copy];
6235 [[self navigationItem] setTitle:title_];
6240 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6242 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6243 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6244 [[self view] addSubview:list_];
6246 // XXX: is 20 the most optimal number here?
6247 [list_ setSectionIndexMinimumDisplayRowCount:20];
6249 [(UITableView *) list_ setDataSource:self];
6250 [list_ setDelegate:self];
6252 [self updateHeight];
6255 - (void) releaseSubviews {
6263 [super releaseSubviews];
6266 - (void) setDelegate:(id)delegate {
6267 delegate_ = delegate;
6270 - (bool) shouldYield {
6274 - (bool) shouldBlock {
6278 - (NSMutableArray *) _reloadPackages {
6279 @synchronized (database_) {
6280 era_ = [database_ era];
6281 NSArray *packages([database_ packages]);
6283 return [NSMutableArray arrayWithArray:packages];
6286 - (void) _reloadData {
6287 if (reloading_ != 0) {
6294 if ([self shouldYield]) {
6298 if (![self shouldBlock])
6301 hud = [delegate_ addProgressHUD];
6302 [hud setText:UCLocalize("LOADING")];
6306 packages = [self yieldToSelector:@selector(_reloadPackages)];
6309 [delegate_ removeProgressHUD:hud];
6310 } while (reloading_ == 2);
6314 packages = [self _reloadPackages];
6317 packages_ = packages;
6319 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6320 sections_ = [NSMutableArray arrayWithCapacity:16];
6322 Section *section = nil;
6324 #if TryIndexedCollation
6325 if ([[self class] hasIndexedCollation]) {
6326 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6328 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6329 NSArray *titles = [collation sectionIndexTitles];
6332 _profile(PackageTable$reloadData$Section)
6333 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6337 _profile(PackageTable$reloadData$Section$Package)
6338 package = [packages_ objectAtIndex:offset];
6339 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6342 while (secidx < index) {
6345 _profile(PackageTable$reloadData$Section$Allocate)
6346 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6349 _profile(PackageTable$reloadData$Section$Add)
6350 [sections_ addObject:section];
6354 [section addToCount];
6360 index_ = [NSMutableArray arrayWithCapacity:32];
6362 bool sectioned([self showsSections]);
6364 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6365 [sections_ addObject:section];
6368 _profile(PackageTable$reloadData$Section)
6369 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6373 _profile(PackageTable$reloadData$Section$Package)
6374 package = [packages_ objectAtIndex:offset];
6375 index = [package index];
6378 if (sectioned && (section == nil || [section index] != index)) {
6379 _profile(PackageTable$reloadData$Section$Allocate)
6380 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6383 [index_ addObject:[section name]];
6384 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6386 _profile(PackageTable$reloadData$Section$Add)
6387 [sections_ addObject:section];
6391 [section addToCount];
6396 [self updateHeight];
6398 _profile(PackageTable$reloadData$List)
6399 [(UITableView *) list_ setDataSource:self];
6404 - (void) reloadData {
6407 if ([self shouldYield])
6408 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6413 - (void) resetCursor {
6414 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6417 - (void) clearData {
6418 [self updateHeight];
6420 [list_ setDataSource:nil];
6428 /* Filtered Package List Controller {{{ */
6429 @interface FilteredPackageListController : PackageListController {
6432 _H<NSObject> object_;
6435 - (void) setObject:(id)object;
6436 - (void) setObject:(id)object forFilter:(SEL)filter;
6439 - (void) setFilter:(SEL)filter;
6441 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6445 @implementation FilteredPackageListController
6451 - (void) setFilter:(SEL)filter {
6452 @synchronized (self) {
6455 /* XXX: this is an unsafe optimization of doomy hell */
6456 Method method(class_getInstanceMethod([Package class], filter));
6457 _assert(method != NULL);
6458 imp_ = method_getImplementation(method);
6459 _assert(imp_ != NULL);
6462 - (void) setObject:(id)object {
6463 @synchronized (self) {
6467 - (void) setObject:(id)object forFilter:(SEL)filter {
6468 @synchronized (self) {
6469 [self setFilter:filter];
6470 [self setObject:object];
6473 - (NSMutableArray *) _reloadPackages {
6474 @synchronized (database_) {
6475 era_ = [database_ era];
6476 NSArray *packages([database_ packages]);
6478 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6482 _H<NSObject> object;
6484 @synchronized (self) {
6490 _profile(PackageTable$reloadData$Filter)
6491 for (Package *package in packages)
6492 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6493 [filtered addObject:package];
6499 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6500 if ((self = [super initWithDatabase:database title:title]) != nil) {
6501 [self setFilter:filter];
6502 [self setObject:object];
6509 /* Home Controller {{{ */
6510 @interface HomeController : CydiaWebViewController {
6515 @implementation HomeController
6518 if ((self = [super init]) != nil) {
6519 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6524 - (NSURL *) navigationURL {
6525 return [NSURL URLWithString:@"cydia://home"];
6528 - (void) didReceiveMemoryWarning {
6531 - (void) aboutButtonClicked {
6532 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6534 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6535 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6536 [alert setCancelButtonIndex:0];
6539 @"Copyright \u00a9 2008-2011\n"
6542 "Jay Freeman (saurik)\n"
6543 "saurik@saurik.com\n"
6544 "http://www.saurik.com/"
6550 - (UIBarButtonItem *) leftButton {
6551 return [[[UIBarButtonItem alloc]
6552 initWithTitle:UCLocalize("ABOUT")
6553 style:UIBarButtonItemStylePlain
6555 action:@selector(aboutButtonClicked)
6561 /* Manage Controller {{{ */
6562 @interface ManageController : CydiaWebViewController {
6565 - (void) queueStatusDidChange;
6569 @implementation ManageController
6572 if ((self = [super init]) != nil) {
6573 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6577 - (NSURL *) navigationURL {
6578 return [NSURL URLWithString:@"cydia://manage"];
6581 - (UIBarButtonItem *) leftButton {
6582 return [[[UIBarButtonItem alloc]
6583 initWithTitle:UCLocalize("SETTINGS")
6584 style:UIBarButtonItemStylePlain
6586 action:@selector(settingsButtonClicked)
6590 - (void) settingsButtonClicked {
6591 [delegate_ showSettings];
6594 - (void) queueButtonClicked {
6598 - (UIBarButtonItem *) rightButton {
6599 return Queuing_ ? [[[UIBarButtonItem alloc]
6600 initWithTitle:UCLocalize("QUEUE")
6601 style:UIBarButtonItemStyleDone
6603 action:@selector(queueButtonClicked)
6604 ] autorelease] : nil;
6607 - (void) queueStatusDidChange {
6608 [self applyRightButton];
6611 - (bool) isLoading {
6612 return !Queuing_ && [super isLoading];
6618 /* Refresh Bar {{{ */
6619 @interface RefreshBar : UINavigationBar {
6620 _H<UIProgressIndicator> indicator_;
6621 _H<UITextLabel> prompt_;
6622 _H<UIProgressBar> progress_;
6623 _H<UINavigationButton> cancel_;
6628 @implementation RefreshBar
6630 - (void) positionViews {
6631 CGRect frame = [cancel_ frame];
6632 frame.size = [cancel_ sizeThatFits:frame.size];
6633 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6634 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6635 [cancel_ setFrame:frame];
6637 CGSize prgsize = {75, 100};
6639 [self frame].size.width - prgsize.width - 10,
6640 ([self frame].size.height - prgsize.height) / 2
6642 [progress_ setFrame:prgrect];
6644 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6645 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6646 CGRect indrect = {{indoffset, indoffset}, indsize};
6647 [indicator_ setFrame:indrect];
6649 CGSize prmsize = {215, indsize.height + 4};
6651 indoffset * 2 + indsize.width,
6652 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6654 [prompt_ setFrame:prmrect];
6657 - (void) setFrame:(CGRect)frame {
6658 [super setFrame:frame];
6659 [self positionViews];
6662 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6663 if ((self = [super initWithFrame:frame]) != nil) {
6664 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6666 [self setBarStyle:UIBarStyleBlack];
6668 UIBarStyle barstyle([self _barStyle:NO]);
6669 bool ugly(barstyle == UIBarStyleDefault);
6671 UIProgressIndicatorStyle style = ugly ?
6672 UIProgressIndicatorStyleMediumBrown :
6673 UIProgressIndicatorStyleMediumWhite;
6675 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6676 [(UIProgressIndicator *) indicator_ setStyle:style];
6677 [indicator_ startAnimation];
6678 [self addSubview:indicator_];
6680 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6681 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6682 [prompt_ setBackgroundColor:[UIColor clearColor]];
6683 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6684 [self addSubview:prompt_];
6686 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6687 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6688 [(UIProgressBar *) progress_ setStyle:0];
6689 [self addSubview:progress_];
6691 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6692 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6693 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6694 [cancel_ setBarStyle:barstyle];
6696 [self positionViews];
6700 - (void) setCancellable:(bool)cancellable {
6702 [self addSubview:cancel_];
6704 [cancel_ removeFromSuperview];
6708 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6709 [progress_ setProgress:0];
6713 [self setCancellable:NO];
6716 - (void) setPrompt:(NSString *)prompt {
6717 [prompt_ setText:prompt];
6720 - (void) setProgress:(float)progress {
6721 [progress_ setProgress:progress];
6727 /* Cydia Navigation Controller Interface {{{ */
6728 @interface UINavigationController (Cydia)
6730 - (NSArray *) navigationURLCollection;
6731 - (void) unloadData;
6736 /* Cydia Tab Bar Controller {{{ */
6737 @interface CYTabBarController : UITabBarController <
6738 UITabBarControllerDelegate,
6741 _transient Database *database_;
6742 _H<RefreshBar, 1> refreshbar_;
6746 // XXX: ok, "updatedelegate_"?...
6747 _transient NSObject<CydiaDelegate> *updatedelegate_;
6749 _H<UIViewController> remembered_;
6750 _transient UIViewController *transient_;
6753 - (NSArray *) navigationURLCollection;
6754 - (void) dropBar:(BOOL)animated;
6755 - (void) beginUpdate;
6756 - (void) raiseBar:(BOOL)animated;
6758 - (void) unloadData;
6762 @implementation CYTabBarController
6764 - (void) setUnselectedViewController:(UIViewController *)transient {
6765 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6766 if (transient != nil) {
6767 if (transient_ == nil)
6768 remembered_ = [controllers objectAtIndex:0];
6769 transient_ = transient;
6770 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6771 [controllers replaceObjectAtIndex:0 withObject:transient_];
6772 [self setSelectedIndex:0];
6773 [self setViewControllers:controllers];
6774 [self concealTabBarSelection];
6775 } else if (remembered_ != nil) {
6776 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6777 transient_ = transient;
6778 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6780 [self setViewControllers:controllers];
6781 [self revealTabBarSelection];
6785 - (UIViewController *) unselectedViewController {
6789 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6790 if ([self unselectedViewController])
6791 [self setUnselectedViewController:nil];
6794 - (NSArray *) navigationURLCollection {
6795 NSMutableArray *items([NSMutableArray array]);
6797 // XXX: Should this deal with transient view controllers?
6798 for (id navigation in [self viewControllers]) {
6799 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6801 [items addObject:stack];
6807 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6808 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6809 [self setUnselectedViewController:nil];
6811 [super dismissModalViewControllerAnimated:YES];
6814 - (void) unloadData {
6817 for (UINavigationController *controller in [self viewControllers])
6818 [controller unloadData];
6820 if (UIViewController *selected = [self selectedViewController])
6821 [selected reloadData];
6823 if (UIViewController *unselected = [self unselectedViewController]) {
6824 [unselected unloadData];
6825 [unselected reloadData];
6830 [[NSNotificationCenter defaultCenter] removeObserver:self];
6835 - (id) initWithDatabase:(Database *)database {
6836 if ((self = [super init]) != nil) {
6837 database_ = database;
6838 [self setDelegate:self];
6840 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6841 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6843 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6847 - (void) setUpdate:(NSDate *)date {
6851 - (void) beginUpdate {
6852 [(RefreshBar *) refreshbar_ start];
6855 [updatedelegate_ retainNetworkActivityIndicator];
6859 detachNewThreadSelector:@selector(performUpdate)
6865 - (void) performUpdate {
6866 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6869 status.setDelegate(self);
6870 [database_ updateWithStatus:status];
6873 performSelectorOnMainThread:@selector(completeUpdate)
6881 - (void) stopUpdateWithSelector:(SEL)selector {
6883 [updatedelegate_ releaseNetworkActivityIndicator];
6885 [self raiseBar:YES];
6888 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6891 - (void) completeUpdate {
6894 [self stopUpdateWithSelector:@selector(reloadData)];
6897 - (void) cancelUpdate {
6898 [self stopUpdateWithSelector:@selector(updateData)];
6901 - (void) cancelPressed {
6902 [self cancelUpdate];
6909 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6910 [refreshbar_ setPrompt:[event compoundMessage]];
6913 - (bool) isProgressCancelled {
6917 - (void) setProgressCancellable:(NSNumber *)cancellable {
6918 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6921 - (void) setProgressPercent:(NSNumber *)percent {
6922 [refreshbar_ setProgress:[percent floatValue]];
6925 - (void) setProgressStatus:(NSDictionary *)status {
6927 [self setProgressPercent:[status objectForKey:@"Percent"]];
6930 - (void) setUpdateDelegate:(id)delegate {
6931 updatedelegate_ = delegate;
6934 - (UIView *) transitionView {
6935 if ([self respondsToSelector:@selector(_transitionView)])
6936 return [self _transitionView];
6938 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6941 - (void) dropBar:(BOOL)animated {
6946 UIView *transition([self transitionView]);
6947 [[self view] addSubview:refreshbar_];
6949 CGRect barframe([refreshbar_ frame]);
6951 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6952 barframe.origin.y = CYStatusBarHeight();
6954 barframe.origin.y = 0;
6956 [refreshbar_ setFrame:barframe];
6959 [UIView beginAnimations:nil context:NULL];
6961 CGRect viewframe = [transition frame];
6962 viewframe.origin.y += barframe.size.height;
6963 viewframe.size.height -= barframe.size.height;
6964 [transition setFrame:viewframe];
6967 [UIView commitAnimations];
6969 // Ensure bar has the proper width for our view, it might have changed
6970 barframe.size.width = viewframe.size.width;
6971 [refreshbar_ setFrame:barframe];
6974 - (void) raiseBar:(BOOL)animated {
6979 UIView *transition([self transitionView]);
6980 [refreshbar_ removeFromSuperview];
6982 CGRect barframe([refreshbar_ frame]);
6985 [UIView beginAnimations:nil context:NULL];
6987 CGRect viewframe = [transition frame];
6988 viewframe.origin.y -= barframe.size.height;
6989 viewframe.size.height += barframe.size.height;
6990 [transition setFrame:viewframe];
6993 [UIView commitAnimations];
6996 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6997 bool dropped(dropped_);
7002 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7008 - (void) statusBarFrameChanged:(NSNotification *)notification {
7018 /* Cydia Navigation Controller Implementation {{{ */
7019 @implementation UINavigationController (Cydia)
7021 - (NSArray *) navigationURLCollection {
7022 NSMutableArray *stack([NSMutableArray array]);
7024 for (CyteViewController *controller in [self viewControllers]) {
7025 NSString *url = [[controller navigationURL] absoluteString];
7027 [stack addObject:url];
7033 - (void) reloadData {
7036 UIViewController *visible([self visibleViewController]);
7038 [visible reloadData];
7040 // on the iPad, this view controller is ALSO visible. :(
7042 if (UIViewController *top = [self topViewController])
7047 - (void) unloadData {
7048 for (CyteViewController *page in [self viewControllers])
7057 /* Cydia:// Protocol {{{ */
7058 @interface CydiaURLProtocol : NSURLProtocol {
7063 @implementation CydiaURLProtocol
7065 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7066 NSURL *url([request URL]);
7070 NSString *scheme([[url scheme] lowercaseString]);
7071 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7073 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7079 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7083 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7084 id<NSURLProtocolClient> client([self client]);
7086 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7088 NSData *data(UIImagePNGRepresentation(icon));
7090 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7091 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7092 [client URLProtocol:self didLoadData:data];
7093 [client URLProtocolDidFinishLoading:self];
7097 - (void) startLoading {
7098 id<NSURLProtocolClient> client([self client]);
7099 NSURLRequest *request([self request]);
7101 NSURL *url([request URL]);
7102 NSString *href([url absoluteString]);
7103 NSString *scheme([[url scheme] lowercaseString]);
7107 if ([scheme isEqualToString:@"cydia"])
7108 path = [href substringFromIndex:8];
7109 else if ([scheme isEqualToString:@"about"])
7110 path = [href substringFromIndex:12];
7111 else _assert(false);
7113 NSRange slash([path rangeOfString:@"/"]);
7116 if (slash.location == NSNotFound) {
7120 command = [path substringToIndex:slash.location];
7121 path = [path substringFromIndex:(slash.location + 1)];
7124 Database *database([Database sharedInstance]);
7126 if ([command isEqualToString:@"package-icon"]) {
7129 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7130 Package *package([database packageWithName:path]);
7134 UIImage *icon([package icon]);
7135 [self _returnPNGWithImage:icon forRequest:request];
7136 } else if ([command isEqualToString:@"uikit-image"]) {
7139 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7140 UIImage *icon(_UIImageWithName(path));
7141 [self _returnPNGWithImage:icon forRequest:request];
7142 } else if ([command isEqualToString:@"section-icon"]) {
7145 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7146 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7148 icon = [UIImage applicationImageNamed:@"unknown.png"];
7149 [self _returnPNGWithImage:icon forRequest:request];
7151 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7155 - (void) stopLoading {
7161 /* Section Controller {{{ */
7162 @interface SectionController : FilteredPackageListController {
7163 _H<NSString> section_;
7166 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7170 @implementation SectionController
7172 - (NSURL *) navigationURL {
7173 NSString *name = section_;
7177 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7180 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7183 title = UCLocalize("ALL_PACKAGES");
7184 else if (![name isEqual:@""])
7185 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7187 title = UCLocalize("NO_SECTION");
7189 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7196 /* Sections Controller {{{ */
7197 @interface SectionsController : CyteViewController <
7198 UITableViewDataSource,
7201 _transient Database *database_;
7202 _H<NSMutableArray> sections_;
7203 _H<NSMutableArray> filtered_;
7204 _H<UITableView, 2> list_;
7207 - (id) initWithDatabase:(Database *)database;
7208 - (void) editButtonClicked;
7212 @implementation SectionsController
7214 - (NSURL *) navigationURL {
7215 return [NSURL URLWithString:@"cydia://sections"];
7218 - (void) updateNavigationItem {
7219 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7220 if ([sections_ count] == 0) {
7221 [[self navigationItem] setRightBarButtonItem:nil];
7223 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7224 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7226 action:@selector(editButtonClicked)
7227 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7231 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7232 [super setEditing:editing animated:animated];
7237 [delegate_ updateData];
7239 [self updateNavigationItem];
7242 - (void) viewDidAppear:(BOOL)animated {
7243 [super viewDidAppear:animated];
7244 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7247 - (void) viewWillDisappear:(BOOL)animated {
7248 [super viewWillDisappear:animated];
7249 if ([self isEditing]) [self setEditing:NO];
7252 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7253 Section *section = nil;
7254 int index = [indexPath row];
7255 if (![self isEditing]) {
7258 section = [filtered_ objectAtIndex:index];
7260 section = [sections_ objectAtIndex:index];
7265 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7266 if ([self isEditing])
7267 return [sections_ count];
7269 return [filtered_ count] + 1;
7272 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7276 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7277 static NSString *reuseIdentifier = @"SectionCell";
7279 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7281 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7283 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7288 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7289 if ([self isEditing])
7292 Section *section = [self sectionAtIndexPath:indexPath];
7294 SectionController *controller = [[[SectionController alloc]
7295 initWithDatabase:database_
7296 section:[section name]
7298 [controller setDelegate:delegate_];
7300 [[self navigationController] pushViewController:controller animated:YES];
7304 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7306 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7307 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7308 [list_ setRowHeight:45.0f];
7309 [(UITableView *) list_ setDataSource:self];
7310 [list_ setDelegate:self];
7311 [[self view] addSubview:list_];
7314 - (void) viewDidLoad {
7315 [super viewDidLoad];
7317 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7320 - (void) releaseSubviews {
7326 [super releaseSubviews];
7329 - (id) initWithDatabase:(Database *)database {
7330 if ((self = [super init]) != nil) {
7331 database_ = database;
7335 - (void) reloadData {
7338 NSArray *packages = [database_ packages];
7340 sections_ = [NSMutableArray arrayWithCapacity:16];
7341 filtered_ = [NSMutableArray arrayWithCapacity:16];
7343 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7346 for (Package *package in packages) {
7347 NSString *name([package section]);
7348 NSString *key(name == nil ? @"" : name);
7352 _profile(SectionsView$reloadData$Section)
7353 section = [sections objectForKey:key];
7354 if (section == nil) {
7355 _profile(SectionsView$reloadData$Section$Allocate)
7356 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7357 [sections setObject:section forKey:key];
7362 [section addToCount];
7364 _profile(SectionsView$reloadData$Filter)
7365 if (![package valid] || ![package visible])
7373 [sections_ addObjectsFromArray:[sections allValues]];
7375 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7377 for (Section *section in (id) sections_) {
7378 size_t count([section row]);
7382 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7383 [section setCount:count];
7384 [filtered_ addObject:section];
7387 [self updateNavigationItem];
7392 - (void) editButtonClicked {
7393 [self setEditing:![self isEditing] animated:YES];
7399 /* Changes Controller {{{ */
7400 @interface ChangesController : CyteViewController <
7401 UITableViewDataSource,
7404 _transient Database *database_;
7406 _H<NSArray> packages_;
7407 _H<NSMutableArray> sections_;
7408 _H<UITableView, 2> list_;
7412 - (id) initWithDatabase:(Database *)database;
7416 @implementation ChangesController
7418 - (NSURL *) navigationURL {
7419 return [NSURL URLWithString:@"cydia://changes"];
7422 - (void) viewDidAppear:(BOOL)animated {
7423 [super viewDidAppear:animated];
7424 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7427 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7428 NSInteger count([sections_ count]);
7429 return count == 0 ? 1 : count;
7432 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7433 if ([sections_ count] == 0)
7435 return [[sections_ objectAtIndex:section] name];
7438 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7439 if ([sections_ count] == 0)
7441 return [[sections_ objectAtIndex:section] count];
7444 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7445 @synchronized (database_) {
7446 if ([database_ era] != era_)
7449 NSUInteger sectionIndex([path section]);
7450 if (sectionIndex >= [sections_ count])
7452 Section *section([sections_ objectAtIndex:sectionIndex]);
7453 NSInteger row([path row]);
7454 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7457 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7458 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7460 cell = [[[PackageCell alloc] init] autorelease];
7462 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7463 [cell setPackage:package asSummary:false];
7467 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7468 Package *package([self packageAtIndexPath:path]);
7469 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7470 [view setDelegate:delegate_];
7471 [[self navigationController] pushViewController:view animated:YES];
7475 - (void) refreshButtonClicked {
7476 [delegate_ beginUpdate];
7477 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7480 - (void) upgradeButtonClicked {
7481 [delegate_ distUpgrade];
7482 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7486 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7488 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7489 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7490 [list_ setRowHeight:73];
7491 [(UITableView *) list_ setDataSource:self];
7492 [list_ setDelegate:self];
7493 [[self view] addSubview:list_];
7496 - (void) viewDidLoad {
7497 [super viewDidLoad];
7499 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7502 - (void) releaseSubviews {
7508 [super releaseSubviews];
7511 - (id) initWithDatabase:(Database *)database {
7512 if ((self = [super init]) != nil) {
7513 database_ = database;
7517 - (NSMutableArray *) _reloadPackages {
7518 @synchronized (database_) {
7519 era_ = [database_ era];
7520 NSArray *packages([database_ packages]);
7522 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7525 _profile(ChangesController$_reloadPackages$Filter)
7526 for (Package *package in packages)
7527 if ([package upgradableAndEssential:YES] || [package visible])
7528 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7531 _profile(ChangesController$_reloadPackages$radixSort)
7532 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7539 - (void) _reloadData {
7544 UIProgressHUD *hud([delegate_ addProgressHUD]);
7545 [hud setText:UCLocalize("LOADING")];
7546 //NSLog(@"HUD:%@::%@", delegate_, hud);
7547 packages = [self yieldToSelector:@selector(_reloadPackages)];
7548 [delegate_ removeProgressHUD:hud];
7550 packages = [self _reloadPackages];
7553 @synchronized (database_) {
7554 if (era_ != [database_ era])
7557 packages_ = packages;
7558 sections_ = [NSMutableArray arrayWithCapacity:16];
7560 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7561 Section *ignored = nil;
7562 Section *section = nil;
7566 bool unseens = false;
7568 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7570 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7571 Package *package = [packages_ objectAtIndex:offset];
7573 BOOL uae = [package upgradableAndEssential:YES];
7577 time_t seen([package seen]);
7579 if (section == nil || last != seen) {
7583 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7586 _profile(ChangesController$reloadData$Allocate)
7587 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7588 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7589 [sections_ addObject:section];
7593 [section addToCount];
7594 } else if ([package ignored]) {
7595 if (ignored == nil) {
7596 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7598 [ignored addToCount];
7601 [upgradable addToCount];
7606 CFRelease(formatter);
7609 Section *last = [sections_ lastObject];
7610 size_t count = [last count];
7611 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7612 [sections_ removeLastObject];
7615 if ([ignored count] != 0)
7616 [sections_ insertObject:ignored atIndex:0];
7618 [sections_ insertObject:upgradable atIndex:0];
7622 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7623 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7624 style:UIBarButtonItemStylePlain
7626 action:@selector(upgradeButtonClicked)
7627 ] autorelease]) animated:YES];
7629 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7630 initWithTitle:UCLocalize("REFRESH")
7631 style:UIBarButtonItemStylePlain
7633 action:@selector(refreshButtonClicked)
7634 ] autorelease]) animated:YES];
7639 - (void) reloadData {
7641 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7646 /* Search Controller {{{ */
7647 @interface SearchController : FilteredPackageListController <
7650 _H<UISearchBar, 1> search_;
7654 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7655 - (void) reloadData;
7659 @implementation SearchController
7661 - (NSURL *) navigationURL {
7662 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7663 return [NSURL URLWithString:@"cydia://search"];
7665 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7668 - (void) useSearch {
7669 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7674 - (void) viewWillAppear:(BOOL)animated {
7675 [super viewWillAppear:animated];
7677 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7681 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7682 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7687 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7688 [search_ resignFirstResponder];
7692 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7693 [search_ setText:@""];
7694 [self searchBarButtonClicked:searchBar];
7697 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7698 [self searchBarButtonClicked:searchBar];
7701 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7702 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7706 - (bool) shouldYield {
7710 - (bool) shouldBlock {
7711 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7714 - (bool) isSummarized {
7715 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7718 - (bool) showsSections {
7722 - (NSMutableArray *) _reloadPackages {
7723 NSMutableArray *packages([super _reloadPackages]);
7724 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7725 [packages radixSortUsingSelector:@selector(rank)];
7729 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7730 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7731 search_ = [[[UISearchBar alloc] init] autorelease];
7732 [search_ setDelegate:self];
7735 [search_ setText:query];
7739 - (void) viewDidAppear:(BOOL)animated {
7740 [super viewDidAppear:animated];
7742 if (!searchloaded_) {
7743 searchloaded_ = YES;
7744 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7745 [search_ layoutSubviews];
7746 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7748 UITextField *textField;
7749 if ([search_ respondsToSelector:@selector(searchField)])
7750 textField = [search_ searchField];
7752 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7754 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7755 [textField setEnablesReturnKeyAutomatically:NO];
7756 [[self navigationItem] setTitleView:textField];
7760 - (void) reloadData {
7761 id object([search_ text]);
7762 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7763 object = [object componentsSeparatedByString:@" "];
7765 [self setObject:object];
7771 - (void) didSelectPackage:(Package *)package {
7772 [search_ resignFirstResponder];
7773 [super didSelectPackage:package];
7778 /* Package Settings Controller {{{ */
7779 @interface PackageSettingsController : CyteViewController <
7780 UITableViewDataSource,
7783 _transient Database *database_;
7785 _H<Package> package_;
7786 _H<UITableView, 2> table_;
7787 _H<UISwitch> subscribedSwitch_;
7788 _H<UISwitch> ignoredSwitch_;
7789 _H<UITableViewCell> subscribedCell_;
7790 _H<UITableViewCell> ignoredCell_;
7793 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7797 @implementation PackageSettingsController
7799 - (NSURL *) navigationURL {
7800 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7803 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7804 if (package_ == nil)
7807 if ([package_ installed] == nil)
7813 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7814 if (package_ == nil)
7817 // both sections contain just one item right now.
7821 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7825 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7827 return UCLocalize("SHOW_ALL_CHANGES_EX");
7829 return UCLocalize("IGNORE_UPGRADES_EX");
7832 - (void) onSubscribed:(id)control {
7833 bool value([control isOn]);
7834 if (package_ == nil)
7836 if ([package_ setSubscribed:value])
7837 [delegate_ updateData];
7840 - (void) _updateIgnored {
7841 const char *package([name_ UTF8String]);
7842 bool on([ignoredSwitch_ isOn]);
7844 pid_t pid(ExecFork());
7846 FILE *dpkg(popen("dpkg --set-selections", "w"));
7847 fwrite(package, strlen(package), 1, dpkg);
7850 fwrite(" hold\n", 6, 1, dpkg);
7852 fwrite(" install\n", 9, 1, dpkg);
7863 - (void) onIgnored:(id)control {
7864 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7865 [invocation setTarget:self];
7866 [invocation setSelector:@selector(_updateIgnored)];
7868 [delegate_ reloadDataWithInvocation:invocation];
7871 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7872 if (package_ == nil)
7875 switch ([indexPath section]) {
7876 case 0: return subscribedCell_;
7877 case 1: return ignoredCell_;
7886 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7888 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7889 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7890 [(UITableView *) table_ setDataSource:self];
7891 [table_ setDelegate:self];
7892 [[self view] addSubview:table_];
7894 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7895 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7896 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7898 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7899 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7900 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7902 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7903 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7904 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7905 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7907 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7908 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7909 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7910 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7913 - (void) viewDidLoad {
7914 [super viewDidLoad];
7916 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7919 - (void) releaseSubviews {
7921 subscribedCell_ = nil;
7923 ignoredSwitch_ = nil;
7924 subscribedSwitch_ = nil;
7926 [super releaseSubviews];
7929 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7930 if ((self = [super init]) != nil) {
7931 database_ = database;
7936 - (void) reloadData {
7939 package_ = [database_ packageWithName:name_];
7941 if (package_ != nil) {
7942 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7943 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7944 } // XXX: what now, G?
7946 [table_ reloadData];
7952 /* Installed Controller {{{ */
7953 @interface InstalledController : FilteredPackageListController {
7957 - (id) initWithDatabase:(Database *)database;
7959 - (void) updateRoleButton;
7960 - (void) queueStatusDidChange;
7964 @implementation InstalledController
7966 - (NSURL *) navigationURL {
7967 return [NSURL URLWithString:@"cydia://installed"];
7970 - (id) initWithDatabase:(Database *)database {
7971 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7972 [self updateRoleButton];
7973 [self queueStatusDidChange];
7978 - (void) queueButtonClicked {
7983 - (void) queueStatusDidChange {
7987 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7988 initWithTitle:UCLocalize("QUEUE")
7989 style:UIBarButtonItemStyleDone
7991 action:@selector(queueButtonClicked)
7994 [[self navigationItem] setLeftBarButtonItem:nil];
8000 - (void) updateRoleButton {
8001 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8002 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8003 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8004 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8006 action:@selector(roleButtonClicked)
8010 - (void) roleButtonClicked {
8011 [self setObject:[NSNumber numberWithBool:expert_]];
8015 [self updateRoleButton];
8021 /* Source Cell {{{ */
8022 @interface SourceCell : CyteTableViewCell <
8023 CyteTableViewCellDelegate
8027 _H<NSString> origin_;
8028 _H<NSString> label_;
8031 - (void) setSource:(Source *)source;
8035 @implementation SourceCell
8037 - (void) _setImage:(NSArray *)data {
8038 if ([url_ isEqual:[data objectAtIndex:0]]) {
8039 icon_ = [data objectAtIndex:1];
8040 [content_ setNeedsDisplay];
8044 - (void) _setSource:(NSURL *) url {
8045 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8047 if (NSData *data = [NSURLConnection
8048 sendSynchronousRequest:[NSURLRequest
8050 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8054 returningResponse:NULL
8057 if (UIImage *image = [UIImage imageWithData:data])
8058 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8063 - (void) setSource:(Source *)source {
8064 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8066 origin_ = [source name];
8067 label_ = [source rooturi];
8069 [content_ setNeedsDisplay];
8071 url_ = [source iconURL];
8072 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8075 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8076 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8077 UIView *content([self contentView]);
8078 CGRect bounds([content bounds]);
8080 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8081 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8082 [content_ setBackgroundColor:[UIColor whiteColor]];
8083 [content addSubview:content_];
8085 [content_ setDelegate:self];
8086 [content_ setOpaque:YES];
8088 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8092 - (NSString *) accessibilityLabel {
8096 - (void) drawContentRect:(CGRect)rect {
8097 bool highlighted(highlighted_);
8098 float width(rect.size.width);
8102 rect.size = [(UIImage *) icon_ size];
8104 while (rect.size.width > 32 || rect.size.height > 32) {
8105 rect.size.width /= 2;
8106 rect.size.height /= 2;
8109 rect.origin.x = 25 - rect.size.width / 2;
8110 rect.origin.y = 25 - rect.size.height / 2;
8112 [icon_ drawInRect:rect];
8120 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8124 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8129 /* Source Controller {{{ */
8130 @interface SourceController : FilteredPackageListController {
8131 _transient Source *source_;
8135 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8139 @implementation SourceController
8141 - (NSURL *) navigationURL {
8142 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8145 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8146 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8148 key_ = [source key];
8152 - (void) reloadData {
8153 source_ = [database_ sourceWithKey:key_];
8154 key_ = [source_ key];
8155 [self setObject:source_];
8157 [[self navigationItem] setTitle:[source_ label]];
8164 /* Sources Controller {{{ */
8165 @interface SourcesController : CyteViewController <
8166 UITableViewDataSource,
8169 _transient Database *database_;
8172 _H<UITableView, 2> list_;
8173 _H<NSMutableArray> sources_;
8177 _H<UIProgressHUD> hud_;
8180 //NSURLConnection *installer_;
8181 NSURLConnection *trivial_;
8182 NSURLConnection *trivial_bz2_;
8183 NSURLConnection *trivial_gz_;
8184 //NSURLConnection *automatic_;
8189 - (id) initWithDatabase:(Database *)database;
8190 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8194 @implementation SourcesController
8196 - (void) _releaseConnection:(NSURLConnection *)connection {
8197 if (connection != nil) {
8198 [connection cancel];
8199 //[connection setDelegate:nil];
8200 [connection release];
8205 //[self _releaseConnection:installer_];
8206 [self _releaseConnection:trivial_];
8207 [self _releaseConnection:trivial_gz_];
8208 [self _releaseConnection:trivial_bz2_];
8209 //[self _releaseConnection:automatic_];
8214 - (NSURL *) navigationURL {
8215 return [NSURL URLWithString:@"cydia://sources"];
8218 - (void) viewDidAppear:(BOOL)animated {
8219 [super viewDidAppear:animated];
8220 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8223 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8227 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8231 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8232 return [sources_ count];
8235 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8236 @synchronized (database_) {
8237 if ([database_ era] != era_)
8240 return [sources_ objectAtIndex:[indexPath row]];
8243 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8244 static NSString *cellIdentifier = @"SourceCell";
8246 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8247 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8248 [cell setSource:[self sourceAtIndexPath:indexPath]];
8249 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8254 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8255 Source *source = [self sourceAtIndexPath:indexPath];
8257 SourceController *controller = [[[SourceController alloc]
8258 initWithDatabase:database_
8262 [controller setDelegate:delegate_];
8264 [[self navigationController] pushViewController:controller animated:YES];
8267 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8268 Source *source = [self sourceAtIndexPath:indexPath];
8269 return [source record] != nil;
8272 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8273 if (editingStyle == UITableViewCellEditingStyleDelete) {
8274 Source *source = [self sourceAtIndexPath:indexPath];
8275 [Sources_ removeObjectForKey:[source key]];
8276 [delegate_ syncData];
8281 [delegate_ addTrivialSource:href_];
8284 [delegate_ syncData];
8287 - (NSString *) getWarning {
8288 NSString *href(href_);
8289 NSRange colon([href rangeOfString:@"://"]);
8290 if (colon.location != NSNotFound)
8291 href = [href substringFromIndex:(colon.location + 3)];
8292 href = [href stringByAddingPercentEscapes];
8293 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8295 NSURL *url([NSURL URLWithString:href]);
8297 NSStringEncoding encoding;
8298 NSError *error(nil);
8300 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8301 return [warning length] == 0 ? nil : warning;
8305 - (void) _endConnection:(NSURLConnection *)connection {
8306 // XXX: the memory management in this method is horribly awkward
8308 NSURLConnection **field = NULL;
8309 if (connection == trivial_)
8311 else if (connection == trivial_bz2_)
8312 field = &trivial_bz2_;
8313 else if (connection == trivial_gz_)
8314 field = &trivial_gz_;
8315 _assert(field != NULL);
8316 [connection release];
8321 trivial_bz2_ == nil &&
8324 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8326 [delegate_ releaseNetworkActivityIndicator];
8328 [delegate_ removeProgressHUD:hud_];
8332 if (warning != nil) {
8333 UIAlertView *alert = [[[UIAlertView alloc]
8334 initWithTitle:UCLocalize("SOURCE_WARNING")
8337 cancelButtonTitle:UCLocalize("CANCEL")
8339 UCLocalize("ADD_ANYWAY"),
8343 [alert setContext:@"warning"];
8344 [alert setNumberOfRows:1];
8347 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8353 } else if (error_ != nil) {
8354 UIAlertView *alert = [[[UIAlertView alloc]
8355 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8356 message:[error_ localizedDescription]
8358 cancelButtonTitle:UCLocalize("OK")
8359 otherButtonTitles:nil
8362 [alert setContext:@"urlerror"];
8367 UIAlertView *alert = [[[UIAlertView alloc]
8368 initWithTitle:UCLocalize("NOT_REPOSITORY")
8369 message:UCLocalize("NOT_REPOSITORY_EX")
8371 cancelButtonTitle:UCLocalize("OK")
8372 otherButtonTitles:nil
8375 [alert setContext:@"trivial"];
8385 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8386 switch ([response statusCode]) {
8392 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8393 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8395 [self _endConnection:connection];
8398 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8399 [self _endConnection:connection];
8402 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8403 NSURL *url([NSURL URLWithString:href]);
8405 NSMutableURLRequest *request = [NSMutableURLRequest
8407 cachePolicy:NSURLRequestUseProtocolCachePolicy
8408 timeoutInterval:120.0
8411 [request setHTTPMethod:method];
8413 if (Machine_ != NULL)
8414 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8416 if ([url isCydiaSecure]) {
8417 if (UniqueID_ != nil) {
8418 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8419 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8423 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8426 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8427 NSString *context([alert context]);
8429 if ([context isEqualToString:@"source"]) {
8432 NSString *href = [[alert textField] text];
8434 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8436 if (![href hasSuffix:@"/"])
8437 href_ = [href stringByAppendingString:@"/"];
8441 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8442 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8443 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8444 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8448 // XXX: this is stupid
8449 hud_ = [delegate_ addProgressHUD];
8450 [hud_ setText:UCLocalize("VERIFYING_URL")];
8451 [delegate_ retainNetworkActivityIndicator];
8460 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8461 } else if ([context isEqualToString:@"trivial"])
8462 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8463 else if ([context isEqualToString:@"urlerror"])
8464 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8465 else if ([context isEqualToString:@"warning"]) {
8468 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8477 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8482 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8484 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8485 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8486 [list_ setRowHeight:53];
8487 [(UITableView *) list_ setDataSource:self];
8488 [list_ setDelegate:self];
8489 [[self view] addSubview:list_];
8492 - (void) viewDidLoad {
8493 [super viewDidLoad];
8495 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8496 [self updateButtonsForEditingStatus:NO animated:NO];
8499 - (void) releaseSubviews {
8504 [super releaseSubviews];
8507 - (id) initWithDatabase:(Database *)database {
8508 if ((self = [super init]) != nil) {
8509 database_ = database;
8513 - (void) reloadData {
8516 @synchronized (database_) {
8517 era_ = [database_ era];
8520 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8523 sources_ = [NSMutableArray arrayWithCapacity:16];
8524 [sources_ addObjectsFromArray:[database_ sources]];
8526 [sources_ sortUsingSelector:@selector(compareByName:)];
8529 int count([sources_ count]);
8531 for (int i = 0; i != count; i++) {
8532 if ([[sources_ objectAtIndex:i] record] == nil)
8537 [list_ setEditing:NO];
8538 [self updateButtonsForEditingStatus:NO animated:NO];
8542 - (void) showAddSourcePrompt {
8543 UIAlertView *alert = [[[UIAlertView alloc]
8544 initWithTitle:UCLocalize("ENTER_APT_URL")
8547 cancelButtonTitle:UCLocalize("CANCEL")
8549 UCLocalize("ADD_SOURCE"),
8553 [alert setContext:@"source"];
8555 [alert setNumberOfRows:1];
8556 [alert addTextFieldWithValue:@"http://" label:@""];
8558 UITextInputTraits *traits = [[alert textField] textInputTraits];
8559 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8560 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8561 [traits setKeyboardType:UIKeyboardTypeURL];
8562 // XXX: UIReturnKeyDone
8563 [traits setReturnKeyType:UIReturnKeyNext];
8568 - (void) addButtonClicked {
8569 [self showAddSourcePrompt];
8572 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8573 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8574 initWithTitle:UCLocalize("ADD")
8575 style:UIBarButtonItemStylePlain
8577 action:@selector(addButtonClicked)
8578 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8580 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8581 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8582 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8584 action:@selector(editButtonClicked)
8585 ] autorelease] animated:animated];
8587 if (IsWildcat_ && !editing)
8588 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8589 initWithTitle:UCLocalize("SETTINGS")
8590 style:UIBarButtonItemStylePlain
8592 action:@selector(settingsButtonClicked)
8596 - (void) settingsButtonClicked {
8597 [delegate_ showSettings];
8600 - (void) editButtonClicked {
8601 [list_ setEditing:![list_ isEditing] animated:YES];
8603 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8609 /* Settings Controller {{{ */
8610 @interface SettingsController : CyteViewController <
8611 UITableViewDataSource,
8614 _transient Database *database_;
8615 // XXX: ok, "roledelegate_"?...
8616 _transient id roledelegate_;
8617 _H<UITableView, 2> table_;
8618 _H<UISegmentedControl> segment_;
8619 _H<UIView> container_;
8622 - (void) showDoneButton;
8623 - (void) resizeSegmentedControl;
8627 @implementation SettingsController
8630 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8632 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8633 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8634 [table_ setDelegate:self];
8635 [(UITableView *) table_ setDataSource:self];
8636 [[self view] addSubview:table_];
8638 NSArray *items = [NSArray arrayWithObjects:
8640 UCLocalize("HACKER"),
8641 UCLocalize("DEVELOPER"),
8643 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8644 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8645 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8646 [container_ addSubview:segment_];
8649 - (void) viewDidLoad {
8650 [super viewDidLoad];
8652 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8655 if ([Role_ isEqualToString:@"User"]) index = 0;
8656 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8657 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8659 [segment_ setSelectedSegmentIndex:index];
8660 [self showDoneButton];
8663 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8664 [self resizeSegmentedControl];
8667 - (void) releaseSubviews {
8672 [super releaseSubviews];
8675 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8676 if ((self = [super init]) != nil) {
8677 database_ = database;
8678 roledelegate_ = delegate;
8682 - (void) resizeSegmentedControl {
8683 CGFloat width = [[self view] frame].size.width;
8684 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8687 - (void) viewWillAppear:(BOOL)animated {
8688 [super viewWillAppear:animated];
8690 [self resizeSegmentedControl];
8693 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8694 [self resizeSegmentedControl];
8697 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8698 [self resizeSegmentedControl];
8702 NSString *role(nil);
8704 switch ([segment_ selectedSegmentIndex]) {
8705 case 0: role = @"User"; break;
8706 case 1: role = @"Hacker"; break;
8707 case 2: role = @"Developer"; break;
8712 if (![role isEqualToString:Role_]) {
8713 bool rolling(Role_ == nil);
8716 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8720 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8724 [roledelegate_ loadData];
8726 [roledelegate_ updateData];
8730 - (void) segmentChanged:(UISegmentedControl *)control {
8731 [self showDoneButton];
8734 - (void) saveAndClose {
8737 [[self navigationItem] setRightBarButtonItem:nil];
8738 [[self navigationController] dismissModalViewControllerAnimated:YES];
8741 - (void) doneButtonClicked {
8742 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8743 [spinner startAnimating];
8744 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8745 [[self navigationItem] setRightBarButtonItem:spinItem];
8747 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8750 - (void) showDoneButton {
8751 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8752 initWithTitle:UCLocalize("DONE")
8753 style:UIBarButtonItemStyleDone
8755 action:@selector(doneButtonClicked)
8756 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8759 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8760 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8764 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8768 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8769 return nil; // This method is required by the protocol.
8772 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8774 return UCLocalize("ROLE_EX");
8776 return [NSString stringWithFormat:
8777 @"%@: %@\n%@: %@\n%@: %@",
8778 UCLocalize("USER"), UCLocalize("USER_EX"),
8779 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8780 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8785 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8786 return section == 3 ? 44.0f : 0;
8789 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8790 return section == 3 ? container_ : nil;
8793 - (void) reloadData {
8796 [table_ reloadData];
8801 /* Stash Controller {{{ */
8802 @interface StashController : CyteViewController {
8803 _H<UIActivityIndicatorView> spinner_;
8804 _H<UILabel> status_;
8805 _H<UILabel> caption_;
8810 @implementation StashController
8813 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8814 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8816 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8817 CGRect spinrect = [spinner_ frame];
8818 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8819 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8820 [spinner_ setFrame:spinrect];
8821 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8822 [[self view] addSubview:spinner_];
8823 [spinner_ startAnimating];
8826 captrect.size.width = [[self view] frame].size.width;
8827 captrect.size.height = 40.0f;
8828 captrect.origin.x = 0;
8829 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8830 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8831 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8832 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8833 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8834 [caption_ setTextColor:[UIColor whiteColor]];
8835 [caption_ setBackgroundColor:[UIColor clearColor]];
8836 [caption_ setShadowColor:[UIColor blackColor]];
8837 [caption_ setTextAlignment:UITextAlignmentCenter];
8838 [[self view] addSubview:caption_];
8841 statusrect.size.width = [[self view] frame].size.width;
8842 statusrect.size.height = 30.0f;
8843 statusrect.origin.x = 0;
8844 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8845 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8846 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8847 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8848 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8849 [status_ setTextColor:[UIColor whiteColor]];
8850 [status_ setBackgroundColor:[UIColor clearColor]];
8851 [status_ setShadowColor:[UIColor blackColor]];
8852 [status_ setTextAlignment:UITextAlignmentCenter];
8853 [[self view] addSubview:status_];
8856 - (void) releaseSubviews {
8861 [super releaseSubviews];
8867 @interface CYURLCache : SDURLCache {
8872 @implementation CYURLCache
8874 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8877 else if ([event isEqualToString:@"no-cache"])
8879 else if ([event isEqualToString:@"store"])
8881 else if ([event isEqualToString:@"invalid"])
8883 else if ([event isEqualToString:@"memory"])
8885 else if ([event isEqualToString:@"disk"])
8887 else if ([event isEqualToString:@"miss"])
8890 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8894 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8895 if (NSURLResponse *response = [cached response])
8896 if (NSString *mime = [response MIMEType])
8897 if ([mime isEqualToString:@"text/cache-manifest"]) {
8898 NSURL *url([response URL]);
8901 NSLog(@"###: %@", [url absoluteString]);
8904 @synchronized (HostConfig_) {
8905 [CachedURLs_ addObject:url];
8909 [super storeCachedResponse:cached forRequest:request];
8914 @interface Cydia : UIApplication <
8915 ConfirmationControllerDelegate,
8918 UINavigationControllerDelegate,
8919 UITabBarControllerDelegate
8921 _H<UIWindow> window_;
8922 _H<CYTabBarController> tabbar_;
8923 _H<CydiaLoadingViewController> emulated_;
8925 _H<NSMutableArray> essential_;
8926 _H<NSMutableArray> broken_;
8928 Database *database_;
8930 _H<NSURL> starturl_;
8935 _H<StashController> stash_;
8944 @implementation Cydia
8946 - (void) beginUpdate {
8947 [tabbar_ beginUpdate];
8951 return [tabbar_ updating];
8955 if ([broken_ count] != 0) {
8956 int count = [broken_ count];
8958 UIAlertView *alert = [[[UIAlertView alloc]
8959 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8960 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8962 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8964 UCLocalize("TEMPORARY_IGNORE"),
8968 [alert setContext:@"fixhalf"];
8969 [alert setNumberOfRows:2];
8971 } else if (!Ignored_ && [essential_ count] != 0) {
8972 int count = [essential_ count];
8974 UIAlertView *alert = [[[UIAlertView alloc]
8975 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8976 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8978 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8980 UCLocalize("UPGRADE_ESSENTIAL"),
8981 UCLocalize("COMPLETE_UPGRADE"),
8985 [alert setContext:@"upgrade"];
8990 - (void) returnToCydia {
8994 - (void) _saveConfig {
8995 @synchronized (database_) {
9002 NSString *error(nil);
9004 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9006 NSError *error(nil);
9007 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9008 NSLog(@"failure to save metadata data: %@", error);
9013 NSLog(@"failure to serialize metadata: %@", error);
9017 CydiaWriteSources();
9020 // Navigation controller for the queuing badge.
9021 - (UINavigationController *) queueNavigationController {
9022 NSArray *controllers = [tabbar_ viewControllers];
9023 return [controllers objectAtIndex:3];
9026 - (void) unloadData {
9027 [tabbar_ unloadData];
9030 - (void) _updateData {
9034 UINavigationController *navigation = [self queueNavigationController];
9036 id queuedelegate = nil;
9037 if ([[navigation viewControllers] count] > 0)
9038 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9040 [queuedelegate queueStatusDidChange];
9041 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9044 - (void) _refreshIfPossible:(NSDate *)update {
9045 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9047 bool recently = false;
9048 if (update != nil) {
9049 NSTimeInterval interval([update timeIntervalSinceNow]);
9050 if (interval <= 0 && interval > -(15*60))
9054 // Don't automatic refresh if:
9055 // - We already refreshed recently.
9056 // - We already auto-refreshed this launch.
9057 // - Auto-refresh is disabled.
9058 if (recently || loaded_ || ManualRefresh) {
9059 // If we are cancelling, we need to make sure it knows it's already loaded.
9062 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9064 // We are going to load, so remember that.
9067 SCNetworkReachabilityFlags flags; {
9068 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9069 SCNetworkReachabilityGetFlags(reachability, &flags);
9070 CFRelease(reachability);
9073 // XXX: this elaborate mess is what Apple is using to determine this? :(
9074 // XXX: do we care if the user has to intervene? maybe that's ok?
9076 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9077 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9078 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9079 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9080 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9081 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9085 // If we can reach the server, auto-refresh!
9087 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9093 - (void) refreshIfPossible {
9094 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9097 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9098 @synchronized (self) {
9099 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9100 [hud setText:UCLocalize("RELOADING_DATA")];
9102 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9106 [essential_ removeAllObjects];
9107 [broken_ removeAllObjects];
9109 NSArray *packages([database_ packages]);
9110 for (Package *package in packages) {
9112 [broken_ addObject:package];
9113 if ([package upgradableAndEssential:NO]) {
9114 if ([package essential])
9115 [essential_ addObject:package];
9120 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9123 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9124 [changesItem setBadgeValue:badge];
9125 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9126 [self setApplicationIconBadgeNumber:changes];
9129 [changesItem setBadgeValue:nil];
9130 [changesItem setAnimatedBadge:NO];
9131 [self setApplicationIconBadgeNumber:0];
9137 [self removeProgressHUD:hud];
9140 - (void) updateData {
9146 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9149 - (void) disemulate {
9150 if (emulated_ == nil)
9153 [window_ addSubview:[tabbar_ view]];
9154 [[emulated_ view] removeFromSuperview];
9156 [window_ setUserInteractionEnabled:YES];
9159 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9160 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9162 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9164 UIViewController *parent;
9165 if (emulated_ == nil)
9174 [parent presentModalViewController:navigation animated:YES];
9177 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9178 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9180 if (navigation != nil)
9181 [navigation pushViewController:progress animated:YES];
9183 [self presentModalViewController:progress force:YES];
9185 [progress invoke:invocation withTitle:title];
9189 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9190 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9193 - (void) repairWithInvocation:(NSInvocation *)invocation {
9195 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9199 - (void) repairWithSelector:(SEL)selector {
9200 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9203 - (void) reloadData {
9204 [self reloadDataWithInvocation:nil];
9205 if ([database_ progressDelegate] == nil)
9211 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9214 - (void) addSource:(NSDictionary *) source {
9215 CydiaAddSource(source);
9218 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9219 CydiaAddSource(href, distribution, sections);
9222 - (void) addTrivialSource:(NSString *)href {
9223 CydiaAddSource(href, @"./");
9226 - (void) updateValues {
9231 pkgProblemResolver *resolver = [database_ resolver];
9233 resolver->InstallProtect();
9234 if (!resolver->Resolve(true))
9239 // XXX: this is a really crappy way of doing this.
9240 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9241 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9242 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9243 if ([tabbar_ updating])
9244 [tabbar_ cancelUpdate];
9246 if (![database_ prepare])
9249 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9250 [page setDelegate:self];
9251 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9254 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9255 [tabbar_ presentModalViewController:confirm_ animated:YES];
9261 @synchronized (self) {
9266 - (void) clearPackage:(Package *)package {
9267 @synchronized (self) {
9274 - (void) installPackages:(NSArray *)packages {
9275 @synchronized (self) {
9276 for (Package *package in packages)
9283 - (void) installPackage:(Package *)package {
9284 @synchronized (self) {
9291 - (void) removePackage:(Package *)package {
9292 @synchronized (self) {
9299 - (void) distUpgrade {
9300 @synchronized (self) {
9301 if (![database_ upgrade])
9308 [database_ perform];
9309 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9312 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9315 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9317 [self refreshIfPossible];
9320 - (void) showSettings {
9321 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9324 - (void) retainNetworkActivityIndicator {
9325 if (activity_++ == 0)
9326 [self setNetworkActivityIndicatorVisible:YES];
9329 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9333 - (void) releaseNetworkActivityIndicator {
9334 if (--activity_ == 0)
9335 [self setNetworkActivityIndicatorVisible:NO];
9338 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9343 - (void) cancelAndClear:(bool)clear {
9344 @synchronized (self) {
9356 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9357 NSString *context([alert context]);
9359 if ([context isEqualToString:@"conffile"]) {
9360 FILE *input = [database_ input];
9361 if (button == [alert cancelButtonIndex])
9362 fprintf(input, "N\n");
9363 else if (button == [alert firstOtherButtonIndex])
9364 fprintf(input, "Y\n");
9367 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9368 } else if ([context isEqualToString:@"fixhalf"]) {
9369 if (button == [alert cancelButtonIndex]) {
9370 @synchronized (self) {
9371 for (Package *broken in (id) broken_) {
9374 NSString *id = [broken id];
9375 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9376 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9377 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9378 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9384 } else if (button == [alert firstOtherButtonIndex]) {
9385 [broken_ removeAllObjects];
9389 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9390 } else if ([context isEqualToString:@"upgrade"]) {
9391 if (button == [alert firstOtherButtonIndex]) {
9392 @synchronized (self) {
9393 for (Package *essential in (id) essential_)
9394 [essential install];
9399 } else if (button == [alert firstOtherButtonIndex] + 1) {
9401 } else if (button == [alert cancelButtonIndex]) {
9405 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9409 - (void) system:(NSString *)command {
9410 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9413 system([command UTF8String]);
9419 - (void) applicationWillSuspend {
9421 [super applicationWillSuspend];
9424 - (BOOL) isSafeToSuspend {
9427 NSLog(@"isSafeToSuspend: locked_ != 0");
9432 // Use external process status API internally.
9433 // This is probably a really bad idea.
9434 // XXX: what is the point of this? does this solve anything at all?
9435 uint64_t status = 0;
9437 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9438 notify_get_state(notify_token, &status);
9439 notify_cancel(notify_token);
9444 NSLog(@"isSafeToSuspend: status != 0");
9450 NSLog(@"isSafeToSuspend: -> true");
9455 - (void) applicationSuspend:(__GSEvent *)event {
9456 if ([self isSafeToSuspend])
9457 [super applicationSuspend:event];
9460 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9461 if ([self isSafeToSuspend])
9462 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9465 - (void) _setSuspended:(BOOL)value {
9466 if ([self isSafeToSuspend])
9467 [super _setSuspended:value];
9470 - (UIProgressHUD *) addProgressHUD {
9471 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9472 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9474 [window_ setUserInteractionEnabled:NO];
9476 UIViewController *target(tabbar_);
9477 if (UIViewController *modal = [target modalViewController])
9480 [hud showInView:[target view]];
9486 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9489 [hud removeFromSuperview];
9490 [window_ setUserInteractionEnabled:YES];
9493 - (CyteViewController *) pageForPackage:(NSString *)name {
9494 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9497 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9498 NSString *scheme([[url scheme] lowercaseString]);
9499 if ([[url absoluteString] length] <= [scheme length] + 3)
9501 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9502 NSArray *components([path componentsSeparatedByString:@"/"]);
9504 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9505 return [self pageForPackage:[components objectAtIndex:1]];
9507 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9510 NSString *base([components objectAtIndex:0]);
9512 CyteViewController *controller = nil;
9514 if ([base isEqualToString:@"url"]) {
9515 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9516 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9517 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9518 } else if (!external && [components count] == 1) {
9519 if ([base isEqualToString:@"manage"]) {
9520 controller = [[[ManageController alloc] init] autorelease];
9523 if ([base isEqualToString:@"storage"]) {
9524 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9527 if ([base isEqualToString:@"sources"]) {
9528 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9531 if ([base isEqualToString:@"home"]) {
9532 controller = [[[HomeController alloc] init] autorelease];
9535 if ([base isEqualToString:@"sections"]) {
9536 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9539 if ([base isEqualToString:@"search"]) {
9540 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9543 if ([base isEqualToString:@"changes"]) {
9544 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9547 if ([base isEqualToString:@"installed"]) {
9548 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9550 } else if ([components count] == 2) {
9551 NSString *argument = [components objectAtIndex:1];
9553 if ([base isEqualToString:@"package"]) {
9554 controller = [self pageForPackage:argument];
9557 if (!external && [base isEqualToString:@"search"]) {
9558 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9561 if (!external && [base isEqualToString:@"sections"]) {
9562 if ([argument isEqualToString:@"all"])
9564 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9567 if (!external && [base isEqualToString:@"sources"]) {
9568 if ([argument isEqualToString:@"add"]) {
9569 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9570 [(SourcesController *)controller showAddSourcePrompt];
9572 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9573 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9577 if (!external && [base isEqualToString:@"launch"]) {
9578 [self launchApplicationWithIdentifier:argument suspended:NO];
9581 } else if (!external && [components count] == 3) {
9582 NSString *arg1 = [components objectAtIndex:1];
9583 NSString *arg2 = [components objectAtIndex:2];
9585 if ([base isEqualToString:@"package"]) {
9586 if ([arg2 isEqualToString:@"settings"]) {
9587 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9588 } else if ([arg2 isEqualToString:@"files"]) {
9589 if (Package *package = [database_ packageWithName:arg1]) {
9590 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9591 [(FileTable *)controller setPackage:package];
9597 [controller setDelegate:self];
9601 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9602 CyteViewController *page([self pageForURL:url forExternal:external]);
9605 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9606 [nav setViewControllers:[NSArray arrayWithObject:page]];
9607 [tabbar_ setUnselectedViewController:nav];
9613 - (void) applicationOpenURL:(NSURL *)url {
9614 [super applicationOpenURL:url];
9619 [self openCydiaURL:url forExternal:YES];
9622 - (void) applicationWillResignActive:(UIApplication *)application {
9623 // Stop refreshing if you get a phone call or lock the device.
9624 if ([tabbar_ updating])
9625 [tabbar_ cancelUpdate];
9627 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9628 [super applicationWillResignActive:application];
9631 - (void) saveState {
9632 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9633 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9634 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9640 - (void) applicationWillTerminate:(UIApplication *)application {
9644 - (void) setConfigurationData:(NSString *)data {
9645 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9647 if (!conffile_r(data)) {
9648 lprintf("E:invalid conffile\n");
9652 NSString *ofile = conffile_r[1];
9653 //NSString *nfile = conffile_r[2];
9655 UIAlertView *alert = [[[UIAlertView alloc]
9656 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9657 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9659 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9661 UCLocalize("ACCEPT_NEW_COPY"),
9662 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9666 [alert setContext:@"conffile"];
9667 [alert setNumberOfRows:2];
9671 - (void) addStashController {
9673 stash_ = [[[StashController alloc] init] autorelease];
9674 [window_ addSubview:[stash_ view]];
9677 - (void) removeStashController {
9678 [[stash_ view] removeFromSuperview];
9684 [self setIdleTimerDisabled:YES];
9686 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9687 UpdateExternalStatus(1);
9688 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9689 UpdateExternalStatus(0);
9691 [self removeStashController];
9693 pid_t pid(ExecFork());
9695 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9696 perror("launchctl stop");
9703 - (void) setupViewControllers {
9704 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9706 NSMutableArray *items([NSMutableArray arrayWithObjects:
9707 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9708 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9709 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9710 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9714 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9715 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9717 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9720 NSMutableArray *controllers([NSMutableArray array]);
9721 for (UITabBarItem *item in items) {
9722 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9723 [controller setTabBarItem:item];
9724 [controllers addObject:controller];
9726 [tabbar_ setViewControllers:controllers];
9728 [tabbar_ setUpdateDelegate:self];
9731 - (void) _sendMemoryWarningNotification {
9732 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9735 - (void) _sendMemoryWarningNotifications {
9737 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9742 - (void) applicationDidFinishLaunching:(id)unused {
9743 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9746 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9747 [self setApplicationSupportsShakeToEdit:NO];
9749 @synchronized (HostConfig_) {
9750 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9753 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9754 initWithMemoryCapacity:524288
9755 diskCapacity:10485760
9756 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9759 [CydiaWebViewController _initialize];
9761 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9763 // this would disallow http{,s} URLs from accessing this data
9764 //[WebView registerURLSchemeAsLocal:@"cydia"];
9766 Font12_ = [UIFont systemFontOfSize:12];
9767 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9768 Font14_ = [UIFont systemFontOfSize:14];
9769 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9770 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9772 essential_ = [NSMutableArray arrayWithCapacity:4];
9773 broken_ = [NSMutableArray arrayWithCapacity:4];
9775 // XXX: I really need this thing... like, seriously... I'm sorry
9776 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9778 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9779 [window_ orderFront:self];
9780 [window_ makeKey:self];
9781 [window_ setHidden:NO];
9784 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9785 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9786 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9787 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9788 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9789 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9790 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9791 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9792 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9795 [self addStashController];
9796 // XXX: this would be much cleaner as a yieldToSelector:
9797 // that way the removeStashController could happen right here inline
9798 // we also could no longer require the useless stash_ field anymore
9799 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9803 database_ = [Database sharedInstance];
9804 [database_ setDelegate:self];
9806 [window_ setUserInteractionEnabled:NO];
9807 [self setupViewControllers];
9809 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9810 [window_ addSubview:[emulated_ view]];
9812 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9816 - (NSArray *) defaultStartPages {
9817 NSMutableArray *standard = [NSMutableArray array];
9818 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9819 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9820 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9822 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9824 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9825 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9827 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9834 [window_ setUserInteractionEnabled:YES];
9835 [self showSettings];
9838 if ([emulated_ modalViewController] != nil)
9839 [emulated_ dismissModalViewControllerAnimated:YES];
9840 [window_ setUserInteractionEnabled:NO];
9843 [self reloadDataWithInvocation:nil];
9844 [self refreshIfPossible];
9849 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9850 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9851 int standardIndex = 0;
9852 NSArray *standard = [self defaultStartPages];
9859 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9860 if (valid && closed != nil) {
9861 NSTimeInterval interval([closed timeIntervalSinceNow]);
9862 // XXX: Is 15 minutes the optimal time here?
9863 if (interval > 0 && interval <= -(15*60))
9867 if (valid && [saved count] != [standard count])
9871 for (unsigned int i = 0; i < [standard count]; i++) {
9872 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9873 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9874 // but it's good enough for now.
9875 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9882 NSArray *items = nil;
9884 [tabbar_ setSelectedIndex:savedIndex];
9887 [tabbar_ setSelectedIndex:standardIndex];
9891 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9892 NSArray *stack = [items objectAtIndex:tab];
9893 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9894 NSMutableArray *current = [NSMutableArray array];
9896 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9897 NSString *addr = [stack objectAtIndex:nav];
9898 NSURL *url = [NSURL URLWithString:addr];
9899 CyteViewController *page = [self pageForURL:url forExternal:NO];
9901 [current addObject:page];
9904 [navigation setViewControllers:current];
9907 // (Try to) show the startup URL.
9908 if (starturl_ != nil) {
9909 [self openCydiaURL:starturl_ forExternal:NO];
9914 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9915 if (item != nil && IsWildcat_) {
9916 [sheet showFromBarButtonItem:item animated:YES];
9918 [sheet showInView:window_];
9922 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9923 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9924 [progress setTitle:task];
9925 [progress addProgressEvent:event];
9928 - (void) addProgressEventForTask:(NSArray *)data {
9929 CydiaProgressEvent *event([data objectAtIndex:0]);
9930 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9931 [self addProgressEvent:event forTask:task];
9934 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9935 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9941 id Alloc_(id self, SEL selector) {
9942 id object = alloc_(self, selector);
9943 lprintf("[%s]A-%p\n", self->isa->name, object);
9948 id Dealloc_(id self, SEL selector) {
9949 id object = dealloc_(self, selector);
9950 lprintf("[%s]D-%p\n", self->isa->name, object);
9954 Class $WebDefaultUIKitDelegate;
9956 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9957 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9958 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9959 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9962 static NSSet *MobilizedFiles_;
9964 static NSURL *MobilizeURL(NSURL *url) {
9965 NSString *path([url path]);
9966 if ([path hasPrefix:@"/var/root/"]) {
9967 NSString *file([path substringFromIndex:10]);
9968 if ([MobilizedFiles_ containsObject:file])
9969 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9975 Class $CFXPreferencesPropertyListSource;
9976 @class CFXPreferencesPropertyListSource;
9978 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9979 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9980 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9981 url = MobilizeURL(url);
9982 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9983 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9989 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9990 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9991 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9992 url = MobilizeURL(url);
9993 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9994 //NSLog(@"%@ %@", [url absoluteString], value);
10000 Class $NSURLConnection;
10002 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10003 NSMutableURLRequest *copy([request mutableCopy]);
10005 NSURL *url([copy URL]);
10007 NSString *host([url host]);
10008 NSString *scheme([[url scheme] lowercaseString]);
10010 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10012 @synchronized (HostConfig_) {
10013 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10014 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10015 [copy setHTTPShouldUsePipelining:YES];
10017 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10018 if ([control isEqualToString:@"max-age=0"])
10019 if ([CachedURLs_ containsObject:url]) {
10021 NSLog(@"~~~: %@", url);
10024 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10026 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10027 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10028 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10032 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10036 int main(int argc, char *argv[]) {
10037 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10041 UpdateExternalStatus(0);
10043 if (Class $UIDevice = objc_getClass("UIDevice")) {
10044 UIDevice *device([$UIDevice currentDevice]);
10045 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10047 IsWildcat_ = false;
10049 UIScreen *screen([UIScreen mainScreen]);
10050 if ([screen respondsToSelector:@selector(scale)])
10051 ScreenScale_ = [screen scale];
10055 UIDevice *device([UIDevice currentDevice]);
10056 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10057 Idiom_ = @"iphone";
10059 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10060 if (idiom == UIUserInterfaceIdiomPhone)
10061 Idiom_ = @"iphone";
10062 else if (idiom == UIUserInterfaceIdiomPad)
10065 NSLog(@"unknown UIUserInterfaceIdiom!");
10068 Pcre pattern("^([0-9]+\\.[0-9]+)");
10070 if (pattern([device systemVersion]))
10071 Firmware_ = pattern[1];
10072 if (pattern(Cydia_))
10073 Major_ = pattern[1];
10075 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10077 HostConfig_ = [[[NSObject alloc] init] autorelease];
10078 @synchronized (HostConfig_) {
10079 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10080 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10081 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10082 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10083 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10086 NSString *ui(@"ui/ios");
10088 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10089 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10090 UI_ = CydiaURL(ui);
10092 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10094 MobilizedFiles_ = [NSMutableSet setWithObjects:
10095 @"Library/Preferences/com.apple.Accessibility.plist",
10096 @"Library/Preferences/com.apple.preferences.sounds.plist",
10099 /* Library Hacks {{{ */
10100 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10102 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10104 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10105 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10106 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10107 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10110 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10111 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10112 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10113 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10116 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10117 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10118 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10119 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10120 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10123 $NSURLConnection = objc_getClass("NSURLConnection");
10124 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10125 if (NSURLConnection$init$ != NULL) {
10126 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10127 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10130 /* Set Locale {{{ */
10131 Locale_ = CFLocaleCopyCurrent();
10132 Languages_ = [NSLocale preferredLanguages];
10134 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10135 //NSLog(@"%@", [Languages_ description]);
10138 if (Locale_ != NULL)
10139 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10140 else if (Languages_ != nil && [Languages_ count] != 0)
10141 lang = [[Languages_ objectAtIndex:0] UTF8String];
10143 // XXX: consider just setting to C and then falling through?
10146 if (lang != NULL) {
10147 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10148 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10151 NSLog(@"Setting Language: %s", lang);
10153 if (lang != NULL) {
10154 setenv("LANG", lang, true);
10155 std::setlocale(LC_ALL, lang);
10159 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10161 /* Parse Arguments {{{ */
10162 bool substrate(false);
10168 for (int argi(1); argi != argc; ++argi)
10169 if (strcmp(argv[argi], "--") == 0) {
10171 argv[argi] = argv[0];
10177 for (int argi(1); argi != arge; ++argi)
10178 if (strcmp(args[argi], "--substrate") == 0)
10181 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10185 App_ = [[NSBundle mainBundle] bundlePath];
10191 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10192 alloc_ = alloc->method_imp;
10193 alloc->method_imp = (IMP) &Alloc_;*/
10195 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10196 dealloc_ = dealloc->method_imp;
10197 dealloc->method_imp = (IMP) &Dealloc_;*/
10199 /* System Information {{{ */
10203 size = sizeof(maxproc);
10204 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10205 perror("sysctlbyname(\"kern.maxproc\", ?)");
10206 else if (maxproc < 64) {
10208 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10209 perror("sysctlbyname(\"kern.maxproc\", #)");
10212 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10213 char *osversion = new char[size];
10214 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10215 perror("sysctlbyname(\"kern.osversion\", ?)");
10217 System_ = [NSString stringWithUTF8String:osversion];
10219 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10220 char *machine = new char[size];
10221 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10222 perror("sysctlbyname(\"hw.machine\", ?)");
10224 Machine_ = machine;
10226 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10227 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10228 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10230 UniqueID_ = [device uniqueIdentifier];
10232 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10233 Build_ = [system objectForKey:@"ProductBuildVersion"];
10234 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10235 Product_ = [info objectForKey:@"SafariProductVersion"];
10236 Safari_ = [info objectForKey:@"CFBundleVersion"];
10239 /* Load Database {{{ */
10241 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10243 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10245 if (Metadata_ == NULL)
10246 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10248 Settings_ = [Metadata_ objectForKey:@"Settings"];
10250 Packages_ = [Metadata_ objectForKey:@"Packages"];
10252 Values_ = [Metadata_ objectForKey:@"Values"];
10253 Sections_ = [Metadata_ objectForKey:@"Sections"];
10254 Sources_ = [Metadata_ objectForKey:@"Sources"];
10256 Token_ = [Metadata_ objectForKey:@"Token"];
10258 Version_ = [Metadata_ objectForKey:@"Version"];
10260 @synchronized (HostConfig_) {
10261 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10265 if (Settings_ != nil)
10266 Role_ = [Settings_ objectForKey:@"Role"];
10268 if (Values_ == nil) {
10269 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10270 [Metadata_ setObject:Values_ forKey:@"Values"];
10273 if (Sections_ == nil) {
10274 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10275 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10278 if (Sources_ == nil) {
10279 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10280 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10283 if (Version_ == nil) {
10284 Version_ = [NSNumber numberWithUnsignedInt:0];
10285 [Metadata_ setObject:Version_ forKey:@"Version"];
10288 @synchronized (HostConfig_) {
10289 if (CydiaSource_ == nil) {
10290 CydiaSource_ = @"apt.saurik.com";
10291 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10295 if ([Version_ unsignedIntValue] == 0) {
10296 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10297 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10298 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10299 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10301 Version_ = [NSNumber numberWithUnsignedInt:1];
10302 [Metadata_ setObject:Version_ forKey:@"Version"];
10304 [Metadata_ removeObjectForKey:@"LastUpdate"];
10310 CydiaWriteSources();
10313 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10316 if (Packages_ != nil) {
10318 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10322 [Metadata_ removeObjectForKey:@"Packages"];
10328 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10330 #define MobileSubstrate_(name) \
10331 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10332 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10333 if (handle == NULL) \
10334 NSLog(@"%s", dlerror()); \
10337 MobileSubstrate_(Activator)
10338 MobileSubstrate_(libstatusbar)
10339 MobileSubstrate_(SimulatedKeyEvents)
10340 MobileSubstrate_(WinterBoard)
10342 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10343 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10345 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10347 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10348 unlink("/tmp/.cydia.fw");
10350 } else if (access("/User", F_OK) != 0 || version < 4) {
10353 system("/usr/libexec/cydia/firmware.sh");
10357 _assert([[NSFileManager defaultManager]
10358 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10359 withIntermediateDirectories:YES
10364 if (access("/tmp/cydia.chk", F_OK) == 0) {
10365 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10366 _assert(errno == ENOENT);
10367 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10368 _assert(errno == ENOENT);
10371 /* APT Initialization {{{ */
10372 _assert(pkgInitConfig(*_config));
10373 _assert(pkgInitSystem(*_config, _system));
10376 _config->Set("APT::Acquire::Translation", lang);
10378 // XXX: this timeout might be important :(
10379 //_config->Set("Acquire::http::Timeout", 15);
10381 _config->Set("Acquire::http::MaxParallel", 3);
10383 /* Color Choices {{{ */
10384 space_ = CGColorSpaceCreateDeviceRGB();
10386 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10387 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10388 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10389 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10390 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10391 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10392 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10393 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10394 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10396 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10397 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10399 /* UIKit Configuration {{{ */
10400 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10401 if ($GSFontSetUseLegacyFontMetrics != NULL)
10402 $GSFontSetUseLegacyFontMetrics(YES);
10404 // XXX: I have a feeling this was important
10405 //UIKeyboardDisableAutomaticAppearance();
10408 Colon_ = UCLocalize("COLON_DELIMITED");
10409 Elision_ = UCLocalize("ELISION");
10410 Error_ = UCLocalize("ERROR");
10411 Warning_ = UCLocalize("WARNING");
10414 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10416 CGColorSpaceRelease(space_);
10417 CFRelease(Locale_);