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 _H<NSString> System_;
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 *Product_ = nil;
695 static NSString *Safari_ = nil;
697 static CFLocaleRef Locale_;
698 static NSArray *Languages_;
699 static CGColorSpaceRef space_;
701 static NSDictionary *SectionMap_;
702 static NSMutableDictionary *Metadata_;
703 static _transient NSMutableDictionary *Settings_;
704 static _transient NSString *Role_;
705 static _transient NSMutableDictionary *Packages_;
706 static _transient NSMutableDictionary *Values_;
707 static _transient NSMutableDictionary *Sections_;
708 _H<NSMutableDictionary> Sources_;
709 static _transient NSNumber *Version_;
714 static CGFloat ScreenScale_;
715 static NSString *Idiom_;
716 static _H<NSString> Firmware_;
717 static NSString *Major_;
719 static _H<NSMutableDictionary> SessionData_;
720 static _H<NSObject> HostConfig_;
721 static _H<NSMutableSet> BridgedHosts_;
722 static _H<NSMutableSet> TokenHosts_;
723 static _H<NSMutableSet> InsecureHosts_;
724 static _H<NSMutableSet> PipelinedHosts_;
725 static _H<NSMutableSet> CachedURLs_;
727 static NSString *kCydiaProgressEventTypeError = @"Error";
728 static NSString *kCydiaProgressEventTypeInformation = @"Information";
729 static NSString *kCydiaProgressEventTypeStatus = @"Status";
730 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
733 /* Display Helpers {{{ */
734 inline float Interpolate(float begin, float end, float fraction) {
735 return (end - begin) * fraction + begin;
738 static _finline const char *StripVersion_(const char *version) {
739 const char *colon(strchr(version, ':'));
740 return colon == NULL ? version : colon + 1;
743 NSString *LocalizeSection(NSString *section) {
744 static Pcre title_r("^(.*?) \\((.*)\\)$");
745 if (title_r(section)) {
746 NSString *parent(title_r[1]);
747 NSString *child(title_r[2]);
749 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
750 LocalizeSection(parent),
751 LocalizeSection(child)
755 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
758 NSString *Simplify(NSString *title) {
759 const char *data = [title UTF8String];
760 size_t size = [title length];
762 static Pcre square_r("^\\[(.*)\\]$");
763 if (square_r(data, size))
764 return Simplify(square_r[1]);
766 static Pcre paren_r("^\\((.*)\\)$");
767 if (paren_r(data, size))
768 return Simplify(paren_r[1]);
770 static Pcre title_r("^(.*?) \\((.*)\\)$");
771 if (title_r(data, size))
772 return Simplify(title_r[1]);
778 NSString *GetLastUpdate() {
779 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
782 return UCLocalize("NEVER_OR_UNKNOWN");
784 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
785 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
787 CFRelease(formatter);
789 return [(NSString *) formatted autorelease];
792 bool isSectionVisible(NSString *section) {
793 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
794 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
795 return hidden == nil || ![hidden boolValue];
798 static NSObject *CYIOGetValue(const char *path, NSString *property) {
799 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
800 if (entry == MACH_PORT_NULL)
803 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
804 IOObjectRelease(entry);
808 return [(id) value autorelease];
811 static NSString *CYHex(NSData *data, bool reverse = false) {
815 size_t length([data length]);
816 uint8_t bytes[length];
817 [data getBytes:bytes];
819 char string[length * 2 + 1];
820 for (size_t i(0); i != length; ++i)
821 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
823 return [NSString stringWithUTF8String:string];
828 /* Delegate Prototypes {{{ */
831 @class CydiaProgressEvent;
833 @protocol DatabaseDelegate
834 - (void) repairWithSelector:(SEL)selector;
835 - (void) setConfigurationData:(NSString *)data;
836 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
839 @class CYPackageController;
841 @protocol CydiaDelegate
842 - (void) returnToCydia;
844 - (void) retainNetworkActivityIndicator;
845 - (void) releaseNetworkActivityIndicator;
846 - (void) clearPackage:(Package *)package;
847 - (void) installPackage:(Package *)package;
848 - (void) installPackages:(NSArray *)packages;
849 - (void) removePackage:(Package *)package;
850 - (void) beginUpdate;
852 - (void) distUpgrade;
856 - (void) addSource:(NSDictionary *)source;
857 - (void) addTrivialSource:(NSString *)href;
858 - (void) showSettings;
859 - (UIProgressHUD *) addProgressHUD;
860 - (void) removeProgressHUD:(UIProgressHUD *)hud;
861 - (CyteViewController *) pageForPackage:(NSString *)name;
862 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
863 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
867 /* Status Delegation {{{ */
869 public pkgAcquireStatus
872 _transient NSObject<ProgressDelegate> *delegate_;
882 void setDelegate(NSObject<ProgressDelegate> *delegate) {
883 delegate_ = delegate;
886 NSObject<ProgressDelegate> *getDelegate() const {
890 virtual bool MediaChange(std::string media, std::string drive) {
894 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
898 virtual void Fetch(pkgAcquire::ItemDesc &item) {
899 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
900 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
901 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
904 virtual void Done(pkgAcquire::ItemDesc &item) {
905 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
906 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
907 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
910 virtual void Fail(pkgAcquire::ItemDesc &item) {
912 item.Owner->Status == pkgAcquire::Item::StatIdle ||
913 item.Owner->Status == pkgAcquire::Item::StatDone
917 std::string &error(item.Owner->ErrorText);
921 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
922 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
925 virtual bool Pulse(pkgAcquire *Owner) {
926 bool value = pkgAcquireStatus::Pulse(Owner);
929 double(CurrentBytes + CurrentItems) /
930 double(TotalBytes + TotalItems)
933 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
934 [NSNumber numberWithDouble:percent], @"Percent",
936 [NSNumber numberWithDouble:CurrentBytes], @"Current",
937 [NSNumber numberWithDouble:TotalBytes], @"Total",
938 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
939 nil] waitUntilDone:YES];
941 if (value && ![delegate_ isProgressCancelled])
949 _finline bool WasCancelled() const {
953 virtual void Start() {
954 pkgAcquireStatus::Start();
955 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
958 virtual void Stop() {
959 pkgAcquireStatus::Stop();
960 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
961 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
965 /* Database Interface {{{ */
966 typedef std::map< unsigned long, _H<Source> > SourceMap;
968 @interface Database : NSObject {
975 pkgDepCache::Policy *policy_;
976 pkgRecords *records_;
977 pkgProblemResolver *resolver_;
978 pkgAcquire *fetcher_;
980 SPtr<pkgPackageManager> manager_;
981 pkgSourceList *list_;
983 SourceMap sourceMap_;
984 _H<NSMutableArray> sourceList_;
986 CFMutableArrayRef packages_;
988 _transient NSObject<DatabaseDelegate> *delegate_;
989 _transient NSObject<ProgressDelegate> *progress_;
997 std::map<const char *, _H<NSString> > sections_;
1000 + (Database *) sharedInstance;
1003 - (void) _readCydia:(NSNumber *)fd;
1004 - (void) _readStatus:(NSNumber *)fd;
1005 - (void) _readOutput:(NSNumber *)fd;
1009 - (Package *) packageWithName:(NSString *)name;
1011 - (pkgCacheFile &) cache;
1012 - (pkgDepCache::Policy *) policy;
1013 - (pkgRecords *) records;
1014 - (pkgProblemResolver *) resolver;
1015 - (pkgAcquire &) fetcher;
1016 - (pkgSourceList &) list;
1017 - (NSArray *) packages;
1018 - (NSArray *) sources;
1019 - (Source *) sourceWithKey:(NSString *)key;
1020 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1028 - (void) updateWithStatus:(Status &)status;
1030 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1032 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1033 - (NSObject<ProgressDelegate> *) progressDelegate;
1035 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1037 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1041 /* ProgressEvent Implementation {{{ */
1042 @implementation CydiaProgressEvent
1044 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1045 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1048 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1049 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1050 [event setPackage:package];
1054 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1055 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1057 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1058 NSArray *fields([description componentsSeparatedByString:@" "]);
1059 [event setItem:fields];
1061 if ([fields count] > 3) {
1062 [event setPackage:[fields objectAtIndex:2]];
1063 [event setVersion:[fields objectAtIndex:3]];
1066 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1071 + (NSArray *) _attributeKeys {
1072 return [NSArray arrayWithObjects:
1082 - (NSArray *) attributeKeys {
1083 return [[self class] _attributeKeys];
1086 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1087 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1090 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1091 if ((self = [super init]) != nil) {
1097 - (NSString *) message {
1101 - (NSString *) type {
1105 - (NSArray *) item {
1106 return (id) item_ ?: [NSNull null];
1109 - (void) setItem:(NSArray *)item {
1113 - (NSString *) package {
1114 return (id) package_ ?: [NSNull null];
1117 - (void) setPackage:(NSString *)package {
1121 - (NSString *) url {
1122 return (id) url_ ?: [NSNull null];
1125 - (void) setURL:(NSString *)url {
1129 - (void) setVersion:(NSString *)version {
1133 - (NSString *) version {
1134 return (id) version_ ?: [NSNull null];
1137 - (NSString *) compound:(NSString *)value {
1139 NSString *mode(nil); {
1140 NSString *type([self type]);
1141 if ([type isEqualToString:kCydiaProgressEventTypeError])
1142 mode = UCLocalize("ERROR");
1143 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1144 mode = UCLocalize("WARNING");
1148 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1154 - (NSString *) compoundMessage {
1155 return [self compound:[self message]];
1158 - (NSString *) compoundTitle {
1161 if (package_ == nil)
1163 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1164 title = [package name];
1168 return [self compound:title];
1174 // Cytore Definitions {{{
1175 struct PackageValue :
1178 Cytore::Offset<PackageValue> next_;
1180 uint32_t index_ : 23;
1181 uint32_t subscribed_ : 1;
1198 Cytore::Offset<PackageValue> packages_[1 << 16];
1201 static Cytore::File<MetaValue> MetaFile_;
1203 // Cytore Helper Functions {{{
1204 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1205 SplitHash nhash = { hashlittle(name, length) };
1207 PackageValue *metadata;
1209 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1210 offset: if (offset->IsNull()) {
1211 *offset = MetaFile_.New<PackageValue>(length + 1);
1212 metadata = &MetaFile_.Get(*offset);
1214 if (metadata == NULL) {
1218 metadata = new PackageValue();
1219 memset(metadata, 0, sizeof(*metadata));
1222 memcpy(metadata->name_, name, length + 1);
1223 metadata->nhash_ = nhash.u16[1];
1225 metadata = &MetaFile_.Get(*offset);
1227 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1228 offset = &metadata->next_;
1236 static void PackageImport(const void *key, const void *value, void *context) {
1237 bool &fail(*reinterpret_cast<bool *>(context));
1240 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1241 NSLog(@"failed to import package %@", key);
1245 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1246 NSDictionary *package((NSDictionary *) value);
1248 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1249 if ([subscribed boolValue] && !metadata->subscribed_)
1250 metadata->subscribed_ = true;
1252 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1253 time_t time([date timeIntervalSince1970]);
1254 if (metadata->first_ > time || metadata->first_ == 0)
1255 metadata->first_ = time;
1258 NSDate *date([package objectForKey:@"LastSeen"]);
1259 NSString *version([package objectForKey:@"LastVersion"]);
1261 if (date != nil && version != nil) {
1262 time_t time([date timeIntervalSince1970]);
1263 if (metadata->last_ < time || metadata->last_ == 0)
1264 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1265 size_t length(strlen(buffer));
1266 uint16_t vhash(hashlittle(buffer, length));
1268 size_t capped(std::min<size_t>(8, length));
1269 char *latest(buffer + length - capped);
1271 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1272 metadata->vhash_ = vhash;
1274 metadata->last_ = time;
1280 /* Source Class {{{ */
1281 @interface Source : NSObject {
1283 Database *database_;
1286 CYString depiction_;
1287 CYString description_;
1293 CYString distribution_;
1299 _H<NSString> authority_;
1301 CYString defaultIcon_;
1303 _H<NSDictionary> record_;
1307 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1309 - (NSComparisonResult) compareByName:(Source *)source;
1311 - (NSString *) depictionForPackage:(NSString *)package;
1312 - (NSString *) supportForPackage:(NSString *)package;
1314 - (NSDictionary *) record;
1317 - (NSString *) rooturi;
1318 - (NSString *) distribution;
1319 - (NSString *) type;
1322 - (NSString *) host;
1324 - (NSString *) name;
1325 - (NSString *) shortDescription;
1326 - (NSString *) label;
1327 - (NSString *) origin;
1328 - (NSString *) version;
1330 - (NSString *) defaultIcon;
1331 - (NSURL *) iconURL;
1335 @implementation Source
1339 distribution_.clear();
1344 description_.clear();
1350 defaultIcon_.clear();
1357 + (NSString *) webScriptNameForSelector:(SEL)selector {
1359 else if (selector == @selector(addSection:))
1360 return @"addSection";
1361 else if (selector == @selector(getField:))
1363 else if (selector == @selector(removeSection:))
1364 return @"removeSection";
1365 else if (selector == @selector(remove))
1371 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1372 return [self webScriptNameForSelector:selector] == nil;
1375 + (NSArray *) _attributeKeys {
1376 return [NSArray arrayWithObjects:
1387 @"shortDescription",
1394 - (NSArray *) attributeKeys {
1395 return [[self class] _attributeKeys];
1398 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1399 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1402 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1405 trusted_ = index->IsTrusted();
1407 uri_.set(pool, index->GetURI());
1408 distribution_.set(pool, index->GetDist());
1409 type_.set(pool, index->GetType());
1411 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1412 if (dindex != NULL) {
1413 base_.set(pool, dindex->MetaIndexURI(""));
1416 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1419 pkgTagFile tags(&fd);
1421 pkgTagSection section;
1428 {"default-icon", &defaultIcon_},
1429 {"depiction", &depiction_},
1430 {"description", &description_},
1432 {"origin", &origin_},
1433 {"support", &support_},
1434 {"version", &version_},
1437 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1438 const char *start, *end;
1440 if (section.Find(names[i].name_, start, end)) {
1441 CYString &value(*names[i].value_);
1442 value.set(pool, start, end - start);
1448 record_ = [Sources_ objectForKey:[self key]];
1450 NSURL *url([NSURL URLWithString:uri_]);
1454 host_ = [host_ lowercaseString];
1459 authority_ = [url path];
1462 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1463 if ((self = [super init]) != nil) {
1464 era_ = [database era];
1465 database_ = database;
1468 [self setMetaIndex:index inPool:pool];
1472 - (NSString *) getField:(NSString *)name {
1473 @synchronized (database_) {
1474 if ([database_ era] != era_ || index_ == NULL)
1477 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1482 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1487 pkgTagFile tags(&fd);
1489 pkgTagSection section;
1492 const char *start, *end;
1493 if (!section.Find([name UTF8String], start, end))
1494 return (NSString *) [NSNull null];
1496 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1499 - (NSComparisonResult) compareByName:(Source *)source {
1500 NSString *lhs = [self name];
1501 NSString *rhs = [source name];
1503 if ([lhs length] != 0 && [rhs length] != 0) {
1504 unichar lhc = [lhs characterAtIndex:0];
1505 unichar rhc = [rhs characterAtIndex:0];
1507 if (isalpha(lhc) && !isalpha(rhc))
1508 return NSOrderedAscending;
1509 else if (!isalpha(lhc) && isalpha(rhc))
1510 return NSOrderedDescending;
1513 return [lhs compare:rhs options:LaxCompareOptions_];
1516 - (NSString *) depictionForPackage:(NSString *)package {
1517 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1520 - (NSString *) supportForPackage:(NSString *)package {
1521 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1524 - (NSArray *) sections {
1525 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1528 - (void) _addSection:(NSString *)section {
1531 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1532 if (![sections containsObject:section]) {
1533 [sections addObject:section];
1537 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1542 - (bool) addSection:(NSString *)section {
1546 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1550 - (void) _removeSection:(NSString *)section {
1554 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1555 if ([sections containsObject:section]) {
1556 [sections removeObject:section];
1561 - (bool) removeSection:(NSString *)section {
1565 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1570 [Sources_ removeObjectForKey:[self key]];
1575 bool value(record_ != nil);
1576 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1580 - (NSDictionary *) record {
1588 - (NSString *) rooturi {
1592 - (NSString *) distribution {
1593 return distribution_;
1596 - (NSString *) type {
1600 - (NSString *) baseuri {
1601 return base_.empty() ? nil : (id) base_;
1604 - (NSString *) iconuri {
1605 if (NSString *base = [self baseuri])
1606 return [base stringByAppendingString:@"CydiaIcon.png"];
1611 - (NSURL *) iconURL {
1612 if (NSString *uri = [self iconuri])
1613 return [NSURL URLWithString:uri];
1617 - (NSString *) key {
1618 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1621 - (NSString *) host {
1625 - (NSString *) name {
1626 return origin_.empty() ? (id) authority_ : origin_;
1629 - (NSString *) shortDescription {
1630 return description_;
1633 - (NSString *) label {
1634 return label_.empty() ? (id) authority_ : label_;
1637 - (NSString *) origin {
1641 - (NSString *) version {
1645 - (NSString *) defaultIcon {
1646 return defaultIcon_;
1651 /* CydiaOperation Class {{{ */
1652 @interface CydiaOperation : NSObject {
1653 _H<NSString> operator_;
1654 _H<NSString> value_;
1657 - (NSString *) operator;
1658 - (NSString *) value;
1662 @implementation CydiaOperation
1664 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1665 if ((self = [super init]) != nil) {
1666 operator_ = [NSString stringWithUTF8String:_operator];
1667 value_ = [NSString stringWithUTF8String:value];
1671 + (NSArray *) _attributeKeys {
1672 return [NSArray arrayWithObjects:
1678 - (NSArray *) attributeKeys {
1679 return [[self class] _attributeKeys];
1682 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1683 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1686 - (NSString *) operator {
1690 - (NSString *) value {
1696 /* CydiaClause Class {{{ */
1697 @interface CydiaClause : NSObject {
1698 _H<NSString> package_;
1699 _H<CydiaOperation> version_;
1702 - (NSString *) package;
1703 - (CydiaOperation *) version;
1707 @implementation CydiaClause
1709 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1710 if ((self = [super init]) != nil) {
1711 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1713 if (const char *version = dep.TargetVer())
1714 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1716 version_ = (id) [NSNull null];
1720 + (NSArray *) _attributeKeys {
1721 return [NSArray arrayWithObjects:
1727 - (NSArray *) attributeKeys {
1728 return [[self class] _attributeKeys];
1731 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1732 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1735 - (NSString *) package {
1739 - (CydiaOperation *) version {
1745 /* CydiaRelation Class {{{ */
1746 @interface CydiaRelation : NSObject {
1747 _H<NSString> relationship_;
1748 _H<NSMutableArray> clauses_;
1751 - (NSString *) relationship;
1752 - (NSArray *) clauses;
1756 @implementation CydiaRelation
1758 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1759 if ((self = [super init]) != nil) {
1760 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1761 clauses_ = [NSMutableArray arrayWithCapacity:8];
1763 pkgCache::DepIterator start;
1764 pkgCache::DepIterator end;
1765 dep.GlobOr(start, end); // ++dep
1768 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1770 // yes, seriously. (wtf?)
1778 + (NSArray *) _attributeKeys {
1779 return [NSArray arrayWithObjects:
1785 - (NSArray *) attributeKeys {
1786 return [[self class] _attributeKeys];
1789 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1790 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1793 - (NSString *) relationship {
1794 return relationship_;
1797 - (NSArray *) clauses {
1801 - (void) addClause:(CydiaClause *)clause {
1802 [clauses_ addObject:clause];
1807 /* Package Class {{{ */
1808 struct ParsedPackage {
1812 CYString architecture_;
1815 CYString depiction_;
1825 @interface Package : NSObject {
1828 uint32_t essential_ : 1;
1829 uint32_t obsolete_ : 1;
1830 uint32_t ignored_ : 1;
1831 uint32_t pooled_ : 1;
1837 _transient Database *database_;
1839 pkgCache::VerIterator version_;
1840 pkgCache::PkgIterator iterator_;
1841 pkgCache::VerFileIterator file_;
1847 CYString installed_;
1849 const char *section_;
1850 _transient NSString *section$_;
1854 PackageValue *metadata_;
1855 ParsedPackage *parsed_;
1857 _H<NSMutableArray> tags_;
1860 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1861 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1863 - (pkgCache::PkgIterator) iterator;
1866 - (NSString *) section;
1867 - (NSString *) simpleSection;
1869 - (NSString *) longSection;
1870 - (NSString *) shortSection;
1874 - (MIMEAddress *) maintainer;
1876 - (NSString *) longDescription;
1877 - (NSString *) shortDescription;
1880 - (PackageValue *) metadata;
1883 - (bool) subscribed;
1884 - (bool) setSubscribed:(bool)subscribed;
1888 - (NSString *) latest;
1889 - (NSString *) installed;
1890 - (BOOL) uninstalled;
1893 - (BOOL) upgradableAndEssential:(BOOL)essential;
1896 - (BOOL) unfiltered;
1900 - (BOOL) halfConfigured;
1901 - (BOOL) halfInstalled;
1903 - (NSString *) mode;
1906 - (NSString *) name;
1908 - (NSString *) homepage;
1909 - (NSString *) depiction;
1910 - (MIMEAddress *) author;
1912 - (NSString *) support;
1914 - (NSArray *) files;
1915 - (NSArray *) warnings;
1916 - (NSArray *) applications;
1918 - (Source *) source;
1921 - (BOOL) matches:(NSArray *)query;
1923 - (bool) hasSupportingRole;
1924 - (BOOL) hasTag:(NSString *)tag;
1925 - (NSString *) primaryPurpose;
1926 - (NSArray *) purposes;
1927 - (bool) isCommercial;
1929 - (void) setIndex:(size_t)index;
1931 - (CYString &) cyname;
1933 - (uint32_t) compareBySection:(NSArray *)sections;
1938 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1939 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1940 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1941 - (bool) isVisibleInSection:(NSString *)section;
1942 - (bool) isVisibleInSource:(Source *)source;
1946 uint32_t PackageChangesRadix(Package *self, void *) {
1951 uint32_t timestamp : 30;
1952 uint32_t ignored : 1;
1953 uint32_t upgradable : 1;
1957 bool upgradable([self upgradableAndEssential:YES]);
1958 value.bits.upgradable = upgradable ? 1 : 0;
1961 value.bits.timestamp = 0;
1962 value.bits.ignored = [self ignored] ? 0 : 1;
1963 value.bits.upgradable = 1;
1965 value.bits.timestamp = [self seen] >> 2;
1966 value.bits.ignored = 0;
1967 value.bits.upgradable = 0;
1970 return _not(uint32_t) - value.key;
1973 uint32_t PackagePrefixRadix(Package *self, void *context) {
1974 size_t offset(reinterpret_cast<size_t>(context));
1975 CYString &name([self cyname]);
1977 size_t size(name.size());
1980 char *text(name.data());
1983 if (!isdigit(text[0]))
1987 while (size != digits && isdigit(text[digits]))
1995 if (offset == 0 && zeros != 0) {
1996 memset(data, '0', zeros);
1997 memcpy(data + zeros, text, 4 - zeros);
1999 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2000 if (size <= offset - zeros)
2003 text += offset - zeros;
2004 size -= offset - zeros;
2007 memcpy(data, text, 4);
2009 memcpy(data, text, size);
2010 memset(data + size, 0, 4 - size);
2013 for (size_t i(0); i != 4; ++i)
2014 if (isalpha(data[i]))
2022 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2024 /* XXX: ntohl may be more honest */
2025 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2028 CYString &(*PackageName)(Package *self, SEL sel);
2030 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2031 _profile(PackageNameCompare)
2032 CYString &lhi(PackageName(lhs, @selector(cyname)));
2033 CYString &rhi(PackageName(rhs, @selector(cyname)));
2034 CFStringRef lhn(lhi), rhn(rhi);
2037 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2038 else if (rhn == NULL)
2039 return NSOrderedDescending;
2041 _profile(PackageNameCompare$NumbersLast)
2042 if (!lhi.empty() && !rhi.empty()) {
2043 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2044 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2045 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2046 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2047 return lha ? NSOrderedAscending : NSOrderedDescending;
2051 CFIndex length = CFStringGetLength(lhn);
2053 _profile(PackageNameCompare$Compare)
2054 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2059 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2060 return PackageNameCompare(*lhs, *rhs, context);
2063 struct PackageNameOrdering :
2064 std::binary_function<Package *, Package *, bool>
2066 _finline bool operator ()(Package *lhs, Package *rhs) const {
2067 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2071 @implementation Package
2073 - (NSString *) description {
2074 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2079 apr_pool_destroy(pool_);
2080 if (parsed_ != NULL)
2085 + (NSString *) webScriptNameForSelector:(SEL)selector {
2087 else if (selector == @selector(clear))
2089 else if (selector == @selector(getField:))
2091 else if (selector == @selector(hasTag:))
2093 else if (selector == @selector(install))
2095 else if (selector == @selector(remove))
2101 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2102 return [self webScriptNameForSelector:selector] == nil;
2105 + (NSArray *) _attributeKeys {
2106 return [NSArray arrayWithObjects:
2127 @"shortDescription",
2140 - (NSArray *) attributeKeys {
2141 return [[self class] _attributeKeys];
2144 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2145 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2148 - (NSArray *) relations {
2149 @synchronized (database_) {
2150 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2151 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2152 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2156 - (NSString *) architecture {
2158 @synchronized (database_) {
2159 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2162 - (NSString *) getField:(NSString *)name {
2163 @synchronized (database_) {
2164 if ([database_ era] != era_ || file_.end())
2167 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2169 const char *start, *end;
2170 if (!parser.Find([name UTF8String], start, end))
2171 return (NSString *) [NSNull null];
2173 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2177 if (parsed_ != NULL)
2179 @synchronized (database_) {
2180 if ([database_ era] != era_ || file_.end())
2183 ParsedPackage *parsed(new ParsedPackage);
2186 _profile(Package$parse)
2187 pkgRecords::Parser *parser;
2189 _profile(Package$parse$Lookup)
2190 parser = &[database_ records]->Lookup(file_);
2195 _profile(Package$parse$Find)
2200 {"architecture", &parsed->architecture_},
2201 {"icon", &parsed->icon_},
2202 {"depiction", &parsed->depiction_},
2203 {"homepage", &parsed->homepage_},
2204 {"website", &website},
2205 {"bugs", &parsed->bugs_},
2206 {"support", &parsed->support_},
2207 {"sponsor", &parsed->sponsor_},
2208 {"author", &parsed->author_},
2209 {"md5sum", &parsed->md5sum_},
2212 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2213 const char *start, *end;
2215 if (parser->Find(names[i].name_, start, end)) {
2216 CYString &value(*names[i].value_);
2217 _profile(Package$parse$Value)
2218 value.set(pool_, start, end - start);
2224 _profile(Package$parse$Tagline)
2225 const char *start, *end;
2226 if (parser->ShortDesc(start, end)) {
2227 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2230 while (stop != start && stop[-1] == '\r')
2232 parsed->tagline_.set(pool_, start, stop - start);
2236 _profile(Package$parse$Retain)
2237 if (parsed->homepage_.empty())
2238 parsed->homepage_ = website;
2239 if (parsed->homepage_ == parsed->depiction_)
2240 parsed->homepage_.clear();
2245 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2246 if ((self = [super init]) != nil) {
2247 _profile(Package$initWithVersion)
2249 apr_pool_create(&pool_, NULL);
2255 database_ = database;
2256 era_ = [database era];
2260 pkgCache::PkgIterator iterator(version.ParentPkg());
2261 iterator_ = iterator;
2263 _profile(Package$initWithVersion$Version)
2264 if (!version_.end())
2265 file_ = version_.FileList();
2267 pkgCache &cache([database_ cache]);
2268 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2272 _profile(Package$initWithVersion$Cache)
2273 name_.set(NULL, iterator.Display());
2275 latest_.set(NULL, StripVersion_(version_.VerStr()));
2277 pkgCache::VerIterator current(iterator.CurrentVer());
2279 installed_.set(NULL, StripVersion_(current.VerStr()));
2282 _profile(Package$initWithVersion$Tags)
2283 pkgCache::TagIterator tag(iterator.TagList());
2285 tags_ = [NSMutableArray arrayWithCapacity:8];
2287 const char *name(tag.Name());
2288 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2290 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2291 if (strcmp(name + 6, "enduser") == 0)
2293 else if (strcmp(name + 6, "hacker") == 0)
2295 else if (strcmp(name + 6, "developer") == 0)
2297 else if (strcmp(name + 6, "cydia") == 0)
2303 if (strncmp(name, "cydia::", 7) == 0) {
2304 if (strcmp(name + 7, "essential") == 0)
2306 else if (strcmp(name + 7, "obsolete") == 0)
2311 } while (!tag.end());
2315 _profile(Package$initWithVersion$Metadata)
2316 const char *mixed(iterator.Name());
2317 size_t size(strlen(mixed));
2318 char lower[size + 1];
2320 for (size_t i(0); i != size; ++i)
2321 lower[i] = mixed[i] | 0x20;
2324 PackageValue *metadata(PackageFind(lower, size));
2325 metadata_ = metadata;
2327 id_.set(NULL, metadata->name_, size);
2329 const char *latest(version_.VerStr());
2330 size_t length(strlen(latest));
2332 uint16_t vhash(hashlittle(latest, length));
2334 size_t capped(std::min<size_t>(8, length));
2335 latest = latest + length - capped;
2337 if (metadata->first_ == 0)
2338 metadata->first_ = now_;
2340 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2341 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2342 metadata->vhash_ = vhash;
2343 metadata->last_ = now_;
2344 } else if (metadata->last_ == 0)
2345 metadata->last_ = metadata->first_;
2348 _profile(Package$initWithVersion$Section)
2349 section_ = iterator.Section();
2352 _profile(Package$initWithVersion$Flags)
2353 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2354 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2359 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2360 pkgCache::VerIterator version;
2362 _profile(Package$packageWithIterator$GetCandidateVer)
2363 version = [database policy]->GetCandidateVer(iterator);
2371 _profile(Package$packageWithIterator$Allocate)
2372 package = [Package allocWithZone:zone];
2375 _profile(Package$packageWithIterator$Initialize)
2377 initWithVersion:version
2384 _profile(Package$packageWithIterator$Autorelease)
2385 package = [package autorelease];
2391 - (pkgCache::PkgIterator) iterator {
2395 - (NSString *) section {
2396 if (section$_ == nil) {
2397 if (section_ == NULL)
2400 _profile(Package$section$mappedSectionForPointer)
2401 section$_ = [database_ mappedSectionForPointer:section_];
2406 - (NSString *) simpleSection {
2407 if (NSString *section = [self section])
2408 return Simplify(section);
2413 - (NSString *) longSection {
2414 return LocalizeSection([self section]);
2417 - (NSString *) shortSection {
2418 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2421 - (NSString *) uri {
2424 pkgIndexFile *index;
2425 pkgCache::PkgFileIterator file(file_.File());
2426 if (![database_ list].FindIndex(file, index))
2428 return [NSString stringWithUTF8String:iterator_->Path];
2429 //return [NSString stringWithUTF8String:file.Site()];
2430 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2434 - (MIMEAddress *) maintainer {
2435 @synchronized (database_) {
2436 if ([database_ era] != era_ || file_.end())
2439 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2440 const std::string &maintainer(parser->Maintainer());
2441 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2444 - (NSString *) md5sum {
2445 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2449 @synchronized (database_) {
2450 if ([database_ era] != era_ || version_.end())
2453 return version_->InstalledSize;
2456 - (NSString *) longDescription {
2457 @synchronized (database_) {
2458 if ([database_ era] != era_ || file_.end())
2461 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2462 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2464 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2465 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2466 if ([lines count] < 2)
2469 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2470 for (size_t i(1), e([lines count]); i != e; ++i) {
2471 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2472 [trimmed addObject:trim];
2475 return [trimmed componentsJoinedByString:@"\n"];
2478 - (NSString *) shortDescription {
2479 if (parsed_ != NULL)
2480 return static_cast<NSString *>(parsed_->tagline_);
2482 @synchronized (database_) {
2483 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2485 const char *start, *end;
2486 if (!parser.ShortDesc(start, end))
2489 if (end - start > 200)
2493 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2496 while (end != start && end[-1] == '\r')
2500 return [(id) CYStringCreate(start, end - start) autorelease];
2504 _profile(Package$index)
2505 CFStringRef name((CFStringRef) [self name]);
2506 if (CFStringGetLength(name) == 0)
2508 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2509 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2511 return toupper(character);
2515 - (PackageValue *) metadata {
2520 PackageValue *metadata([self metadata]);
2521 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2524 - (bool) subscribed {
2525 return [self metadata]->subscribed_;
2528 - (bool) setSubscribed:(bool)subscribed {
2529 PackageValue *metadata([self metadata]);
2530 if (metadata->subscribed_ == subscribed)
2532 metadata->subscribed_ = subscribed;
2540 - (NSString *) latest {
2544 - (NSString *) installed {
2548 - (BOOL) uninstalled {
2549 return installed_.empty();
2553 return !version_.end();
2556 - (BOOL) upgradableAndEssential:(BOOL)essential {
2557 _profile(Package$upgradableAndEssential)
2558 pkgCache::VerIterator current(iterator_.CurrentVer());
2560 return essential && essential_;
2562 return !version_.end() && version_ != current;
2566 - (BOOL) essential {
2571 return [database_ cache][iterator_].InstBroken();
2574 - (BOOL) unfiltered {
2575 _profile(Package$unfiltered$obsolete)
2576 if (_unlikely(obsolete_))
2580 _profile(Package$unfiltered$hasSupportingRole)
2581 if (_unlikely(![self hasSupportingRole]))
2589 if (![self unfiltered])
2594 _profile(Package$visible$section)
2595 section = [self section];
2598 _profile(Package$visible$isSectionVisible)
2599 if (!isSectionVisible(section))
2607 unsigned char current(iterator_->CurrentState);
2608 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2611 - (BOOL) halfConfigured {
2612 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2615 - (BOOL) halfInstalled {
2616 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2620 @synchronized (database_) {
2621 if ([database_ era] != era_ || iterator_.end())
2624 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2625 return state.Mode != pkgDepCache::ModeKeep;
2628 - (NSString *) mode {
2629 @synchronized (database_) {
2630 if ([database_ era] != era_ || iterator_.end())
2633 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2635 switch (state.Mode) {
2636 case pkgDepCache::ModeDelete:
2637 if ((state.iFlags & pkgDepCache::Purge) != 0)
2641 case pkgDepCache::ModeKeep:
2642 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2643 return @"REINSTALL";
2644 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2648 case pkgDepCache::ModeInstall:
2649 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2650 return @"REINSTALL";
2651 else*/ switch (state.Status) {
2653 return @"DOWNGRADE";
2659 return @"NEW_INSTALL";
2670 - (NSString *) name {
2671 return name_.empty() ? id_ : name_;
2674 - (UIImage *) icon {
2675 NSString *section = [self simpleSection];
2678 if (parsed_ != NULL)
2679 if (NSString *href = parsed_->icon_)
2680 if ([href hasPrefix:@"file:///"])
2681 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2682 if (icon == nil) if (section != nil)
2683 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2684 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2685 if ([dicon hasPrefix:@"file:///"])
2686 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2688 icon = [UIImage applicationImageNamed:@"unknown.png"];
2692 - (NSString *) homepage {
2693 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2696 - (NSString *) depiction {
2697 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2700 - (MIMEAddress *) sponsor {
2701 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2704 - (MIMEAddress *) author {
2705 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2708 - (NSString *) support {
2709 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2712 - (NSArray *) files {
2713 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2714 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2717 fin.open([path UTF8String]);
2722 while (std::getline(fin, line))
2723 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2728 - (NSString *) state {
2729 @synchronized (database_) {
2730 if ([database_ era] != era_ || file_.end())
2733 switch (iterator_->CurrentState) {
2734 case pkgCache::State::NotInstalled:
2735 return @"NotInstalled";
2736 case pkgCache::State::UnPacked:
2738 case pkgCache::State::HalfConfigured:
2739 return @"HalfConfigured";
2740 case pkgCache::State::HalfInstalled:
2741 return @"HalfInstalled";
2742 case pkgCache::State::ConfigFiles:
2743 return @"ConfigFiles";
2744 case pkgCache::State::Installed:
2745 return @"Installed";
2746 case pkgCache::State::TriggersAwaited:
2747 return @"TriggersAwaited";
2748 case pkgCache::State::TriggersPending:
2749 return @"TriggersPending";
2752 return (NSString *) [NSNull null];
2755 - (NSString *) selection {
2756 @synchronized (database_) {
2757 if ([database_ era] != era_ || file_.end())
2760 switch (iterator_->SelectedState) {
2761 case pkgCache::State::Unknown:
2763 case pkgCache::State::Install:
2765 case pkgCache::State::Hold:
2767 case pkgCache::State::DeInstall:
2768 return @"DeInstall";
2769 case pkgCache::State::Purge:
2773 return (NSString *) [NSNull null];
2776 - (NSArray *) warnings {
2777 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2778 const char *name(iterator_.Name());
2780 size_t length(strlen(name));
2781 if (length < 2) invalid:
2782 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2783 else for (size_t i(0); i != length; ++i)
2785 /* XXX: technically this is not allowed */
2786 (name[i] < 'A' || name[i] > 'Z') &&
2787 (name[i] < 'a' || name[i] > 'z') &&
2788 (name[i] < '0' || name[i] > '9') &&
2789 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2792 if (strcmp(name, "cydia") != 0) {
2795 bool _private = false;
2798 bool repository = [[self section] isEqualToString:@"Repositories"];
2800 if (NSArray *files = [self files])
2801 for (NSString *file in files)
2802 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2804 else if (!user && [file isEqualToString:@"/User"])
2806 else if (!_private && [file isEqualToString:@"/private"])
2808 else if (!stash && [file isEqualToString:@"/var/stash"])
2811 /* XXX: this is not sensitive enough. only some folders are valid. */
2812 if (cydia && !repository)
2813 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2815 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2817 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2819 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2822 return [warnings count] == 0 ? nil : warnings;
2825 - (NSArray *) applications {
2826 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2828 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2830 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2831 if (NSArray *files = [self files])
2832 for (NSString *file in files)
2833 if (application_r(file)) {
2834 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2835 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2836 if ([id isEqualToString:me])
2839 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2841 display = application_r[1];
2843 NSString *bundle([file stringByDeletingLastPathComponent]);
2844 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2845 if (icon == nil || [icon length] == 0)
2847 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2849 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2850 [applications addObject:application];
2852 [application addObject:id];
2853 [application addObject:display];
2854 [application addObject:url];
2857 return [applications count] == 0 ? nil : applications;
2860 - (Source *) source {
2861 if (source_ == nil) {
2862 @synchronized (database_) {
2863 if ([database_ era] != era_ || file_.end())
2864 source_ = (Source *) [NSNull null];
2866 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2870 return source_ == (Source *) [NSNull null] ? nil : source_;
2877 - (BOOL) matches:(NSArray *)query {
2878 if (query == nil || [query count] == 0)
2887 string = [self name];
2888 length = [string length];
2890 for (NSString *term in query) {
2891 range = [string rangeOfString:term options:MatchCompareOptions_];
2892 if (range.location != NSNotFound)
2893 rank_ -= 6 * 1000000 / length;
2898 length = [string length];
2900 for (NSString *term in query) {
2901 range = [string rangeOfString:term options:MatchCompareOptions_];
2902 if (range.location != NSNotFound)
2903 rank_ -= 6 * 1000000 / length;
2907 string = [self shortDescription];
2908 length = [string length];
2909 NSUInteger stop(std::min<NSUInteger>(length, 200));
2911 for (NSString *term in query) {
2912 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2913 if (range.location != NSNotFound)
2914 rank_ -= 2 * 100000;
2920 - (bool) hasSupportingRole {
2925 if ([Role_ isEqualToString:@"User"])
2929 if ([Role_ isEqualToString:@"Hacker"])
2933 if ([Role_ isEqualToString:@"Developer"])
2938 - (NSArray *) tags {
2942 - (BOOL) hasTag:(NSString *)tag {
2943 return tags_ == nil ? NO : [tags_ containsObject:tag];
2946 - (NSString *) primaryPurpose {
2947 for (NSString *tag in (NSArray *) tags_)
2948 if ([tag hasPrefix:@"purpose::"])
2949 return [tag substringFromIndex:9];
2953 - (NSArray *) purposes {
2954 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2955 for (NSString *tag in (NSArray *) tags_)
2956 if ([tag hasPrefix:@"purpose::"])
2957 [purposes addObject:[tag substringFromIndex:9]];
2958 return [purposes count] == 0 ? nil : purposes;
2961 - (bool) isCommercial {
2962 return [self hasTag:@"cydia::commercial"];
2965 - (void) setIndex:(size_t)index {
2966 if (metadata_->index_ != index)
2967 metadata_->index_ = index;
2970 - (CYString &) cyname {
2971 return name_.empty() ? id_ : name_;
2974 - (uint32_t) compareBySection:(NSArray *)sections {
2975 NSString *section([self section]);
2976 for (size_t i(0), e([sections count]); i != e; ++i) {
2977 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2981 return _not(uint32_t);
2985 @synchronized (database_) {
2986 pkgProblemResolver *resolver = [database_ resolver];
2987 resolver->Clear(iterator_);
2989 pkgCacheFile &cache([database_ cache]);
2990 cache->SetReInstall(iterator_, false);
2991 cache->MarkKeep(iterator_, false);
2995 @synchronized (database_) {
2996 pkgProblemResolver *resolver = [database_ resolver];
2997 resolver->Clear(iterator_);
2998 resolver->Protect(iterator_);
3000 pkgCacheFile &cache([database_ cache]);
3001 cache->SetReInstall(iterator_, false);
3002 cache->MarkInstall(iterator_, false);
3004 pkgDepCache::StateCache &state((*cache)[iterator_]);
3005 if (!state.Install())
3006 cache->SetReInstall(iterator_, true);
3010 @synchronized (database_) {
3011 pkgProblemResolver *resolver = [database_ resolver];
3012 resolver->Clear(iterator_);
3013 resolver->Remove(iterator_);
3014 resolver->Protect(iterator_);
3016 pkgCacheFile &cache([database_ cache]);
3017 cache->SetReInstall(iterator_, false);
3018 cache->MarkDelete(iterator_, true);
3021 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3022 _profile(Package$isUnfilteredAndSearchedForBy)
3025 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3026 value &= [self unfiltered];
3029 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3030 value &= [self matches:query];
3037 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3038 if ([search length] == 0)
3041 _profile(Package$isUnfilteredAndSelectedForBy)
3044 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3045 value &= [self unfiltered];
3048 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3049 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3056 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3057 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3060 - (bool) isVisibleInSection:(NSString *)name {
3061 NSString *section([self section]);
3065 section == nil && [name length] == 0 ||
3066 [name isEqualToString:section]
3067 ) && [self visible];
3070 - (bool) isVisibleInSource:(Source *)source {
3071 return [self source] == source && [self visible];
3076 /* Section Class {{{ */
3077 @interface Section : NSObject {
3082 _H<NSString> localized_;
3085 - (NSComparisonResult) compareByLocalized:(Section *)section;
3086 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3087 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3088 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3089 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3090 - (NSString *) name;
3097 - (void) addToCount;
3099 - (void) setCount:(size_t)count;
3100 - (NSString *) localized;
3104 @implementation Section
3106 - (NSComparisonResult) compareByLocalized:(Section *)section {
3107 NSString *lhs(localized_);
3108 NSString *rhs([section localized]);
3110 /*if ([lhs length] != 0 && [rhs length] != 0) {
3111 unichar lhc = [lhs characterAtIndex:0];
3112 unichar rhc = [rhs characterAtIndex:0];
3114 if (isalpha(lhc) && !isalpha(rhc))
3115 return NSOrderedAscending;
3116 else if (!isalpha(lhc) && isalpha(rhc))
3117 return NSOrderedDescending;
3120 return [lhs compare:rhs options:LaxCompareOptions_];
3123 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3124 if ((self = [self initWithName:name localize:NO]) != nil) {
3125 if (localized != nil)
3126 localized_ = localized;
3130 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3131 return [self initWithName:name row:0 localize:localize];
3134 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3135 if ((self = [super init]) != nil) {
3140 localized_ = LocalizeSection(name_);
3144 /* XXX: localize the index thingees */
3145 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3146 if ((self = [super init]) != nil) {
3147 name_ = [NSString stringWithCharacters:&index length:1];
3153 - (NSString *) name {
3173 - (void) addToCount {
3177 - (void) setCount:(size_t)count {
3181 - (NSString *) localized {
3188 class CydiaLogCleaner :
3189 public pkgArchiveCleaner
3192 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3197 /* Database Implementation {{{ */
3198 @implementation Database
3200 + (Database *) sharedInstance {
3201 static _H<Database> instance;
3202 if (instance == nil)
3203 instance = [[[Database alloc] init] autorelease];
3211 - (void) releasePackages {
3212 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3213 CFArrayRemoveAllValues(packages_);
3217 // XXX: actually implement this thing
3219 [self releasePackages];
3220 apr_pool_destroy(pool_);
3221 NSRecycleZone(zone_);
3225 - (void) _readCydia:(NSNumber *)fd {
3226 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3227 std::istream is(&ib);
3230 static Pcre finish_r("^finish:([^:]*)$");
3232 while (std::getline(is, line)) {
3233 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3235 const char *data(line.c_str());
3236 size_t size = line.size();
3237 lprintf("C:%s\n", data);
3239 if (finish_r(data, size)) {
3240 NSString *finish = finish_r[1];
3241 int index = [Finishes_ indexOfObject:finish];
3242 if (index != INT_MAX && index > Finish_)
3252 - (void) _readStatus:(NSNumber *)fd {
3253 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3254 std::istream is(&ib);
3257 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3258 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3260 while (std::getline(is, line)) {
3261 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3263 const char *data(line.c_str());
3264 size_t size(line.size());
3265 lprintf("S:%s\n", data);
3267 if (conffile_r(data, size)) {
3268 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3269 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3270 } else if (strncmp(data, "status: ", 8) == 0) {
3271 // status: <package>: {unpacked,half-configured,installed}
3272 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3273 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3274 } else if (strncmp(data, "processing: ", 12) == 0) {
3275 // processing: configure: config-test
3276 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3277 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3278 } else if (pmstatus_r(data, size)) {
3279 std::string type([pmstatus_r[1] UTF8String]);
3281 NSString *package = pmstatus_r[2];
3282 if ([package isEqualToString:@"dpkg-exec"])
3285 float percent([pmstatus_r[3] floatValue]);
3286 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3288 NSString *string = pmstatus_r[4];
3290 if (type == "pmerror") {
3291 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3292 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3293 } else if (type == "pmstatus") {
3294 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3295 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3296 } else if (type == "pmconffile")
3297 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3299 lprintf("E:unknown pmstatus\n");
3301 lprintf("E:unknown status\n");
3309 - (void) _readOutput:(NSNumber *)fd {
3310 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3311 std::istream is(&ib);
3314 while (std::getline(is, line)) {
3315 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3317 lprintf("O:%s\n", line.c_str());
3319 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3320 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3332 - (Package *) packageWithName:(NSString *)name {
3335 @synchronized (self) {
3336 if (static_cast<pkgDepCache *>(cache_) == NULL)
3338 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3339 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3343 if ((self = [super init]) != nil) {
3350 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3351 apr_pool_create(&pool_, NULL);
3353 size_t capacity(MetaFile_->active_);
3359 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3360 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3364 _assert(pipe(fds) != -1);
3367 _config->Set("APT::Keep-Fds::", cydiafd_);
3368 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3371 detachNewThreadSelector:@selector(_readCydia:)
3373 withObject:[NSNumber numberWithInt:fds[0]]
3376 _assert(pipe(fds) != -1);
3380 detachNewThreadSelector:@selector(_readStatus:)
3382 withObject:[NSNumber numberWithInt:fds[0]]
3385 _assert(pipe(fds) != -1);
3386 _assert(dup2(fds[0], 0) != -1);
3387 _assert(close(fds[0]) != -1);
3389 input_ = fdopen(fds[1], "a");
3391 _assert(pipe(fds) != -1);
3392 _assert(dup2(fds[1], 1) != -1);
3393 _assert(close(fds[1]) != -1);
3396 detachNewThreadSelector:@selector(_readOutput:)
3398 withObject:[NSNumber numberWithInt:fds[0]]
3403 - (pkgCacheFile &) cache {
3407 - (pkgDepCache::Policy *) policy {
3411 - (pkgRecords *) records {
3415 - (pkgProblemResolver *) resolver {
3419 - (pkgAcquire &) fetcher {
3423 - (pkgSourceList &) list {
3427 - (NSArray *) packages {
3428 return (NSArray *) packages_;
3431 - (NSArray *) sources {
3435 - (Source *) sourceWithKey:(NSString *)key {
3436 for (Source *source in [self sources]) {
3437 if ([[source key] isEqualToString:key])
3442 - (bool) popErrorWithTitle:(NSString *)title {
3445 while (!_error->empty()) {
3447 bool warning(!_error->PopMessage(error));
3452 size_t size(error.size());
3453 if (size == 0 || error[size - 1] != '\n')
3455 error.resize(size - 1);
3458 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3460 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3461 if (warning && no_pubkey(error.c_str()))
3464 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3470 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3471 return [self popErrorWithTitle:title] || !success;
3474 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3475 @synchronized (self) {
3478 [self releasePackages];
3481 [sourceList_ removeAllObjects];
3501 apr_pool_clear(pool_);
3503 NSRecycleZone(zone_);
3504 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3506 int chk(creat("/tmp/cydia.chk", 0644));
3510 if (invocation != nil)
3511 [invocation invoke];
3513 NSString *title(UCLocalize("DATABASE"));
3516 OpProgress progress;
3517 while (!cache_.Open(progress, true)) { pop:
3519 bool warning(!_error->PopMessage(error));
3520 lprintf("cache_.Open():[%s]\n", error.c_str());
3522 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3523 [delegate_ repairWithSelector:@selector(configure)];
3524 else if (error == "The package lists or status file could not be parsed or opened.")
3525 [delegate_ repairWithSelector:@selector(update)];
3526 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3527 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3528 // else if (error == "Malformed Status line")
3529 // else if (error == "The list of sources could not be read.")
3531 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3541 unlink("/tmp/cydia.chk");
3543 now_ = [[NSDate date] timeIntervalSince1970];
3545 policy_ = new pkgDepCache::Policy();
3546 records_ = new pkgRecords(cache_);
3547 resolver_ = new pkgProblemResolver(cache_);
3548 fetcher_ = new pkgAcquire(&status_);
3551 list_ = new pkgSourceList();
3552 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3555 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3556 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3560 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3563 if (cache_->BrokenCount() != 0) {
3564 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3567 if (cache_->BrokenCount() != 0) {
3568 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3572 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3576 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3577 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3578 [sourceList_ addObject:object];
3580 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3581 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3582 // XXX: this could be more intelligent
3583 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3584 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3586 sourceMap_[cached->ID] = object;
3591 /*std::vector<Package *> packages;
3592 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3597 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3598 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3599 //packages.push_back(package);
3600 CFArrayAppendValue(packages_, CFRetain(package));
3604 /*if (packages.empty())
3605 packages_ = [[NSArray alloc] init];
3607 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3610 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3611 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3612 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3620 /*if (!packages.empty())
3621 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3622 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3624 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3626 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3628 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3632 size_t count(CFArrayGetCount(packages_));
3633 MetaFile_->active_ = count;
3635 for (size_t index(0); index != count; ++index)
3636 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3643 @synchronized (self) {
3645 resolver_ = new pkgProblemResolver(cache_);
3647 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3648 if (!cache_[iterator].Keep())
3649 cache_->MarkKeep(iterator, false);
3650 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3651 cache_->SetReInstall(iterator, false);
3654 - (void) configure {
3655 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3657 system([dpkg UTF8String]);
3662 // XXX: I don't remember this condition
3667 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3669 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3671 if ([self popErrorWithTitle:title])
3675 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3677 CydiaLogCleaner cleaner;
3678 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3685 fetcher_->Shutdown();
3687 pkgRecords records(cache_);
3689 lock_ = new FileFd();
3690 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3692 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3694 if ([self popErrorWithTitle:title])
3698 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3701 manager_ = (_system->CreatePM(cache_));
3702 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3709 bool substrate(RestartSubstrate_);
3710 RestartSubstrate_ = false;
3712 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3714 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3716 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3718 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3719 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3722 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3724 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3726 [self popErrorWithTitle:title];
3730 bool failed = false;
3731 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3732 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3734 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3740 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3748 RestartSubstrate_ = true;
3751 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3753 if (_error->PendingError()) {
3758 if (result == pkgPackageManager::Failed) {
3763 if (result != pkgPackageManager::Completed) {
3768 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3770 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3772 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3773 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3776 if (![before isEqualToArray:after])
3781 NSString *title(UCLocalize("UPGRADE"));
3782 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3788 [self updateWithStatus:status_];
3791 - (void) updateWithStatus:(Status &)status {
3792 NSString *title(UCLocalize("REFRESHING_DATA"));
3795 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3799 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3800 if ([self popErrorWithTitle:title])
3803 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3805 bool success(ListUpdate(status, list, PulseInterval_));
3806 if (status.WasCancelled())
3809 [self popErrorWithTitle:title forOperation:success];
3810 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3814 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3817 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3818 delegate_ = delegate;
3821 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3822 progress_ = delegate;
3823 status_.setDelegate(delegate);
3826 - (NSObject<ProgressDelegate> *) progressDelegate {
3830 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3831 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3832 return i == sourceMap_.end() ? nil : i->second;
3835 - (NSString *) mappedSectionForPointer:(const char *)section {
3836 _H<NSString> *mapped;
3838 _profile(Database$mappedSectionForPointer$Cache)
3839 mapped = §ions_[section];
3842 if (*mapped == NULL) {
3843 size_t length(strlen(section));
3844 char spaced[length + 1];
3846 _profile(Database$mappedSectionForPointer$Replace)
3847 for (size_t index(0); index != length; ++index)
3848 spaced[index] = section[index] == '_' ? ' ' : section[index];
3849 spaced[length] = '\0';
3854 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3855 string = [NSString stringWithUTF8String:spaced];
3858 _profile(Database$mappedSectionForPointer$Map)
3859 string = [SectionMap_ objectForKey:string] ?: string;
3869 static _H<NSMutableSet> Diversions_;
3871 @interface Diversion : NSObject {
3874 _H<NSString> format_;
3879 @implementation Diversion
3881 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3882 if ((self = [super init]) != nil) {
3883 pattern_ = [from UTF8String];
3889 - (NSString *) divert:(NSString *)url {
3890 return !pattern_(url) ? nil : pattern_->*format_;
3893 + (NSURL *) divertURL:(NSURL *)url {
3895 NSString *href([url absoluteString]);
3897 for (Diversion *diversion in (id) Diversions_)
3898 if (NSString *diverted = [diversion divert:href]) {
3900 NSLog(@"div: %@", diverted);
3902 url = [NSURL URLWithString:diverted];
3909 - (NSString *) key {
3913 - (NSUInteger) hash {
3917 - (BOOL) isEqual:(Diversion *)object {
3918 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3923 @interface CydiaObject : NSObject {
3924 _H<IndirectDelegate> indirect_;
3925 _transient id delegate_;
3928 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3932 @interface CydiaWebViewController : CyteWebViewController {
3933 _H<CydiaObject> cydia_;
3936 + (void) addDiversion:(Diversion *)diversion;
3940 /* Web Scripting {{{ */
3941 @implementation CydiaObject
3943 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3944 if ((self = [super init]) != nil) {
3945 indirect_ = indirect;
3949 - (void) setDelegate:(id)delegate {
3950 delegate_ = delegate;
3953 + (NSArray *) _attributeKeys {
3954 return [NSArray arrayWithObjects:
3973 - (NSArray *) attributeKeys {
3974 return [[self class] _attributeKeys];
3977 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3978 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3981 - (NSString *) version {
3985 - (NSString *) device {
3986 return [[UIDevice currentDevice] uniqueIdentifier];
3989 - (NSString *) firmware {
3990 return [[UIDevice currentDevice] systemVersion];
3993 - (NSString *) hostname {
3994 return [[UIDevice currentDevice] name];
3997 - (NSString *) idiom {
3998 return (id) Idiom_ ?: [NSNull null];
4001 - (NSString *) mcc {
4002 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4003 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4007 - (NSString *) mnc {
4008 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4009 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4013 - (NSString *) operator {
4014 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4015 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4019 - (NSString *) bbsnum {
4020 return (id) BBSNum_ ?: [NSNull null];
4023 - (NSString *) ecid {
4024 return (id) ChipID_ ?: [NSNull null];
4027 - (NSString *) serial {
4028 return SerialNumber_;
4031 - (NSString *) role {
4032 return (id) Role_ ?: [NSNull null];
4035 - (NSString *) model {
4036 return [NSString stringWithUTF8String:Machine_];
4039 - (NSString *) token {
4040 return (id) Token_ ?: [NSNull null];
4043 + (NSString *) webScriptNameForSelector:(SEL)selector {
4045 else if (selector == @selector(addBridgedHost:))
4046 return @"addBridgedHost";
4047 else if (selector == @selector(addInsecureHost:))
4048 return @"addInsecureHost";
4049 else if (selector == @selector(addInternalRedirect::))
4050 return @"addInternalRedirect";
4051 else if (selector == @selector(addPipelinedHost:scheme:))
4052 return @"addPipelinedHost";
4053 else if (selector == @selector(addSource:::))
4054 return @"addSource";
4055 else if (selector == @selector(addTokenHost:))
4056 return @"addTokenHost";
4057 else if (selector == @selector(addTrivialSource:))
4058 return @"addTrivialSource";
4059 else if (selector == @selector(close))
4061 else if (selector == @selector(du:))
4063 else if (selector == @selector(stringWithFormat:arguments:))
4065 else if (selector == @selector(getAllSources))
4066 return @"getAllSourcs";
4067 else if (selector == @selector(getKernelNumber:))
4068 return @"getKernelNumber";
4069 else if (selector == @selector(getKernelString:))
4070 return @"getKernelString";
4071 else if (selector == @selector(getInstalledPackages))
4072 return @"getInstalledPackages";
4073 else if (selector == @selector(getIORegistryEntry::))
4074 return @"getIORegistryEntry";
4075 else if (selector == @selector(getLocaleIdentifier))
4076 return @"getLocaleIdentifier";
4077 else if (selector == @selector(getPreferredLanguages))
4078 return @"getPreferredLanguages";
4079 else if (selector == @selector(getPackageById:))
4080 return @"getPackageById";
4081 else if (selector == @selector(getMetadataKeys))
4082 return @"getMetadataKeys";
4083 else if (selector == @selector(getMetadataValue:))
4084 return @"getMetadataValue";
4085 else if (selector == @selector(getSessionValue:))
4086 return @"getSessionValue";
4087 else if (selector == @selector(installPackages:))
4088 return @"installPackages";
4089 else if (selector == @selector(localizedStringForKey:value:table:))
4091 else if (selector == @selector(popViewController:))
4092 return @"popViewController";
4093 else if (selector == @selector(refreshSources))
4094 return @"refreshSources";
4095 else if (selector == @selector(removeButton))
4096 return @"removeButton";
4097 else if (selector == @selector(saveConfig))
4098 return @"saveConfig";
4099 else if (selector == @selector(setMetadataValue::))
4100 return @"setMetadataValue";
4101 else if (selector == @selector(setSessionValue::))
4102 return @"setSessionValue";
4103 else if (selector == @selector(substitutePackageNames:))
4104 return @"substitutePackageNames";
4105 else if (selector == @selector(scrollToBottom:))
4106 return @"scrollToBottom";
4107 else if (selector == @selector(setAllowsNavigationAction:))
4108 return @"setAllowsNavigationAction";
4109 else if (selector == @selector(setBadgeValue:))
4110 return @"setBadgeValue";
4111 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4112 return @"setButtonImage";
4113 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4114 return @"setButtonTitle";
4115 else if (selector == @selector(setHidesBackButton:))
4116 return @"setHidesBackButton";
4117 else if (selector == @selector(setHidesNavigationBar:))
4118 return @"setHidesNavigationBar";
4119 else if (selector == @selector(setNavigationBarStyle:))
4120 return @"setNavigationBarStyle";
4121 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4122 return @"setNavigationBarTintColor";
4123 else if (selector == @selector(setPasteboardString:))
4124 return @"setPasteboardString";
4125 else if (selector == @selector(setPasteboardURL:))
4126 return @"setPasteboardURL";
4127 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4128 return @"setScrollAlwaysBounceVertical";
4129 else if (selector == @selector(setScrollIndicatorStyle:))
4130 return @"setScrollIndicatorStyle";
4131 else if (selector == @selector(setToken:))
4133 else if (selector == @selector(setViewportWidth:))
4134 return @"setViewportWidth";
4135 else if (selector == @selector(statfs:))
4137 else if (selector == @selector(supports:))
4139 else if (selector == @selector(unload))
4145 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4146 return [self webScriptNameForSelector:selector] == nil;
4149 - (BOOL) supports:(NSString *)feature {
4150 return [feature isEqualToString:@"window.open"];
4154 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4157 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4158 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4161 - (void) setScrollIndicatorStyle:(NSString *)style {
4162 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4165 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4166 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4169 - (NSNumber *) getKernelNumber:(NSString *)name {
4170 const char *string([name UTF8String]);
4173 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4174 return (id) [NSNull null];
4176 if (size != sizeof(int))
4177 return (id) [NSNull null];
4180 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4181 return (id) [NSNull null];
4183 return [NSNumber numberWithInt:value];
4186 - (NSString *) getKernelString:(NSString *)name {
4187 const char *string([name UTF8String]);
4190 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4191 return (id) [NSNull null];
4193 char value[size + 1];
4194 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4195 return (id) [NSNull null];
4197 // XXX: just in case you request something ludicrous
4200 return [NSString stringWithCString:value];
4203 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4204 NSObject *value(CYIOGetValue([path UTF8String], entry));
4207 if ([value isKindOfClass:[NSData class]])
4208 value = CYHex((NSData *) value);
4213 - (NSArray *) getMetadataKeys {
4214 @synchronized (Values_) {
4215 return [Values_ allKeys];
4218 - (id) getMetadataValue:(NSString *)key {
4219 @synchronized (Values_) {
4220 return [Values_ objectForKey:key];
4223 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4224 @synchronized (Values_) {
4225 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4226 [Values_ removeObjectForKey:key];
4228 [Values_ setObject:value forKey:key];
4230 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4233 - (id) getSessionValue:(NSString *)key {
4234 @synchronized (SessionData_) {
4235 return [SessionData_ objectForKey:key];
4238 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4239 @synchronized (SessionData_) {
4240 if (value == (id) [WebUndefined undefined])
4241 [SessionData_ removeObjectForKey:key];
4243 [SessionData_ setObject:value forKey:key];
4246 - (void) addBridgedHost:(NSString *)host {
4247 @synchronized (HostConfig_) {
4248 [BridgedHosts_ addObject:host];
4251 - (void) addInsecureHost:(NSString *)host {
4252 @synchronized (HostConfig_) {
4253 [InsecureHosts_ addObject:host];
4256 - (void) addTokenHost:(NSString *)host {
4257 @synchronized (HostConfig_) {
4258 [TokenHosts_ addObject:host];
4261 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4262 @synchronized (HostConfig_) {
4263 if (scheme != (id) [WebUndefined undefined])
4264 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4266 [PipelinedHosts_ addObject:host];
4269 - (void) popViewController:(NSNumber *)value {
4270 if (value == (id) [WebUndefined undefined])
4271 value = [NSNumber numberWithBool:YES];
4272 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4275 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4276 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4278 for (NSString *section in sections)
4279 [array addObject:section];
4281 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4284 distribution, @"Distribution",
4286 nil] waitUntilDone:NO];
4289 - (void) addTrivialSource:(NSString *)href {
4290 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4293 - (void) refreshSources {
4294 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4297 - (void) saveConfig {
4298 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4301 - (NSArray *) getAllSources {
4302 return [[Database sharedInstance] sources];
4305 - (NSArray *) getInstalledPackages {
4306 Database *database([Database sharedInstance]);
4307 @synchronized (database) {
4308 NSArray *packages([database packages]);
4309 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4310 for (Package *package in packages)
4311 if (![package uninstalled])
4312 [installed addObject:package];
4316 - (Package *) getPackageById:(NSString *)id {
4317 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4321 return (Package *) [NSNull null];
4324 - (NSString *) getLocaleIdentifier {
4325 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4328 - (NSArray *) getPreferredLanguages {
4332 - (NSArray *) statfs:(NSString *)path {
4335 if (path == nil || statfs([path UTF8String], &stat) == -1)
4338 return [NSArray arrayWithObjects:
4339 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4340 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4341 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4345 - (NSNumber *) du:(NSString *)path {
4346 NSNumber *value(nil);
4349 _assert(pipe(fds) != -1);
4351 pid_t pid(ExecFork());
4353 _assert(dup2(fds[1], 1) != -1);
4354 _assert(close(fds[0]) != -1);
4355 _assert(close(fds[1]) != -1);
4356 /* XXX: this should probably not use du */
4357 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4362 _assert(close(fds[1]) != -1);
4364 if (FILE *du = fdopen(fds[0], "r")) {
4366 while (fgets(line, sizeof(line), du) != NULL) {
4367 size_t length(strlen(line));
4368 while (length != 0 && line[length - 1] == '\n')
4369 line[--length] = '\0';
4370 if (char *tab = strchr(line, '\t')) {
4372 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4377 } else _assert(close(fds[0]));
4385 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4388 - (void) installPackages:(NSArray *)packages {
4389 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4392 - (NSString *) substitutePackageNames:(NSString *)message {
4393 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4394 for (size_t i(0), e([words count]); i != e; ++i) {
4395 NSString *word([words objectAtIndex:i]);
4396 if (Package *package = [[Database sharedInstance] packageWithName:word])
4397 [words replaceObjectAtIndex:i withObject:[package name]];
4400 return [words componentsJoinedByString:@" "];
4403 - (void) removeButton {
4404 [indirect_ removeButton];
4407 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4408 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4411 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4412 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4415 - (void) setBadgeValue:(id)value {
4416 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4419 - (void) setAllowsNavigationAction:(NSString *)value {
4420 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4423 - (void) setHidesBackButton:(NSString *)value {
4424 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4427 - (void) setHidesNavigationBar:(NSString *)value {
4428 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4431 - (void) setNavigationBarStyle:(NSString *)value {
4432 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4435 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4436 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4437 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4438 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4441 - (void) setPasteboardString:(NSString *)value {
4442 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4445 - (void) setPasteboardURL:(NSString *)value {
4446 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4449 - (void) _setToken:(NSString *)token {
4453 [Metadata_ removeObjectForKey:@"Token"];
4455 [Metadata_ setObject:Token_ forKey:@"Token"];
4460 - (void) setToken:(NSString *)token {
4461 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4464 - (void) scrollToBottom:(NSNumber *)animated {
4465 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4468 - (void) setViewportWidth:(float)width {
4469 [indirect_ setViewportWidthOnMainThread:width];
4472 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4473 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4474 unsigned count([arguments count]);
4476 for (unsigned i(0); i != count; ++i)
4477 values[i] = [arguments objectAtIndex:i];
4478 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4481 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4482 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4484 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4486 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4492 @interface NSURL (CydiaSecure)
4495 @implementation NSURL (CydiaSecure)
4497 - (bool) isCydiaSecure {
4498 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4501 @synchronized (HostConfig_) {
4502 if ([InsecureHosts_ containsObject:[self host]])
4511 /* Cydia Browser Controller {{{ */
4512 @implementation CydiaWebViewController
4514 - (NSURL *) navigationURL {
4515 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4518 + (void) _initialize {
4519 [super _initialize];
4521 Diversions_ = [NSMutableSet setWithCapacity:0];
4524 + (void) addDiversion:(Diversion *)diversion {
4525 [Diversions_ addObject:diversion];
4528 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4529 [super webView:view didClearWindowObject:window forFrame:frame];
4531 WebDataSource *source([frame dataSource]);
4532 NSURLResponse *response([source response]);
4533 NSURL *url([response URL]);
4534 NSString *scheme([[url scheme] lowercaseString]);
4536 bool bridged(false);
4538 @synchronized (HostConfig_) {
4539 if ([scheme isEqualToString:@"file"])
4541 else if ([scheme isEqualToString:@"https"])
4542 if ([BridgedHosts_ containsObject:[url host]])
4547 [window setValue:cydia_ forKey:@"cydia"];
4550 - (void) _setupMail:(MFMailComposeViewController *)controller {
4551 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4553 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4554 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4557 - (NSURL *) URLWithURL:(NSURL *)url {
4558 return [Diversion divertURL:url];
4561 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4562 NSURL *url([request URL]);
4563 NSString *host([url host]);
4565 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4567 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4568 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4573 @synchronized (HostConfig_) {
4574 bridged = [BridgedHosts_ containsObject:host];
4575 token = [TokenHosts_ containsObject:host];
4578 if ([url isCydiaSecure]) {
4580 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4581 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4583 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4584 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4591 - (void) setDelegate:(id)delegate {
4592 [super setDelegate:delegate];
4593 [cydia_ setDelegate:delegate];
4596 - (NSString *) applicationNameForUserAgent {
4597 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4600 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4602 application = [NSString stringWithFormat:@"Mobile/%@ %@", (id) System_, application];
4603 if (Product_ != nil)
4604 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4610 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4611 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4617 @interface AppCacheController : CydiaWebViewController {
4622 @implementation AppCacheController
4624 - (void) didReceiveMemoryWarning {
4631 @interface NSObject (CydiaScript)
4632 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4635 @implementation NSObject (CydiaScript)
4637 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4643 @implementation NSArray (CydiaScript)
4645 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4646 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4647 for (size_t i(0), e([self count]); i != e; ++i)
4648 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4654 @implementation NSDictionary (CydiaScript)
4656 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4657 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4659 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4666 /* Confirmation Controller {{{ */
4667 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4668 if (!iterator.end())
4669 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4670 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4672 pkgCache::PkgIterator package(dep.TargetPkg());
4675 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4682 @protocol ConfirmationControllerDelegate
4683 - (void) cancelAndClear:(bool)clear;
4684 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4688 @interface ConfirmationController : CydiaWebViewController {
4689 _transient Database *database_;
4691 _H<UIAlertView> essential_;
4693 _H<NSDictionary> changes_;
4694 _H<NSMutableArray> issues_;
4695 _H<NSDictionary> sizes_;
4700 - (id) initWithDatabase:(Database *)database;
4704 @implementation ConfirmationController
4708 RestartSubstrate_ = true;
4709 [delegate_ confirmWithNavigationController:[self navigationController]];
4712 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4713 NSString *context([alert context]);
4715 if ([context isEqualToString:@"remove"]) {
4716 if (button == [alert cancelButtonIndex])
4717 [self dismissModalViewControllerAnimated:YES];
4718 else if (button == [alert firstOtherButtonIndex]) {
4722 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4723 } else if ([context isEqualToString:@"unable"]) {
4724 [self dismissModalViewControllerAnimated:YES];
4725 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4727 [super alertView:alert clickedButtonAtIndex:button];
4731 - (void) _doContinue {
4732 [delegate_ cancelAndClear:NO];
4733 [self dismissModalViewControllerAnimated:YES];
4736 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4737 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4741 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4742 [super webView:view didClearWindowObject:window forFrame:frame];
4744 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4745 (id) changes_, @"changes",
4746 (id) issues_, @"issues",
4747 (id) sizes_, @"sizes",
4749 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4752 - (id) initWithDatabase:(Database *)database {
4753 if ((self = [super init]) != nil) {
4754 database_ = database;
4756 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4757 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4758 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4759 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4760 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4764 pkgCacheFile &cache([database_ cache]);
4765 NSArray *packages([database_ packages]);
4766 pkgDepCache::Policy *policy([database_ policy]);
4768 issues_ = [NSMutableArray arrayWithCapacity:4];
4770 for (Package *package in packages) {
4771 pkgCache::PkgIterator iterator([package iterator]);
4772 NSString *name([package id]);
4774 if ([package broken]) {
4775 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4777 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4779 reasons, @"reasons",
4782 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4786 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4787 pkgCache::DepIterator start;
4788 pkgCache::DepIterator end;
4789 dep.GlobOr(start, end); // ++dep
4791 if (!cache->IsImportantDep(end))
4793 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4796 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4798 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4799 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4800 clauses, @"clauses",
4804 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4806 pkgCache::PkgIterator target(start.TargetPkg());
4807 if (target->ProvidesList != 0)
4808 reason = @"missing";
4810 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4812 reason = @"installed";
4813 installed = [NSString stringWithUTF8String:ver.VerStr()];
4814 } else if (!cache[target].CandidateVerIter(cache).end())
4815 reason = @"uninstalled";
4816 else if (target->ProvidesList == 0)
4817 reason = @"uninstallable";
4819 reason = @"virtual";
4822 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4823 [NSString stringWithUTF8String:start.CompType()], @"operator",
4824 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4827 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4828 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4829 version, @"version",
4831 installed, @"installed",
4834 // yes, seriously. (wtf?)
4842 pkgDepCache::StateCache &state(cache[iterator]);
4844 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4846 if (state.NewInstall())
4847 [installs addObject:name];
4848 // XXX: else if (state.Install())
4849 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4850 [reinstalls addObject:name];
4851 // XXX: move before previous if
4852 else if (state.Upgrade())
4853 [upgrades addObject:name];
4854 else if (state.Downgrade())
4855 [downgrades addObject:name];
4856 else if (!state.Delete())
4857 // XXX: _assert(state.Keep());
4859 else if (special_r(name))
4860 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4861 [NSNull null], @"package",
4862 [NSArray arrayWithObjects:
4863 [NSDictionary dictionaryWithObjectsAndKeys:
4864 @"Conflicts", @"relationship",
4865 [NSArray arrayWithObjects:
4866 [NSDictionary dictionaryWithObjectsAndKeys:
4868 [NSNull null], @"version",
4869 @"installed", @"reason",
4876 if ([package essential])
4878 [removes addObject:name];
4881 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4882 substrate_ |= DepSubstrate(iterator.CurrentVer());
4887 else if (Advanced_) {
4888 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4890 essential_ = [[[UIAlertView alloc]
4891 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4892 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4894 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4896 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4900 [essential_ setContext:@"remove"];
4902 essential_ = [[[UIAlertView alloc]
4903 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4904 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4906 cancelButtonTitle:UCLocalize("OKAY")
4907 otherButtonTitles:nil
4910 [essential_ setContext:@"unable"];
4913 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4914 installs, @"installs",
4915 reinstalls, @"reinstalls",
4916 upgrades, @"upgrades",
4917 downgrades, @"downgrades",
4918 removes, @"removes",
4921 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4922 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4923 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4926 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4930 - (UIBarButtonItem *) leftButton {
4931 return [[[UIBarButtonItem alloc]
4932 initWithTitle:UCLocalize("CANCEL")
4933 style:UIBarButtonItemStylePlain
4935 action:@selector(cancelButtonClicked)
4940 - (void) applyRightButton {
4941 if ([issues_ count] == 0 && ![self isLoading])
4942 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4943 initWithTitle:UCLocalize("CONFIRM")
4944 style:UIBarButtonItemStyleDone
4946 action:@selector(confirmButtonClicked)
4949 [[self navigationItem] setRightBarButtonItem:nil];
4953 - (void) cancelButtonClicked {
4954 [self dismissModalViewControllerAnimated:YES];
4955 [delegate_ cancelAndClear:YES];
4959 - (void) confirmButtonClicked {
4960 if (essential_ != nil)
4970 /* Progress Data {{{ */
4971 @interface CydiaProgressData : NSObject {
4972 _transient id delegate_;
4981 _H<NSMutableArray> events_;
4982 _H<NSString> title_;
4984 _H<NSString> status_;
4985 _H<NSString> finish_;
4990 @implementation CydiaProgressData
4992 + (NSArray *) _attributeKeys {
4993 return [NSArray arrayWithObjects:
5005 - (NSArray *) attributeKeys {
5006 return [[self class] _attributeKeys];
5009 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5010 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5014 if ((self = [super init]) != nil) {
5015 events_ = [NSMutableArray arrayWithCapacity:32];
5019 - (void) setDelegate:(id)delegate {
5020 delegate_ = delegate;
5023 - (void) setPercent:(float)value {
5027 - (NSNumber *) percent {
5028 return [NSNumber numberWithFloat:percent_];
5031 - (void) setCurrent:(float)value {
5035 - (NSNumber *) current {
5036 return [NSNumber numberWithFloat:current_];
5039 - (void) setTotal:(float)value {
5043 - (NSNumber *) total {
5044 return [NSNumber numberWithFloat:total_];
5047 - (void) setSpeed:(float)value {
5051 - (NSNumber *) speed {
5052 return [NSNumber numberWithFloat:speed_];
5055 - (NSArray *) events {
5059 - (void) removeAllEvents {
5060 [events_ removeAllObjects];
5063 - (void) addEvent:(CydiaProgressEvent *)event {
5064 [events_ addObject:event];
5067 - (void) setTitle:(NSString *)text {
5071 - (NSString *) title {
5075 - (void) setFinish:(NSString *)text {
5079 - (NSString *) finish {
5080 return (id) finish_ ?: [NSNull null];
5083 - (void) setRunning:(bool)running {
5087 - (NSNumber *) running {
5088 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5093 /* Progress Controller {{{ */
5094 @interface ProgressController : CydiaWebViewController <
5097 _transient Database *database_;
5098 _H<CydiaProgressData, 1> progress_;
5102 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5104 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5106 - (void) setTitle:(NSString *)title;
5107 - (void) setCancellable:(bool)cancellable;
5111 @implementation ProgressController
5114 [database_ setProgressDelegate:nil];
5118 - (UIBarButtonItem *) leftButton {
5119 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5120 initWithTitle:UCLocalize("CANCEL")
5121 style:UIBarButtonItemStylePlain
5123 action:@selector(cancel)
5124 ] autorelease] : nil;
5127 - (void) updateCancel {
5128 [super applyLeftButton];
5131 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5132 if ((self = [super init]) != nil) {
5133 database_ = database;
5134 delegate_ = delegate;
5136 [database_ setProgressDelegate:self];
5138 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5139 [progress_ setDelegate:self];
5141 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5143 [scroller_ setBackgroundColor:[UIColor blackColor]];
5145 [[self navigationItem] setHidesBackButton:YES];
5147 [self updateCancel];
5151 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5152 [super webView:view didClearWindowObject:window forFrame:frame];
5153 [window setValue:progress_ forKey:@"cydiaProgress"];
5156 - (void) updateProgress {
5157 [self dispatchEvent:@"CydiaProgressUpdate"];
5160 - (void) viewWillAppear:(BOOL)animated {
5161 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5162 [super viewWillAppear:animated];
5166 UpdateExternalStatus(0);
5169 [delegate_ saveState];
5173 [delegate_ returnToCydia];
5177 [delegate_ terminateWithSuccess];
5178 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5179 [delegate_ suspendWithAnimation:YES];
5181 [delegate_ suspend];*/
5193 system("/usr/bin/sbreload");
5199 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5200 SBReboot(SBSSpringBoardServerPort());
5202 reboot2(RB_AUTOBOOT);
5209 - (void) setTitle:(NSString *)title {
5210 [progress_ setTitle:title];
5211 [self updateProgress];
5214 - (UIBarButtonItem *) rightButton {
5215 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5216 initWithTitle:UCLocalize("CLOSE")
5217 style:UIBarButtonItemStylePlain
5219 action:@selector(close)
5225 system("su -c /usr/bin/uicache mobile");
5229 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5230 UpdateExternalStatus(1);
5232 [progress_ setRunning:true];
5233 [self setTitle:title];
5234 // implicit updateProgress
5236 SHA1SumValue notifyconf; {
5238 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5241 MMap mmap(file, MMap::ReadOnly);
5243 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5244 notifyconf = sha1.Result();
5248 SHA1SumValue springlist; {
5250 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5253 MMap mmap(file, MMap::ReadOnly);
5255 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5256 springlist = sha1.Result();
5260 if (invocation != nil) {
5261 [invocation yieldToSelector:@selector(invoke)];
5262 [self setTitle:@"COMPLETE"];
5267 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5270 MMap mmap(file, MMap::ReadOnly);
5272 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5273 if (!(notifyconf == sha1.Result()))
5280 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5283 MMap mmap(file, MMap::ReadOnly);
5285 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5286 if (!(springlist == sha1.Result()))
5292 if (RestartSubstrate_)
5296 RestartSubstrate_ = false;
5299 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5300 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5301 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5302 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5303 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5306 UIProgressHUD *hud([delegate_ addProgressHUD]);
5307 [hud setText:UCLocalize("LOADING")];
5308 [self yieldToSelector:@selector(uicache)];
5309 [delegate_ removeProgressHUD:hud];
5311 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5313 [progress_ setRunning:false];
5314 [self updateProgress];
5316 [self applyRightButton];
5319 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5320 [progress_ addEvent:event];
5321 [self updateProgress];
5324 - (bool) isProgressCancelled {
5325 return cancel_ == 2;
5330 [self updateCancel];
5333 - (void) setCancellable:(bool)cancellable {
5334 unsigned cancel(cancel_);
5338 else if (cancel_ == 0)
5341 if (cancel != cancel_)
5342 [self updateCancel];
5345 - (void) setProgressCancellable:(NSNumber *)cancellable {
5346 [self setCancellable:[cancellable boolValue]];
5349 - (void) setProgressPercent:(NSNumber *)percent {
5350 [progress_ setPercent:[percent floatValue]];
5351 [self updateProgress];
5354 - (void) setProgressStatus:(NSDictionary *)status {
5355 if (status == nil) {
5356 [progress_ setCurrent:0];
5357 [progress_ setTotal:0];
5358 [progress_ setSpeed:0];
5360 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5362 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5363 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5364 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5367 [self updateProgress];
5373 /* Package Cell {{{ */
5374 @interface PackageCell : CyteTableViewCell <
5375 CyteTableViewCellDelegate
5379 _H<NSString> description_;
5381 _H<NSString> source_;
5383 _H<UIImage> placard_;
5387 - (PackageCell *) init;
5388 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5390 - (void) drawContentRect:(CGRect)rect;
5394 @implementation PackageCell
5396 - (PackageCell *) init {
5397 CGRect frame(CGRectMake(0, 0, 320, 74));
5398 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5399 UIView *content([self contentView]);
5400 CGRect bounds([content bounds]);
5402 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5403 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5404 [content addSubview:content_];
5406 [content_ setDelegate:self];
5407 [content_ setOpaque:YES];
5411 - (NSString *) accessibilityLabel {
5412 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5415 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5416 summarized_ = summary;
5426 [content_ setBackgroundColor:[UIColor whiteColor]];
5430 Source *source = [package source];
5432 icon_ = [package icon];
5434 if (NSString *name = [package name])
5435 name_ = [NSString stringWithString:name];
5437 NSString *description(nil);
5439 if (description == nil && IsWildcat_)
5440 description = [package longDescription];
5441 if (description == nil)
5442 description = [package shortDescription];
5444 if (description != nil)
5445 description_ = [NSString stringWithString:description];
5447 commercial_ = [package isCommercial];
5449 NSString *label = nil;
5450 bool trusted = false;
5452 if (source != nil) {
5453 label = [source label];
5454 trusted = [source trusted];
5455 } else if ([[package id] isEqualToString:@"firmware"])
5456 label = UCLocalize("APPLE");
5458 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5460 NSString *from(label);
5462 NSString *section = [package simpleSection];
5463 if (section != nil && ![section isEqualToString:label]) {
5464 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5465 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5468 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5470 if (NSString *purpose = [package primaryPurpose])
5471 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5476 if (NSString *mode = [package mode]) {
5477 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5478 color = RemovingColor_;
5479 //placard = @"removing";
5481 color = InstallingColor_;
5482 //placard = @"installing";
5485 // XXX: the removing/installing placards are not @2x
5488 color = [UIColor whiteColor];
5490 if ([package installed] != nil)
5491 placard = @"installed";
5496 [content_ setBackgroundColor:color];
5499 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5502 [self setNeedsDisplay];
5503 [content_ setNeedsDisplay];
5506 - (void) drawSummaryContentRect:(CGRect)rect {
5507 bool highlighted(highlighted_);
5508 float width([self bounds].size.width);
5512 rect.size = [(UIImage *) icon_ size];
5514 while (rect.size.width > 16 || rect.size.height > 16) {
5515 rect.size.width /= 2;
5516 rect.size.height /= 2;
5519 rect.origin.x = 18 - rect.size.width / 2;
5520 rect.origin.y = 18 - rect.size.height / 2;
5522 [icon_ drawInRect:rect];
5525 if (badge_ != nil) {
5527 rect.size = [(UIImage *) badge_ size];
5529 rect.size.width /= 4;
5530 rect.size.height /= 4;
5532 rect.origin.x = 23 - rect.size.width / 2;
5533 rect.origin.y = 23 - rect.size.height / 2;
5535 [badge_ drawInRect:rect];
5542 UISetColor(commercial_ ? Purple_ : Black_);
5543 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5545 if (placard_ != nil)
5546 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5549 - (void) drawNormalContentRect:(CGRect)rect {
5550 bool highlighted(highlighted_);
5551 float width([self bounds].size.width);
5555 rect.size = [(UIImage *) icon_ size];
5557 while (rect.size.width > 32 || rect.size.height > 32) {
5558 rect.size.width /= 2;
5559 rect.size.height /= 2;
5562 rect.origin.x = 25 - rect.size.width / 2;
5563 rect.origin.y = 25 - rect.size.height / 2;
5565 [icon_ drawInRect:rect];
5568 if (badge_ != nil) {
5570 rect.size = [(UIImage *) badge_ size];
5572 rect.size.width /= 2;
5573 rect.size.height /= 2;
5575 rect.origin.x = 36 - rect.size.width / 2;
5576 rect.origin.y = 36 - rect.size.height / 2;
5578 [badge_ drawInRect:rect];
5585 UISetColor(commercial_ ? Purple_ : Black_);
5586 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5587 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5590 UISetColor(commercial_ ? Purplish_ : Gray_);
5591 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5593 if (placard_ != nil)
5594 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5597 - (void) drawContentRect:(CGRect)rect {
5599 [self drawSummaryContentRect:rect];
5601 [self drawNormalContentRect:rect];
5606 /* Section Cell {{{ */
5607 @interface SectionCell : CyteTableViewCell <
5608 CyteTableViewCellDelegate
5610 _H<NSString> basic_;
5611 _H<NSString> section_;
5613 _H<NSString> count_;
5615 _H<UISwitch> switch_;
5619 - (void) setSection:(Section *)section editing:(BOOL)editing;
5623 @implementation SectionCell
5625 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5626 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5627 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5628 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5629 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5631 UIView *content([self contentView]);
5632 CGRect bounds([content bounds]);
5634 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5635 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5636 [content addSubview:content_];
5637 [content_ setBackgroundColor:[UIColor whiteColor]];
5639 [content_ setDelegate:self];
5643 - (void) onSwitch:(id)sender {
5644 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5645 if (metadata == nil) {
5646 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5647 [Sections_ setObject:metadata forKey:basic_];
5650 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5654 - (void) setSection:(Section *)section editing:(BOOL)editing {
5655 if (editing != editing_) {
5657 [switch_ removeFromSuperview];
5659 [self addSubview:switch_];
5668 if (section == nil) {
5669 name_ = UCLocalize("ALL_PACKAGES");
5672 basic_ = [section name];
5673 section_ = [section localized];
5675 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5676 count_ = [NSString stringWithFormat:@"%d", [section count]];
5679 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5682 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5683 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5685 [content_ setNeedsDisplay];
5688 - (void) setFrame:(CGRect)frame {
5689 [super setFrame:frame];
5691 CGRect rect([switch_ frame]);
5692 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5695 - (NSString *) accessibilityLabel {
5699 - (void) drawContentRect:(CGRect)rect {
5700 bool highlighted(highlighted_ && !editing_);
5702 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5707 float width(rect.size.width);
5713 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5715 CGSize size = [count_ sizeWithFont:Font14_];
5719 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5725 /* File Table {{{ */
5726 @interface FileTable : CyteViewController <
5727 UITableViewDataSource,
5730 _transient Database *database_;
5731 _H<Package> package_;
5733 _H<NSMutableArray> files_;
5734 _H<UITableView, 2> list_;
5737 - (id) initWithDatabase:(Database *)database;
5738 - (void) setPackage:(Package *)package;
5742 @implementation FileTable
5744 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5745 return files_ == nil ? 0 : [files_ count];
5748 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5752 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5753 static NSString *reuseIdentifier = @"Cell";
5755 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5757 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5758 [cell setFont:[UIFont systemFontOfSize:16]];
5760 [cell setText:[files_ objectAtIndex:indexPath.row]];
5761 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5766 - (NSURL *) navigationURL {
5767 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5771 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5773 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5774 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5775 [list_ setRowHeight:24.0f];
5776 [(UITableView *) list_ setDataSource:self];
5777 [list_ setDelegate:self];
5778 [[self view] addSubview:list_];
5781 - (void) viewDidLoad {
5782 [super viewDidLoad];
5784 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5787 - (void) releaseSubviews {
5793 [super releaseSubviews];
5796 - (id) initWithDatabase:(Database *)database {
5797 if ((self = [super init]) != nil) {
5798 database_ = database;
5802 - (void) setPackage:(Package *)package {
5806 files_ = [NSMutableArray arrayWithCapacity:32];
5808 if (package != nil) {
5810 name_ = [package id];
5812 if (NSArray *files = [package files])
5813 [files_ addObjectsFromArray:files];
5815 if ([files_ count] != 0) {
5816 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5817 [files_ removeObjectAtIndex:0];
5818 [files_ sortUsingSelector:@selector(compareByPath:)];
5820 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5821 [stack addObject:@"/"];
5823 for (int i(0), e([files_ count]); i != e; ++i) {
5824 NSString *file = [files_ objectAtIndex:i];
5825 while (![file hasPrefix:[stack lastObject]])
5826 [stack removeLastObject];
5827 NSString *directory = [stack lastObject];
5828 [stack addObject:[file stringByAppendingString:@"/"]];
5829 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5830 ([stack count] - 2) * 3, "",
5831 [file substringFromIndex:[directory length]]
5840 - (void) reloadData {
5843 [self setPackage:[database_ packageWithName:name_]];
5848 /* Package Controller {{{ */
5849 @interface CYPackageController : CydiaWebViewController <
5850 UIActionSheetDelegate
5852 _transient Database *database_;
5853 _H<Package> package_;
5856 _H<NSMutableArray> buttons_;
5857 _H<UIBarButtonItem> button_;
5860 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5864 @implementation CYPackageController
5866 - (NSURL *) navigationURL {
5867 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5870 /* XXX: this is not safe at all... localization of /fail/ */
5871 - (void) _clickButtonWithName:(NSString *)name {
5872 if ([name isEqualToString:UCLocalize("CLEAR")])
5873 [delegate_ clearPackage:package_];
5874 else if ([name isEqualToString:UCLocalize("INSTALL")])
5875 [delegate_ installPackage:package_];
5876 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5877 [delegate_ installPackage:package_];
5878 else if ([name isEqualToString:UCLocalize("REMOVE")])
5879 [delegate_ removePackage:package_];
5880 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5881 [delegate_ installPackage:package_];
5882 else _assert(false);
5885 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5886 NSString *context([sheet context]);
5888 if ([context isEqualToString:@"modify"]) {
5889 if (button != [sheet cancelButtonIndex]) {
5890 NSString *buttonName = [buttons_ objectAtIndex:button];
5891 [self _clickButtonWithName:buttonName];
5894 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5898 - (bool) _allowJavaScriptPanel {
5903 - (void) _customButtonClicked {
5904 int count([buttons_ count]);
5909 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5911 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5912 [buttons addObjectsFromArray:buttons_];
5914 UIActionSheet *sheet = [[[UIActionSheet alloc]
5917 cancelButtonTitle:nil
5918 destructiveButtonTitle:nil
5919 otherButtonTitles:nil
5922 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5924 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5925 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5927 [sheet setContext:@"modify"];
5929 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5933 // We don't want to allow non-commercial packages to do custom things to the install button,
5934 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5935 - (void) customButtonClicked {
5937 [super customButtonClicked];
5939 [self _customButtonClicked];
5942 - (void) reloadButtonClicked {
5943 // Don't reload a commerical package by tapping the loading button,
5944 // but if it's not an Install button, we should forward it on.
5945 if (![package_ uninstalled])
5946 [self _customButtonClicked];
5949 - (void) applyLoadingTitle {
5950 // Don't show "Loading" as the title. Ever.
5953 - (UIBarButtonItem *) rightButton {
5958 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5959 if ((self = [super init]) != nil) {
5960 database_ = database;
5961 buttons_ = [NSMutableArray arrayWithCapacity:4];
5962 name_ = name == nil ? @"" : [NSString stringWithString:name];
5963 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5967 - (void) reloadData {
5970 package_ = [database_ packageWithName:name_];
5972 [buttons_ removeAllObjects];
5974 if (package_ != nil) {
5975 [(Package *) package_ parse];
5977 commercial_ = [package_ isCommercial];
5979 if ([package_ mode] != nil)
5980 [buttons_ addObject:UCLocalize("CLEAR")];
5981 if ([package_ source] == nil);
5982 else if ([package_ upgradableAndEssential:NO])
5983 [buttons_ addObject:UCLocalize("UPGRADE")];
5984 else if ([package_ uninstalled])
5985 [buttons_ addObject:UCLocalize("INSTALL")];
5987 [buttons_ addObject:UCLocalize("REINSTALL")];
5988 if (![package_ uninstalled])
5989 [buttons_ addObject:UCLocalize("REMOVE")];
5993 switch ([buttons_ count]) {
5994 case 0: title = nil; break;
5995 case 1: title = [buttons_ objectAtIndex:0]; break;
5996 default: title = UCLocalize("MODIFY"); break;
5999 button_ = [[[UIBarButtonItem alloc]
6001 style:UIBarButtonItemStylePlain
6003 action:@selector(customButtonClicked)
6007 - (bool) isLoading {
6008 return commercial_ ? [super isLoading] : false;
6014 /* Package List Controller {{{ */
6015 @interface PackageListController : CyteViewController <
6016 UITableViewDataSource,
6019 _transient Database *database_;
6021 _H<NSArray> packages_;
6022 _H<NSMutableArray> sections_;
6023 _H<UITableView, 2> list_;
6024 _H<NSMutableArray> index_;
6025 _H<NSMutableDictionary> indices_;
6026 _H<NSString> title_;
6027 unsigned reloading_;
6030 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6031 - (void) setDelegate:(id)delegate;
6032 - (void) resetCursor;
6037 @implementation PackageListController
6039 - (bool) isSummarized {
6043 - (bool) showsSections {
6047 - (void) deselectWithAnimation:(BOOL)animated {
6048 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6051 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6052 CGRect base = [[self view] bounds];
6053 base.size.height -= bounds.size.height;
6054 base.origin = [list_ frame].origin;
6056 [UIView beginAnimations:nil context:NULL];
6057 [UIView setAnimationBeginsFromCurrentState:YES];
6058 [UIView setAnimationCurve:curve];
6059 [UIView setAnimationDuration:duration];
6060 [list_ setFrame:base];
6061 [UIView commitAnimations];
6064 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6065 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6068 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6069 [self resizeForKeyboardBounds:bounds duration:0];
6072 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6073 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6074 *curve = UIViewAnimationCurveEaseInOut;
6076 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6078 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6081 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6084 - (void) keyboardWillShow:(NSNotification *)notification {
6087 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6088 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6090 NSTimeInterval duration;
6091 UIViewAnimationCurve curve;
6092 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6094 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);
6095 UIViewController *base = self;
6096 while ([base parentViewController] != nil)
6097 base = [base parentViewController];
6098 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6099 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6101 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6102 intersection.size.height += CYStatusBarHeight();
6104 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6107 - (void) keyboardWillHide:(NSNotification *)notification {
6108 NSTimeInterval duration;
6109 UIViewAnimationCurve curve;
6110 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6112 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6115 - (void) viewWillAppear:(BOOL)animated {
6116 [super viewWillAppear:animated];
6118 [self resizeForKeyboardBounds:CGRectZero];
6119 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6120 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6123 - (void) viewWillDisappear:(BOOL)animated {
6124 [super viewWillDisappear:animated];
6126 [self resizeForKeyboardBounds:CGRectZero];
6127 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6128 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6131 - (void) viewDidAppear:(BOOL)animated {
6132 [super viewDidAppear:animated];
6133 [self deselectWithAnimation:animated];
6136 - (void) didSelectPackage:(Package *)package {
6137 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6138 [view setDelegate:delegate_];
6139 [[self navigationController] pushViewController:view animated:YES];
6142 #if TryIndexedCollation
6143 + (BOOL) hasIndexedCollation {
6144 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6148 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6149 NSInteger count([sections_ count]);
6150 return count == 0 ? 1 : count;
6153 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6154 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6156 return [[sections_ objectAtIndex:section] name];
6159 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6160 if ([sections_ count] == 0)
6162 return [[sections_ objectAtIndex:section] count];
6165 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6166 @synchronized (database_) {
6167 if ([database_ era] != era_)
6170 Section *section([sections_ objectAtIndex:[path section]]);
6171 NSInteger row([path row]);
6172 Package *package([packages_ objectAtIndex:([section row] + row)]);
6173 return [[package retain] autorelease];
6176 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6177 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6179 cell = [[[PackageCell alloc] init] autorelease];
6181 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6182 [cell setPackage:package asSummary:[self isSummarized]];
6186 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6187 Package *package([self packageAtIndexPath:path]);
6188 package = [database_ packageWithName:[package id]];
6189 [self didSelectPackage:package];
6192 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6193 if (![self showsSections])
6199 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6200 #if TryIndexedCollation
6201 if ([[self class] hasIndexedCollation]) {
6202 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6209 - (void) updateHeight {
6210 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6213 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6214 if ((self = [super init]) != nil) {
6215 database_ = database;
6216 title_ = [title copy];
6217 [[self navigationItem] setTitle:title_];
6222 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6224 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6225 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6226 [[self view] addSubview:list_];
6228 // XXX: is 20 the most optimal number here?
6229 [list_ setSectionIndexMinimumDisplayRowCount:20];
6231 [(UITableView *) list_ setDataSource:self];
6232 [list_ setDelegate:self];
6234 [self updateHeight];
6237 - (void) releaseSubviews {
6245 [super releaseSubviews];
6248 - (void) setDelegate:(id)delegate {
6249 delegate_ = delegate;
6252 - (bool) shouldYield {
6256 - (bool) shouldBlock {
6260 - (NSMutableArray *) _reloadPackages {
6261 @synchronized (database_) {
6262 era_ = [database_ era];
6263 NSArray *packages([database_ packages]);
6265 return [NSMutableArray arrayWithArray:packages];
6268 - (void) _reloadData {
6269 if (reloading_ != 0) {
6277 if ([self shouldYield]) {
6281 if (![self shouldBlock])
6284 hud = [delegate_ addProgressHUD];
6285 [hud setText:UCLocalize("LOADING")];
6289 packages = [self yieldToSelector:@selector(_reloadPackages)];
6292 [delegate_ removeProgressHUD:hud];
6293 } while (reloading_ == 2);
6295 packages = [self _reloadPackages];
6298 @synchronized (database_) {
6299 if (era_ != [database_ era])
6303 packages_ = packages;
6305 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6306 sections_ = [NSMutableArray arrayWithCapacity:16];
6308 Section *section = nil;
6310 #if TryIndexedCollation
6311 if ([[self class] hasIndexedCollation]) {
6312 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6314 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6315 NSArray *titles = [collation sectionIndexTitles];
6318 _profile(PackageTable$reloadData$Section)
6319 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6323 _profile(PackageTable$reloadData$Section$Package)
6324 package = [packages_ objectAtIndex:offset];
6325 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6328 while (secidx < index) {
6331 _profile(PackageTable$reloadData$Section$Allocate)
6332 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6335 _profile(PackageTable$reloadData$Section$Add)
6336 [sections_ addObject:section];
6340 [section addToCount];
6346 index_ = [NSMutableArray arrayWithCapacity:32];
6348 bool sectioned([self showsSections]);
6350 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6351 [sections_ addObject:section];
6354 _profile(PackageTable$reloadData$Section)
6355 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6359 _profile(PackageTable$reloadData$Section$Package)
6360 package = [packages_ objectAtIndex:offset];
6361 index = [package index];
6364 if (sectioned && (section == nil || [section index] != index)) {
6365 _profile(PackageTable$reloadData$Section$Allocate)
6366 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6369 [index_ addObject:[section name]];
6370 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6372 _profile(PackageTable$reloadData$Section$Add)
6373 [sections_ addObject:section];
6377 [section addToCount];
6382 [self updateHeight];
6384 _profile(PackageTable$reloadData$List)
6385 [(UITableView *) list_ setDataSource:self];
6390 - (void) reloadData {
6393 if ([self shouldYield])
6394 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6399 - (void) resetCursor {
6400 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6403 - (void) clearData {
6404 [self updateHeight];
6406 [list_ setDataSource:nil];
6414 /* Filtered Package List Controller {{{ */
6415 @interface FilteredPackageListController : PackageListController {
6418 _H<NSObject> object_;
6421 - (void) setObject:(id)object;
6422 - (void) setObject:(id)object forFilter:(SEL)filter;
6425 - (void) setFilter:(SEL)filter;
6427 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6431 @implementation FilteredPackageListController
6437 - (void) setFilter:(SEL)filter {
6438 @synchronized (self) {
6441 /* XXX: this is an unsafe optimization of doomy hell */
6442 Method method(class_getInstanceMethod([Package class], filter));
6443 _assert(method != NULL);
6444 imp_ = method_getImplementation(method);
6445 _assert(imp_ != NULL);
6448 - (void) setObject:(id)object {
6449 @synchronized (self) {
6453 - (void) setObject:(id)object forFilter:(SEL)filter {
6454 @synchronized (self) {
6455 [self setFilter:filter];
6456 [self setObject:object];
6459 - (NSMutableArray *) _reloadPackages {
6460 @synchronized (database_) {
6461 era_ = [database_ era];
6462 NSArray *packages([database_ packages]);
6464 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6468 _H<NSObject> object;
6470 @synchronized (self) {
6476 _profile(PackageTable$reloadData$Filter)
6477 for (Package *package in packages)
6478 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6479 [filtered addObject:package];
6485 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6486 if ((self = [super initWithDatabase:database title:title]) != nil) {
6487 [self setFilter:filter];
6488 [self setObject:object];
6495 /* Home Controller {{{ */
6496 @interface HomeController : CydiaWebViewController {
6501 @implementation HomeController
6504 if ((self = [super init]) != nil) {
6505 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6510 - (NSURL *) navigationURL {
6511 return [NSURL URLWithString:@"cydia://home"];
6514 - (void) didReceiveMemoryWarning {
6517 - (void) aboutButtonClicked {
6518 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6520 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6521 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6522 [alert setCancelButtonIndex:0];
6525 @"Copyright \u00a9 2008-2011\n"
6528 "Jay Freeman (saurik)\n"
6529 "saurik@saurik.com\n"
6530 "http://www.saurik.com/"
6536 - (UIBarButtonItem *) leftButton {
6537 return [[[UIBarButtonItem alloc]
6538 initWithTitle:UCLocalize("ABOUT")
6539 style:UIBarButtonItemStylePlain
6541 action:@selector(aboutButtonClicked)
6547 /* Manage Controller {{{ */
6548 @interface ManageController : CydiaWebViewController {
6551 - (void) queueStatusDidChange;
6555 @implementation ManageController
6558 if ((self = [super init]) != nil) {
6559 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6563 - (NSURL *) navigationURL {
6564 return [NSURL URLWithString:@"cydia://manage"];
6567 - (UIBarButtonItem *) leftButton {
6568 return [[[UIBarButtonItem alloc]
6569 initWithTitle:UCLocalize("SETTINGS")
6570 style:UIBarButtonItemStylePlain
6572 action:@selector(settingsButtonClicked)
6576 - (void) settingsButtonClicked {
6577 [delegate_ showSettings];
6580 - (void) queueButtonClicked {
6584 - (UIBarButtonItem *) rightButton {
6585 return Queuing_ ? [[[UIBarButtonItem alloc]
6586 initWithTitle:UCLocalize("QUEUE")
6587 style:UIBarButtonItemStyleDone
6589 action:@selector(queueButtonClicked)
6590 ] autorelease] : nil;
6593 - (void) queueStatusDidChange {
6594 [self applyRightButton];
6597 - (bool) isLoading {
6598 return !Queuing_ && [super isLoading];
6604 /* Refresh Bar {{{ */
6605 @interface RefreshBar : UINavigationBar {
6606 _H<UIProgressIndicator> indicator_;
6607 _H<UITextLabel> prompt_;
6608 _H<UIProgressBar> progress_;
6609 _H<UINavigationButton> cancel_;
6614 @implementation RefreshBar
6616 - (void) positionViews {
6617 CGRect frame = [cancel_ frame];
6618 frame.size = [cancel_ sizeThatFits:frame.size];
6619 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6620 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6621 [cancel_ setFrame:frame];
6623 CGSize prgsize = {75, 100};
6625 [self frame].size.width - prgsize.width - 10,
6626 ([self frame].size.height - prgsize.height) / 2
6628 [progress_ setFrame:prgrect];
6630 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6631 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6632 CGRect indrect = {{indoffset, indoffset}, indsize};
6633 [indicator_ setFrame:indrect];
6635 CGSize prmsize = {215, indsize.height + 4};
6637 indoffset * 2 + indsize.width,
6638 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6640 [prompt_ setFrame:prmrect];
6643 - (void) setFrame:(CGRect)frame {
6644 [super setFrame:frame];
6645 [self positionViews];
6648 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6649 if ((self = [super initWithFrame:frame]) != nil) {
6650 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6652 [self setBarStyle:UIBarStyleBlack];
6654 UIBarStyle barstyle([self _barStyle:NO]);
6655 bool ugly(barstyle == UIBarStyleDefault);
6657 UIProgressIndicatorStyle style = ugly ?
6658 UIProgressIndicatorStyleMediumBrown :
6659 UIProgressIndicatorStyleMediumWhite;
6661 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6662 [(UIProgressIndicator *) indicator_ setStyle:style];
6663 [indicator_ startAnimation];
6664 [self addSubview:indicator_];
6666 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6667 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6668 [prompt_ setBackgroundColor:[UIColor clearColor]];
6669 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6670 [self addSubview:prompt_];
6672 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6673 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6674 [(UIProgressBar *) progress_ setStyle:0];
6675 [self addSubview:progress_];
6677 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6678 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6679 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6680 [cancel_ setBarStyle:barstyle];
6682 [self positionViews];
6686 - (void) setCancellable:(bool)cancellable {
6688 [self addSubview:cancel_];
6690 [cancel_ removeFromSuperview];
6694 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6695 [progress_ setProgress:0];
6699 [self setCancellable:NO];
6702 - (void) setPrompt:(NSString *)prompt {
6703 [prompt_ setText:prompt];
6706 - (void) setProgress:(float)progress {
6707 [progress_ setProgress:progress];
6713 /* Cydia Navigation Controller Interface {{{ */
6714 @interface UINavigationController (Cydia)
6716 - (NSArray *) navigationURLCollection;
6717 - (void) unloadData;
6722 /* Cydia Tab Bar Controller {{{ */
6723 @interface CYTabBarController : UITabBarController <
6724 UITabBarControllerDelegate,
6727 _transient Database *database_;
6728 _H<RefreshBar, 1> refreshbar_;
6732 // XXX: ok, "updatedelegate_"?...
6733 _transient NSObject<CydiaDelegate> *updatedelegate_;
6735 _H<UIViewController> remembered_;
6736 _transient UIViewController *transient_;
6739 - (NSArray *) navigationURLCollection;
6740 - (void) dropBar:(BOOL)animated;
6741 - (void) beginUpdate;
6742 - (void) raiseBar:(BOOL)animated;
6744 - (void) unloadData;
6748 @implementation CYTabBarController
6750 - (void) setUnselectedViewController:(UIViewController *)transient {
6751 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6752 if (transient != nil) {
6753 if (transient_ == nil)
6754 remembered_ = [controllers objectAtIndex:0];
6755 transient_ = transient;
6756 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6757 [controllers replaceObjectAtIndex:0 withObject:transient_];
6758 [self setSelectedIndex:0];
6759 [self setViewControllers:controllers];
6760 [self concealTabBarSelection];
6761 } else if (remembered_ != nil) {
6762 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6763 transient_ = transient;
6764 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6766 [self setViewControllers:controllers];
6767 [self revealTabBarSelection];
6771 - (UIViewController *) unselectedViewController {
6775 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6776 if ([self unselectedViewController])
6777 [self setUnselectedViewController:nil];
6780 - (NSArray *) navigationURLCollection {
6781 NSMutableArray *items([NSMutableArray array]);
6783 // XXX: Should this deal with transient view controllers?
6784 for (id navigation in [self viewControllers]) {
6785 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6787 [items addObject:stack];
6793 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6794 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6795 [self setUnselectedViewController:nil];
6797 [super dismissModalViewControllerAnimated:YES];
6800 - (void) unloadData {
6803 for (UINavigationController *controller in [self viewControllers])
6804 [controller unloadData];
6806 if (UIViewController *selected = [self selectedViewController])
6807 [selected reloadData];
6809 if (UIViewController *unselected = [self unselectedViewController]) {
6810 [unselected unloadData];
6811 [unselected reloadData];
6816 [[NSNotificationCenter defaultCenter] removeObserver:self];
6821 - (id) initWithDatabase:(Database *)database {
6822 if ((self = [super init]) != nil) {
6823 database_ = database;
6824 [self setDelegate:self];
6826 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6827 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6829 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6833 - (void) setUpdate:(NSDate *)date {
6837 - (void) beginUpdate {
6838 [(RefreshBar *) refreshbar_ start];
6841 [updatedelegate_ retainNetworkActivityIndicator];
6845 detachNewThreadSelector:@selector(performUpdate)
6851 - (void) performUpdate {
6852 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6855 status.setDelegate(self);
6856 [database_ updateWithStatus:status];
6859 performSelectorOnMainThread:@selector(completeUpdate)
6867 - (void) stopUpdateWithSelector:(SEL)selector {
6869 [updatedelegate_ releaseNetworkActivityIndicator];
6871 [self raiseBar:YES];
6874 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6877 - (void) completeUpdate {
6880 [self stopUpdateWithSelector:@selector(reloadData)];
6883 - (void) cancelUpdate {
6884 [self stopUpdateWithSelector:@selector(updateData)];
6887 - (void) cancelPressed {
6888 [self cancelUpdate];
6895 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6896 [refreshbar_ setPrompt:[event compoundMessage]];
6899 - (bool) isProgressCancelled {
6903 - (void) setProgressCancellable:(NSNumber *)cancellable {
6904 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6907 - (void) setProgressPercent:(NSNumber *)percent {
6908 [refreshbar_ setProgress:[percent floatValue]];
6911 - (void) setProgressStatus:(NSDictionary *)status {
6913 [self setProgressPercent:[status objectForKey:@"Percent"]];
6916 - (void) setUpdateDelegate:(id)delegate {
6917 updatedelegate_ = delegate;
6920 - (UIView *) transitionView {
6921 if ([self respondsToSelector:@selector(_transitionView)])
6922 return [self _transitionView];
6924 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6927 - (void) dropBar:(BOOL)animated {
6932 UIView *transition([self transitionView]);
6933 [[self view] addSubview:refreshbar_];
6935 CGRect barframe([refreshbar_ frame]);
6937 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6938 barframe.origin.y = CYStatusBarHeight();
6940 barframe.origin.y = 0;
6942 [refreshbar_ setFrame:barframe];
6945 [UIView beginAnimations:nil context:NULL];
6947 CGRect viewframe = [transition frame];
6948 viewframe.origin.y += barframe.size.height;
6949 viewframe.size.height -= barframe.size.height;
6950 [transition setFrame:viewframe];
6953 [UIView commitAnimations];
6955 // Ensure bar has the proper width for our view, it might have changed
6956 barframe.size.width = viewframe.size.width;
6957 [refreshbar_ setFrame:barframe];
6960 - (void) raiseBar:(BOOL)animated {
6965 UIView *transition([self transitionView]);
6966 [refreshbar_ removeFromSuperview];
6968 CGRect barframe([refreshbar_ frame]);
6971 [UIView beginAnimations:nil context:NULL];
6973 CGRect viewframe = [transition frame];
6974 viewframe.origin.y -= barframe.size.height;
6975 viewframe.size.height += barframe.size.height;
6976 [transition setFrame:viewframe];
6979 [UIView commitAnimations];
6982 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6983 bool dropped(dropped_);
6988 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6994 - (void) statusBarFrameChanged:(NSNotification *)notification {
7004 /* Cydia Navigation Controller Implementation {{{ */
7005 @implementation UINavigationController (Cydia)
7007 - (NSArray *) navigationURLCollection {
7008 NSMutableArray *stack([NSMutableArray array]);
7010 for (CyteViewController *controller in [self viewControllers]) {
7011 NSString *url = [[controller navigationURL] absoluteString];
7013 [stack addObject:url];
7019 - (void) reloadData {
7022 UIViewController *visible([self visibleViewController]);
7024 [visible reloadData];
7026 // on the iPad, this view controller is ALSO visible. :(
7028 if (UIViewController *top = [self topViewController])
7033 - (void) unloadData {
7034 for (CyteViewController *page in [self viewControllers])
7043 /* Cydia:// Protocol {{{ */
7044 @interface CydiaURLProtocol : NSURLProtocol {
7049 @implementation CydiaURLProtocol
7051 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7052 NSURL *url([request URL]);
7056 NSString *scheme([[url scheme] lowercaseString]);
7057 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7059 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7065 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7069 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7070 id<NSURLProtocolClient> client([self client]);
7072 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7074 NSData *data(UIImagePNGRepresentation(icon));
7076 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7077 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7078 [client URLProtocol:self didLoadData:data];
7079 [client URLProtocolDidFinishLoading:self];
7083 - (void) startLoading {
7084 id<NSURLProtocolClient> client([self client]);
7085 NSURLRequest *request([self request]);
7087 NSURL *url([request URL]);
7088 NSString *href([url absoluteString]);
7089 NSString *scheme([[url scheme] lowercaseString]);
7093 if ([scheme isEqualToString:@"cydia"])
7094 path = [href substringFromIndex:8];
7095 else if ([scheme isEqualToString:@"about"])
7096 path = [href substringFromIndex:12];
7097 else _assert(false);
7099 NSRange slash([path rangeOfString:@"/"]);
7102 if (slash.location == NSNotFound) {
7106 command = [path substringToIndex:slash.location];
7107 path = [path substringFromIndex:(slash.location + 1)];
7110 Database *database([Database sharedInstance]);
7112 if ([command isEqualToString:@"package-icon"]) {
7115 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7116 Package *package([database packageWithName:path]);
7120 UIImage *icon([package icon]);
7121 [self _returnPNGWithImage:icon forRequest:request];
7122 } else if ([command isEqualToString:@"uikit-image"]) {
7125 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7126 UIImage *icon(_UIImageWithName(path));
7127 [self _returnPNGWithImage:icon forRequest:request];
7128 } else if ([command isEqualToString:@"section-icon"]) {
7131 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7132 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7134 icon = [UIImage applicationImageNamed:@"unknown.png"];
7135 [self _returnPNGWithImage:icon forRequest:request];
7137 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7141 - (void) stopLoading {
7147 /* Section Controller {{{ */
7148 @interface SectionController : FilteredPackageListController {
7149 _H<NSString> section_;
7152 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7156 @implementation SectionController
7158 - (NSURL *) navigationURL {
7159 NSString *name = section_;
7163 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7166 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7169 title = UCLocalize("ALL_PACKAGES");
7170 else if (![name isEqual:@""])
7171 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7173 title = UCLocalize("NO_SECTION");
7175 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7182 /* Sections Controller {{{ */
7183 @interface SectionsController : CyteViewController <
7184 UITableViewDataSource,
7187 _transient Database *database_;
7188 _H<NSMutableArray> sections_;
7189 _H<NSMutableArray> filtered_;
7190 _H<UITableView, 2> list_;
7193 - (id) initWithDatabase:(Database *)database;
7194 - (void) editButtonClicked;
7198 @implementation SectionsController
7200 - (NSURL *) navigationURL {
7201 return [NSURL URLWithString:@"cydia://sections"];
7204 - (void) updateNavigationItem {
7205 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7206 if ([sections_ count] == 0) {
7207 [[self navigationItem] setRightBarButtonItem:nil];
7209 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7210 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7212 action:@selector(editButtonClicked)
7213 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7217 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7218 [super setEditing:editing animated:animated];
7223 [delegate_ updateData];
7225 [self updateNavigationItem];
7228 - (void) viewDidAppear:(BOOL)animated {
7229 [super viewDidAppear:animated];
7230 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7233 - (void) viewWillDisappear:(BOOL)animated {
7234 [super viewWillDisappear:animated];
7235 if ([self isEditing]) [self setEditing:NO];
7238 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7239 Section *section = nil;
7240 int index = [indexPath row];
7241 if (![self isEditing]) {
7244 section = [filtered_ objectAtIndex:index];
7246 section = [sections_ objectAtIndex:index];
7251 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7252 if ([self isEditing])
7253 return [sections_ count];
7255 return [filtered_ count] + 1;
7258 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7262 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7263 static NSString *reuseIdentifier = @"SectionCell";
7265 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7267 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7269 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7274 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7275 if ([self isEditing])
7278 Section *section = [self sectionAtIndexPath:indexPath];
7280 SectionController *controller = [[[SectionController alloc]
7281 initWithDatabase:database_
7282 section:[section name]
7284 [controller setDelegate:delegate_];
7286 [[self navigationController] pushViewController:controller animated:YES];
7290 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7292 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7293 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7294 [list_ setRowHeight:45.0f];
7295 [(UITableView *) list_ setDataSource:self];
7296 [list_ setDelegate:self];
7297 [[self view] addSubview:list_];
7300 - (void) viewDidLoad {
7301 [super viewDidLoad];
7303 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7306 - (void) releaseSubviews {
7312 [super releaseSubviews];
7315 - (id) initWithDatabase:(Database *)database {
7316 if ((self = [super init]) != nil) {
7317 database_ = database;
7321 - (void) reloadData {
7324 NSArray *packages = [database_ packages];
7326 sections_ = [NSMutableArray arrayWithCapacity:16];
7327 filtered_ = [NSMutableArray arrayWithCapacity:16];
7329 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7332 for (Package *package in packages) {
7333 NSString *name([package section]);
7334 NSString *key(name == nil ? @"" : name);
7338 _profile(SectionsView$reloadData$Section)
7339 section = [sections objectForKey:key];
7340 if (section == nil) {
7341 _profile(SectionsView$reloadData$Section$Allocate)
7342 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7343 [sections setObject:section forKey:key];
7348 [section addToCount];
7350 _profile(SectionsView$reloadData$Filter)
7351 if (![package valid] || ![package visible])
7359 [sections_ addObjectsFromArray:[sections allValues]];
7361 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7363 for (Section *section in (id) sections_) {
7364 size_t count([section row]);
7368 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7369 [section setCount:count];
7370 [filtered_ addObject:section];
7373 [self updateNavigationItem];
7378 - (void) editButtonClicked {
7379 [self setEditing:![self isEditing] animated:YES];
7385 /* Changes Controller {{{ */
7386 @interface ChangesController : CyteViewController <
7387 UITableViewDataSource,
7390 _transient Database *database_;
7392 _H<NSArray> packages_;
7393 _H<NSMutableArray> sections_;
7394 _H<UITableView, 2> list_;
7398 - (id) initWithDatabase:(Database *)database;
7402 @implementation ChangesController
7404 - (NSURL *) navigationURL {
7405 return [NSURL URLWithString:@"cydia://changes"];
7408 - (void) viewDidAppear:(BOOL)animated {
7409 [super viewDidAppear:animated];
7410 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7413 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7414 NSInteger count([sections_ count]);
7415 return count == 0 ? 1 : count;
7418 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7419 if ([sections_ count] == 0)
7421 return [[sections_ objectAtIndex:section] name];
7424 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7425 if ([sections_ count] == 0)
7427 return [[sections_ objectAtIndex:section] count];
7430 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7431 @synchronized (database_) {
7432 if ([database_ era] != era_)
7435 NSUInteger sectionIndex([path section]);
7436 if (sectionIndex >= [sections_ count])
7438 Section *section([sections_ objectAtIndex:sectionIndex]);
7439 NSInteger row([path row]);
7440 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7443 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7444 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7446 cell = [[[PackageCell alloc] init] autorelease];
7448 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7449 [cell setPackage:package asSummary:false];
7453 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7454 Package *package([self packageAtIndexPath:path]);
7455 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7456 [view setDelegate:delegate_];
7457 [[self navigationController] pushViewController:view animated:YES];
7461 - (void) refreshButtonClicked {
7462 [delegate_ beginUpdate];
7463 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7466 - (void) upgradeButtonClicked {
7467 [delegate_ distUpgrade];
7468 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7472 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7474 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7475 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7476 [list_ setRowHeight:73];
7477 [(UITableView *) list_ setDataSource:self];
7478 [list_ setDelegate:self];
7479 [[self view] addSubview:list_];
7482 - (void) viewDidLoad {
7483 [super viewDidLoad];
7485 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7488 - (void) releaseSubviews {
7494 [super releaseSubviews];
7497 - (id) initWithDatabase:(Database *)database {
7498 if ((self = [super init]) != nil) {
7499 database_ = database;
7503 - (NSMutableArray *) _reloadPackages {
7504 @synchronized (database_) {
7505 era_ = [database_ era];
7506 NSArray *packages([database_ packages]);
7508 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7511 _profile(ChangesController$_reloadPackages$Filter)
7512 for (Package *package in packages)
7513 if ([package upgradableAndEssential:YES] || [package visible])
7514 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7517 _profile(ChangesController$_reloadPackages$radixSort)
7518 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7525 - (void) _reloadData {
7530 UIProgressHUD *hud([delegate_ addProgressHUD]);
7531 [hud setText:UCLocalize("LOADING")];
7532 //NSLog(@"HUD:%@::%@", delegate_, hud);
7533 packages = [self yieldToSelector:@selector(_reloadPackages)];
7534 [delegate_ removeProgressHUD:hud];
7536 packages = [self _reloadPackages];
7539 @synchronized (database_) {
7540 if (era_ != [database_ era])
7543 packages_ = packages;
7544 sections_ = [NSMutableArray arrayWithCapacity:16];
7546 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7547 Section *ignored = nil;
7548 Section *section = nil;
7552 bool unseens = false;
7554 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7556 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7557 Package *package = [packages_ objectAtIndex:offset];
7559 BOOL uae = [package upgradableAndEssential:YES];
7563 time_t seen([package seen]);
7565 if (section == nil || last != seen) {
7569 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7572 _profile(ChangesController$reloadData$Allocate)
7573 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7574 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7575 [sections_ addObject:section];
7579 [section addToCount];
7580 } else if ([package ignored]) {
7581 if (ignored == nil) {
7582 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7584 [ignored addToCount];
7587 [upgradable addToCount];
7592 CFRelease(formatter);
7595 Section *last = [sections_ lastObject];
7596 size_t count = [last count];
7597 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7598 [sections_ removeLastObject];
7601 if ([ignored count] != 0)
7602 [sections_ insertObject:ignored atIndex:0];
7604 [sections_ insertObject:upgradable atIndex:0];
7608 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7609 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7610 style:UIBarButtonItemStylePlain
7612 action:@selector(upgradeButtonClicked)
7613 ] autorelease]) animated:YES];
7615 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7616 initWithTitle:UCLocalize("REFRESH")
7617 style:UIBarButtonItemStylePlain
7619 action:@selector(refreshButtonClicked)
7620 ] autorelease]) animated:YES];
7625 - (void) reloadData {
7627 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7632 /* Search Controller {{{ */
7633 @interface SearchController : FilteredPackageListController <
7636 _H<UISearchBar, 1> search_;
7640 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7641 - (void) reloadData;
7645 @implementation SearchController
7647 - (NSURL *) navigationURL {
7648 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7649 return [NSURL URLWithString:@"cydia://search"];
7651 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7654 - (void) useSearch {
7655 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7660 - (void) viewWillAppear:(BOOL)animated {
7661 [super viewWillAppear:animated];
7663 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7667 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7668 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7673 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7674 [search_ resignFirstResponder];
7678 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7679 [search_ setText:@""];
7680 [self searchBarButtonClicked:searchBar];
7683 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7684 [self searchBarButtonClicked:searchBar];
7687 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7688 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7692 - (bool) shouldYield {
7696 - (bool) shouldBlock {
7697 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7700 - (bool) isSummarized {
7701 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7704 - (bool) showsSections {
7708 - (NSMutableArray *) _reloadPackages {
7709 NSMutableArray *packages([super _reloadPackages]);
7710 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7711 [packages radixSortUsingSelector:@selector(rank)];
7715 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7716 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7717 search_ = [[[UISearchBar alloc] init] autorelease];
7718 [search_ setDelegate:self];
7721 [search_ setText:query];
7725 - (void) viewDidAppear:(BOOL)animated {
7726 [super viewDidAppear:animated];
7728 if (!searchloaded_) {
7729 searchloaded_ = YES;
7730 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7731 [search_ layoutSubviews];
7732 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7734 UITextField *textField;
7735 if ([search_ respondsToSelector:@selector(searchField)])
7736 textField = [search_ searchField];
7738 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7740 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7741 [textField setEnablesReturnKeyAutomatically:NO];
7742 [[self navigationItem] setTitleView:textField];
7746 - (void) reloadData {
7747 id object([search_ text]);
7748 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7749 object = [object componentsSeparatedByString:@" "];
7751 [self setObject:object];
7757 - (void) didSelectPackage:(Package *)package {
7758 [search_ resignFirstResponder];
7759 [super didSelectPackage:package];
7764 /* Package Settings Controller {{{ */
7765 @interface PackageSettingsController : CyteViewController <
7766 UITableViewDataSource,
7769 _transient Database *database_;
7771 _H<Package> package_;
7772 _H<UITableView, 2> table_;
7773 _H<UISwitch> subscribedSwitch_;
7774 _H<UISwitch> ignoredSwitch_;
7775 _H<UITableViewCell> subscribedCell_;
7776 _H<UITableViewCell> ignoredCell_;
7779 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7783 @implementation PackageSettingsController
7785 - (NSURL *) navigationURL {
7786 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7789 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7790 if (package_ == nil)
7793 if ([package_ installed] == nil)
7799 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7800 if (package_ == nil)
7803 // both sections contain just one item right now.
7807 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7811 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7813 return UCLocalize("SHOW_ALL_CHANGES_EX");
7815 return UCLocalize("IGNORE_UPGRADES_EX");
7818 - (void) onSubscribed:(id)control {
7819 bool value([control isOn]);
7820 if (package_ == nil)
7822 if ([package_ setSubscribed:value])
7823 [delegate_ updateData];
7826 - (void) _updateIgnored {
7827 const char *package([name_ UTF8String]);
7828 bool on([ignoredSwitch_ isOn]);
7830 pid_t pid(ExecFork());
7832 FILE *dpkg(popen("dpkg --set-selections", "w"));
7833 fwrite(package, strlen(package), 1, dpkg);
7836 fwrite(" hold\n", 6, 1, dpkg);
7838 fwrite(" install\n", 9, 1, dpkg);
7849 - (void) onIgnored:(id)control {
7850 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7851 [invocation setTarget:self];
7852 [invocation setSelector:@selector(_updateIgnored)];
7854 [delegate_ reloadDataWithInvocation:invocation];
7857 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7858 if (package_ == nil)
7861 switch ([indexPath section]) {
7862 case 0: return subscribedCell_;
7863 case 1: return ignoredCell_;
7872 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7874 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7875 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7876 [(UITableView *) table_ setDataSource:self];
7877 [table_ setDelegate:self];
7878 [[self view] addSubview:table_];
7880 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7881 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7882 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7884 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7885 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7886 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7888 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7889 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7890 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7891 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7893 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7894 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7895 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7896 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7899 - (void) viewDidLoad {
7900 [super viewDidLoad];
7902 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7905 - (void) releaseSubviews {
7907 subscribedCell_ = nil;
7909 ignoredSwitch_ = nil;
7910 subscribedSwitch_ = nil;
7912 [super releaseSubviews];
7915 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7916 if ((self = [super init]) != nil) {
7917 database_ = database;
7922 - (void) reloadData {
7925 package_ = [database_ packageWithName:name_];
7927 if (package_ != nil) {
7928 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7929 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7930 } // XXX: what now, G?
7932 [table_ reloadData];
7938 /* Installed Controller {{{ */
7939 @interface InstalledController : FilteredPackageListController {
7943 - (id) initWithDatabase:(Database *)database;
7945 - (void) updateRoleButton;
7946 - (void) queueStatusDidChange;
7950 @implementation InstalledController
7952 - (NSURL *) navigationURL {
7953 return [NSURL URLWithString:@"cydia://installed"];
7956 - (id) initWithDatabase:(Database *)database {
7957 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7958 [self updateRoleButton];
7959 [self queueStatusDidChange];
7964 - (void) queueButtonClicked {
7969 - (void) queueStatusDidChange {
7973 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7974 initWithTitle:UCLocalize("QUEUE")
7975 style:UIBarButtonItemStyleDone
7977 action:@selector(queueButtonClicked)
7980 [[self navigationItem] setLeftBarButtonItem:nil];
7986 - (void) updateRoleButton {
7987 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7988 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7989 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7990 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7992 action:@selector(roleButtonClicked)
7996 - (void) roleButtonClicked {
7997 [self setObject:[NSNumber numberWithBool:expert_]];
8001 [self updateRoleButton];
8007 /* Source Cell {{{ */
8008 @interface SourceCell : CyteTableViewCell <
8009 CyteTableViewCellDelegate
8013 _H<NSString> origin_;
8014 _H<NSString> label_;
8017 - (void) setSource:(Source *)source;
8021 @implementation SourceCell
8023 - (void) _setImage:(NSArray *)data {
8024 if ([url_ isEqual:[data objectAtIndex:0]]) {
8025 icon_ = [data objectAtIndex:1];
8026 [content_ setNeedsDisplay];
8030 - (void) _setSource:(NSURL *) url {
8031 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8033 if (NSData *data = [NSURLConnection
8034 sendSynchronousRequest:[NSURLRequest
8036 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8040 returningResponse:NULL
8043 if (UIImage *image = [UIImage imageWithData:data])
8044 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8049 - (void) setSource:(Source *)source {
8050 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8052 origin_ = [source name];
8053 label_ = [source rooturi];
8055 [content_ setNeedsDisplay];
8057 url_ = [source iconURL];
8058 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8061 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8062 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8063 UIView *content([self contentView]);
8064 CGRect bounds([content bounds]);
8066 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8067 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8068 [content_ setBackgroundColor:[UIColor whiteColor]];
8069 [content addSubview:content_];
8071 [content_ setDelegate:self];
8072 [content_ setOpaque:YES];
8074 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8078 - (NSString *) accessibilityLabel {
8082 - (void) drawContentRect:(CGRect)rect {
8083 bool highlighted(highlighted_);
8084 float width(rect.size.width);
8088 rect.size = [(UIImage *) icon_ size];
8090 while (rect.size.width > 32 || rect.size.height > 32) {
8091 rect.size.width /= 2;
8092 rect.size.height /= 2;
8095 rect.origin.x = 25 - rect.size.width / 2;
8096 rect.origin.y = 25 - rect.size.height / 2;
8098 [icon_ drawInRect:rect];
8106 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8110 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8115 /* Source Controller {{{ */
8116 @interface SourceController : FilteredPackageListController {
8117 _transient Source *source_;
8121 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8125 @implementation SourceController
8127 - (NSURL *) navigationURL {
8128 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8131 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8132 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8134 key_ = [source key];
8138 - (void) reloadData {
8139 source_ = [database_ sourceWithKey:key_];
8140 key_ = [source_ key];
8141 [self setObject:source_];
8143 [[self navigationItem] setTitle:[source_ label]];
8150 /* Sources Controller {{{ */
8151 @interface SourcesController : CyteViewController <
8152 UITableViewDataSource,
8155 _transient Database *database_;
8158 _H<UITableView, 2> list_;
8159 _H<NSMutableArray> sources_;
8163 _H<UIProgressHUD> hud_;
8166 //NSURLConnection *installer_;
8167 NSURLConnection *trivial_;
8168 NSURLConnection *trivial_bz2_;
8169 NSURLConnection *trivial_gz_;
8170 //NSURLConnection *automatic_;
8175 - (id) initWithDatabase:(Database *)database;
8176 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8180 @implementation SourcesController
8182 - (void) _releaseConnection:(NSURLConnection *)connection {
8183 if (connection != nil) {
8184 [connection cancel];
8185 //[connection setDelegate:nil];
8186 [connection release];
8191 //[self _releaseConnection:installer_];
8192 [self _releaseConnection:trivial_];
8193 [self _releaseConnection:trivial_gz_];
8194 [self _releaseConnection:trivial_bz2_];
8195 //[self _releaseConnection:automatic_];
8200 - (NSURL *) navigationURL {
8201 return [NSURL URLWithString:@"cydia://sources"];
8204 - (void) viewDidAppear:(BOOL)animated {
8205 [super viewDidAppear:animated];
8206 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8209 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8213 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8217 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8218 return [sources_ count];
8221 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8222 @synchronized (database_) {
8223 if ([database_ era] != era_)
8226 return [sources_ objectAtIndex:[indexPath row]];
8229 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8230 static NSString *cellIdentifier = @"SourceCell";
8232 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8233 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8234 [cell setSource:[self sourceAtIndexPath:indexPath]];
8235 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8240 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8241 Source *source = [self sourceAtIndexPath:indexPath];
8243 SourceController *controller = [[[SourceController alloc]
8244 initWithDatabase:database_
8248 [controller setDelegate:delegate_];
8250 [[self navigationController] pushViewController:controller animated:YES];
8253 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8254 Source *source = [self sourceAtIndexPath:indexPath];
8255 return [source record] != nil;
8258 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8259 if (editingStyle == UITableViewCellEditingStyleDelete) {
8260 Source *source = [self sourceAtIndexPath:indexPath];
8261 [Sources_ removeObjectForKey:[source key]];
8262 [delegate_ syncData];
8267 [delegate_ addTrivialSource:href_];
8270 [delegate_ syncData];
8273 - (NSString *) getWarning {
8274 NSString *href(href_);
8275 NSRange colon([href rangeOfString:@"://"]);
8276 if (colon.location != NSNotFound)
8277 href = [href substringFromIndex:(colon.location + 3)];
8278 href = [href stringByAddingPercentEscapes];
8279 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8281 NSURL *url([NSURL URLWithString:href]);
8283 NSStringEncoding encoding;
8284 NSError *error(nil);
8286 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8287 return [warning length] == 0 ? nil : warning;
8291 - (void) _endConnection:(NSURLConnection *)connection {
8292 // XXX: the memory management in this method is horribly awkward
8294 NSURLConnection **field = NULL;
8295 if (connection == trivial_)
8297 else if (connection == trivial_bz2_)
8298 field = &trivial_bz2_;
8299 else if (connection == trivial_gz_)
8300 field = &trivial_gz_;
8301 _assert(field != NULL);
8302 [connection release];
8307 trivial_bz2_ == nil &&
8310 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8312 [delegate_ releaseNetworkActivityIndicator];
8314 [delegate_ removeProgressHUD:hud_];
8318 if (warning != nil) {
8319 UIAlertView *alert = [[[UIAlertView alloc]
8320 initWithTitle:UCLocalize("SOURCE_WARNING")
8323 cancelButtonTitle:UCLocalize("CANCEL")
8325 UCLocalize("ADD_ANYWAY"),
8329 [alert setContext:@"warning"];
8330 [alert setNumberOfRows:1];
8333 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8339 } else if (error_ != nil) {
8340 UIAlertView *alert = [[[UIAlertView alloc]
8341 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8342 message:[error_ localizedDescription]
8344 cancelButtonTitle:UCLocalize("OK")
8345 otherButtonTitles:nil
8348 [alert setContext:@"urlerror"];
8353 UIAlertView *alert = [[[UIAlertView alloc]
8354 initWithTitle:UCLocalize("NOT_REPOSITORY")
8355 message:UCLocalize("NOT_REPOSITORY_EX")
8357 cancelButtonTitle:UCLocalize("OK")
8358 otherButtonTitles:nil
8361 [alert setContext:@"trivial"];
8371 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8372 switch ([response statusCode]) {
8378 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8379 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8381 [self _endConnection:connection];
8384 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8385 [self _endConnection:connection];
8388 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8389 NSURL *url([NSURL URLWithString:href]);
8391 NSMutableURLRequest *request = [NSMutableURLRequest
8393 cachePolicy:NSURLRequestUseProtocolCachePolicy
8394 timeoutInterval:120.0
8397 [request setHTTPMethod:method];
8399 if (Machine_ != NULL)
8400 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8402 if ([url isCydiaSecure]) {
8403 if (UniqueID_ != nil) {
8404 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8405 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8409 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8412 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8413 NSString *context([alert context]);
8415 if ([context isEqualToString:@"source"]) {
8418 NSString *href = [[alert textField] text];
8420 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8422 if (![href hasSuffix:@"/"])
8423 href_ = [href stringByAppendingString:@"/"];
8427 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8428 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8429 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8430 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8434 // XXX: this is stupid
8435 hud_ = [delegate_ addProgressHUD];
8436 [hud_ setText:UCLocalize("VERIFYING_URL")];
8437 [delegate_ retainNetworkActivityIndicator];
8446 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8447 } else if ([context isEqualToString:@"trivial"])
8448 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8449 else if ([context isEqualToString:@"urlerror"])
8450 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8451 else if ([context isEqualToString:@"warning"]) {
8454 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8463 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8468 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8470 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8471 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8472 [list_ setRowHeight:53];
8473 [(UITableView *) list_ setDataSource:self];
8474 [list_ setDelegate:self];
8475 [[self view] addSubview:list_];
8478 - (void) viewDidLoad {
8479 [super viewDidLoad];
8481 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8482 [self updateButtonsForEditingStatus:NO animated:NO];
8485 - (void) releaseSubviews {
8490 [super releaseSubviews];
8493 - (id) initWithDatabase:(Database *)database {
8494 if ((self = [super init]) != nil) {
8495 database_ = database;
8499 - (void) reloadData {
8502 @synchronized (database_) {
8503 era_ = [database_ era];
8506 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8509 sources_ = [NSMutableArray arrayWithCapacity:16];
8510 [sources_ addObjectsFromArray:[database_ sources]];
8512 [sources_ sortUsingSelector:@selector(compareByName:)];
8515 int count([sources_ count]);
8517 for (int i = 0; i != count; i++) {
8518 if ([[sources_ objectAtIndex:i] record] == nil)
8523 [list_ setEditing:NO];
8524 [self updateButtonsForEditingStatus:NO animated:NO];
8528 - (void) showAddSourcePrompt {
8529 UIAlertView *alert = [[[UIAlertView alloc]
8530 initWithTitle:UCLocalize("ENTER_APT_URL")
8533 cancelButtonTitle:UCLocalize("CANCEL")
8535 UCLocalize("ADD_SOURCE"),
8539 [alert setContext:@"source"];
8541 [alert setNumberOfRows:1];
8542 [alert addTextFieldWithValue:@"http://" label:@""];
8544 UITextInputTraits *traits = [[alert textField] textInputTraits];
8545 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8546 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8547 [traits setKeyboardType:UIKeyboardTypeURL];
8548 // XXX: UIReturnKeyDone
8549 [traits setReturnKeyType:UIReturnKeyNext];
8554 - (void) addButtonClicked {
8555 [self showAddSourcePrompt];
8558 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8559 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8560 initWithTitle:UCLocalize("ADD")
8561 style:UIBarButtonItemStylePlain
8563 action:@selector(addButtonClicked)
8564 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8566 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8567 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8568 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8570 action:@selector(editButtonClicked)
8571 ] autorelease] animated:animated];
8573 if (IsWildcat_ && !editing)
8574 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8575 initWithTitle:UCLocalize("SETTINGS")
8576 style:UIBarButtonItemStylePlain
8578 action:@selector(settingsButtonClicked)
8582 - (void) settingsButtonClicked {
8583 [delegate_ showSettings];
8586 - (void) editButtonClicked {
8587 [list_ setEditing:![list_ isEditing] animated:YES];
8589 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8595 /* Settings Controller {{{ */
8596 @interface SettingsController : CyteViewController <
8597 UITableViewDataSource,
8600 _transient Database *database_;
8601 // XXX: ok, "roledelegate_"?...
8602 _transient id roledelegate_;
8603 _H<UITableView, 2> table_;
8604 _H<UISegmentedControl> segment_;
8605 _H<UIView> container_;
8608 - (void) showDoneButton;
8609 - (void) resizeSegmentedControl;
8613 @implementation SettingsController
8616 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8618 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8619 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8620 [table_ setDelegate:self];
8621 [(UITableView *) table_ setDataSource:self];
8622 [[self view] addSubview:table_];
8624 NSArray *items = [NSArray arrayWithObjects:
8626 UCLocalize("HACKER"),
8627 UCLocalize("DEVELOPER"),
8629 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8630 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8631 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8632 [container_ addSubview:segment_];
8635 - (void) viewDidLoad {
8636 [super viewDidLoad];
8638 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8641 if ([Role_ isEqualToString:@"User"]) index = 0;
8642 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8643 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8645 [segment_ setSelectedSegmentIndex:index];
8646 [self showDoneButton];
8649 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8650 [self resizeSegmentedControl];
8653 - (void) releaseSubviews {
8658 [super releaseSubviews];
8661 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8662 if ((self = [super init]) != nil) {
8663 database_ = database;
8664 roledelegate_ = delegate;
8668 - (void) resizeSegmentedControl {
8669 CGFloat width = [[self view] frame].size.width;
8670 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8673 - (void) viewWillAppear:(BOOL)animated {
8674 [super viewWillAppear:animated];
8676 [self resizeSegmentedControl];
8679 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8680 [self resizeSegmentedControl];
8683 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8684 [self resizeSegmentedControl];
8688 NSString *role(nil);
8690 switch ([segment_ selectedSegmentIndex]) {
8691 case 0: role = @"User"; break;
8692 case 1: role = @"Hacker"; break;
8693 case 2: role = @"Developer"; break;
8698 if (![role isEqualToString:Role_]) {
8699 bool rolling(Role_ == nil);
8702 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8706 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8710 [roledelegate_ loadData];
8712 [roledelegate_ updateData];
8716 - (void) segmentChanged:(UISegmentedControl *)control {
8717 [self showDoneButton];
8720 - (void) saveAndClose {
8723 [[self navigationItem] setRightBarButtonItem:nil];
8724 [[self navigationController] dismissModalViewControllerAnimated:YES];
8727 - (void) doneButtonClicked {
8728 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8729 [spinner startAnimating];
8730 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8731 [[self navigationItem] setRightBarButtonItem:spinItem];
8733 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8736 - (void) showDoneButton {
8737 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8738 initWithTitle:UCLocalize("DONE")
8739 style:UIBarButtonItemStyleDone
8741 action:@selector(doneButtonClicked)
8742 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8745 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8746 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8750 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8754 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8755 return nil; // This method is required by the protocol.
8758 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8760 return UCLocalize("ROLE_EX");
8762 return [NSString stringWithFormat:
8763 @"%@: %@\n%@: %@\n%@: %@",
8764 UCLocalize("USER"), UCLocalize("USER_EX"),
8765 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8766 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8771 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8772 return section == 3 ? 44.0f : 0;
8775 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8776 return section == 3 ? container_ : nil;
8779 - (void) reloadData {
8782 [table_ reloadData];
8787 /* Stash Controller {{{ */
8788 @interface StashController : CyteViewController {
8789 _H<UIActivityIndicatorView> spinner_;
8790 _H<UILabel> status_;
8791 _H<UILabel> caption_;
8796 @implementation StashController
8799 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8800 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8802 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8803 CGRect spinrect = [spinner_ frame];
8804 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8805 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8806 [spinner_ setFrame:spinrect];
8807 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8808 [[self view] addSubview:spinner_];
8809 [spinner_ startAnimating];
8812 captrect.size.width = [[self view] frame].size.width;
8813 captrect.size.height = 40.0f;
8814 captrect.origin.x = 0;
8815 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8816 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8817 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8818 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8819 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8820 [caption_ setTextColor:[UIColor whiteColor]];
8821 [caption_ setBackgroundColor:[UIColor clearColor]];
8822 [caption_ setShadowColor:[UIColor blackColor]];
8823 [caption_ setTextAlignment:UITextAlignmentCenter];
8824 [[self view] addSubview:caption_];
8827 statusrect.size.width = [[self view] frame].size.width;
8828 statusrect.size.height = 30.0f;
8829 statusrect.origin.x = 0;
8830 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8831 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8832 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8833 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8834 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8835 [status_ setTextColor:[UIColor whiteColor]];
8836 [status_ setBackgroundColor:[UIColor clearColor]];
8837 [status_ setShadowColor:[UIColor blackColor]];
8838 [status_ setTextAlignment:UITextAlignmentCenter];
8839 [[self view] addSubview:status_];
8842 - (void) releaseSubviews {
8847 [super releaseSubviews];
8853 @interface CYURLCache : SDURLCache {
8858 @implementation CYURLCache
8860 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8863 else if ([event isEqualToString:@"no-cache"])
8865 else if ([event isEqualToString:@"store"])
8867 else if ([event isEqualToString:@"invalid"])
8869 else if ([event isEqualToString:@"memory"])
8871 else if ([event isEqualToString:@"disk"])
8873 else if ([event isEqualToString:@"miss"])
8876 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8880 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8881 if (NSURLResponse *response = [cached response])
8882 if (NSString *mime = [response MIMEType])
8883 if ([mime isEqualToString:@"text/cache-manifest"]) {
8884 NSURL *url([response URL]);
8887 NSLog(@"###: %@", [url absoluteString]);
8890 @synchronized (HostConfig_) {
8891 [CachedURLs_ addObject:url];
8895 [super storeCachedResponse:cached forRequest:request];
8900 @interface Cydia : UIApplication <
8901 ConfirmationControllerDelegate,
8904 UINavigationControllerDelegate,
8905 UITabBarControllerDelegate
8907 _H<UIWindow> window_;
8908 _H<CYTabBarController> tabbar_;
8909 _H<CydiaLoadingViewController> emulated_;
8911 _H<NSMutableArray> essential_;
8912 _H<NSMutableArray> broken_;
8914 Database *database_;
8916 _H<NSURL> starturl_;
8921 _H<StashController> stash_;
8930 @implementation Cydia
8932 - (void) beginUpdate {
8933 [tabbar_ beginUpdate];
8937 return [tabbar_ updating];
8941 if ([broken_ count] != 0) {
8942 int count = [broken_ count];
8944 UIAlertView *alert = [[[UIAlertView alloc]
8945 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8946 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8948 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8950 UCLocalize("TEMPORARY_IGNORE"),
8954 [alert setContext:@"fixhalf"];
8955 [alert setNumberOfRows:2];
8957 } else if (!Ignored_ && [essential_ count] != 0) {
8958 int count = [essential_ count];
8960 UIAlertView *alert = [[[UIAlertView alloc]
8961 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8962 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8964 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8966 UCLocalize("UPGRADE_ESSENTIAL"),
8967 UCLocalize("COMPLETE_UPGRADE"),
8971 [alert setContext:@"upgrade"];
8976 - (void) returnToCydia {
8980 - (void) _saveConfig {
8981 @synchronized (database_) {
8988 NSString *error(nil);
8990 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8992 NSError *error(nil);
8993 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8994 NSLog(@"failure to save metadata data: %@", error);
8999 NSLog(@"failure to serialize metadata: %@", error);
9003 CydiaWriteSources();
9006 // Navigation controller for the queuing badge.
9007 - (UINavigationController *) queueNavigationController {
9008 NSArray *controllers = [tabbar_ viewControllers];
9009 return [controllers objectAtIndex:3];
9012 - (void) unloadData {
9013 [tabbar_ unloadData];
9016 - (void) _updateData {
9020 UINavigationController *navigation = [self queueNavigationController];
9022 id queuedelegate = nil;
9023 if ([[navigation viewControllers] count] > 0)
9024 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9026 [queuedelegate queueStatusDidChange];
9027 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9030 - (void) _refreshIfPossible:(NSDate *)update {
9031 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9033 bool recently = false;
9034 if (update != nil) {
9035 NSTimeInterval interval([update timeIntervalSinceNow]);
9036 if (interval <= 0 && interval > -(15*60))
9040 // Don't automatic refresh if:
9041 // - We already refreshed recently.
9042 // - We already auto-refreshed this launch.
9043 // - Auto-refresh is disabled.
9044 if (recently || loaded_ || ManualRefresh) {
9045 // If we are cancelling, we need to make sure it knows it's already loaded.
9048 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9050 // We are going to load, so remember that.
9053 SCNetworkReachabilityFlags flags; {
9054 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9055 SCNetworkReachabilityGetFlags(reachability, &flags);
9056 CFRelease(reachability);
9059 // XXX: this elaborate mess is what Apple is using to determine this? :(
9060 // XXX: do we care if the user has to intervene? maybe that's ok?
9062 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9063 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9064 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9065 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9066 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9067 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9071 // If we can reach the server, auto-refresh!
9073 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9079 - (void) refreshIfPossible {
9080 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9083 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9084 @synchronized (self) {
9085 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9086 [hud setText:UCLocalize("RELOADING_DATA")];
9088 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9092 [essential_ removeAllObjects];
9093 [broken_ removeAllObjects];
9095 NSArray *packages([database_ packages]);
9096 for (Package *package in packages) {
9098 [broken_ addObject:package];
9099 if ([package upgradableAndEssential:NO]) {
9100 if ([package essential])
9101 [essential_ addObject:package];
9106 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9109 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9110 [changesItem setBadgeValue:badge];
9111 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9112 [self setApplicationIconBadgeNumber:changes];
9115 [changesItem setBadgeValue:nil];
9116 [changesItem setAnimatedBadge:NO];
9117 [self setApplicationIconBadgeNumber:0];
9123 [self removeProgressHUD:hud];
9126 - (void) updateData {
9132 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9135 - (void) disemulate {
9136 if (emulated_ == nil)
9139 [window_ addSubview:[tabbar_ view]];
9140 [[emulated_ view] removeFromSuperview];
9142 [window_ setUserInteractionEnabled:YES];
9145 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9146 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9148 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9150 UIViewController *parent;
9151 if (emulated_ == nil)
9160 [parent presentModalViewController:navigation animated:YES];
9163 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9164 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9166 if (navigation != nil)
9167 [navigation pushViewController:progress animated:YES];
9169 [self presentModalViewController:progress force:YES];
9171 [progress invoke:invocation withTitle:title];
9175 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9176 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9179 - (void) repairWithInvocation:(NSInvocation *)invocation {
9181 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9185 - (void) repairWithSelector:(SEL)selector {
9186 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9189 - (void) reloadData {
9190 [self reloadDataWithInvocation:nil];
9191 if ([database_ progressDelegate] == nil)
9197 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9200 - (void) addSource:(NSDictionary *) source {
9201 CydiaAddSource(source);
9204 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9205 CydiaAddSource(href, distribution, sections);
9208 - (void) addTrivialSource:(NSString *)href {
9209 CydiaAddSource(href, @"./");
9212 - (void) updateValues {
9217 pkgProblemResolver *resolver = [database_ resolver];
9219 resolver->InstallProtect();
9220 if (!resolver->Resolve(true))
9225 // XXX: this is a really crappy way of doing this.
9226 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9227 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9228 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9229 if ([tabbar_ updating])
9230 [tabbar_ cancelUpdate];
9232 if (![database_ prepare])
9235 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9236 [page setDelegate:self];
9237 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9240 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9241 [tabbar_ presentModalViewController:confirm_ animated:YES];
9247 @synchronized (self) {
9252 - (void) clearPackage:(Package *)package {
9253 @synchronized (self) {
9260 - (void) installPackages:(NSArray *)packages {
9261 @synchronized (self) {
9262 for (Package *package in packages)
9269 - (void) installPackage:(Package *)package {
9270 @synchronized (self) {
9277 - (void) removePackage:(Package *)package {
9278 @synchronized (self) {
9285 - (void) distUpgrade {
9286 @synchronized (self) {
9287 if (![database_ upgrade])
9294 [database_ perform];
9295 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9298 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9301 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9303 [self refreshIfPossible];
9306 - (void) showSettings {
9307 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9310 - (void) retainNetworkActivityIndicator {
9311 if (activity_++ == 0)
9312 [self setNetworkActivityIndicatorVisible:YES];
9315 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9319 - (void) releaseNetworkActivityIndicator {
9320 if (--activity_ == 0)
9321 [self setNetworkActivityIndicatorVisible:NO];
9324 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9329 - (void) cancelAndClear:(bool)clear {
9330 @synchronized (self) {
9342 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9343 NSString *context([alert context]);
9345 if ([context isEqualToString:@"conffile"]) {
9346 FILE *input = [database_ input];
9347 if (button == [alert cancelButtonIndex])
9348 fprintf(input, "N\n");
9349 else if (button == [alert firstOtherButtonIndex])
9350 fprintf(input, "Y\n");
9353 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9354 } else if ([context isEqualToString:@"fixhalf"]) {
9355 if (button == [alert cancelButtonIndex]) {
9356 @synchronized (self) {
9357 for (Package *broken in (id) broken_) {
9360 NSString *id = [broken id];
9361 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9362 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9363 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9364 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9370 } else if (button == [alert firstOtherButtonIndex]) {
9371 [broken_ removeAllObjects];
9375 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9376 } else if ([context isEqualToString:@"upgrade"]) {
9377 if (button == [alert firstOtherButtonIndex]) {
9378 @synchronized (self) {
9379 for (Package *essential in (id) essential_)
9380 [essential install];
9385 } else if (button == [alert firstOtherButtonIndex] + 1) {
9387 } else if (button == [alert cancelButtonIndex]) {
9391 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9395 - (void) system:(NSString *)command {
9396 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9399 system([command UTF8String]);
9405 - (void) applicationWillSuspend {
9407 [super applicationWillSuspend];
9410 - (BOOL) isSafeToSuspend {
9413 NSLog(@"isSafeToSuspend: locked_ != 0");
9418 // Use external process status API internally.
9419 // This is probably a really bad idea.
9420 // XXX: what is the point of this? does this solve anything at all?
9421 uint64_t status = 0;
9423 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9424 notify_get_state(notify_token, &status);
9425 notify_cancel(notify_token);
9430 NSLog(@"isSafeToSuspend: status != 0");
9436 NSLog(@"isSafeToSuspend: -> true");
9441 - (void) applicationSuspend:(__GSEvent *)event {
9442 if ([self isSafeToSuspend])
9443 [super applicationSuspend:event];
9446 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9447 if ([self isSafeToSuspend])
9448 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9451 - (void) _setSuspended:(BOOL)value {
9452 if ([self isSafeToSuspend])
9453 [super _setSuspended:value];
9456 - (UIProgressHUD *) addProgressHUD {
9457 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9458 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9460 [window_ setUserInteractionEnabled:NO];
9462 UIViewController *target(tabbar_);
9463 if (UIViewController *modal = [target modalViewController])
9466 [hud showInView:[target view]];
9472 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9475 [hud removeFromSuperview];
9476 [window_ setUserInteractionEnabled:YES];
9479 - (CyteViewController *) pageForPackage:(NSString *)name {
9480 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9483 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9484 NSString *scheme([[url scheme] lowercaseString]);
9485 if ([[url absoluteString] length] <= [scheme length] + 3)
9487 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9488 NSArray *components([path componentsSeparatedByString:@"/"]);
9490 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9491 return [self pageForPackage:[components objectAtIndex:1]];
9493 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9496 NSString *base([components objectAtIndex:0]);
9498 CyteViewController *controller = nil;
9500 if ([base isEqualToString:@"url"]) {
9501 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9502 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9503 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9504 } else if (!external && [components count] == 1) {
9505 if ([base isEqualToString:@"manage"]) {
9506 controller = [[[ManageController alloc] init] autorelease];
9509 if ([base isEqualToString:@"storage"]) {
9510 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9513 if ([base isEqualToString:@"sources"]) {
9514 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9517 if ([base isEqualToString:@"home"]) {
9518 controller = [[[HomeController alloc] init] autorelease];
9521 if ([base isEqualToString:@"sections"]) {
9522 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9525 if ([base isEqualToString:@"search"]) {
9526 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9529 if ([base isEqualToString:@"changes"]) {
9530 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9533 if ([base isEqualToString:@"installed"]) {
9534 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9536 } else if ([components count] == 2) {
9537 NSString *argument = [components objectAtIndex:1];
9539 if ([base isEqualToString:@"package"]) {
9540 controller = [self pageForPackage:argument];
9543 if (!external && [base isEqualToString:@"search"]) {
9544 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9547 if (!external && [base isEqualToString:@"sections"]) {
9548 if ([argument isEqualToString:@"all"])
9550 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9553 if (!external && [base isEqualToString:@"sources"]) {
9554 if ([argument isEqualToString:@"add"]) {
9555 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9556 [(SourcesController *)controller showAddSourcePrompt];
9558 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9559 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9563 if (!external && [base isEqualToString:@"launch"]) {
9564 [self launchApplicationWithIdentifier:argument suspended:NO];
9567 } else if (!external && [components count] == 3) {
9568 NSString *arg1 = [components objectAtIndex:1];
9569 NSString *arg2 = [components objectAtIndex:2];
9571 if ([base isEqualToString:@"package"]) {
9572 if ([arg2 isEqualToString:@"settings"]) {
9573 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9574 } else if ([arg2 isEqualToString:@"files"]) {
9575 if (Package *package = [database_ packageWithName:arg1]) {
9576 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9577 [(FileTable *)controller setPackage:package];
9583 [controller setDelegate:self];
9587 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9588 CyteViewController *page([self pageForURL:url forExternal:external]);
9591 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9592 [nav setViewControllers:[NSArray arrayWithObject:page]];
9593 [tabbar_ setUnselectedViewController:nav];
9599 - (void) applicationOpenURL:(NSURL *)url {
9600 [super applicationOpenURL:url];
9605 [self openCydiaURL:url forExternal:YES];
9608 - (void) applicationWillResignActive:(UIApplication *)application {
9609 // Stop refreshing if you get a phone call or lock the device.
9610 if ([tabbar_ updating])
9611 [tabbar_ cancelUpdate];
9613 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9614 [super applicationWillResignActive:application];
9617 - (void) saveState {
9618 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9619 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9620 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9626 - (void) applicationWillTerminate:(UIApplication *)application {
9630 - (void) setConfigurationData:(NSString *)data {
9631 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9633 if (!conffile_r(data)) {
9634 lprintf("E:invalid conffile\n");
9638 NSString *ofile = conffile_r[1];
9639 //NSString *nfile = conffile_r[2];
9641 UIAlertView *alert = [[[UIAlertView alloc]
9642 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9643 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9645 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9647 UCLocalize("ACCEPT_NEW_COPY"),
9648 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9652 [alert setContext:@"conffile"];
9653 [alert setNumberOfRows:2];
9657 - (void) addStashController {
9659 stash_ = [[[StashController alloc] init] autorelease];
9660 [window_ addSubview:[stash_ view]];
9663 - (void) removeStashController {
9664 [[stash_ view] removeFromSuperview];
9670 [self setIdleTimerDisabled:YES];
9672 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9673 UpdateExternalStatus(1);
9674 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9675 UpdateExternalStatus(0);
9677 [self removeStashController];
9679 pid_t pid(ExecFork());
9681 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9682 perror("launchctl stop");
9689 - (void) setupViewControllers {
9690 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9692 NSMutableArray *items([NSMutableArray arrayWithObjects:
9693 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9694 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9695 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9696 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9700 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9701 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9703 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9706 NSMutableArray *controllers([NSMutableArray array]);
9707 for (UITabBarItem *item in items) {
9708 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9709 [controller setTabBarItem:item];
9710 [controllers addObject:controller];
9712 [tabbar_ setViewControllers:controllers];
9714 [tabbar_ setUpdateDelegate:self];
9717 - (void) _sendMemoryWarningNotification {
9718 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9721 - (void) _sendMemoryWarningNotifications {
9723 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9728 - (void) applicationDidFinishLaunching:(id)unused {
9729 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9732 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9733 [self setApplicationSupportsShakeToEdit:NO];
9735 @synchronized (HostConfig_) {
9736 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9739 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9740 initWithMemoryCapacity:524288
9741 diskCapacity:10485760
9742 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9745 [CydiaWebViewController _initialize];
9747 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9749 // this would disallow http{,s} URLs from accessing this data
9750 //[WebView registerURLSchemeAsLocal:@"cydia"];
9752 Font12_ = [UIFont systemFontOfSize:12];
9753 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9754 Font14_ = [UIFont systemFontOfSize:14];
9755 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9756 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9758 essential_ = [NSMutableArray arrayWithCapacity:4];
9759 broken_ = [NSMutableArray arrayWithCapacity:4];
9761 // XXX: I really need this thing... like, seriously... I'm sorry
9762 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9764 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9765 [window_ orderFront:self];
9766 [window_ makeKey:self];
9767 [window_ setHidden:NO];
9770 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9771 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9772 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9773 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9774 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9775 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9776 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9777 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9778 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9781 [self addStashController];
9782 // XXX: this would be much cleaner as a yieldToSelector:
9783 // that way the removeStashController could happen right here inline
9784 // we also could no longer require the useless stash_ field anymore
9785 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9789 database_ = [Database sharedInstance];
9790 [database_ setDelegate:self];
9792 [window_ setUserInteractionEnabled:NO];
9793 [self setupViewControllers];
9795 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9796 [window_ addSubview:[emulated_ view]];
9798 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9802 - (NSArray *) defaultStartPages {
9803 NSMutableArray *standard = [NSMutableArray array];
9804 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9805 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9806 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9808 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9810 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9811 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9813 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9820 [window_ setUserInteractionEnabled:YES];
9821 [self showSettings];
9824 if ([emulated_ modalViewController] != nil)
9825 [emulated_ dismissModalViewControllerAnimated:YES];
9826 [window_ setUserInteractionEnabled:NO];
9829 [self reloadDataWithInvocation:nil];
9830 [self refreshIfPossible];
9835 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9836 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9837 int standardIndex = 0;
9838 NSArray *standard = [self defaultStartPages];
9845 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9846 if (valid && closed != nil) {
9847 NSTimeInterval interval([closed timeIntervalSinceNow]);
9848 // XXX: Is 60 minutes the optimal time here?
9849 if (interval <= -(60*60))
9853 if (valid && [saved count] != [standard count])
9857 for (unsigned int i = 0; i < [standard count]; i++) {
9858 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9859 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9860 // but it's good enough for now.
9861 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9868 NSArray *items = nil;
9870 [tabbar_ setSelectedIndex:savedIndex];
9873 [tabbar_ setSelectedIndex:standardIndex];
9877 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9878 NSArray *stack = [items objectAtIndex:tab];
9879 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9880 NSMutableArray *current = [NSMutableArray array];
9882 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9883 NSString *addr = [stack objectAtIndex:nav];
9884 NSURL *url = [NSURL URLWithString:addr];
9885 CyteViewController *page = [self pageForURL:url forExternal:NO];
9887 [current addObject:page];
9890 [navigation setViewControllers:current];
9893 // (Try to) show the startup URL.
9894 if (starturl_ != nil) {
9895 [self openCydiaURL:starturl_ forExternal:NO];
9900 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9901 if (item != nil && IsWildcat_) {
9902 [sheet showFromBarButtonItem:item animated:YES];
9904 [sheet showInView:window_];
9908 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9909 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9910 [progress setTitle:task];
9911 [progress addProgressEvent:event];
9914 - (void) addProgressEventForTask:(NSArray *)data {
9915 CydiaProgressEvent *event([data objectAtIndex:0]);
9916 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9917 [self addProgressEvent:event forTask:task];
9920 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9921 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9927 id Alloc_(id self, SEL selector) {
9928 id object = alloc_(self, selector);
9929 lprintf("[%s]A-%p\n", self->isa->name, object);
9934 id Dealloc_(id self, SEL selector) {
9935 id object = dealloc_(self, selector);
9936 lprintf("[%s]D-%p\n", self->isa->name, object);
9940 Class $WebDefaultUIKitDelegate;
9942 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9943 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9944 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9945 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9948 static NSSet *MobilizedFiles_;
9950 static NSURL *MobilizeURL(NSURL *url) {
9951 NSString *path([url path]);
9952 if ([path hasPrefix:@"/var/root/"]) {
9953 NSString *file([path substringFromIndex:10]);
9954 if ([MobilizedFiles_ containsObject:file])
9955 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9961 Class $CFXPreferencesPropertyListSource;
9962 @class CFXPreferencesPropertyListSource;
9964 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9965 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9966 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9967 url = MobilizeURL(url);
9968 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9969 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9975 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9976 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9977 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9978 url = MobilizeURL(url);
9979 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9980 //NSLog(@"%@ %@", [url absoluteString], value);
9986 Class $NSURLConnection;
9988 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9989 NSMutableURLRequest *copy([request mutableCopy]);
9991 NSURL *url([copy URL]);
9993 NSString *host([url host]);
9994 NSString *scheme([[url scheme] lowercaseString]);
9996 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9998 @synchronized (HostConfig_) {
9999 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10000 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10001 [copy setHTTPShouldUsePipelining:YES];
10003 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10004 if ([control isEqualToString:@"max-age=0"])
10005 if ([CachedURLs_ containsObject:url]) {
10007 NSLog(@"~~~: %@", url);
10010 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10012 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10013 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10014 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10018 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10022 int main(int argc, char *argv[]) {
10023 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10027 UpdateExternalStatus(0);
10029 if (Class $UIDevice = objc_getClass("UIDevice")) {
10030 UIDevice *device([$UIDevice currentDevice]);
10031 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10033 IsWildcat_ = false;
10035 UIScreen *screen([UIScreen mainScreen]);
10036 if ([screen respondsToSelector:@selector(scale)])
10037 ScreenScale_ = [screen scale];
10041 UIDevice *device([UIDevice currentDevice]);
10042 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10043 Idiom_ = @"iphone";
10045 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10046 if (idiom == UIUserInterfaceIdiomPhone)
10047 Idiom_ = @"iphone";
10048 else if (idiom == UIUserInterfaceIdiomPad)
10051 NSLog(@"unknown UIUserInterfaceIdiom!");
10054 Pcre pattern("^([0-9]+\\.[0-9]+)");
10056 if (pattern([device systemVersion]))
10057 Firmware_ = pattern[1];
10058 if (pattern(Cydia_))
10059 Major_ = pattern[1];
10061 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10063 HostConfig_ = [[[NSObject alloc] init] autorelease];
10064 @synchronized (HostConfig_) {
10065 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10066 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10067 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10068 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10069 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10072 NSString *ui(@"ui/ios");
10074 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10075 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10076 UI_ = CydiaURL(ui);
10078 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10080 MobilizedFiles_ = [NSMutableSet setWithObjects:
10081 @"Library/Preferences/com.apple.Accessibility.plist",
10082 @"Library/Preferences/com.apple.preferences.sounds.plist",
10085 /* Library Hacks {{{ */
10086 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10088 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10090 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10091 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10092 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10093 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10096 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10097 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10098 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10099 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10102 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10103 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10104 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10105 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10106 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10109 $NSURLConnection = objc_getClass("NSURLConnection");
10110 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10111 if (NSURLConnection$init$ != NULL) {
10112 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10113 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10116 /* Set Locale {{{ */
10117 Locale_ = CFLocaleCopyCurrent();
10118 Languages_ = [NSLocale preferredLanguages];
10120 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10121 //NSLog(@"%@", [Languages_ description]);
10124 if (Locale_ != NULL)
10125 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10126 else if (Languages_ != nil && [Languages_ count] != 0)
10127 lang = [[Languages_ objectAtIndex:0] UTF8String];
10129 // XXX: consider just setting to C and then falling through?
10132 if (lang != NULL) {
10133 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10134 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10137 NSLog(@"Setting Language: %s", lang);
10139 if (lang != NULL) {
10140 setenv("LANG", lang, true);
10141 std::setlocale(LC_ALL, lang);
10145 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10147 /* Parse Arguments {{{ */
10148 bool substrate(false);
10154 for (int argi(1); argi != argc; ++argi)
10155 if (strcmp(argv[argi], "--") == 0) {
10157 argv[argi] = argv[0];
10163 for (int argi(1); argi != arge; ++argi)
10164 if (strcmp(args[argi], "--substrate") == 0)
10167 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10171 App_ = [[NSBundle mainBundle] bundlePath];
10177 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10178 alloc_ = alloc->method_imp;
10179 alloc->method_imp = (IMP) &Alloc_;*/
10181 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10182 dealloc_ = dealloc->method_imp;
10183 dealloc->method_imp = (IMP) &Dealloc_;*/
10185 /* System Information {{{ */
10189 size = sizeof(maxproc);
10190 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10191 perror("sysctlbyname(\"kern.maxproc\", ?)");
10192 else if (maxproc < 64) {
10194 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10195 perror("sysctlbyname(\"kern.maxproc\", #)");
10198 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10199 char *osversion = new char[size];
10200 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10201 perror("sysctlbyname(\"kern.osversion\", ?)");
10203 System_ = [NSString stringWithUTF8String:osversion];
10205 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10206 char *machine = new char[size];
10207 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10208 perror("sysctlbyname(\"hw.machine\", ?)");
10210 Machine_ = machine;
10212 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10213 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10214 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10216 UniqueID_ = [device uniqueIdentifier];
10218 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10219 Product_ = [info objectForKey:@"SafariProductVersion"];
10220 Safari_ = [info objectForKey:@"CFBundleVersion"];
10223 /* Load Database {{{ */
10225 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10227 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10229 if (Metadata_ == NULL)
10230 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10232 Settings_ = [Metadata_ objectForKey:@"Settings"];
10234 Packages_ = [Metadata_ objectForKey:@"Packages"];
10236 Values_ = [Metadata_ objectForKey:@"Values"];
10237 Sections_ = [Metadata_ objectForKey:@"Sections"];
10238 Sources_ = [Metadata_ objectForKey:@"Sources"];
10240 Token_ = [Metadata_ objectForKey:@"Token"];
10242 Version_ = [Metadata_ objectForKey:@"Version"];
10245 if (Settings_ != nil)
10246 Role_ = [Settings_ objectForKey:@"Role"];
10248 if (Values_ == nil) {
10249 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10250 [Metadata_ setObject:Values_ forKey:@"Values"];
10253 if (Sections_ == nil) {
10254 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10255 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10258 if (Sources_ == nil) {
10259 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10260 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10263 if (Version_ == nil) {
10264 Version_ = [NSNumber numberWithUnsignedInt:0];
10265 [Metadata_ setObject:Version_ forKey:@"Version"];
10268 if ([Version_ unsignedIntValue] == 0) {
10269 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10270 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10271 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10272 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10274 Version_ = [NSNumber numberWithUnsignedInt:1];
10275 [Metadata_ setObject:Version_ forKey:@"Version"];
10277 [Metadata_ removeObjectForKey:@"LastUpdate"];
10283 CydiaWriteSources();
10286 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10289 if (Packages_ != nil) {
10291 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10295 [Metadata_ removeObjectForKey:@"Packages"];
10301 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10303 #define MobileSubstrate_(name) \
10304 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10305 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10306 if (handle == NULL) \
10307 NSLog(@"%s", dlerror()); \
10310 MobileSubstrate_(Activator)
10311 MobileSubstrate_(libstatusbar)
10312 MobileSubstrate_(SimulatedKeyEvents)
10313 MobileSubstrate_(WinterBoard)
10315 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10316 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10318 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10320 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10321 unlink("/tmp/.cydia.fw");
10323 } else if (access("/User", F_OK) != 0 || version < 4) {
10326 system("/usr/libexec/cydia/firmware.sh");
10330 _assert([[NSFileManager defaultManager]
10331 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10332 withIntermediateDirectories:YES
10337 if (access("/tmp/cydia.chk", F_OK) == 0) {
10338 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10339 _assert(errno == ENOENT);
10340 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10341 _assert(errno == ENOENT);
10344 /* APT Initialization {{{ */
10345 _assert(pkgInitConfig(*_config));
10346 _assert(pkgInitSystem(*_config, _system));
10349 _config->Set("APT::Acquire::Translation", lang);
10351 // XXX: this timeout might be important :(
10352 //_config->Set("Acquire::http::Timeout", 15);
10354 _config->Set("Acquire::http::MaxParallel", 3);
10356 /* Color Choices {{{ */
10357 space_ = CGColorSpaceCreateDeviceRGB();
10359 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10360 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10361 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10362 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10363 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10364 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10365 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10366 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10367 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10369 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10370 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10372 /* UIKit Configuration {{{ */
10373 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10374 if ($GSFontSetUseLegacyFontMetrics != NULL)
10375 $GSFontSetUseLegacyFontMetrics(YES);
10377 // XXX: I have a feeling this was important
10378 //UIKeyboardDisableAutomaticAppearance();
10381 Colon_ = UCLocalize("COLON_DELIMITED");
10382 Elision_ = UCLocalize("ELISION");
10383 Error_ = UCLocalize("ERROR");
10384 Warning_ = UCLocalize("WARNING");
10387 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10389 CGColorSpaceRelease(space_);
10390 CFRelease(Locale_);