1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
126 #include <CydiaSubstrate/CydiaSubstrate.h>
127 #include "Menes/Menes.h"
129 #include "CyteKit/PerlCompatibleRegEx.hpp"
130 #include "CyteKit/TableViewCell.h"
131 #include "CyteKit/WebScriptObject-Cyte.h"
132 #include "CyteKit/WebViewController.h"
133 #include "CyteKit/stringWithUTF8Bytes.h"
135 #include "Cydia/MIMEAddress.h"
136 #include "Cydia/LoadingViewController.h"
137 #include "Cydia/ProgressEvent.h"
139 #include "SDURLCache/SDURLCache.h"
146 #define _timestamp ({ \
148 gettimeofday(&tv, NULL); \
149 tv.tv_sec * 1000000 + tv.tv_usec; \
152 typedef std::vector<class ProfileTime *> TimeList;
162 ProfileTime(const char *name) :
166 times_.push_back(this);
169 void AddTime(uint64_t time) {
176 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
188 ProfileTimer(ProfileTime &time) :
195 time_.AddTime(_timestamp - start_);
200 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
202 std::cerr << "========" << std::endl;
205 #define _profile(name) { \
206 static ProfileTime name(#name); \
207 ProfileTimer _ ## name(name);
212 extern NSString *Cydia_;
214 #define lprintf(args...) fprintf(stderr, args)
217 #define TraceLogging (1 && !ForRelease)
218 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
219 #define ProfileTimes (0 && !ForRelease)
220 #define ForSaurik (0 && !ForRelease)
221 #define LogBrowser (0 && !ForRelease)
222 #define TrackResize (0 && !ForRelease)
223 #define ManualRefresh (1 && !ForRelease)
224 #define ShowInternals (0 && !ForRelease)
225 #define AlwaysReload (0 && !ForRelease)
226 #define TryIndexedCollation (0 && !ForRelease)
230 #define _trace(args...)
235 #define _profile(name) {
238 #define PrintTimes() do {} while (false)
241 // Hash Functions/Structures {{{
242 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
250 static NSString *Colon_;
252 static NSString *Error_;
253 static NSString *Warning_;
255 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
257 static _finline NSString *CydiaURL(NSString *path) {
259 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
260 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
261 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
262 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
263 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
265 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
268 static void ReapZombie(pid_t pid) {
271 if (waitpid(pid, &status, 0) == -1)
277 static _finline void UpdateExternalStatus(uint64_t newStatus) {
279 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
280 notify_set_state(notify_token, newStatus);
281 notify_cancel(notify_token);
283 notify_post("com.saurik.Cydia.status");
286 static CGFloat CYStatusBarHeight() {
287 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
288 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
291 /* NSForcedOrderingSearch doesn't work on the iPhone */
292 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
293 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
294 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
296 /* Insertion Sort {{{ */
298 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
299 const char *ptr = (const char *)list;
301 CFIndex half = count / 2;
302 const char *probe = ptr + elementSize * half;
303 CFComparisonResult cr = comparator(element, probe, context);
304 if (0 == cr) return (probe - (const char *)list) / elementSize;
305 ptr = (cr < 0) ? ptr : probe + elementSize;
306 count = (cr < 0) ? half : (half + (count & 1) - 1);
308 return (ptr - (const char *)list) / elementSize;
311 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
312 const char *ptr = (const char *)list;
314 CFIndex half = count / 2;
315 const char *probe = ptr + elementSize * half;
316 CFComparisonResult cr = comparator(element, probe, context);
317 if (0 == cr) return (probe - (const char *)list) / elementSize;
318 ptr = (cr < 0) ? ptr : probe + elementSize;
319 count = (cr < 0) ? half : (half + (count & 1) - 1);
321 return (ptr - (const char *)list) / elementSize;
324 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
325 if (range.length == 0)
327 const void **values(new const void *[range.length]);
328 CFArrayGetValues(array, range, values);
330 #if HistogramInsertionSort > 0
331 uint32_t total(0), *offsets(new uint32_t[range.length]);
334 for (CFIndex index(1); index != range.length; ++index) {
335 const void *value(values[index]);
336 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
337 CFIndex correct(index);
338 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
339 #if HistogramInsertionSort > 1
340 NSLog(@"%@ < %@", value, values[correct - 1]);
345 if (correct != index) {
346 size_t offset(index - correct);
347 #if HistogramInsertionSort
351 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
353 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
354 values[correct] = value;
358 CFArrayReplaceValues(array, range, values, range.length);
361 #if HistogramInsertionSort > 0
362 for (CFIndex index(0); index != range.length; ++index)
363 if (offsets[index] != 0)
364 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
365 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
372 /* Apple Bug Fixes {{{ */
373 @implementation UIWebDocumentView (Cydia)
375 - (void) _setScrollerOffset:(CGPoint)offset {
376 UIScroller *scroller([self _scroller]);
378 CGSize size([scroller contentSize]);
379 CGSize bounds([scroller bounds].size);
382 max.x = size.width - bounds.width;
383 max.y = size.height - bounds.height;
391 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
392 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
394 [scroller setOffset:offset];
400 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
401 size_t length([self length] - state->state);
404 else if (length > count)
406 for (size_t i(0); i != length; ++i)
407 objects[i] = [self item:state->state++];
408 state->itemsPtr = objects;
409 state->mutationsPtr = (unsigned long *) self;
413 /* Cydia NSString Additions {{{ */
414 @interface NSString (Cydia)
415 - (NSComparisonResult) compareByPath:(NSString *)other;
416 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
419 @implementation NSString (Cydia)
421 - (NSComparisonResult) compareByPath:(NSString *)other {
422 NSString *prefix = [self commonPrefixWithString:other options:0];
423 size_t length = [prefix length];
425 NSRange lrange = NSMakeRange(length, [self length] - length);
426 NSRange rrange = NSMakeRange(length, [other length] - length);
428 lrange = [self rangeOfString:@"/" options:0 range:lrange];
429 rrange = [other rangeOfString:@"/" options:0 range:rrange];
431 NSComparisonResult value;
433 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
434 value = NSOrderedSame;
435 else if (lrange.location == NSNotFound)
436 value = NSOrderedAscending;
437 else if (rrange.location == NSNotFound)
438 value = NSOrderedDescending;
440 value = NSOrderedSame;
442 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
443 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
444 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
445 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
447 NSComparisonResult result = [lpath compare:rpath];
448 return result == NSOrderedSame ? value : result;
451 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
452 return [(id)CFURLCreateStringByAddingPercentEscapes(
457 kCFStringEncodingUTF8
464 /* C++ NSString Wrapper Cache {{{ */
465 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
466 return size == 0 ? NULL :
467 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
468 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
471 static _finline CFStringRef CYStringCreate(const char *data) {
472 return CYStringCreate(data, strlen(data));
481 _finline void clear_() {
482 if (cache_ != NULL) {
489 _finline bool empty() const {
493 _finline size_t size() const {
497 _finline char *data() const {
501 _finline void clear() {
506 _finline CYString() :
513 _finline ~CYString() {
517 void operator =(const CYString &rhs) {
521 if (rhs.cache_ == nil)
524 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
527 void copy(apr_pool_t *pool) {
528 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
529 memcpy(temp, data_, size_);
534 void set(apr_pool_t *pool, const char *data, size_t size) {
540 data_ = const_cast<char *>(data);
548 _finline void set(apr_pool_t *pool, const char *data) {
549 set(pool, data, data == NULL ? 0 : strlen(data));
552 _finline void set(apr_pool_t *pool, const std::string &rhs) {
553 set(pool, rhs.data(), rhs.size());
556 bool operator ==(const CYString &rhs) const {
557 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
560 _finline operator CFStringRef() {
562 cache_ = CYStringCreate(data_, size_);
566 _finline operator id() {
567 return (NSString *) static_cast<CFStringRef>(*this);
570 _finline operator const char *() {
571 return reinterpret_cast<const char *>(data_);
575 /* C++ NSString Algorithm Adapters {{{ */
577 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
580 struct NSStringMapHash :
581 std::unary_function<NSString *, size_t>
583 _finline size_t operator ()(NSString *value) const {
584 return CFStringHashNSString((CFStringRef) value);
588 struct NSStringMapLess :
589 std::binary_function<NSString *, NSString *, bool>
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return [lhs compare:rhs] == NSOrderedAscending;
596 struct NSStringMapEqual :
597 std::binary_function<NSString *, NSString *, bool>
599 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
600 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
601 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
602 //[lhs isEqualToString:rhs];
607 /* CoreGraphics Primitives {{{ */
612 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
613 CGFloat color[] = {red, green, blue, alpha};
614 return CGColorCreate(space, color);
623 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
624 color_(Create_(space, red, green, blue, alpha))
626 Set(space, red, green, blue, alpha);
631 CGColorRelease(color_);
638 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
640 color_ = Create_(space, red, green, blue, alpha);
643 operator CGColorRef() {
649 /* Random Global Variables {{{ */
650 static const int PulseInterval_ = 50000;
652 static const NSString *UI_;
655 static bool RestartSubstrate_;
656 static NSArray *Finishes_;
658 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
659 #define NotifyConfig_ "/etc/notify.conf"
661 static bool Queuing_;
663 static CYColor Blue_;
664 static CYColor Blueish_;
665 static CYColor Black_;
667 static CYColor White_;
668 static CYColor Gray_;
669 static CYColor Green_;
670 static CYColor Purple_;
671 static CYColor Purplish_;
673 static UIColor *InstallingColor_;
674 static UIColor *RemovingColor_;
676 static NSString *App_;
678 static BOOL Advanced_;
679 static BOOL Ignored_;
681 static _H<UIFont> Font12_;
682 static _H<UIFont> Font12Bold_;
683 static _H<UIFont> Font14_;
684 static _H<UIFont> Font18Bold_;
685 static _H<UIFont> Font22Bold_;
687 static const char *Machine_ = NULL;
688 static NSString *System_ = nil;
689 static NSString *SerialNumber_ = nil;
690 static NSString *ChipID_ = nil;
691 static NSString *BBSNum_ = nil;
692 static _H<NSString> Token_;
693 static NSString *UniqueID_ = nil;
694 static NSString *PLMN_ = nil;
695 static NSString *Build_ = nil;
696 static NSString *Product_ = nil;
697 static NSString *Safari_ = nil;
699 static CFLocaleRef Locale_;
700 static NSArray *Languages_;
701 static CGColorSpaceRef space_;
703 static NSDictionary *SectionMap_;
704 static NSMutableDictionary *Metadata_;
705 static _transient NSMutableDictionary *Settings_;
706 static _transient NSString *Role_;
707 static _transient NSMutableDictionary *Packages_;
708 static _transient NSMutableDictionary *Values_;
709 static _transient NSMutableDictionary *Sections_;
710 _H<NSMutableDictionary> Sources_;
711 static _transient NSNumber *Version_;
712 _H<NSString> CydiaSource_;
717 static CGFloat ScreenScale_;
718 static NSString *Idiom_;
719 _H<NSString> Firmware_;
720 static NSString *Major_;
722 static _H<NSMutableDictionary> SessionData_;
723 static _H<NSObject> HostConfig_;
724 static _H<NSMutableSet> BridgedHosts_;
725 static _H<NSMutableSet> TokenHosts_;
726 static _H<NSMutableSet> InsecureHosts_;
727 static _H<NSMutableSet> PipelinedHosts_;
728 static _H<NSMutableSet> CachedURLs_;
730 static NSString *kCydiaProgressEventTypeError = @"Error";
731 static NSString *kCydiaProgressEventTypeInformation = @"Information";
732 static NSString *kCydiaProgressEventTypeStatus = @"Status";
733 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
736 /* Display Helpers {{{ */
737 inline float Interpolate(float begin, float end, float fraction) {
738 return (end - begin) * fraction + begin;
741 static _finline const char *StripVersion_(const char *version) {
742 const char *colon(strchr(version, ':'));
743 return colon == NULL ? version : colon + 1;
746 NSString *LocalizeSection(NSString *section) {
747 static Pcre title_r("^(.*?) \\((.*)\\)$");
748 if (title_r(section)) {
749 NSString *parent(title_r[1]);
750 NSString *child(title_r[2]);
752 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
753 LocalizeSection(parent),
754 LocalizeSection(child)
758 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
761 NSString *Simplify(NSString *title) {
762 const char *data = [title UTF8String];
763 size_t size = [title length];
765 static Pcre square_r("^\\[(.*)\\]$");
766 if (square_r(data, size))
767 return Simplify(square_r[1]);
769 static Pcre paren_r("^\\((.*)\\)$");
770 if (paren_r(data, size))
771 return Simplify(paren_r[1]);
773 static Pcre title_r("^(.*?) \\((.*)\\)$");
774 if (title_r(data, size))
775 return Simplify(title_r[1]);
781 NSString *GetLastUpdate() {
782 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
785 return UCLocalize("NEVER_OR_UNKNOWN");
787 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
788 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
790 CFRelease(formatter);
792 return [(NSString *) formatted autorelease];
795 bool isSectionVisible(NSString *section) {
796 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
797 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
798 return hidden == nil || ![hidden boolValue];
801 static NSObject *CYIOGetValue(const char *path, NSString *property) {
802 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
803 if (entry == MACH_PORT_NULL)
806 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
807 IOObjectRelease(entry);
811 return [(id) value autorelease];
814 static NSString *CYHex(NSData *data, bool reverse = false) {
818 size_t length([data length]);
819 uint8_t bytes[length];
820 [data getBytes:bytes];
822 char string[length * 2 + 1];
823 for (size_t i(0); i != length; ++i)
824 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
826 return [NSString stringWithUTF8String:string];
831 /* Delegate Prototypes {{{ */
834 @class CydiaProgressEvent;
836 @protocol DatabaseDelegate
837 - (void) repairWithSelector:(SEL)selector;
838 - (void) setConfigurationData:(NSString *)data;
839 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
842 @class CYPackageController;
844 @protocol CydiaDelegate
845 - (void) returnToCydia;
847 - (void) retainNetworkActivityIndicator;
848 - (void) releaseNetworkActivityIndicator;
849 - (void) clearPackage:(Package *)package;
850 - (void) installPackage:(Package *)package;
851 - (void) installPackages:(NSArray *)packages;
852 - (void) removePackage:(Package *)package;
853 - (void) beginUpdate;
855 - (void) distUpgrade;
859 - (void) addSource:(NSDictionary *)source;
860 - (void) addTrivialSource:(NSString *)href;
861 - (void) showSettings;
862 - (UIProgressHUD *) addProgressHUD;
863 - (void) removeProgressHUD:(UIProgressHUD *)hud;
864 - (CyteViewController *) pageForPackage:(NSString *)name;
865 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
866 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
870 /* Status Delegation {{{ */
872 public pkgAcquireStatus
875 _transient NSObject<ProgressDelegate> *delegate_;
885 void setDelegate(NSObject<ProgressDelegate> *delegate) {
886 delegate_ = delegate;
889 NSObject<ProgressDelegate> *getDelegate() const {
893 virtual bool MediaChange(std::string media, std::string drive) {
897 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
901 virtual void Fetch(pkgAcquire::ItemDesc &item) {
902 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
903 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
904 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
907 virtual void Done(pkgAcquire::ItemDesc &item) {
908 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
909 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
910 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
913 virtual void Fail(pkgAcquire::ItemDesc &item) {
915 item.Owner->Status == pkgAcquire::Item::StatIdle ||
916 item.Owner->Status == pkgAcquire::Item::StatDone
920 std::string &error(item.Owner->ErrorText);
924 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
925 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
928 virtual bool Pulse(pkgAcquire *Owner) {
929 bool value = pkgAcquireStatus::Pulse(Owner);
932 double(CurrentBytes + CurrentItems) /
933 double(TotalBytes + TotalItems)
936 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
937 [NSNumber numberWithDouble:percent], @"Percent",
939 [NSNumber numberWithDouble:CurrentBytes], @"Current",
940 [NSNumber numberWithDouble:TotalBytes], @"Total",
941 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
942 nil] waitUntilDone:YES];
944 if (value && ![delegate_ isProgressCancelled])
952 _finline bool WasCancelled() const {
956 virtual void Start() {
957 pkgAcquireStatus::Start();
958 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
961 virtual void Stop() {
962 pkgAcquireStatus::Stop();
963 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
964 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
968 /* Database Interface {{{ */
969 typedef std::map< unsigned long, _H<Source> > SourceMap;
971 @interface Database : NSObject {
978 pkgDepCache::Policy *policy_;
979 pkgRecords *records_;
980 pkgProblemResolver *resolver_;
981 pkgAcquire *fetcher_;
983 SPtr<pkgPackageManager> manager_;
984 pkgSourceList *list_;
986 SourceMap sourceMap_;
987 _H<NSMutableArray> sourceList_;
989 CFMutableArrayRef packages_;
991 _transient NSObject<DatabaseDelegate> *delegate_;
992 _transient NSObject<ProgressDelegate> *progress_;
1000 std::map<const char *, _H<NSString> > sections_;
1003 + (Database *) sharedInstance;
1006 - (void) _readCydia:(NSNumber *)fd;
1007 - (void) _readStatus:(NSNumber *)fd;
1008 - (void) _readOutput:(NSNumber *)fd;
1012 - (Package *) packageWithName:(NSString *)name;
1014 - (pkgCacheFile &) cache;
1015 - (pkgDepCache::Policy *) policy;
1016 - (pkgRecords *) records;
1017 - (pkgProblemResolver *) resolver;
1018 - (pkgAcquire &) fetcher;
1019 - (pkgSourceList &) list;
1020 - (NSArray *) packages;
1021 - (NSArray *) sources;
1022 - (Source *) sourceWithKey:(NSString *)key;
1023 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1031 - (void) updateWithStatus:(Status &)status;
1033 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1035 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1036 - (NSObject<ProgressDelegate> *) progressDelegate;
1038 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1040 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1044 /* ProgressEvent Implementation {{{ */
1045 @implementation CydiaProgressEvent
1047 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1048 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1051 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1052 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1053 [event setPackage:package];
1057 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1058 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1060 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1061 NSArray *fields([description componentsSeparatedByString:@" "]);
1062 [event setItem:fields];
1064 if ([fields count] > 3) {
1065 [event setPackage:[fields objectAtIndex:2]];
1066 [event setVersion:[fields objectAtIndex:3]];
1069 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1074 + (NSArray *) _attributeKeys {
1075 return [NSArray arrayWithObjects:
1085 - (NSArray *) attributeKeys {
1086 return [[self class] _attributeKeys];
1089 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1090 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1093 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1094 if ((self = [super init]) != nil) {
1100 - (NSString *) message {
1104 - (NSString *) type {
1108 - (NSArray *) item {
1109 return (id) item_ ?: [NSNull null];
1112 - (void) setItem:(NSArray *)item {
1116 - (NSString *) package {
1117 return (id) package_ ?: [NSNull null];
1120 - (void) setPackage:(NSString *)package {
1124 - (NSString *) url {
1125 return (id) url_ ?: [NSNull null];
1128 - (void) setURL:(NSString *)url {
1132 - (void) setVersion:(NSString *)version {
1136 - (NSString *) version {
1137 return (id) version_ ?: [NSNull null];
1140 - (NSString *) compound:(NSString *)value {
1142 NSString *mode(nil); {
1143 NSString *type([self type]);
1144 if ([type isEqualToString:kCydiaProgressEventTypeError])
1145 mode = UCLocalize("ERROR");
1146 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1147 mode = UCLocalize("WARNING");
1151 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1157 - (NSString *) compoundMessage {
1158 return [self compound:[self message]];
1161 - (NSString *) compoundTitle {
1164 if (package_ == nil)
1166 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1167 title = [package name];
1171 return [self compound:title];
1177 // Cytore Definitions {{{
1178 struct PackageValue :
1181 Cytore::Offset<PackageValue> next_;
1183 uint32_t index_ : 23;
1184 uint32_t subscribed_ : 1;
1201 Cytore::Offset<PackageValue> packages_[1 << 16];
1204 static Cytore::File<MetaValue> MetaFile_;
1206 // Cytore Helper Functions {{{
1207 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1208 SplitHash nhash = { hashlittle(name, length) };
1210 PackageValue *metadata;
1212 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1213 offset: if (offset->IsNull()) {
1214 *offset = MetaFile_.New<PackageValue>(length + 1);
1215 metadata = &MetaFile_.Get(*offset);
1217 if (metadata == NULL) {
1221 metadata = new PackageValue();
1222 memset(metadata, 0, sizeof(*metadata));
1225 memcpy(metadata->name_, name, length + 1);
1226 metadata->nhash_ = nhash.u16[1];
1228 metadata = &MetaFile_.Get(*offset);
1230 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1231 offset = &metadata->next_;
1239 static void PackageImport(const void *key, const void *value, void *context) {
1240 bool &fail(*reinterpret_cast<bool *>(context));
1243 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1244 NSLog(@"failed to import package %@", key);
1248 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1249 NSDictionary *package((NSDictionary *) value);
1251 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1252 if ([subscribed boolValue] && !metadata->subscribed_)
1253 metadata->subscribed_ = true;
1255 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1256 time_t time([date timeIntervalSince1970]);
1257 if (metadata->first_ > time || metadata->first_ == 0)
1258 metadata->first_ = time;
1261 NSDate *date([package objectForKey:@"LastSeen"]);
1262 NSString *version([package objectForKey:@"LastVersion"]);
1264 if (date != nil && version != nil) {
1265 time_t time([date timeIntervalSince1970]);
1266 if (metadata->last_ < time || metadata->last_ == 0)
1267 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1268 size_t length(strlen(buffer));
1269 uint16_t vhash(hashlittle(buffer, length));
1271 size_t capped(std::min<size_t>(8, length));
1272 char *latest(buffer + length - capped);
1274 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1275 metadata->vhash_ = vhash;
1277 metadata->last_ = time;
1283 /* Source Class {{{ */
1284 @interface Source : NSObject {
1286 Database *database_;
1289 CYString depiction_;
1290 CYString description_;
1296 CYString distribution_;
1302 _H<NSString> authority_;
1304 CYString defaultIcon_;
1306 _H<NSDictionary> record_;
1310 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1312 - (NSComparisonResult) compareByName:(Source *)source;
1314 - (NSString *) depictionForPackage:(NSString *)package;
1315 - (NSString *) supportForPackage:(NSString *)package;
1317 - (NSDictionary *) record;
1320 - (NSString *) rooturi;
1321 - (NSString *) distribution;
1322 - (NSString *) type;
1325 - (NSString *) host;
1327 - (NSString *) name;
1328 - (NSString *) shortDescription;
1329 - (NSString *) label;
1330 - (NSString *) origin;
1331 - (NSString *) version;
1333 - (NSString *) defaultIcon;
1334 - (NSURL *) iconURL;
1338 @implementation Source
1342 distribution_.clear();
1347 description_.clear();
1353 defaultIcon_.clear();
1360 + (NSString *) webScriptNameForSelector:(SEL)selector {
1362 else if (selector == @selector(addSection:))
1363 return @"addSection";
1364 else if (selector == @selector(getField:))
1366 else if (selector == @selector(removeSection:))
1367 return @"removeSection";
1368 else if (selector == @selector(remove))
1374 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1375 return [self webScriptNameForSelector:selector] == nil;
1378 + (NSArray *) _attributeKeys {
1379 return [NSArray arrayWithObjects:
1390 @"shortDescription",
1397 - (NSArray *) attributeKeys {
1398 return [[self class] _attributeKeys];
1401 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1402 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1405 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1408 trusted_ = index->IsTrusted();
1410 uri_.set(pool, index->GetURI());
1411 distribution_.set(pool, index->GetDist());
1412 type_.set(pool, index->GetType());
1414 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1415 if (dindex != NULL) {
1416 base_.set(pool, dindex->MetaIndexURI(""));
1419 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1422 pkgTagFile tags(&fd);
1424 pkgTagSection section;
1431 {"default-icon", &defaultIcon_},
1432 {"depiction", &depiction_},
1433 {"description", &description_},
1435 {"origin", &origin_},
1436 {"support", &support_},
1437 {"version", &version_},
1440 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1441 const char *start, *end;
1443 if (section.Find(names[i].name_, start, end)) {
1444 CYString &value(*names[i].value_);
1445 value.set(pool, start, end - start);
1451 record_ = [Sources_ objectForKey:[self key]];
1453 NSURL *url([NSURL URLWithString:uri_]);
1457 host_ = [host_ lowercaseString];
1462 authority_ = [url path];
1465 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1466 if ((self = [super init]) != nil) {
1467 era_ = [database era];
1468 database_ = database;
1471 [self setMetaIndex:index inPool:pool];
1475 - (NSString *) getField:(NSString *)name {
1476 @synchronized (database_) {
1477 if ([database_ era] != era_ || index_ == NULL)
1480 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1485 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1490 pkgTagFile tags(&fd);
1492 pkgTagSection section;
1495 const char *start, *end;
1496 if (!section.Find([name UTF8String], start, end))
1497 return (NSString *) [NSNull null];
1499 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1502 - (NSComparisonResult) compareByName:(Source *)source {
1503 NSString *lhs = [self name];
1504 NSString *rhs = [source name];
1506 if ([lhs length] != 0 && [rhs length] != 0) {
1507 unichar lhc = [lhs characterAtIndex:0];
1508 unichar rhc = [rhs characterAtIndex:0];
1510 if (isalpha(lhc) && !isalpha(rhc))
1511 return NSOrderedAscending;
1512 else if (!isalpha(lhc) && isalpha(rhc))
1513 return NSOrderedDescending;
1516 return [lhs compare:rhs options:LaxCompareOptions_];
1519 - (NSString *) depictionForPackage:(NSString *)package {
1520 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1523 - (NSString *) supportForPackage:(NSString *)package {
1524 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1527 - (NSArray *) sections {
1528 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1531 - (void) _addSection:(NSString *)section {
1534 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1535 if (![sections containsObject:section]) {
1536 [sections addObject:section];
1540 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1545 - (bool) addSection:(NSString *)section {
1549 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1553 - (void) _removeSection:(NSString *)section {
1557 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1558 if ([sections containsObject:section]) {
1559 [sections removeObject:section];
1564 - (bool) removeSection:(NSString *)section {
1568 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1573 [Sources_ removeObjectForKey:[self key]];
1578 bool value(record_ != nil);
1579 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1583 - (NSDictionary *) record {
1591 - (NSString *) rooturi {
1595 - (NSString *) distribution {
1596 return distribution_;
1599 - (NSString *) type {
1603 - (NSString *) baseuri {
1604 return base_.empty() ? nil : (id) base_;
1607 - (NSString *) iconuri {
1608 if (NSString *base = [self baseuri])
1609 return [base stringByAppendingString:@"CydiaIcon.png"];
1614 - (NSURL *) iconURL {
1615 if (NSString *uri = [self iconuri])
1616 return [NSURL URLWithString:uri];
1620 - (NSString *) key {
1621 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1624 - (NSString *) host {
1628 - (NSString *) name {
1629 return origin_.empty() ? (id) authority_ : origin_;
1632 - (NSString *) shortDescription {
1633 return description_;
1636 - (NSString *) label {
1637 return label_.empty() ? (id) authority_ : label_;
1640 - (NSString *) origin {
1644 - (NSString *) version {
1648 - (NSString *) defaultIcon {
1649 return defaultIcon_;
1654 /* CydiaOperation Class {{{ */
1655 @interface CydiaOperation : NSObject {
1656 _H<NSString> operator_;
1657 _H<NSString> value_;
1660 - (NSString *) operator;
1661 - (NSString *) value;
1665 @implementation CydiaOperation
1667 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1668 if ((self = [super init]) != nil) {
1669 operator_ = [NSString stringWithUTF8String:_operator];
1670 value_ = [NSString stringWithUTF8String:value];
1674 + (NSArray *) _attributeKeys {
1675 return [NSArray arrayWithObjects:
1681 - (NSArray *) attributeKeys {
1682 return [[self class] _attributeKeys];
1685 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1686 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1689 - (NSString *) operator {
1693 - (NSString *) value {
1699 /* CydiaClause Class {{{ */
1700 @interface CydiaClause : NSObject {
1701 _H<NSString> package_;
1702 _H<CydiaOperation> version_;
1705 - (NSString *) package;
1706 - (CydiaOperation *) version;
1710 @implementation CydiaClause
1712 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1713 if ((self = [super init]) != nil) {
1714 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1716 if (const char *version = dep.TargetVer())
1717 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1719 version_ = (id) [NSNull null];
1723 + (NSArray *) _attributeKeys {
1724 return [NSArray arrayWithObjects:
1730 - (NSArray *) attributeKeys {
1731 return [[self class] _attributeKeys];
1734 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1735 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1738 - (NSString *) package {
1742 - (CydiaOperation *) version {
1748 /* CydiaRelation Class {{{ */
1749 @interface CydiaRelation : NSObject {
1750 _H<NSString> relationship_;
1751 _H<NSMutableArray> clauses_;
1754 - (NSString *) relationship;
1755 - (NSArray *) clauses;
1759 @implementation CydiaRelation
1761 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1762 if ((self = [super init]) != nil) {
1763 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1764 clauses_ = [NSMutableArray arrayWithCapacity:8];
1766 pkgCache::DepIterator start;
1767 pkgCache::DepIterator end;
1768 dep.GlobOr(start, end); // ++dep
1771 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1773 // yes, seriously. (wtf?)
1781 + (NSArray *) _attributeKeys {
1782 return [NSArray arrayWithObjects:
1788 - (NSArray *) attributeKeys {
1789 return [[self class] _attributeKeys];
1792 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1793 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1796 - (NSString *) relationship {
1797 return relationship_;
1800 - (NSArray *) clauses {
1804 - (void) addClause:(CydiaClause *)clause {
1805 [clauses_ addObject:clause];
1810 /* Package Class {{{ */
1811 struct ParsedPackage {
1815 CYString architecture_;
1818 CYString depiction_;
1828 @interface Package : NSObject {
1831 uint32_t essential_ : 1;
1832 uint32_t obsolete_ : 1;
1833 uint32_t ignored_ : 1;
1834 uint32_t pooled_ : 1;
1840 _transient Database *database_;
1842 pkgCache::VerIterator version_;
1843 pkgCache::PkgIterator iterator_;
1844 pkgCache::VerFileIterator file_;
1850 CYString installed_;
1852 const char *section_;
1853 _transient NSString *section$_;
1857 PackageValue *metadata_;
1858 ParsedPackage *parsed_;
1860 _H<NSMutableArray> tags_;
1863 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1864 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1866 - (pkgCache::PkgIterator) iterator;
1869 - (NSString *) section;
1870 - (NSString *) simpleSection;
1872 - (NSString *) longSection;
1873 - (NSString *) shortSection;
1877 - (MIMEAddress *) maintainer;
1879 - (NSString *) longDescription;
1880 - (NSString *) shortDescription;
1883 - (PackageValue *) metadata;
1886 - (bool) subscribed;
1887 - (bool) setSubscribed:(bool)subscribed;
1891 - (NSString *) latest;
1892 - (NSString *) installed;
1893 - (BOOL) uninstalled;
1896 - (BOOL) upgradableAndEssential:(BOOL)essential;
1899 - (BOOL) unfiltered;
1903 - (BOOL) halfConfigured;
1904 - (BOOL) halfInstalled;
1906 - (NSString *) mode;
1909 - (NSString *) name;
1911 - (NSString *) homepage;
1912 - (NSString *) depiction;
1913 - (MIMEAddress *) author;
1915 - (NSString *) support;
1917 - (NSArray *) files;
1918 - (NSArray *) warnings;
1919 - (NSArray *) applications;
1921 - (Source *) source;
1924 - (BOOL) matches:(NSArray *)query;
1926 - (bool) hasSupportingRole;
1927 - (BOOL) hasTag:(NSString *)tag;
1928 - (NSString *) primaryPurpose;
1929 - (NSArray *) purposes;
1930 - (bool) isCommercial;
1932 - (void) setIndex:(size_t)index;
1934 - (CYString &) cyname;
1936 - (uint32_t) compareBySection:(NSArray *)sections;
1941 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1942 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1943 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1944 - (bool) isVisibleInSection:(NSString *)section;
1945 - (bool) isVisibleInSource:(Source *)source;
1949 uint32_t PackageChangesRadix(Package *self, void *) {
1954 uint32_t timestamp : 30;
1955 uint32_t ignored : 1;
1956 uint32_t upgradable : 1;
1960 bool upgradable([self upgradableAndEssential:YES]);
1961 value.bits.upgradable = upgradable ? 1 : 0;
1964 value.bits.timestamp = 0;
1965 value.bits.ignored = [self ignored] ? 0 : 1;
1966 value.bits.upgradable = 1;
1968 value.bits.timestamp = [self seen] >> 2;
1969 value.bits.ignored = 0;
1970 value.bits.upgradable = 0;
1973 return _not(uint32_t) - value.key;
1976 uint32_t PackagePrefixRadix(Package *self, void *context) {
1977 size_t offset(reinterpret_cast<size_t>(context));
1978 CYString &name([self cyname]);
1980 size_t size(name.size());
1983 char *text(name.data());
1986 if (!isdigit(text[0]))
1990 while (size != digits && isdigit(text[digits]))
1998 if (offset == 0 && zeros != 0) {
1999 memset(data, '0', zeros);
2000 memcpy(data + zeros, text, 4 - zeros);
2002 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2003 if (size <= offset - zeros)
2006 text += offset - zeros;
2007 size -= offset - zeros;
2010 memcpy(data, text, 4);
2012 memcpy(data, text, size);
2013 memset(data + size, 0, 4 - size);
2016 for (size_t i(0); i != 4; ++i)
2017 if (isalpha(data[i]))
2025 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2027 /* XXX: ntohl may be more honest */
2028 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2031 CYString &(*PackageName)(Package *self, SEL sel);
2033 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2034 _profile(PackageNameCompare)
2035 CYString &lhi(PackageName(lhs, @selector(cyname)));
2036 CYString &rhi(PackageName(rhs, @selector(cyname)));
2037 CFStringRef lhn(lhi), rhn(rhi);
2040 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2041 else if (rhn == NULL)
2042 return NSOrderedDescending;
2044 _profile(PackageNameCompare$NumbersLast)
2045 if (!lhi.empty() && !rhi.empty()) {
2046 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2047 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2048 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2049 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2050 return lha ? NSOrderedAscending : NSOrderedDescending;
2054 CFIndex length = CFStringGetLength(lhn);
2056 _profile(PackageNameCompare$Compare)
2057 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2062 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2063 return PackageNameCompare(*lhs, *rhs, context);
2066 struct PackageNameOrdering :
2067 std::binary_function<Package *, Package *, bool>
2069 _finline bool operator ()(Package *lhs, Package *rhs) const {
2070 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2074 @implementation Package
2076 - (NSString *) description {
2077 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2082 apr_pool_destroy(pool_);
2083 if (parsed_ != NULL)
2088 + (NSString *) webScriptNameForSelector:(SEL)selector {
2090 else if (selector == @selector(clear))
2092 else if (selector == @selector(getField:))
2094 else if (selector == @selector(hasTag:))
2096 else if (selector == @selector(install))
2098 else if (selector == @selector(remove))
2104 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2105 return [self webScriptNameForSelector:selector] == nil;
2108 + (NSArray *) _attributeKeys {
2109 return [NSArray arrayWithObjects:
2130 @"shortDescription",
2143 - (NSArray *) attributeKeys {
2144 return [[self class] _attributeKeys];
2147 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2148 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2151 - (NSArray *) relations {
2152 @synchronized (database_) {
2153 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2154 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2155 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2159 - (NSString *) architecture {
2161 @synchronized (database_) {
2162 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2165 - (NSString *) getField:(NSString *)name {
2166 @synchronized (database_) {
2167 if ([database_ era] != era_ || file_.end())
2170 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2172 const char *start, *end;
2173 if (!parser.Find([name UTF8String], start, end))
2174 return (NSString *) [NSNull null];
2176 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2180 if (parsed_ != NULL)
2182 @synchronized (database_) {
2183 if ([database_ era] != era_ || file_.end())
2186 ParsedPackage *parsed(new ParsedPackage);
2189 _profile(Package$parse)
2190 pkgRecords::Parser *parser;
2192 _profile(Package$parse$Lookup)
2193 parser = &[database_ records]->Lookup(file_);
2198 _profile(Package$parse$Find)
2203 {"architecture", &parsed->architecture_},
2204 {"icon", &parsed->icon_},
2205 {"depiction", &parsed->depiction_},
2206 {"homepage", &parsed->homepage_},
2207 {"website", &website},
2208 {"bugs", &parsed->bugs_},
2209 {"support", &parsed->support_},
2210 {"sponsor", &parsed->sponsor_},
2211 {"author", &parsed->author_},
2212 {"md5sum", &parsed->md5sum_},
2215 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2216 const char *start, *end;
2218 if (parser->Find(names[i].name_, start, end)) {
2219 CYString &value(*names[i].value_);
2220 _profile(Package$parse$Value)
2221 value.set(pool_, start, end - start);
2227 _profile(Package$parse$Tagline)
2228 const char *start, *end;
2229 if (parser->ShortDesc(start, end)) {
2230 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2233 while (stop != start && stop[-1] == '\r')
2235 parsed->tagline_.set(pool_, start, stop - start);
2239 _profile(Package$parse$Retain)
2240 if (parsed->homepage_.empty())
2241 parsed->homepage_ = website;
2242 if (parsed->homepage_ == parsed->depiction_)
2243 parsed->homepage_.clear();
2248 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2249 if ((self = [super init]) != nil) {
2250 _profile(Package$initWithVersion)
2252 apr_pool_create(&pool_, NULL);
2258 database_ = database;
2259 era_ = [database era];
2263 pkgCache::PkgIterator iterator(version.ParentPkg());
2264 iterator_ = iterator;
2266 _profile(Package$initWithVersion$Version)
2267 if (!version_.end())
2268 file_ = version_.FileList();
2270 pkgCache &cache([database_ cache]);
2271 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2275 _profile(Package$initWithVersion$Cache)
2276 name_.set(NULL, iterator.Display());
2278 latest_.set(NULL, StripVersion_(version_.VerStr()));
2280 pkgCache::VerIterator current(iterator.CurrentVer());
2282 installed_.set(NULL, StripVersion_(current.VerStr()));
2285 _profile(Package$initWithVersion$Tags)
2286 pkgCache::TagIterator tag(iterator.TagList());
2288 tags_ = [NSMutableArray arrayWithCapacity:8];
2290 const char *name(tag.Name());
2291 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2293 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2294 if (strcmp(name + 6, "enduser") == 0)
2296 else if (strcmp(name + 6, "hacker") == 0)
2298 else if (strcmp(name + 6, "developer") == 0)
2300 else if (strcmp(name + 6, "cydia") == 0)
2306 if (strncmp(name, "cydia::", 7) == 0) {
2307 if (strcmp(name + 7, "essential") == 0)
2309 else if (strcmp(name + 7, "obsolete") == 0)
2314 } while (!tag.end());
2318 _profile(Package$initWithVersion$Metadata)
2319 const char *mixed(iterator.Name());
2320 size_t size(strlen(mixed));
2321 char lower[size + 1];
2323 for (size_t i(0); i != size; ++i)
2324 lower[i] = mixed[i] | 0x20;
2327 PackageValue *metadata(PackageFind(lower, size));
2328 metadata_ = metadata;
2330 id_.set(NULL, metadata->name_, size);
2332 const char *latest(version_.VerStr());
2333 size_t length(strlen(latest));
2335 uint16_t vhash(hashlittle(latest, length));
2337 size_t capped(std::min<size_t>(8, length));
2338 latest = latest + length - capped;
2340 if (metadata->first_ == 0)
2341 metadata->first_ = now_;
2343 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2344 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2345 metadata->vhash_ = vhash;
2346 metadata->last_ = now_;
2347 } else if (metadata->last_ == 0)
2348 metadata->last_ = metadata->first_;
2351 _profile(Package$initWithVersion$Section)
2352 section_ = iterator.Section();
2355 _profile(Package$initWithVersion$Flags)
2356 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2357 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2362 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2363 pkgCache::VerIterator version;
2365 _profile(Package$packageWithIterator$GetCandidateVer)
2366 version = [database policy]->GetCandidateVer(iterator);
2374 _profile(Package$packageWithIterator$Allocate)
2375 package = [Package allocWithZone:zone];
2378 _profile(Package$packageWithIterator$Initialize)
2380 initWithVersion:version
2387 _profile(Package$packageWithIterator$Autorelease)
2388 package = [package autorelease];
2394 - (pkgCache::PkgIterator) iterator {
2398 - (NSString *) section {
2399 if (section$_ == nil) {
2400 if (section_ == NULL)
2403 _profile(Package$section$mappedSectionForPointer)
2404 section$_ = [database_ mappedSectionForPointer:section_];
2409 - (NSString *) simpleSection {
2410 if (NSString *section = [self section])
2411 return Simplify(section);
2416 - (NSString *) longSection {
2417 return LocalizeSection([self section]);
2420 - (NSString *) shortSection {
2421 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2424 - (NSString *) uri {
2427 pkgIndexFile *index;
2428 pkgCache::PkgFileIterator file(file_.File());
2429 if (![database_ list].FindIndex(file, index))
2431 return [NSString stringWithUTF8String:iterator_->Path];
2432 //return [NSString stringWithUTF8String:file.Site()];
2433 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2437 - (MIMEAddress *) maintainer {
2438 @synchronized (database_) {
2439 if ([database_ era] != era_ || file_.end())
2442 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2443 const std::string &maintainer(parser->Maintainer());
2444 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2447 - (NSString *) md5sum {
2448 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2452 @synchronized (database_) {
2453 if ([database_ era] != era_ || version_.end())
2456 return version_->InstalledSize;
2459 - (NSString *) longDescription {
2460 @synchronized (database_) {
2461 if ([database_ era] != era_ || file_.end())
2464 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2465 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2467 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2468 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2469 if ([lines count] < 2)
2472 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2473 for (size_t i(1), e([lines count]); i != e; ++i) {
2474 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2475 [trimmed addObject:trim];
2478 return [trimmed componentsJoinedByString:@"\n"];
2481 - (NSString *) shortDescription {
2482 if (parsed_ != NULL)
2483 return static_cast<NSString *>(parsed_->tagline_);
2485 @synchronized (database_) {
2486 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2488 const char *start, *end;
2489 if (!parser.ShortDesc(start, end))
2492 if (end - start > 200)
2496 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2499 while (end != start && end[-1] == '\r')
2503 return [(id) CYStringCreate(start, end - start) autorelease];
2507 _profile(Package$index)
2508 CFStringRef name((CFStringRef) [self name]);
2509 if (CFStringGetLength(name) == 0)
2511 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2512 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2514 return toupper(character);
2518 - (PackageValue *) metadata {
2523 PackageValue *metadata([self metadata]);
2524 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2527 - (bool) subscribed {
2528 return [self metadata]->subscribed_;
2531 - (bool) setSubscribed:(bool)subscribed {
2532 PackageValue *metadata([self metadata]);
2533 if (metadata->subscribed_ == subscribed)
2535 metadata->subscribed_ = subscribed;
2543 - (NSString *) latest {
2547 - (NSString *) installed {
2551 - (BOOL) uninstalled {
2552 return installed_.empty();
2556 return !version_.end();
2559 - (BOOL) upgradableAndEssential:(BOOL)essential {
2560 _profile(Package$upgradableAndEssential)
2561 pkgCache::VerIterator current(iterator_.CurrentVer());
2563 return essential && essential_;
2565 return !version_.end() && version_ != current;
2569 - (BOOL) essential {
2574 return [database_ cache][iterator_].InstBroken();
2577 - (BOOL) unfiltered {
2578 _profile(Package$unfiltered$obsolete)
2579 if (_unlikely(obsolete_))
2583 _profile(Package$unfiltered$hasSupportingRole)
2584 if (_unlikely(![self hasSupportingRole]))
2592 if (![self unfiltered])
2597 _profile(Package$visible$section)
2598 section = [self section];
2601 _profile(Package$visible$isSectionVisible)
2602 if (!isSectionVisible(section))
2610 unsigned char current(iterator_->CurrentState);
2611 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2614 - (BOOL) halfConfigured {
2615 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2618 - (BOOL) halfInstalled {
2619 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2623 @synchronized (database_) {
2624 if ([database_ era] != era_ || iterator_.end())
2627 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2628 return state.Mode != pkgDepCache::ModeKeep;
2631 - (NSString *) mode {
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || iterator_.end())
2636 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2638 switch (state.Mode) {
2639 case pkgDepCache::ModeDelete:
2640 if ((state.iFlags & pkgDepCache::Purge) != 0)
2644 case pkgDepCache::ModeKeep:
2645 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2646 return @"REINSTALL";
2647 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2651 case pkgDepCache::ModeInstall:
2652 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2653 return @"REINSTALL";
2654 else*/ switch (state.Status) {
2656 return @"DOWNGRADE";
2662 return @"NEW_INSTALL";
2673 - (NSString *) name {
2674 return name_.empty() ? id_ : name_;
2677 - (UIImage *) icon {
2678 NSString *section = [self simpleSection];
2681 if (parsed_ != NULL)
2682 if (NSString *href = parsed_->icon_)
2683 if ([href hasPrefix:@"file:///"])
2684 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2685 if (icon == nil) if (section != nil)
2686 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2687 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2688 if ([dicon hasPrefix:@"file:///"])
2689 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2691 icon = [UIImage applicationImageNamed:@"unknown.png"];
2695 - (NSString *) homepage {
2696 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2699 - (NSString *) depiction {
2700 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2703 - (MIMEAddress *) sponsor {
2704 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2707 - (MIMEAddress *) author {
2708 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2711 - (NSString *) support {
2712 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2715 - (NSArray *) files {
2716 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2717 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2720 fin.open([path UTF8String]);
2725 while (std::getline(fin, line))
2726 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2731 - (NSString *) state {
2732 @synchronized (database_) {
2733 if ([database_ era] != era_ || file_.end())
2736 switch (iterator_->CurrentState) {
2737 case pkgCache::State::NotInstalled:
2738 return @"NotInstalled";
2739 case pkgCache::State::UnPacked:
2741 case pkgCache::State::HalfConfigured:
2742 return @"HalfConfigured";
2743 case pkgCache::State::HalfInstalled:
2744 return @"HalfInstalled";
2745 case pkgCache::State::ConfigFiles:
2746 return @"ConfigFiles";
2747 case pkgCache::State::Installed:
2748 return @"Installed";
2749 case pkgCache::State::TriggersAwaited:
2750 return @"TriggersAwaited";
2751 case pkgCache::State::TriggersPending:
2752 return @"TriggersPending";
2755 return (NSString *) [NSNull null];
2758 - (NSString *) selection {
2759 @synchronized (database_) {
2760 if ([database_ era] != era_ || file_.end())
2763 switch (iterator_->SelectedState) {
2764 case pkgCache::State::Unknown:
2766 case pkgCache::State::Install:
2768 case pkgCache::State::Hold:
2770 case pkgCache::State::DeInstall:
2771 return @"DeInstall";
2772 case pkgCache::State::Purge:
2776 return (NSString *) [NSNull null];
2779 - (NSArray *) warnings {
2780 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2781 const char *name(iterator_.Name());
2783 size_t length(strlen(name));
2784 if (length < 2) invalid:
2785 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2786 else for (size_t i(0); i != length; ++i)
2788 /* XXX: technically this is not allowed */
2789 (name[i] < 'A' || name[i] > 'Z') &&
2790 (name[i] < 'a' || name[i] > 'z') &&
2791 (name[i] < '0' || name[i] > '9') &&
2792 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2795 if (strcmp(name, "cydia") != 0) {
2798 bool _private = false;
2801 bool repository = [[self section] isEqualToString:@"Repositories"];
2803 if (NSArray *files = [self files])
2804 for (NSString *file in files)
2805 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2807 else if (!user && [file isEqualToString:@"/User"])
2809 else if (!_private && [file isEqualToString:@"/private"])
2811 else if (!stash && [file isEqualToString:@"/var/stash"])
2814 /* XXX: this is not sensitive enough. only some folders are valid. */
2815 if (cydia && !repository)
2816 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2818 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2820 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2822 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2825 return [warnings count] == 0 ? nil : warnings;
2828 - (NSArray *) applications {
2829 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2831 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2833 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2834 if (NSArray *files = [self files])
2835 for (NSString *file in files)
2836 if (application_r(file)) {
2837 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2838 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2839 if ([id isEqualToString:me])
2842 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2844 display = application_r[1];
2846 NSString *bundle([file stringByDeletingLastPathComponent]);
2847 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2848 if (icon == nil || [icon length] == 0)
2850 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2852 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2853 [applications addObject:application];
2855 [application addObject:id];
2856 [application addObject:display];
2857 [application addObject:url];
2860 return [applications count] == 0 ? nil : applications;
2863 - (Source *) source {
2864 if (source_ == nil) {
2865 @synchronized (database_) {
2866 if ([database_ era] != era_ || file_.end())
2867 source_ = (Source *) [NSNull null];
2869 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2873 return source_ == (Source *) [NSNull null] ? nil : source_;
2880 - (BOOL) matches:(NSArray *)query {
2881 if (query == nil || [query count] == 0)
2890 string = [self name];
2891 length = [string length];
2893 for (NSString *term in query) {
2894 range = [string rangeOfString:term options:MatchCompareOptions_];
2895 if (range.location != NSNotFound)
2896 rank_ -= 6 * 1000000 / length;
2901 length = [string length];
2903 for (NSString *term in query) {
2904 range = [string rangeOfString:term options:MatchCompareOptions_];
2905 if (range.location != NSNotFound)
2906 rank_ -= 6 * 1000000 / length;
2910 string = [self shortDescription];
2911 length = [string length];
2912 NSUInteger stop(std::min<NSUInteger>(length, 200));
2914 for (NSString *term in query) {
2915 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2916 if (range.location != NSNotFound)
2917 rank_ -= 2 * 100000;
2923 - (bool) hasSupportingRole {
2928 if ([Role_ isEqualToString:@"User"])
2932 if ([Role_ isEqualToString:@"Hacker"])
2936 if ([Role_ isEqualToString:@"Developer"])
2941 - (NSArray *) tags {
2945 - (BOOL) hasTag:(NSString *)tag {
2946 return tags_ == nil ? NO : [tags_ containsObject:tag];
2949 - (NSString *) primaryPurpose {
2950 for (NSString *tag in (NSArray *) tags_)
2951 if ([tag hasPrefix:@"purpose::"])
2952 return [tag substringFromIndex:9];
2956 - (NSArray *) purposes {
2957 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2958 for (NSString *tag in (NSArray *) tags_)
2959 if ([tag hasPrefix:@"purpose::"])
2960 [purposes addObject:[tag substringFromIndex:9]];
2961 return [purposes count] == 0 ? nil : purposes;
2964 - (bool) isCommercial {
2965 return [self hasTag:@"cydia::commercial"];
2968 - (void) setIndex:(size_t)index {
2969 if (metadata_->index_ != index)
2970 metadata_->index_ = index;
2973 - (CYString &) cyname {
2974 return name_.empty() ? id_ : name_;
2977 - (uint32_t) compareBySection:(NSArray *)sections {
2978 NSString *section([self section]);
2979 for (size_t i(0), e([sections count]); i != e; ++i) {
2980 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2984 return _not(uint32_t);
2988 @synchronized (database_) {
2989 pkgProblemResolver *resolver = [database_ resolver];
2990 resolver->Clear(iterator_);
2992 pkgCacheFile &cache([database_ cache]);
2993 cache->SetReInstall(iterator_, false);
2994 cache->MarkKeep(iterator_, false);
2998 @synchronized (database_) {
2999 pkgProblemResolver *resolver = [database_ resolver];
3000 resolver->Clear(iterator_);
3001 resolver->Protect(iterator_);
3003 pkgCacheFile &cache([database_ cache]);
3004 cache->SetReInstall(iterator_, false);
3005 cache->MarkInstall(iterator_, false);
3007 pkgDepCache::StateCache &state((*cache)[iterator_]);
3008 if (!state.Install())
3009 cache->SetReInstall(iterator_, true);
3013 @synchronized (database_) {
3014 pkgProblemResolver *resolver = [database_ resolver];
3015 resolver->Clear(iterator_);
3016 resolver->Remove(iterator_);
3017 resolver->Protect(iterator_);
3019 pkgCacheFile &cache([database_ cache]);
3020 cache->SetReInstall(iterator_, false);
3021 cache->MarkDelete(iterator_, true);
3024 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3025 _profile(Package$isUnfilteredAndSearchedForBy)
3028 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3029 value &= [self unfiltered];
3032 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3033 value &= [self matches:query];
3040 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3041 if ([search length] == 0)
3044 _profile(Package$isUnfilteredAndSelectedForBy)
3047 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3048 value &= [self unfiltered];
3051 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3052 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3059 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3060 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3063 - (bool) isVisibleInSection:(NSString *)name {
3064 NSString *section([self section]);
3068 section == nil && [name length] == 0 ||
3069 [name isEqualToString:section]
3070 ) && [self visible];
3073 - (bool) isVisibleInSource:(Source *)source {
3074 return [self source] == source && [self visible];
3079 /* Section Class {{{ */
3080 @interface Section : NSObject {
3085 _H<NSString> localized_;
3088 - (NSComparisonResult) compareByLocalized:(Section *)section;
3089 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3090 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3091 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3092 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3093 - (NSString *) name;
3100 - (void) addToCount;
3102 - (void) setCount:(size_t)count;
3103 - (NSString *) localized;
3107 @implementation Section
3109 - (NSComparisonResult) compareByLocalized:(Section *)section {
3110 NSString *lhs(localized_);
3111 NSString *rhs([section localized]);
3113 /*if ([lhs length] != 0 && [rhs length] != 0) {
3114 unichar lhc = [lhs characterAtIndex:0];
3115 unichar rhc = [rhs characterAtIndex:0];
3117 if (isalpha(lhc) && !isalpha(rhc))
3118 return NSOrderedAscending;
3119 else if (!isalpha(lhc) && isalpha(rhc))
3120 return NSOrderedDescending;
3123 return [lhs compare:rhs options:LaxCompareOptions_];
3126 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3127 if ((self = [self initWithName:name localize:NO]) != nil) {
3128 if (localized != nil)
3129 localized_ = localized;
3133 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3134 return [self initWithName:name row:0 localize:localize];
3137 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3138 if ((self = [super init]) != nil) {
3143 localized_ = LocalizeSection(name_);
3147 /* XXX: localize the index thingees */
3148 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3149 if ((self = [super init]) != nil) {
3150 name_ = [NSString stringWithCharacters:&index length:1];
3156 - (NSString *) name {
3176 - (void) addToCount {
3180 - (void) setCount:(size_t)count {
3184 - (NSString *) localized {
3191 class CydiaLogCleaner :
3192 public pkgArchiveCleaner
3195 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3200 /* Database Implementation {{{ */
3201 @implementation Database
3203 + (Database *) sharedInstance {
3204 static _H<Database> instance;
3205 if (instance == nil)
3206 instance = [[[Database alloc] init] autorelease];
3214 - (void) releasePackages {
3215 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3216 CFArrayRemoveAllValues(packages_);
3220 // XXX: actually implement this thing
3222 [self releasePackages];
3223 apr_pool_destroy(pool_);
3224 NSRecycleZone(zone_);
3228 - (void) _readCydia:(NSNumber *)fd {
3229 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3230 std::istream is(&ib);
3233 static Pcre finish_r("^finish:([^:]*)$");
3235 while (std::getline(is, line)) {
3236 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3238 const char *data(line.c_str());
3239 size_t size = line.size();
3240 lprintf("C:%s\n", data);
3242 if (finish_r(data, size)) {
3243 NSString *finish = finish_r[1];
3244 int index = [Finishes_ indexOfObject:finish];
3245 if (index != INT_MAX && index > Finish_)
3255 - (void) _readStatus:(NSNumber *)fd {
3256 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3257 std::istream is(&ib);
3260 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3261 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3263 while (std::getline(is, line)) {
3264 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3266 const char *data(line.c_str());
3267 size_t size(line.size());
3268 lprintf("S:%s\n", data);
3270 if (conffile_r(data, size)) {
3271 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3272 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3273 } else if (strncmp(data, "status: ", 8) == 0) {
3274 // status: <package>: {unpacked,half-configured,installed}
3275 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3276 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3277 } else if (strncmp(data, "processing: ", 12) == 0) {
3278 // processing: configure: config-test
3279 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3280 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3281 } else if (pmstatus_r(data, size)) {
3282 std::string type([pmstatus_r[1] UTF8String]);
3284 NSString *package = pmstatus_r[2];
3285 if ([package isEqualToString:@"dpkg-exec"])
3288 float percent([pmstatus_r[3] floatValue]);
3289 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3291 NSString *string = pmstatus_r[4];
3293 if (type == "pmerror") {
3294 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3295 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3296 } else if (type == "pmstatus") {
3297 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3298 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3299 } else if (type == "pmconffile")
3300 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3302 lprintf("E:unknown pmstatus\n");
3304 lprintf("E:unknown status\n");
3312 - (void) _readOutput:(NSNumber *)fd {
3313 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3314 std::istream is(&ib);
3317 while (std::getline(is, line)) {
3318 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3320 lprintf("O:%s\n", line.c_str());
3322 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3323 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3335 - (Package *) packageWithName:(NSString *)name {
3338 @synchronized (self) {
3339 if (static_cast<pkgDepCache *>(cache_) == NULL)
3341 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3342 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3346 if ((self = [super init]) != nil) {
3353 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3354 apr_pool_create(&pool_, NULL);
3356 size_t capacity(MetaFile_->active_);
3362 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3363 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3367 _assert(pipe(fds) != -1);
3370 _config->Set("APT::Keep-Fds::", cydiafd_);
3371 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3374 detachNewThreadSelector:@selector(_readCydia:)
3376 withObject:[NSNumber numberWithInt:fds[0]]
3379 _assert(pipe(fds) != -1);
3383 detachNewThreadSelector:@selector(_readStatus:)
3385 withObject:[NSNumber numberWithInt:fds[0]]
3388 _assert(pipe(fds) != -1);
3389 _assert(dup2(fds[0], 0) != -1);
3390 _assert(close(fds[0]) != -1);
3392 input_ = fdopen(fds[1], "a");
3394 _assert(pipe(fds) != -1);
3395 _assert(dup2(fds[1], 1) != -1);
3396 _assert(close(fds[1]) != -1);
3399 detachNewThreadSelector:@selector(_readOutput:)
3401 withObject:[NSNumber numberWithInt:fds[0]]
3406 - (pkgCacheFile &) cache {
3410 - (pkgDepCache::Policy *) policy {
3414 - (pkgRecords *) records {
3418 - (pkgProblemResolver *) resolver {
3422 - (pkgAcquire &) fetcher {
3426 - (pkgSourceList &) list {
3430 - (NSArray *) packages {
3431 return (NSArray *) packages_;
3434 - (NSArray *) sources {
3438 - (Source *) sourceWithKey:(NSString *)key {
3439 for (Source *source in [self sources]) {
3440 if ([[source key] isEqualToString:key])
3445 - (bool) popErrorWithTitle:(NSString *)title {
3448 while (!_error->empty()) {
3450 bool warning(!_error->PopMessage(error));
3455 size_t size(error.size());
3456 if (size == 0 || error[size - 1] != '\n')
3458 error.resize(size - 1);
3461 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3463 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3464 if (warning && no_pubkey(error.c_str()))
3467 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3473 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3474 return [self popErrorWithTitle:title] || !success;
3477 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3478 @synchronized (self) {
3481 [self releasePackages];
3484 [sourceList_ removeAllObjects];
3504 apr_pool_clear(pool_);
3506 NSRecycleZone(zone_);
3507 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3509 int chk(creat("/tmp/cydia.chk", 0644));
3513 if (invocation != nil)
3514 [invocation invoke];
3516 NSString *title(UCLocalize("DATABASE"));
3519 OpProgress progress;
3520 while (!cache_.Open(progress, true)) { pop:
3522 bool warning(!_error->PopMessage(error));
3523 lprintf("cache_.Open():[%s]\n", error.c_str());
3525 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3526 [delegate_ repairWithSelector:@selector(configure)];
3527 else if (error == "The package lists or status file could not be parsed or opened.")
3528 [delegate_ repairWithSelector:@selector(update)];
3529 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3530 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3531 // else if (error == "Malformed Status line")
3532 // else if (error == "The list of sources could not be read.")
3534 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3544 unlink("/tmp/cydia.chk");
3546 now_ = [[NSDate date] timeIntervalSince1970];
3548 policy_ = new pkgDepCache::Policy();
3549 records_ = new pkgRecords(cache_);
3550 resolver_ = new pkgProblemResolver(cache_);
3551 fetcher_ = new pkgAcquire(&status_);
3554 list_ = new pkgSourceList();
3555 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3558 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3559 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3563 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3566 if (cache_->BrokenCount() != 0) {
3567 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3570 if (cache_->BrokenCount() != 0) {
3571 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3575 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3579 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3580 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3581 [sourceList_ addObject:object];
3583 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3584 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3585 // XXX: this could be more intelligent
3586 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3587 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3589 sourceMap_[cached->ID] = object;
3594 /*std::vector<Package *> packages;
3595 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3600 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3601 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3602 //packages.push_back(package);
3603 CFArrayAppendValue(packages_, CFRetain(package));
3607 /*if (packages.empty())
3608 packages_ = [[NSArray alloc] init];
3610 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3613 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3614 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3615 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3623 /*if (!packages.empty())
3624 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3625 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3627 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3629 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3631 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3635 size_t count(CFArrayGetCount(packages_));
3636 MetaFile_->active_ = count;
3638 for (size_t index(0); index != count; ++index)
3639 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3646 @synchronized (self) {
3648 resolver_ = new pkgProblemResolver(cache_);
3650 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3651 if (!cache_[iterator].Keep())
3652 cache_->MarkKeep(iterator, false);
3653 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3654 cache_->SetReInstall(iterator, false);
3657 - (void) configure {
3658 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3660 system([dpkg UTF8String]);
3665 // XXX: I don't remember this condition
3670 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3672 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3674 if ([self popErrorWithTitle:title])
3678 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3680 CydiaLogCleaner cleaner;
3681 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3688 fetcher_->Shutdown();
3690 pkgRecords records(cache_);
3692 lock_ = new FileFd();
3693 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3695 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3697 if ([self popErrorWithTitle:title])
3701 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3704 manager_ = (_system->CreatePM(cache_));
3705 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3712 bool substrate(RestartSubstrate_);
3713 RestartSubstrate_ = false;
3715 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3717 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3719 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3721 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3722 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3725 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3727 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3729 [self popErrorWithTitle:title];
3733 bool failed = false;
3734 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3735 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3737 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3743 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3751 RestartSubstrate_ = true;
3754 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3756 if (_error->PendingError()) {
3761 if (result == pkgPackageManager::Failed) {
3766 if (result != pkgPackageManager::Completed) {
3771 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3773 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3775 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3776 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3779 if (![before isEqualToArray:after])
3784 NSString *title(UCLocalize("UPGRADE"));
3785 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3791 [self updateWithStatus:status_];
3794 - (void) updateWithStatus:(Status &)status {
3795 NSString *title(UCLocalize("REFRESHING_DATA"));
3798 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3802 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3803 if ([self popErrorWithTitle:title])
3806 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3808 bool success(ListUpdate(status, list, PulseInterval_));
3809 if (status.WasCancelled())
3812 [self popErrorWithTitle:title forOperation:success];
3813 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3817 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3820 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3821 delegate_ = delegate;
3824 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3825 progress_ = delegate;
3826 status_.setDelegate(delegate);
3829 - (NSObject<ProgressDelegate> *) progressDelegate {
3833 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3834 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3835 return i == sourceMap_.end() ? nil : i->second;
3838 - (NSString *) mappedSectionForPointer:(const char *)section {
3839 _H<NSString> *mapped;
3841 _profile(Database$mappedSectionForPointer$Cache)
3842 mapped = §ions_[section];
3845 if (*mapped == NULL) {
3846 size_t length(strlen(section));
3847 char spaced[length + 1];
3849 _profile(Database$mappedSectionForPointer$Replace)
3850 for (size_t index(0); index != length; ++index)
3851 spaced[index] = section[index] == '_' ? ' ' : section[index];
3852 spaced[length] = '\0';
3857 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3858 string = [NSString stringWithUTF8String:spaced];
3861 _profile(Database$mappedSectionForPointer$Map)
3862 string = [SectionMap_ objectForKey:string] ?: string;
3872 static _H<NSMutableSet> Diversions_;
3874 @interface Diversion : NSObject {
3877 _H<NSString> format_;
3882 @implementation Diversion
3884 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3885 if ((self = [super init]) != nil) {
3886 pattern_ = [from UTF8String];
3892 - (NSString *) divert:(NSString *)url {
3893 return !pattern_(url) ? nil : pattern_->*format_;
3896 + (NSURL *) divertURL:(NSURL *)url {
3898 NSString *href([url absoluteString]);
3900 for (Diversion *diversion in (id) Diversions_)
3901 if (NSString *diverted = [diversion divert:href]) {
3903 NSLog(@"div: %@", diverted);
3905 url = [NSURL URLWithString:diverted];
3912 - (NSString *) key {
3916 - (NSUInteger) hash {
3920 - (BOOL) isEqual:(Diversion *)object {
3921 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3926 @interface CydiaObject : NSObject {
3927 _H<IndirectDelegate> indirect_;
3928 _transient id delegate_;
3931 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3935 @interface CydiaWebViewController : CyteWebViewController {
3936 _H<CydiaObject> cydia_;
3939 + (void) addDiversion:(Diversion *)diversion;
3943 /* Web Scripting {{{ */
3944 @implementation CydiaObject
3946 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3947 if ((self = [super init]) != nil) {
3948 indirect_ = indirect;
3952 - (void) setDelegate:(id)delegate {
3953 delegate_ = delegate;
3956 + (NSArray *) _attributeKeys {
3957 return [NSArray arrayWithObjects:
3974 - (NSArray *) attributeKeys {
3975 return [[self class] _attributeKeys];
3978 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3979 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3982 - (NSString *) version {
3986 - (NSString *) device {
3987 return [[UIDevice currentDevice] uniqueIdentifier];
3990 - (NSString *) firmware {
3991 return [[UIDevice currentDevice] systemVersion];
3994 - (NSString *) hostname {
3995 return [[UIDevice currentDevice] name];
3998 - (NSString *) idiom {
3999 return (id) Idiom_ ?: [NSNull null];
4002 - (NSString *) plmn {
4003 return (id) PLMN_ ?: [NSNull null];
4006 - (NSString *) bbsnum {
4007 return (id) BBSNum_ ?: [NSNull null];
4010 - (NSString *) ecid {
4011 return (id) ChipID_ ?: [NSNull null];
4014 - (NSString *) serial {
4015 return SerialNumber_;
4018 - (NSString *) role {
4019 return (id) Role_ ?: [NSNull null];
4022 - (NSString *) model {
4023 return [NSString stringWithUTF8String:Machine_];
4026 - (NSString *) token {
4027 return (id) Token_ ?: [NSNull null];
4030 + (NSString *) webScriptNameForSelector:(SEL)selector {
4032 else if (selector == @selector(addBridgedHost:))
4033 return @"addBridgedHost";
4034 else if (selector == @selector(addInsecureHost:))
4035 return @"addInsecureHost";
4036 else if (selector == @selector(addInternalRedirect::))
4037 return @"addInternalRedirect";
4038 else if (selector == @selector(addPipelinedHost:scheme:))
4039 return @"addPipelinedHost";
4040 else if (selector == @selector(addSource:::))
4041 return @"addSource";
4042 else if (selector == @selector(addTokenHost:))
4043 return @"addTokenHost";
4044 else if (selector == @selector(addTrivialSource:))
4045 return @"addTrivialSource";
4046 else if (selector == @selector(close))
4048 else if (selector == @selector(du:))
4050 else if (selector == @selector(stringWithFormat:arguments:))
4052 else if (selector == @selector(getAllSources))
4053 return @"getAllSourcs";
4054 else if (selector == @selector(getKernelNumber:))
4055 return @"getKernelNumber";
4056 else if (selector == @selector(getKernelString:))
4057 return @"getKernelString";
4058 else if (selector == @selector(getInstalledPackages))
4059 return @"getInstalledPackages";
4060 else if (selector == @selector(getIORegistryEntry::))
4061 return @"getIORegistryEntry";
4062 else if (selector == @selector(getLocaleIdentifier))
4063 return @"getLocaleIdentifier";
4064 else if (selector == @selector(getPreferredLanguages))
4065 return @"getPreferredLanguages";
4066 else if (selector == @selector(getPackageById:))
4067 return @"getPackageById";
4068 else if (selector == @selector(getMetadataKeys))
4069 return @"getMetadataKeys";
4070 else if (selector == @selector(getMetadataValue:))
4071 return @"getMetadataValue";
4072 else if (selector == @selector(getSessionValue:))
4073 return @"getSessionValue";
4074 else if (selector == @selector(installPackages:))
4075 return @"installPackages";
4076 else if (selector == @selector(localizedStringForKey:value:table:))
4078 else if (selector == @selector(popViewController:))
4079 return @"popViewController";
4080 else if (selector == @selector(refreshSources))
4081 return @"refreshSources";
4082 else if (selector == @selector(removeButton))
4083 return @"removeButton";
4084 else if (selector == @selector(saveConfig))
4085 return @"saveConfig";
4086 else if (selector == @selector(setCydiaSource:))
4087 return @"setCydiaSource";
4088 else if (selector == @selector(setMetadataValue::))
4089 return @"setMetadataValue";
4090 else if (selector == @selector(setSessionValue::))
4091 return @"setSessionValue";
4092 else if (selector == @selector(substitutePackageNames:))
4093 return @"substitutePackageNames";
4094 else if (selector == @selector(scrollToBottom:))
4095 return @"scrollToBottom";
4096 else if (selector == @selector(setAllowsNavigationAction:))
4097 return @"setAllowsNavigationAction";
4098 else if (selector == @selector(setBadgeValue:))
4099 return @"setBadgeValue";
4100 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4101 return @"setButtonImage";
4102 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4103 return @"setButtonTitle";
4104 else if (selector == @selector(setHidesBackButton:))
4105 return @"setHidesBackButton";
4106 else if (selector == @selector(setHidesNavigationBar:))
4107 return @"setHidesNavigationBar";
4108 else if (selector == @selector(setNavigationBarStyle:))
4109 return @"setNavigationBarStyle";
4110 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4111 return @"setNavigationBarTintColor";
4112 else if (selector == @selector(setPasteboardString:))
4113 return @"setPasteboardString";
4114 else if (selector == @selector(setPasteboardURL:))
4115 return @"setPasteboardURL";
4116 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4117 return @"setScrollAlwaysBounceVertical";
4118 else if (selector == @selector(setScrollIndicatorStyle:))
4119 return @"setScrollIndicatorStyle";
4120 else if (selector == @selector(setToken:))
4122 else if (selector == @selector(setViewportWidth:))
4123 return @"setViewportWidth";
4124 else if (selector == @selector(statfs:))
4126 else if (selector == @selector(supports:))
4128 else if (selector == @selector(unload))
4134 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4135 return [self webScriptNameForSelector:selector] == nil;
4138 - (BOOL) supports:(NSString *)feature {
4139 return [feature isEqualToString:@"window.open"];
4143 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4146 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4147 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4150 - (void) setScrollIndicatorStyle:(NSString *)style {
4151 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4154 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4155 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4158 - (NSNumber *) getKernelNumber:(NSString *)name {
4159 const char *string([name UTF8String]);
4162 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4163 return (id) [NSNull null];
4165 if (size != sizeof(int))
4166 return (id) [NSNull null];
4169 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4170 return (id) [NSNull null];
4172 return [NSNumber numberWithInt:value];
4175 - (NSString *) getKernelString:(NSString *)name {
4176 const char *string([name UTF8String]);
4179 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4180 return (id) [NSNull null];
4182 char value[size + 1];
4183 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4184 return (id) [NSNull null];
4186 // XXX: just in case you request something ludicrous
4189 return [NSString stringWithCString:value];
4192 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4193 NSObject *value(CYIOGetValue([path UTF8String], entry));
4196 if ([value isKindOfClass:[NSData class]])
4197 value = CYHex((NSData *) value);
4202 - (void) _setCydiaSource:(NSString *)source {
4203 @synchronized (HostConfig_) {
4204 CydiaSource_ = source;
4205 [Metadata_ setObject:source forKey:@"CydiaSource"];
4211 - (void) setCydiaSource:(NSString *)source {
4212 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4215 - (NSString *) cydiaSource {
4216 @synchronized (HostConfig_) {
4217 return (id) CydiaSource_ ?: [NSNull null];
4221 - (NSArray *) getMetadataKeys {
4222 @synchronized (Values_) {
4223 return [Values_ allKeys];
4226 - (id) getMetadataValue:(NSString *)key {
4227 @synchronized (Values_) {
4228 return [Values_ objectForKey:key];
4231 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4232 @synchronized (Values_) {
4233 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4234 [Values_ removeObjectForKey:key];
4236 [Values_ setObject:value forKey:key];
4238 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4241 - (id) getSessionValue:(NSString *)key {
4242 @synchronized (SessionData_) {
4243 return [SessionData_ objectForKey:key];
4246 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4247 @synchronized (SessionData_) {
4248 if (value == (id) [WebUndefined undefined])
4249 [SessionData_ removeObjectForKey:key];
4251 [SessionData_ setObject:value forKey:key];
4254 - (void) addBridgedHost:(NSString *)host {
4255 @synchronized (HostConfig_) {
4256 [BridgedHosts_ addObject:host];
4259 - (void) addInsecureHost:(NSString *)host {
4260 @synchronized (HostConfig_) {
4261 [InsecureHosts_ addObject:host];
4264 - (void) addTokenHost:(NSString *)host {
4265 @synchronized (HostConfig_) {
4266 [TokenHosts_ addObject:host];
4269 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4270 @synchronized (HostConfig_) {
4271 if (scheme != (id) [WebUndefined undefined])
4272 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4274 [PipelinedHosts_ addObject:host];
4277 - (void) popViewController:(NSNumber *)value {
4278 if (value == (id) [WebUndefined undefined])
4279 value = [NSNumber numberWithBool:YES];
4280 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4283 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4284 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4286 for (NSString *section in sections)
4287 [array addObject:section];
4289 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4292 distribution, @"Distribution",
4294 nil] waitUntilDone:NO];
4297 - (void) addTrivialSource:(NSString *)href {
4298 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4301 - (void) refreshSources {
4302 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4305 - (void) saveConfig {
4306 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4309 - (NSArray *) getAllSources {
4310 return [[Database sharedInstance] sources];
4313 - (NSArray *) getInstalledPackages {
4314 Database *database([Database sharedInstance]);
4315 @synchronized (database) {
4316 NSArray *packages([database packages]);
4317 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4318 for (Package *package in packages)
4319 if (![package uninstalled])
4320 [installed addObject:package];
4324 - (Package *) getPackageById:(NSString *)id {
4325 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4329 return (Package *) [NSNull null];
4332 - (NSString *) getLocaleIdentifier {
4333 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4336 - (NSArray *) getPreferredLanguages {
4340 - (NSArray *) statfs:(NSString *)path {
4343 if (path == nil || statfs([path UTF8String], &stat) == -1)
4346 return [NSArray arrayWithObjects:
4347 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4348 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4349 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4353 - (NSNumber *) du:(NSString *)path {
4354 NSNumber *value(nil);
4357 _assert(pipe(fds) != -1);
4359 pid_t pid(ExecFork());
4361 _assert(dup2(fds[1], 1) != -1);
4362 _assert(close(fds[0]) != -1);
4363 _assert(close(fds[1]) != -1);
4364 /* XXX: this should probably not use du */
4365 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4370 _assert(close(fds[1]) != -1);
4372 if (FILE *du = fdopen(fds[0], "r")) {
4374 while (fgets(line, sizeof(line), du) != NULL) {
4375 size_t length(strlen(line));
4376 while (length != 0 && line[length - 1] == '\n')
4377 line[--length] = '\0';
4378 if (char *tab = strchr(line, '\t')) {
4380 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4385 } else _assert(close(fds[0]));
4393 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4396 - (void) installPackages:(NSArray *)packages {
4397 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4400 - (NSString *) substitutePackageNames:(NSString *)message {
4401 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4402 for (size_t i(0), e([words count]); i != e; ++i) {
4403 NSString *word([words objectAtIndex:i]);
4404 if (Package *package = [[Database sharedInstance] packageWithName:word])
4405 [words replaceObjectAtIndex:i withObject:[package name]];
4408 return [words componentsJoinedByString:@" "];
4411 - (void) removeButton {
4412 [indirect_ removeButton];
4415 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4416 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4419 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4420 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4423 - (void) setBadgeValue:(id)value {
4424 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4427 - (void) setAllowsNavigationAction:(NSString *)value {
4428 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4431 - (void) setHidesBackButton:(NSString *)value {
4432 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4435 - (void) setHidesNavigationBar:(NSString *)value {
4436 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4439 - (void) setNavigationBarStyle:(NSString *)value {
4440 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4443 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4444 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4445 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4446 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4449 - (void) setPasteboardString:(NSString *)value {
4450 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4453 - (void) setPasteboardURL:(NSString *)value {
4454 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4457 - (void) _setToken:(NSString *)token {
4461 [Metadata_ removeObjectForKey:@"Token"];
4463 [Metadata_ setObject:Token_ forKey:@"Token"];
4468 - (void) setToken:(NSString *)token {
4469 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4472 - (void) scrollToBottom:(NSNumber *)animated {
4473 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4476 - (void) setViewportWidth:(float)width {
4477 [indirect_ setViewportWidthOnMainThread:width];
4480 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4481 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4482 unsigned count([arguments count]);
4484 for (unsigned i(0); i != count; ++i)
4485 values[i] = [arguments objectAtIndex:i];
4486 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4489 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4490 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4492 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4494 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4500 @interface NSURL (CydiaSecure)
4503 @implementation NSURL (CydiaSecure)
4505 - (bool) isCydiaSecure {
4506 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4509 @synchronized (HostConfig_) {
4510 if ([InsecureHosts_ containsObject:[self host]])
4519 /* Cydia Browser Controller {{{ */
4520 @implementation CydiaWebViewController
4522 - (NSURL *) navigationURL {
4523 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4526 + (void) _initialize {
4527 [super _initialize];
4529 Diversions_ = [NSMutableSet setWithCapacity:0];
4532 + (void) addDiversion:(Diversion *)diversion {
4533 [Diversions_ addObject:diversion];
4536 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4537 [super webView:view didClearWindowObject:window forFrame:frame];
4539 WebDataSource *source([frame dataSource]);
4540 NSURLResponse *response([source response]);
4541 NSURL *url([response URL]);
4542 NSString *scheme([[url scheme] lowercaseString]);
4544 bool bridged(false);
4546 @synchronized (HostConfig_) {
4547 if ([scheme isEqualToString:@"file"])
4549 else if ([scheme isEqualToString:@"https"])
4550 if ([BridgedHosts_ containsObject:[url host]])
4555 [window setValue:cydia_ forKey:@"cydia"];
4558 - (void) _setupMail:(MFMailComposeViewController *)controller {
4559 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4561 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4562 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4565 - (NSURL *) URLWithURL:(NSURL *)url {
4566 return [Diversion divertURL:url];
4569 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4570 NSURL *url([request URL]);
4571 NSString *host([url host]);
4573 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4575 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4576 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4577 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4578 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4583 @synchronized (HostConfig_) {
4584 bridged = [BridgedHosts_ containsObject:host];
4585 token = [TokenHosts_ containsObject:host];
4588 if ([url isCydiaSecure]) {
4590 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4591 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4593 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4594 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4601 - (void) setDelegate:(id)delegate {
4602 [super setDelegate:delegate];
4603 [cydia_ setDelegate:delegate];
4606 - (NSString *) applicationNameForUserAgent {
4607 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4610 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4612 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4613 if (Product_ != nil)
4614 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4620 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4621 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4627 @interface AppCacheController : CydiaWebViewController {
4632 @implementation AppCacheController
4634 - (void) didReceiveMemoryWarning {
4641 @interface NSObject (CydiaScript)
4642 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4645 @implementation NSObject (CydiaScript)
4647 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4653 @implementation NSArray (CydiaScript)
4655 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4656 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4657 for (size_t i(0), e([self count]); i != e; ++i)
4658 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4664 @implementation NSDictionary (CydiaScript)
4666 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4667 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4669 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4676 /* Confirmation Controller {{{ */
4677 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4678 if (!iterator.end())
4679 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4680 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4682 pkgCache::PkgIterator package(dep.TargetPkg());
4685 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4692 @protocol ConfirmationControllerDelegate
4693 - (void) cancelAndClear:(bool)clear;
4694 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4698 @interface ConfirmationController : CydiaWebViewController {
4699 _transient Database *database_;
4701 _H<UIAlertView> essential_;
4703 _H<NSDictionary> changes_;
4704 _H<NSMutableArray> issues_;
4705 _H<NSDictionary> sizes_;
4710 - (id) initWithDatabase:(Database *)database;
4714 @implementation ConfirmationController
4718 RestartSubstrate_ = true;
4719 [delegate_ confirmWithNavigationController:[self navigationController]];
4722 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4723 NSString *context([alert context]);
4725 if ([context isEqualToString:@"remove"]) {
4726 if (button == [alert cancelButtonIndex])
4727 [self dismissModalViewControllerAnimated:YES];
4728 else if (button == [alert firstOtherButtonIndex]) {
4732 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4733 } else if ([context isEqualToString:@"unable"]) {
4734 [self dismissModalViewControllerAnimated:YES];
4735 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4737 [super alertView:alert clickedButtonAtIndex:button];
4741 - (void) _doContinue {
4742 [delegate_ cancelAndClear:NO];
4743 [self dismissModalViewControllerAnimated:YES];
4746 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4747 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4751 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4752 [super webView:view didClearWindowObject:window forFrame:frame];
4754 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4755 (id) changes_, @"changes",
4756 (id) issues_, @"issues",
4757 (id) sizes_, @"sizes",
4759 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4762 - (id) initWithDatabase:(Database *)database {
4763 if ((self = [super init]) != nil) {
4764 database_ = database;
4766 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4767 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4768 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4769 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4770 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4774 pkgCacheFile &cache([database_ cache]);
4775 NSArray *packages([database_ packages]);
4776 pkgDepCache::Policy *policy([database_ policy]);
4778 issues_ = [NSMutableArray arrayWithCapacity:4];
4780 for (Package *package in packages) {
4781 pkgCache::PkgIterator iterator([package iterator]);
4782 NSString *name([package id]);
4784 if ([package broken]) {
4785 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4787 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4789 reasons, @"reasons",
4792 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4796 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4797 pkgCache::DepIterator start;
4798 pkgCache::DepIterator end;
4799 dep.GlobOr(start, end); // ++dep
4801 if (!cache->IsImportantDep(end))
4803 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4806 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4808 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4809 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4810 clauses, @"clauses",
4814 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4816 pkgCache::PkgIterator target(start.TargetPkg());
4817 if (target->ProvidesList != 0)
4818 reason = @"missing";
4820 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4822 reason = @"installed";
4823 installed = [NSString stringWithUTF8String:ver.VerStr()];
4824 } else if (!cache[target].CandidateVerIter(cache).end())
4825 reason = @"uninstalled";
4826 else if (target->ProvidesList == 0)
4827 reason = @"uninstallable";
4829 reason = @"virtual";
4832 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4833 [NSString stringWithUTF8String:start.CompType()], @"operator",
4834 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4837 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4838 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4839 version, @"version",
4841 installed, @"installed",
4844 // yes, seriously. (wtf?)
4852 pkgDepCache::StateCache &state(cache[iterator]);
4854 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4856 if (state.NewInstall())
4857 [installs addObject:name];
4858 // XXX: else if (state.Install())
4859 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4860 [reinstalls addObject:name];
4861 // XXX: move before previous if
4862 else if (state.Upgrade())
4863 [upgrades addObject:name];
4864 else if (state.Downgrade())
4865 [downgrades addObject:name];
4866 else if (!state.Delete())
4867 // XXX: _assert(state.Keep());
4869 else if (special_r(name))
4870 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4871 [NSNull null], @"package",
4872 [NSArray arrayWithObjects:
4873 [NSDictionary dictionaryWithObjectsAndKeys:
4874 @"Conflicts", @"relationship",
4875 [NSArray arrayWithObjects:
4876 [NSDictionary dictionaryWithObjectsAndKeys:
4878 [NSNull null], @"version",
4879 @"installed", @"reason",
4886 if ([package essential])
4888 [removes addObject:name];
4891 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4892 substrate_ |= DepSubstrate(iterator.CurrentVer());
4897 else if (Advanced_) {
4898 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4900 essential_ = [[[UIAlertView alloc]
4901 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4902 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4904 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4906 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4910 [essential_ setContext:@"remove"];
4912 essential_ = [[[UIAlertView alloc]
4913 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4914 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4916 cancelButtonTitle:UCLocalize("OKAY")
4917 otherButtonTitles:nil
4920 [essential_ setContext:@"unable"];
4923 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4924 installs, @"installs",
4925 reinstalls, @"reinstalls",
4926 upgrades, @"upgrades",
4927 downgrades, @"downgrades",
4928 removes, @"removes",
4931 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4932 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4933 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4936 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4940 - (UIBarButtonItem *) leftButton {
4941 return [[[UIBarButtonItem alloc]
4942 initWithTitle:UCLocalize("CANCEL")
4943 style:UIBarButtonItemStylePlain
4945 action:@selector(cancelButtonClicked)
4950 - (void) applyRightButton {
4951 if ([issues_ count] == 0 && ![self isLoading])
4952 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4953 initWithTitle:UCLocalize("CONFIRM")
4954 style:UIBarButtonItemStyleDone
4956 action:@selector(confirmButtonClicked)
4959 [[self navigationItem] setRightBarButtonItem:nil];
4963 - (void) cancelButtonClicked {
4964 [self dismissModalViewControllerAnimated:YES];
4965 [delegate_ cancelAndClear:YES];
4969 - (void) confirmButtonClicked {
4970 if (essential_ != nil)
4980 /* Progress Data {{{ */
4981 @interface CydiaProgressData : NSObject {
4982 _transient id delegate_;
4991 _H<NSMutableArray> events_;
4992 _H<NSString> title_;
4994 _H<NSString> status_;
4995 _H<NSString> finish_;
5000 @implementation CydiaProgressData
5002 + (NSArray *) _attributeKeys {
5003 return [NSArray arrayWithObjects:
5015 - (NSArray *) attributeKeys {
5016 return [[self class] _attributeKeys];
5019 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5020 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5024 if ((self = [super init]) != nil) {
5025 events_ = [NSMutableArray arrayWithCapacity:32];
5029 - (void) setDelegate:(id)delegate {
5030 delegate_ = delegate;
5033 - (void) setPercent:(float)value {
5037 - (NSNumber *) percent {
5038 return [NSNumber numberWithFloat:percent_];
5041 - (void) setCurrent:(float)value {
5045 - (NSNumber *) current {
5046 return [NSNumber numberWithFloat:current_];
5049 - (void) setTotal:(float)value {
5053 - (NSNumber *) total {
5054 return [NSNumber numberWithFloat:total_];
5057 - (void) setSpeed:(float)value {
5061 - (NSNumber *) speed {
5062 return [NSNumber numberWithFloat:speed_];
5065 - (NSArray *) events {
5069 - (void) removeAllEvents {
5070 [events_ removeAllObjects];
5073 - (void) addEvent:(CydiaProgressEvent *)event {
5074 [events_ addObject:event];
5077 - (void) setTitle:(NSString *)text {
5081 - (NSString *) title {
5085 - (void) setFinish:(NSString *)text {
5089 - (NSString *) finish {
5090 return (id) finish_ ?: [NSNull null];
5093 - (void) setRunning:(bool)running {
5097 - (NSNumber *) running {
5098 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5103 /* Progress Controller {{{ */
5104 @interface ProgressController : CydiaWebViewController <
5107 _transient Database *database_;
5108 _H<CydiaProgressData, 1> progress_;
5112 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5114 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5116 - (void) setTitle:(NSString *)title;
5117 - (void) setCancellable:(bool)cancellable;
5121 @implementation ProgressController
5124 [database_ setProgressDelegate:nil];
5128 - (UIBarButtonItem *) leftButton {
5129 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5130 initWithTitle:UCLocalize("CANCEL")
5131 style:UIBarButtonItemStylePlain
5133 action:@selector(cancel)
5134 ] autorelease] : nil;
5137 - (void) updateCancel {
5138 [super applyLeftButton];
5141 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5142 if ((self = [super init]) != nil) {
5143 database_ = database;
5144 delegate_ = delegate;
5146 [database_ setProgressDelegate:self];
5148 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5149 [progress_ setDelegate:self];
5151 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5153 [scroller_ setBackgroundColor:[UIColor blackColor]];
5155 [[self navigationItem] setHidesBackButton:YES];
5157 [self updateCancel];
5161 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5162 [super webView:view didClearWindowObject:window forFrame:frame];
5163 [window setValue:progress_ forKey:@"cydiaProgress"];
5166 - (void) updateProgress {
5167 [self dispatchEvent:@"CydiaProgressUpdate"];
5170 - (void) viewWillAppear:(BOOL)animated {
5171 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5172 [super viewWillAppear:animated];
5176 UpdateExternalStatus(0);
5179 [delegate_ saveState];
5183 [delegate_ returnToCydia];
5187 [delegate_ terminateWithSuccess];
5188 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5189 [delegate_ suspendWithAnimation:YES];
5191 [delegate_ suspend];*/
5203 system("/usr/bin/sbreload");
5209 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5210 SBReboot(SBSSpringBoardServerPort());
5212 reboot2(RB_AUTOBOOT);
5219 - (void) setTitle:(NSString *)title {
5220 [progress_ setTitle:title];
5221 [self updateProgress];
5224 - (UIBarButtonItem *) rightButton {
5225 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5226 initWithTitle:UCLocalize("CLOSE")
5227 style:UIBarButtonItemStylePlain
5229 action:@selector(close)
5235 system("su -c /usr/bin/uicache mobile");
5239 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5240 UpdateExternalStatus(1);
5242 [progress_ setRunning:true];
5243 [self setTitle:title];
5244 // implicit updateProgress
5246 SHA1SumValue notifyconf; {
5248 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5251 MMap mmap(file, MMap::ReadOnly);
5253 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5254 notifyconf = sha1.Result();
5258 SHA1SumValue springlist; {
5260 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5263 MMap mmap(file, MMap::ReadOnly);
5265 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5266 springlist = sha1.Result();
5270 if (invocation != nil) {
5271 [invocation yieldToSelector:@selector(invoke)];
5272 [self setTitle:@"COMPLETE"];
5277 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5280 MMap mmap(file, MMap::ReadOnly);
5282 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5283 if (!(notifyconf == sha1.Result()))
5290 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5293 MMap mmap(file, MMap::ReadOnly);
5295 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5296 if (!(springlist == sha1.Result()))
5302 if (RestartSubstrate_)
5306 RestartSubstrate_ = false;
5309 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5310 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5311 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5312 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5313 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5316 UIProgressHUD *hud([delegate_ addProgressHUD]);
5317 [hud setText:UCLocalize("LOADING")];
5318 [self yieldToSelector:@selector(uicache)];
5319 [delegate_ removeProgressHUD:hud];
5321 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5323 [progress_ setRunning:false];
5324 [self updateProgress];
5326 [self applyRightButton];
5329 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5330 [progress_ addEvent:event];
5331 [self updateProgress];
5334 - (bool) isProgressCancelled {
5335 return cancel_ == 2;
5340 [self updateCancel];
5343 - (void) setCancellable:(bool)cancellable {
5344 unsigned cancel(cancel_);
5348 else if (cancel_ == 0)
5351 if (cancel != cancel_)
5352 [self updateCancel];
5355 - (void) setProgressCancellable:(NSNumber *)cancellable {
5356 [self setCancellable:[cancellable boolValue]];
5359 - (void) setProgressPercent:(NSNumber *)percent {
5360 [progress_ setPercent:[percent floatValue]];
5361 [self updateProgress];
5364 - (void) setProgressStatus:(NSDictionary *)status {
5365 if (status == nil) {
5366 [progress_ setCurrent:0];
5367 [progress_ setTotal:0];
5368 [progress_ setSpeed:0];
5370 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5372 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5373 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5374 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5377 [self updateProgress];
5383 /* Package Cell {{{ */
5384 @interface PackageCell : CyteTableViewCell <
5385 CyteTableViewCellDelegate
5389 _H<NSString> description_;
5391 _H<NSString> source_;
5393 _H<UIImage> placard_;
5397 - (PackageCell *) init;
5398 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5400 - (void) drawContentRect:(CGRect)rect;
5404 @implementation PackageCell
5406 - (PackageCell *) init {
5407 CGRect frame(CGRectMake(0, 0, 320, 74));
5408 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5409 UIView *content([self contentView]);
5410 CGRect bounds([content bounds]);
5412 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5413 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5414 [content addSubview:content_];
5416 [content_ setDelegate:self];
5417 [content_ setOpaque:YES];
5421 - (NSString *) accessibilityLabel {
5422 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5425 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5426 summarized_ = summary;
5436 [content_ setBackgroundColor:[UIColor whiteColor]];
5440 Source *source = [package source];
5442 icon_ = [package icon];
5444 if (NSString *name = [package name])
5445 name_ = [NSString stringWithString:name];
5447 NSString *description(nil);
5449 if (description == nil && IsWildcat_)
5450 description = [package longDescription];
5451 if (description == nil)
5452 description = [package shortDescription];
5454 if (description != nil)
5455 description_ = [NSString stringWithString:description];
5457 commercial_ = [package isCommercial];
5459 NSString *label = nil;
5460 bool trusted = false;
5462 if (source != nil) {
5463 label = [source label];
5464 trusted = [source trusted];
5465 } else if ([[package id] isEqualToString:@"firmware"])
5466 label = UCLocalize("APPLE");
5468 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5470 NSString *from(label);
5472 NSString *section = [package simpleSection];
5473 if (section != nil && ![section isEqualToString:label]) {
5474 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5475 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5478 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5480 if (NSString *purpose = [package primaryPurpose])
5481 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5486 if (NSString *mode = [package mode]) {
5487 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5488 color = RemovingColor_;
5489 //placard = @"removing";
5491 color = InstallingColor_;
5492 //placard = @"installing";
5495 // XXX: the removing/installing placards are not @2x
5498 color = [UIColor whiteColor];
5500 if ([package installed] != nil)
5501 placard = @"installed";
5506 [content_ setBackgroundColor:color];
5509 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5512 [self setNeedsDisplay];
5513 [content_ setNeedsDisplay];
5516 - (void) drawSummaryContentRect:(CGRect)rect {
5517 bool highlighted(highlighted_);
5518 float width([self bounds].size.width);
5522 rect.size = [(UIImage *) icon_ size];
5524 while (rect.size.width > 16 || rect.size.height > 16) {
5525 rect.size.width /= 2;
5526 rect.size.height /= 2;
5529 rect.origin.x = 18 - rect.size.width / 2;
5530 rect.origin.y = 18 - rect.size.height / 2;
5532 [icon_ drawInRect:rect];
5535 if (badge_ != nil) {
5537 rect.size = [(UIImage *) badge_ size];
5539 rect.size.width /= 4;
5540 rect.size.height /= 4;
5542 rect.origin.x = 23 - rect.size.width / 2;
5543 rect.origin.y = 23 - rect.size.height / 2;
5545 [badge_ drawInRect:rect];
5552 UISetColor(commercial_ ? Purple_ : Black_);
5553 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5555 if (placard_ != nil)
5556 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5559 - (void) drawNormalContentRect:(CGRect)rect {
5560 bool highlighted(highlighted_);
5561 float width([self bounds].size.width);
5565 rect.size = [(UIImage *) icon_ size];
5567 while (rect.size.width > 32 || rect.size.height > 32) {
5568 rect.size.width /= 2;
5569 rect.size.height /= 2;
5572 rect.origin.x = 25 - rect.size.width / 2;
5573 rect.origin.y = 25 - rect.size.height / 2;
5575 [icon_ drawInRect:rect];
5578 if (badge_ != nil) {
5580 rect.size = [(UIImage *) badge_ size];
5582 rect.size.width /= 2;
5583 rect.size.height /= 2;
5585 rect.origin.x = 36 - rect.size.width / 2;
5586 rect.origin.y = 36 - rect.size.height / 2;
5588 [badge_ drawInRect:rect];
5595 UISetColor(commercial_ ? Purple_ : Black_);
5596 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5597 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5600 UISetColor(commercial_ ? Purplish_ : Gray_);
5601 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5603 if (placard_ != nil)
5604 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5607 - (void) drawContentRect:(CGRect)rect {
5609 [self drawSummaryContentRect:rect];
5611 [self drawNormalContentRect:rect];
5616 /* Section Cell {{{ */
5617 @interface SectionCell : CyteTableViewCell <
5618 CyteTableViewCellDelegate
5620 _H<NSString> basic_;
5621 _H<NSString> section_;
5623 _H<NSString> count_;
5625 _H<UISwitch> switch_;
5629 - (void) setSection:(Section *)section editing:(BOOL)editing;
5633 @implementation SectionCell
5635 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5636 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5637 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5638 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5639 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5641 UIView *content([self contentView]);
5642 CGRect bounds([content bounds]);
5644 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5645 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5646 [content addSubview:content_];
5647 [content_ setBackgroundColor:[UIColor whiteColor]];
5649 [content_ setDelegate:self];
5653 - (void) onSwitch:(id)sender {
5654 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5655 if (metadata == nil) {
5656 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5657 [Sections_ setObject:metadata forKey:basic_];
5660 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5664 - (void) setSection:(Section *)section editing:(BOOL)editing {
5665 if (editing != editing_) {
5667 [switch_ removeFromSuperview];
5669 [self addSubview:switch_];
5678 if (section == nil) {
5679 name_ = UCLocalize("ALL_PACKAGES");
5682 basic_ = [section name];
5683 section_ = [section localized];
5685 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5686 count_ = [NSString stringWithFormat:@"%d", [section count]];
5689 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5692 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5693 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5695 [content_ setNeedsDisplay];
5698 - (void) setFrame:(CGRect)frame {
5699 [super setFrame:frame];
5701 CGRect rect([switch_ frame]);
5702 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5705 - (NSString *) accessibilityLabel {
5709 - (void) drawContentRect:(CGRect)rect {
5710 bool highlighted(highlighted_ && !editing_);
5712 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5717 float width(rect.size.width);
5723 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5725 CGSize size = [count_ sizeWithFont:Font14_];
5729 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5735 /* File Table {{{ */
5736 @interface FileTable : CyteViewController <
5737 UITableViewDataSource,
5740 _transient Database *database_;
5741 _H<Package> package_;
5743 _H<NSMutableArray> files_;
5744 _H<UITableView, 2> list_;
5747 - (id) initWithDatabase:(Database *)database;
5748 - (void) setPackage:(Package *)package;
5752 @implementation FileTable
5754 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5755 return files_ == nil ? 0 : [files_ count];
5758 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5762 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5763 static NSString *reuseIdentifier = @"Cell";
5765 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5767 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5768 [cell setFont:[UIFont systemFontOfSize:16]];
5770 [cell setText:[files_ objectAtIndex:indexPath.row]];
5771 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5776 - (NSURL *) navigationURL {
5777 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5781 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5783 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5784 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5785 [list_ setRowHeight:24.0f];
5786 [(UITableView *) list_ setDataSource:self];
5787 [list_ setDelegate:self];
5788 [[self view] addSubview:list_];
5791 - (void) viewDidLoad {
5792 [super viewDidLoad];
5794 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5797 - (void) releaseSubviews {
5803 [super releaseSubviews];
5806 - (id) initWithDatabase:(Database *)database {
5807 if ((self = [super init]) != nil) {
5808 database_ = database;
5812 - (void) setPackage:(Package *)package {
5816 files_ = [NSMutableArray arrayWithCapacity:32];
5818 if (package != nil) {
5820 name_ = [package id];
5822 if (NSArray *files = [package files])
5823 [files_ addObjectsFromArray:files];
5825 if ([files_ count] != 0) {
5826 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5827 [files_ removeObjectAtIndex:0];
5828 [files_ sortUsingSelector:@selector(compareByPath:)];
5830 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5831 [stack addObject:@"/"];
5833 for (int i(0), e([files_ count]); i != e; ++i) {
5834 NSString *file = [files_ objectAtIndex:i];
5835 while (![file hasPrefix:[stack lastObject]])
5836 [stack removeLastObject];
5837 NSString *directory = [stack lastObject];
5838 [stack addObject:[file stringByAppendingString:@"/"]];
5839 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5840 ([stack count] - 2) * 3, "",
5841 [file substringFromIndex:[directory length]]
5850 - (void) reloadData {
5853 [self setPackage:[database_ packageWithName:name_]];
5858 /* Package Controller {{{ */
5859 @interface CYPackageController : CydiaWebViewController <
5860 UIActionSheetDelegate
5862 _transient Database *database_;
5863 _H<Package> package_;
5866 _H<NSMutableArray> buttons_;
5867 _H<UIBarButtonItem> button_;
5870 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5874 @implementation CYPackageController
5876 - (NSURL *) navigationURL {
5877 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5880 /* XXX: this is not safe at all... localization of /fail/ */
5881 - (void) _clickButtonWithName:(NSString *)name {
5882 if ([name isEqualToString:UCLocalize("CLEAR")])
5883 [delegate_ clearPackage:package_];
5884 else if ([name isEqualToString:UCLocalize("INSTALL")])
5885 [delegate_ installPackage:package_];
5886 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5887 [delegate_ installPackage:package_];
5888 else if ([name isEqualToString:UCLocalize("REMOVE")])
5889 [delegate_ removePackage:package_];
5890 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5891 [delegate_ installPackage:package_];
5892 else _assert(false);
5895 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5896 NSString *context([sheet context]);
5898 if ([context isEqualToString:@"modify"]) {
5899 if (button != [sheet cancelButtonIndex]) {
5900 NSString *buttonName = [buttons_ objectAtIndex:button];
5901 [self _clickButtonWithName:buttonName];
5904 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5908 - (bool) _allowJavaScriptPanel {
5913 - (void) _customButtonClicked {
5914 int count([buttons_ count]);
5919 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5921 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5922 [buttons addObjectsFromArray:buttons_];
5924 UIActionSheet *sheet = [[[UIActionSheet alloc]
5927 cancelButtonTitle:nil
5928 destructiveButtonTitle:nil
5929 otherButtonTitles:nil
5932 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5934 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5935 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5937 [sheet setContext:@"modify"];
5939 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5943 // We don't want to allow non-commercial packages to do custom things to the install button,
5944 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5945 - (void) customButtonClicked {
5947 [super customButtonClicked];
5949 [self _customButtonClicked];
5952 - (void) reloadButtonClicked {
5953 // Don't reload a commerical package by tapping the loading button,
5954 // but if it's not an Install button, we should forward it on.
5955 if (![package_ uninstalled])
5956 [self _customButtonClicked];
5959 - (void) applyLoadingTitle {
5960 // Don't show "Loading" as the title. Ever.
5963 - (UIBarButtonItem *) rightButton {
5968 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5969 if ((self = [super init]) != nil) {
5970 database_ = database;
5971 buttons_ = [NSMutableArray arrayWithCapacity:4];
5972 name_ = name == nil ? @"" : [NSString stringWithString:name];
5973 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5977 - (void) reloadData {
5980 package_ = [database_ packageWithName:name_];
5982 [buttons_ removeAllObjects];
5984 if (package_ != nil) {
5985 [(Package *) package_ parse];
5987 commercial_ = [package_ isCommercial];
5989 if ([package_ mode] != nil)
5990 [buttons_ addObject:UCLocalize("CLEAR")];
5991 if ([package_ source] == nil);
5992 else if ([package_ upgradableAndEssential:NO])
5993 [buttons_ addObject:UCLocalize("UPGRADE")];
5994 else if ([package_ uninstalled])
5995 [buttons_ addObject:UCLocalize("INSTALL")];
5997 [buttons_ addObject:UCLocalize("REINSTALL")];
5998 if (![package_ uninstalled])
5999 [buttons_ addObject:UCLocalize("REMOVE")];
6003 switch ([buttons_ count]) {
6004 case 0: title = nil; break;
6005 case 1: title = [buttons_ objectAtIndex:0]; break;
6006 default: title = UCLocalize("MODIFY"); break;
6009 button_ = [[[UIBarButtonItem alloc]
6011 style:UIBarButtonItemStylePlain
6013 action:@selector(customButtonClicked)
6017 - (bool) isLoading {
6018 return commercial_ ? [super isLoading] : false;
6024 /* Package List Controller {{{ */
6025 @interface PackageListController : CyteViewController <
6026 UITableViewDataSource,
6029 _transient Database *database_;
6031 _H<NSArray> packages_;
6032 _H<NSMutableArray> sections_;
6033 _H<UITableView, 2> list_;
6034 _H<NSMutableArray> index_;
6035 _H<NSMutableDictionary> indices_;
6036 _H<NSString> title_;
6037 unsigned reloading_;
6040 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6041 - (void) setDelegate:(id)delegate;
6042 - (void) resetCursor;
6047 @implementation PackageListController
6049 - (bool) isSummarized {
6053 - (bool) showsSections {
6057 - (void) deselectWithAnimation:(BOOL)animated {
6058 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6061 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6062 CGRect base = [[self view] bounds];
6063 base.size.height -= bounds.size.height;
6064 base.origin = [list_ frame].origin;
6066 [UIView beginAnimations:nil context:NULL];
6067 [UIView setAnimationBeginsFromCurrentState:YES];
6068 [UIView setAnimationCurve:curve];
6069 [UIView setAnimationDuration:duration];
6070 [list_ setFrame:base];
6071 [UIView commitAnimations];
6074 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6075 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6078 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6079 [self resizeForKeyboardBounds:bounds duration:0];
6082 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6083 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6084 *curve = UIViewAnimationCurveEaseInOut;
6086 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6088 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6091 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6094 - (void) keyboardWillShow:(NSNotification *)notification {
6097 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6098 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6100 NSTimeInterval duration;
6101 UIViewAnimationCurve curve;
6102 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6104 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);
6105 UIViewController *base = self;
6106 while ([base parentViewController] != nil)
6107 base = [base parentViewController];
6108 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6109 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6111 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6112 intersection.size.height += CYStatusBarHeight();
6114 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6117 - (void) keyboardWillHide:(NSNotification *)notification {
6118 NSTimeInterval duration;
6119 UIViewAnimationCurve curve;
6120 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6122 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6125 - (void) viewWillAppear:(BOOL)animated {
6126 [super viewWillAppear:animated];
6128 [self resizeForKeyboardBounds:CGRectZero];
6129 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6130 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6133 - (void) viewWillDisappear:(BOOL)animated {
6134 [super viewWillDisappear:animated];
6136 [self resizeForKeyboardBounds:CGRectZero];
6137 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6138 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6141 - (void) viewDidAppear:(BOOL)animated {
6142 [super viewDidAppear:animated];
6143 [self deselectWithAnimation:animated];
6146 - (void) didSelectPackage:(Package *)package {
6147 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6148 [view setDelegate:delegate_];
6149 [[self navigationController] pushViewController:view animated:YES];
6152 #if TryIndexedCollation
6153 + (BOOL) hasIndexedCollation {
6154 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6158 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6159 NSInteger count([sections_ count]);
6160 return count == 0 ? 1 : count;
6163 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6164 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6166 return [[sections_ objectAtIndex:section] name];
6169 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6170 if ([sections_ count] == 0)
6172 return [[sections_ objectAtIndex:section] count];
6175 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6176 @synchronized (database_) {
6177 if ([database_ era] != era_)
6180 Section *section([sections_ objectAtIndex:[path section]]);
6181 NSInteger row([path row]);
6182 Package *package([packages_ objectAtIndex:([section row] + row)]);
6183 return [[package retain] autorelease];
6186 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6187 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6189 cell = [[[PackageCell alloc] init] autorelease];
6191 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6192 [cell setPackage:package asSummary:[self isSummarized]];
6196 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6197 Package *package([self packageAtIndexPath:path]);
6198 package = [database_ packageWithName:[package id]];
6199 [self didSelectPackage:package];
6202 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6203 if (![self showsSections])
6209 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6210 #if TryIndexedCollation
6211 if ([[self class] hasIndexedCollation]) {
6212 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6219 - (void) updateHeight {
6220 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6223 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6224 if ((self = [super init]) != nil) {
6225 database_ = database;
6226 title_ = [title copy];
6227 [[self navigationItem] setTitle:title_];
6232 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6234 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6235 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6236 [[self view] addSubview:list_];
6238 // XXX: is 20 the most optimal number here?
6239 [list_ setSectionIndexMinimumDisplayRowCount:20];
6241 [(UITableView *) list_ setDataSource:self];
6242 [list_ setDelegate:self];
6244 [self updateHeight];
6247 - (void) releaseSubviews {
6255 [super releaseSubviews];
6258 - (void) setDelegate:(id)delegate {
6259 delegate_ = delegate;
6262 - (bool) shouldYield {
6266 - (bool) shouldBlock {
6270 - (NSMutableArray *) _reloadPackages {
6271 @synchronized (database_) {
6272 era_ = [database_ era];
6273 NSArray *packages([database_ packages]);
6275 return [NSMutableArray arrayWithArray:packages];
6278 - (void) _reloadData {
6279 if (reloading_ != 0) {
6286 if ([self shouldYield]) {
6290 if (![self shouldBlock])
6293 hud = [delegate_ addProgressHUD];
6294 [hud setText:UCLocalize("LOADING")];
6298 packages = [self yieldToSelector:@selector(_reloadPackages)];
6301 [delegate_ removeProgressHUD:hud];
6302 } while (reloading_ == 2);
6306 packages = [self _reloadPackages];
6309 packages_ = packages;
6311 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6312 sections_ = [NSMutableArray arrayWithCapacity:16];
6314 Section *section = nil;
6316 #if TryIndexedCollation
6317 if ([[self class] hasIndexedCollation]) {
6318 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6320 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6321 NSArray *titles = [collation sectionIndexTitles];
6324 _profile(PackageTable$reloadData$Section)
6325 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6329 _profile(PackageTable$reloadData$Section$Package)
6330 package = [packages_ objectAtIndex:offset];
6331 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6334 while (secidx < index) {
6337 _profile(PackageTable$reloadData$Section$Allocate)
6338 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6341 _profile(PackageTable$reloadData$Section$Add)
6342 [sections_ addObject:section];
6346 [section addToCount];
6352 index_ = [NSMutableArray arrayWithCapacity:32];
6354 bool sectioned([self showsSections]);
6356 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6357 [sections_ addObject:section];
6360 _profile(PackageTable$reloadData$Section)
6361 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6365 _profile(PackageTable$reloadData$Section$Package)
6366 package = [packages_ objectAtIndex:offset];
6367 index = [package index];
6370 if (sectioned && (section == nil || [section index] != index)) {
6371 _profile(PackageTable$reloadData$Section$Allocate)
6372 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6375 [index_ addObject:[section name]];
6376 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6378 _profile(PackageTable$reloadData$Section$Add)
6379 [sections_ addObject:section];
6383 [section addToCount];
6388 [self updateHeight];
6390 _profile(PackageTable$reloadData$List)
6391 [(UITableView *) list_ setDataSource:self];
6396 - (void) reloadData {
6399 if ([self shouldYield])
6400 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6405 - (void) resetCursor {
6406 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6409 - (void) clearData {
6410 [self updateHeight];
6412 [list_ setDataSource:nil];
6420 /* Filtered Package List Controller {{{ */
6421 @interface FilteredPackageListController : PackageListController {
6424 _H<NSObject> object_;
6427 - (void) setObject:(id)object;
6428 - (void) setObject:(id)object forFilter:(SEL)filter;
6431 - (void) setFilter:(SEL)filter;
6433 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6437 @implementation FilteredPackageListController
6443 - (void) setFilter:(SEL)filter {
6444 @synchronized (self) {
6447 /* XXX: this is an unsafe optimization of doomy hell */
6448 Method method(class_getInstanceMethod([Package class], filter));
6449 _assert(method != NULL);
6450 imp_ = method_getImplementation(method);
6451 _assert(imp_ != NULL);
6454 - (void) setObject:(id)object {
6455 @synchronized (self) {
6459 - (void) setObject:(id)object forFilter:(SEL)filter {
6460 @synchronized (self) {
6461 [self setFilter:filter];
6462 [self setObject:object];
6465 - (NSMutableArray *) _reloadPackages {
6466 @synchronized (database_) {
6467 era_ = [database_ era];
6468 NSArray *packages([database_ packages]);
6470 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6474 _H<NSObject> object;
6476 @synchronized (self) {
6482 _profile(PackageTable$reloadData$Filter)
6483 for (Package *package in packages)
6484 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6485 [filtered addObject:package];
6491 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6492 if ((self = [super initWithDatabase:database title:title]) != nil) {
6493 [self setFilter:filter];
6494 [self setObject:object];
6501 /* Home Controller {{{ */
6502 @interface HomeController : CydiaWebViewController {
6507 @implementation HomeController
6510 if ((self = [super init]) != nil) {
6511 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6516 - (NSURL *) navigationURL {
6517 return [NSURL URLWithString:@"cydia://home"];
6520 - (void) didReceiveMemoryWarning {
6523 - (void) aboutButtonClicked {
6524 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6526 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6527 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6528 [alert setCancelButtonIndex:0];
6531 @"Copyright \u00a9 2008-2011\n"
6534 "Jay Freeman (saurik)\n"
6535 "saurik@saurik.com\n"
6536 "http://www.saurik.com/"
6542 - (UIBarButtonItem *) leftButton {
6543 return [[[UIBarButtonItem alloc]
6544 initWithTitle:UCLocalize("ABOUT")
6545 style:UIBarButtonItemStylePlain
6547 action:@selector(aboutButtonClicked)
6553 /* Manage Controller {{{ */
6554 @interface ManageController : CydiaWebViewController {
6557 - (void) queueStatusDidChange;
6561 @implementation ManageController
6564 if ((self = [super init]) != nil) {
6565 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6569 - (NSURL *) navigationURL {
6570 return [NSURL URLWithString:@"cydia://manage"];
6573 - (UIBarButtonItem *) leftButton {
6574 return [[[UIBarButtonItem alloc]
6575 initWithTitle:UCLocalize("SETTINGS")
6576 style:UIBarButtonItemStylePlain
6578 action:@selector(settingsButtonClicked)
6582 - (void) settingsButtonClicked {
6583 [delegate_ showSettings];
6586 - (void) queueButtonClicked {
6590 - (UIBarButtonItem *) rightButton {
6591 return Queuing_ ? [[[UIBarButtonItem alloc]
6592 initWithTitle:UCLocalize("QUEUE")
6593 style:UIBarButtonItemStyleDone
6595 action:@selector(queueButtonClicked)
6596 ] autorelease] : nil;
6599 - (void) queueStatusDidChange {
6600 [self applyRightButton];
6603 - (bool) isLoading {
6604 return !Queuing_ && [super isLoading];
6610 /* Refresh Bar {{{ */
6611 @interface RefreshBar : UINavigationBar {
6612 _H<UIProgressIndicator> indicator_;
6613 _H<UITextLabel> prompt_;
6614 _H<UIProgressBar> progress_;
6615 _H<UINavigationButton> cancel_;
6620 @implementation RefreshBar
6622 - (void) positionViews {
6623 CGRect frame = [cancel_ frame];
6624 frame.size = [cancel_ sizeThatFits:frame.size];
6625 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6626 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6627 [cancel_ setFrame:frame];
6629 CGSize prgsize = {75, 100};
6631 [self frame].size.width - prgsize.width - 10,
6632 ([self frame].size.height - prgsize.height) / 2
6634 [progress_ setFrame:prgrect];
6636 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6637 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6638 CGRect indrect = {{indoffset, indoffset}, indsize};
6639 [indicator_ setFrame:indrect];
6641 CGSize prmsize = {215, indsize.height + 4};
6643 indoffset * 2 + indsize.width,
6644 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6646 [prompt_ setFrame:prmrect];
6649 - (void) setFrame:(CGRect)frame {
6650 [super setFrame:frame];
6651 [self positionViews];
6654 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6655 if ((self = [super initWithFrame:frame]) != nil) {
6656 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6658 [self setBarStyle:UIBarStyleBlack];
6660 UIBarStyle barstyle([self _barStyle:NO]);
6661 bool ugly(barstyle == UIBarStyleDefault);
6663 UIProgressIndicatorStyle style = ugly ?
6664 UIProgressIndicatorStyleMediumBrown :
6665 UIProgressIndicatorStyleMediumWhite;
6667 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6668 [(UIProgressIndicator *) indicator_ setStyle:style];
6669 [indicator_ startAnimation];
6670 [self addSubview:indicator_];
6672 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6673 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6674 [prompt_ setBackgroundColor:[UIColor clearColor]];
6675 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6676 [self addSubview:prompt_];
6678 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6679 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6680 [(UIProgressBar *) progress_ setStyle:0];
6681 [self addSubview:progress_];
6683 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6684 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6685 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6686 [cancel_ setBarStyle:barstyle];
6688 [self positionViews];
6692 - (void) setCancellable:(bool)cancellable {
6694 [self addSubview:cancel_];
6696 [cancel_ removeFromSuperview];
6700 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6701 [progress_ setProgress:0];
6705 [self setCancellable:NO];
6708 - (void) setPrompt:(NSString *)prompt {
6709 [prompt_ setText:prompt];
6712 - (void) setProgress:(float)progress {
6713 [progress_ setProgress:progress];
6719 /* Cydia Navigation Controller Interface {{{ */
6720 @interface UINavigationController (Cydia)
6722 - (NSArray *) navigationURLCollection;
6723 - (void) unloadData;
6728 /* Cydia Tab Bar Controller {{{ */
6729 @interface CYTabBarController : UITabBarController <
6730 UITabBarControllerDelegate,
6733 _transient Database *database_;
6734 _H<RefreshBar, 1> refreshbar_;
6738 // XXX: ok, "updatedelegate_"?...
6739 _transient NSObject<CydiaDelegate> *updatedelegate_;
6741 _H<UIViewController> remembered_;
6742 _transient UIViewController *transient_;
6745 - (NSArray *) navigationURLCollection;
6746 - (void) dropBar:(BOOL)animated;
6747 - (void) beginUpdate;
6748 - (void) raiseBar:(BOOL)animated;
6750 - (void) unloadData;
6754 @implementation CYTabBarController
6756 - (void) setUnselectedViewController:(UIViewController *)transient {
6757 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6758 if (transient != nil) {
6759 if (transient_ == nil)
6760 remembered_ = [controllers objectAtIndex:0];
6761 transient_ = transient;
6762 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6763 [controllers replaceObjectAtIndex:0 withObject:transient_];
6764 [self setSelectedIndex:0];
6765 [self setViewControllers:controllers];
6766 [self concealTabBarSelection];
6767 } else if (remembered_ != nil) {
6768 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6769 transient_ = transient;
6770 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6772 [self setViewControllers:controllers];
6773 [self revealTabBarSelection];
6777 - (UIViewController *) unselectedViewController {
6781 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6782 if ([self unselectedViewController])
6783 [self setUnselectedViewController:nil];
6786 - (NSArray *) navigationURLCollection {
6787 NSMutableArray *items([NSMutableArray array]);
6789 // XXX: Should this deal with transient view controllers?
6790 for (id navigation in [self viewControllers]) {
6791 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6793 [items addObject:stack];
6799 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6800 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6801 [self setUnselectedViewController:nil];
6803 [super dismissModalViewControllerAnimated:YES];
6806 - (void) unloadData {
6809 for (UINavigationController *controller in [self viewControllers])
6810 [controller unloadData];
6812 if (UIViewController *selected = [self selectedViewController])
6813 [selected reloadData];
6815 if (UIViewController *unselected = [self unselectedViewController]) {
6816 [unselected unloadData];
6817 [unselected reloadData];
6822 [[NSNotificationCenter defaultCenter] removeObserver:self];
6827 - (id) initWithDatabase:(Database *)database {
6828 if ((self = [super init]) != nil) {
6829 database_ = database;
6830 [self setDelegate:self];
6832 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6833 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6835 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6839 - (void) setUpdate:(NSDate *)date {
6843 - (void) beginUpdate {
6844 [(RefreshBar *) refreshbar_ start];
6847 [updatedelegate_ retainNetworkActivityIndicator];
6851 detachNewThreadSelector:@selector(performUpdate)
6857 - (void) performUpdate {
6858 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6861 status.setDelegate(self);
6862 [database_ updateWithStatus:status];
6865 performSelectorOnMainThread:@selector(completeUpdate)
6873 - (void) stopUpdateWithSelector:(SEL)selector {
6875 [updatedelegate_ releaseNetworkActivityIndicator];
6877 [self raiseBar:YES];
6880 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6883 - (void) completeUpdate {
6886 [self stopUpdateWithSelector:@selector(reloadData)];
6889 - (void) cancelUpdate {
6890 [self stopUpdateWithSelector:@selector(updateData)];
6893 - (void) cancelPressed {
6894 [self cancelUpdate];
6901 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6902 [refreshbar_ setPrompt:[event compoundMessage]];
6905 - (bool) isProgressCancelled {
6909 - (void) setProgressCancellable:(NSNumber *)cancellable {
6910 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6913 - (void) setProgressPercent:(NSNumber *)percent {
6914 [refreshbar_ setProgress:[percent floatValue]];
6917 - (void) setProgressStatus:(NSDictionary *)status {
6919 [self setProgressPercent:[status objectForKey:@"Percent"]];
6922 - (void) setUpdateDelegate:(id)delegate {
6923 updatedelegate_ = delegate;
6926 - (UIView *) transitionView {
6927 if ([self respondsToSelector:@selector(_transitionView)])
6928 return [self _transitionView];
6930 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6933 - (void) dropBar:(BOOL)animated {
6938 UIView *transition([self transitionView]);
6939 [[self view] addSubview:refreshbar_];
6941 CGRect barframe([refreshbar_ frame]);
6943 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6944 barframe.origin.y = CYStatusBarHeight();
6946 barframe.origin.y = 0;
6948 [refreshbar_ setFrame:barframe];
6951 [UIView beginAnimations:nil context:NULL];
6953 CGRect viewframe = [transition frame];
6954 viewframe.origin.y += barframe.size.height;
6955 viewframe.size.height -= barframe.size.height;
6956 [transition setFrame:viewframe];
6959 [UIView commitAnimations];
6961 // Ensure bar has the proper width for our view, it might have changed
6962 barframe.size.width = viewframe.size.width;
6963 [refreshbar_ setFrame:barframe];
6966 - (void) raiseBar:(BOOL)animated {
6971 UIView *transition([self transitionView]);
6972 [refreshbar_ removeFromSuperview];
6974 CGRect barframe([refreshbar_ frame]);
6977 [UIView beginAnimations:nil context:NULL];
6979 CGRect viewframe = [transition frame];
6980 viewframe.origin.y -= barframe.size.height;
6981 viewframe.size.height += barframe.size.height;
6982 [transition setFrame:viewframe];
6985 [UIView commitAnimations];
6988 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6989 bool dropped(dropped_);
6994 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7000 - (void) statusBarFrameChanged:(NSNotification *)notification {
7010 /* Cydia Navigation Controller Implementation {{{ */
7011 @implementation UINavigationController (Cydia)
7013 - (NSArray *) navigationURLCollection {
7014 NSMutableArray *stack([NSMutableArray array]);
7016 for (CyteViewController *controller in [self viewControllers]) {
7017 NSString *url = [[controller navigationURL] absoluteString];
7019 [stack addObject:url];
7025 - (void) reloadData {
7028 UIViewController *visible([self visibleViewController]);
7030 [visible reloadData];
7032 // on the iPad, this view controller is ALSO visible. :(
7034 if (UIViewController *top = [self topViewController])
7039 - (void) unloadData {
7040 for (CyteViewController *page in [self viewControllers])
7049 /* Cydia:// Protocol {{{ */
7050 @interface CydiaURLProtocol : NSURLProtocol {
7055 @implementation CydiaURLProtocol
7057 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7058 NSURL *url([request URL]);
7062 NSString *scheme([[url scheme] lowercaseString]);
7063 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7065 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7071 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7075 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7076 id<NSURLProtocolClient> client([self client]);
7078 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7080 NSData *data(UIImagePNGRepresentation(icon));
7082 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7083 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7084 [client URLProtocol:self didLoadData:data];
7085 [client URLProtocolDidFinishLoading:self];
7089 - (void) startLoading {
7090 id<NSURLProtocolClient> client([self client]);
7091 NSURLRequest *request([self request]);
7093 NSURL *url([request URL]);
7094 NSString *href([url absoluteString]);
7095 NSString *scheme([[url scheme] lowercaseString]);
7099 if ([scheme isEqualToString:@"cydia"])
7100 path = [href substringFromIndex:8];
7101 else if ([scheme isEqualToString:@"about"])
7102 path = [href substringFromIndex:12];
7103 else _assert(false);
7105 NSRange slash([path rangeOfString:@"/"]);
7108 if (slash.location == NSNotFound) {
7112 command = [path substringToIndex:slash.location];
7113 path = [path substringFromIndex:(slash.location + 1)];
7116 Database *database([Database sharedInstance]);
7118 if ([command isEqualToString:@"package-icon"]) {
7121 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7122 Package *package([database packageWithName:path]);
7126 UIImage *icon([package icon]);
7127 [self _returnPNGWithImage:icon forRequest:request];
7128 } else if ([command isEqualToString:@"uikit-image"]) {
7131 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7132 UIImage *icon(_UIImageWithName(path));
7133 [self _returnPNGWithImage:icon forRequest:request];
7134 } else if ([command isEqualToString:@"section-icon"]) {
7137 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7138 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7140 icon = [UIImage applicationImageNamed:@"unknown.png"];
7141 [self _returnPNGWithImage:icon forRequest:request];
7143 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7147 - (void) stopLoading {
7153 /* Section Controller {{{ */
7154 @interface SectionController : FilteredPackageListController {
7155 _H<NSString> section_;
7158 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7162 @implementation SectionController
7164 - (NSURL *) navigationURL {
7165 NSString *name = section_;
7169 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7172 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7175 title = UCLocalize("ALL_PACKAGES");
7176 else if (![name isEqual:@""])
7177 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7179 title = UCLocalize("NO_SECTION");
7181 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7188 /* Sections Controller {{{ */
7189 @interface SectionsController : CyteViewController <
7190 UITableViewDataSource,
7193 _transient Database *database_;
7194 _H<NSMutableArray> sections_;
7195 _H<NSMutableArray> filtered_;
7196 _H<UITableView, 2> list_;
7199 - (id) initWithDatabase:(Database *)database;
7200 - (void) editButtonClicked;
7204 @implementation SectionsController
7206 - (NSURL *) navigationURL {
7207 return [NSURL URLWithString:@"cydia://sections"];
7210 - (void) updateNavigationItem {
7211 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7212 if ([sections_ count] == 0) {
7213 [[self navigationItem] setRightBarButtonItem:nil];
7215 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7216 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7218 action:@selector(editButtonClicked)
7219 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7223 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7224 [super setEditing:editing animated:animated];
7229 [delegate_ updateData];
7231 [self updateNavigationItem];
7234 - (void) viewDidAppear:(BOOL)animated {
7235 [super viewDidAppear:animated];
7236 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7239 - (void) viewWillDisappear:(BOOL)animated {
7240 [super viewWillDisappear:animated];
7241 if ([self isEditing]) [self setEditing:NO];
7244 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7245 Section *section = nil;
7246 int index = [indexPath row];
7247 if (![self isEditing]) {
7250 section = [filtered_ objectAtIndex:index];
7252 section = [sections_ objectAtIndex:index];
7257 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7258 if ([self isEditing])
7259 return [sections_ count];
7261 return [filtered_ count] + 1;
7264 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7268 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7269 static NSString *reuseIdentifier = @"SectionCell";
7271 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7273 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7275 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7280 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7281 if ([self isEditing])
7284 Section *section = [self sectionAtIndexPath:indexPath];
7286 SectionController *controller = [[[SectionController alloc]
7287 initWithDatabase:database_
7288 section:[section name]
7290 [controller setDelegate:delegate_];
7292 [[self navigationController] pushViewController:controller animated:YES];
7296 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7298 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7299 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7300 [list_ setRowHeight:45.0f];
7301 [(UITableView *) list_ setDataSource:self];
7302 [list_ setDelegate:self];
7303 [[self view] addSubview:list_];
7306 - (void) viewDidLoad {
7307 [super viewDidLoad];
7309 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7312 - (void) releaseSubviews {
7318 [super releaseSubviews];
7321 - (id) initWithDatabase:(Database *)database {
7322 if ((self = [super init]) != nil) {
7323 database_ = database;
7327 - (void) reloadData {
7330 NSArray *packages = [database_ packages];
7332 sections_ = [NSMutableArray arrayWithCapacity:16];
7333 filtered_ = [NSMutableArray arrayWithCapacity:16];
7335 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7338 for (Package *package in packages) {
7339 NSString *name([package section]);
7340 NSString *key(name == nil ? @"" : name);
7344 _profile(SectionsView$reloadData$Section)
7345 section = [sections objectForKey:key];
7346 if (section == nil) {
7347 _profile(SectionsView$reloadData$Section$Allocate)
7348 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7349 [sections setObject:section forKey:key];
7354 [section addToCount];
7356 _profile(SectionsView$reloadData$Filter)
7357 if (![package valid] || ![package visible])
7365 [sections_ addObjectsFromArray:[sections allValues]];
7367 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7369 for (Section *section in (id) sections_) {
7370 size_t count([section row]);
7374 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7375 [section setCount:count];
7376 [filtered_ addObject:section];
7379 [self updateNavigationItem];
7384 - (void) editButtonClicked {
7385 [self setEditing:![self isEditing] animated:YES];
7391 /* Changes Controller {{{ */
7392 @interface ChangesController : CyteViewController <
7393 UITableViewDataSource,
7396 _transient Database *database_;
7398 _H<NSArray> packages_;
7399 _H<NSMutableArray> sections_;
7400 _H<UITableView, 2> list_;
7404 - (id) initWithDatabase:(Database *)database;
7408 @implementation ChangesController
7410 - (NSURL *) navigationURL {
7411 return [NSURL URLWithString:@"cydia://changes"];
7414 - (void) viewDidAppear:(BOOL)animated {
7415 [super viewDidAppear:animated];
7416 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7419 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7420 NSInteger count([sections_ count]);
7421 return count == 0 ? 1 : count;
7424 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7425 if ([sections_ count] == 0)
7427 return [[sections_ objectAtIndex:section] name];
7430 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7431 if ([sections_ count] == 0)
7433 return [[sections_ objectAtIndex:section] count];
7436 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7437 @synchronized (database_) {
7438 if ([database_ era] != era_)
7441 NSUInteger sectionIndex([path section]);
7442 if (sectionIndex >= [sections_ count])
7444 Section *section([sections_ objectAtIndex:sectionIndex]);
7445 NSInteger row([path row]);
7446 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7449 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7450 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7452 cell = [[[PackageCell alloc] init] autorelease];
7454 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7455 [cell setPackage:package asSummary:false];
7459 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7460 Package *package([self packageAtIndexPath:path]);
7461 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7462 [view setDelegate:delegate_];
7463 [[self navigationController] pushViewController:view animated:YES];
7467 - (void) refreshButtonClicked {
7468 [delegate_ beginUpdate];
7469 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7472 - (void) upgradeButtonClicked {
7473 [delegate_ distUpgrade];
7474 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7478 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7480 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7481 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7482 [list_ setRowHeight:73];
7483 [(UITableView *) list_ setDataSource:self];
7484 [list_ setDelegate:self];
7485 [[self view] addSubview:list_];
7488 - (void) viewDidLoad {
7489 [super viewDidLoad];
7491 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7494 - (void) releaseSubviews {
7500 [super releaseSubviews];
7503 - (id) initWithDatabase:(Database *)database {
7504 if ((self = [super init]) != nil) {
7505 database_ = database;
7509 - (NSMutableArray *) _reloadPackages {
7510 @synchronized (database_) {
7511 era_ = [database_ era];
7512 NSArray *packages([database_ packages]);
7514 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7517 _profile(ChangesController$_reloadPackages$Filter)
7518 for (Package *package in packages)
7519 if ([package upgradableAndEssential:YES] || [package visible])
7520 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7523 _profile(ChangesController$_reloadPackages$radixSort)
7524 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7531 - (void) _reloadData {
7536 UIProgressHUD *hud([delegate_ addProgressHUD]);
7537 [hud setText:UCLocalize("LOADING")];
7538 //NSLog(@"HUD:%@::%@", delegate_, hud);
7539 packages = [self yieldToSelector:@selector(_reloadPackages)];
7540 [delegate_ removeProgressHUD:hud];
7542 packages = [self _reloadPackages];
7545 @synchronized (database_) {
7546 if (era_ != [database_ era])
7549 packages_ = packages;
7550 sections_ = [NSMutableArray arrayWithCapacity:16];
7552 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7553 Section *ignored = nil;
7554 Section *section = nil;
7558 bool unseens = false;
7560 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7562 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7563 Package *package = [packages_ objectAtIndex:offset];
7565 BOOL uae = [package upgradableAndEssential:YES];
7569 time_t seen([package seen]);
7571 if (section == nil || last != seen) {
7575 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7578 _profile(ChangesController$reloadData$Allocate)
7579 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7580 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7581 [sections_ addObject:section];
7585 [section addToCount];
7586 } else if ([package ignored]) {
7587 if (ignored == nil) {
7588 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7590 [ignored addToCount];
7593 [upgradable addToCount];
7598 CFRelease(formatter);
7601 Section *last = [sections_ lastObject];
7602 size_t count = [last count];
7603 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7604 [sections_ removeLastObject];
7607 if ([ignored count] != 0)
7608 [sections_ insertObject:ignored atIndex:0];
7610 [sections_ insertObject:upgradable atIndex:0];
7614 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7615 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7616 style:UIBarButtonItemStylePlain
7618 action:@selector(upgradeButtonClicked)
7619 ] autorelease]) animated:YES];
7621 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7622 initWithTitle:UCLocalize("REFRESH")
7623 style:UIBarButtonItemStylePlain
7625 action:@selector(refreshButtonClicked)
7626 ] autorelease]) animated:YES];
7631 - (void) reloadData {
7633 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7638 /* Search Controller {{{ */
7639 @interface SearchController : FilteredPackageListController <
7642 _H<UISearchBar, 1> search_;
7646 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7647 - (void) reloadData;
7651 @implementation SearchController
7653 - (NSURL *) navigationURL {
7654 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7655 return [NSURL URLWithString:@"cydia://search"];
7657 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7660 - (void) useSearch {
7661 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7666 - (void) viewWillAppear:(BOOL)animated {
7667 [super viewWillAppear:animated];
7669 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7673 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7674 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7679 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7680 [search_ resignFirstResponder];
7684 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7685 [search_ setText:@""];
7686 [self searchBarButtonClicked:searchBar];
7689 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7690 [self searchBarButtonClicked:searchBar];
7693 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7694 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7698 - (bool) shouldYield {
7702 - (bool) shouldBlock {
7703 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7706 - (bool) isSummarized {
7707 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7710 - (bool) showsSections {
7714 - (NSMutableArray *) _reloadPackages {
7715 NSMutableArray *packages([super _reloadPackages]);
7716 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7717 [packages radixSortUsingSelector:@selector(rank)];
7721 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7722 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7723 search_ = [[[UISearchBar alloc] init] autorelease];
7724 [search_ setDelegate:self];
7727 [search_ setText:query];
7731 - (void) viewDidAppear:(BOOL)animated {
7732 [super viewDidAppear:animated];
7734 if (!searchloaded_) {
7735 searchloaded_ = YES;
7736 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7737 [search_ layoutSubviews];
7738 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7740 UITextField *textField;
7741 if ([search_ respondsToSelector:@selector(searchField)])
7742 textField = [search_ searchField];
7744 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7746 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7747 [textField setEnablesReturnKeyAutomatically:NO];
7748 [[self navigationItem] setTitleView:textField];
7752 - (void) reloadData {
7753 id object([search_ text]);
7754 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7755 object = [object componentsSeparatedByString:@" "];
7757 [self setObject:object];
7763 - (void) didSelectPackage:(Package *)package {
7764 [search_ resignFirstResponder];
7765 [super didSelectPackage:package];
7770 /* Package Settings Controller {{{ */
7771 @interface PackageSettingsController : CyteViewController <
7772 UITableViewDataSource,
7775 _transient Database *database_;
7777 _H<Package> package_;
7778 _H<UITableView, 2> table_;
7779 _H<UISwitch> subscribedSwitch_;
7780 _H<UISwitch> ignoredSwitch_;
7781 _H<UITableViewCell> subscribedCell_;
7782 _H<UITableViewCell> ignoredCell_;
7785 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7789 @implementation PackageSettingsController
7791 - (NSURL *) navigationURL {
7792 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7795 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7796 if (package_ == nil)
7799 if ([package_ installed] == nil)
7805 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7806 if (package_ == nil)
7809 // both sections contain just one item right now.
7813 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7817 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7819 return UCLocalize("SHOW_ALL_CHANGES_EX");
7821 return UCLocalize("IGNORE_UPGRADES_EX");
7824 - (void) onSubscribed:(id)control {
7825 bool value([control isOn]);
7826 if (package_ == nil)
7828 if ([package_ setSubscribed:value])
7829 [delegate_ updateData];
7832 - (void) _updateIgnored {
7833 const char *package([name_ UTF8String]);
7834 bool on([ignoredSwitch_ isOn]);
7836 pid_t pid(ExecFork());
7838 FILE *dpkg(popen("dpkg --set-selections", "w"));
7839 fwrite(package, strlen(package), 1, dpkg);
7842 fwrite(" hold\n", 6, 1, dpkg);
7844 fwrite(" install\n", 9, 1, dpkg);
7855 - (void) onIgnored:(id)control {
7856 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7857 [invocation setTarget:self];
7858 [invocation setSelector:@selector(_updateIgnored)];
7860 [delegate_ reloadDataWithInvocation:invocation];
7863 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7864 if (package_ == nil)
7867 switch ([indexPath section]) {
7868 case 0: return subscribedCell_;
7869 case 1: return ignoredCell_;
7878 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7880 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7881 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7882 [(UITableView *) table_ setDataSource:self];
7883 [table_ setDelegate:self];
7884 [[self view] addSubview:table_];
7886 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7887 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7888 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7890 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7891 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7892 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7894 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7895 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7896 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7897 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7899 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7900 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7901 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7902 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7905 - (void) viewDidLoad {
7906 [super viewDidLoad];
7908 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7911 - (void) releaseSubviews {
7913 subscribedCell_ = nil;
7915 ignoredSwitch_ = nil;
7916 subscribedSwitch_ = nil;
7918 [super releaseSubviews];
7921 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7922 if ((self = [super init]) != nil) {
7923 database_ = database;
7928 - (void) reloadData {
7931 package_ = [database_ packageWithName:name_];
7933 if (package_ != nil) {
7934 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7935 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7936 } // XXX: what now, G?
7938 [table_ reloadData];
7944 /* Installed Controller {{{ */
7945 @interface InstalledController : FilteredPackageListController {
7949 - (id) initWithDatabase:(Database *)database;
7951 - (void) updateRoleButton;
7952 - (void) queueStatusDidChange;
7956 @implementation InstalledController
7958 - (NSURL *) navigationURL {
7959 return [NSURL URLWithString:@"cydia://installed"];
7962 - (id) initWithDatabase:(Database *)database {
7963 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7964 [self updateRoleButton];
7965 [self queueStatusDidChange];
7970 - (void) queueButtonClicked {
7975 - (void) queueStatusDidChange {
7979 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7980 initWithTitle:UCLocalize("QUEUE")
7981 style:UIBarButtonItemStyleDone
7983 action:@selector(queueButtonClicked)
7986 [[self navigationItem] setLeftBarButtonItem:nil];
7992 - (void) updateRoleButton {
7993 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7994 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7995 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7996 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7998 action:@selector(roleButtonClicked)
8002 - (void) roleButtonClicked {
8003 [self setObject:[NSNumber numberWithBool:expert_]];
8007 [self updateRoleButton];
8013 /* Source Cell {{{ */
8014 @interface SourceCell : CyteTableViewCell <
8015 CyteTableViewCellDelegate
8019 _H<NSString> origin_;
8020 _H<NSString> label_;
8023 - (void) setSource:(Source *)source;
8027 @implementation SourceCell
8029 - (void) _setImage:(NSArray *)data {
8030 if ([url_ isEqual:[data objectAtIndex:0]]) {
8031 icon_ = [data objectAtIndex:1];
8032 [content_ setNeedsDisplay];
8036 - (void) _setSource:(NSURL *) url {
8037 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8039 if (NSData *data = [NSURLConnection
8040 sendSynchronousRequest:[NSURLRequest
8042 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8046 returningResponse:NULL
8049 if (UIImage *image = [UIImage imageWithData:data])
8050 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8055 - (void) setSource:(Source *)source {
8056 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8058 origin_ = [source name];
8059 label_ = [source rooturi];
8061 [content_ setNeedsDisplay];
8063 url_ = [source iconURL];
8064 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8067 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8068 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8069 UIView *content([self contentView]);
8070 CGRect bounds([content bounds]);
8072 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8073 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8074 [content_ setBackgroundColor:[UIColor whiteColor]];
8075 [content addSubview:content_];
8077 [content_ setDelegate:self];
8078 [content_ setOpaque:YES];
8080 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8084 - (NSString *) accessibilityLabel {
8088 - (void) drawContentRect:(CGRect)rect {
8089 bool highlighted(highlighted_);
8090 float width(rect.size.width);
8094 rect.size = [(UIImage *) icon_ size];
8096 while (rect.size.width > 32 || rect.size.height > 32) {
8097 rect.size.width /= 2;
8098 rect.size.height /= 2;
8101 rect.origin.x = 25 - rect.size.width / 2;
8102 rect.origin.y = 25 - rect.size.height / 2;
8104 [icon_ drawInRect:rect];
8112 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8116 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8121 /* Source Controller {{{ */
8122 @interface SourceController : FilteredPackageListController {
8123 _transient Source *source_;
8127 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8131 @implementation SourceController
8133 - (NSURL *) navigationURL {
8134 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8137 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8138 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8140 key_ = [source key];
8144 - (void) reloadData {
8145 source_ = [database_ sourceWithKey:key_];
8146 key_ = [source_ key];
8147 [self setObject:source_];
8149 [[self navigationItem] setTitle:[source_ label]];
8156 /* Sources Controller {{{ */
8157 @interface SourcesController : CyteViewController <
8158 UITableViewDataSource,
8161 _transient Database *database_;
8164 _H<UITableView, 2> list_;
8165 _H<NSMutableArray> sources_;
8169 _H<UIProgressHUD> hud_;
8172 //NSURLConnection *installer_;
8173 NSURLConnection *trivial_;
8174 NSURLConnection *trivial_bz2_;
8175 NSURLConnection *trivial_gz_;
8176 //NSURLConnection *automatic_;
8181 - (id) initWithDatabase:(Database *)database;
8182 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8186 @implementation SourcesController
8188 - (void) _releaseConnection:(NSURLConnection *)connection {
8189 if (connection != nil) {
8190 [connection cancel];
8191 //[connection setDelegate:nil];
8192 [connection release];
8197 //[self _releaseConnection:installer_];
8198 [self _releaseConnection:trivial_];
8199 [self _releaseConnection:trivial_gz_];
8200 [self _releaseConnection:trivial_bz2_];
8201 //[self _releaseConnection:automatic_];
8206 - (NSURL *) navigationURL {
8207 return [NSURL URLWithString:@"cydia://sources"];
8210 - (void) viewDidAppear:(BOOL)animated {
8211 [super viewDidAppear:animated];
8212 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8215 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8219 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8223 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8224 return [sources_ count];
8227 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8228 @synchronized (database_) {
8229 if ([database_ era] != era_)
8232 return [sources_ objectAtIndex:[indexPath row]];
8235 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8236 static NSString *cellIdentifier = @"SourceCell";
8238 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8239 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8240 [cell setSource:[self sourceAtIndexPath:indexPath]];
8241 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8246 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8247 Source *source = [self sourceAtIndexPath:indexPath];
8249 SourceController *controller = [[[SourceController alloc]
8250 initWithDatabase:database_
8254 [controller setDelegate:delegate_];
8256 [[self navigationController] pushViewController:controller animated:YES];
8259 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8260 Source *source = [self sourceAtIndexPath:indexPath];
8261 return [source record] != nil;
8264 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8265 if (editingStyle == UITableViewCellEditingStyleDelete) {
8266 Source *source = [self sourceAtIndexPath:indexPath];
8267 [Sources_ removeObjectForKey:[source key]];
8268 [delegate_ syncData];
8273 [delegate_ addTrivialSource:href_];
8276 [delegate_ syncData];
8279 - (NSString *) getWarning {
8280 NSString *href(href_);
8281 NSRange colon([href rangeOfString:@"://"]);
8282 if (colon.location != NSNotFound)
8283 href = [href substringFromIndex:(colon.location + 3)];
8284 href = [href stringByAddingPercentEscapes];
8285 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8287 NSURL *url([NSURL URLWithString:href]);
8289 NSStringEncoding encoding;
8290 NSError *error(nil);
8292 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8293 return [warning length] == 0 ? nil : warning;
8297 - (void) _endConnection:(NSURLConnection *)connection {
8298 // XXX: the memory management in this method is horribly awkward
8300 NSURLConnection **field = NULL;
8301 if (connection == trivial_)
8303 else if (connection == trivial_bz2_)
8304 field = &trivial_bz2_;
8305 else if (connection == trivial_gz_)
8306 field = &trivial_gz_;
8307 _assert(field != NULL);
8308 [connection release];
8313 trivial_bz2_ == nil &&
8316 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8318 [delegate_ releaseNetworkActivityIndicator];
8320 [delegate_ removeProgressHUD:hud_];
8324 if (warning != nil) {
8325 UIAlertView *alert = [[[UIAlertView alloc]
8326 initWithTitle:UCLocalize("SOURCE_WARNING")
8329 cancelButtonTitle:UCLocalize("CANCEL")
8331 UCLocalize("ADD_ANYWAY"),
8335 [alert setContext:@"warning"];
8336 [alert setNumberOfRows:1];
8339 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8345 } else if (error_ != nil) {
8346 UIAlertView *alert = [[[UIAlertView alloc]
8347 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8348 message:[error_ localizedDescription]
8350 cancelButtonTitle:UCLocalize("OK")
8351 otherButtonTitles:nil
8354 [alert setContext:@"urlerror"];
8359 UIAlertView *alert = [[[UIAlertView alloc]
8360 initWithTitle:UCLocalize("NOT_REPOSITORY")
8361 message:UCLocalize("NOT_REPOSITORY_EX")
8363 cancelButtonTitle:UCLocalize("OK")
8364 otherButtonTitles:nil
8367 [alert setContext:@"trivial"];
8377 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8378 switch ([response statusCode]) {
8384 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8385 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8387 [self _endConnection:connection];
8390 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8391 [self _endConnection:connection];
8394 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8395 NSURL *url([NSURL URLWithString:href]);
8397 NSMutableURLRequest *request = [NSMutableURLRequest
8399 cachePolicy:NSURLRequestUseProtocolCachePolicy
8400 timeoutInterval:120.0
8403 [request setHTTPMethod:method];
8405 if (Machine_ != NULL)
8406 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8408 if ([url isCydiaSecure]) {
8409 if (UniqueID_ != nil) {
8410 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8411 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8415 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8418 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8419 NSString *context([alert context]);
8421 if ([context isEqualToString:@"source"]) {
8424 NSString *href = [[alert textField] text];
8426 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8428 if (![href hasSuffix:@"/"])
8429 href_ = [href stringByAppendingString:@"/"];
8433 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8434 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8435 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8436 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8440 // XXX: this is stupid
8441 hud_ = [delegate_ addProgressHUD];
8442 [hud_ setText:UCLocalize("VERIFYING_URL")];
8443 [delegate_ retainNetworkActivityIndicator];
8452 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8453 } else if ([context isEqualToString:@"trivial"])
8454 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8455 else if ([context isEqualToString:@"urlerror"])
8456 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8457 else if ([context isEqualToString:@"warning"]) {
8460 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8469 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8474 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8476 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8477 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8478 [list_ setRowHeight:53];
8479 [(UITableView *) list_ setDataSource:self];
8480 [list_ setDelegate:self];
8481 [[self view] addSubview:list_];
8484 - (void) viewDidLoad {
8485 [super viewDidLoad];
8487 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8488 [self updateButtonsForEditingStatus:NO animated:NO];
8491 - (void) releaseSubviews {
8496 [super releaseSubviews];
8499 - (id) initWithDatabase:(Database *)database {
8500 if ((self = [super init]) != nil) {
8501 database_ = database;
8505 - (void) reloadData {
8508 @synchronized (database_) {
8509 era_ = [database_ era];
8512 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8515 sources_ = [NSMutableArray arrayWithCapacity:16];
8516 [sources_ addObjectsFromArray:[database_ sources]];
8518 [sources_ sortUsingSelector:@selector(compareByName:)];
8521 int count([sources_ count]);
8523 for (int i = 0; i != count; i++) {
8524 if ([[sources_ objectAtIndex:i] record] == nil)
8529 [list_ setEditing:NO];
8530 [self updateButtonsForEditingStatus:NO animated:NO];
8534 - (void) showAddSourcePrompt {
8535 UIAlertView *alert = [[[UIAlertView alloc]
8536 initWithTitle:UCLocalize("ENTER_APT_URL")
8539 cancelButtonTitle:UCLocalize("CANCEL")
8541 UCLocalize("ADD_SOURCE"),
8545 [alert setContext:@"source"];
8547 [alert setNumberOfRows:1];
8548 [alert addTextFieldWithValue:@"http://" label:@""];
8550 UITextInputTraits *traits = [[alert textField] textInputTraits];
8551 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8552 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8553 [traits setKeyboardType:UIKeyboardTypeURL];
8554 // XXX: UIReturnKeyDone
8555 [traits setReturnKeyType:UIReturnKeyNext];
8560 - (void) addButtonClicked {
8561 [self showAddSourcePrompt];
8564 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8565 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8566 initWithTitle:UCLocalize("ADD")
8567 style:UIBarButtonItemStylePlain
8569 action:@selector(addButtonClicked)
8570 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8572 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8573 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8574 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8576 action:@selector(editButtonClicked)
8577 ] autorelease] animated:animated];
8579 if (IsWildcat_ && !editing)
8580 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8581 initWithTitle:UCLocalize("SETTINGS")
8582 style:UIBarButtonItemStylePlain
8584 action:@selector(settingsButtonClicked)
8588 - (void) settingsButtonClicked {
8589 [delegate_ showSettings];
8592 - (void) editButtonClicked {
8593 [list_ setEditing:![list_ isEditing] animated:YES];
8595 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8601 /* Settings Controller {{{ */
8602 @interface SettingsController : CyteViewController <
8603 UITableViewDataSource,
8606 _transient Database *database_;
8607 // XXX: ok, "roledelegate_"?...
8608 _transient id roledelegate_;
8609 _H<UITableView, 2> table_;
8610 _H<UISegmentedControl> segment_;
8611 _H<UIView> container_;
8614 - (void) showDoneButton;
8615 - (void) resizeSegmentedControl;
8619 @implementation SettingsController
8622 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8624 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8625 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8626 [table_ setDelegate:self];
8627 [(UITableView *) table_ setDataSource:self];
8628 [[self view] addSubview:table_];
8630 NSArray *items = [NSArray arrayWithObjects:
8632 UCLocalize("HACKER"),
8633 UCLocalize("DEVELOPER"),
8635 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8636 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8637 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8638 [container_ addSubview:segment_];
8641 - (void) viewDidLoad {
8642 [super viewDidLoad];
8644 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8647 if ([Role_ isEqualToString:@"User"]) index = 0;
8648 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8649 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8651 [segment_ setSelectedSegmentIndex:index];
8652 [self showDoneButton];
8655 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8656 [self resizeSegmentedControl];
8659 - (void) releaseSubviews {
8664 [super releaseSubviews];
8667 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8668 if ((self = [super init]) != nil) {
8669 database_ = database;
8670 roledelegate_ = delegate;
8674 - (void) resizeSegmentedControl {
8675 CGFloat width = [[self view] frame].size.width;
8676 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8679 - (void) viewWillAppear:(BOOL)animated {
8680 [super viewWillAppear:animated];
8682 [self resizeSegmentedControl];
8685 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8686 [self resizeSegmentedControl];
8689 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8690 [self resizeSegmentedControl];
8694 NSString *role(nil);
8696 switch ([segment_ selectedSegmentIndex]) {
8697 case 0: role = @"User"; break;
8698 case 1: role = @"Hacker"; break;
8699 case 2: role = @"Developer"; break;
8704 if (![role isEqualToString:Role_]) {
8705 bool rolling(Role_ == nil);
8708 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8712 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8716 [roledelegate_ loadData];
8718 [roledelegate_ updateData];
8722 - (void) segmentChanged:(UISegmentedControl *)control {
8723 [self showDoneButton];
8726 - (void) saveAndClose {
8729 [[self navigationItem] setRightBarButtonItem:nil];
8730 [[self navigationController] dismissModalViewControllerAnimated:YES];
8733 - (void) doneButtonClicked {
8734 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8735 [spinner startAnimating];
8736 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8737 [[self navigationItem] setRightBarButtonItem:spinItem];
8739 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8742 - (void) showDoneButton {
8743 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8744 initWithTitle:UCLocalize("DONE")
8745 style:UIBarButtonItemStyleDone
8747 action:@selector(doneButtonClicked)
8748 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8751 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8752 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8756 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8760 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8761 return nil; // This method is required by the protocol.
8764 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8766 return UCLocalize("ROLE_EX");
8768 return [NSString stringWithFormat:
8769 @"%@: %@\n%@: %@\n%@: %@",
8770 UCLocalize("USER"), UCLocalize("USER_EX"),
8771 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8772 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8777 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8778 return section == 3 ? 44.0f : 0;
8781 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8782 return section == 3 ? container_ : nil;
8785 - (void) reloadData {
8788 [table_ reloadData];
8793 /* Stash Controller {{{ */
8794 @interface StashController : CyteViewController {
8795 _H<UIActivityIndicatorView> spinner_;
8796 _H<UILabel> status_;
8797 _H<UILabel> caption_;
8802 @implementation StashController
8805 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8806 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8808 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8809 CGRect spinrect = [spinner_ frame];
8810 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8811 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8812 [spinner_ setFrame:spinrect];
8813 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8814 [[self view] addSubview:spinner_];
8815 [spinner_ startAnimating];
8818 captrect.size.width = [[self view] frame].size.width;
8819 captrect.size.height = 40.0f;
8820 captrect.origin.x = 0;
8821 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8822 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8823 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8824 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8825 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8826 [caption_ setTextColor:[UIColor whiteColor]];
8827 [caption_ setBackgroundColor:[UIColor clearColor]];
8828 [caption_ setShadowColor:[UIColor blackColor]];
8829 [caption_ setTextAlignment:UITextAlignmentCenter];
8830 [[self view] addSubview:caption_];
8833 statusrect.size.width = [[self view] frame].size.width;
8834 statusrect.size.height = 30.0f;
8835 statusrect.origin.x = 0;
8836 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8837 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8838 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8839 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8840 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8841 [status_ setTextColor:[UIColor whiteColor]];
8842 [status_ setBackgroundColor:[UIColor clearColor]];
8843 [status_ setShadowColor:[UIColor blackColor]];
8844 [status_ setTextAlignment:UITextAlignmentCenter];
8845 [[self view] addSubview:status_];
8848 - (void) releaseSubviews {
8853 [super releaseSubviews];
8859 @interface CYURLCache : SDURLCache {
8864 @implementation CYURLCache
8866 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8869 else if ([event isEqualToString:@"no-cache"])
8871 else if ([event isEqualToString:@"store"])
8873 else if ([event isEqualToString:@"invalid"])
8875 else if ([event isEqualToString:@"memory"])
8877 else if ([event isEqualToString:@"disk"])
8879 else if ([event isEqualToString:@"miss"])
8882 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8886 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8887 if (NSURLResponse *response = [cached response])
8888 if (NSString *mime = [response MIMEType])
8889 if ([mime isEqualToString:@"text/cache-manifest"]) {
8890 NSURL *url([response URL]);
8893 NSLog(@"###: %@", [url absoluteString]);
8896 @synchronized (HostConfig_) {
8897 [CachedURLs_ addObject:url];
8901 [super storeCachedResponse:cached forRequest:request];
8906 @interface Cydia : UIApplication <
8907 ConfirmationControllerDelegate,
8910 UINavigationControllerDelegate,
8911 UITabBarControllerDelegate
8913 _H<UIWindow> window_;
8914 _H<CYTabBarController> tabbar_;
8915 _H<CydiaLoadingViewController> emulated_;
8917 _H<NSMutableArray> essential_;
8918 _H<NSMutableArray> broken_;
8920 Database *database_;
8922 _H<NSURL> starturl_;
8927 _H<StashController> stash_;
8936 @implementation Cydia
8938 - (void) beginUpdate {
8939 [tabbar_ beginUpdate];
8943 return [tabbar_ updating];
8947 if ([broken_ count] != 0) {
8948 int count = [broken_ count];
8950 UIAlertView *alert = [[[UIAlertView alloc]
8951 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8952 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8954 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8956 UCLocalize("TEMPORARY_IGNORE"),
8960 [alert setContext:@"fixhalf"];
8961 [alert setNumberOfRows:2];
8963 } else if (!Ignored_ && [essential_ count] != 0) {
8964 int count = [essential_ count];
8966 UIAlertView *alert = [[[UIAlertView alloc]
8967 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8968 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8970 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8972 UCLocalize("UPGRADE_ESSENTIAL"),
8973 UCLocalize("COMPLETE_UPGRADE"),
8977 [alert setContext:@"upgrade"];
8982 - (void) returnToCydia {
8986 - (void) _saveConfig {
8987 @synchronized (database_) {
8994 NSString *error(nil);
8996 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8998 NSError *error(nil);
8999 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9000 NSLog(@"failure to save metadata data: %@", error);
9005 NSLog(@"failure to serialize metadata: %@", error);
9009 CydiaWriteSources();
9012 // Navigation controller for the queuing badge.
9013 - (UINavigationController *) queueNavigationController {
9014 NSArray *controllers = [tabbar_ viewControllers];
9015 return [controllers objectAtIndex:3];
9018 - (void) unloadData {
9019 [tabbar_ unloadData];
9022 - (void) _updateData {
9026 UINavigationController *navigation = [self queueNavigationController];
9028 id queuedelegate = nil;
9029 if ([[navigation viewControllers] count] > 0)
9030 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9032 [queuedelegate queueStatusDidChange];
9033 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9036 - (void) _refreshIfPossible:(NSDate *)update {
9037 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9039 bool recently = false;
9040 if (update != nil) {
9041 NSTimeInterval interval([update timeIntervalSinceNow]);
9042 if (interval <= 0 && interval > -(15*60))
9046 // Don't automatic refresh if:
9047 // - We already refreshed recently.
9048 // - We already auto-refreshed this launch.
9049 // - Auto-refresh is disabled.
9050 if (recently || loaded_ || ManualRefresh) {
9051 // If we are cancelling, we need to make sure it knows it's already loaded.
9054 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9056 // We are going to load, so remember that.
9059 SCNetworkReachabilityFlags flags; {
9060 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9061 SCNetworkReachabilityGetFlags(reachability, &flags);
9062 CFRelease(reachability);
9065 // XXX: this elaborate mess is what Apple is using to determine this? :(
9066 // XXX: do we care if the user has to intervene? maybe that's ok?
9068 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9069 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9070 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9071 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9072 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9073 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9077 // If we can reach the server, auto-refresh!
9079 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9085 - (void) refreshIfPossible {
9086 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9089 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9090 @synchronized (self) {
9091 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9092 [hud setText:UCLocalize("RELOADING_DATA")];
9094 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9098 [essential_ removeAllObjects];
9099 [broken_ removeAllObjects];
9101 NSArray *packages([database_ packages]);
9102 for (Package *package in packages) {
9104 [broken_ addObject:package];
9105 if ([package upgradableAndEssential:NO]) {
9106 if ([package essential])
9107 [essential_ addObject:package];
9112 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9115 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9116 [changesItem setBadgeValue:badge];
9117 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9118 [self setApplicationIconBadgeNumber:changes];
9121 [changesItem setBadgeValue:nil];
9122 [changesItem setAnimatedBadge:NO];
9123 [self setApplicationIconBadgeNumber:0];
9129 [self removeProgressHUD:hud];
9132 - (void) updateData {
9138 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9141 - (void) disemulate {
9142 if (emulated_ == nil)
9145 [window_ addSubview:[tabbar_ view]];
9146 [[emulated_ view] removeFromSuperview];
9148 [window_ setUserInteractionEnabled:YES];
9151 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9152 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9154 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9156 UIViewController *parent;
9157 if (emulated_ == nil)
9166 [parent presentModalViewController:navigation animated:YES];
9169 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9170 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9172 if (navigation != nil)
9173 [navigation pushViewController:progress animated:YES];
9175 [self presentModalViewController:progress force:YES];
9177 [progress invoke:invocation withTitle:title];
9181 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9182 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9185 - (void) repairWithInvocation:(NSInvocation *)invocation {
9187 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9191 - (void) repairWithSelector:(SEL)selector {
9192 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9195 - (void) reloadData {
9196 [self reloadDataWithInvocation:nil];
9197 if ([database_ progressDelegate] == nil)
9203 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9206 - (void) addSource:(NSDictionary *) source {
9207 CydiaAddSource(source);
9210 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9211 CydiaAddSource(href, distribution, sections);
9214 - (void) addTrivialSource:(NSString *)href {
9215 CydiaAddSource(href, @"./");
9218 - (void) updateValues {
9223 pkgProblemResolver *resolver = [database_ resolver];
9225 resolver->InstallProtect();
9226 if (!resolver->Resolve(true))
9231 // XXX: this is a really crappy way of doing this.
9232 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9233 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9234 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9235 if ([tabbar_ updating])
9236 [tabbar_ cancelUpdate];
9238 if (![database_ prepare])
9241 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9242 [page setDelegate:self];
9243 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9246 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9247 [tabbar_ presentModalViewController:confirm_ animated:YES];
9253 @synchronized (self) {
9258 - (void) clearPackage:(Package *)package {
9259 @synchronized (self) {
9266 - (void) installPackages:(NSArray *)packages {
9267 @synchronized (self) {
9268 for (Package *package in packages)
9275 - (void) installPackage:(Package *)package {
9276 @synchronized (self) {
9283 - (void) removePackage:(Package *)package {
9284 @synchronized (self) {
9291 - (void) distUpgrade {
9292 @synchronized (self) {
9293 if (![database_ upgrade])
9300 [database_ perform];
9301 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9304 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9307 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9309 [self refreshIfPossible];
9312 - (void) showSettings {
9313 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9316 - (void) retainNetworkActivityIndicator {
9317 if (activity_++ == 0)
9318 [self setNetworkActivityIndicatorVisible:YES];
9321 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9325 - (void) releaseNetworkActivityIndicator {
9326 if (--activity_ == 0)
9327 [self setNetworkActivityIndicatorVisible:NO];
9330 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9335 - (void) cancelAndClear:(bool)clear {
9336 @synchronized (self) {
9348 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9349 NSString *context([alert context]);
9351 if ([context isEqualToString:@"conffile"]) {
9352 FILE *input = [database_ input];
9353 if (button == [alert cancelButtonIndex])
9354 fprintf(input, "N\n");
9355 else if (button == [alert firstOtherButtonIndex])
9356 fprintf(input, "Y\n");
9359 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9360 } else if ([context isEqualToString:@"fixhalf"]) {
9361 if (button == [alert cancelButtonIndex]) {
9362 @synchronized (self) {
9363 for (Package *broken in (id) broken_) {
9366 NSString *id = [broken id];
9367 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9368 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9369 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9370 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9376 } else if (button == [alert firstOtherButtonIndex]) {
9377 [broken_ removeAllObjects];
9381 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9382 } else if ([context isEqualToString:@"upgrade"]) {
9383 if (button == [alert firstOtherButtonIndex]) {
9384 @synchronized (self) {
9385 for (Package *essential in (id) essential_)
9386 [essential install];
9391 } else if (button == [alert firstOtherButtonIndex] + 1) {
9393 } else if (button == [alert cancelButtonIndex]) {
9397 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9401 - (void) system:(NSString *)command {
9402 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9405 system([command UTF8String]);
9411 - (void) applicationWillSuspend {
9413 [super applicationWillSuspend];
9416 - (BOOL) isSafeToSuspend {
9419 NSLog(@"isSafeToSuspend: locked_ != 0");
9424 // Use external process status API internally.
9425 // This is probably a really bad idea.
9426 // XXX: what is the point of this? does this solve anything at all?
9427 uint64_t status = 0;
9429 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9430 notify_get_state(notify_token, &status);
9431 notify_cancel(notify_token);
9436 NSLog(@"isSafeToSuspend: status != 0");
9442 NSLog(@"isSafeToSuspend: -> true");
9447 - (void) applicationSuspend:(__GSEvent *)event {
9448 if ([self isSafeToSuspend])
9449 [super applicationSuspend:event];
9452 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9453 if ([self isSafeToSuspend])
9454 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9457 - (void) _setSuspended:(BOOL)value {
9458 if ([self isSafeToSuspend])
9459 [super _setSuspended:value];
9462 - (UIProgressHUD *) addProgressHUD {
9463 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9464 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9466 [window_ setUserInteractionEnabled:NO];
9468 UIViewController *target(tabbar_);
9469 if (UIViewController *modal = [target modalViewController])
9472 [hud showInView:[target view]];
9478 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9481 [hud removeFromSuperview];
9482 [window_ setUserInteractionEnabled:YES];
9485 - (CyteViewController *) pageForPackage:(NSString *)name {
9486 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9489 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9490 NSString *scheme([[url scheme] lowercaseString]);
9491 if ([[url absoluteString] length] <= [scheme length] + 3)
9493 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9494 NSArray *components([path componentsSeparatedByString:@"/"]);
9496 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9497 return [self pageForPackage:[components objectAtIndex:1]];
9499 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9502 NSString *base([components objectAtIndex:0]);
9504 CyteViewController *controller = nil;
9506 if ([base isEqualToString:@"url"]) {
9507 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9508 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9509 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9510 } else if (!external && [components count] == 1) {
9511 if ([base isEqualToString:@"manage"]) {
9512 controller = [[[ManageController alloc] init] autorelease];
9515 if ([base isEqualToString:@"storage"]) {
9516 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9519 if ([base isEqualToString:@"sources"]) {
9520 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9523 if ([base isEqualToString:@"home"]) {
9524 controller = [[[HomeController alloc] init] autorelease];
9527 if ([base isEqualToString:@"sections"]) {
9528 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9531 if ([base isEqualToString:@"search"]) {
9532 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9535 if ([base isEqualToString:@"changes"]) {
9536 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9539 if ([base isEqualToString:@"installed"]) {
9540 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9542 } else if ([components count] == 2) {
9543 NSString *argument = [components objectAtIndex:1];
9545 if ([base isEqualToString:@"package"]) {
9546 controller = [self pageForPackage:argument];
9549 if (!external && [base isEqualToString:@"search"]) {
9550 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9553 if (!external && [base isEqualToString:@"sections"]) {
9554 if ([argument isEqualToString:@"all"])
9556 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9559 if (!external && [base isEqualToString:@"sources"]) {
9560 if ([argument isEqualToString:@"add"]) {
9561 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9562 [(SourcesController *)controller showAddSourcePrompt];
9564 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9565 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9569 if (!external && [base isEqualToString:@"launch"]) {
9570 [self launchApplicationWithIdentifier:argument suspended:NO];
9573 } else if (!external && [components count] == 3) {
9574 NSString *arg1 = [components objectAtIndex:1];
9575 NSString *arg2 = [components objectAtIndex:2];
9577 if ([base isEqualToString:@"package"]) {
9578 if ([arg2 isEqualToString:@"settings"]) {
9579 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9580 } else if ([arg2 isEqualToString:@"files"]) {
9581 if (Package *package = [database_ packageWithName:arg1]) {
9582 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9583 [(FileTable *)controller setPackage:package];
9589 [controller setDelegate:self];
9593 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9594 CyteViewController *page([self pageForURL:url forExternal:external]);
9597 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9598 [nav setViewControllers:[NSArray arrayWithObject:page]];
9599 [tabbar_ setUnselectedViewController:nav];
9605 - (void) applicationOpenURL:(NSURL *)url {
9606 [super applicationOpenURL:url];
9611 [self openCydiaURL:url forExternal:YES];
9614 - (void) applicationWillResignActive:(UIApplication *)application {
9615 // Stop refreshing if you get a phone call or lock the device.
9616 if ([tabbar_ updating])
9617 [tabbar_ cancelUpdate];
9619 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9620 [super applicationWillResignActive:application];
9623 - (void) saveState {
9624 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9625 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9626 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9632 - (void) applicationWillTerminate:(UIApplication *)application {
9636 - (void) setConfigurationData:(NSString *)data {
9637 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9639 if (!conffile_r(data)) {
9640 lprintf("E:invalid conffile\n");
9644 NSString *ofile = conffile_r[1];
9645 //NSString *nfile = conffile_r[2];
9647 UIAlertView *alert = [[[UIAlertView alloc]
9648 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9649 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9651 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9653 UCLocalize("ACCEPT_NEW_COPY"),
9654 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9658 [alert setContext:@"conffile"];
9659 [alert setNumberOfRows:2];
9663 - (void) addStashController {
9665 stash_ = [[[StashController alloc] init] autorelease];
9666 [window_ addSubview:[stash_ view]];
9669 - (void) removeStashController {
9670 [[stash_ view] removeFromSuperview];
9676 [self setIdleTimerDisabled:YES];
9678 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9679 UpdateExternalStatus(1);
9680 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9681 UpdateExternalStatus(0);
9683 [self removeStashController];
9685 pid_t pid(ExecFork());
9687 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9688 perror("launchctl stop");
9695 - (void) setupViewControllers {
9696 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9698 NSMutableArray *items([NSMutableArray arrayWithObjects:
9699 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9700 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9701 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9702 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9706 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9707 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9709 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9712 NSMutableArray *controllers([NSMutableArray array]);
9713 for (UITabBarItem *item in items) {
9714 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9715 [controller setTabBarItem:item];
9716 [controllers addObject:controller];
9718 [tabbar_ setViewControllers:controllers];
9720 [tabbar_ setUpdateDelegate:self];
9723 - (void) _sendMemoryWarningNotification {
9724 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9727 - (void) _sendMemoryWarningNotifications {
9729 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9734 - (void) applicationDidFinishLaunching:(id)unused {
9735 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9738 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9739 [self setApplicationSupportsShakeToEdit:NO];
9741 @synchronized (HostConfig_) {
9742 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9745 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9746 initWithMemoryCapacity:524288
9747 diskCapacity:10485760
9748 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9751 [CydiaWebViewController _initialize];
9753 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9755 // this would disallow http{,s} URLs from accessing this data
9756 //[WebView registerURLSchemeAsLocal:@"cydia"];
9758 Font12_ = [UIFont systemFontOfSize:12];
9759 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9760 Font14_ = [UIFont systemFontOfSize:14];
9761 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9762 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9764 essential_ = [NSMutableArray arrayWithCapacity:4];
9765 broken_ = [NSMutableArray arrayWithCapacity:4];
9767 // XXX: I really need this thing... like, seriously... I'm sorry
9768 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9770 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9771 [window_ orderFront:self];
9772 [window_ makeKey:self];
9773 [window_ setHidden:NO];
9776 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9777 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9778 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9779 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9780 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9781 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9782 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9783 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9784 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9787 [self addStashController];
9788 // XXX: this would be much cleaner as a yieldToSelector:
9789 // that way the removeStashController could happen right here inline
9790 // we also could no longer require the useless stash_ field anymore
9791 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9795 database_ = [Database sharedInstance];
9796 [database_ setDelegate:self];
9798 [window_ setUserInteractionEnabled:NO];
9799 [self setupViewControllers];
9801 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9802 [window_ addSubview:[emulated_ view]];
9804 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9808 - (NSArray *) defaultStartPages {
9809 NSMutableArray *standard = [NSMutableArray array];
9810 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9811 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9812 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9814 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9816 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9817 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9819 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9826 [window_ setUserInteractionEnabled:YES];
9827 [self showSettings];
9830 if ([emulated_ modalViewController] != nil)
9831 [emulated_ dismissModalViewControllerAnimated:YES];
9832 [window_ setUserInteractionEnabled:NO];
9835 [self reloadDataWithInvocation:nil];
9836 [self refreshIfPossible];
9841 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9842 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9843 int standardIndex = 0;
9844 NSArray *standard = [self defaultStartPages];
9851 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9852 if (valid && closed != nil) {
9853 NSTimeInterval interval([closed timeIntervalSinceNow]);
9854 // XXX: Is 15 minutes the optimal time here?
9855 if (interval > 0 && interval <= -(15*60))
9859 if (valid && [saved count] != [standard count])
9863 for (unsigned int i = 0; i < [standard count]; i++) {
9864 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9865 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9866 // but it's good enough for now.
9867 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9874 NSArray *items = nil;
9876 [tabbar_ setSelectedIndex:savedIndex];
9879 [tabbar_ setSelectedIndex:standardIndex];
9883 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9884 NSArray *stack = [items objectAtIndex:tab];
9885 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9886 NSMutableArray *current = [NSMutableArray array];
9888 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9889 NSString *addr = [stack objectAtIndex:nav];
9890 NSURL *url = [NSURL URLWithString:addr];
9891 CyteViewController *page = [self pageForURL:url forExternal:NO];
9893 [current addObject:page];
9896 [navigation setViewControllers:current];
9899 // (Try to) show the startup URL.
9900 if (starturl_ != nil) {
9901 [self openCydiaURL:starturl_ forExternal:NO];
9906 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9907 if (item != nil && IsWildcat_) {
9908 [sheet showFromBarButtonItem:item animated:YES];
9910 [sheet showInView:window_];
9914 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9915 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9916 [progress setTitle:task];
9917 [progress addProgressEvent:event];
9920 - (void) addProgressEventForTask:(NSArray *)data {
9921 CydiaProgressEvent *event([data objectAtIndex:0]);
9922 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9923 [self addProgressEvent:event forTask:task];
9926 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9927 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9933 id Alloc_(id self, SEL selector) {
9934 id object = alloc_(self, selector);
9935 lprintf("[%s]A-%p\n", self->isa->name, object);
9940 id Dealloc_(id self, SEL selector) {
9941 id object = dealloc_(self, selector);
9942 lprintf("[%s]D-%p\n", self->isa->name, object);
9946 Class $WebDefaultUIKitDelegate;
9948 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9949 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9950 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9951 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9954 static NSSet *MobilizedFiles_;
9956 static NSURL *MobilizeURL(NSURL *url) {
9957 NSString *path([url path]);
9958 if ([path hasPrefix:@"/var/root/"]) {
9959 NSString *file([path substringFromIndex:10]);
9960 if ([MobilizedFiles_ containsObject:file])
9961 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9967 Class $CFXPreferencesPropertyListSource;
9968 @class CFXPreferencesPropertyListSource;
9970 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9971 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9972 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9973 url = MobilizeURL(url);
9974 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9975 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9981 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9982 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9983 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9984 url = MobilizeURL(url);
9985 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9986 //NSLog(@"%@ %@", [url absoluteString], value);
9992 Class $NSURLConnection;
9994 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9995 NSMutableURLRequest *copy([request mutableCopy]);
9997 NSURL *url([copy URL]);
9999 NSString *host([url host]);
10000 NSString *scheme([[url scheme] lowercaseString]);
10002 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10004 @synchronized (HostConfig_) {
10005 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10006 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10007 [copy setHTTPShouldUsePipelining:YES];
10009 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10010 if ([control isEqualToString:@"max-age=0"])
10011 if ([CachedURLs_ containsObject:url]) {
10013 NSLog(@"~~~: %@", url);
10016 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10018 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10019 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10020 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10024 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10028 int main(int argc, char *argv[]) {
10029 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10033 UpdateExternalStatus(0);
10035 if (Class $UIDevice = objc_getClass("UIDevice")) {
10036 UIDevice *device([$UIDevice currentDevice]);
10037 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10039 IsWildcat_ = false;
10041 UIScreen *screen([UIScreen mainScreen]);
10042 if ([screen respondsToSelector:@selector(scale)])
10043 ScreenScale_ = [screen scale];
10047 UIDevice *device([UIDevice currentDevice]);
10048 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10049 Idiom_ = @"iphone";
10051 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10052 if (idiom == UIUserInterfaceIdiomPhone)
10053 Idiom_ = @"iphone";
10054 else if (idiom == UIUserInterfaceIdiomPad)
10057 NSLog(@"unknown UIUserInterfaceIdiom!");
10060 Pcre pattern("^([0-9]+\\.[0-9]+)");
10062 if (pattern([device systemVersion]))
10063 Firmware_ = pattern[1];
10064 if (pattern(Cydia_))
10065 Major_ = pattern[1];
10067 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10069 HostConfig_ = [[[NSObject alloc] init] autorelease];
10070 @synchronized (HostConfig_) {
10071 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10072 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10073 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10074 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10075 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10078 NSString *ui(@"ui/ios");
10080 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10081 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10082 UI_ = CydiaURL(ui);
10084 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10086 MobilizedFiles_ = [NSMutableSet setWithObjects:
10087 @"Library/Preferences/com.apple.Accessibility.plist",
10088 @"Library/Preferences/com.apple.preferences.sounds.plist",
10091 /* Library Hacks {{{ */
10092 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10094 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10096 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10097 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10098 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10099 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10102 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10103 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10104 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10105 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10108 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10109 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10110 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10111 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10112 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10115 $NSURLConnection = objc_getClass("NSURLConnection");
10116 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10117 if (NSURLConnection$init$ != NULL) {
10118 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10119 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10122 /* Set Locale {{{ */
10123 Locale_ = CFLocaleCopyCurrent();
10124 Languages_ = [NSLocale preferredLanguages];
10126 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10127 //NSLog(@"%@", [Languages_ description]);
10130 if (Locale_ != NULL)
10131 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10132 else if (Languages_ != nil && [Languages_ count] != 0)
10133 lang = [[Languages_ objectAtIndex:0] UTF8String];
10135 // XXX: consider just setting to C and then falling through?
10138 if (lang != NULL) {
10139 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10140 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10143 NSLog(@"Setting Language: %s", lang);
10145 if (lang != NULL) {
10146 setenv("LANG", lang, true);
10147 std::setlocale(LC_ALL, lang);
10151 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10153 /* Parse Arguments {{{ */
10154 bool substrate(false);
10160 for (int argi(1); argi != argc; ++argi)
10161 if (strcmp(argv[argi], "--") == 0) {
10163 argv[argi] = argv[0];
10169 for (int argi(1); argi != arge; ++argi)
10170 if (strcmp(args[argi], "--substrate") == 0)
10173 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10177 App_ = [[NSBundle mainBundle] bundlePath];
10183 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10184 alloc_ = alloc->method_imp;
10185 alloc->method_imp = (IMP) &Alloc_;*/
10187 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10188 dealloc_ = dealloc->method_imp;
10189 dealloc->method_imp = (IMP) &Dealloc_;*/
10191 /* System Information {{{ */
10195 size = sizeof(maxproc);
10196 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10197 perror("sysctlbyname(\"kern.maxproc\", ?)");
10198 else if (maxproc < 64) {
10200 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10201 perror("sysctlbyname(\"kern.maxproc\", #)");
10204 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10205 char *osversion = new char[size];
10206 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10207 perror("sysctlbyname(\"kern.osversion\", ?)");
10209 System_ = [NSString stringWithUTF8String:osversion];
10211 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10212 char *machine = new char[size];
10213 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10214 perror("sysctlbyname(\"hw.machine\", ?)");
10216 Machine_ = machine;
10218 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10219 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10220 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10222 UniqueID_ = [device uniqueIdentifier];
10224 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10225 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10226 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10228 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10229 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10230 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10232 if (mcc != NULL && mnc != NULL)
10233 if (CFStringGetLength(mcc) == 3) {
10234 CFIndex length(CFStringGetLength(mnc));
10235 if (length == 2 || length == 3) {
10236 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10238 Pcre pattern("^[0-9]{5,6}$");
10239 if (!pattern(PLMN_))
10249 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10250 Build_ = [system objectForKey:@"ProductBuildVersion"];
10251 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10252 Product_ = [info objectForKey:@"SafariProductVersion"];
10253 Safari_ = [info objectForKey:@"CFBundleVersion"];
10256 /* Load Database {{{ */
10258 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10260 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10262 if (Metadata_ == NULL)
10263 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10265 Settings_ = [Metadata_ objectForKey:@"Settings"];
10267 Packages_ = [Metadata_ objectForKey:@"Packages"];
10269 Values_ = [Metadata_ objectForKey:@"Values"];
10270 Sections_ = [Metadata_ objectForKey:@"Sections"];
10271 Sources_ = [Metadata_ objectForKey:@"Sources"];
10273 Token_ = [Metadata_ objectForKey:@"Token"];
10275 Version_ = [Metadata_ objectForKey:@"Version"];
10277 @synchronized (HostConfig_) {
10278 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10282 if (Settings_ != nil)
10283 Role_ = [Settings_ objectForKey:@"Role"];
10285 if (Values_ == nil) {
10286 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10287 [Metadata_ setObject:Values_ forKey:@"Values"];
10290 if (Sections_ == nil) {
10291 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10292 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10295 if (Sources_ == nil) {
10296 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10297 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10300 if (Version_ == nil) {
10301 Version_ = [NSNumber numberWithUnsignedInt:0];
10302 [Metadata_ setObject:Version_ forKey:@"Version"];
10305 @synchronized (HostConfig_) {
10306 if (CydiaSource_ == nil) {
10307 CydiaSource_ = @"apt.saurik.com";
10308 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10312 if ([Version_ unsignedIntValue] == 0) {
10313 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10314 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10315 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10316 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10318 Version_ = [NSNumber numberWithUnsignedInt:1];
10319 [Metadata_ setObject:Version_ forKey:@"Version"];
10321 [Metadata_ removeObjectForKey:@"LastUpdate"];
10327 CydiaWriteSources();
10330 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10333 if (Packages_ != nil) {
10335 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10339 [Metadata_ removeObjectForKey:@"Packages"];
10345 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10347 #define MobileSubstrate_(name) \
10348 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10349 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10350 if (handle == NULL) \
10351 NSLog(@"%s", dlerror()); \
10354 MobileSubstrate_(Activator)
10355 MobileSubstrate_(libstatusbar)
10356 MobileSubstrate_(SimulatedKeyEvents)
10357 MobileSubstrate_(WinterBoard)
10359 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10360 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10362 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10364 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10365 unlink("/tmp/.cydia.fw");
10367 } else if (access("/User", F_OK) != 0 || version < 4) {
10370 system("/usr/libexec/cydia/firmware.sh");
10374 _assert([[NSFileManager defaultManager]
10375 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10376 withIntermediateDirectories:YES
10381 if (access("/tmp/cydia.chk", F_OK) == 0) {
10382 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10383 _assert(errno == ENOENT);
10384 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10385 _assert(errno == ENOENT);
10388 /* APT Initialization {{{ */
10389 _assert(pkgInitConfig(*_config));
10390 _assert(pkgInitSystem(*_config, _system));
10393 _config->Set("APT::Acquire::Translation", lang);
10395 // XXX: this timeout might be important :(
10396 //_config->Set("Acquire::http::Timeout", 15);
10398 _config->Set("Acquire::http::MaxParallel", 3);
10400 /* Color Choices {{{ */
10401 space_ = CGColorSpaceCreateDeviceRGB();
10403 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10404 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10405 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10406 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10407 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10408 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10409 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10410 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10411 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10413 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10414 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10416 /* UIKit Configuration {{{ */
10417 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10418 if ($GSFontSetUseLegacyFontMetrics != NULL)
10419 $GSFontSetUseLegacyFontMetrics(YES);
10421 // XXX: I have a feeling this was important
10422 //UIKeyboardDisableAutomaticAppearance();
10425 Colon_ = UCLocalize("COLON_DELIMITED");
10426 Elision_ = UCLocalize("ELISION");
10427 Error_ = UCLocalize("ERROR");
10428 Warning_ = UCLocalize("WARNING");
10431 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10433 CGColorSpaceRelease(space_);
10434 CFRelease(Locale_);