1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
126 #include <CydiaSubstrate/CydiaSubstrate.h>
127 #include "Menes/Menes.h"
129 #include "CyteKit/PerlCompatibleRegEx.hpp"
130 #include "CyteKit/TableViewCell.h"
131 #include "CyteKit/WebScriptObject-Cyte.h"
132 #include "CyteKit/WebViewController.h"
133 #include "CyteKit/stringWithUTF8Bytes.h"
135 #include "Cydia/MIMEAddress.h"
136 #include "Cydia/LoadingViewController.h"
137 #include "Cydia/ProgressEvent.h"
139 #include "SDURLCache/SDURLCache.h"
146 #define _timestamp ({ \
148 gettimeofday(&tv, NULL); \
149 tv.tv_sec * 1000000 + tv.tv_usec; \
152 typedef std::vector<class ProfileTime *> TimeList;
162 ProfileTime(const char *name) :
166 times_.push_back(this);
169 void AddTime(uint64_t time) {
176 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
188 ProfileTimer(ProfileTime &time) :
195 time_.AddTime(_timestamp - start_);
200 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
202 std::cerr << "========" << std::endl;
205 #define _profile(name) { \
206 static ProfileTime name(#name); \
207 ProfileTimer _ ## name(name);
212 extern NSString *Cydia_;
214 #define lprintf(args...) fprintf(stderr, args)
217 #define TraceLogging (1 && !ForRelease)
218 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
219 #define ProfileTimes (0 && !ForRelease)
220 #define ForSaurik (0 && !ForRelease)
221 #define LogBrowser (0 && !ForRelease)
222 #define TrackResize (0 && !ForRelease)
223 #define ManualRefresh (1 && !ForRelease)
224 #define ShowInternals (0 && !ForRelease)
225 #define AlwaysReload (0 && !ForRelease)
226 #define TryIndexedCollation (0 && !ForRelease)
230 #define _trace(args...)
235 #define _profile(name) {
238 #define PrintTimes() do {} while (false)
241 // Hash Functions/Structures {{{
242 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
250 static NSString *Colon_;
252 static NSString *Error_;
253 static NSString *Warning_;
255 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
257 static _finline NSString *CydiaURL(NSString *path) {
259 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
260 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
261 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
262 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
263 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
265 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
268 static void ReapZombie(pid_t pid) {
271 if (waitpid(pid, &status, 0) == -1)
277 static _finline void UpdateExternalStatus(uint64_t newStatus) {
279 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
280 notify_set_state(notify_token, newStatus);
281 notify_cancel(notify_token);
283 notify_post("com.saurik.Cydia.status");
286 static CGFloat CYStatusBarHeight() {
287 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
288 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
291 /* NSForcedOrderingSearch doesn't work on the iPhone */
292 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
293 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
294 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
296 /* Insertion Sort {{{ */
298 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
299 const char *ptr = (const char *)list;
301 CFIndex half = count / 2;
302 const char *probe = ptr + elementSize * half;
303 CFComparisonResult cr = comparator(element, probe, context);
304 if (0 == cr) return (probe - (const char *)list) / elementSize;
305 ptr = (cr < 0) ? ptr : probe + elementSize;
306 count = (cr < 0) ? half : (half + (count & 1) - 1);
308 return (ptr - (const char *)list) / elementSize;
311 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
312 const char *ptr = (const char *)list;
314 CFIndex half = count / 2;
315 const char *probe = ptr + elementSize * half;
316 CFComparisonResult cr = comparator(element, probe, context);
317 if (0 == cr) return (probe - (const char *)list) / elementSize;
318 ptr = (cr < 0) ? ptr : probe + elementSize;
319 count = (cr < 0) ? half : (half + (count & 1) - 1);
321 return (ptr - (const char *)list) / elementSize;
324 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
325 if (range.length == 0)
327 const void **values(new const void *[range.length]);
328 CFArrayGetValues(array, range, values);
330 #if HistogramInsertionSort > 0
331 uint32_t total(0), *offsets(new uint32_t[range.length]);
334 for (CFIndex index(1); index != range.length; ++index) {
335 const void *value(values[index]);
336 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
337 CFIndex correct(index);
338 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
339 #if HistogramInsertionSort > 1
340 NSLog(@"%@ < %@", value, values[correct - 1]);
345 if (correct != index) {
346 size_t offset(index - correct);
347 #if HistogramInsertionSort
351 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
353 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
354 values[correct] = value;
358 CFArrayReplaceValues(array, range, values, range.length);
361 #if HistogramInsertionSort > 0
362 for (CFIndex index(0); index != range.length; ++index)
363 if (offsets[index] != 0)
364 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
365 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
372 /* Apple Bug Fixes {{{ */
373 @implementation UIWebDocumentView (Cydia)
375 - (void) _setScrollerOffset:(CGPoint)offset {
376 UIScroller *scroller([self _scroller]);
378 CGSize size([scroller contentSize]);
379 CGSize bounds([scroller bounds].size);
382 max.x = size.width - bounds.width;
383 max.y = size.height - bounds.height;
391 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
392 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
394 [scroller setOffset:offset];
400 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
401 size_t length([self length] - state->state);
404 else if (length > count)
406 for (size_t i(0); i != length; ++i)
407 objects[i] = [self item:state->state++];
408 state->itemsPtr = objects;
409 state->mutationsPtr = (unsigned long *) self;
413 /* Cydia NSString Additions {{{ */
414 @interface NSString (Cydia)
415 - (NSComparisonResult) compareByPath:(NSString *)other;
416 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
419 @implementation NSString (Cydia)
421 - (NSComparisonResult) compareByPath:(NSString *)other {
422 NSString *prefix = [self commonPrefixWithString:other options:0];
423 size_t length = [prefix length];
425 NSRange lrange = NSMakeRange(length, [self length] - length);
426 NSRange rrange = NSMakeRange(length, [other length] - length);
428 lrange = [self rangeOfString:@"/" options:0 range:lrange];
429 rrange = [other rangeOfString:@"/" options:0 range:rrange];
431 NSComparisonResult value;
433 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
434 value = NSOrderedSame;
435 else if (lrange.location == NSNotFound)
436 value = NSOrderedAscending;
437 else if (rrange.location == NSNotFound)
438 value = NSOrderedDescending;
440 value = NSOrderedSame;
442 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
443 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
444 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
445 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
447 NSComparisonResult result = [lpath compare:rpath];
448 return result == NSOrderedSame ? value : result;
451 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
452 return [(id)CFURLCreateStringByAddingPercentEscapes(
457 kCFStringEncodingUTF8
464 /* C++ NSString Wrapper Cache {{{ */
465 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
466 return size == 0 ? NULL :
467 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
468 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
471 static _finline CFStringRef CYStringCreate(const char *data) {
472 return CYStringCreate(data, strlen(data));
481 _finline void clear_() {
482 if (cache_ != NULL) {
489 _finline bool empty() const {
493 _finline size_t size() const {
497 _finline char *data() const {
501 _finline void clear() {
506 _finline CYString() :
513 _finline ~CYString() {
517 void operator =(const CYString &rhs) {
521 if (rhs.cache_ == nil)
524 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
527 void copy(apr_pool_t *pool) {
528 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
529 memcpy(temp, data_, size_);
534 void set(apr_pool_t *pool, const char *data, size_t size) {
540 data_ = const_cast<char *>(data);
548 _finline void set(apr_pool_t *pool, const char *data) {
549 set(pool, data, data == NULL ? 0 : strlen(data));
552 _finline void set(apr_pool_t *pool, const std::string &rhs) {
553 set(pool, rhs.data(), rhs.size());
556 bool operator ==(const CYString &rhs) const {
557 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
560 _finline operator CFStringRef() {
562 cache_ = CYStringCreate(data_, size_);
566 _finline operator id() {
567 return (NSString *) static_cast<CFStringRef>(*this);
570 _finline operator const char *() {
571 return reinterpret_cast<const char *>(data_);
575 /* C++ NSString Algorithm Adapters {{{ */
577 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
580 struct NSStringMapHash :
581 std::unary_function<NSString *, size_t>
583 _finline size_t operator ()(NSString *value) const {
584 return CFStringHashNSString((CFStringRef) value);
588 struct NSStringMapLess :
589 std::binary_function<NSString *, NSString *, bool>
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return [lhs compare:rhs] == NSOrderedAscending;
596 struct NSStringMapEqual :
597 std::binary_function<NSString *, NSString *, bool>
599 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
600 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
601 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
602 //[lhs isEqualToString:rhs];
607 /* CoreGraphics Primitives {{{ */
612 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
613 CGFloat color[] = {red, green, blue, alpha};
614 return CGColorCreate(space, color);
623 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
624 color_(Create_(space, red, green, blue, alpha))
626 Set(space, red, green, blue, alpha);
631 CGColorRelease(color_);
638 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
640 color_ = Create_(space, red, green, blue, alpha);
643 operator CGColorRef() {
649 /* Random Global Variables {{{ */
650 static const int PulseInterval_ = 50000;
652 static const NSString *UI_;
655 static bool RestartSubstrate_;
656 static NSArray *Finishes_;
658 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
659 #define NotifyConfig_ "/etc/notify.conf"
661 static bool Queuing_;
663 static CYColor Blue_;
664 static CYColor Blueish_;
665 static CYColor Black_;
667 static CYColor White_;
668 static CYColor Gray_;
669 static CYColor Green_;
670 static CYColor Purple_;
671 static CYColor Purplish_;
673 static UIColor *InstallingColor_;
674 static UIColor *RemovingColor_;
676 static NSString *App_;
678 static BOOL Advanced_;
679 static BOOL Ignored_;
681 static _H<UIFont> Font12_;
682 static _H<UIFont> Font12Bold_;
683 static _H<UIFont> Font14_;
684 static _H<UIFont> Font18Bold_;
685 static _H<UIFont> Font22Bold_;
687 static const char *Machine_ = NULL;
688 static _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 _H<NSString> UserAgent_;
695 static _H<NSString> Product_;
696 static _H<NSString> Safari_;
698 static CFLocaleRef Locale_;
699 static NSArray *Languages_;
700 static CGColorSpaceRef space_;
702 static NSDictionary *SectionMap_;
703 static NSMutableDictionary *Metadata_;
704 static _transient NSMutableDictionary *Settings_;
705 static _transient NSString *Role_;
706 static _transient NSMutableDictionary *Packages_;
707 static _transient NSMutableDictionary *Values_;
708 static _transient NSMutableDictionary *Sections_;
709 _H<NSMutableDictionary> Sources_;
710 static _transient NSNumber *Version_;
715 static CGFloat ScreenScale_;
716 static NSString *Idiom_;
717 static _H<NSString> Firmware_;
718 static NSString *Major_;
720 static _H<NSMutableDictionary> SessionData_;
721 static _H<NSObject> HostConfig_;
722 static _H<NSMutableSet> BridgedHosts_;
723 static _H<NSMutableSet> TokenHosts_;
724 static _H<NSMutableSet> InsecureHosts_;
725 static _H<NSMutableSet> PipelinedHosts_;
726 static _H<NSMutableSet> CachedURLs_;
728 static NSString *kCydiaProgressEventTypeError = @"Error";
729 static NSString *kCydiaProgressEventTypeInformation = @"Information";
730 static NSString *kCydiaProgressEventTypeStatus = @"Status";
731 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
734 /* Display Helpers {{{ */
735 inline float Interpolate(float begin, float end, float fraction) {
736 return (end - begin) * fraction + begin;
739 static _finline const char *StripVersion_(const char *version) {
740 const char *colon(strchr(version, ':'));
741 return colon == NULL ? version : colon + 1;
744 NSString *LocalizeSection(NSString *section) {
745 static Pcre title_r("^(.*?) \\((.*)\\)$");
746 if (title_r(section)) {
747 NSString *parent(title_r[1]);
748 NSString *child(title_r[2]);
750 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
751 LocalizeSection(parent),
752 LocalizeSection(child)
756 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
759 NSString *Simplify(NSString *title) {
760 const char *data = [title UTF8String];
761 size_t size = [title length];
763 static Pcre square_r("^\\[(.*)\\]$");
764 if (square_r(data, size))
765 return Simplify(square_r[1]);
767 static Pcre paren_r("^\\((.*)\\)$");
768 if (paren_r(data, size))
769 return Simplify(paren_r[1]);
771 static Pcre title_r("^(.*?) \\((.*)\\)$");
772 if (title_r(data, size))
773 return Simplify(title_r[1]);
779 NSString *GetLastUpdate() {
780 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
783 return UCLocalize("NEVER_OR_UNKNOWN");
785 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
786 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
788 CFRelease(formatter);
790 return [(NSString *) formatted autorelease];
793 bool isSectionVisible(NSString *section) {
794 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
795 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
796 return hidden == nil || ![hidden boolValue];
799 static NSObject *CYIOGetValue(const char *path, NSString *property) {
800 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
801 if (entry == MACH_PORT_NULL)
804 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
805 IOObjectRelease(entry);
809 return [(id) value autorelease];
812 static NSString *CYHex(NSData *data, bool reverse = false) {
816 size_t length([data length]);
817 uint8_t bytes[length];
818 [data getBytes:bytes];
820 char string[length * 2 + 1];
821 for (size_t i(0); i != length; ++i)
822 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
824 return [NSString stringWithUTF8String:string];
829 /* Delegate Prototypes {{{ */
832 @class CydiaProgressEvent;
834 @protocol DatabaseDelegate
835 - (void) repairWithSelector:(SEL)selector;
836 - (void) setConfigurationData:(NSString *)data;
837 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
840 @class CYPackageController;
842 @protocol CydiaDelegate
843 - (void) returnToCydia;
845 - (void) retainNetworkActivityIndicator;
846 - (void) releaseNetworkActivityIndicator;
847 - (void) clearPackage:(Package *)package;
848 - (void) installPackage:(Package *)package;
849 - (void) installPackages:(NSArray *)packages;
850 - (void) removePackage:(Package *)package;
851 - (void) beginUpdate;
853 - (void) distUpgrade;
857 - (void) addSource:(NSDictionary *)source;
858 - (void) addTrivialSource:(NSString *)href;
859 - (void) showSettings;
860 - (UIProgressHUD *) addProgressHUD;
861 - (void) removeProgressHUD:(UIProgressHUD *)hud;
862 - (CyteViewController *) pageForPackage:(NSString *)name;
863 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
864 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
868 /* Status Delegation {{{ */
870 public pkgAcquireStatus
873 _transient NSObject<ProgressDelegate> *delegate_;
883 void setDelegate(NSObject<ProgressDelegate> *delegate) {
884 delegate_ = delegate;
887 NSObject<ProgressDelegate> *getDelegate() const {
891 virtual bool MediaChange(std::string media, std::string drive) {
895 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
899 virtual void Fetch(pkgAcquire::ItemDesc &item) {
900 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
901 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
902 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
905 virtual void Done(pkgAcquire::ItemDesc &item) {
906 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
907 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
908 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
911 virtual void Fail(pkgAcquire::ItemDesc &item) {
913 item.Owner->Status == pkgAcquire::Item::StatIdle ||
914 item.Owner->Status == pkgAcquire::Item::StatDone
918 std::string &error(item.Owner->ErrorText);
922 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
923 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
926 virtual bool Pulse(pkgAcquire *Owner) {
927 bool value = pkgAcquireStatus::Pulse(Owner);
930 double(CurrentBytes + CurrentItems) /
931 double(TotalBytes + TotalItems)
934 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
935 [NSNumber numberWithDouble:percent], @"Percent",
937 [NSNumber numberWithDouble:CurrentBytes], @"Current",
938 [NSNumber numberWithDouble:TotalBytes], @"Total",
939 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
940 nil] waitUntilDone:YES];
942 if (value && ![delegate_ isProgressCancelled])
950 _finline bool WasCancelled() const {
954 virtual void Start() {
955 pkgAcquireStatus::Start();
956 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
959 virtual void Stop() {
960 pkgAcquireStatus::Stop();
961 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
962 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
966 /* Database Interface {{{ */
967 typedef std::map< unsigned long, _H<Source> > SourceMap;
969 @interface Database : NSObject {
976 pkgDepCache::Policy *policy_;
977 pkgRecords *records_;
978 pkgProblemResolver *resolver_;
979 pkgAcquire *fetcher_;
981 SPtr<pkgPackageManager> manager_;
982 pkgSourceList *list_;
984 SourceMap sourceMap_;
985 _H<NSMutableArray> sourceList_;
987 CFMutableArrayRef packages_;
989 _transient NSObject<DatabaseDelegate> *delegate_;
990 _transient NSObject<ProgressDelegate> *progress_;
998 std::map<const char *, _H<NSString> > sections_;
1001 + (Database *) sharedInstance;
1004 - (void) _readCydia:(NSNumber *)fd;
1005 - (void) _readStatus:(NSNumber *)fd;
1006 - (void) _readOutput:(NSNumber *)fd;
1010 - (Package *) packageWithName:(NSString *)name;
1012 - (pkgCacheFile &) cache;
1013 - (pkgDepCache::Policy *) policy;
1014 - (pkgRecords *) records;
1015 - (pkgProblemResolver *) resolver;
1016 - (pkgAcquire &) fetcher;
1017 - (pkgSourceList &) list;
1018 - (NSArray *) packages;
1019 - (NSArray *) sources;
1020 - (Source *) sourceWithKey:(NSString *)key;
1021 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1029 - (void) updateWithStatus:(Status &)status;
1031 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1033 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1034 - (NSObject<ProgressDelegate> *) progressDelegate;
1036 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1038 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1042 /* ProgressEvent Implementation {{{ */
1043 @implementation CydiaProgressEvent
1045 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1046 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1049 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1050 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1051 [event setPackage:package];
1055 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1056 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1058 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1059 NSArray *fields([description componentsSeparatedByString:@" "]);
1060 [event setItem:fields];
1062 if ([fields count] > 3) {
1063 [event setPackage:[fields objectAtIndex:2]];
1064 [event setVersion:[fields objectAtIndex:3]];
1067 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1072 + (NSArray *) _attributeKeys {
1073 return [NSArray arrayWithObjects:
1083 - (NSArray *) attributeKeys {
1084 return [[self class] _attributeKeys];
1087 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1088 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1091 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1092 if ((self = [super init]) != nil) {
1098 - (NSString *) message {
1102 - (NSString *) type {
1106 - (NSArray *) item {
1107 return (id) item_ ?: [NSNull null];
1110 - (void) setItem:(NSArray *)item {
1114 - (NSString *) package {
1115 return (id) package_ ?: [NSNull null];
1118 - (void) setPackage:(NSString *)package {
1122 - (NSString *) url {
1123 return (id) url_ ?: [NSNull null];
1126 - (void) setURL:(NSString *)url {
1130 - (void) setVersion:(NSString *)version {
1134 - (NSString *) version {
1135 return (id) version_ ?: [NSNull null];
1138 - (NSString *) compound:(NSString *)value {
1140 NSString *mode(nil); {
1141 NSString *type([self type]);
1142 if ([type isEqualToString:kCydiaProgressEventTypeError])
1143 mode = UCLocalize("ERROR");
1144 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1145 mode = UCLocalize("WARNING");
1149 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1155 - (NSString *) compoundMessage {
1156 return [self compound:[self message]];
1159 - (NSString *) compoundTitle {
1162 if (package_ == nil)
1164 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1165 title = [package name];
1169 return [self compound:title];
1175 // Cytore Definitions {{{
1176 struct PackageValue :
1179 Cytore::Offset<PackageValue> next_;
1181 uint32_t index_ : 23;
1182 uint32_t subscribed_ : 1;
1199 Cytore::Offset<PackageValue> packages_[1 << 16];
1202 static Cytore::File<MetaValue> MetaFile_;
1204 // Cytore Helper Functions {{{
1205 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1206 SplitHash nhash = { hashlittle(name, length) };
1208 PackageValue *metadata;
1210 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1211 offset: if (offset->IsNull()) {
1212 *offset = MetaFile_.New<PackageValue>(length + 1);
1213 metadata = &MetaFile_.Get(*offset);
1215 if (metadata == NULL) {
1219 metadata = new PackageValue();
1220 memset(metadata, 0, sizeof(*metadata));
1223 memcpy(metadata->name_, name, length + 1);
1224 metadata->nhash_ = nhash.u16[1];
1226 metadata = &MetaFile_.Get(*offset);
1228 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1229 offset = &metadata->next_;
1237 static void PackageImport(const void *key, const void *value, void *context) {
1238 bool &fail(*reinterpret_cast<bool *>(context));
1241 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1242 NSLog(@"failed to import package %@", key);
1246 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1247 NSDictionary *package((NSDictionary *) value);
1249 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1250 if ([subscribed boolValue] && !metadata->subscribed_)
1251 metadata->subscribed_ = true;
1253 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1254 time_t time([date timeIntervalSince1970]);
1255 if (metadata->first_ > time || metadata->first_ == 0)
1256 metadata->first_ = time;
1259 NSDate *date([package objectForKey:@"LastSeen"]);
1260 NSString *version([package objectForKey:@"LastVersion"]);
1262 if (date != nil && version != nil) {
1263 time_t time([date timeIntervalSince1970]);
1264 if (metadata->last_ < time || metadata->last_ == 0)
1265 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1266 size_t length(strlen(buffer));
1267 uint16_t vhash(hashlittle(buffer, length));
1269 size_t capped(std::min<size_t>(8, length));
1270 char *latest(buffer + length - capped);
1272 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1273 metadata->vhash_ = vhash;
1275 metadata->last_ = time;
1281 /* Source Class {{{ */
1282 @interface Source : NSObject {
1284 Database *database_;
1287 CYString depiction_;
1288 CYString description_;
1294 CYString distribution_;
1300 _H<NSString> authority_;
1302 CYString defaultIcon_;
1304 _H<NSDictionary> record_;
1308 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1310 - (NSComparisonResult) compareByName:(Source *)source;
1312 - (NSString *) depictionForPackage:(NSString *)package;
1313 - (NSString *) supportForPackage:(NSString *)package;
1315 - (NSDictionary *) record;
1318 - (NSString *) rooturi;
1319 - (NSString *) distribution;
1320 - (NSString *) type;
1323 - (NSString *) host;
1325 - (NSString *) name;
1326 - (NSString *) shortDescription;
1327 - (NSString *) label;
1328 - (NSString *) origin;
1329 - (NSString *) version;
1331 - (NSString *) defaultIcon;
1332 - (NSURL *) iconURL;
1336 @implementation Source
1340 distribution_.clear();
1345 description_.clear();
1351 defaultIcon_.clear();
1358 + (NSString *) webScriptNameForSelector:(SEL)selector {
1360 else if (selector == @selector(addSection:))
1361 return @"addSection";
1362 else if (selector == @selector(getField:))
1364 else if (selector == @selector(removeSection:))
1365 return @"removeSection";
1366 else if (selector == @selector(remove))
1372 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1373 return [self webScriptNameForSelector:selector] == nil;
1376 + (NSArray *) _attributeKeys {
1377 return [NSArray arrayWithObjects:
1388 @"shortDescription",
1395 - (NSArray *) attributeKeys {
1396 return [[self class] _attributeKeys];
1399 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1400 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1403 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1406 trusted_ = index->IsTrusted();
1408 uri_.set(pool, index->GetURI());
1409 distribution_.set(pool, index->GetDist());
1410 type_.set(pool, index->GetType());
1412 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1413 if (dindex != NULL) {
1414 base_.set(pool, dindex->MetaIndexURI(""));
1417 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1420 pkgTagFile tags(&fd);
1422 pkgTagSection section;
1429 {"default-icon", &defaultIcon_},
1430 {"depiction", &depiction_},
1431 {"description", &description_},
1433 {"origin", &origin_},
1434 {"support", &support_},
1435 {"version", &version_},
1438 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1439 const char *start, *end;
1441 if (section.Find(names[i].name_, start, end)) {
1442 CYString &value(*names[i].value_);
1443 value.set(pool, start, end - start);
1449 record_ = [Sources_ objectForKey:[self key]];
1451 NSURL *url([NSURL URLWithString:uri_]);
1455 host_ = [host_ lowercaseString];
1460 authority_ = [url path];
1463 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1464 if ((self = [super init]) != nil) {
1465 era_ = [database era];
1466 database_ = database;
1469 [self setMetaIndex:index inPool:pool];
1473 - (NSString *) getField:(NSString *)name {
1474 @synchronized (database_) {
1475 if ([database_ era] != era_ || index_ == NULL)
1478 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1483 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1488 pkgTagFile tags(&fd);
1490 pkgTagSection section;
1493 const char *start, *end;
1494 if (!section.Find([name UTF8String], start, end))
1495 return (NSString *) [NSNull null];
1497 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1500 - (NSComparisonResult) compareByName:(Source *)source {
1501 NSString *lhs = [self name];
1502 NSString *rhs = [source name];
1504 if ([lhs length] != 0 && [rhs length] != 0) {
1505 unichar lhc = [lhs characterAtIndex:0];
1506 unichar rhc = [rhs characterAtIndex:0];
1508 if (isalpha(lhc) && !isalpha(rhc))
1509 return NSOrderedAscending;
1510 else if (!isalpha(lhc) && isalpha(rhc))
1511 return NSOrderedDescending;
1514 return [lhs compare:rhs options:LaxCompareOptions_];
1517 - (NSString *) depictionForPackage:(NSString *)package {
1518 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1521 - (NSString *) supportForPackage:(NSString *)package {
1522 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1525 - (NSArray *) sections {
1526 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1529 - (void) _addSection:(NSString *)section {
1532 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1533 if (![sections containsObject:section]) {
1534 [sections addObject:section];
1538 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1543 - (bool) addSection:(NSString *)section {
1547 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1551 - (void) _removeSection:(NSString *)section {
1555 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1556 if ([sections containsObject:section]) {
1557 [sections removeObject:section];
1562 - (bool) removeSection:(NSString *)section {
1566 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1571 [Sources_ removeObjectForKey:[self key]];
1576 bool value(record_ != nil);
1577 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1581 - (NSDictionary *) record {
1589 - (NSString *) rooturi {
1593 - (NSString *) distribution {
1594 return distribution_;
1597 - (NSString *) type {
1601 - (NSString *) baseuri {
1602 return base_.empty() ? nil : (id) base_;
1605 - (NSString *) iconuri {
1606 if (NSString *base = [self baseuri])
1607 return [base stringByAppendingString:@"CydiaIcon.png"];
1612 - (NSURL *) iconURL {
1613 if (NSString *uri = [self iconuri])
1614 return [NSURL URLWithString:uri];
1618 - (NSString *) key {
1619 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1622 - (NSString *) host {
1626 - (NSString *) name {
1627 return origin_.empty() ? (id) authority_ : origin_;
1630 - (NSString *) shortDescription {
1631 return description_;
1634 - (NSString *) label {
1635 return label_.empty() ? (id) authority_ : label_;
1638 - (NSString *) origin {
1642 - (NSString *) version {
1646 - (NSString *) defaultIcon {
1647 return defaultIcon_;
1652 /* CydiaOperation Class {{{ */
1653 @interface CydiaOperation : NSObject {
1654 _H<NSString> operator_;
1655 _H<NSString> value_;
1658 - (NSString *) operator;
1659 - (NSString *) value;
1663 @implementation CydiaOperation
1665 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1666 if ((self = [super init]) != nil) {
1667 operator_ = [NSString stringWithUTF8String:_operator];
1668 value_ = [NSString stringWithUTF8String:value];
1672 + (NSArray *) _attributeKeys {
1673 return [NSArray arrayWithObjects:
1679 - (NSArray *) attributeKeys {
1680 return [[self class] _attributeKeys];
1683 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1684 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1687 - (NSString *) operator {
1691 - (NSString *) value {
1697 /* CydiaClause Class {{{ */
1698 @interface CydiaClause : NSObject {
1699 _H<NSString> package_;
1700 _H<CydiaOperation> version_;
1703 - (NSString *) package;
1704 - (CydiaOperation *) version;
1708 @implementation CydiaClause
1710 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1711 if ((self = [super init]) != nil) {
1712 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1714 if (const char *version = dep.TargetVer())
1715 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1717 version_ = (id) [NSNull null];
1721 + (NSArray *) _attributeKeys {
1722 return [NSArray arrayWithObjects:
1728 - (NSArray *) attributeKeys {
1729 return [[self class] _attributeKeys];
1732 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1733 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1736 - (NSString *) package {
1740 - (CydiaOperation *) version {
1746 /* CydiaRelation Class {{{ */
1747 @interface CydiaRelation : NSObject {
1748 _H<NSString> relationship_;
1749 _H<NSMutableArray> clauses_;
1752 - (NSString *) relationship;
1753 - (NSArray *) clauses;
1757 @implementation CydiaRelation
1759 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1760 if ((self = [super init]) != nil) {
1761 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1762 clauses_ = [NSMutableArray arrayWithCapacity:8];
1764 pkgCache::DepIterator start;
1765 pkgCache::DepIterator end;
1766 dep.GlobOr(start, end); // ++dep
1769 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1771 // yes, seriously. (wtf?)
1779 + (NSArray *) _attributeKeys {
1780 return [NSArray arrayWithObjects:
1786 - (NSArray *) attributeKeys {
1787 return [[self class] _attributeKeys];
1790 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1791 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1794 - (NSString *) relationship {
1795 return relationship_;
1798 - (NSArray *) clauses {
1802 - (void) addClause:(CydiaClause *)clause {
1803 [clauses_ addObject:clause];
1808 /* Package Class {{{ */
1809 struct ParsedPackage {
1813 CYString architecture_;
1816 CYString depiction_;
1826 @interface Package : NSObject {
1829 uint32_t essential_ : 1;
1830 uint32_t obsolete_ : 1;
1831 uint32_t ignored_ : 1;
1832 uint32_t pooled_ : 1;
1838 _transient Database *database_;
1840 pkgCache::VerIterator version_;
1841 pkgCache::PkgIterator iterator_;
1842 pkgCache::VerFileIterator file_;
1848 CYString installed_;
1850 const char *section_;
1851 _transient NSString *section$_;
1855 PackageValue *metadata_;
1856 ParsedPackage *parsed_;
1858 _H<NSMutableArray> tags_;
1861 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1862 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1864 - (pkgCache::PkgIterator) iterator;
1867 - (NSString *) section;
1868 - (NSString *) simpleSection;
1870 - (NSString *) longSection;
1871 - (NSString *) shortSection;
1875 - (MIMEAddress *) maintainer;
1877 - (NSString *) longDescription;
1878 - (NSString *) shortDescription;
1881 - (PackageValue *) metadata;
1884 - (bool) subscribed;
1885 - (bool) setSubscribed:(bool)subscribed;
1889 - (NSString *) latest;
1890 - (NSString *) installed;
1891 - (BOOL) uninstalled;
1894 - (BOOL) upgradableAndEssential:(BOOL)essential;
1897 - (BOOL) unfiltered;
1901 - (BOOL) halfConfigured;
1902 - (BOOL) halfInstalled;
1904 - (NSString *) mode;
1907 - (NSString *) name;
1909 - (NSString *) homepage;
1910 - (NSString *) depiction;
1911 - (MIMEAddress *) author;
1913 - (NSString *) support;
1915 - (NSArray *) files;
1916 - (NSArray *) warnings;
1917 - (NSArray *) applications;
1919 - (Source *) source;
1922 - (BOOL) matches:(NSArray *)query;
1924 - (bool) hasSupportingRole;
1925 - (BOOL) hasTag:(NSString *)tag;
1926 - (NSString *) primaryPurpose;
1927 - (NSArray *) purposes;
1928 - (bool) isCommercial;
1930 - (void) setIndex:(size_t)index;
1932 - (CYString &) cyname;
1934 - (uint32_t) compareBySection:(NSArray *)sections;
1939 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1940 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1941 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1942 - (bool) isVisibleInSection:(NSString *)section;
1943 - (bool) isVisibleInSource:(Source *)source;
1947 uint32_t PackageChangesRadix(Package *self, void *) {
1952 uint32_t timestamp : 30;
1953 uint32_t ignored : 1;
1954 uint32_t upgradable : 1;
1958 bool upgradable([self upgradableAndEssential:YES]);
1959 value.bits.upgradable = upgradable ? 1 : 0;
1962 value.bits.timestamp = 0;
1963 value.bits.ignored = [self ignored] ? 0 : 1;
1964 value.bits.upgradable = 1;
1966 value.bits.timestamp = [self seen] >> 2;
1967 value.bits.ignored = 0;
1968 value.bits.upgradable = 0;
1971 return _not(uint32_t) - value.key;
1974 uint32_t PackagePrefixRadix(Package *self, void *context) {
1975 size_t offset(reinterpret_cast<size_t>(context));
1976 CYString &name([self cyname]);
1978 size_t size(name.size());
1981 char *text(name.data());
1984 if (!isdigit(text[0]))
1988 while (size != digits && isdigit(text[digits]))
1996 if (offset == 0 && zeros != 0) {
1997 memset(data, '0', zeros);
1998 memcpy(data + zeros, text, 4 - zeros);
2000 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2001 if (size <= offset - zeros)
2004 text += offset - zeros;
2005 size -= offset - zeros;
2008 memcpy(data, text, 4);
2010 memcpy(data, text, size);
2011 memset(data + size, 0, 4 - size);
2014 for (size_t i(0); i != 4; ++i)
2015 if (isalpha(data[i]))
2023 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2025 /* XXX: ntohl may be more honest */
2026 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2029 CYString &(*PackageName)(Package *self, SEL sel);
2031 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2032 _profile(PackageNameCompare)
2033 CYString &lhi(PackageName(lhs, @selector(cyname)));
2034 CYString &rhi(PackageName(rhs, @selector(cyname)));
2035 CFStringRef lhn(lhi), rhn(rhi);
2038 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2039 else if (rhn == NULL)
2040 return NSOrderedDescending;
2042 _profile(PackageNameCompare$NumbersLast)
2043 if (!lhi.empty() && !rhi.empty()) {
2044 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2045 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2046 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2047 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2048 return lha ? NSOrderedAscending : NSOrderedDescending;
2052 CFIndex length = CFStringGetLength(lhn);
2054 _profile(PackageNameCompare$Compare)
2055 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2060 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2061 return PackageNameCompare(*lhs, *rhs, context);
2064 struct PackageNameOrdering :
2065 std::binary_function<Package *, Package *, bool>
2067 _finline bool operator ()(Package *lhs, Package *rhs) const {
2068 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2072 @implementation Package
2074 - (NSString *) description {
2075 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2080 apr_pool_destroy(pool_);
2081 if (parsed_ != NULL)
2086 + (NSString *) webScriptNameForSelector:(SEL)selector {
2088 else if (selector == @selector(clear))
2090 else if (selector == @selector(getField:))
2092 else if (selector == @selector(hasTag:))
2094 else if (selector == @selector(install))
2096 else if (selector == @selector(remove))
2102 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2103 return [self webScriptNameForSelector:selector] == nil;
2106 + (NSArray *) _attributeKeys {
2107 return [NSArray arrayWithObjects:
2128 @"shortDescription",
2141 - (NSArray *) attributeKeys {
2142 return [[self class] _attributeKeys];
2145 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2146 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2149 - (NSArray *) relations {
2150 @synchronized (database_) {
2151 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2152 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2153 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2157 - (NSString *) architecture {
2159 @synchronized (database_) {
2160 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2163 - (NSString *) getField:(NSString *)name {
2164 @synchronized (database_) {
2165 if ([database_ era] != era_ || file_.end())
2168 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2170 const char *start, *end;
2171 if (!parser.Find([name UTF8String], start, end))
2172 return (NSString *) [NSNull null];
2174 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2178 if (parsed_ != NULL)
2180 @synchronized (database_) {
2181 if ([database_ era] != era_ || file_.end())
2184 ParsedPackage *parsed(new ParsedPackage);
2187 _profile(Package$parse)
2188 pkgRecords::Parser *parser;
2190 _profile(Package$parse$Lookup)
2191 parser = &[database_ records]->Lookup(file_);
2196 _profile(Package$parse$Find)
2201 {"architecture", &parsed->architecture_},
2202 {"icon", &parsed->icon_},
2203 {"depiction", &parsed->depiction_},
2204 {"homepage", &parsed->homepage_},
2205 {"website", &website},
2206 {"bugs", &parsed->bugs_},
2207 {"support", &parsed->support_},
2208 {"sponsor", &parsed->sponsor_},
2209 {"author", &parsed->author_},
2210 {"md5sum", &parsed->md5sum_},
2213 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2214 const char *start, *end;
2216 if (parser->Find(names[i].name_, start, end)) {
2217 CYString &value(*names[i].value_);
2218 _profile(Package$parse$Value)
2219 value.set(pool_, start, end - start);
2225 _profile(Package$parse$Tagline)
2226 const char *start, *end;
2227 if (parser->ShortDesc(start, end)) {
2228 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2231 while (stop != start && stop[-1] == '\r')
2233 parsed->tagline_.set(pool_, start, stop - start);
2237 _profile(Package$parse$Retain)
2238 if (parsed->homepage_.empty())
2239 parsed->homepage_ = website;
2240 if (parsed->homepage_ == parsed->depiction_)
2241 parsed->homepage_.clear();
2246 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2247 if ((self = [super init]) != nil) {
2248 _profile(Package$initWithVersion)
2250 apr_pool_create(&pool_, NULL);
2256 database_ = database;
2257 era_ = [database era];
2261 pkgCache::PkgIterator iterator(version.ParentPkg());
2262 iterator_ = iterator;
2264 _profile(Package$initWithVersion$Version)
2265 if (!version_.end())
2266 file_ = version_.FileList();
2268 pkgCache &cache([database_ cache]);
2269 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2273 _profile(Package$initWithVersion$Cache)
2274 name_.set(NULL, iterator.Display());
2276 latest_.set(NULL, StripVersion_(version_.VerStr()));
2278 pkgCache::VerIterator current(iterator.CurrentVer());
2280 installed_.set(NULL, StripVersion_(current.VerStr()));
2283 _profile(Package$initWithVersion$Tags)
2284 pkgCache::TagIterator tag(iterator.TagList());
2286 tags_ = [NSMutableArray arrayWithCapacity:8];
2288 const char *name(tag.Name());
2289 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2291 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2292 if (strcmp(name + 6, "enduser") == 0)
2294 else if (strcmp(name + 6, "hacker") == 0)
2296 else if (strcmp(name + 6, "developer") == 0)
2298 else if (strcmp(name + 6, "cydia") == 0)
2304 if (strncmp(name, "cydia::", 7) == 0) {
2305 if (strcmp(name + 7, "essential") == 0)
2307 else if (strcmp(name + 7, "obsolete") == 0)
2312 } while (!tag.end());
2316 _profile(Package$initWithVersion$Metadata)
2317 const char *mixed(iterator.Name());
2318 size_t size(strlen(mixed));
2319 char lower[size + 1];
2321 for (size_t i(0); i != size; ++i)
2322 lower[i] = mixed[i] | 0x20;
2325 PackageValue *metadata(PackageFind(lower, size));
2326 metadata_ = metadata;
2328 id_.set(NULL, metadata->name_, size);
2330 const char *latest(version_.VerStr());
2331 size_t length(strlen(latest));
2333 uint16_t vhash(hashlittle(latest, length));
2335 size_t capped(std::min<size_t>(8, length));
2336 latest = latest + length - capped;
2338 if (metadata->first_ == 0)
2339 metadata->first_ = now_;
2341 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2342 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2343 metadata->vhash_ = vhash;
2344 metadata->last_ = now_;
2345 } else if (metadata->last_ == 0)
2346 metadata->last_ = metadata->first_;
2349 _profile(Package$initWithVersion$Section)
2350 section_ = iterator.Section();
2353 _profile(Package$initWithVersion$Flags)
2354 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2355 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2360 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2361 pkgCache::VerIterator version;
2363 _profile(Package$packageWithIterator$GetCandidateVer)
2364 version = [database policy]->GetCandidateVer(iterator);
2372 _profile(Package$packageWithIterator$Allocate)
2373 package = [Package allocWithZone:zone];
2376 _profile(Package$packageWithIterator$Initialize)
2378 initWithVersion:version
2385 _profile(Package$packageWithIterator$Autorelease)
2386 package = [package autorelease];
2392 - (pkgCache::PkgIterator) iterator {
2396 - (NSString *) section {
2397 if (section$_ == nil) {
2398 if (section_ == NULL)
2401 _profile(Package$section$mappedSectionForPointer)
2402 section$_ = [database_ mappedSectionForPointer:section_];
2407 - (NSString *) simpleSection {
2408 if (NSString *section = [self section])
2409 return Simplify(section);
2414 - (NSString *) longSection {
2415 return LocalizeSection([self section]);
2418 - (NSString *) shortSection {
2419 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2422 - (NSString *) uri {
2425 pkgIndexFile *index;
2426 pkgCache::PkgFileIterator file(file_.File());
2427 if (![database_ list].FindIndex(file, index))
2429 return [NSString stringWithUTF8String:iterator_->Path];
2430 //return [NSString stringWithUTF8String:file.Site()];
2431 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2435 - (MIMEAddress *) maintainer {
2436 @synchronized (database_) {
2437 if ([database_ era] != era_ || file_.end())
2440 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2441 const std::string &maintainer(parser->Maintainer());
2442 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2445 - (NSString *) md5sum {
2446 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2450 @synchronized (database_) {
2451 if ([database_ era] != era_ || version_.end())
2454 return version_->InstalledSize;
2457 - (NSString *) longDescription {
2458 @synchronized (database_) {
2459 if ([database_ era] != era_ || file_.end())
2462 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2463 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2465 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2466 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2467 if ([lines count] < 2)
2470 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2471 for (size_t i(1), e([lines count]); i != e; ++i) {
2472 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2473 [trimmed addObject:trim];
2476 return [trimmed componentsJoinedByString:@"\n"];
2479 - (NSString *) shortDescription {
2480 if (parsed_ != NULL)
2481 return static_cast<NSString *>(parsed_->tagline_);
2483 @synchronized (database_) {
2484 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2486 const char *start, *end;
2487 if (!parser.ShortDesc(start, end))
2490 if (end - start > 200)
2494 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2497 while (end != start && end[-1] == '\r')
2501 return [(id) CYStringCreate(start, end - start) autorelease];
2505 _profile(Package$index)
2506 CFStringRef name((CFStringRef) [self name]);
2507 if (CFStringGetLength(name) == 0)
2509 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2510 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2512 return toupper(character);
2516 - (PackageValue *) metadata {
2521 PackageValue *metadata([self metadata]);
2522 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2525 - (bool) subscribed {
2526 return [self metadata]->subscribed_;
2529 - (bool) setSubscribed:(bool)subscribed {
2530 PackageValue *metadata([self metadata]);
2531 if (metadata->subscribed_ == subscribed)
2533 metadata->subscribed_ = subscribed;
2541 - (NSString *) latest {
2545 - (NSString *) installed {
2549 - (BOOL) uninstalled {
2550 return installed_.empty();
2554 return !version_.end();
2557 - (BOOL) upgradableAndEssential:(BOOL)essential {
2558 _profile(Package$upgradableAndEssential)
2559 pkgCache::VerIterator current(iterator_.CurrentVer());
2561 return essential && essential_;
2563 return !version_.end() && version_ != current;
2567 - (BOOL) essential {
2572 return [database_ cache][iterator_].InstBroken();
2575 - (BOOL) unfiltered {
2576 _profile(Package$unfiltered$obsolete)
2577 if (_unlikely(obsolete_))
2581 _profile(Package$unfiltered$hasSupportingRole)
2582 if (_unlikely(![self hasSupportingRole]))
2590 if (![self unfiltered])
2595 _profile(Package$visible$section)
2596 section = [self section];
2599 _profile(Package$visible$isSectionVisible)
2600 if (!isSectionVisible(section))
2608 unsigned char current(iterator_->CurrentState);
2609 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2612 - (BOOL) halfConfigured {
2613 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2616 - (BOOL) halfInstalled {
2617 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2621 @synchronized (database_) {
2622 if ([database_ era] != era_ || iterator_.end())
2625 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2626 return state.Mode != pkgDepCache::ModeKeep;
2629 - (NSString *) mode {
2630 @synchronized (database_) {
2631 if ([database_ era] != era_ || iterator_.end())
2634 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2636 switch (state.Mode) {
2637 case pkgDepCache::ModeDelete:
2638 if ((state.iFlags & pkgDepCache::Purge) != 0)
2642 case pkgDepCache::ModeKeep:
2643 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2644 return @"REINSTALL";
2645 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2649 case pkgDepCache::ModeInstall:
2650 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2651 return @"REINSTALL";
2652 else*/ switch (state.Status) {
2654 return @"DOWNGRADE";
2660 return @"NEW_INSTALL";
2671 - (NSString *) name {
2672 return name_.empty() ? id_ : name_;
2675 - (UIImage *) icon {
2676 NSString *section = [self simpleSection];
2679 if (parsed_ != NULL)
2680 if (NSString *href = parsed_->icon_)
2681 if ([href hasPrefix:@"file:///"])
2682 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2683 if (icon == nil) if (section != nil)
2684 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2685 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2686 if ([dicon hasPrefix:@"file:///"])
2687 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2689 icon = [UIImage applicationImageNamed:@"unknown.png"];
2693 - (NSString *) homepage {
2694 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2697 - (NSString *) depiction {
2698 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2701 - (MIMEAddress *) sponsor {
2702 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2705 - (MIMEAddress *) author {
2706 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2709 - (NSString *) support {
2710 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2713 - (NSArray *) files {
2714 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2715 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2718 fin.open([path UTF8String]);
2723 while (std::getline(fin, line))
2724 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2729 - (NSString *) state {
2730 @synchronized (database_) {
2731 if ([database_ era] != era_ || file_.end())
2734 switch (iterator_->CurrentState) {
2735 case pkgCache::State::NotInstalled:
2736 return @"NotInstalled";
2737 case pkgCache::State::UnPacked:
2739 case pkgCache::State::HalfConfigured:
2740 return @"HalfConfigured";
2741 case pkgCache::State::HalfInstalled:
2742 return @"HalfInstalled";
2743 case pkgCache::State::ConfigFiles:
2744 return @"ConfigFiles";
2745 case pkgCache::State::Installed:
2746 return @"Installed";
2747 case pkgCache::State::TriggersAwaited:
2748 return @"TriggersAwaited";
2749 case pkgCache::State::TriggersPending:
2750 return @"TriggersPending";
2753 return (NSString *) [NSNull null];
2756 - (NSString *) selection {
2757 @synchronized (database_) {
2758 if ([database_ era] != era_ || file_.end())
2761 switch (iterator_->SelectedState) {
2762 case pkgCache::State::Unknown:
2764 case pkgCache::State::Install:
2766 case pkgCache::State::Hold:
2768 case pkgCache::State::DeInstall:
2769 return @"DeInstall";
2770 case pkgCache::State::Purge:
2774 return (NSString *) [NSNull null];
2777 - (NSArray *) warnings {
2778 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2779 const char *name(iterator_.Name());
2781 size_t length(strlen(name));
2782 if (length < 2) invalid:
2783 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2784 else for (size_t i(0); i != length; ++i)
2786 /* XXX: technically this is not allowed */
2787 (name[i] < 'A' || name[i] > 'Z') &&
2788 (name[i] < 'a' || name[i] > 'z') &&
2789 (name[i] < '0' || name[i] > '9') &&
2790 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2793 if (strcmp(name, "cydia") != 0) {
2796 bool _private = false;
2799 bool repository = [[self section] isEqualToString:@"Repositories"];
2801 if (NSArray *files = [self files])
2802 for (NSString *file in files)
2803 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2805 else if (!user && [file isEqualToString:@"/User"])
2807 else if (!_private && [file isEqualToString:@"/private"])
2809 else if (!stash && [file isEqualToString:@"/var/stash"])
2812 /* XXX: this is not sensitive enough. only some folders are valid. */
2813 if (cydia && !repository)
2814 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2816 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2818 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2820 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2823 return [warnings count] == 0 ? nil : warnings;
2826 - (NSArray *) applications {
2827 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2829 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2831 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2832 if (NSArray *files = [self files])
2833 for (NSString *file in files)
2834 if (application_r(file)) {
2835 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2836 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2837 if ([id isEqualToString:me])
2840 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2842 display = application_r[1];
2844 NSString *bundle([file stringByDeletingLastPathComponent]);
2845 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2846 if (icon == nil || [icon length] == 0)
2848 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2850 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2851 [applications addObject:application];
2853 [application addObject:id];
2854 [application addObject:display];
2855 [application addObject:url];
2858 return [applications count] == 0 ? nil : applications;
2861 - (Source *) source {
2862 if (source_ == nil) {
2863 @synchronized (database_) {
2864 if ([database_ era] != era_ || file_.end())
2865 source_ = (Source *) [NSNull null];
2867 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2871 return source_ == (Source *) [NSNull null] ? nil : source_;
2878 - (BOOL) matches:(NSArray *)query {
2879 if (query == nil || [query count] == 0)
2888 string = [self name];
2889 length = [string length];
2891 for (NSString *term in query) {
2892 range = [string rangeOfString:term options:MatchCompareOptions_];
2893 if (range.location != NSNotFound)
2894 rank_ -= 6 * 1000000 / length;
2899 length = [string length];
2901 for (NSString *term in query) {
2902 range = [string rangeOfString:term options:MatchCompareOptions_];
2903 if (range.location != NSNotFound)
2904 rank_ -= 6 * 1000000 / length;
2908 string = [self shortDescription];
2909 length = [string length];
2910 NSUInteger stop(std::min<NSUInteger>(length, 200));
2912 for (NSString *term in query) {
2913 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2914 if (range.location != NSNotFound)
2915 rank_ -= 2 * 100000;
2921 - (bool) hasSupportingRole {
2926 if ([Role_ isEqualToString:@"User"])
2930 if ([Role_ isEqualToString:@"Hacker"])
2934 if ([Role_ isEqualToString:@"Developer"])
2939 - (NSArray *) tags {
2943 - (BOOL) hasTag:(NSString *)tag {
2944 return tags_ == nil ? NO : [tags_ containsObject:tag];
2947 - (NSString *) primaryPurpose {
2948 for (NSString *tag in (NSArray *) tags_)
2949 if ([tag hasPrefix:@"purpose::"])
2950 return [tag substringFromIndex:9];
2954 - (NSArray *) purposes {
2955 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2956 for (NSString *tag in (NSArray *) tags_)
2957 if ([tag hasPrefix:@"purpose::"])
2958 [purposes addObject:[tag substringFromIndex:9]];
2959 return [purposes count] == 0 ? nil : purposes;
2962 - (bool) isCommercial {
2963 return [self hasTag:@"cydia::commercial"];
2966 - (void) setIndex:(size_t)index {
2967 if (metadata_->index_ != index)
2968 metadata_->index_ = index;
2971 - (CYString &) cyname {
2972 return name_.empty() ? id_ : name_;
2975 - (uint32_t) compareBySection:(NSArray *)sections {
2976 NSString *section([self section]);
2977 for (size_t i(0), e([sections count]); i != e; ++i) {
2978 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2982 return _not(uint32_t);
2986 @synchronized (database_) {
2987 pkgProblemResolver *resolver = [database_ resolver];
2988 resolver->Clear(iterator_);
2990 pkgCacheFile &cache([database_ cache]);
2991 cache->SetReInstall(iterator_, false);
2992 cache->MarkKeep(iterator_, false);
2996 @synchronized (database_) {
2997 pkgProblemResolver *resolver = [database_ resolver];
2998 resolver->Clear(iterator_);
2999 resolver->Protect(iterator_);
3001 pkgCacheFile &cache([database_ cache]);
3002 cache->SetReInstall(iterator_, false);
3003 cache->MarkInstall(iterator_, false);
3005 pkgDepCache::StateCache &state((*cache)[iterator_]);
3006 if (!state.Install())
3007 cache->SetReInstall(iterator_, true);
3011 @synchronized (database_) {
3012 pkgProblemResolver *resolver = [database_ resolver];
3013 resolver->Clear(iterator_);
3014 resolver->Remove(iterator_);
3015 resolver->Protect(iterator_);
3017 pkgCacheFile &cache([database_ cache]);
3018 cache->SetReInstall(iterator_, false);
3019 cache->MarkDelete(iterator_, true);
3022 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3023 _profile(Package$isUnfilteredAndSearchedForBy)
3026 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3027 value &= [self unfiltered];
3030 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3031 value &= [self matches:query];
3038 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3039 if ([search length] == 0)
3042 _profile(Package$isUnfilteredAndSelectedForBy)
3045 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3046 value &= [self unfiltered];
3049 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3050 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3057 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3058 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3061 - (bool) isVisibleInSection:(NSString *)name {
3062 NSString *section([self section]);
3066 section == nil && [name length] == 0 ||
3067 [name isEqualToString:section]
3068 ) && [self visible];
3071 - (bool) isVisibleInSource:(Source *)source {
3072 return [self source] == source && [self visible];
3077 /* Section Class {{{ */
3078 @interface Section : NSObject {
3083 _H<NSString> localized_;
3086 - (NSComparisonResult) compareByLocalized:(Section *)section;
3087 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3088 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3089 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3090 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3091 - (NSString *) name;
3098 - (void) addToCount;
3100 - (void) setCount:(size_t)count;
3101 - (NSString *) localized;
3105 @implementation Section
3107 - (NSComparisonResult) compareByLocalized:(Section *)section {
3108 NSString *lhs(localized_);
3109 NSString *rhs([section localized]);
3111 /*if ([lhs length] != 0 && [rhs length] != 0) {
3112 unichar lhc = [lhs characterAtIndex:0];
3113 unichar rhc = [rhs characterAtIndex:0];
3115 if (isalpha(lhc) && !isalpha(rhc))
3116 return NSOrderedAscending;
3117 else if (!isalpha(lhc) && isalpha(rhc))
3118 return NSOrderedDescending;
3121 return [lhs compare:rhs options:LaxCompareOptions_];
3124 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3125 if ((self = [self initWithName:name localize:NO]) != nil) {
3126 if (localized != nil)
3127 localized_ = localized;
3131 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3132 return [self initWithName:name row:0 localize:localize];
3135 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3136 if ((self = [super init]) != nil) {
3141 localized_ = LocalizeSection(name_);
3145 /* XXX: localize the index thingees */
3146 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3147 if ((self = [super init]) != nil) {
3148 name_ = [NSString stringWithCharacters:&index length:1];
3154 - (NSString *) name {
3174 - (void) addToCount {
3178 - (void) setCount:(size_t)count {
3182 - (NSString *) localized {
3189 class CydiaLogCleaner :
3190 public pkgArchiveCleaner
3193 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3198 /* Database Implementation {{{ */
3199 @implementation Database
3201 + (Database *) sharedInstance {
3202 static _H<Database> instance;
3203 if (instance == nil)
3204 instance = [[[Database alloc] init] autorelease];
3212 - (void) releasePackages {
3213 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3214 CFArrayRemoveAllValues(packages_);
3218 // XXX: actually implement this thing
3220 [self releasePackages];
3221 apr_pool_destroy(pool_);
3222 NSRecycleZone(zone_);
3226 - (void) _readCydia:(NSNumber *)fd {
3227 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3228 std::istream is(&ib);
3231 static Pcre finish_r("^finish:([^:]*)$");
3233 while (std::getline(is, line)) {
3234 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3236 const char *data(line.c_str());
3237 size_t size = line.size();
3238 lprintf("C:%s\n", data);
3240 if (finish_r(data, size)) {
3241 NSString *finish = finish_r[1];
3242 int index = [Finishes_ indexOfObject:finish];
3243 if (index != INT_MAX && index > Finish_)
3253 - (void) _readStatus:(NSNumber *)fd {
3254 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3255 std::istream is(&ib);
3258 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3259 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3261 while (std::getline(is, line)) {
3262 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3264 const char *data(line.c_str());
3265 size_t size(line.size());
3266 lprintf("S:%s\n", data);
3268 if (conffile_r(data, size)) {
3269 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3270 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3271 } else if (strncmp(data, "status: ", 8) == 0) {
3272 // status: <package>: {unpacked,half-configured,installed}
3273 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3274 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3275 } else if (strncmp(data, "processing: ", 12) == 0) {
3276 // processing: configure: config-test
3277 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3278 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3279 } else if (pmstatus_r(data, size)) {
3280 std::string type([pmstatus_r[1] UTF8String]);
3282 NSString *package = pmstatus_r[2];
3283 if ([package isEqualToString:@"dpkg-exec"])
3286 float percent([pmstatus_r[3] floatValue]);
3287 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3289 NSString *string = pmstatus_r[4];
3291 if (type == "pmerror") {
3292 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3293 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3294 } else if (type == "pmstatus") {
3295 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3296 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3297 } else if (type == "pmconffile")
3298 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3300 lprintf("E:unknown pmstatus\n");
3302 lprintf("E:unknown status\n");
3310 - (void) _readOutput:(NSNumber *)fd {
3311 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3312 std::istream is(&ib);
3315 while (std::getline(is, line)) {
3316 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3318 lprintf("O:%s\n", line.c_str());
3320 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3321 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3333 - (Package *) packageWithName:(NSString *)name {
3336 @synchronized (self) {
3337 if (static_cast<pkgDepCache *>(cache_) == NULL)
3339 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3340 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3344 if ((self = [super init]) != nil) {
3351 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3352 apr_pool_create(&pool_, NULL);
3354 size_t capacity(MetaFile_->active_);
3360 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3361 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3365 _assert(pipe(fds) != -1);
3368 _config->Set("APT::Keep-Fds::", cydiafd_);
3369 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3372 detachNewThreadSelector:@selector(_readCydia:)
3374 withObject:[NSNumber numberWithInt:fds[0]]
3377 _assert(pipe(fds) != -1);
3381 detachNewThreadSelector:@selector(_readStatus:)
3383 withObject:[NSNumber numberWithInt:fds[0]]
3386 _assert(pipe(fds) != -1);
3387 _assert(dup2(fds[0], 0) != -1);
3388 _assert(close(fds[0]) != -1);
3390 input_ = fdopen(fds[1], "a");
3392 _assert(pipe(fds) != -1);
3393 _assert(dup2(fds[1], 1) != -1);
3394 _assert(close(fds[1]) != -1);
3397 detachNewThreadSelector:@selector(_readOutput:)
3399 withObject:[NSNumber numberWithInt:fds[0]]
3404 - (pkgCacheFile &) cache {
3408 - (pkgDepCache::Policy *) policy {
3412 - (pkgRecords *) records {
3416 - (pkgProblemResolver *) resolver {
3420 - (pkgAcquire &) fetcher {
3424 - (pkgSourceList &) list {
3428 - (NSArray *) packages {
3429 return (NSArray *) packages_;
3432 - (NSArray *) sources {
3436 - (Source *) sourceWithKey:(NSString *)key {
3437 for (Source *source in [self sources]) {
3438 if ([[source key] isEqualToString:key])
3443 - (bool) popErrorWithTitle:(NSString *)title {
3446 while (!_error->empty()) {
3448 bool warning(!_error->PopMessage(error));
3453 size_t size(error.size());
3454 if (size == 0 || error[size - 1] != '\n')
3456 error.resize(size - 1);
3459 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3461 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3462 if (warning && no_pubkey(error.c_str()))
3465 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3471 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3472 return [self popErrorWithTitle:title] || !success;
3475 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3476 @synchronized (self) {
3479 [self releasePackages];
3482 [sourceList_ removeAllObjects];
3502 apr_pool_clear(pool_);
3504 NSRecycleZone(zone_);
3505 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3507 int chk(creat("/tmp/cydia.chk", 0644));
3511 if (invocation != nil)
3512 [invocation invoke];
3514 NSString *title(UCLocalize("DATABASE"));
3517 OpProgress progress;
3518 while (!cache_.Open(progress, true)) { pop:
3520 bool warning(!_error->PopMessage(error));
3521 lprintf("cache_.Open():[%s]\n", error.c_str());
3523 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3524 [delegate_ repairWithSelector:@selector(configure)];
3525 else if (error == "The package lists or status file could not be parsed or opened.")
3526 [delegate_ repairWithSelector:@selector(update)];
3527 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3528 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3529 // else if (error == "Malformed Status line")
3530 // else if (error == "The list of sources could not be read.")
3532 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3542 unlink("/tmp/cydia.chk");
3544 now_ = [[NSDate date] timeIntervalSince1970];
3546 policy_ = new pkgDepCache::Policy();
3547 records_ = new pkgRecords(cache_);
3548 resolver_ = new pkgProblemResolver(cache_);
3549 fetcher_ = new pkgAcquire(&status_);
3552 list_ = new pkgSourceList();
3553 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3556 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3557 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3561 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3564 if (cache_->BrokenCount() != 0) {
3565 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3568 if (cache_->BrokenCount() != 0) {
3569 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3573 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3577 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3578 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3579 [sourceList_ addObject:object];
3581 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3582 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3583 // XXX: this could be more intelligent
3584 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3585 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3587 sourceMap_[cached->ID] = object;
3592 /*std::vector<Package *> packages;
3593 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3598 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3599 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3600 //packages.push_back(package);
3601 CFArrayAppendValue(packages_, CFRetain(package));
3605 /*if (packages.empty())
3606 packages_ = [[NSArray alloc] init];
3608 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3611 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3612 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3613 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3621 /*if (!packages.empty())
3622 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3623 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3625 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3627 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3629 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3633 size_t count(CFArrayGetCount(packages_));
3634 MetaFile_->active_ = count;
3636 for (size_t index(0); index != count; ++index)
3637 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3644 @synchronized (self) {
3646 resolver_ = new pkgProblemResolver(cache_);
3648 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3649 if (!cache_[iterator].Keep())
3650 cache_->MarkKeep(iterator, false);
3651 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3652 cache_->SetReInstall(iterator, false);
3655 - (void) configure {
3656 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3658 system([dpkg UTF8String]);
3663 // XXX: I don't remember this condition
3668 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3670 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3672 if ([self popErrorWithTitle:title])
3676 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3678 CydiaLogCleaner cleaner;
3679 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3686 fetcher_->Shutdown();
3688 pkgRecords records(cache_);
3690 lock_ = new FileFd();
3691 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3693 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3695 if ([self popErrorWithTitle:title])
3699 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3702 manager_ = (_system->CreatePM(cache_));
3703 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3710 bool substrate(RestartSubstrate_);
3711 RestartSubstrate_ = false;
3713 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3715 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3717 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3719 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3720 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3723 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3725 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3727 [self popErrorWithTitle:title];
3731 bool failed = false;
3732 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3733 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3735 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3741 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3749 RestartSubstrate_ = true;
3752 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3754 if (_error->PendingError()) {
3759 if (result == pkgPackageManager::Failed) {
3764 if (result != pkgPackageManager::Completed) {
3769 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3771 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3773 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3774 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3777 if (![before isEqualToArray:after])
3782 NSString *title(UCLocalize("UPGRADE"));
3783 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3789 [self updateWithStatus:status_];
3792 - (void) updateWithStatus:(Status &)status {
3793 NSString *title(UCLocalize("REFRESHING_DATA"));
3796 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3800 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3801 if ([self popErrorWithTitle:title])
3804 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3806 bool success(ListUpdate(status, list, PulseInterval_));
3807 if (status.WasCancelled())
3810 [self popErrorWithTitle:title forOperation:success];
3811 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3815 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3818 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3819 delegate_ = delegate;
3822 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3823 progress_ = delegate;
3824 status_.setDelegate(delegate);
3827 - (NSObject<ProgressDelegate> *) progressDelegate {
3831 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3832 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3833 return i == sourceMap_.end() ? nil : i->second;
3836 - (NSString *) mappedSectionForPointer:(const char *)section {
3837 _H<NSString> *mapped;
3839 _profile(Database$mappedSectionForPointer$Cache)
3840 mapped = §ions_[section];
3843 if (*mapped == NULL) {
3844 size_t length(strlen(section));
3845 char spaced[length + 1];
3847 _profile(Database$mappedSectionForPointer$Replace)
3848 for (size_t index(0); index != length; ++index)
3849 spaced[index] = section[index] == '_' ? ' ' : section[index];
3850 spaced[length] = '\0';
3855 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3856 string = [NSString stringWithUTF8String:spaced];
3859 _profile(Database$mappedSectionForPointer$Map)
3860 string = [SectionMap_ objectForKey:string] ?: string;
3870 static _H<NSMutableSet> Diversions_;
3872 @interface Diversion : NSObject {
3875 _H<NSString> format_;
3880 @implementation Diversion
3882 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3883 if ((self = [super init]) != nil) {
3884 pattern_ = [from UTF8String];
3890 - (NSString *) divert:(NSString *)url {
3891 return !pattern_(url) ? nil : pattern_->*format_;
3894 + (NSURL *) divertURL:(NSURL *)url {
3896 NSString *href([url absoluteString]);
3898 for (Diversion *diversion in (id) Diversions_)
3899 if (NSString *diverted = [diversion divert:href]) {
3901 NSLog(@"div: %@", diverted);
3903 url = [NSURL URLWithString:diverted];
3910 - (NSString *) key {
3914 - (NSUInteger) hash {
3918 - (BOOL) isEqual:(Diversion *)object {
3919 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3924 @interface CydiaObject : NSObject {
3925 _H<IndirectDelegate> indirect_;
3926 _transient id delegate_;
3929 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3933 @interface CydiaWebViewController : CyteWebViewController {
3934 _H<CydiaObject> cydia_;
3937 + (void) addDiversion:(Diversion *)diversion;
3938 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3942 /* Web Scripting {{{ */
3943 @implementation CydiaObject
3945 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3946 if ((self = [super init]) != nil) {
3947 indirect_ = indirect;
3951 - (void) setDelegate:(id)delegate {
3952 delegate_ = delegate;
3955 + (NSArray *) _attributeKeys {
3956 return [NSArray arrayWithObjects:
3959 @"coreFoundationVersionNumber",
3976 - (NSArray *) attributeKeys {
3977 return [[self class] _attributeKeys];
3980 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3981 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3984 - (NSString *) version {
3988 - (NSString *) build {
3992 - (NSString *) coreFoundationVersionNumber {
3993 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
3996 - (NSString *) device {
3997 return [[UIDevice currentDevice] uniqueIdentifier];
4000 - (NSString *) firmware {
4001 return [[UIDevice currentDevice] systemVersion];
4004 - (NSString *) hostname {
4005 return [[UIDevice currentDevice] name];
4008 - (NSString *) idiom {
4009 return (id) Idiom_ ?: [NSNull null];
4012 - (NSString *) mcc {
4013 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4014 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4018 - (NSString *) mnc {
4019 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4020 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4024 - (NSString *) operator {
4025 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4026 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4030 - (NSString *) bbsnum {
4031 return (id) BBSNum_ ?: [NSNull null];
4034 - (NSString *) ecid {
4035 return (id) ChipID_ ?: [NSNull null];
4038 - (NSString *) serial {
4039 return SerialNumber_;
4042 - (NSString *) role {
4043 return (id) Role_ ?: [NSNull null];
4046 - (NSString *) model {
4047 return [NSString stringWithUTF8String:Machine_];
4050 - (NSString *) token {
4051 return (id) Token_ ?: [NSNull null];
4054 + (NSString *) webScriptNameForSelector:(SEL)selector {
4056 else if (selector == @selector(addBridgedHost:))
4057 return @"addBridgedHost";
4058 else if (selector == @selector(addInsecureHost:))
4059 return @"addInsecureHost";
4060 else if (selector == @selector(addInternalRedirect::))
4061 return @"addInternalRedirect";
4062 else if (selector == @selector(addPipelinedHost:scheme:))
4063 return @"addPipelinedHost";
4064 else if (selector == @selector(addSource:::))
4065 return @"addSource";
4066 else if (selector == @selector(addTokenHost:))
4067 return @"addTokenHost";
4068 else if (selector == @selector(addTrivialSource:))
4069 return @"addTrivialSource";
4070 else if (selector == @selector(close))
4072 else if (selector == @selector(du:))
4074 else if (selector == @selector(stringWithFormat:arguments:))
4076 else if (selector == @selector(getAllSources))
4077 return @"getAllSourcs";
4078 else if (selector == @selector(getKernelNumber:))
4079 return @"getKernelNumber";
4080 else if (selector == @selector(getKernelString:))
4081 return @"getKernelString";
4082 else if (selector == @selector(getInstalledPackages))
4083 return @"getInstalledPackages";
4084 else if (selector == @selector(getIORegistryEntry::))
4085 return @"getIORegistryEntry";
4086 else if (selector == @selector(getLocaleIdentifier))
4087 return @"getLocaleIdentifier";
4088 else if (selector == @selector(getPreferredLanguages))
4089 return @"getPreferredLanguages";
4090 else if (selector == @selector(getPackageById:))
4091 return @"getPackageById";
4092 else if (selector == @selector(getMetadataKeys))
4093 return @"getMetadataKeys";
4094 else if (selector == @selector(getMetadataValue:))
4095 return @"getMetadataValue";
4096 else if (selector == @selector(getSessionValue:))
4097 return @"getSessionValue";
4098 else if (selector == @selector(installPackages:))
4099 return @"installPackages";
4100 else if (selector == @selector(localizedStringForKey:value:table:))
4102 else if (selector == @selector(popViewController:))
4103 return @"popViewController";
4104 else if (selector == @selector(refreshSources))
4105 return @"refreshSources";
4106 else if (selector == @selector(removeButton))
4107 return @"removeButton";
4108 else if (selector == @selector(saveConfig))
4109 return @"saveConfig";
4110 else if (selector == @selector(setMetadataValue::))
4111 return @"setMetadataValue";
4112 else if (selector == @selector(setSessionValue::))
4113 return @"setSessionValue";
4114 else if (selector == @selector(substitutePackageNames:))
4115 return @"substitutePackageNames";
4116 else if (selector == @selector(scrollToBottom:))
4117 return @"scrollToBottom";
4118 else if (selector == @selector(setAllowsNavigationAction:))
4119 return @"setAllowsNavigationAction";
4120 else if (selector == @selector(setBadgeValue:))
4121 return @"setBadgeValue";
4122 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4123 return @"setButtonImage";
4124 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4125 return @"setButtonTitle";
4126 else if (selector == @selector(setHidesBackButton:))
4127 return @"setHidesBackButton";
4128 else if (selector == @selector(setHidesNavigationBar:))
4129 return @"setHidesNavigationBar";
4130 else if (selector == @selector(setNavigationBarStyle:))
4131 return @"setNavigationBarStyle";
4132 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4133 return @"setNavigationBarTintColor";
4134 else if (selector == @selector(setPasteboardString:))
4135 return @"setPasteboardString";
4136 else if (selector == @selector(setPasteboardURL:))
4137 return @"setPasteboardURL";
4138 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4139 return @"setScrollAlwaysBounceVertical";
4140 else if (selector == @selector(setScrollIndicatorStyle:))
4141 return @"setScrollIndicatorStyle";
4142 else if (selector == @selector(setToken:))
4144 else if (selector == @selector(setViewportWidth:))
4145 return @"setViewportWidth";
4146 else if (selector == @selector(statfs:))
4148 else if (selector == @selector(supports:))
4150 else if (selector == @selector(unload))
4156 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4157 return [self webScriptNameForSelector:selector] == nil;
4160 - (BOOL) supports:(NSString *)feature {
4161 return [feature isEqualToString:@"window.open"];
4165 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4168 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4169 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4172 - (void) setScrollIndicatorStyle:(NSString *)style {
4173 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4176 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4177 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4180 - (NSNumber *) getKernelNumber:(NSString *)name {
4181 const char *string([name UTF8String]);
4184 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4185 return (id) [NSNull null];
4187 if (size != sizeof(int))
4188 return (id) [NSNull null];
4191 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4192 return (id) [NSNull null];
4194 return [NSNumber numberWithInt:value];
4197 - (NSString *) getKernelString:(NSString *)name {
4198 const char *string([name UTF8String]);
4201 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4202 return (id) [NSNull null];
4204 char value[size + 1];
4205 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4206 return (id) [NSNull null];
4208 // XXX: just in case you request something ludicrous
4211 return [NSString stringWithCString:value];
4214 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4215 NSObject *value(CYIOGetValue([path UTF8String], entry));
4218 if ([value isKindOfClass:[NSData class]])
4219 value = CYHex((NSData *) value);
4224 - (NSArray *) getMetadataKeys {
4225 @synchronized (Values_) {
4226 return [Values_ allKeys];
4229 - (id) getMetadataValue:(NSString *)key {
4230 @synchronized (Values_) {
4231 return [Values_ objectForKey:key];
4234 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4235 @synchronized (Values_) {
4236 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4237 [Values_ removeObjectForKey:key];
4239 [Values_ setObject:value forKey:key];
4241 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4244 - (id) getSessionValue:(NSString *)key {
4245 @synchronized (SessionData_) {
4246 return [SessionData_ objectForKey:key];
4249 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4250 @synchronized (SessionData_) {
4251 if (value == (id) [WebUndefined undefined])
4252 [SessionData_ removeObjectForKey:key];
4254 [SessionData_ setObject:value forKey:key];
4257 - (void) addBridgedHost:(NSString *)host {
4258 @synchronized (HostConfig_) {
4259 [BridgedHosts_ addObject:host];
4262 - (void) addInsecureHost:(NSString *)host {
4263 @synchronized (HostConfig_) {
4264 [InsecureHosts_ addObject:host];
4267 - (void) addTokenHost:(NSString *)host {
4268 @synchronized (HostConfig_) {
4269 [TokenHosts_ addObject:host];
4272 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4273 @synchronized (HostConfig_) {
4274 if (scheme != (id) [WebUndefined undefined])
4275 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4277 [PipelinedHosts_ addObject:host];
4280 - (void) popViewController:(NSNumber *)value {
4281 if (value == (id) [WebUndefined undefined])
4282 value = [NSNumber numberWithBool:YES];
4283 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4286 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4287 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4289 for (NSString *section in sections)
4290 [array addObject:section];
4292 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4295 distribution, @"Distribution",
4297 nil] waitUntilDone:NO];
4300 - (void) addTrivialSource:(NSString *)href {
4301 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4304 - (void) refreshSources {
4305 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4308 - (void) saveConfig {
4309 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4312 - (NSArray *) getAllSources {
4313 return [[Database sharedInstance] sources];
4316 - (NSArray *) getInstalledPackages {
4317 Database *database([Database sharedInstance]);
4318 @synchronized (database) {
4319 NSArray *packages([database packages]);
4320 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4321 for (Package *package in packages)
4322 if (![package uninstalled])
4323 [installed addObject:package];
4327 - (Package *) getPackageById:(NSString *)id {
4328 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4332 return (Package *) [NSNull null];
4335 - (NSString *) getLocaleIdentifier {
4336 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4339 - (NSArray *) getPreferredLanguages {
4343 - (NSArray *) statfs:(NSString *)path {
4346 if (path == nil || statfs([path UTF8String], &stat) == -1)
4349 return [NSArray arrayWithObjects:
4350 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4351 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4352 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4356 - (NSNumber *) du:(NSString *)path {
4357 NSNumber *value(nil);
4360 _assert(pipe(fds) != -1);
4362 pid_t pid(ExecFork());
4364 _assert(dup2(fds[1], 1) != -1);
4365 _assert(close(fds[0]) != -1);
4366 _assert(close(fds[1]) != -1);
4367 /* XXX: this should probably not use du */
4368 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4373 _assert(close(fds[1]) != -1);
4375 if (FILE *du = fdopen(fds[0], "r")) {
4377 while (fgets(line, sizeof(line), du) != NULL) {
4378 size_t length(strlen(line));
4379 while (length != 0 && line[length - 1] == '\n')
4380 line[--length] = '\0';
4381 if (char *tab = strchr(line, '\t')) {
4383 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4388 } else _assert(close(fds[0]));
4396 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4399 - (void) installPackages:(NSArray *)packages {
4400 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4403 - (NSString *) substitutePackageNames:(NSString *)message {
4404 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4405 for (size_t i(0), e([words count]); i != e; ++i) {
4406 NSString *word([words objectAtIndex:i]);
4407 if (Package *package = [[Database sharedInstance] packageWithName:word])
4408 [words replaceObjectAtIndex:i withObject:[package name]];
4411 return [words componentsJoinedByString:@" "];
4414 - (void) removeButton {
4415 [indirect_ removeButton];
4418 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4419 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4422 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4423 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4426 - (void) setBadgeValue:(id)value {
4427 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4430 - (void) setAllowsNavigationAction:(NSString *)value {
4431 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4434 - (void) setHidesBackButton:(NSString *)value {
4435 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4438 - (void) setHidesNavigationBar:(NSString *)value {
4439 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4442 - (void) setNavigationBarStyle:(NSString *)value {
4443 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4446 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4447 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4448 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4449 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4452 - (void) setPasteboardString:(NSString *)value {
4453 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4456 - (void) setPasteboardURL:(NSString *)value {
4457 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4460 - (void) _setToken:(NSString *)token {
4464 [Metadata_ removeObjectForKey:@"Token"];
4466 [Metadata_ setObject:Token_ forKey:@"Token"];
4471 - (void) setToken:(NSString *)token {
4472 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4475 - (void) scrollToBottom:(NSNumber *)animated {
4476 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4479 - (void) setViewportWidth:(float)width {
4480 [indirect_ setViewportWidthOnMainThread:width];
4483 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4484 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4485 unsigned count([arguments count]);
4487 for (unsigned i(0); i != count; ++i)
4488 values[i] = [arguments objectAtIndex:i];
4489 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4492 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4493 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4495 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4497 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4503 @interface NSURL (CydiaSecure)
4506 @implementation NSURL (CydiaSecure)
4508 - (bool) isCydiaSecure {
4509 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4512 @synchronized (HostConfig_) {
4513 if ([InsecureHosts_ containsObject:[self host]])
4522 /* Cydia Browser Controller {{{ */
4523 @implementation CydiaWebViewController
4525 - (NSURL *) navigationURL {
4526 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4529 + (void) _initialize {
4530 [super _initialize];
4532 Diversions_ = [NSMutableSet setWithCapacity:0];
4535 + (void) addDiversion:(Diversion *)diversion {
4536 [Diversions_ addObject:diversion];
4539 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4540 [super webView:view didClearWindowObject:window forFrame:frame];
4542 WebDataSource *source([frame dataSource]);
4543 NSURLResponse *response([source response]);
4544 NSURL *url([response URL]);
4545 NSString *scheme([[url scheme] lowercaseString]);
4547 bool bridged(false);
4549 @synchronized (HostConfig_) {
4550 if ([scheme isEqualToString:@"file"])
4552 else if ([scheme isEqualToString:@"https"])
4553 if ([BridgedHosts_ containsObject:[url host]])
4558 [window setValue:cydia_ forKey:@"cydia"];
4561 - (void) _setupMail:(MFMailComposeViewController *)controller {
4562 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4564 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4565 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4568 - (NSURL *) URLWithURL:(NSURL *)url {
4569 return [Diversion divertURL:url];
4572 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4573 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4576 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4577 NSMutableURLRequest *copy([request mutableCopy]);
4579 NSURL *url([copy URL]);
4580 NSString *host([url host]);
4582 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf-Version"] == nil)
4583 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf-Version"];
4584 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4585 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4590 @synchronized (HostConfig_) {
4591 bridged = [BridgedHosts_ containsObject:host];
4592 token = [TokenHosts_ containsObject:host];
4595 if ([url isCydiaSecure]) {
4597 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4598 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4600 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4601 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4608 - (void) setDelegate:(id)delegate {
4609 [super setDelegate:delegate];
4610 [cydia_ setDelegate:delegate];
4613 - (NSString *) applicationNameForUserAgent {
4618 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4619 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4625 @interface AppCacheController : CydiaWebViewController {
4630 @implementation AppCacheController
4632 - (void) didReceiveMemoryWarning {
4633 // XXX: this doesn't work
4636 - (bool) retainsNetworkActivityIndicator {
4644 @interface NSObject (CydiaScript)
4645 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4648 @implementation NSObject (CydiaScript)
4650 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4656 @implementation NSArray (CydiaScript)
4658 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4659 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4660 for (size_t i(0), e([self count]); i != e; ++i)
4661 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4667 @implementation NSDictionary (CydiaScript)
4669 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4670 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4672 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4679 /* Confirmation Controller {{{ */
4680 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4681 if (!iterator.end())
4682 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4683 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4685 pkgCache::PkgIterator package(dep.TargetPkg());
4688 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4695 @protocol ConfirmationControllerDelegate
4696 - (void) cancelAndClear:(bool)clear;
4697 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4701 @interface ConfirmationController : CydiaWebViewController {
4702 _transient Database *database_;
4704 _H<UIAlertView> essential_;
4706 _H<NSDictionary> changes_;
4707 _H<NSMutableArray> issues_;
4708 _H<NSDictionary> sizes_;
4713 - (id) initWithDatabase:(Database *)database;
4717 @implementation ConfirmationController
4721 RestartSubstrate_ = true;
4722 [delegate_ confirmWithNavigationController:[self navigationController]];
4725 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4726 NSString *context([alert context]);
4728 if ([context isEqualToString:@"remove"]) {
4729 if (button == [alert cancelButtonIndex])
4730 [self dismissModalViewControllerAnimated:YES];
4731 else if (button == [alert firstOtherButtonIndex]) {
4735 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4736 } else if ([context isEqualToString:@"unable"]) {
4737 [self dismissModalViewControllerAnimated:YES];
4738 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4740 [super alertView:alert clickedButtonAtIndex:button];
4744 - (void) _doContinue {
4745 [delegate_ cancelAndClear:NO];
4746 [self dismissModalViewControllerAnimated:YES];
4749 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4750 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4754 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4755 [super webView:view didClearWindowObject:window forFrame:frame];
4757 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4758 (id) changes_, @"changes",
4759 (id) issues_, @"issues",
4760 (id) sizes_, @"sizes",
4762 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4765 - (id) initWithDatabase:(Database *)database {
4766 if ((self = [super init]) != nil) {
4767 database_ = database;
4769 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4770 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4771 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4772 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4773 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4777 pkgCacheFile &cache([database_ cache]);
4778 NSArray *packages([database_ packages]);
4779 pkgDepCache::Policy *policy([database_ policy]);
4781 issues_ = [NSMutableArray arrayWithCapacity:4];
4783 for (Package *package in packages) {
4784 pkgCache::PkgIterator iterator([package iterator]);
4785 NSString *name([package id]);
4787 if ([package broken]) {
4788 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4790 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4792 reasons, @"reasons",
4795 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4799 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4800 pkgCache::DepIterator start;
4801 pkgCache::DepIterator end;
4802 dep.GlobOr(start, end); // ++dep
4804 if (!cache->IsImportantDep(end))
4806 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4809 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4811 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4812 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4813 clauses, @"clauses",
4817 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4819 pkgCache::PkgIterator target(start.TargetPkg());
4820 if (target->ProvidesList != 0)
4821 reason = @"missing";
4823 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4825 reason = @"installed";
4826 installed = [NSString stringWithUTF8String:ver.VerStr()];
4827 } else if (!cache[target].CandidateVerIter(cache).end())
4828 reason = @"uninstalled";
4829 else if (target->ProvidesList == 0)
4830 reason = @"uninstallable";
4832 reason = @"virtual";
4835 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4836 [NSString stringWithUTF8String:start.CompType()], @"operator",
4837 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4840 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4841 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4842 version, @"version",
4844 installed, @"installed",
4847 // yes, seriously. (wtf?)
4855 pkgDepCache::StateCache &state(cache[iterator]);
4857 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4859 if (state.NewInstall())
4860 [installs addObject:name];
4861 // XXX: else if (state.Install())
4862 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4863 [reinstalls addObject:name];
4864 // XXX: move before previous if
4865 else if (state.Upgrade())
4866 [upgrades addObject:name];
4867 else if (state.Downgrade())
4868 [downgrades addObject:name];
4869 else if (!state.Delete())
4870 // XXX: _assert(state.Keep());
4872 else if (special_r(name))
4873 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4874 [NSNull null], @"package",
4875 [NSArray arrayWithObjects:
4876 [NSDictionary dictionaryWithObjectsAndKeys:
4877 @"Conflicts", @"relationship",
4878 [NSArray arrayWithObjects:
4879 [NSDictionary dictionaryWithObjectsAndKeys:
4881 [NSNull null], @"version",
4882 @"installed", @"reason",
4889 if ([package essential])
4891 [removes addObject:name];
4894 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4895 substrate_ |= DepSubstrate(iterator.CurrentVer());
4900 else if (Advanced_) {
4901 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4903 essential_ = [[[UIAlertView alloc]
4904 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4905 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4907 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4909 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4913 [essential_ setContext:@"remove"];
4915 essential_ = [[[UIAlertView alloc]
4916 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4917 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4919 cancelButtonTitle:UCLocalize("OKAY")
4920 otherButtonTitles:nil
4923 [essential_ setContext:@"unable"];
4926 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4927 installs, @"installs",
4928 reinstalls, @"reinstalls",
4929 upgrades, @"upgrades",
4930 downgrades, @"downgrades",
4931 removes, @"removes",
4934 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4935 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4936 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4939 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4943 - (UIBarButtonItem *) leftButton {
4944 return [[[UIBarButtonItem alloc]
4945 initWithTitle:UCLocalize("CANCEL")
4946 style:UIBarButtonItemStylePlain
4948 action:@selector(cancelButtonClicked)
4953 - (void) applyRightButton {
4954 if ([issues_ count] == 0 && ![self isLoading])
4955 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4956 initWithTitle:UCLocalize("CONFIRM")
4957 style:UIBarButtonItemStyleDone
4959 action:@selector(confirmButtonClicked)
4962 [[self navigationItem] setRightBarButtonItem:nil];
4966 - (void) cancelButtonClicked {
4967 [self dismissModalViewControllerAnimated:YES];
4968 [delegate_ cancelAndClear:YES];
4972 - (void) confirmButtonClicked {
4973 if (essential_ != nil)
4983 /* Progress Data {{{ */
4984 @interface CydiaProgressData : NSObject {
4985 _transient id delegate_;
4994 _H<NSMutableArray> events_;
4995 _H<NSString> title_;
4997 _H<NSString> status_;
4998 _H<NSString> finish_;
5003 @implementation CydiaProgressData
5005 + (NSArray *) _attributeKeys {
5006 return [NSArray arrayWithObjects:
5018 - (NSArray *) attributeKeys {
5019 return [[self class] _attributeKeys];
5022 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5023 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5027 if ((self = [super init]) != nil) {
5028 events_ = [NSMutableArray arrayWithCapacity:32];
5032 - (void) setDelegate:(id)delegate {
5033 delegate_ = delegate;
5036 - (void) setPercent:(float)value {
5040 - (NSNumber *) percent {
5041 return [NSNumber numberWithFloat:percent_];
5044 - (void) setCurrent:(float)value {
5048 - (NSNumber *) current {
5049 return [NSNumber numberWithFloat:current_];
5052 - (void) setTotal:(float)value {
5056 - (NSNumber *) total {
5057 return [NSNumber numberWithFloat:total_];
5060 - (void) setSpeed:(float)value {
5064 - (NSNumber *) speed {
5065 return [NSNumber numberWithFloat:speed_];
5068 - (NSArray *) events {
5072 - (void) removeAllEvents {
5073 [events_ removeAllObjects];
5076 - (void) addEvent:(CydiaProgressEvent *)event {
5077 [events_ addObject:event];
5080 - (void) setTitle:(NSString *)text {
5084 - (NSString *) title {
5088 - (void) setFinish:(NSString *)text {
5092 - (NSString *) finish {
5093 return (id) finish_ ?: [NSNull null];
5096 - (void) setRunning:(bool)running {
5100 - (NSNumber *) running {
5101 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5106 /* Progress Controller {{{ */
5107 @interface ProgressController : CydiaWebViewController <
5110 _transient Database *database_;
5111 _H<CydiaProgressData, 1> progress_;
5115 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5117 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5119 - (void) setTitle:(NSString *)title;
5120 - (void) setCancellable:(bool)cancellable;
5124 @implementation ProgressController
5127 [database_ setProgressDelegate:nil];
5131 - (UIBarButtonItem *) leftButton {
5132 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5133 initWithTitle:UCLocalize("CANCEL")
5134 style:UIBarButtonItemStylePlain
5136 action:@selector(cancel)
5137 ] autorelease] : nil;
5140 - (void) updateCancel {
5141 [super applyLeftButton];
5144 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5145 if ((self = [super init]) != nil) {
5146 database_ = database;
5147 delegate_ = delegate;
5149 [database_ setProgressDelegate:self];
5151 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5152 [progress_ setDelegate:self];
5154 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5156 [scroller_ setBackgroundColor:[UIColor blackColor]];
5158 [[self navigationItem] setHidesBackButton:YES];
5160 [self updateCancel];
5164 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5165 [super webView:view didClearWindowObject:window forFrame:frame];
5166 [window setValue:progress_ forKey:@"cydiaProgress"];
5169 - (void) updateProgress {
5170 [self dispatchEvent:@"CydiaProgressUpdate"];
5173 - (void) viewWillAppear:(BOOL)animated {
5174 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5175 [super viewWillAppear:animated];
5179 UpdateExternalStatus(0);
5182 [delegate_ saveState];
5186 [delegate_ returnToCydia];
5190 [delegate_ terminateWithSuccess];
5191 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5192 [delegate_ suspendWithAnimation:YES];
5194 [delegate_ suspend];*/
5206 system("/usr/bin/sbreload");
5212 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5213 SBReboot(SBSSpringBoardServerPort());
5215 reboot2(RB_AUTOBOOT);
5222 - (void) setTitle:(NSString *)title {
5223 [progress_ setTitle:title];
5224 [self updateProgress];
5227 - (UIBarButtonItem *) rightButton {
5228 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5229 initWithTitle:UCLocalize("CLOSE")
5230 style:UIBarButtonItemStylePlain
5232 action:@selector(close)
5238 system("su -c /usr/bin/uicache mobile");
5242 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5243 UpdateExternalStatus(1);
5245 [progress_ setRunning:true];
5246 [self setTitle:title];
5247 // implicit updateProgress
5249 SHA1SumValue notifyconf; {
5251 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5254 MMap mmap(file, MMap::ReadOnly);
5256 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5257 notifyconf = sha1.Result();
5261 SHA1SumValue springlist; {
5263 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5266 MMap mmap(file, MMap::ReadOnly);
5268 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5269 springlist = sha1.Result();
5273 if (invocation != nil) {
5274 [invocation yieldToSelector:@selector(invoke)];
5275 [self setTitle:@"COMPLETE"];
5280 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5283 MMap mmap(file, MMap::ReadOnly);
5285 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5286 if (!(notifyconf == sha1.Result()))
5293 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5296 MMap mmap(file, MMap::ReadOnly);
5298 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5299 if (!(springlist == sha1.Result()))
5305 if (RestartSubstrate_)
5309 RestartSubstrate_ = false;
5312 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5313 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5314 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5315 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5316 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5319 UIProgressHUD *hud([delegate_ addProgressHUD]);
5320 [hud setText:UCLocalize("LOADING")];
5321 [self yieldToSelector:@selector(uicache)];
5322 [delegate_ removeProgressHUD:hud];
5324 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5326 [progress_ setRunning:false];
5327 [self updateProgress];
5329 [self applyRightButton];
5332 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5333 [progress_ addEvent:event];
5334 [self updateProgress];
5337 - (bool) isProgressCancelled {
5338 return cancel_ == 2;
5343 [self updateCancel];
5346 - (void) setCancellable:(bool)cancellable {
5347 unsigned cancel(cancel_);
5351 else if (cancel_ == 0)
5354 if (cancel != cancel_)
5355 [self updateCancel];
5358 - (void) setProgressCancellable:(NSNumber *)cancellable {
5359 [self setCancellable:[cancellable boolValue]];
5362 - (void) setProgressPercent:(NSNumber *)percent {
5363 [progress_ setPercent:[percent floatValue]];
5364 [self updateProgress];
5367 - (void) setProgressStatus:(NSDictionary *)status {
5368 if (status == nil) {
5369 [progress_ setCurrent:0];
5370 [progress_ setTotal:0];
5371 [progress_ setSpeed:0];
5373 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5375 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5376 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5377 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5380 [self updateProgress];
5386 /* Package Cell {{{ */
5387 @interface PackageCell : CyteTableViewCell <
5388 CyteTableViewCellDelegate
5392 _H<NSString> description_;
5394 _H<NSString> source_;
5396 _H<UIImage> placard_;
5400 - (PackageCell *) init;
5401 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5403 - (void) drawContentRect:(CGRect)rect;
5407 @implementation PackageCell
5409 - (PackageCell *) init {
5410 CGRect frame(CGRectMake(0, 0, 320, 74));
5411 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5412 UIView *content([self contentView]);
5413 CGRect bounds([content bounds]);
5415 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5416 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5417 [content addSubview:content_];
5419 [content_ setDelegate:self];
5420 [content_ setOpaque:YES];
5424 - (NSString *) accessibilityLabel {
5425 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5428 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5429 summarized_ = summary;
5439 [content_ setBackgroundColor:[UIColor whiteColor]];
5443 Source *source = [package source];
5445 icon_ = [package icon];
5447 if (NSString *name = [package name])
5448 name_ = [NSString stringWithString:name];
5450 NSString *description(nil);
5452 if (description == nil && IsWildcat_)
5453 description = [package longDescription];
5454 if (description == nil)
5455 description = [package shortDescription];
5457 if (description != nil)
5458 description_ = [NSString stringWithString:description];
5460 commercial_ = [package isCommercial];
5462 NSString *label = nil;
5463 bool trusted = false;
5465 if (source != nil) {
5466 label = [source label];
5467 trusted = [source trusted];
5468 } else if ([[package id] isEqualToString:@"firmware"])
5469 label = UCLocalize("APPLE");
5471 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5473 NSString *from(label);
5475 NSString *section = [package simpleSection];
5476 if (section != nil && ![section isEqualToString:label]) {
5477 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5478 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5481 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5483 if (NSString *purpose = [package primaryPurpose])
5484 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5489 if (NSString *mode = [package mode]) {
5490 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5491 color = RemovingColor_;
5492 //placard = @"removing";
5494 color = InstallingColor_;
5495 //placard = @"installing";
5498 // XXX: the removing/installing placards are not @2x
5501 color = [UIColor whiteColor];
5503 if ([package installed] != nil)
5504 placard = @"installed";
5509 [content_ setBackgroundColor:color];
5512 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5515 [self setNeedsDisplay];
5516 [content_ setNeedsDisplay];
5519 - (void) drawSummaryContentRect:(CGRect)rect {
5520 bool highlighted(highlighted_);
5521 float width([self bounds].size.width);
5525 rect.size = [(UIImage *) icon_ size];
5527 while (rect.size.width > 16 || rect.size.height > 16) {
5528 rect.size.width /= 2;
5529 rect.size.height /= 2;
5532 rect.origin.x = 18 - rect.size.width / 2;
5533 rect.origin.y = 18 - rect.size.height / 2;
5535 [icon_ drawInRect:rect];
5538 if (badge_ != nil) {
5540 rect.size = [(UIImage *) badge_ size];
5542 rect.size.width /= 4;
5543 rect.size.height /= 4;
5545 rect.origin.x = 23 - rect.size.width / 2;
5546 rect.origin.y = 23 - rect.size.height / 2;
5548 [badge_ drawInRect:rect];
5555 UISetColor(commercial_ ? Purple_ : Black_);
5556 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5558 if (placard_ != nil)
5559 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5562 - (void) drawNormalContentRect:(CGRect)rect {
5563 bool highlighted(highlighted_);
5564 float width([self bounds].size.width);
5568 rect.size = [(UIImage *) icon_ size];
5570 while (rect.size.width > 32 || rect.size.height > 32) {
5571 rect.size.width /= 2;
5572 rect.size.height /= 2;
5575 rect.origin.x = 25 - rect.size.width / 2;
5576 rect.origin.y = 25 - rect.size.height / 2;
5578 [icon_ drawInRect:rect];
5581 if (badge_ != nil) {
5583 rect.size = [(UIImage *) badge_ size];
5585 rect.size.width /= 2;
5586 rect.size.height /= 2;
5588 rect.origin.x = 36 - rect.size.width / 2;
5589 rect.origin.y = 36 - rect.size.height / 2;
5591 [badge_ drawInRect:rect];
5598 UISetColor(commercial_ ? Purple_ : Black_);
5599 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5600 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5603 UISetColor(commercial_ ? Purplish_ : Gray_);
5604 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5606 if (placard_ != nil)
5607 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5610 - (void) drawContentRect:(CGRect)rect {
5612 [self drawSummaryContentRect:rect];
5614 [self drawNormalContentRect:rect];
5619 /* Section Cell {{{ */
5620 @interface SectionCell : CyteTableViewCell <
5621 CyteTableViewCellDelegate
5623 _H<NSString> basic_;
5624 _H<NSString> section_;
5626 _H<NSString> count_;
5628 _H<UISwitch> switch_;
5632 - (void) setSection:(Section *)section editing:(BOOL)editing;
5636 @implementation SectionCell
5638 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5639 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5640 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5641 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5642 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5644 UIView *content([self contentView]);
5645 CGRect bounds([content bounds]);
5647 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5648 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5649 [content addSubview:content_];
5650 [content_ setBackgroundColor:[UIColor whiteColor]];
5652 [content_ setDelegate:self];
5656 - (void) onSwitch:(id)sender {
5657 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5658 if (metadata == nil) {
5659 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5660 [Sections_ setObject:metadata forKey:basic_];
5663 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5667 - (void) setSection:(Section *)section editing:(BOOL)editing {
5668 if (editing != editing_) {
5670 [switch_ removeFromSuperview];
5672 [self addSubview:switch_];
5681 if (section == nil) {
5682 name_ = UCLocalize("ALL_PACKAGES");
5685 basic_ = [section name];
5686 section_ = [section localized];
5688 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5689 count_ = [NSString stringWithFormat:@"%d", [section count]];
5692 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5695 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5696 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5698 [content_ setNeedsDisplay];
5701 - (void) setFrame:(CGRect)frame {
5702 [super setFrame:frame];
5704 CGRect rect([switch_ frame]);
5705 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5708 - (NSString *) accessibilityLabel {
5712 - (void) drawContentRect:(CGRect)rect {
5713 bool highlighted(highlighted_ && !editing_);
5715 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5720 float width(rect.size.width);
5726 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5728 CGSize size = [count_ sizeWithFont:Font14_];
5732 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5738 /* File Table {{{ */
5739 @interface FileTable : CyteViewController <
5740 UITableViewDataSource,
5743 _transient Database *database_;
5744 _H<Package> package_;
5746 _H<NSMutableArray> files_;
5747 _H<UITableView, 2> list_;
5750 - (id) initWithDatabase:(Database *)database;
5751 - (void) setPackage:(Package *)package;
5755 @implementation FileTable
5757 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5758 return files_ == nil ? 0 : [files_ count];
5761 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5765 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5766 static NSString *reuseIdentifier = @"Cell";
5768 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5770 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5771 [cell setFont:[UIFont systemFontOfSize:16]];
5773 [cell setText:[files_ objectAtIndex:indexPath.row]];
5774 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5779 - (NSURL *) navigationURL {
5780 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5784 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5785 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5786 [list_ setRowHeight:24.0f];
5787 [(UITableView *) list_ setDataSource:self];
5788 [list_ setDelegate:self];
5789 [self setView:list_];
5792 - (void) viewDidLoad {
5793 [super viewDidLoad];
5795 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5798 - (void) releaseSubviews {
5804 [super releaseSubviews];
5807 - (id) initWithDatabase:(Database *)database {
5808 if ((self = [super init]) != nil) {
5809 database_ = database;
5813 - (void) setPackage:(Package *)package {
5817 files_ = [NSMutableArray arrayWithCapacity:32];
5819 if (package != nil) {
5821 name_ = [package id];
5823 if (NSArray *files = [package files])
5824 [files_ addObjectsFromArray:files];
5826 if ([files_ count] != 0) {
5827 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5828 [files_ removeObjectAtIndex:0];
5829 [files_ sortUsingSelector:@selector(compareByPath:)];
5831 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5832 [stack addObject:@"/"];
5834 for (int i(0), e([files_ count]); i != e; ++i) {
5835 NSString *file = [files_ objectAtIndex:i];
5836 while (![file hasPrefix:[stack lastObject]])
5837 [stack removeLastObject];
5838 NSString *directory = [stack lastObject];
5839 [stack addObject:[file stringByAppendingString:@"/"]];
5840 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5841 ([stack count] - 2) * 3, "",
5842 [file substringFromIndex:[directory length]]
5851 - (void) reloadData {
5854 [self setPackage:[database_ packageWithName:name_]];
5859 /* Package Controller {{{ */
5860 @interface CYPackageController : CydiaWebViewController <
5861 UIActionSheetDelegate
5863 _transient Database *database_;
5864 _H<Package> package_;
5867 _H<NSMutableArray> buttons_;
5868 _H<UIBarButtonItem> button_;
5871 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5875 @implementation CYPackageController
5877 - (NSURL *) navigationURL {
5878 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5881 /* XXX: this is not safe at all... localization of /fail/ */
5882 - (void) _clickButtonWithName:(NSString *)name {
5883 if ([name isEqualToString:UCLocalize("CLEAR")])
5884 [delegate_ clearPackage:package_];
5885 else if ([name isEqualToString:UCLocalize("INSTALL")])
5886 [delegate_ installPackage:package_];
5887 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5888 [delegate_ installPackage:package_];
5889 else if ([name isEqualToString:UCLocalize("REMOVE")])
5890 [delegate_ removePackage:package_];
5891 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5892 [delegate_ installPackage:package_];
5893 else _assert(false);
5896 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5897 NSString *context([sheet context]);
5899 if ([context isEqualToString:@"modify"]) {
5900 if (button != [sheet cancelButtonIndex]) {
5901 NSString *buttonName = [buttons_ objectAtIndex:button];
5902 [self _clickButtonWithName:buttonName];
5905 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5909 - (bool) _allowJavaScriptPanel {
5914 - (void) _customButtonClicked {
5915 int count([buttons_ count]);
5920 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5922 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5923 [buttons addObjectsFromArray:buttons_];
5925 UIActionSheet *sheet = [[[UIActionSheet alloc]
5928 cancelButtonTitle:nil
5929 destructiveButtonTitle:nil
5930 otherButtonTitles:nil
5933 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5935 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5936 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5938 [sheet setContext:@"modify"];
5940 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5944 // We don't want to allow non-commercial packages to do custom things to the install button,
5945 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5946 - (void) customButtonClicked {
5948 [super customButtonClicked];
5950 [self _customButtonClicked];
5953 - (void) reloadButtonClicked {
5954 // Don't reload a commerical package by tapping the loading button,
5955 // but if it's not an Install button, we should forward it on.
5956 if (![package_ uninstalled])
5957 [self _customButtonClicked];
5960 - (void) applyLoadingTitle {
5961 // Don't show "Loading" as the title. Ever.
5964 - (UIBarButtonItem *) rightButton {
5969 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5970 if ((self = [super init]) != nil) {
5971 database_ = database;
5972 buttons_ = [NSMutableArray arrayWithCapacity:4];
5973 name_ = name == nil ? @"" : [NSString stringWithString:name];
5974 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5978 - (void) reloadData {
5981 package_ = [database_ packageWithName:name_];
5983 [buttons_ removeAllObjects];
5985 if (package_ != nil) {
5986 [(Package *) package_ parse];
5988 commercial_ = [package_ isCommercial];
5990 if ([package_ mode] != nil)
5991 [buttons_ addObject:UCLocalize("CLEAR")];
5992 if ([package_ source] == nil);
5993 else if ([package_ upgradableAndEssential:NO])
5994 [buttons_ addObject:UCLocalize("UPGRADE")];
5995 else if ([package_ uninstalled])
5996 [buttons_ addObject:UCLocalize("INSTALL")];
5998 [buttons_ addObject:UCLocalize("REINSTALL")];
5999 if (![package_ uninstalled])
6000 [buttons_ addObject:UCLocalize("REMOVE")];
6004 switch ([buttons_ count]) {
6005 case 0: title = nil; break;
6006 case 1: title = [buttons_ objectAtIndex:0]; break;
6007 default: title = UCLocalize("MODIFY"); break;
6010 button_ = [[[UIBarButtonItem alloc]
6012 style:UIBarButtonItemStylePlain
6014 action:@selector(customButtonClicked)
6018 - (bool) isLoading {
6019 return commercial_ ? [super isLoading] : false;
6025 /* Package List Controller {{{ */
6026 @interface PackageListController : CyteViewController <
6027 UITableViewDataSource,
6030 _transient Database *database_;
6032 _H<NSArray> packages_;
6033 _H<NSMutableArray> sections_;
6034 _H<UITableView, 2> list_;
6035 _H<NSMutableArray> index_;
6036 _H<NSMutableDictionary> indices_;
6037 _H<NSString> title_;
6038 unsigned reloading_;
6041 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6042 - (void) setDelegate:(id)delegate;
6043 - (void) resetCursor;
6048 @implementation PackageListController
6050 - (bool) isSummarized {
6054 - (bool) showsSections {
6058 - (void) deselectWithAnimation:(BOOL)animated {
6059 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6062 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6063 CGRect base = [[self view] bounds];
6064 base.size.height -= bounds.size.height;
6065 base.origin = [list_ frame].origin;
6067 [UIView beginAnimations:nil context:NULL];
6068 [UIView setAnimationBeginsFromCurrentState:YES];
6069 [UIView setAnimationCurve:curve];
6070 [UIView setAnimationDuration:duration];
6071 [list_ setFrame:base];
6072 [UIView commitAnimations];
6075 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6076 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6079 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6080 [self resizeForKeyboardBounds:bounds duration:0];
6083 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6084 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6085 *curve = UIViewAnimationCurveEaseInOut;
6087 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6089 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6092 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6095 - (void) keyboardWillShow:(NSNotification *)notification {
6098 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6099 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6101 NSTimeInterval duration;
6102 UIViewAnimationCurve curve;
6103 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6105 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);
6106 UIViewController *base = self;
6107 while ([base parentViewController] != nil)
6108 base = [base parentViewController];
6109 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6110 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6112 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6113 intersection.size.height += CYStatusBarHeight();
6115 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6118 - (void) keyboardWillHide:(NSNotification *)notification {
6119 NSTimeInterval duration;
6120 UIViewAnimationCurve curve;
6121 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6123 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6126 - (void) viewWillAppear:(BOOL)animated {
6127 [super viewWillAppear:animated];
6129 [self resizeForKeyboardBounds:CGRectZero];
6130 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6131 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6134 - (void) viewWillDisappear:(BOOL)animated {
6135 [super viewWillDisappear:animated];
6137 [self resizeForKeyboardBounds:CGRectZero];
6138 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6139 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6142 - (void) viewDidAppear:(BOOL)animated {
6143 [super viewDidAppear:animated];
6144 [self deselectWithAnimation:animated];
6147 - (void) didSelectPackage:(Package *)package {
6148 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6149 [view setDelegate:delegate_];
6150 [[self navigationController] pushViewController:view animated:YES];
6153 #if TryIndexedCollation
6154 + (BOOL) hasIndexedCollation {
6155 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6159 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6160 NSInteger count([sections_ count]);
6161 return count == 0 ? 1 : count;
6164 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6165 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6167 return [[sections_ objectAtIndex:section] name];
6170 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6171 if ([sections_ count] == 0)
6173 return [[sections_ objectAtIndex:section] count];
6176 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6177 @synchronized (database_) {
6178 if ([database_ era] != era_)
6181 Section *section([sections_ objectAtIndex:[path section]]);
6182 NSInteger row([path row]);
6183 Package *package([packages_ objectAtIndex:([section row] + row)]);
6184 return [[package retain] autorelease];
6187 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6188 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6190 cell = [[[PackageCell alloc] init] autorelease];
6192 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6193 [cell setPackage:package asSummary:[self isSummarized]];
6197 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6198 Package *package([self packageAtIndexPath:path]);
6199 package = [database_ packageWithName:[package id]];
6200 [self didSelectPackage:package];
6203 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6204 if (![self showsSections])
6210 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6211 #if TryIndexedCollation
6212 if ([[self class] hasIndexedCollation]) {
6213 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6220 - (void) updateHeight {
6221 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6224 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6225 if ((self = [super init]) != nil) {
6226 database_ = database;
6227 title_ = [title copy];
6228 [[self navigationItem] setTitle:title_];
6233 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6234 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6235 [self setView:view];
6237 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6238 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6239 [view addSubview:list_];
6241 // XXX: is 20 the most optimal number here?
6242 [list_ setSectionIndexMinimumDisplayRowCount:20];
6244 [(UITableView *) list_ setDataSource:self];
6245 [list_ setDelegate:self];
6247 [self updateHeight];
6250 - (void) releaseSubviews {
6258 [super releaseSubviews];
6261 - (void) setDelegate:(id)delegate {
6262 delegate_ = delegate;
6265 - (bool) shouldYield {
6269 - (bool) shouldBlock {
6273 - (NSMutableArray *) _reloadPackages {
6274 @synchronized (database_) {
6275 era_ = [database_ era];
6276 NSArray *packages([database_ packages]);
6278 return [NSMutableArray arrayWithArray:packages];
6281 - (void) _reloadData {
6282 if (reloading_ != 0) {
6290 if ([self shouldYield]) {
6294 if (![self shouldBlock])
6297 hud = [delegate_ addProgressHUD];
6298 [hud setText:UCLocalize("LOADING")];
6302 packages = [self yieldToSelector:@selector(_reloadPackages)];
6305 [delegate_ removeProgressHUD:hud];
6306 } while (reloading_ == 2);
6308 packages = [self _reloadPackages];
6311 @synchronized (database_) {
6312 if (era_ != [database_ era])
6316 packages_ = packages;
6318 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6319 sections_ = [NSMutableArray arrayWithCapacity:16];
6321 Section *section = nil;
6323 #if TryIndexedCollation
6324 if ([[self class] hasIndexedCollation]) {
6325 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6327 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6328 NSArray *titles = [collation sectionIndexTitles];
6331 _profile(PackageTable$reloadData$Section)
6332 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6336 _profile(PackageTable$reloadData$Section$Package)
6337 package = [packages_ objectAtIndex:offset];
6338 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6341 while (secidx < index) {
6344 _profile(PackageTable$reloadData$Section$Allocate)
6345 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6348 _profile(PackageTable$reloadData$Section$Add)
6349 [sections_ addObject:section];
6353 [section addToCount];
6359 index_ = [NSMutableArray arrayWithCapacity:32];
6361 bool sectioned([self showsSections]);
6363 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6364 [sections_ addObject:section];
6367 _profile(PackageTable$reloadData$Section)
6368 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6372 _profile(PackageTable$reloadData$Section$Package)
6373 package = [packages_ objectAtIndex:offset];
6374 index = [package index];
6377 if (sectioned && (section == nil || [section index] != index)) {
6378 _profile(PackageTable$reloadData$Section$Allocate)
6379 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6382 [index_ addObject:[section name]];
6383 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6385 _profile(PackageTable$reloadData$Section$Add)
6386 [sections_ addObject:section];
6390 [section addToCount];
6395 [self updateHeight];
6397 _profile(PackageTable$reloadData$List)
6398 [(UITableView *) list_ setDataSource:self];
6403 - (void) reloadData {
6406 if ([self shouldYield])
6407 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6412 - (void) resetCursor {
6413 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6416 - (void) clearData {
6417 [self updateHeight];
6419 [list_ setDataSource:nil];
6427 /* Filtered Package List Controller {{{ */
6428 @interface FilteredPackageListController : PackageListController {
6431 _H<NSObject> object_;
6434 - (void) setObject:(id)object;
6435 - (void) setObject:(id)object forFilter:(SEL)filter;
6438 - (void) setFilter:(SEL)filter;
6440 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6444 @implementation FilteredPackageListController
6450 - (void) setFilter:(SEL)filter {
6451 @synchronized (self) {
6454 /* XXX: this is an unsafe optimization of doomy hell */
6455 Method method(class_getInstanceMethod([Package class], filter));
6456 _assert(method != NULL);
6457 imp_ = method_getImplementation(method);
6458 _assert(imp_ != NULL);
6461 - (void) setObject:(id)object {
6462 @synchronized (self) {
6466 - (void) setObject:(id)object forFilter:(SEL)filter {
6467 @synchronized (self) {
6468 [self setFilter:filter];
6469 [self setObject:object];
6472 - (NSMutableArray *) _reloadPackages {
6473 @synchronized (database_) {
6474 era_ = [database_ era];
6475 NSArray *packages([database_ packages]);
6477 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6481 _H<NSObject> object;
6483 @synchronized (self) {
6489 _profile(PackageTable$reloadData$Filter)
6490 for (Package *package in packages)
6491 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6492 [filtered addObject:package];
6498 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6499 if ((self = [super initWithDatabase:database title:title]) != nil) {
6500 [self setFilter:filter];
6501 [self setObject:object];
6508 /* Home Controller {{{ */
6509 @interface HomeController : CydiaWebViewController {
6514 @implementation HomeController
6517 if ((self = [super init]) != nil) {
6518 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6523 - (NSURL *) navigationURL {
6524 return [NSURL URLWithString:@"cydia://home"];
6527 - (void) aboutButtonClicked {
6528 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6530 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6531 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6532 [alert setCancelButtonIndex:0];
6535 @"Copyright \u00a9 2008-2011\n"
6538 "Jay Freeman (saurik)\n"
6539 "saurik@saurik.com\n"
6540 "http://www.saurik.com/"
6546 - (UIBarButtonItem *) leftButton {
6547 return [[[UIBarButtonItem alloc]
6548 initWithTitle:UCLocalize("ABOUT")
6549 style:UIBarButtonItemStylePlain
6551 action:@selector(aboutButtonClicked)
6557 /* Manage Controller {{{ */
6558 @interface ManageController : CydiaWebViewController {
6561 - (void) queueStatusDidChange;
6565 @implementation ManageController
6568 if ((self = [super init]) != nil) {
6569 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6573 - (NSURL *) navigationURL {
6574 return [NSURL URLWithString:@"cydia://manage"];
6577 - (UIBarButtonItem *) leftButton {
6578 return [[[UIBarButtonItem alloc]
6579 initWithTitle:UCLocalize("SETTINGS")
6580 style:UIBarButtonItemStylePlain
6582 action:@selector(settingsButtonClicked)
6586 - (void) settingsButtonClicked {
6587 [delegate_ showSettings];
6590 - (void) queueButtonClicked {
6594 - (UIBarButtonItem *) rightButton {
6595 return Queuing_ ? [[[UIBarButtonItem alloc]
6596 initWithTitle:UCLocalize("QUEUE")
6597 style:UIBarButtonItemStyleDone
6599 action:@selector(queueButtonClicked)
6600 ] autorelease] : nil;
6603 - (void) queueStatusDidChange {
6604 [self applyRightButton];
6607 - (bool) isLoading {
6608 return !Queuing_ && [super isLoading];
6614 /* Refresh Bar {{{ */
6615 @interface RefreshBar : UINavigationBar {
6616 _H<UIProgressIndicator> indicator_;
6617 _H<UITextLabel> prompt_;
6618 _H<UIProgressBar> progress_;
6619 _H<UINavigationButton> cancel_;
6624 @implementation RefreshBar
6626 - (void) positionViews {
6627 CGRect frame = [cancel_ frame];
6628 frame.size = [cancel_ sizeThatFits:frame.size];
6629 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6630 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6631 [cancel_ setFrame:frame];
6633 CGSize prgsize = {75, 100};
6635 [self frame].size.width - prgsize.width - 10,
6636 ([self frame].size.height - prgsize.height) / 2
6638 [progress_ setFrame:prgrect];
6640 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6641 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6642 CGRect indrect = {{indoffset, indoffset}, indsize};
6643 [indicator_ setFrame:indrect];
6645 CGSize prmsize = {215, indsize.height + 4};
6647 indoffset * 2 + indsize.width,
6648 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6650 [prompt_ setFrame:prmrect];
6653 - (void) setFrame:(CGRect)frame {
6654 [super setFrame:frame];
6655 [self positionViews];
6658 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6659 if ((self = [super initWithFrame:frame]) != nil) {
6660 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6662 [self setBarStyle:UIBarStyleBlack];
6664 UIBarStyle barstyle([self _barStyle:NO]);
6665 bool ugly(barstyle == UIBarStyleDefault);
6667 UIProgressIndicatorStyle style = ugly ?
6668 UIProgressIndicatorStyleMediumBrown :
6669 UIProgressIndicatorStyleMediumWhite;
6671 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6672 [(UIProgressIndicator *) indicator_ setStyle:style];
6673 [indicator_ startAnimation];
6674 [self addSubview:indicator_];
6676 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6677 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6678 [prompt_ setBackgroundColor:[UIColor clearColor]];
6679 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6680 [self addSubview:prompt_];
6682 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6683 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6684 [(UIProgressBar *) progress_ setStyle:0];
6685 [self addSubview:progress_];
6687 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6688 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6689 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6690 [cancel_ setBarStyle:barstyle];
6692 [self positionViews];
6696 - (void) setCancellable:(bool)cancellable {
6698 [self addSubview:cancel_];
6700 [cancel_ removeFromSuperview];
6704 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6705 [progress_ setProgress:0];
6709 [self setCancellable:NO];
6712 - (void) setPrompt:(NSString *)prompt {
6713 [prompt_ setText:prompt];
6716 - (void) setProgress:(float)progress {
6717 [progress_ setProgress:progress];
6723 /* Cydia Navigation Controller Interface {{{ */
6724 @interface UINavigationController (Cydia)
6726 - (NSArray *) navigationURLCollection;
6727 - (void) unloadData;
6732 /* Cydia Tab Bar Controller {{{ */
6733 @interface CYTabBarController : UITabBarController <
6734 UITabBarControllerDelegate,
6737 _transient Database *database_;
6738 _H<RefreshBar, 1> refreshbar_;
6742 // XXX: ok, "updatedelegate_"?...
6743 _transient NSObject<CydiaDelegate> *updatedelegate_;
6745 _H<UIViewController> remembered_;
6746 _transient UIViewController *transient_;
6749 - (NSArray *) navigationURLCollection;
6750 - (void) dropBar:(BOOL)animated;
6751 - (void) beginUpdate;
6752 - (void) raiseBar:(BOOL)animated;
6754 - (void) unloadData;
6758 @implementation CYTabBarController
6760 - (void) didReceiveMemoryWarning {
6761 [super didReceiveMemoryWarning];
6763 // presenting a UINavigationController on 2.x does not update its transitionView
6764 // it thereby will not allow its topViewController to be unloaded by memory pressure
6765 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6766 UIViewController *selected([self selectedViewController]);
6767 for (UINavigationController *controller in [self viewControllers])
6768 if (controller != selected)
6769 if (UIViewController *top = [controller topViewController])
6774 - (void) setUnselectedViewController:(UIViewController *)transient {
6775 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6776 if (transient != nil) {
6777 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6778 [self setSelectedIndex:0];
6782 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6783 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6784 transient = navigation;
6786 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6787 if (transient != nil) {
6788 if (transient_ == nil)
6789 remembered_ = [controllers objectAtIndex:0];
6790 transient_ = transient;
6791 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6792 [controllers replaceObjectAtIndex:0 withObject:transient_];
6793 [self setSelectedIndex:0];
6794 [self setViewControllers:controllers];
6795 [self concealTabBarSelection];
6796 } else if (remembered_ != nil) {
6797 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6798 transient_ = transient;
6799 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6801 [self setViewControllers:controllers];
6802 [self revealTabBarSelection];
6806 - (UIViewController *) unselectedViewController {
6810 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6811 if ([self unselectedViewController])
6812 [self setUnselectedViewController:nil];
6814 // presenting a UINavigationController on 2.x does not update its transitionView
6815 // if this view was unloaded, the tranitionView may currently be presenting nothing
6816 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6817 UINavigationController *navigation((UINavigationController *) viewController);
6818 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6819 [navigation popViewControllerAnimated:NO];
6823 - (NSArray *) navigationURLCollection {
6824 NSMutableArray *items([NSMutableArray array]);
6826 // XXX: Should this deal with transient view controllers?
6827 for (id navigation in [self viewControllers]) {
6828 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6830 [items addObject:stack];
6836 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6837 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6838 [self setUnselectedViewController:nil];
6840 [super dismissModalViewControllerAnimated:YES];
6843 - (void) unloadData {
6846 for (UINavigationController *controller in [self viewControllers])
6847 [controller unloadData];
6849 if (UIViewController *selected = [self selectedViewController])
6850 [selected reloadData];
6852 if (UIViewController *unselected = [self unselectedViewController]) {
6853 [unselected unloadData];
6854 [unselected reloadData];
6859 [[NSNotificationCenter defaultCenter] removeObserver:self];
6864 - (id) initWithDatabase:(Database *)database {
6865 if ((self = [super init]) != nil) {
6866 database_ = database;
6867 [self setDelegate:self];
6869 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6870 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6872 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6876 - (void) setUpdate:(NSDate *)date {
6880 - (void) beginUpdate {
6881 [(RefreshBar *) refreshbar_ start];
6884 [updatedelegate_ retainNetworkActivityIndicator];
6888 detachNewThreadSelector:@selector(performUpdate)
6894 - (void) performUpdate {
6895 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6898 status.setDelegate(self);
6899 [database_ updateWithStatus:status];
6902 performSelectorOnMainThread:@selector(completeUpdate)
6910 - (void) stopUpdateWithSelector:(SEL)selector {
6912 [updatedelegate_ releaseNetworkActivityIndicator];
6914 [self raiseBar:YES];
6917 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6920 - (void) completeUpdate {
6923 [self stopUpdateWithSelector:@selector(reloadData)];
6926 - (void) cancelUpdate {
6927 [self stopUpdateWithSelector:@selector(updateData)];
6930 - (void) cancelPressed {
6931 [self cancelUpdate];
6938 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6939 [refreshbar_ setPrompt:[event compoundMessage]];
6942 - (bool) isProgressCancelled {
6946 - (void) setProgressCancellable:(NSNumber *)cancellable {
6947 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6950 - (void) setProgressPercent:(NSNumber *)percent {
6951 [refreshbar_ setProgress:[percent floatValue]];
6954 - (void) setProgressStatus:(NSDictionary *)status {
6956 [self setProgressPercent:[status objectForKey:@"Percent"]];
6959 - (void) setUpdateDelegate:(id)delegate {
6960 updatedelegate_ = delegate;
6963 - (UIView *) transitionView {
6964 if ([self respondsToSelector:@selector(_transitionView)])
6965 return [self _transitionView];
6967 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6970 - (void) dropBar:(BOOL)animated {
6975 UIView *transition([self transitionView]);
6976 [[self view] addSubview:refreshbar_];
6978 CGRect barframe([refreshbar_ frame]);
6980 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6981 barframe.origin.y = CYStatusBarHeight();
6983 barframe.origin.y = 0;
6985 [refreshbar_ setFrame:barframe];
6988 [UIView beginAnimations:nil context:NULL];
6990 CGRect viewframe = [transition frame];
6991 viewframe.origin.y += barframe.size.height;
6992 viewframe.size.height -= barframe.size.height;
6993 [transition setFrame:viewframe];
6996 [UIView commitAnimations];
6998 // Ensure bar has the proper width for our view, it might have changed
6999 barframe.size.width = viewframe.size.width;
7000 [refreshbar_ setFrame:barframe];
7003 - (void) raiseBar:(BOOL)animated {
7008 UIView *transition([self transitionView]);
7009 [refreshbar_ removeFromSuperview];
7011 CGRect barframe([refreshbar_ frame]);
7014 [UIView beginAnimations:nil context:NULL];
7016 CGRect viewframe = [transition frame];
7017 viewframe.origin.y -= barframe.size.height;
7018 viewframe.size.height += barframe.size.height;
7019 [transition setFrame:viewframe];
7022 [UIView commitAnimations];
7025 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7026 bool dropped(dropped_);
7031 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7037 - (void) statusBarFrameChanged:(NSNotification *)notification {
7047 /* Cydia Navigation Controller Implementation {{{ */
7048 @implementation UINavigationController (Cydia)
7050 - (NSArray *) navigationURLCollection {
7051 NSMutableArray *stack([NSMutableArray array]);
7053 for (CyteViewController *controller in [self viewControllers]) {
7054 NSString *url = [[controller navigationURL] absoluteString];
7056 [stack addObject:url];
7062 - (void) reloadData {
7065 UIViewController *visible([self visibleViewController]);
7067 [visible reloadData];
7069 // on the iPad, this view controller is ALSO visible. :(
7071 if (UIViewController *top = [self topViewController])
7076 - (void) unloadData {
7077 for (CyteViewController *page in [self viewControllers])
7086 /* Cydia:// Protocol {{{ */
7087 @interface CydiaURLProtocol : NSURLProtocol {
7092 @implementation CydiaURLProtocol
7094 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7095 NSURL *url([request URL]);
7099 NSString *scheme([[url scheme] lowercaseString]);
7100 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7102 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7108 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7112 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7113 id<NSURLProtocolClient> client([self client]);
7115 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7117 NSData *data(UIImagePNGRepresentation(icon));
7119 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7120 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7121 [client URLProtocol:self didLoadData:data];
7122 [client URLProtocolDidFinishLoading:self];
7126 - (void) startLoading {
7127 id<NSURLProtocolClient> client([self client]);
7128 NSURLRequest *request([self request]);
7130 NSURL *url([request URL]);
7131 NSString *href([url absoluteString]);
7132 NSString *scheme([[url scheme] lowercaseString]);
7136 if ([scheme isEqualToString:@"cydia"])
7137 path = [href substringFromIndex:8];
7138 else if ([scheme isEqualToString:@"about"])
7139 path = [href substringFromIndex:12];
7140 else _assert(false);
7142 NSRange slash([path rangeOfString:@"/"]);
7145 if (slash.location == NSNotFound) {
7149 command = [path substringToIndex:slash.location];
7150 path = [path substringFromIndex:(slash.location + 1)];
7153 Database *database([Database sharedInstance]);
7155 if ([command isEqualToString:@"package-icon"]) {
7158 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7159 Package *package([database packageWithName:path]);
7163 UIImage *icon([package icon]);
7164 [self _returnPNGWithImage:icon forRequest:request];
7165 } else if ([command isEqualToString:@"uikit-image"]) {
7168 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7169 UIImage *icon(_UIImageWithName(path));
7170 [self _returnPNGWithImage:icon forRequest:request];
7171 } else if ([command isEqualToString:@"section-icon"]) {
7174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7175 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7177 icon = [UIImage applicationImageNamed:@"unknown.png"];
7178 [self _returnPNGWithImage:icon forRequest:request];
7180 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7184 - (void) stopLoading {
7190 /* Section Controller {{{ */
7191 @interface SectionController : FilteredPackageListController {
7192 _H<NSString> section_;
7195 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7199 @implementation SectionController
7201 - (NSURL *) navigationURL {
7202 NSString *name = section_;
7206 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7209 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7212 title = UCLocalize("ALL_PACKAGES");
7213 else if (![name isEqual:@""])
7214 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7216 title = UCLocalize("NO_SECTION");
7218 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7225 /* Sections Controller {{{ */
7226 @interface SectionsController : CyteViewController <
7227 UITableViewDataSource,
7230 _transient Database *database_;
7231 _H<NSMutableArray> sections_;
7232 _H<NSMutableArray> filtered_;
7233 _H<UITableView, 2> list_;
7236 - (id) initWithDatabase:(Database *)database;
7237 - (void) editButtonClicked;
7241 @implementation SectionsController
7243 - (NSURL *) navigationURL {
7244 return [NSURL URLWithString:@"cydia://sections"];
7247 - (void) updateNavigationItem {
7248 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7249 if ([sections_ count] == 0) {
7250 [[self navigationItem] setRightBarButtonItem:nil];
7252 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7253 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7255 action:@selector(editButtonClicked)
7256 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7260 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7261 [super setEditing:editing animated:animated];
7266 [delegate_ updateData];
7268 [self updateNavigationItem];
7271 - (void) viewDidAppear:(BOOL)animated {
7272 [super viewDidAppear:animated];
7273 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7276 - (void) viewWillDisappear:(BOOL)animated {
7277 [super viewWillDisappear:animated];
7278 if ([self isEditing]) [self setEditing:NO];
7281 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7282 Section *section = nil;
7283 int index = [indexPath row];
7284 if (![self isEditing]) {
7287 section = [filtered_ objectAtIndex:index];
7289 section = [sections_ objectAtIndex:index];
7294 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7295 if ([self isEditing])
7296 return [sections_ count];
7298 return [filtered_ count] + 1;
7301 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7305 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7306 static NSString *reuseIdentifier = @"SectionCell";
7308 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7310 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7312 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7317 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7318 if ([self isEditing])
7321 Section *section = [self sectionAtIndexPath:indexPath];
7323 SectionController *controller = [[[SectionController alloc]
7324 initWithDatabase:database_
7325 section:[section name]
7327 [controller setDelegate:delegate_];
7329 [[self navigationController] pushViewController:controller animated:YES];
7333 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7334 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7335 [list_ setRowHeight:45.0f];
7336 [(UITableView *) list_ setDataSource:self];
7337 [list_ setDelegate:self];
7338 [self setView:list_];
7341 - (void) viewDidLoad {
7342 [super viewDidLoad];
7344 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7347 - (void) releaseSubviews {
7353 [super releaseSubviews];
7356 - (id) initWithDatabase:(Database *)database {
7357 if ((self = [super init]) != nil) {
7358 database_ = database;
7362 - (void) reloadData {
7365 NSArray *packages = [database_ packages];
7367 sections_ = [NSMutableArray arrayWithCapacity:16];
7368 filtered_ = [NSMutableArray arrayWithCapacity:16];
7370 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7373 for (Package *package in packages) {
7374 NSString *name([package section]);
7375 NSString *key(name == nil ? @"" : name);
7379 _profile(SectionsView$reloadData$Section)
7380 section = [sections objectForKey:key];
7381 if (section == nil) {
7382 _profile(SectionsView$reloadData$Section$Allocate)
7383 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7384 [sections setObject:section forKey:key];
7389 [section addToCount];
7391 _profile(SectionsView$reloadData$Filter)
7392 if (![package valid] || ![package visible])
7400 [sections_ addObjectsFromArray:[sections allValues]];
7402 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7404 for (Section *section in (id) sections_) {
7405 size_t count([section row]);
7409 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7410 [section setCount:count];
7411 [filtered_ addObject:section];
7414 [self updateNavigationItem];
7419 - (void) editButtonClicked {
7420 [self setEditing:![self isEditing] animated:YES];
7426 /* Changes Controller {{{ */
7427 @interface ChangesController : CyteViewController <
7428 UITableViewDataSource,
7431 _transient Database *database_;
7433 _H<NSArray> packages_;
7434 _H<NSMutableArray> sections_;
7435 _H<UITableView, 2> list_;
7439 - (id) initWithDatabase:(Database *)database;
7443 @implementation ChangesController
7445 - (NSURL *) navigationURL {
7446 return [NSURL URLWithString:@"cydia://changes"];
7449 - (void) viewDidAppear:(BOOL)animated {
7450 [super viewDidAppear:animated];
7451 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7454 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7455 NSInteger count([sections_ count]);
7456 return count == 0 ? 1 : count;
7459 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7460 if ([sections_ count] == 0)
7462 return [[sections_ objectAtIndex:section] name];
7465 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7466 if ([sections_ count] == 0)
7468 return [[sections_ objectAtIndex:section] count];
7471 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7472 @synchronized (database_) {
7473 if ([database_ era] != era_)
7476 NSUInteger sectionIndex([path section]);
7477 if (sectionIndex >= [sections_ count])
7479 Section *section([sections_ objectAtIndex:sectionIndex]);
7480 NSInteger row([path row]);
7481 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7484 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7485 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7487 cell = [[[PackageCell alloc] init] autorelease];
7489 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7490 [cell setPackage:package asSummary:false];
7494 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7495 Package *package([self packageAtIndexPath:path]);
7496 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7497 [view setDelegate:delegate_];
7498 [[self navigationController] pushViewController:view animated:YES];
7502 - (void) refreshButtonClicked {
7503 [delegate_ beginUpdate];
7504 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7507 - (void) upgradeButtonClicked {
7508 [delegate_ distUpgrade];
7509 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7513 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
7514 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7515 [list_ setRowHeight:73];
7516 [(UITableView *) list_ setDataSource:self];
7517 [list_ setDelegate:self];
7518 [self setView:list_];
7521 - (void) viewDidLoad {
7522 [super viewDidLoad];
7524 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7527 - (void) releaseSubviews {
7533 [super releaseSubviews];
7536 - (id) initWithDatabase:(Database *)database {
7537 if ((self = [super init]) != nil) {
7538 database_ = database;
7542 - (NSMutableArray *) _reloadPackages {
7543 @synchronized (database_) {
7544 era_ = [database_ era];
7545 NSArray *packages([database_ packages]);
7547 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7550 _profile(ChangesController$_reloadPackages$Filter)
7551 for (Package *package in packages)
7552 if ([package upgradableAndEssential:YES] || [package visible])
7553 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7556 _profile(ChangesController$_reloadPackages$radixSort)
7557 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7564 - (void) _reloadData {
7569 UIProgressHUD *hud([delegate_ addProgressHUD]);
7570 [hud setText:UCLocalize("LOADING")];
7571 //NSLog(@"HUD:%@::%@", delegate_, hud);
7572 packages = [self yieldToSelector:@selector(_reloadPackages)];
7573 [delegate_ removeProgressHUD:hud];
7575 packages = [self _reloadPackages];
7578 @synchronized (database_) {
7579 if (era_ != [database_ era])
7582 packages_ = packages;
7583 sections_ = [NSMutableArray arrayWithCapacity:16];
7585 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7586 Section *ignored = nil;
7587 Section *section = nil;
7591 bool unseens = false;
7593 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7595 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7596 Package *package = [packages_ objectAtIndex:offset];
7598 BOOL uae = [package upgradableAndEssential:YES];
7602 time_t seen([package seen]);
7604 if (section == nil || last != seen) {
7608 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7611 _profile(ChangesController$reloadData$Allocate)
7612 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7613 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7614 [sections_ addObject:section];
7618 [section addToCount];
7619 } else if ([package ignored]) {
7620 if (ignored == nil) {
7621 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7623 [ignored addToCount];
7626 [upgradable addToCount];
7631 CFRelease(formatter);
7634 Section *last = [sections_ lastObject];
7635 size_t count = [last count];
7636 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7637 [sections_ removeLastObject];
7640 if ([ignored count] != 0)
7641 [sections_ insertObject:ignored atIndex:0];
7643 [sections_ insertObject:upgradable atIndex:0];
7647 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7648 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7649 style:UIBarButtonItemStylePlain
7651 action:@selector(upgradeButtonClicked)
7652 ] autorelease]) animated:YES];
7654 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7655 initWithTitle:UCLocalize("REFRESH")
7656 style:UIBarButtonItemStylePlain
7658 action:@selector(refreshButtonClicked)
7659 ] autorelease]) animated:YES];
7664 - (void) reloadData {
7666 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7671 /* Search Controller {{{ */
7672 @interface SearchController : FilteredPackageListController <
7675 _H<UISearchBar, 1> search_;
7679 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7680 - (void) reloadData;
7684 @implementation SearchController
7686 - (NSURL *) navigationURL {
7687 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7688 return [NSURL URLWithString:@"cydia://search"];
7690 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7693 - (void) useSearch {
7694 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7699 - (void) viewWillAppear:(BOOL)animated {
7700 [super viewWillAppear:animated];
7702 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7706 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7707 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7712 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7713 [search_ resignFirstResponder];
7717 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7718 [search_ setText:@""];
7719 [self searchBarButtonClicked:searchBar];
7722 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7723 [self searchBarButtonClicked:searchBar];
7726 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7727 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7731 - (bool) shouldYield {
7735 - (bool) shouldBlock {
7736 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7739 - (bool) isSummarized {
7740 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7743 - (bool) showsSections {
7747 - (NSMutableArray *) _reloadPackages {
7748 NSMutableArray *packages([super _reloadPackages]);
7749 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7750 [packages radixSortUsingSelector:@selector(rank)];
7754 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7755 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7756 search_ = [[[UISearchBar alloc] init] autorelease];
7757 [search_ setDelegate:self];
7760 [search_ setText:query];
7764 - (void) viewDidAppear:(BOOL)animated {
7765 [super viewDidAppear:animated];
7767 if (!searchloaded_) {
7768 searchloaded_ = YES;
7769 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7770 [search_ layoutSubviews];
7771 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7773 UITextField *textField;
7774 if ([search_ respondsToSelector:@selector(searchField)])
7775 textField = [search_ searchField];
7777 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7779 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7780 [textField setEnablesReturnKeyAutomatically:NO];
7781 [[self navigationItem] setTitleView:textField];
7785 - (void) reloadData {
7786 id object([search_ text]);
7787 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7788 object = [object componentsSeparatedByString:@" "];
7790 [self setObject:object];
7796 - (void) didSelectPackage:(Package *)package {
7797 [search_ resignFirstResponder];
7798 [super didSelectPackage:package];
7803 /* Package Settings Controller {{{ */
7804 @interface PackageSettingsController : CyteViewController <
7805 UITableViewDataSource,
7808 _transient Database *database_;
7810 _H<Package> package_;
7811 _H<UITableView, 2> table_;
7812 _H<UISwitch> subscribedSwitch_;
7813 _H<UISwitch> ignoredSwitch_;
7814 _H<UITableViewCell> subscribedCell_;
7815 _H<UITableViewCell> ignoredCell_;
7818 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7822 @implementation PackageSettingsController
7824 - (NSURL *) navigationURL {
7825 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7828 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7829 if (package_ == nil)
7832 if ([package_ installed] == nil)
7838 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7839 if (package_ == nil)
7842 // both sections contain just one item right now.
7846 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7850 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7852 return UCLocalize("SHOW_ALL_CHANGES_EX");
7854 return UCLocalize("IGNORE_UPGRADES_EX");
7857 - (void) onSubscribed:(id)control {
7858 bool value([control isOn]);
7859 if (package_ == nil)
7861 if ([package_ setSubscribed:value])
7862 [delegate_ updateData];
7865 - (void) _updateIgnored {
7866 const char *package([name_ UTF8String]);
7867 bool on([ignoredSwitch_ isOn]);
7869 pid_t pid(ExecFork());
7871 FILE *dpkg(popen("dpkg --set-selections", "w"));
7872 fwrite(package, strlen(package), 1, dpkg);
7875 fwrite(" hold\n", 6, 1, dpkg);
7877 fwrite(" install\n", 9, 1, dpkg);
7888 - (void) onIgnored:(id)control {
7889 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7890 [invocation setTarget:self];
7891 [invocation setSelector:@selector(_updateIgnored)];
7893 [delegate_ reloadDataWithInvocation:invocation];
7896 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7897 if (package_ == nil)
7900 switch ([indexPath section]) {
7901 case 0: return subscribedCell_;
7902 case 1: return ignoredCell_;
7911 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7912 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7913 [self setView:view];
7915 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7916 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7917 [(UITableView *) table_ setDataSource:self];
7918 [table_ setDelegate:self];
7919 [view addSubview:table_];
7921 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7922 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7923 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7925 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7926 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7927 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7929 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7930 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7931 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7932 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7934 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7935 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7936 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7937 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7940 - (void) viewDidLoad {
7941 [super viewDidLoad];
7943 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7946 - (void) releaseSubviews {
7948 subscribedCell_ = nil;
7950 ignoredSwitch_ = nil;
7951 subscribedSwitch_ = nil;
7953 [super releaseSubviews];
7956 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7957 if ((self = [super init]) != nil) {
7958 database_ = database;
7963 - (void) reloadData {
7966 package_ = [database_ packageWithName:name_];
7968 if (package_ != nil) {
7969 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7970 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7971 } // XXX: what now, G?
7973 [table_ reloadData];
7979 /* Installed Controller {{{ */
7980 @interface InstalledController : FilteredPackageListController {
7984 - (id) initWithDatabase:(Database *)database;
7986 - (void) updateRoleButton;
7987 - (void) queueStatusDidChange;
7991 @implementation InstalledController
7993 - (NSURL *) navigationURL {
7994 return [NSURL URLWithString:@"cydia://installed"];
7997 - (id) initWithDatabase:(Database *)database {
7998 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7999 [self updateRoleButton];
8000 [self queueStatusDidChange];
8005 - (void) queueButtonClicked {
8010 - (void) queueStatusDidChange {
8014 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8015 initWithTitle:UCLocalize("QUEUE")
8016 style:UIBarButtonItemStyleDone
8018 action:@selector(queueButtonClicked)
8021 [[self navigationItem] setLeftBarButtonItem:nil];
8027 - (void) updateRoleButton {
8028 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8029 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8030 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8031 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8033 action:@selector(roleButtonClicked)
8037 - (void) roleButtonClicked {
8038 [self setObject:[NSNumber numberWithBool:expert_]];
8042 [self updateRoleButton];
8048 /* Source Cell {{{ */
8049 @interface SourceCell : CyteTableViewCell <
8050 CyteTableViewCellDelegate
8054 _H<NSString> origin_;
8055 _H<NSString> label_;
8058 - (void) setSource:(Source *)source;
8062 @implementation SourceCell
8064 - (void) _setImage:(NSArray *)data {
8065 if ([url_ isEqual:[data objectAtIndex:0]]) {
8066 icon_ = [data objectAtIndex:1];
8067 [content_ setNeedsDisplay];
8071 - (void) _setSource:(NSURL *) url {
8072 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8074 if (NSData *data = [NSURLConnection
8075 sendSynchronousRequest:[NSURLRequest
8077 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8081 returningResponse:NULL
8084 if (UIImage *image = [UIImage imageWithData:data])
8085 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8090 - (void) setSource:(Source *)source {
8091 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8093 origin_ = [source name];
8094 label_ = [source rooturi];
8096 [content_ setNeedsDisplay];
8098 url_ = [source iconURL];
8099 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8102 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8103 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8104 UIView *content([self contentView]);
8105 CGRect bounds([content bounds]);
8107 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8108 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8109 [content_ setBackgroundColor:[UIColor whiteColor]];
8110 [content addSubview:content_];
8112 [content_ setDelegate:self];
8113 [content_ setOpaque:YES];
8115 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8119 - (NSString *) accessibilityLabel {
8123 - (void) drawContentRect:(CGRect)rect {
8124 bool highlighted(highlighted_);
8125 float width(rect.size.width);
8129 rect.size = [(UIImage *) icon_ size];
8131 while (rect.size.width > 32 || rect.size.height > 32) {
8132 rect.size.width /= 2;
8133 rect.size.height /= 2;
8136 rect.origin.x = 25 - rect.size.width / 2;
8137 rect.origin.y = 25 - rect.size.height / 2;
8139 [icon_ drawInRect:rect];
8147 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8151 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8156 /* Source Controller {{{ */
8157 @interface SourceController : FilteredPackageListController {
8158 _transient Source *source_;
8162 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8166 @implementation SourceController
8168 - (NSURL *) navigationURL {
8169 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8172 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8173 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8175 key_ = [source key];
8179 - (void) reloadData {
8180 source_ = [database_ sourceWithKey:key_];
8181 key_ = [source_ key];
8182 [self setObject:source_];
8184 [[self navigationItem] setTitle:[source_ label]];
8191 /* Sources Controller {{{ */
8192 @interface SourcesController : CyteViewController <
8193 UITableViewDataSource,
8196 _transient Database *database_;
8199 _H<UITableView, 2> list_;
8200 _H<NSMutableArray> sources_;
8204 _H<UIProgressHUD> hud_;
8207 //NSURLConnection *installer_;
8208 NSURLConnection *trivial_;
8209 NSURLConnection *trivial_bz2_;
8210 NSURLConnection *trivial_gz_;
8211 //NSURLConnection *automatic_;
8216 - (id) initWithDatabase:(Database *)database;
8217 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8221 @implementation SourcesController
8223 - (void) _releaseConnection:(NSURLConnection *)connection {
8224 if (connection != nil) {
8225 [connection cancel];
8226 //[connection setDelegate:nil];
8227 [connection release];
8232 //[self _releaseConnection:installer_];
8233 [self _releaseConnection:trivial_];
8234 [self _releaseConnection:trivial_gz_];
8235 [self _releaseConnection:trivial_bz2_];
8236 //[self _releaseConnection:automatic_];
8241 - (NSURL *) navigationURL {
8242 return [NSURL URLWithString:@"cydia://sources"];
8245 - (void) viewDidAppear:(BOOL)animated {
8246 [super viewDidAppear:animated];
8247 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8250 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8254 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8258 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8259 return [sources_ count];
8262 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8263 @synchronized (database_) {
8264 if ([database_ era] != era_)
8267 return [sources_ objectAtIndex:[indexPath row]];
8270 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8271 static NSString *cellIdentifier = @"SourceCell";
8273 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8274 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8275 [cell setSource:[self sourceAtIndexPath:indexPath]];
8276 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8281 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8282 Source *source = [self sourceAtIndexPath:indexPath];
8284 SourceController *controller = [[[SourceController alloc]
8285 initWithDatabase:database_
8289 [controller setDelegate:delegate_];
8291 [[self navigationController] pushViewController:controller animated:YES];
8294 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8295 Source *source = [self sourceAtIndexPath:indexPath];
8296 return [source record] != nil;
8299 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8300 if (editingStyle == UITableViewCellEditingStyleDelete) {
8301 Source *source = [self sourceAtIndexPath:indexPath];
8302 [Sources_ removeObjectForKey:[source key]];
8303 [delegate_ syncData];
8308 [delegate_ addTrivialSource:href_];
8311 [delegate_ syncData];
8314 - (NSString *) getWarning {
8315 NSString *href(href_);
8316 NSRange colon([href rangeOfString:@"://"]);
8317 if (colon.location != NSNotFound)
8318 href = [href substringFromIndex:(colon.location + 3)];
8319 href = [href stringByAddingPercentEscapes];
8320 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8322 NSURL *url([NSURL URLWithString:href]);
8324 NSStringEncoding encoding;
8325 NSError *error(nil);
8327 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8328 return [warning length] == 0 ? nil : warning;
8332 - (void) _endConnection:(NSURLConnection *)connection {
8333 // XXX: the memory management in this method is horribly awkward
8335 NSURLConnection **field = NULL;
8336 if (connection == trivial_)
8338 else if (connection == trivial_bz2_)
8339 field = &trivial_bz2_;
8340 else if (connection == trivial_gz_)
8341 field = &trivial_gz_;
8342 _assert(field != NULL);
8343 [connection release];
8348 trivial_bz2_ == nil &&
8351 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8353 [delegate_ releaseNetworkActivityIndicator];
8355 [delegate_ removeProgressHUD:hud_];
8359 if (warning != nil) {
8360 UIAlertView *alert = [[[UIAlertView alloc]
8361 initWithTitle:UCLocalize("SOURCE_WARNING")
8364 cancelButtonTitle:UCLocalize("CANCEL")
8366 UCLocalize("ADD_ANYWAY"),
8370 [alert setContext:@"warning"];
8371 [alert setNumberOfRows:1];
8374 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8380 } else if (error_ != nil) {
8381 UIAlertView *alert = [[[UIAlertView alloc]
8382 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8383 message:[error_ localizedDescription]
8385 cancelButtonTitle:UCLocalize("OK")
8386 otherButtonTitles:nil
8389 [alert setContext:@"urlerror"];
8394 UIAlertView *alert = [[[UIAlertView alloc]
8395 initWithTitle:UCLocalize("NOT_REPOSITORY")
8396 message:UCLocalize("NOT_REPOSITORY_EX")
8398 cancelButtonTitle:UCLocalize("OK")
8399 otherButtonTitles:nil
8402 [alert setContext:@"trivial"];
8412 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8413 switch ([response statusCode]) {
8419 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8420 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8422 [self _endConnection:connection];
8425 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8426 [self _endConnection:connection];
8429 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8430 NSURL *url([NSURL URLWithString:href]);
8432 NSMutableURLRequest *request = [NSMutableURLRequest
8434 cachePolicy:NSURLRequestUseProtocolCachePolicy
8435 timeoutInterval:120.0
8438 [request setHTTPMethod:method];
8440 if (Machine_ != NULL)
8441 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8443 if ([url isCydiaSecure]) {
8444 if (UniqueID_ != nil) {
8445 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8446 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8450 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8453 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8454 NSString *context([alert context]);
8456 if ([context isEqualToString:@"source"]) {
8459 NSString *href = [[alert textField] text];
8461 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8463 if (![href hasSuffix:@"/"])
8464 href_ = [href stringByAppendingString:@"/"];
8468 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8469 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8470 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8471 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8475 // XXX: this is stupid
8476 hud_ = [delegate_ addProgressHUD];
8477 [hud_ setText:UCLocalize("VERIFYING_URL")];
8478 [delegate_ retainNetworkActivityIndicator];
8487 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8488 } else if ([context isEqualToString:@"trivial"])
8489 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8490 else if ([context isEqualToString:@"urlerror"])
8491 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8492 else if ([context isEqualToString:@"warning"]) {
8495 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8504 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8509 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8510 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8511 [list_ setRowHeight:53];
8512 [(UITableView *) list_ setDataSource:self];
8513 [list_ setDelegate:self];
8514 [self setView:list_];
8517 - (void) viewDidLoad {
8518 [super viewDidLoad];
8520 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8521 [self updateButtonsForEditingStatus:NO animated:NO];
8524 - (void) releaseSubviews {
8529 [super releaseSubviews];
8532 - (id) initWithDatabase:(Database *)database {
8533 if ((self = [super init]) != nil) {
8534 database_ = database;
8538 - (void) reloadData {
8541 @synchronized (database_) {
8542 era_ = [database_ era];
8545 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8548 sources_ = [NSMutableArray arrayWithCapacity:16];
8549 [sources_ addObjectsFromArray:[database_ sources]];
8551 [sources_ sortUsingSelector:@selector(compareByName:)];
8554 int count([sources_ count]);
8556 for (int i = 0; i != count; i++) {
8557 if ([[sources_ objectAtIndex:i] record] == nil)
8562 [list_ setEditing:NO];
8563 [self updateButtonsForEditingStatus:NO animated:NO];
8567 - (void) showAddSourcePrompt {
8568 UIAlertView *alert = [[[UIAlertView alloc]
8569 initWithTitle:UCLocalize("ENTER_APT_URL")
8572 cancelButtonTitle:UCLocalize("CANCEL")
8574 UCLocalize("ADD_SOURCE"),
8578 [alert setContext:@"source"];
8580 [alert setNumberOfRows:1];
8581 [alert addTextFieldWithValue:@"http://" label:@""];
8583 UITextInputTraits *traits = [[alert textField] textInputTraits];
8584 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8585 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8586 [traits setKeyboardType:UIKeyboardTypeURL];
8587 // XXX: UIReturnKeyDone
8588 [traits setReturnKeyType:UIReturnKeyNext];
8593 - (void) addButtonClicked {
8594 [self showAddSourcePrompt];
8597 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8598 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8599 initWithTitle:UCLocalize("ADD")
8600 style:UIBarButtonItemStylePlain
8602 action:@selector(addButtonClicked)
8603 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8605 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8606 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8607 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8609 action:@selector(editButtonClicked)
8610 ] autorelease] animated:animated];
8612 if (IsWildcat_ && !editing)
8613 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8614 initWithTitle:UCLocalize("SETTINGS")
8615 style:UIBarButtonItemStylePlain
8617 action:@selector(settingsButtonClicked)
8621 - (void) settingsButtonClicked {
8622 [delegate_ showSettings];
8625 - (void) editButtonClicked {
8626 [list_ setEditing:![list_ isEditing] animated:YES];
8628 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8634 /* Settings Controller {{{ */
8635 @interface SettingsController : CyteViewController <
8636 UITableViewDataSource,
8639 _transient Database *database_;
8640 // XXX: ok, "roledelegate_"?...
8641 _transient id roledelegate_;
8642 _H<UITableView, 2> table_;
8643 _H<UISegmentedControl> segment_;
8644 _H<UIView> container_;
8647 - (void) showDoneButton;
8648 - (void) resizeSegmentedControl;
8652 @implementation SettingsController
8655 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8656 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8657 [table_ setDelegate:self];
8658 [(UITableView *) table_ setDataSource:self];
8659 [self setView:table_];
8661 NSArray *items = [NSArray arrayWithObjects:
8663 UCLocalize("HACKER"),
8664 UCLocalize("DEVELOPER"),
8666 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8667 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8668 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8669 [container_ addSubview:segment_];
8672 - (void) viewDidLoad {
8673 [super viewDidLoad];
8675 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8678 if ([Role_ isEqualToString:@"User"]) index = 0;
8679 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8680 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8682 [segment_ setSelectedSegmentIndex:index];
8683 [self showDoneButton];
8686 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8687 [self resizeSegmentedControl];
8690 - (void) releaseSubviews {
8695 [super releaseSubviews];
8698 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8699 if ((self = [super init]) != nil) {
8700 database_ = database;
8701 roledelegate_ = delegate;
8705 - (void) resizeSegmentedControl {
8706 CGFloat width = [[self view] frame].size.width;
8707 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8710 - (void) viewWillAppear:(BOOL)animated {
8711 [super viewWillAppear:animated];
8713 [self resizeSegmentedControl];
8716 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8717 [self resizeSegmentedControl];
8720 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8721 [self resizeSegmentedControl];
8725 NSString *role(nil);
8727 switch ([segment_ selectedSegmentIndex]) {
8728 case 0: role = @"User"; break;
8729 case 1: role = @"Hacker"; break;
8730 case 2: role = @"Developer"; break;
8735 if (![role isEqualToString:Role_]) {
8736 bool rolling(Role_ == nil);
8739 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8743 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8747 [roledelegate_ loadData];
8749 [roledelegate_ updateData];
8753 - (void) segmentChanged:(UISegmentedControl *)control {
8754 [self showDoneButton];
8757 - (void) saveAndClose {
8760 [[self navigationItem] setRightBarButtonItem:nil];
8761 [[self navigationController] dismissModalViewControllerAnimated:YES];
8764 - (void) doneButtonClicked {
8765 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8766 [spinner startAnimating];
8767 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8768 [[self navigationItem] setRightBarButtonItem:spinItem];
8770 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8773 - (void) showDoneButton {
8774 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8775 initWithTitle:UCLocalize("DONE")
8776 style:UIBarButtonItemStyleDone
8778 action:@selector(doneButtonClicked)
8779 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8782 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8783 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8787 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8791 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8792 return nil; // This method is required by the protocol.
8795 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8797 return UCLocalize("ROLE_EX");
8799 return [NSString stringWithFormat:
8800 @"%@: %@\n%@: %@\n%@: %@",
8801 UCLocalize("USER"), UCLocalize("USER_EX"),
8802 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8803 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8808 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8809 return section == 3 ? 44.0f : 0;
8812 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8813 return section == 3 ? container_ : nil;
8816 - (void) reloadData {
8819 [table_ reloadData];
8824 /* Stash Controller {{{ */
8825 @interface StashController : CyteViewController {
8826 _H<UIActivityIndicatorView> spinner_;
8827 _H<UILabel> status_;
8828 _H<UILabel> caption_;
8833 @implementation StashController
8836 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8837 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8838 [self setView:view];
8840 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8842 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8843 CGRect spinrect = [spinner_ frame];
8844 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8845 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8846 [spinner_ setFrame:spinrect];
8847 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8848 [view addSubview:spinner_];
8849 [spinner_ startAnimating];
8852 captrect.size.width = [[self view] frame].size.width;
8853 captrect.size.height = 40.0f;
8854 captrect.origin.x = 0;
8855 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8856 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8857 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8858 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8859 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8860 [caption_ setTextColor:[UIColor whiteColor]];
8861 [caption_ setBackgroundColor:[UIColor clearColor]];
8862 [caption_ setShadowColor:[UIColor blackColor]];
8863 [caption_ setTextAlignment:UITextAlignmentCenter];
8864 [view addSubview:caption_];
8867 statusrect.size.width = [[self view] frame].size.width;
8868 statusrect.size.height = 30.0f;
8869 statusrect.origin.x = 0;
8870 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8871 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8872 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8873 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8874 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8875 [status_ setTextColor:[UIColor whiteColor]];
8876 [status_ setBackgroundColor:[UIColor clearColor]];
8877 [status_ setShadowColor:[UIColor blackColor]];
8878 [status_ setTextAlignment:UITextAlignmentCenter];
8879 [view addSubview:status_];
8882 - (void) releaseSubviews {
8887 [super releaseSubviews];
8893 @interface CYURLCache : SDURLCache {
8898 @implementation CYURLCache
8900 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8903 else if ([event isEqualToString:@"no-cache"])
8905 else if ([event isEqualToString:@"store"])
8907 else if ([event isEqualToString:@"invalid"])
8909 else if ([event isEqualToString:@"memory"])
8911 else if ([event isEqualToString:@"disk"])
8913 else if ([event isEqualToString:@"miss"])
8916 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8920 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8921 if (NSURLResponse *response = [cached response])
8922 if (NSString *mime = [response MIMEType])
8923 if ([mime isEqualToString:@"text/cache-manifest"]) {
8924 NSURL *url([response URL]);
8927 NSLog(@"###: %@", [url absoluteString]);
8930 @synchronized (HostConfig_) {
8931 [CachedURLs_ addObject:url];
8935 [super storeCachedResponse:cached forRequest:request];
8940 @interface Cydia : UIApplication <
8941 ConfirmationControllerDelegate,
8944 UINavigationControllerDelegate,
8945 UITabBarControllerDelegate
8947 _H<UIWindow> window_;
8948 _H<CYTabBarController> tabbar_;
8949 _H<CydiaLoadingViewController> emulated_;
8951 _H<NSMutableArray> essential_;
8952 _H<NSMutableArray> broken_;
8954 Database *database_;
8956 _H<NSURL> starturl_;
8961 _H<StashController> stash_;
8970 @implementation Cydia
8972 - (void) beginUpdate {
8973 [tabbar_ beginUpdate];
8977 return [tabbar_ updating];
8981 if ([broken_ count] != 0) {
8982 int count = [broken_ count];
8984 UIAlertView *alert = [[[UIAlertView alloc]
8985 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8986 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8988 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8990 UCLocalize("TEMPORARY_IGNORE"),
8994 [alert setContext:@"fixhalf"];
8995 [alert setNumberOfRows:2];
8997 } else if (!Ignored_ && [essential_ count] != 0) {
8998 int count = [essential_ count];
9000 UIAlertView *alert = [[[UIAlertView alloc]
9001 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9002 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9004 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9006 UCLocalize("UPGRADE_ESSENTIAL"),
9007 UCLocalize("COMPLETE_UPGRADE"),
9011 [alert setContext:@"upgrade"];
9016 - (void) returnToCydia {
9020 - (void) _saveConfig {
9021 @synchronized (database_) {
9028 NSString *error(nil);
9030 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9032 NSError *error(nil);
9033 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9034 NSLog(@"failure to save metadata data: %@", error);
9039 NSLog(@"failure to serialize metadata: %@", error);
9043 CydiaWriteSources();
9046 // Navigation controller for the queuing badge.
9047 - (UINavigationController *) queueNavigationController {
9048 NSArray *controllers = [tabbar_ viewControllers];
9049 return [controllers objectAtIndex:3];
9052 - (void) unloadData {
9053 [tabbar_ unloadData];
9056 - (void) _updateData {
9060 UINavigationController *navigation = [self queueNavigationController];
9062 id queuedelegate = nil;
9063 if ([[navigation viewControllers] count] > 0)
9064 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9066 [queuedelegate queueStatusDidChange];
9067 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9070 - (void) _refreshIfPossible:(NSDate *)update {
9071 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9073 bool recently = false;
9074 if (update != nil) {
9075 NSTimeInterval interval([update timeIntervalSinceNow]);
9076 if (interval <= 0 && interval > -(15*60))
9080 // Don't automatic refresh if:
9081 // - We already refreshed recently.
9082 // - We already auto-refreshed this launch.
9083 // - Auto-refresh is disabled.
9084 if (recently || loaded_ || ManualRefresh) {
9085 // If we are cancelling, we need to make sure it knows it's already loaded.
9088 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9090 // We are going to load, so remember that.
9093 SCNetworkReachabilityFlags flags; {
9094 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9095 SCNetworkReachabilityGetFlags(reachability, &flags);
9096 CFRelease(reachability);
9099 // XXX: this elaborate mess is what Apple is using to determine this? :(
9100 // XXX: do we care if the user has to intervene? maybe that's ok?
9102 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9103 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9104 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9105 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9106 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9107 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9111 // If we can reach the server, auto-refresh!
9113 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9119 - (void) refreshIfPossible {
9120 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9123 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9124 @synchronized (self) {
9125 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9126 [hud setText:UCLocalize("RELOADING_DATA")];
9128 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9132 [essential_ removeAllObjects];
9133 [broken_ removeAllObjects];
9135 NSArray *packages([database_ packages]);
9136 for (Package *package in packages) {
9138 [broken_ addObject:package];
9139 if ([package upgradableAndEssential:NO]) {
9140 if ([package essential])
9141 [essential_ addObject:package];
9146 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9149 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9150 [changesItem setBadgeValue:badge];
9151 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9152 [self setApplicationIconBadgeNumber:changes];
9155 [changesItem setBadgeValue:nil];
9156 [changesItem setAnimatedBadge:NO];
9157 [self setApplicationIconBadgeNumber:0];
9163 [self removeProgressHUD:hud];
9166 - (void) updateData {
9172 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9175 - (void) disemulate {
9176 if (emulated_ == nil)
9179 [window_ addSubview:[tabbar_ view]];
9180 [[emulated_ view] removeFromSuperview];
9182 [window_ setUserInteractionEnabled:YES];
9185 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9186 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9188 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9190 UIViewController *parent;
9191 if (emulated_ == nil)
9200 [parent presentModalViewController:navigation animated:YES];
9203 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9204 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9206 if (navigation != nil)
9207 [navigation pushViewController:progress animated:YES];
9209 [self presentModalViewController:progress force:YES];
9211 [progress invoke:invocation withTitle:title];
9215 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9216 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9219 - (void) repairWithInvocation:(NSInvocation *)invocation {
9221 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9225 - (void) repairWithSelector:(SEL)selector {
9226 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9229 - (void) reloadData {
9230 [self reloadDataWithInvocation:nil];
9231 if ([database_ progressDelegate] == nil)
9237 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9240 - (void) addSource:(NSDictionary *) source {
9241 CydiaAddSource(source);
9244 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9245 CydiaAddSource(href, distribution, sections);
9248 - (void) addTrivialSource:(NSString *)href {
9249 CydiaAddSource(href, @"./");
9252 - (void) updateValues {
9257 pkgProblemResolver *resolver = [database_ resolver];
9259 resolver->InstallProtect();
9260 if (!resolver->Resolve(true))
9265 // XXX: this is a really crappy way of doing this.
9266 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9267 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9268 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9269 if ([tabbar_ updating])
9270 [tabbar_ cancelUpdate];
9272 if (![database_ prepare])
9275 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9276 [page setDelegate:self];
9277 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9280 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9281 [tabbar_ presentModalViewController:confirm_ animated:YES];
9287 @synchronized (self) {
9292 - (void) clearPackage:(Package *)package {
9293 @synchronized (self) {
9300 - (void) installPackages:(NSArray *)packages {
9301 @synchronized (self) {
9302 for (Package *package in packages)
9309 - (void) installPackage:(Package *)package {
9310 @synchronized (self) {
9317 - (void) removePackage:(Package *)package {
9318 @synchronized (self) {
9325 - (void) distUpgrade {
9326 @synchronized (self) {
9327 if (![database_ upgrade])
9334 [database_ perform];
9335 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9338 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9341 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9343 [self refreshIfPossible];
9346 - (void) showSettings {
9347 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9350 - (void) retainNetworkActivityIndicator {
9351 if (activity_++ == 0)
9352 [self setNetworkActivityIndicatorVisible:YES];
9355 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9359 - (void) releaseNetworkActivityIndicator {
9360 if (--activity_ == 0)
9361 [self setNetworkActivityIndicatorVisible:NO];
9364 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9369 - (void) cancelAndClear:(bool)clear {
9370 @synchronized (self) {
9382 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9383 NSString *context([alert context]);
9385 if ([context isEqualToString:@"conffile"]) {
9386 FILE *input = [database_ input];
9387 if (button == [alert cancelButtonIndex])
9388 fprintf(input, "N\n");
9389 else if (button == [alert firstOtherButtonIndex])
9390 fprintf(input, "Y\n");
9393 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9394 } else if ([context isEqualToString:@"fixhalf"]) {
9395 if (button == [alert cancelButtonIndex]) {
9396 @synchronized (self) {
9397 for (Package *broken in (id) broken_) {
9400 NSString *id = [broken id];
9401 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9402 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9403 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9404 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9410 } else if (button == [alert firstOtherButtonIndex]) {
9411 [broken_ removeAllObjects];
9415 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9416 } else if ([context isEqualToString:@"upgrade"]) {
9417 if (button == [alert firstOtherButtonIndex]) {
9418 @synchronized (self) {
9419 for (Package *essential in (id) essential_)
9420 [essential install];
9425 } else if (button == [alert firstOtherButtonIndex] + 1) {
9427 } else if (button == [alert cancelButtonIndex]) {
9431 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9435 - (void) system:(NSString *)command {
9436 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9439 system([command UTF8String]);
9445 - (void) applicationWillSuspend {
9447 [super applicationWillSuspend];
9450 - (BOOL) isSafeToSuspend {
9453 NSLog(@"isSafeToSuspend: locked_ != 0");
9458 // Use external process status API internally.
9459 // This is probably a really bad idea.
9460 // XXX: what is the point of this? does this solve anything at all?
9461 uint64_t status = 0;
9463 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9464 notify_get_state(notify_token, &status);
9465 notify_cancel(notify_token);
9470 NSLog(@"isSafeToSuspend: status != 0");
9476 NSLog(@"isSafeToSuspend: -> true");
9481 - (void) applicationSuspend:(__GSEvent *)event {
9482 if ([self isSafeToSuspend])
9483 [super applicationSuspend:event];
9486 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9487 if ([self isSafeToSuspend])
9488 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9491 - (void) _setSuspended:(BOOL)value {
9492 if ([self isSafeToSuspend])
9493 [super _setSuspended:value];
9496 - (UIProgressHUD *) addProgressHUD {
9497 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9498 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9500 [window_ setUserInteractionEnabled:NO];
9502 UIViewController *target(tabbar_);
9503 if (UIViewController *modal = [target modalViewController])
9506 [hud showInView:[target view]];
9512 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9515 [hud removeFromSuperview];
9516 [window_ setUserInteractionEnabled:YES];
9519 - (CyteViewController *) pageForPackage:(NSString *)name {
9520 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9523 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9524 NSString *scheme([[url scheme] lowercaseString]);
9525 if ([[url absoluteString] length] <= [scheme length] + 3)
9527 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9528 NSArray *components([path componentsSeparatedByString:@"/"]);
9530 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9531 return [self pageForPackage:[components objectAtIndex:1]];
9533 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9536 NSString *base([components objectAtIndex:0]);
9538 CyteViewController *controller = nil;
9540 if ([base isEqualToString:@"url"]) {
9541 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9542 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9543 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9544 } else if (!external && [components count] == 1) {
9545 if ([base isEqualToString:@"manage"]) {
9546 controller = [[[ManageController alloc] init] autorelease];
9549 if ([base isEqualToString:@"storage"]) {
9550 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9553 if ([base isEqualToString:@"sources"]) {
9554 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9557 if ([base isEqualToString:@"home"]) {
9558 controller = [[[HomeController alloc] init] autorelease];
9561 if ([base isEqualToString:@"sections"]) {
9562 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9565 if ([base isEqualToString:@"search"]) {
9566 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9569 if ([base isEqualToString:@"changes"]) {
9570 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9573 if ([base isEqualToString:@"installed"]) {
9574 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9576 } else if ([components count] == 2) {
9577 NSString *argument = [components objectAtIndex:1];
9579 if ([base isEqualToString:@"package"]) {
9580 controller = [self pageForPackage:argument];
9583 if (!external && [base isEqualToString:@"search"]) {
9584 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9587 if (!external && [base isEqualToString:@"sections"]) {
9588 if ([argument isEqualToString:@"all"])
9590 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9593 if (!external && [base isEqualToString:@"sources"]) {
9594 if ([argument isEqualToString:@"add"]) {
9595 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9596 [(SourcesController *)controller showAddSourcePrompt];
9598 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9599 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9603 if (!external && [base isEqualToString:@"launch"]) {
9604 [self launchApplicationWithIdentifier:argument suspended:NO];
9607 } else if (!external && [components count] == 3) {
9608 NSString *arg1 = [components objectAtIndex:1];
9609 NSString *arg2 = [components objectAtIndex:2];
9611 if ([base isEqualToString:@"package"]) {
9612 if ([arg2 isEqualToString:@"settings"]) {
9613 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9614 } else if ([arg2 isEqualToString:@"files"]) {
9615 if (Package *package = [database_ packageWithName:arg1]) {
9616 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9617 [(FileTable *)controller setPackage:package];
9623 [controller setDelegate:self];
9627 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9628 CyteViewController *page([self pageForURL:url forExternal:external]);
9631 [tabbar_ setUnselectedViewController:page];
9636 - (void) applicationOpenURL:(NSURL *)url {
9637 [super applicationOpenURL:url];
9642 [self openCydiaURL:url forExternal:YES];
9645 - (void) applicationWillResignActive:(UIApplication *)application {
9646 // Stop refreshing if you get a phone call or lock the device.
9647 if ([tabbar_ updating])
9648 [tabbar_ cancelUpdate];
9650 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9651 [super applicationWillResignActive:application];
9654 - (void) saveState {
9655 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9656 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9657 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9663 - (void) applicationWillTerminate:(UIApplication *)application {
9667 - (void) setConfigurationData:(NSString *)data {
9668 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9670 if (!conffile_r(data)) {
9671 lprintf("E:invalid conffile\n");
9675 NSString *ofile = conffile_r[1];
9676 //NSString *nfile = conffile_r[2];
9678 UIAlertView *alert = [[[UIAlertView alloc]
9679 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9680 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9682 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9684 UCLocalize("ACCEPT_NEW_COPY"),
9685 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9689 [alert setContext:@"conffile"];
9690 [alert setNumberOfRows:2];
9694 - (void) addStashController {
9696 stash_ = [[[StashController alloc] init] autorelease];
9697 [window_ addSubview:[stash_ view]];
9700 - (void) removeStashController {
9701 [[stash_ view] removeFromSuperview];
9707 [self setIdleTimerDisabled:YES];
9709 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9710 UpdateExternalStatus(1);
9711 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9712 UpdateExternalStatus(0);
9714 [self removeStashController];
9716 pid_t pid(ExecFork());
9718 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9719 perror("launchctl stop");
9726 - (void) setupViewControllers {
9727 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9729 NSMutableArray *items([NSMutableArray arrayWithObjects:
9730 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9731 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9732 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9733 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9737 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9738 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9740 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9743 NSMutableArray *controllers([NSMutableArray array]);
9744 for (UITabBarItem *item in items) {
9745 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9746 [controller setTabBarItem:item];
9747 [controllers addObject:controller];
9749 [tabbar_ setViewControllers:controllers];
9751 [tabbar_ setUpdateDelegate:self];
9754 - (void) _sendMemoryWarningNotification {
9755 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9756 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9758 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9761 - (void) _sendMemoryWarningNotifications {
9763 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9769 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9771 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9774 - (void) applicationDidFinishLaunching:(id)unused {
9775 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9778 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9779 [self setApplicationSupportsShakeToEdit:NO];
9781 @synchronized (HostConfig_) {
9782 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9785 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9786 initWithMemoryCapacity:524288
9787 diskCapacity:10485760
9788 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9791 [CydiaWebViewController _initialize];
9793 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9795 // this would disallow http{,s} URLs from accessing this data
9796 //[WebView registerURLSchemeAsLocal:@"cydia"];
9798 Font12_ = [UIFont systemFontOfSize:12];
9799 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9800 Font14_ = [UIFont systemFontOfSize:14];
9801 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9802 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9804 essential_ = [NSMutableArray arrayWithCapacity:4];
9805 broken_ = [NSMutableArray arrayWithCapacity:4];
9807 // XXX: I really need this thing... like, seriously... I'm sorry
9808 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9810 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9811 [window_ orderFront:self];
9812 [window_ makeKey:self];
9813 [window_ setHidden:NO];
9816 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9817 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9818 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9819 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9820 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9821 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9822 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9823 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9824 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9827 [self addStashController];
9828 // XXX: this would be much cleaner as a yieldToSelector:
9829 // that way the removeStashController could happen right here inline
9830 // we also could no longer require the useless stash_ field anymore
9831 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9835 database_ = [Database sharedInstance];
9836 [database_ setDelegate:self];
9838 [window_ setUserInteractionEnabled:NO];
9839 [self setupViewControllers];
9841 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9842 [window_ addSubview:[emulated_ view]];
9844 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9848 - (NSArray *) defaultStartPages {
9849 NSMutableArray *standard = [NSMutableArray array];
9850 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9851 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9852 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9854 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9856 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9857 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9859 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9866 [window_ setUserInteractionEnabled:YES];
9867 [self showSettings];
9870 if ([emulated_ modalViewController] != nil)
9871 [emulated_ dismissModalViewControllerAnimated:YES];
9872 [window_ setUserInteractionEnabled:NO];
9875 [self reloadDataWithInvocation:nil];
9876 [self refreshIfPossible];
9881 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9882 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9883 int standardIndex = 0;
9884 NSArray *standard = [self defaultStartPages];
9891 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9892 if (valid && closed != nil) {
9893 NSTimeInterval interval([closed timeIntervalSinceNow]);
9894 // XXX: Is 30 minutes the optimal time here?
9895 if (interval <= -(30*60))
9899 if (valid && [saved count] != [standard count])
9903 for (unsigned int i = 0; i < [standard count]; i++) {
9904 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9905 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9906 // but it's good enough for now.
9907 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9914 NSArray *items = nil;
9916 [tabbar_ setSelectedIndex:savedIndex];
9919 [tabbar_ setSelectedIndex:standardIndex];
9923 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9924 NSArray *stack = [items objectAtIndex:tab];
9925 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9926 NSMutableArray *current = [NSMutableArray array];
9928 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9929 NSString *addr = [stack objectAtIndex:nav];
9930 NSURL *url = [NSURL URLWithString:addr];
9931 CyteViewController *page = [self pageForURL:url forExternal:NO];
9933 [current addObject:page];
9936 [navigation setViewControllers:current];
9939 // (Try to) show the startup URL.
9940 if (starturl_ != nil) {
9941 [self openCydiaURL:starturl_ forExternal:NO];
9946 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9947 if (item != nil && IsWildcat_) {
9948 [sheet showFromBarButtonItem:item animated:YES];
9950 [sheet showInView:window_];
9954 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9955 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9956 [progress setTitle:task];
9957 [progress addProgressEvent:event];
9960 - (void) addProgressEventForTask:(NSArray *)data {
9961 CydiaProgressEvent *event([data objectAtIndex:0]);
9962 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9963 [self addProgressEvent:event forTask:task];
9966 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9967 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9973 id Alloc_(id self, SEL selector) {
9974 id object = alloc_(self, selector);
9975 lprintf("[%s]A-%p\n", self->isa->name, object);
9980 id Dealloc_(id self, SEL selector) {
9981 id object = dealloc_(self, selector);
9982 lprintf("[%s]D-%p\n", self->isa->name, object);
9986 Class $WebDefaultUIKitDelegate;
9988 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9989 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9990 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9991 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9994 static NSSet *MobilizedFiles_;
9996 static NSURL *MobilizeURL(NSURL *url) {
9997 NSString *path([url path]);
9998 if ([path hasPrefix:@"/var/root/"]) {
9999 NSString *file([path substringFromIndex:10]);
10000 if ([MobilizedFiles_ containsObject:file])
10001 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10007 Class $CFXPreferencesPropertyListSource;
10008 @class CFXPreferencesPropertyListSource;
10010 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10011 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10012 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10013 url = MobilizeURL(url);
10014 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10015 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10021 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10022 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10023 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10024 url = MobilizeURL(url);
10025 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10026 //NSLog(@"%@ %@", [url absoluteString], value);
10032 Class $NSURLConnection;
10034 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10035 NSMutableURLRequest *copy([request mutableCopy]);
10037 NSURL *url([copy URL]);
10039 NSString *host([url host]);
10040 NSString *scheme([[url scheme] lowercaseString]);
10042 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10044 @synchronized (HostConfig_) {
10045 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10046 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10047 [copy setHTTPShouldUsePipelining:YES];
10049 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10050 if ([control isEqualToString:@"max-age=0"])
10051 if ([CachedURLs_ containsObject:url]) {
10053 NSLog(@"~~~: %@", url);
10056 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10058 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10059 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10060 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10064 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10068 int main(int argc, char *argv[]) {
10069 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10073 UpdateExternalStatus(0);
10075 if (Class $UIDevice = objc_getClass("UIDevice")) {
10076 UIDevice *device([$UIDevice currentDevice]);
10077 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10079 IsWildcat_ = false;
10081 UIScreen *screen([UIScreen mainScreen]);
10082 if ([screen respondsToSelector:@selector(scale)])
10083 ScreenScale_ = [screen scale];
10087 UIDevice *device([UIDevice currentDevice]);
10088 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10089 Idiom_ = @"iphone";
10091 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10092 if (idiom == UIUserInterfaceIdiomPhone)
10093 Idiom_ = @"iphone";
10094 else if (idiom == UIUserInterfaceIdiomPad)
10097 NSLog(@"unknown UIUserInterfaceIdiom!");
10100 Pcre pattern("^([0-9]+\\.[0-9]+)");
10102 if (pattern([device systemVersion]))
10103 Firmware_ = pattern[1];
10104 if (pattern(Cydia_))
10105 Major_ = pattern[1];
10107 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10109 HostConfig_ = [[[NSObject alloc] init] autorelease];
10110 @synchronized (HostConfig_) {
10111 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10112 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10113 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10114 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10115 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10118 NSString *ui(@"ui/ios");
10120 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10121 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10122 UI_ = CydiaURL(ui);
10124 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10126 MobilizedFiles_ = [NSMutableSet setWithObjects:
10127 @"Library/Preferences/com.apple.Accessibility.plist",
10128 @"Library/Preferences/com.apple.preferences.sounds.plist",
10131 /* Library Hacks {{{ */
10132 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10134 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10136 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10137 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10138 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10139 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10142 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10143 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10144 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10145 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10148 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10149 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10150 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10151 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10152 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10155 $NSURLConnection = objc_getClass("NSURLConnection");
10156 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10157 if (NSURLConnection$init$ != NULL) {
10158 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10159 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10162 /* Set Locale {{{ */
10163 Locale_ = CFLocaleCopyCurrent();
10164 Languages_ = [NSLocale preferredLanguages];
10166 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10167 //NSLog(@"%@", [Languages_ description]);
10170 if (Locale_ != NULL)
10171 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10172 else if (Languages_ != nil && [Languages_ count] != 0)
10173 lang = [[Languages_ objectAtIndex:0] UTF8String];
10175 // XXX: consider just setting to C and then falling through?
10178 if (lang != NULL) {
10179 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10180 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10183 NSLog(@"Setting Language: %s", lang);
10185 if (lang != NULL) {
10186 setenv("LANG", lang, true);
10187 std::setlocale(LC_ALL, lang);
10191 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10193 /* Parse Arguments {{{ */
10194 bool substrate(false);
10200 for (int argi(1); argi != argc; ++argi)
10201 if (strcmp(argv[argi], "--") == 0) {
10203 argv[argi] = argv[0];
10209 for (int argi(1); argi != arge; ++argi)
10210 if (strcmp(args[argi], "--substrate") == 0)
10213 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10217 App_ = [[NSBundle mainBundle] bundlePath];
10223 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10224 alloc_ = alloc->method_imp;
10225 alloc->method_imp = (IMP) &Alloc_;*/
10227 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10228 dealloc_ = dealloc->method_imp;
10229 dealloc->method_imp = (IMP) &Dealloc_;*/
10231 /* System Information {{{ */
10235 size = sizeof(maxproc);
10236 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10237 perror("sysctlbyname(\"kern.maxproc\", ?)");
10238 else if (maxproc < 64) {
10240 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10241 perror("sysctlbyname(\"kern.maxproc\", #)");
10244 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10245 char *osversion = new char[size];
10246 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10247 perror("sysctlbyname(\"kern.osversion\", ?)");
10249 System_ = [NSString stringWithUTF8String:osversion];
10251 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10252 char *machine = new char[size];
10253 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10254 perror("sysctlbyname(\"hw.machine\", ?)");
10256 Machine_ = machine;
10258 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10259 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10260 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10262 UniqueID_ = [device uniqueIdentifier];
10264 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10265 Product_ = [info objectForKey:@"SafariProductVersion"];
10266 Safari_ = [info objectForKey:@"CFBundleVersion"];
10269 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10271 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10272 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10273 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10274 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10275 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10276 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10278 UserAgent_ = agent;
10280 /* Load Database {{{ */
10282 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10284 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10286 if (Metadata_ == NULL)
10287 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10289 Settings_ = [Metadata_ objectForKey:@"Settings"];
10291 Packages_ = [Metadata_ objectForKey:@"Packages"];
10293 Values_ = [Metadata_ objectForKey:@"Values"];
10294 Sections_ = [Metadata_ objectForKey:@"Sections"];
10295 Sources_ = [Metadata_ objectForKey:@"Sources"];
10297 Token_ = [Metadata_ objectForKey:@"Token"];
10299 Version_ = [Metadata_ objectForKey:@"Version"];
10302 if (Settings_ != nil)
10303 Role_ = [Settings_ objectForKey:@"Role"];
10305 if (Values_ == nil) {
10306 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10307 [Metadata_ setObject:Values_ forKey:@"Values"];
10310 if (Sections_ == nil) {
10311 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10312 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10315 if (Sources_ == nil) {
10316 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10317 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10320 if (Version_ == nil) {
10321 Version_ = [NSNumber numberWithUnsignedInt:0];
10322 [Metadata_ setObject:Version_ forKey:@"Version"];
10325 if ([Version_ unsignedIntValue] == 0) {
10326 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10327 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10328 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10329 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10331 Version_ = [NSNumber numberWithUnsignedInt:1];
10332 [Metadata_ setObject:Version_ forKey:@"Version"];
10334 [Metadata_ removeObjectForKey:@"LastUpdate"];
10340 CydiaWriteSources();
10343 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10346 if (Packages_ != nil) {
10348 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10352 [Metadata_ removeObjectForKey:@"Packages"];
10358 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10360 #define MobileSubstrate_(name) \
10361 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10362 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10363 if (handle == NULL) \
10364 NSLog(@"%s", dlerror()); \
10367 MobileSubstrate_(Activator)
10368 MobileSubstrate_(libstatusbar)
10369 MobileSubstrate_(SimulatedKeyEvents)
10370 MobileSubstrate_(WinterBoard)
10372 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10373 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10375 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10377 if (access("/User", F_OK) != 0 || version != 5) {
10379 system("/usr/libexec/cydia/firmware.sh");
10383 _assert([[NSFileManager defaultManager]
10384 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10385 withIntermediateDirectories:YES
10390 if (access("/tmp/cydia.chk", F_OK) == 0) {
10391 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10392 _assert(errno == ENOENT);
10393 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10394 _assert(errno == ENOENT);
10397 /* APT Initialization {{{ */
10398 _assert(pkgInitConfig(*_config));
10399 _assert(pkgInitSystem(*_config, _system));
10402 _config->Set("APT::Acquire::Translation", lang);
10404 // XXX: this timeout might be important :(
10405 //_config->Set("Acquire::http::Timeout", 15);
10407 _config->Set("Acquire::http::MaxParallel", 3);
10409 /* Color Choices {{{ */
10410 space_ = CGColorSpaceCreateDeviceRGB();
10412 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10413 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10414 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10415 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10416 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10417 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10418 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10419 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10420 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10422 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10423 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10425 /* UIKit Configuration {{{ */
10426 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10427 if ($GSFontSetUseLegacyFontMetrics != NULL)
10428 $GSFontSetUseLegacyFontMetrics(YES);
10430 // XXX: I have a feeling this was important
10431 //UIKeyboardDisableAutomaticAppearance();
10434 Colon_ = UCLocalize("COLON_DELIMITED");
10435 Elision_ = UCLocalize("ELISION");
10436 Error_ = UCLocalize("ERROR");
10437 Warning_ = UCLocalize("WARNING");
10440 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10442 CGColorSpaceRelease(space_);
10443 CFRelease(Locale_);