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 <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
210 #define Cydia_ CYDIA_VERSION
212 #define lprintf(args...) fprintf(stderr, args)
215 #define TraceLogging (1 && !ForRelease)
216 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
217 #define ProfileTimes (0 && !ForRelease)
218 #define ForSaurik (0 && !ForRelease)
219 #define LogBrowser (0 && !ForRelease)
220 #define TrackResize (0 && !ForRelease)
221 #define ManualRefresh (1 && !ForRelease)
222 #define ShowInternals (0 && !ForRelease)
223 #define AlwaysReload (0 && !ForRelease)
224 #define TryIndexedCollation (0 && !ForRelease)
228 #define _trace(args...)
233 #define _profile(name) {
236 #define PrintTimes() do {} while (false)
239 // Hash Functions/Structures {{{
240 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
250 static _finline NSString *CydiaURL(NSString *path) {
252 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
253 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
254 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
255 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
256 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
258 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
261 static _finline void UpdateExternalStatus(uint64_t newStatus) {
263 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
264 notify_set_state(notify_token, newStatus);
265 notify_cancel(notify_token);
267 notify_post("com.saurik.Cydia.status");
270 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
271 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
272 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
275 /* NSForcedOrderingSearch doesn't work on the iPhone */
276 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
277 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
278 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
280 /* Insertion Sort {{{ */
282 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
283 const char *ptr = (const char *)list;
285 CFIndex half = count / 2;
286 const char *probe = ptr + elementSize * half;
287 CFComparisonResult cr = comparator(element, probe, context);
288 if (0 == cr) return (probe - (const char *)list) / elementSize;
289 ptr = (cr < 0) ? ptr : probe + elementSize;
290 count = (cr < 0) ? half : (half + (count & 1) - 1);
292 return (ptr - (const char *)list) / elementSize;
295 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
296 const char *ptr = (const char *)list;
298 CFIndex half = count / 2;
299 const char *probe = ptr + elementSize * half;
300 CFComparisonResult cr = comparator(element, probe, context);
301 if (0 == cr) return (probe - (const char *)list) / elementSize;
302 ptr = (cr < 0) ? ptr : probe + elementSize;
303 count = (cr < 0) ? half : (half + (count & 1) - 1);
305 return (ptr - (const char *)list) / elementSize;
308 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
309 if (range.length == 0)
311 const void **values(new const void *[range.length]);
312 CFArrayGetValues(array, range, values);
314 #if HistogramInsertionSort > 0
315 uint32_t total(0), *offsets(new uint32_t[range.length]);
318 for (CFIndex index(1); index != range.length; ++index) {
319 const void *value(values[index]);
320 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
321 CFIndex correct(index);
322 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
323 #if HistogramInsertionSort > 1
324 NSLog(@"%@ < %@", value, values[correct - 1]);
329 if (correct != index) {
330 size_t offset(index - correct);
331 #if HistogramInsertionSort
335 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
337 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
338 values[correct] = value;
342 CFArrayReplaceValues(array, range, values, range.length);
345 #if HistogramInsertionSort > 0
346 for (CFIndex index(0); index != range.length; ++index)
347 if (offsets[index] != 0)
348 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
349 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
356 /* Apple Bug Fixes {{{ */
357 @implementation UIWebDocumentView (Cydia)
359 - (void) _setScrollerOffset:(CGPoint)offset {
360 UIScroller *scroller([self _scroller]);
362 CGSize size([scroller contentSize]);
363 CGSize bounds([scroller bounds].size);
366 max.x = size.width - bounds.width;
367 max.y = size.height - bounds.height;
375 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
376 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
378 [scroller setOffset:offset];
384 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
385 size_t length([self length] - state->state);
388 else if (length > count)
390 for (size_t i(0); i != length; ++i)
391 objects[i] = [self item:state->state++];
392 state->itemsPtr = objects;
393 state->mutationsPtr = (unsigned long *) self;
397 /* Cydia NSString Additions {{{ */
398 @interface NSString (Cydia)
399 - (NSComparisonResult) compareByPath:(NSString *)other;
400 - (NSString *) stringByCachingURLWithCurrentCDN;
401 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
404 @implementation NSString (Cydia)
406 - (NSComparisonResult) compareByPath:(NSString *)other {
407 NSString *prefix = [self commonPrefixWithString:other options:0];
408 size_t length = [prefix length];
410 NSRange lrange = NSMakeRange(length, [self length] - length);
411 NSRange rrange = NSMakeRange(length, [other length] - length);
413 lrange = [self rangeOfString:@"/" options:0 range:lrange];
414 rrange = [other rangeOfString:@"/" options:0 range:rrange];
416 NSComparisonResult value;
418 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
419 value = NSOrderedSame;
420 else if (lrange.location == NSNotFound)
421 value = NSOrderedAscending;
422 else if (rrange.location == NSNotFound)
423 value = NSOrderedDescending;
425 value = NSOrderedSame;
427 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
428 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
429 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
430 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
432 NSComparisonResult result = [lpath compare:rpath];
433 return result == NSOrderedSame ? value : result;
436 - (NSString *) stringByCachingURLWithCurrentCDN {
438 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
439 withString:@"://cache.cydia.saurik.com/"
443 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
444 return [(id)CFURLCreateStringByAddingPercentEscapes(
449 kCFStringEncodingUTF8
456 /* C++ NSString Wrapper Cache {{{ */
457 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
458 return size == 0 ? NULL :
459 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
460 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
463 static _finline CFStringRef CYStringCreate(const char *data) {
464 return CYStringCreate(data, strlen(data));
473 _finline void clear_() {
474 if (cache_ != NULL) {
481 _finline bool empty() const {
485 _finline size_t size() const {
489 _finline char *data() const {
493 _finline void clear() {
498 _finline CYString() :
505 _finline ~CYString() {
509 void operator =(const CYString &rhs) {
513 if (rhs.cache_ == nil)
516 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
519 void copy(apr_pool_t *pool) {
520 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
521 memcpy(temp, data_, size_);
526 void set(apr_pool_t *pool, const char *data, size_t size) {
532 data_ = const_cast<char *>(data);
540 _finline void set(apr_pool_t *pool, const char *data) {
541 set(pool, data, data == NULL ? 0 : strlen(data));
544 _finline void set(apr_pool_t *pool, const std::string &rhs) {
545 set(pool, rhs.data(), rhs.size());
548 bool operator ==(const CYString &rhs) const {
549 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
552 _finline operator CFStringRef() {
554 cache_ = CYStringCreate(data_, size_);
558 _finline operator id() {
559 return (NSString *) static_cast<CFStringRef>(*this);
562 _finline operator const char *() {
563 return reinterpret_cast<const char *>(data_);
567 /* C++ NSString Algorithm Adapters {{{ */
569 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
572 struct NSStringMapHash :
573 std::unary_function<NSString *, size_t>
575 _finline size_t operator ()(NSString *value) const {
576 return CFStringHashNSString((CFStringRef) value);
580 struct NSStringMapLess :
581 std::binary_function<NSString *, NSString *, bool>
583 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
584 return [lhs compare:rhs] == NSOrderedAscending;
588 struct NSStringMapEqual :
589 std::binary_function<NSString *, NSString *, bool>
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
593 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
594 //[lhs isEqualToString:rhs];
599 /* CoreGraphics Primitives {{{ */
604 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
605 CGFloat color[] = {red, green, blue, alpha};
606 return CGColorCreate(space, color);
615 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
616 color_(Create_(space, red, green, blue, alpha))
618 Set(space, red, green, blue, alpha);
623 CGColorRelease(color_);
630 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
632 color_ = Create_(space, red, green, blue, alpha);
635 operator CGColorRef() {
641 /* Random Global Variables {{{ */
642 static const int PulseInterval_ = 50000;
644 static const NSString *UI_;
647 static bool RestartSubstrate_;
648 static NSArray *Finishes_;
650 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
651 #define NotifyConfig_ "/etc/notify.conf"
653 static bool Queuing_;
655 static CYColor Blue_;
656 static CYColor Blueish_;
657 static CYColor Black_;
659 static CYColor White_;
660 static CYColor Gray_;
661 static CYColor Green_;
662 static CYColor Purple_;
663 static CYColor Purplish_;
665 static UIColor *InstallingColor_;
666 static UIColor *RemovingColor_;
668 static NSString *App_;
670 static BOOL Advanced_;
671 static BOOL Ignored_;
673 static _H<UIFont> Font12_;
674 static _H<UIFont> Font12Bold_;
675 static _H<UIFont> Font14_;
676 static _H<UIFont> Font18Bold_;
677 static _H<UIFont> Font22Bold_;
679 static const char *Machine_ = NULL;
680 static NSString *System_ = nil;
681 static NSString *SerialNumber_ = nil;
682 static NSString *ChipID_ = nil;
683 static NSString *BBSNum_ = nil;
684 static _H<NSString> Token_;
685 static NSString *UniqueID_ = nil;
686 static NSString *PLMN_ = nil;
687 static NSString *Build_ = nil;
688 static NSString *Product_ = nil;
689 static NSString *Safari_ = nil;
691 static CFLocaleRef Locale_;
692 static NSArray *Languages_;
693 static CGColorSpaceRef space_;
695 static NSDictionary *SectionMap_;
696 static NSMutableDictionary *Metadata_;
697 static _transient NSMutableDictionary *Settings_;
698 static _transient NSString *Role_;
699 static _transient NSMutableDictionary *Packages_;
700 static _transient NSMutableDictionary *Values_;
701 static _transient NSMutableDictionary *Sections_;
702 static _transient NSMutableDictionary *Sources_;
703 static bool Changed_;
707 static CGFloat ScreenScale_;
708 static NSString *Idiom_;
710 static _H<NSMutableDictionary> SessionData_;
711 static _H<NSObject> HostConfig_;
712 static _H<NSMutableSet> BridgedHosts_;
713 static _H<NSMutableSet> TokenHosts_;
714 static _H<NSMutableSet> InsecureHosts_;
715 static _H<NSMutableSet> PipelinedHosts_;
716 static _H<NSMutableSet> CachedURLs_;
718 static NSString *kCydiaProgressEventTypeError = @"Error";
719 static NSString *kCydiaProgressEventTypeInformation = @"Information";
720 static NSString *kCydiaProgressEventTypeStatus = @"Status";
721 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
724 /* Display Helpers {{{ */
725 inline float Interpolate(float begin, float end, float fraction) {
726 return (end - begin) * fraction + begin;
729 static _finline const char *StripVersion_(const char *version) {
730 const char *colon(strchr(version, ':'));
731 return colon == NULL ? version : colon + 1;
734 NSString *LocalizeSection(NSString *section) {
735 static Pcre title_r("^(.*?) \\((.*)\\)$");
736 if (title_r(section)) {
737 NSString *parent(title_r[1]);
738 NSString *child(title_r[2]);
740 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
741 LocalizeSection(parent),
742 LocalizeSection(child)
746 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
749 NSString *Simplify(NSString *title) {
750 const char *data = [title UTF8String];
751 size_t size = [title length];
753 static Pcre square_r("^\\[(.*)\\]$");
754 if (square_r(data, size))
755 return Simplify(square_r[1]);
757 static Pcre paren_r("^\\((.*)\\)$");
758 if (paren_r(data, size))
759 return Simplify(paren_r[1]);
761 static Pcre title_r("^(.*?) \\((.*)\\)$");
762 if (title_r(data, size))
763 return Simplify(title_r[1]);
769 NSString *GetLastUpdate() {
770 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
773 return UCLocalize("NEVER_OR_UNKNOWN");
775 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
776 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
778 CFRelease(formatter);
780 return [(NSString *) formatted autorelease];
783 bool isSectionVisible(NSString *section) {
784 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
785 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
786 return hidden == nil || ![hidden boolValue];
789 static NSObject *CYIOGetValue(const char *path, NSString *property) {
790 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
791 if (entry == MACH_PORT_NULL)
794 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
795 IOObjectRelease(entry);
799 return [(id) value autorelease];
802 static NSString *CYHex(NSData *data, bool reverse = false) {
806 size_t length([data length]);
807 uint8_t bytes[length];
808 [data getBytes:bytes];
810 char string[length * 2 + 1];
811 for (size_t i(0); i != length; ++i)
812 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
814 return [NSString stringWithUTF8String:string];
819 /* Delegate Prototypes {{{ */
822 @class CydiaProgressEvent;
824 @protocol DatabaseDelegate
825 - (void) repairWithSelector:(SEL)selector;
826 - (void) setConfigurationData:(NSString *)data;
827 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
830 @class CYPackageController;
832 @protocol CydiaDelegate
833 - (void) retainNetworkActivityIndicator;
834 - (void) releaseNetworkActivityIndicator;
835 - (void) clearPackage:(Package *)package;
836 - (void) installPackage:(Package *)package;
837 - (void) installPackages:(NSArray *)packages;
838 - (void) removePackage:(Package *)package;
839 - (void) beginUpdate;
841 - (void) distUpgrade;
845 - (void) addTrivialSource:(NSString *)href;
846 - (void) showSettings;
847 - (UIProgressHUD *) addProgressHUD;
848 - (void) removeProgressHUD:(UIProgressHUD *)hud;
849 - (CyteViewController *) pageForPackage:(NSString *)name;
850 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
851 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
855 /* Status Delegation {{{ */
857 public pkgAcquireStatus
860 _transient NSObject<ProgressDelegate> *delegate_;
870 void setDelegate(NSObject<ProgressDelegate> *delegate) {
871 delegate_ = delegate;
874 NSObject<ProgressDelegate> *getDelegate() const {
878 virtual bool MediaChange(std::string media, std::string drive) {
882 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
885 virtual void Fetch(pkgAcquire::ItemDesc &item) {
886 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
887 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
888 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
891 virtual void Done(pkgAcquire::ItemDesc &item) {
894 virtual void Fail(pkgAcquire::ItemDesc &item) {
896 item.Owner->Status == pkgAcquire::Item::StatIdle ||
897 item.Owner->Status == pkgAcquire::Item::StatDone
901 std::string &error(item.Owner->ErrorText);
905 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
906 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
909 virtual bool Pulse(pkgAcquire *Owner) {
910 bool value = pkgAcquireStatus::Pulse(Owner);
913 double(CurrentBytes + CurrentItems) /
914 double(TotalBytes + TotalItems)
917 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
918 [NSNumber numberWithDouble:percent], @"Percent",
920 [NSNumber numberWithDouble:CurrentBytes], @"Current",
921 [NSNumber numberWithDouble:TotalBytes], @"Total",
922 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
923 nil] waitUntilDone:YES];
925 if (value && ![delegate_ isProgressCancelled])
933 _finline bool WasCancelled() const {
937 virtual void Start() {
938 pkgAcquireStatus::Start();
939 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
942 virtual void Stop() {
943 pkgAcquireStatus::Stop();
944 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
945 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
949 /* Database Interface {{{ */
950 typedef std::map< unsigned long, _H<Source> > SourceMap;
952 @interface Database : NSObject {
959 pkgDepCache::Policy *policy_;
960 pkgRecords *records_;
961 pkgProblemResolver *resolver_;
962 pkgAcquire *fetcher_;
964 SPtr<pkgPackageManager> manager_;
965 pkgSourceList *list_;
967 SourceMap sourceMap_;
968 _H<NSMutableArray> sourceList_;
970 CFMutableArrayRef packages_;
972 _transient NSObject<DatabaseDelegate> *delegate_;
973 _transient NSObject<ProgressDelegate> *progress_;
981 std::map<const char *, _H<NSString> > sections_;
984 + (Database *) sharedInstance;
987 - (void) _readCydia:(NSNumber *)fd;
988 - (void) _readStatus:(NSNumber *)fd;
989 - (void) _readOutput:(NSNumber *)fd;
993 - (Package *) packageWithName:(NSString *)name;
995 - (pkgCacheFile &) cache;
996 - (pkgDepCache::Policy *) policy;
997 - (pkgRecords *) records;
998 - (pkgProblemResolver *) resolver;
999 - (pkgAcquire &) fetcher;
1000 - (pkgSourceList &) list;
1001 - (NSArray *) packages;
1002 - (NSArray *) sources;
1003 - (Source *) sourceWithKey:(NSString *)key;
1004 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1012 - (void) updateWithStatus:(Status &)status;
1014 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1016 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1017 - (NSObject<ProgressDelegate> *) progressDelegate;
1019 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1021 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1025 /* ProgressEvent Implementation {{{ */
1026 @implementation CydiaProgressEvent
1028 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1029 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1032 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1033 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1034 [event setPackage:package];
1038 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1039 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1041 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1042 NSArray *fields([description componentsSeparatedByString:@" "]);
1043 [event setItem:fields];
1045 if ([fields count] > 3) {
1046 [event setPackage:[fields objectAtIndex:2]];
1047 [event setVersion:[fields objectAtIndex:3]];
1050 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1055 + (NSArray *) _attributeKeys {
1056 return [NSArray arrayWithObjects:
1066 - (NSArray *) attributeKeys {
1067 return [[self class] _attributeKeys];
1070 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1071 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1074 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1075 if ((self = [super init]) != nil) {
1081 - (NSString *) message {
1085 - (NSString *) type {
1089 - (NSArray *) item {
1090 return (id) item_ ?: [NSNull null];
1093 - (void) setItem:(NSArray *)item {
1097 - (NSString *) package {
1098 return (id) package_ ?: [NSNull null];
1101 - (void) setPackage:(NSString *)package {
1105 - (NSString *) url {
1106 return (id) url_ ?: [NSNull null];
1109 - (void) setURL:(NSString *)url {
1113 - (void) setVersion:(NSString *)version {
1117 - (NSString *) version {
1118 return (id) version_ ?: [NSNull null];
1121 - (NSString *) compound:(NSString *)value {
1123 NSString *mode(nil); {
1124 NSString *type([self type]);
1125 if ([type isEqualToString:kCydiaProgressEventTypeError])
1126 mode = UCLocalize("ERROR");
1127 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1128 mode = UCLocalize("WARNING");
1132 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1138 - (NSString *) compoundMessage {
1139 return [self compound:[self message]];
1142 - (NSString *) compoundTitle {
1145 if (package_ == nil)
1147 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1148 title = [package name];
1152 return [self compound:title];
1158 // Cytore Definitions {{{
1159 struct PackageValue :
1162 Cytore::Offset<PackageValue> next_;
1164 uint32_t index_ : 23;
1165 uint32_t subscribed_ : 1;
1182 Cytore::Offset<PackageValue> packages_[1 << 16];
1185 static Cytore::File<MetaValue> MetaFile_;
1187 // Cytore Helper Functions {{{
1188 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1189 SplitHash nhash = { hashlittle(name, length) };
1191 PackageValue *metadata;
1193 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1194 offset: if (offset->IsNull()) {
1195 *offset = MetaFile_.New<PackageValue>(length + 1);
1196 metadata = &MetaFile_.Get(*offset);
1198 if (metadata == NULL) {
1202 metadata = new PackageValue();
1203 memset(metadata, 0, sizeof(*metadata));
1206 memcpy(metadata->name_, name, length + 1);
1207 metadata->nhash_ = nhash.u16[1];
1209 metadata = &MetaFile_.Get(*offset);
1211 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1212 offset = &metadata->next_;
1220 static void PackageImport(const void *key, const void *value, void *context) {
1221 bool &fail(*reinterpret_cast<bool *>(context));
1224 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1225 NSLog(@"failed to import package %@", key);
1229 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1230 NSDictionary *package((NSDictionary *) value);
1232 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1233 if ([subscribed boolValue] && !metadata->subscribed_)
1234 metadata->subscribed_ = true;
1236 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1237 time_t time([date timeIntervalSince1970]);
1238 if (metadata->first_ > time || metadata->first_ == 0)
1239 metadata->first_ = time;
1242 NSDate *date([package objectForKey:@"LastSeen"]);
1243 NSString *version([package objectForKey:@"LastVersion"]);
1245 if (date != nil && version != nil) {
1246 time_t time([date timeIntervalSince1970]);
1247 if (metadata->last_ < time || metadata->last_ == 0)
1248 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1249 size_t length(strlen(buffer));
1250 uint16_t vhash(hashlittle(buffer, length));
1252 size_t capped(std::min<size_t>(8, length));
1253 char *latest(buffer + length - capped);
1255 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1256 metadata->vhash_ = vhash;
1258 metadata->last_ = time;
1264 /* Source Class {{{ */
1265 @interface Source : NSObject {
1266 CYString depiction_;
1267 CYString description_;
1273 CYString distribution_;
1279 _H<NSString> authority_;
1281 CYString defaultIcon_;
1283 _H<NSDictionary> record_;
1287 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1289 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1291 - (NSString *) depictionForPackage:(NSString *)package;
1292 - (NSString *) supportForPackage:(NSString *)package;
1294 - (NSDictionary *) record;
1298 - (NSString *) distribution;
1299 - (NSString *) type;
1301 - (NSString *) base;
1304 - (NSString *) host;
1306 - (NSString *) name;
1307 - (NSString *) shortDescription;
1308 - (NSString *) label;
1309 - (NSString *) origin;
1310 - (NSString *) version;
1312 - (NSString *) defaultIcon;
1316 @implementation Source
1320 distribution_.clear();
1325 description_.clear();
1331 defaultIcon_.clear();
1338 + (NSArray *) _attributeKeys {
1339 return [NSArray arrayWithObjects:
1346 @"shortDescription",
1354 - (NSArray *) attributeKeys {
1355 return [[self class] _attributeKeys];
1358 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1359 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1362 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1365 trusted_ = index->IsTrusted();
1367 uri_.set(pool, index->GetURI());
1368 distribution_.set(pool, index->GetDist());
1369 type_.set(pool, index->GetType());
1371 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1372 if (dindex != NULL) {
1373 base_.set(pool, dindex->MetaIndexURI(""));
1376 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1379 pkgTagFile tags(&fd);
1381 pkgTagSection section;
1388 {"default-icon", &defaultIcon_},
1389 {"depiction", &depiction_},
1390 {"description", &description_},
1392 {"origin", &origin_},
1393 {"support", &support_},
1394 {"version", &version_},
1397 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1398 const char *start, *end;
1400 if (section.Find(names[i].name_, start, end)) {
1401 CYString &value(*names[i].value_);
1402 value.set(pool, start, end - start);
1408 record_ = [Sources_ objectForKey:[self key]];
1410 NSURL *url([NSURL URLWithString:uri_]);
1414 host_ = [host_ lowercaseString];
1419 authority_ = [url path];
1422 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1423 if ((self = [super init]) != nil) {
1424 [self setMetaIndex:index inPool:pool];
1428 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1429 NSDictionary *lhr = [self record];
1430 NSDictionary *rhr = [source record];
1433 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1435 NSString *lhs = [self name];
1436 NSString *rhs = [source name];
1438 if ([lhs length] != 0 && [rhs length] != 0) {
1439 unichar lhc = [lhs characterAtIndex:0];
1440 unichar rhc = [rhs characterAtIndex:0];
1442 if (isalpha(lhc) && !isalpha(rhc))
1443 return NSOrderedAscending;
1444 else if (!isalpha(lhc) && isalpha(rhc))
1445 return NSOrderedDescending;
1448 return [lhs compare:rhs options:LaxCompareOptions_];
1451 - (NSString *) depictionForPackage:(NSString *)package {
1452 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1455 - (NSString *) supportForPackage:(NSString *)package {
1456 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1459 - (NSDictionary *) record {
1467 - (NSString *) uri {
1471 - (NSString *) distribution {
1472 return distribution_;
1475 - (NSString *) type {
1479 - (NSString *) base {
1483 - (NSString *) key {
1484 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1487 - (NSString *) host {
1491 - (NSString *) name {
1492 return origin_.empty() ? (id) authority_ : origin_;
1495 - (NSString *) shortDescription {
1496 return description_;
1499 - (NSString *) label {
1500 return label_.empty() ? (id) authority_ : label_;
1503 - (NSString *) origin {
1507 - (NSString *) version {
1511 - (NSString *) defaultIcon {
1512 return defaultIcon_;
1517 /* CydiaOperation Class {{{ */
1518 @interface CydiaOperation : NSObject {
1519 _H<NSString> operator_;
1520 _H<NSString> value_;
1523 - (NSString *) operator;
1524 - (NSString *) value;
1528 @implementation CydiaOperation
1530 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1531 if ((self = [super init]) != nil) {
1532 operator_ = [NSString stringWithUTF8String:_operator];
1533 value_ = [NSString stringWithUTF8String:value];
1537 + (NSArray *) _attributeKeys {
1538 return [NSArray arrayWithObjects:
1544 - (NSArray *) attributeKeys {
1545 return [[self class] _attributeKeys];
1548 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1549 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1552 - (NSString *) operator {
1556 - (NSString *) value {
1562 /* CydiaClause Class {{{ */
1563 @interface CydiaClause : NSObject {
1564 _H<NSString> package_;
1565 _H<CydiaOperation> version_;
1568 - (NSString *) package;
1569 - (CydiaOperation *) version;
1573 @implementation CydiaClause
1575 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1576 if ((self = [super init]) != nil) {
1577 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1579 if (const char *version = dep.TargetVer())
1580 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1582 version_ = (id) [NSNull null];
1586 + (NSArray *) _attributeKeys {
1587 return [NSArray arrayWithObjects:
1593 - (NSArray *) attributeKeys {
1594 return [[self class] _attributeKeys];
1597 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1598 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1601 - (NSString *) package {
1605 - (CydiaOperation *) version {
1611 /* CydiaRelation Class {{{ */
1612 @interface CydiaRelation : NSObject {
1613 _H<NSString> relationship_;
1614 _H<NSMutableArray> clauses_;
1617 - (NSString *) relationship;
1618 - (NSArray *) clauses;
1622 @implementation CydiaRelation
1624 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1625 if ((self = [super init]) != nil) {
1626 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1627 clauses_ = [NSMutableArray arrayWithCapacity:8];
1629 pkgCache::DepIterator start;
1630 pkgCache::DepIterator end;
1631 dep.GlobOr(start, end); // ++dep
1634 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1636 // yes, seriously. (wtf?)
1644 + (NSArray *) _attributeKeys {
1645 return [NSArray arrayWithObjects:
1651 - (NSArray *) attributeKeys {
1652 return [[self class] _attributeKeys];
1655 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1656 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1659 - (NSString *) relationship {
1660 return relationship_;
1663 - (NSArray *) clauses {
1667 - (void) addClause:(CydiaClause *)clause {
1668 [clauses_ addObject:clause];
1673 /* Package Class {{{ */
1674 struct ParsedPackage {
1679 CYString depiction_;
1689 @interface Package : NSObject {
1692 uint32_t essential_ : 1;
1693 uint32_t obsolete_ : 1;
1694 uint32_t ignored_ : 1;
1700 _transient Database *database_;
1702 pkgCache::VerIterator version_;
1703 pkgCache::PkgIterator iterator_;
1704 pkgCache::VerFileIterator file_;
1710 CYString installed_;
1712 const char *section_;
1713 _transient NSString *section$_;
1717 PackageValue *metadata_;
1718 ParsedPackage *parsed_;
1720 _H<NSMutableArray> tags_;
1723 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1724 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1726 - (pkgCache::PkgIterator) iterator;
1729 - (NSString *) section;
1730 - (NSString *) simpleSection;
1732 - (NSString *) longSection;
1733 - (NSString *) shortSection;
1737 - (MIMEAddress *) maintainer;
1739 - (NSString *) longDescription;
1740 - (NSString *) shortDescription;
1743 - (PackageValue *) metadata;
1746 - (bool) subscribed;
1747 - (bool) setSubscribed:(bool)subscribed;
1751 - (NSString *) latest;
1752 - (NSString *) installed;
1753 - (BOOL) uninstalled;
1756 - (BOOL) upgradableAndEssential:(BOOL)essential;
1759 - (BOOL) unfiltered;
1763 - (BOOL) halfConfigured;
1764 - (BOOL) halfInstalled;
1766 - (NSString *) mode;
1769 - (NSString *) name;
1771 - (NSString *) homepage;
1772 - (NSString *) depiction;
1773 - (MIMEAddress *) author;
1775 - (NSString *) support;
1777 - (NSArray *) files;
1778 - (NSArray *) warnings;
1779 - (NSArray *) applications;
1781 - (Source *) source;
1784 - (BOOL) matches:(NSArray *)query;
1786 - (bool) hasSupportingRole;
1787 - (BOOL) hasTag:(NSString *)tag;
1788 - (NSString *) primaryPurpose;
1789 - (NSArray *) purposes;
1790 - (bool) isCommercial;
1792 - (void) setIndex:(size_t)index;
1794 - (CYString &) cyname;
1796 - (uint32_t) compareBySection:(NSArray *)sections;
1801 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1802 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1803 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1804 - (bool) isVisibleInSection:(NSString *)section;
1805 - (bool) isVisibleInSource:(Source *)source;
1809 uint32_t PackageChangesRadix(Package *self, void *) {
1814 uint32_t timestamp : 30;
1815 uint32_t ignored : 1;
1816 uint32_t upgradable : 1;
1820 bool upgradable([self upgradableAndEssential:YES]);
1821 value.bits.upgradable = upgradable ? 1 : 0;
1824 value.bits.timestamp = 0;
1825 value.bits.ignored = [self ignored] ? 0 : 1;
1826 value.bits.upgradable = 1;
1828 value.bits.timestamp = [self seen] >> 2;
1829 value.bits.ignored = 0;
1830 value.bits.upgradable = 0;
1833 return _not(uint32_t) - value.key;
1836 uint32_t PackagePrefixRadix(Package *self, void *context) {
1837 size_t offset(reinterpret_cast<size_t>(context));
1838 CYString &name([self cyname]);
1840 size_t size(name.size());
1843 char *text(name.data());
1846 if (!isdigit(text[0]))
1850 while (size != digits && isdigit(text[digits]))
1858 if (offset == 0 && zeros != 0) {
1859 memset(data, '0', zeros);
1860 memcpy(data + zeros, text, 4 - zeros);
1862 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1863 if (size <= offset - zeros)
1866 text += offset - zeros;
1867 size -= offset - zeros;
1870 memcpy(data, text, 4);
1872 memcpy(data, text, size);
1873 memset(data + size, 0, 4 - size);
1876 for (size_t i(0); i != 4; ++i)
1877 if (isalpha(data[i]))
1885 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1887 /* XXX: ntohl may be more honest */
1888 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1891 CYString &(*PackageName)(Package *self, SEL sel);
1893 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1894 _profile(PackageNameCompare)
1895 CYString &lhi(PackageName(lhs, @selector(cyname)));
1896 CYString &rhi(PackageName(rhs, @selector(cyname)));
1897 CFStringRef lhn(lhi), rhn(rhi);
1900 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1901 else if (rhn == NULL)
1902 return NSOrderedDescending;
1904 _profile(PackageNameCompare$NumbersLast)
1905 if (!lhi.empty() && !rhi.empty()) {
1906 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1907 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1908 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1909 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1910 return lha ? NSOrderedAscending : NSOrderedDescending;
1914 CFIndex length = CFStringGetLength(lhn);
1916 _profile(PackageNameCompare$Compare)
1917 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1922 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1923 return PackageNameCompare(*lhs, *rhs, context);
1926 struct PackageNameOrdering :
1927 std::binary_function<Package *, Package *, bool>
1929 _finline bool operator ()(Package *lhs, Package *rhs) const {
1930 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1934 @implementation Package
1936 - (NSString *) description {
1937 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1941 if (parsed_ != NULL)
1946 + (NSString *) webScriptNameForSelector:(SEL)selector {
1948 else if (selector == @selector(clear))
1950 else if (selector == @selector(getField:))
1952 else if (selector == @selector(hasTag:))
1954 else if (selector == @selector(install))
1956 else if (selector == @selector(remove))
1962 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1963 return [self webScriptNameForSelector:selector] == nil;
1966 + (NSArray *) _attributeKeys {
1967 return [NSArray arrayWithObjects:
1986 @"shortDescription",
1999 - (NSArray *) attributeKeys {
2000 return [[self class] _attributeKeys];
2003 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2004 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2007 - (NSArray *) relations {
2008 @synchronized (database_) {
2009 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2010 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2011 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2015 - (NSString *) getField:(NSString *)name {
2016 @synchronized (database_) {
2017 if ([database_ era] != era_ || file_.end())
2020 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2022 const char *start, *end;
2023 if (!parser.Find([name UTF8String], start, end))
2024 return (NSString *) [NSNull null];
2026 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2030 if (parsed_ != NULL)
2032 @synchronized (database_) {
2033 if ([database_ era] != era_ || file_.end())
2036 ParsedPackage *parsed(new ParsedPackage);
2039 _profile(Package$parse)
2040 pkgRecords::Parser *parser;
2042 _profile(Package$parse$Lookup)
2043 parser = &[database_ records]->Lookup(file_);
2048 _profile(Package$parse$Find)
2053 {"icon", &parsed->icon_},
2054 {"depiction", &parsed->depiction_},
2055 {"homepage", &parsed->homepage_},
2056 {"website", &website},
2057 {"bugs", &parsed->bugs_},
2058 {"support", &parsed->support_},
2059 {"sponsor", &parsed->sponsor_},
2060 {"author", &parsed->author_},
2063 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2064 const char *start, *end;
2066 if (parser->Find(names[i].name_, start, end)) {
2067 CYString &value(*names[i].value_);
2068 _profile(Package$parse$Value)
2069 value.set(pool_, start, end - start);
2075 _profile(Package$parse$Tagline)
2076 const char *start, *end;
2077 if (parser->ShortDesc(start, end)) {
2078 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2081 while (stop != start && stop[-1] == '\r')
2083 parsed->tagline_.set(pool_, start, stop - start);
2087 _profile(Package$parse$Retain)
2088 if (parsed->homepage_.empty())
2089 parsed->homepage_ = website;
2090 if (parsed->homepage_ == parsed->depiction_)
2091 parsed->homepage_.clear();
2096 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2097 if ((self = [super init]) != nil) {
2098 _profile(Package$initWithVersion)
2101 database_ = database;
2102 era_ = [database era];
2106 pkgCache::PkgIterator iterator(version.ParentPkg());
2107 iterator_ = iterator;
2109 _profile(Package$initWithVersion$Version)
2110 if (!version_.end())
2111 file_ = version_.FileList();
2113 pkgCache &cache([database_ cache]);
2114 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2118 _profile(Package$initWithVersion$Cache)
2119 name_.set(NULL, iterator.Display());
2121 latest_.set(NULL, StripVersion_(version_.VerStr()));
2123 pkgCache::VerIterator current(iterator.CurrentVer());
2125 installed_.set(NULL, StripVersion_(current.VerStr()));
2128 _profile(Package$initWithVersion$Tags)
2129 pkgCache::TagIterator tag(iterator.TagList());
2131 tags_ = [NSMutableArray arrayWithCapacity:8];
2133 const char *name(tag.Name());
2134 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2136 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2137 if (strcmp(name + 6, "enduser") == 0)
2139 else if (strcmp(name + 6, "hacker") == 0)
2141 else if (strcmp(name + 6, "developer") == 0)
2143 else if (strcmp(name + 6, "cydia") == 0)
2149 if (strncmp(name, "cydia::", 7) == 0) {
2150 if (strcmp(name + 7, "essential") == 0)
2152 else if (strcmp(name + 7, "obsolete") == 0)
2157 } while (!tag.end());
2161 _profile(Package$initWithVersion$Metadata)
2162 const char *mixed(iterator.Name());
2163 size_t size(strlen(mixed));
2164 char lower[size + 1];
2166 for (size_t i(0); i != size; ++i)
2167 lower[i] = mixed[i] | 0x20;
2170 PackageValue *metadata(PackageFind(lower, size));
2171 metadata_ = metadata;
2173 id_.set(NULL, metadata->name_, size);
2175 const char *latest(version_.VerStr());
2176 size_t length(strlen(latest));
2178 uint16_t vhash(hashlittle(latest, length));
2180 size_t capped(std::min<size_t>(8, length));
2181 latest = latest + length - capped;
2183 if (metadata->first_ == 0)
2184 metadata->first_ = now_;
2186 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2187 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2188 metadata->vhash_ = vhash;
2189 metadata->last_ = now_;
2190 } else if (metadata->last_ == 0)
2191 metadata->last_ = metadata->first_;
2194 _profile(Package$initWithVersion$Section)
2195 section_ = iterator.Section();
2198 _profile(Package$initWithVersion$Flags)
2199 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2200 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2205 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2206 pkgCache::VerIterator version;
2208 _profile(Package$packageWithIterator$GetCandidateVer)
2209 version = [database policy]->GetCandidateVer(iterator);
2217 _profile(Package$packageWithIterator$Allocate)
2218 package = [Package allocWithZone:zone];
2221 _profile(Package$packageWithIterator$Initialize)
2223 initWithVersion:version
2230 _profile(Package$packageWithIterator$Autorelease)
2231 package = [package autorelease];
2237 - (pkgCache::PkgIterator) iterator {
2241 - (NSString *) section {
2242 if (section$_ == nil) {
2243 if (section_ == NULL)
2246 _profile(Package$section$mappedSectionForPointer)
2247 section$_ = [database_ mappedSectionForPointer:section_];
2252 - (NSString *) simpleSection {
2253 if (NSString *section = [self section])
2254 return Simplify(section);
2259 - (NSString *) longSection {
2260 return LocalizeSection([self section]);
2263 - (NSString *) shortSection {
2264 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2267 - (NSString *) uri {
2270 pkgIndexFile *index;
2271 pkgCache::PkgFileIterator file(file_.File());
2272 if (![database_ list].FindIndex(file, index))
2274 return [NSString stringWithUTF8String:iterator_->Path];
2275 //return [NSString stringWithUTF8String:file.Site()];
2276 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2280 - (MIMEAddress *) maintainer {
2281 @synchronized (database_) {
2282 if ([database_ era] != era_ || file_.end())
2285 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2286 const std::string &maintainer(parser->Maintainer());
2287 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2291 @synchronized (database_) {
2292 if ([database_ era] != era_ || version_.end())
2295 return version_->InstalledSize;
2298 - (NSString *) longDescription {
2299 @synchronized (database_) {
2300 if ([database_ era] != era_ || file_.end())
2303 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2304 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2306 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2307 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2308 if ([lines count] < 2)
2311 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2312 for (size_t i(1), e([lines count]); i != e; ++i) {
2313 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2314 [trimmed addObject:trim];
2317 return [trimmed componentsJoinedByString:@"\n"];
2320 - (NSString *) shortDescription {
2321 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2325 _profile(Package$index)
2326 CFStringRef name((CFStringRef) [self name]);
2327 if (CFStringGetLength(name) == 0)
2329 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2330 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2332 return toupper(character);
2336 - (PackageValue *) metadata {
2341 PackageValue *metadata([self metadata]);
2342 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2345 - (bool) subscribed {
2346 return [self metadata]->subscribed_;
2349 - (bool) setSubscribed:(bool)subscribed {
2350 PackageValue *metadata([self metadata]);
2351 if (metadata->subscribed_ == subscribed)
2353 metadata->subscribed_ = subscribed;
2361 - (NSString *) latest {
2365 - (NSString *) installed {
2369 - (BOOL) uninstalled {
2370 return installed_.empty();
2374 return !version_.end();
2377 - (BOOL) upgradableAndEssential:(BOOL)essential {
2378 _profile(Package$upgradableAndEssential)
2379 pkgCache::VerIterator current(iterator_.CurrentVer());
2381 return essential && essential_;
2383 return !version_.end() && version_ != current;
2387 - (BOOL) essential {
2392 return [database_ cache][iterator_].InstBroken();
2395 - (BOOL) unfiltered {
2396 _profile(Package$unfiltered$obsolete)
2397 if (_unlikely(obsolete_))
2401 _profile(Package$unfiltered$hasSupportingRole)
2402 if (_unlikely(![self hasSupportingRole]))
2410 if (![self unfiltered])
2415 _profile(Package$visible$section)
2416 section = [self section];
2419 _profile(Package$visible$isSectionVisible)
2420 if (!isSectionVisible(section))
2428 unsigned char current(iterator_->CurrentState);
2429 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2432 - (BOOL) halfConfigured {
2433 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2436 - (BOOL) halfInstalled {
2437 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2441 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2442 return state.Mode != pkgDepCache::ModeKeep;
2445 - (NSString *) mode {
2446 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2448 switch (state.Mode) {
2449 case pkgDepCache::ModeDelete:
2450 if ((state.iFlags & pkgDepCache::Purge) != 0)
2454 case pkgDepCache::ModeKeep:
2455 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2456 return @"REINSTALL";
2457 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2461 case pkgDepCache::ModeInstall:
2462 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2463 return @"REINSTALL";
2464 else*/ switch (state.Status) {
2466 return @"DOWNGRADE";
2472 return @"NEW_INSTALL";
2483 - (NSString *) name {
2484 return name_.empty() ? id_ : name_;
2487 - (UIImage *) icon {
2488 NSString *section = [self simpleSection];
2491 if (parsed_ != NULL)
2492 if (NSString *href = parsed_->icon_)
2493 if ([href hasPrefix:@"file:///"])
2494 // XXX: correct escaping
2495 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2496 if (icon == nil) if (section != nil)
2497 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2498 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2499 if ([dicon hasPrefix:@"file:///"])
2500 // XXX: correct escaping
2501 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2503 icon = [UIImage applicationImageNamed:@"unknown.png"];
2507 - (NSString *) homepage {
2508 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2511 - (NSString *) depiction {
2512 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2515 - (MIMEAddress *) sponsor {
2516 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2519 - (MIMEAddress *) author {
2520 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2523 - (NSString *) support {
2524 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2527 - (NSArray *) files {
2528 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2529 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2532 fin.open([path UTF8String]);
2537 while (std::getline(fin, line))
2538 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2543 - (NSString *) state {
2544 @synchronized (database_) {
2545 if ([database_ era] != era_ || file_.end())
2548 switch (iterator_->CurrentState) {
2549 case pkgCache::State::NotInstalled:
2550 return @"NotInstalled";
2551 case pkgCache::State::UnPacked:
2553 case pkgCache::State::HalfConfigured:
2554 return @"HalfConfigured";
2555 case pkgCache::State::HalfInstalled:
2556 return @"HalfInstalled";
2557 case pkgCache::State::ConfigFiles:
2558 return @"ConfigFiles";
2559 case pkgCache::State::Installed:
2560 return @"Installed";
2561 case pkgCache::State::TriggersAwaited:
2562 return @"TriggersAwaited";
2563 case pkgCache::State::TriggersPending:
2564 return @"TriggersPending";
2567 return (NSString *) [NSNull null];
2570 - (NSString *) selection {
2571 @synchronized (database_) {
2572 if ([database_ era] != era_ || file_.end())
2575 switch (iterator_->SelectedState) {
2576 case pkgCache::State::Unknown:
2578 case pkgCache::State::Install:
2580 case pkgCache::State::Hold:
2582 case pkgCache::State::DeInstall:
2583 return @"DeInstall";
2584 case pkgCache::State::Purge:
2588 return (NSString *) [NSNull null];
2591 - (NSArray *) warnings {
2592 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2593 const char *name(iterator_.Name());
2595 size_t length(strlen(name));
2596 if (length < 2) invalid:
2597 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2598 else for (size_t i(0); i != length; ++i)
2600 /* XXX: technically this is not allowed */
2601 (name[i] < 'A' || name[i] > 'Z') &&
2602 (name[i] < 'a' || name[i] > 'z') &&
2603 (name[i] < '0' || name[i] > '9') &&
2604 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2607 if (strcmp(name, "cydia") != 0) {
2610 bool _private = false;
2613 bool repository = [[self section] isEqualToString:@"Repositories"];
2615 if (NSArray *files = [self files])
2616 for (NSString *file in files)
2617 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2619 else if (!user && [file isEqualToString:@"/User"])
2621 else if (!_private && [file isEqualToString:@"/private"])
2623 else if (!stash && [file isEqualToString:@"/var/stash"])
2626 /* XXX: this is not sensitive enough. only some folders are valid. */
2627 if (cydia && !repository)
2628 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2630 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2632 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2634 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2637 return [warnings count] == 0 ? nil : warnings;
2640 - (NSArray *) applications {
2641 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2643 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2645 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2646 if (NSArray *files = [self files])
2647 for (NSString *file in files)
2648 if (application_r(file)) {
2649 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2650 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2651 if ([id isEqualToString:me])
2654 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2656 display = application_r[1];
2658 NSString *bundle([file stringByDeletingLastPathComponent]);
2659 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2660 if (icon == nil || [icon length] == 0)
2662 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2664 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2665 [applications addObject:application];
2667 [application addObject:id];
2668 [application addObject:display];
2669 [application addObject:url];
2672 return [applications count] == 0 ? nil : applications;
2675 - (Source *) source {
2676 if (source_ == nil) {
2677 @synchronized (database_) {
2678 if ([database_ era] != era_ || file_.end())
2679 source_ = (Source *) [NSNull null];
2681 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2685 return source_ == (Source *) [NSNull null] ? nil : source_;
2692 - (BOOL) matches:(NSArray *)query {
2693 if (query == nil || [query count] == 0)
2704 string = [self name];
2705 length = [string length];
2707 for (NSString *term in query) {
2708 range = [string rangeOfString:term options:MatchCompareOptions_];
2709 if (range.location != NSNotFound)
2710 rank_ -= 6 * 1000000 / length;
2715 length = [string length];
2717 for (NSString *term in query) {
2718 range = [string rangeOfString:term options:MatchCompareOptions_];
2719 if (range.location != NSNotFound)
2720 rank_ -= 6 * 1000000 / length;
2724 string = [self shortDescription];
2725 length = [string length];
2726 NSUInteger stop(std::min<NSUInteger>(length, 100));
2728 for (NSString *term in query) {
2729 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2730 if (range.location != NSNotFound)
2731 rank_ -= 2 * 100000;
2737 - (bool) hasSupportingRole {
2742 if ([Role_ isEqualToString:@"User"])
2746 if ([Role_ isEqualToString:@"Hacker"])
2750 if ([Role_ isEqualToString:@"Developer"])
2755 - (NSArray *) tags {
2759 - (BOOL) hasTag:(NSString *)tag {
2760 return tags_ == nil ? NO : [tags_ containsObject:tag];
2763 - (NSString *) primaryPurpose {
2764 for (NSString *tag in (NSArray *) tags_)
2765 if ([tag hasPrefix:@"purpose::"])
2766 return [tag substringFromIndex:9];
2770 - (NSArray *) purposes {
2771 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2772 for (NSString *tag in (NSArray *) tags_)
2773 if ([tag hasPrefix:@"purpose::"])
2774 [purposes addObject:[tag substringFromIndex:9]];
2775 return [purposes count] == 0 ? nil : purposes;
2778 - (bool) isCommercial {
2779 return [self hasTag:@"cydia::commercial"];
2782 - (void) setIndex:(size_t)index {
2783 if (metadata_->index_ != index)
2784 metadata_->index_ = index;
2787 - (CYString &) cyname {
2788 return name_.empty() ? id_ : name_;
2791 - (uint32_t) compareBySection:(NSArray *)sections {
2792 NSString *section([self section]);
2793 for (size_t i(0), e([sections count]); i != e; ++i) {
2794 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2798 return _not(uint32_t);
2802 @synchronized (database_) {
2803 pkgProblemResolver *resolver = [database_ resolver];
2804 resolver->Clear(iterator_);
2806 pkgCacheFile &cache([database_ cache]);
2807 cache->SetReInstall(iterator_, false);
2808 cache->MarkKeep(iterator_, false);
2812 @synchronized (database_) {
2813 pkgProblemResolver *resolver = [database_ resolver];
2814 resolver->Clear(iterator_);
2815 resolver->Protect(iterator_);
2817 pkgCacheFile &cache([database_ cache]);
2818 cache->SetReInstall(iterator_, false);
2819 cache->MarkInstall(iterator_, false);
2821 pkgDepCache::StateCache &state((*cache)[iterator_]);
2822 if (!state.Install())
2823 cache->SetReInstall(iterator_, true);
2827 @synchronized (database_) {
2828 pkgProblemResolver *resolver = [database_ resolver];
2829 resolver->Clear(iterator_);
2830 resolver->Remove(iterator_);
2831 resolver->Protect(iterator_);
2833 pkgCacheFile &cache([database_ cache]);
2834 cache->SetReInstall(iterator_, false);
2835 cache->MarkDelete(iterator_, true);
2838 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2839 _profile(Package$isUnfilteredAndSearchedForBy)
2842 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2843 value &= [self unfiltered];
2846 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2847 value &= [self matches:query];
2854 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2855 if ([search length] == 0)
2858 _profile(Package$isUnfilteredAndSelectedForBy)
2861 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2862 value &= [self unfiltered];
2865 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2866 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2873 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2874 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2877 - (bool) isVisibleInSection:(NSString *)name {
2878 NSString *section([self section]);
2882 section == nil && [name length] == 0 ||
2883 [name isEqualToString:section]
2884 ) && [self visible];
2887 - (bool) isVisibleInSource:(Source *)source {
2888 return [self source] == source && [self visible];
2893 /* Section Class {{{ */
2894 @interface Section : NSObject {
2899 _H<NSString> localized_;
2902 - (NSComparisonResult) compareByLocalized:(Section *)section;
2903 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2904 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2905 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2906 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2907 - (NSString *) name;
2914 - (void) addToCount;
2916 - (void) setCount:(size_t)count;
2917 - (NSString *) localized;
2921 @implementation Section
2923 - (NSComparisonResult) compareByLocalized:(Section *)section {
2924 NSString *lhs(localized_);
2925 NSString *rhs([section localized]);
2927 /*if ([lhs length] != 0 && [rhs length] != 0) {
2928 unichar lhc = [lhs characterAtIndex:0];
2929 unichar rhc = [rhs characterAtIndex:0];
2931 if (isalpha(lhc) && !isalpha(rhc))
2932 return NSOrderedAscending;
2933 else if (!isalpha(lhc) && isalpha(rhc))
2934 return NSOrderedDescending;
2937 return [lhs compare:rhs options:LaxCompareOptions_];
2940 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2941 if ((self = [self initWithName:name localize:NO]) != nil) {
2942 if (localized != nil)
2943 localized_ = localized;
2947 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2948 return [self initWithName:name row:0 localize:localize];
2951 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2952 if ((self = [super init]) != nil) {
2957 localized_ = LocalizeSection(name_);
2961 /* XXX: localize the index thingees */
2962 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2963 if ((self = [super init]) != nil) {
2964 name_ = [NSString stringWithCharacters:&index length:1];
2970 - (NSString *) name {
2990 - (void) addToCount {
2994 - (void) setCount:(size_t)count {
2998 - (NSString *) localized {
3005 static NSString *Colon_;
3007 static NSString *Error_;
3008 static NSString *Warning_;
3010 class CydiaLogCleaner :
3011 public pkgArchiveCleaner
3014 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3019 /* Database Implementation {{{ */
3020 @implementation Database
3022 + (Database *) sharedInstance {
3023 static _H<Database> instance;
3024 if (instance == nil)
3025 instance = [[[Database alloc] init] autorelease];
3033 - (void) releasePackages {
3034 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3035 CFArrayRemoveAllValues(packages_);
3039 // XXX: actually implement this thing
3041 [self releasePackages];
3042 apr_pool_destroy(pool_);
3043 NSRecycleZone(zone_);
3047 - (void) _readCydia:(NSNumber *)fd {
3048 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3049 std::istream is(&ib);
3052 static Pcre finish_r("^finish:([^:]*)$");
3054 while (std::getline(is, line)) {
3055 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3057 const char *data(line.c_str());
3058 size_t size = line.size();
3059 lprintf("C:%s\n", data);
3061 if (finish_r(data, size)) {
3062 NSString *finish = finish_r[1];
3063 int index = [Finishes_ indexOfObject:finish];
3064 if (index != INT_MAX && index > Finish_)
3074 - (void) _readStatus:(NSNumber *)fd {
3075 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3076 std::istream is(&ib);
3079 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3080 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3082 while (std::getline(is, line)) {
3083 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3085 const char *data(line.c_str());
3086 size_t size(line.size());
3087 lprintf("S:%s\n", data);
3089 if (conffile_r(data, size)) {
3090 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3091 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3092 } else if (strncmp(data, "status: ", 8) == 0) {
3093 // status: <package>: {unpacked,half-configured,installed}
3094 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3095 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3096 } else if (strncmp(data, "processing: ", 12) == 0) {
3097 // processing: configure: config-test
3098 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3099 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3100 } else if (pmstatus_r(data, size)) {
3101 std::string type([pmstatus_r[1] UTF8String]);
3103 NSString *package = pmstatus_r[2];
3104 if ([package isEqualToString:@"dpkg-exec"])
3107 float percent([pmstatus_r[3] floatValue]);
3108 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3110 NSString *string = pmstatus_r[4];
3112 if (type == "pmerror") {
3113 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3114 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3115 } else if (type == "pmstatus") {
3116 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3117 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3118 } else if (type == "pmconffile")
3119 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3121 lprintf("E:unknown pmstatus\n");
3123 lprintf("E:unknown status\n");
3131 - (void) _readOutput:(NSNumber *)fd {
3132 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3133 std::istream is(&ib);
3136 while (std::getline(is, line)) {
3137 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3139 lprintf("O:%s\n", line.c_str());
3141 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3142 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3154 - (Package *) packageWithName:(NSString *)name {
3155 @synchronized (self) {
3156 if (static_cast<pkgDepCache *>(cache_) == NULL)
3158 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3159 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3163 if ((self = [super init]) != nil) {
3170 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3171 apr_pool_create(&pool_, NULL);
3173 size_t capacity(MetaFile_->active_);
3179 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3180 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3184 _assert(pipe(fds) != -1);
3187 _config->Set("APT::Keep-Fds::", cydiafd_);
3188 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3191 detachNewThreadSelector:@selector(_readCydia:)
3193 withObject:[NSNumber numberWithInt:fds[0]]
3196 _assert(pipe(fds) != -1);
3200 detachNewThreadSelector:@selector(_readStatus:)
3202 withObject:[NSNumber numberWithInt:fds[0]]
3205 _assert(pipe(fds) != -1);
3206 _assert(dup2(fds[0], 0) != -1);
3207 _assert(close(fds[0]) != -1);
3209 input_ = fdopen(fds[1], "a");
3211 _assert(pipe(fds) != -1);
3212 _assert(dup2(fds[1], 1) != -1);
3213 _assert(close(fds[1]) != -1);
3216 detachNewThreadSelector:@selector(_readOutput:)
3218 withObject:[NSNumber numberWithInt:fds[0]]
3223 - (pkgCacheFile &) cache {
3227 - (pkgDepCache::Policy *) policy {
3231 - (pkgRecords *) records {
3235 - (pkgProblemResolver *) resolver {
3239 - (pkgAcquire &) fetcher {
3243 - (pkgSourceList &) list {
3247 - (NSArray *) packages {
3248 return (NSArray *) packages_;
3251 - (NSArray *) sources {
3255 - (Source *) sourceWithKey:(NSString *)key {
3256 for (Source *source in [self sources]) {
3257 if ([[source key] isEqualToString:key])
3262 - (bool) popErrorWithTitle:(NSString *)title {
3265 while (!_error->empty()) {
3267 bool warning(!_error->PopMessage(error));
3272 size_t size(error.size());
3273 if (size == 0 || error[size - 1] != '\n')
3275 error.resize(size - 1);
3278 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3280 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3286 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3287 return [self popErrorWithTitle:title] || !success;
3290 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3291 @synchronized (self) {
3294 [self releasePackages];
3297 [sourceList_ removeAllObjects];
3317 apr_pool_clear(pool_);
3319 NSRecycleZone(zone_);
3320 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3322 int chk(creat("/tmp/cydia.chk", 0644));
3326 if (invocation != nil)
3327 [invocation invoke];
3329 NSString *title(UCLocalize("DATABASE"));
3332 OpProgress progress;
3333 while (!cache_.Open(progress, true)) { pop:
3335 bool warning(!_error->PopMessage(error));
3336 lprintf("cache_.Open():[%s]\n", error.c_str());
3338 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3339 [delegate_ repairWithSelector:@selector(configure)];
3340 else if (error == "The package lists or status file could not be parsed or opened.")
3341 [delegate_ repairWithSelector:@selector(update)];
3342 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3343 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3344 // else if (error == "Malformed Status line")
3345 // else if (error == "The list of sources could not be read.")
3347 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3357 unlink("/tmp/cydia.chk");
3359 now_ = [[NSDate date] timeIntervalSince1970];
3361 policy_ = new pkgDepCache::Policy();
3362 records_ = new pkgRecords(cache_);
3363 resolver_ = new pkgProblemResolver(cache_);
3364 fetcher_ = new pkgAcquire(&status_);
3367 list_ = new pkgSourceList();
3368 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3371 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3372 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3376 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3379 if (cache_->BrokenCount() != 0) {
3380 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3383 if (cache_->BrokenCount() != 0) {
3384 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3388 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3392 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3393 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3394 [sourceList_ addObject:object];
3396 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3397 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3398 // XXX: this could be more intelligent
3399 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3400 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3402 sourceMap_[cached->ID] = object;
3407 /*std::vector<Package *> packages;
3408 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3413 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3414 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3415 //packages.push_back(package);
3416 CFArrayAppendValue(packages_, CFRetain(package));
3420 /*if (packages.empty())
3421 packages_ = [[NSArray alloc] init];
3423 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3426 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3427 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3428 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3436 /*if (!packages.empty())
3437 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3438 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3440 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3442 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3444 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3448 size_t count(CFArrayGetCount(packages_));
3449 MetaFile_->active_ = count;
3451 for (size_t index(0); index != count; ++index)
3452 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3459 @synchronized (self) {
3461 resolver_ = new pkgProblemResolver(cache_);
3463 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3464 if (!cache_[iterator].Keep())
3465 cache_->MarkKeep(iterator, false);
3466 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3467 cache_->SetReInstall(iterator, false);
3470 - (void) configure {
3471 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3473 system([dpkg UTF8String]);
3478 // XXX: I don't remember this condition
3483 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3485 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3487 if ([self popErrorWithTitle:title])
3491 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3493 CydiaLogCleaner cleaner;
3494 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3501 fetcher_->Shutdown();
3503 pkgRecords records(cache_);
3505 lock_ = new FileFd();
3506 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3508 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3510 if ([self popErrorWithTitle:title])
3514 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3517 manager_ = (_system->CreatePM(cache_));
3518 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3525 bool substrate(RestartSubstrate_);
3526 RestartSubstrate_ = false;
3528 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3530 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3532 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3534 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3535 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3538 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3540 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3542 [self popErrorWithTitle:title];
3546 bool failed = false;
3547 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3548 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3550 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3556 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3564 RestartSubstrate_ = true;
3567 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3569 if (_error->PendingError()) {
3574 if (result == pkgPackageManager::Failed) {
3579 if (result != pkgPackageManager::Completed) {
3584 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3586 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3588 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3589 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3592 if (![before isEqualToArray:after])
3597 NSString *title(UCLocalize("UPGRADE"));
3598 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3604 [self updateWithStatus:status_];
3607 - (void) updateWithStatus:(Status &)status {
3608 NSString *title(UCLocalize("REFRESHING_DATA"));
3611 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3615 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3616 if ([self popErrorWithTitle:title])
3619 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3621 bool success(ListUpdate(status, list, PulseInterval_));
3622 if (status.WasCancelled())
3625 [self popErrorWithTitle:title forOperation:success];
3626 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3630 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3633 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3634 delegate_ = delegate;
3637 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3638 progress_ = delegate;
3639 status_.setDelegate(delegate);
3642 - (NSObject<ProgressDelegate> *) progressDelegate {
3646 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3647 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3648 return i == sourceMap_.end() ? nil : i->second;
3651 - (NSString *) mappedSectionForPointer:(const char *)section {
3652 _H<NSString> *mapped;
3654 _profile(Database$mappedSectionForPointer$Cache)
3655 mapped = §ions_[section];
3658 if (*mapped == NULL) {
3659 size_t length(strlen(section));
3660 char spaced[length + 1];
3662 _profile(Database$mappedSectionForPointer$Replace)
3663 for (size_t index(0); index != length; ++index)
3664 spaced[index] = section[index] == '_' ? ' ' : section[index];
3665 spaced[length] = '\0';
3670 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3671 string = [NSString stringWithUTF8String:spaced];
3674 _profile(Database$mappedSectionForPointer$Map)
3675 string = [SectionMap_ objectForKey:string] ?: string;
3685 static _H<NSMutableSet> Diversions_;
3687 @interface Diversion : NSObject {
3690 _H<NSString> format_;
3695 @implementation Diversion
3697 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3698 if ((self = [super init]) != nil) {
3699 pattern_ = [from UTF8String];
3705 - (NSString *) divert:(NSString *)url {
3706 return !pattern_(url) ? nil : pattern_->*format_;
3709 + (NSURL *) divertURL:(NSURL *)url {
3711 NSString *href([url absoluteString]);
3713 for (Diversion *diversion in (id) Diversions_)
3714 if (NSString *diverted = [diversion divert:href]) {
3716 NSLog(@"div: %@", diverted);
3718 url = [NSURL URLWithString:diverted];
3725 - (NSString *) key {
3729 - (NSUInteger) hash {
3733 - (BOOL) isEqual:(Diversion *)object {
3734 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3739 @interface CydiaObject : NSObject {
3740 _H<IndirectDelegate> indirect_;
3741 _transient id delegate_;
3744 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3748 @interface CydiaWebViewController : CyteWebViewController {
3749 _H<CydiaObject> cydia_;
3752 + (void) addDiversion:(Diversion *)diversion;
3756 /* Web Scripting {{{ */
3757 @implementation CydiaObject
3759 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3760 if ((self = [super init]) != nil) {
3761 indirect_ = indirect;
3765 - (void) setDelegate:(id)delegate {
3766 delegate_ = delegate;
3769 + (NSArray *) _attributeKeys {
3770 return [NSArray arrayWithObjects:
3786 - (NSArray *) attributeKeys {
3787 return [[self class] _attributeKeys];
3790 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3791 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3794 - (NSString *) version {
3798 - (NSString *) device {
3799 return [[UIDevice currentDevice] uniqueIdentifier];
3802 - (NSString *) firmware {
3803 return [[UIDevice currentDevice] systemVersion];
3806 - (NSString *) hostname {
3807 return [[UIDevice currentDevice] name];
3810 - (NSString *) idiom {
3811 return (id) Idiom_ ?: [NSNull null];
3814 - (NSString *) plmn {
3815 return (id) PLMN_ ?: [NSNull null];
3818 - (NSString *) bbsnum {
3819 return (id) BBSNum_ ?: [NSNull null];
3822 - (NSString *) ecid {
3823 return (id) ChipID_ ?: [NSNull null];
3826 - (NSString *) serial {
3827 return SerialNumber_;
3830 - (NSString *) role {
3831 return (id) Role_ ?: [NSNull null];
3834 - (NSString *) model {
3835 return [NSString stringWithUTF8String:Machine_];
3838 - (NSString *) token {
3839 return (id) Token_ ?: [NSNull null];
3842 + (NSString *) webScriptNameForSelector:(SEL)selector {
3844 else if (selector == @selector(addBridgedHost:))
3845 return @"addBridgedHost";
3846 else if (selector == @selector(addInsecureHost:))
3847 return @"addInsecureHost";
3848 else if (selector == @selector(addInternalRedirect::))
3849 return @"addInternalRedirect";
3850 else if (selector == @selector(addPipelinedHost:scheme:))
3851 return @"addPipelinedHost";
3852 else if (selector == @selector(addTokenHost:))
3853 return @"addTokenHost";
3854 else if (selector == @selector(addTrivialSource:))
3855 return @"addTrivialSource";
3856 else if (selector == @selector(close))
3858 else if (selector == @selector(du:))
3860 else if (selector == @selector(stringWithFormat:arguments:))
3862 else if (selector == @selector(getAllSources))
3863 return @"getAllSourcs";
3864 else if (selector == @selector(getKernelNumber:))
3865 return @"getKernelNumber";
3866 else if (selector == @selector(getKernelString:))
3867 return @"getKernelString";
3868 else if (selector == @selector(getInstalledPackages))
3869 return @"getInstalledPackages";
3870 else if (selector == @selector(getIORegistryEntry::))
3871 return @"getIORegistryEntry";
3872 else if (selector == @selector(getLocaleIdentifier))
3873 return @"getLocaleIdentifier";
3874 else if (selector == @selector(getPreferredLanguages))
3875 return @"getPreferredLanguages";
3876 else if (selector == @selector(getPackageById:))
3877 return @"getPackageById";
3878 else if (selector == @selector(getMetadataValue:))
3879 return @"getMetadataValue";
3880 else if (selector == @selector(getSessionValue:))
3881 return @"getSessionValue";
3882 else if (selector == @selector(installPackages:))
3883 return @"installPackages";
3884 else if (selector == @selector(localizedStringForKey:value:table:))
3886 else if (selector == @selector(popViewController:))
3887 return @"popViewController";
3888 else if (selector == @selector(refreshSources))
3889 return @"refreshSources";
3890 else if (selector == @selector(removeButton))
3891 return @"removeButton";
3892 else if (selector == @selector(setMetadataValue::))
3893 return @"setMetadataValue";
3894 else if (selector == @selector(setSessionValue::))
3895 return @"setSessionValue";
3896 else if (selector == @selector(substitutePackageNames:))
3897 return @"substitutePackageNames";
3898 else if (selector == @selector(scrollToBottom:))
3899 return @"scrollToBottom";
3900 else if (selector == @selector(setAllowsNavigationAction:))
3901 return @"setAllowsNavigationAction";
3902 else if (selector == @selector(setBadgeValue:))
3903 return @"setBadgeValue";
3904 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3905 return @"setButtonImage";
3906 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3907 return @"setButtonTitle";
3908 else if (selector == @selector(setHidesBackButton:))
3909 return @"setHidesBackButton";
3910 else if (selector == @selector(setHidesNavigationBar:))
3911 return @"setHidesNavigationBar";
3912 else if (selector == @selector(setNavigationBarStyle:))
3913 return @"setNavigationBarStyle";
3914 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3915 return @"setNavigationBarTintColor";
3916 else if (selector == @selector(setPasteboardString:))
3917 return @"setPasteboardString";
3918 else if (selector == @selector(setPasteboardURL:))
3919 return @"setPasteboardURL";
3920 else if (selector == @selector(setToken:))
3922 else if (selector == @selector(setViewportWidth:))
3923 return @"setViewportWidth";
3924 else if (selector == @selector(statfs:))
3926 else if (selector == @selector(supports:))
3928 else if (selector == @selector(unload))
3934 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3935 return [self webScriptNameForSelector:selector] == nil;
3938 - (BOOL) supports:(NSString *)feature {
3939 return [feature isEqualToString:@"window.open"];
3943 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
3946 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3947 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3950 - (NSNumber *) getKernelNumber:(NSString *)name {
3951 const char *string([name UTF8String]);
3954 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3955 return (id) [NSNull null];
3957 if (size != sizeof(int))
3958 return (id) [NSNull null];
3961 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3962 return (id) [NSNull null];
3964 return [NSNumber numberWithInt:value];
3967 - (NSString *) getKernelString:(NSString *)name {
3968 const char *string([name UTF8String]);
3971 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3972 return (id) [NSNull null];
3974 char value[size + 1];
3975 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3976 return (id) [NSNull null];
3978 // XXX: just in case you request something ludicrous
3981 return [NSString stringWithCString:value];
3984 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3985 NSObject *value(CYIOGetValue([path UTF8String], entry));
3988 if ([value isKindOfClass:[NSData class]])
3989 value = CYHex((NSData *) value);
3994 - (id) getMetadataValue:(NSString *)key {
3995 @synchronized (Values_) {
3996 return [Values_ objectForKey:key];
3999 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4000 @synchronized (Values_) {
4001 if (value == (id) [WebUndefined undefined])
4002 [Values_ removeObjectForKey:key];
4004 [Values_ setObject:value forKey:key];
4006 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4009 - (id) getSessionValue:(NSString *)key {
4010 @synchronized (SessionData_) {
4011 return [SessionData_ objectForKey:key];
4014 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4015 @synchronized (SessionData_) {
4016 if (value == (id) [WebUndefined undefined])
4017 [SessionData_ removeObjectForKey:key];
4019 [SessionData_ setObject:value forKey:key];
4022 - (void) addBridgedHost:(NSString *)host {
4023 @synchronized (HostConfig_) {
4024 [BridgedHosts_ addObject:host];
4027 - (void) addInsecureHost:(NSString *)host {
4028 @synchronized (HostConfig_) {
4029 [InsecureHosts_ addObject:host];
4032 - (void) addTokenHost:(NSString *)host {
4033 @synchronized (HostConfig_) {
4034 [TokenHosts_ addObject:host];
4037 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4038 @synchronized (HostConfig_) {
4039 if (scheme != (id) [WebUndefined undefined])
4040 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4042 [PipelinedHosts_ addObject:host];
4045 - (void) popViewController:(NSNumber *)value {
4046 if (value == (id) [WebUndefined undefined])
4047 value = [NSNumber numberWithBool:YES];
4048 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4051 - (void) addTrivialSource:(NSString *)href {
4052 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4055 - (void) refreshSources {
4056 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4059 - (NSArray *) getAllSources {
4060 return [[Database sharedInstance] sources];
4063 - (NSArray *) getInstalledPackages {
4064 Database *database([Database sharedInstance]);
4065 @synchronized (database) {
4066 NSArray *packages([database packages]);
4067 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4068 for (Package *package in packages)
4069 if (![package uninstalled])
4070 [installed addObject:package];
4074 - (Package *) getPackageById:(NSString *)id {
4075 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4079 return (Package *) [NSNull null];
4082 - (NSString *) getLocaleIdentifier {
4083 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4086 - (NSArray *) getPreferredLanguages {
4090 - (NSArray *) statfs:(NSString *)path {
4093 if (path == nil || statfs([path UTF8String], &stat) == -1)
4096 return [NSArray arrayWithObjects:
4097 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4098 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4099 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4103 - (NSNumber *) du:(NSString *)path {
4104 NSNumber *value(nil);
4107 _assert(pipe(fds) != -1);
4109 pid_t pid(ExecFork());
4111 _assert(dup2(fds[1], 1) != -1);
4112 _assert(close(fds[0]) != -1);
4113 _assert(close(fds[1]) != -1);
4114 /* XXX: this should probably not use du */
4115 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4120 _assert(close(fds[1]) != -1);
4122 if (FILE *du = fdopen(fds[0], "r")) {
4124 while (fgets(line, sizeof(line), du) != NULL) {
4125 size_t length(strlen(line));
4126 while (length != 0 && line[length - 1] == '\n')
4127 line[--length] = '\0';
4128 if (char *tab = strchr(line, '\t')) {
4130 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4135 } else _assert(close(fds[0]));
4139 if (waitpid(pid, &status, 0) == -1)
4142 else _assert(false);
4148 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4151 - (void) installPackages:(NSArray *)packages {
4152 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4155 - (NSString *) substitutePackageNames:(NSString *)message {
4156 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4157 for (size_t i(0), e([words count]); i != e; ++i) {
4158 NSString *word([words objectAtIndex:i]);
4159 if (Package *package = [[Database sharedInstance] packageWithName:word])
4160 [words replaceObjectAtIndex:i withObject:[package name]];
4163 return [words componentsJoinedByString:@" "];
4166 - (void) removeButton {
4167 [indirect_ removeButton];
4170 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4171 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4174 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4175 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4178 - (void) setBadgeValue:(id)value {
4179 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4182 - (void) setAllowsNavigationAction:(NSString *)value {
4183 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4186 - (void) setHidesBackButton:(NSString *)value {
4187 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4190 - (void) setHidesNavigationBar:(NSString *)value {
4191 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4194 - (void) setNavigationBarStyle:(NSString *)value {
4195 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4198 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4199 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4200 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4201 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4204 - (void) setPasteboardString:(NSString *)value {
4205 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4208 - (void) setPasteboardURL:(NSString *)value {
4209 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4212 - (void) _setToken:(NSString *)token {
4216 [Metadata_ removeObjectForKey:@"Token"];
4218 [Metadata_ setObject:Token_ forKey:@"Token"];
4223 - (void) setToken:(NSString *)token {
4224 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4227 - (void) scrollToBottom:(NSNumber *)animated {
4228 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4231 - (void) setViewportWidth:(float)width {
4232 [indirect_ setViewportWidthOnMainThread:width];
4235 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4236 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4237 unsigned count([arguments count]);
4239 for (unsigned i(0); i != count; ++i)
4240 values[i] = [arguments objectAtIndex:i];
4241 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4244 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4245 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4247 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4249 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4255 @interface NSURL (CydiaSecure)
4258 @implementation NSURL (CydiaSecure)
4260 - (bool) isCydiaSecure {
4261 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4264 @synchronized (HostConfig_) {
4265 if ([InsecureHosts_ containsObject:[self host]])
4274 /* Cydia Browser Controller {{{ */
4275 @implementation CydiaWebViewController
4277 - (NSURL *) navigationURL {
4278 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4281 + (void) initialize {
4282 Diversions_ = [NSMutableSet setWithCapacity:0];
4285 + (void) addDiversion:(Diversion *)diversion {
4286 [Diversions_ addObject:diversion];
4289 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4290 [super webView:view didClearWindowObject:window forFrame:frame];
4292 WebDataSource *source([frame dataSource]);
4293 NSURLResponse *response([source response]);
4294 NSURL *url([response URL]);
4295 NSString *scheme([[url scheme] lowercaseString]);
4297 bool bridged(false);
4299 @synchronized (HostConfig_) {
4300 if ([scheme isEqualToString:@"file"])
4302 else if ([scheme isEqualToString:@"https"])
4303 if ([BridgedHosts_ containsObject:[url host]])
4308 [window setValue:cydia_ forKey:@"cydia"];
4311 - (void) _setupMail:(MFMailComposeViewController *)controller {
4312 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4314 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4315 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4318 - (NSURL *) URLWithURL:(NSURL *)url {
4319 return [Diversion divertURL:url];
4322 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4323 NSURL *url([request URL]);
4324 NSString *host([url host]);
4326 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4328 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4329 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4330 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4331 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4334 @synchronized (HostConfig_) {
4335 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4338 if ([url isCydiaSecure] && token) {
4339 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4340 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4346 - (void) setDelegate:(id)delegate {
4347 [super setDelegate:delegate];
4348 [cydia_ setDelegate:delegate];
4351 - (NSString *) applicationNameForUserAgent {
4352 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4355 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4357 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4358 if (Product_ != nil)
4359 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4365 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4366 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4374 @interface NSObject (CydiaScript)
4375 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4378 @implementation NSObject (CydiaScript)
4380 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4386 @implementation NSArray (CydiaScript)
4388 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4389 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4390 for (size_t i(0), e([self count]); i != e; ++i)
4391 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4397 @implementation NSDictionary (CydiaScript)
4399 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4400 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4402 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4409 /* Confirmation Controller {{{ */
4410 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4411 if (!iterator.end())
4412 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4413 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4415 pkgCache::PkgIterator package(dep.TargetPkg());
4418 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4425 @protocol ConfirmationControllerDelegate
4426 - (void) cancelAndClear:(bool)clear;
4427 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4431 @interface ConfirmationController : CydiaWebViewController {
4432 _transient Database *database_;
4434 _H<UIAlertView> essential_;
4436 _H<NSDictionary> changes_;
4437 _H<NSMutableArray> issues_;
4438 _H<NSDictionary> sizes_;
4443 - (id) initWithDatabase:(Database *)database;
4447 @implementation ConfirmationController
4451 RestartSubstrate_ = true;
4452 [delegate_ confirmWithNavigationController:[self navigationController]];
4455 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4456 NSString *context([alert context]);
4458 if ([context isEqualToString:@"remove"]) {
4459 if (button == [alert cancelButtonIndex])
4460 [self dismissModalViewControllerAnimated:YES];
4461 else if (button == [alert firstOtherButtonIndex]) {
4465 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4466 } else if ([context isEqualToString:@"unable"]) {
4467 [self dismissModalViewControllerAnimated:YES];
4468 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4470 [super alertView:alert clickedButtonAtIndex:button];
4474 - (void) _doContinue {
4475 [self dismissModalViewControllerAnimated:YES];
4476 [delegate_ cancelAndClear:NO];
4479 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4480 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4484 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4485 [super webView:view didClearWindowObject:window forFrame:frame];
4487 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4488 (id) changes_, @"changes",
4489 (id) issues_, @"issues",
4490 (id) sizes_, @"sizes",
4492 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4495 - (id) initWithDatabase:(Database *)database {
4496 if ((self = [super init]) != nil) {
4497 database_ = database;
4499 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4500 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4501 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4502 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4503 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4507 pkgCacheFile &cache([database_ cache]);
4508 NSArray *packages([database_ packages]);
4509 pkgDepCache::Policy *policy([database_ policy]);
4511 issues_ = [NSMutableArray arrayWithCapacity:4];
4513 for (Package *package in packages) {
4514 pkgCache::PkgIterator iterator([package iterator]);
4515 NSString *name([package id]);
4517 if ([package broken]) {
4518 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4520 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4522 reasons, @"reasons",
4525 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4529 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4530 pkgCache::DepIterator start;
4531 pkgCache::DepIterator end;
4532 dep.GlobOr(start, end); // ++dep
4534 if (!cache->IsImportantDep(end))
4536 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4539 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4541 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4542 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4543 clauses, @"clauses",
4547 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4549 pkgCache::PkgIterator target(start.TargetPkg());
4550 if (target->ProvidesList != 0)
4551 reason = @"missing";
4553 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4555 reason = @"installed";
4556 installed = [NSString stringWithUTF8String:ver.VerStr()];
4557 } else if (!cache[target].CandidateVerIter(cache).end())
4558 reason = @"uninstalled";
4559 else if (target->ProvidesList == 0)
4560 reason = @"uninstallable";
4562 reason = @"virtual";
4565 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4566 [NSString stringWithUTF8String:start.CompType()], @"operator",
4567 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4570 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4571 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4572 version, @"version",
4574 installed, @"installed",
4577 // yes, seriously. (wtf?)
4585 pkgDepCache::StateCache &state(cache[iterator]);
4587 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4589 if (state.NewInstall())
4590 [installs addObject:name];
4591 // XXX: else if (state.Install())
4592 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4593 [reinstalls addObject:name];
4594 // XXX: move before previous if
4595 else if (state.Upgrade())
4596 [upgrades addObject:name];
4597 else if (state.Downgrade())
4598 [downgrades addObject:name];
4599 else if (!state.Delete())
4600 // XXX: _assert(state.Keep());
4602 else if (special_r(name))
4603 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4604 [NSNull null], @"package",
4605 [NSArray arrayWithObjects:
4606 [NSDictionary dictionaryWithObjectsAndKeys:
4607 @"Conflicts", @"relationship",
4608 [NSArray arrayWithObjects:
4609 [NSDictionary dictionaryWithObjectsAndKeys:
4611 [NSNull null], @"version",
4612 @"installed", @"reason",
4619 if ([package essential])
4621 [removes addObject:name];
4624 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4625 substrate_ |= DepSubstrate(iterator.CurrentVer());
4630 else if (Advanced_) {
4631 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4633 essential_ = [[[UIAlertView alloc]
4634 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4635 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4637 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4639 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4643 [essential_ setContext:@"remove"];
4645 essential_ = [[[UIAlertView alloc]
4646 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4647 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4649 cancelButtonTitle:UCLocalize("OKAY")
4650 otherButtonTitles:nil
4653 [essential_ setContext:@"unable"];
4656 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4657 installs, @"installs",
4658 reinstalls, @"reinstalls",
4659 upgrades, @"upgrades",
4660 downgrades, @"downgrades",
4661 removes, @"removes",
4664 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4665 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4666 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4669 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4673 - (UIBarButtonItem *) leftButton {
4674 return [[[UIBarButtonItem alloc]
4675 initWithTitle:UCLocalize("CANCEL")
4676 style:UIBarButtonItemStylePlain
4678 action:@selector(cancelButtonClicked)
4683 - (void) applyRightButton {
4684 if ([issues_ count] == 0 && ![self isLoading])
4685 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4686 initWithTitle:UCLocalize("CONFIRM")
4687 style:UIBarButtonItemStyleDone
4689 action:@selector(confirmButtonClicked)
4692 [[self navigationItem] setRightBarButtonItem:nil];
4696 - (void) cancelButtonClicked {
4697 [self dismissModalViewControllerAnimated:YES];
4698 [delegate_ cancelAndClear:YES];
4702 - (void) confirmButtonClicked {
4703 if (essential_ != nil)
4713 /* Progress Data {{{ */
4714 @interface CydiaProgressData : NSObject {
4715 _transient id delegate_;
4724 _H<NSMutableArray> events_;
4725 _H<NSString> title_;
4727 _H<NSString> status_;
4728 _H<NSString> finish_;
4733 @implementation CydiaProgressData
4735 + (NSArray *) _attributeKeys {
4736 return [NSArray arrayWithObjects:
4748 - (NSArray *) attributeKeys {
4749 return [[self class] _attributeKeys];
4752 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4753 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4757 if ((self = [super init]) != nil) {
4758 events_ = [NSMutableArray arrayWithCapacity:32];
4762 - (void) setDelegate:(id)delegate {
4763 delegate_ = delegate;
4766 - (void) setPercent:(float)value {
4770 - (NSNumber *) percent {
4771 return [NSNumber numberWithFloat:percent_];
4774 - (void) setCurrent:(float)value {
4778 - (NSNumber *) current {
4779 return [NSNumber numberWithFloat:current_];
4782 - (void) setTotal:(float)value {
4786 - (NSNumber *) total {
4787 return [NSNumber numberWithFloat:total_];
4790 - (void) setSpeed:(float)value {
4794 - (NSNumber *) speed {
4795 return [NSNumber numberWithFloat:speed_];
4798 - (NSArray *) events {
4802 - (void) removeAllEvents {
4803 [events_ removeAllObjects];
4806 - (void) addEvent:(CydiaProgressEvent *)event {
4807 [events_ addObject:event];
4810 - (void) setTitle:(NSString *)text {
4814 - (NSString *) title {
4818 - (void) setFinish:(NSString *)text {
4822 - (NSString *) finish {
4823 return (id) finish_ ?: [NSNull null];
4826 - (void) setRunning:(bool)running {
4830 - (NSNumber *) running {
4831 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4836 /* Progress Controller {{{ */
4837 @interface ProgressController : CydiaWebViewController <
4840 _transient Database *database_;
4841 _H<CydiaProgressData, 1> progress_;
4845 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4847 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4849 - (void) setTitle:(NSString *)title;
4850 - (void) setCancellable:(bool)cancellable;
4854 @implementation ProgressController
4857 [database_ setProgressDelegate:nil];
4861 - (UIBarButtonItem *) leftButton {
4862 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4863 initWithTitle:UCLocalize("CANCEL")
4864 style:UIBarButtonItemStylePlain
4866 action:@selector(cancel)
4867 ] autorelease] : nil;
4870 - (void) updateCancel {
4871 [super applyLeftButton];
4874 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4875 if ((self = [super init]) != nil) {
4876 database_ = database;
4877 delegate_ = delegate;
4879 [database_ setProgressDelegate:self];
4881 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4882 [progress_ setDelegate:self];
4884 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4886 [scroller_ setBackgroundColor:[UIColor blackColor]];
4888 [[self navigationItem] setHidesBackButton:YES];
4890 [self updateCancel];
4894 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4895 [super webView:view didClearWindowObject:window forFrame:frame];
4896 [window setValue:progress_ forKey:@"cydiaProgress"];
4899 - (void) updateProgress {
4900 [self dispatchEvent:@"CydiaProgressUpdate"];
4903 - (void) viewWillAppear:(BOOL)animated {
4904 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4905 [super viewWillAppear:animated];
4909 UpdateExternalStatus(0);
4916 [delegate_ terminateWithSuccess];
4917 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4918 [delegate_ suspendWithAnimation:YES];
4920 [delegate_ suspend];*/
4932 system("/usr/bin/sbreload");
4938 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4939 SBReboot(SBSSpringBoardServerPort());
4941 reboot2(RB_AUTOBOOT);
4948 - (void) setTitle:(NSString *)title {
4949 [progress_ setTitle:title];
4950 [self updateProgress];
4953 - (UIBarButtonItem *) rightButton {
4954 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4955 initWithTitle:UCLocalize("CLOSE")
4956 style:UIBarButtonItemStylePlain
4958 action:@selector(close)
4962 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4963 UpdateExternalStatus(1);
4965 [progress_ setRunning:true];
4966 [self setTitle:title];
4967 // implicit updateProgress
4969 SHA1SumValue notifyconf; {
4971 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4974 MMap mmap(file, MMap::ReadOnly);
4976 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4977 notifyconf = sha1.Result();
4981 SHA1SumValue springlist; {
4983 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4986 MMap mmap(file, MMap::ReadOnly);
4988 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4989 springlist = sha1.Result();
4993 if (invocation != nil) {
4994 [invocation yieldToSelector:@selector(invoke)];
4995 [self setTitle:@"COMPLETE"];
5000 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5003 MMap mmap(file, MMap::ReadOnly);
5005 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5006 if (!(notifyconf == sha1.Result()))
5013 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5016 MMap mmap(file, MMap::ReadOnly);
5018 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5019 if (!(springlist == sha1.Result()))
5025 if (RestartSubstrate_)
5029 RestartSubstrate_ = false;
5032 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5033 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5034 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5035 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5036 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5040 system("su -c /usr/bin/uicache mobile");
5043 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5045 [progress_ setRunning:false];
5046 [self updateProgress];
5048 [self applyRightButton];
5051 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5052 [progress_ addEvent:event];
5053 [self updateProgress];
5056 - (bool) isProgressCancelled {
5057 return cancel_ == 2;
5062 [self updateCancel];
5065 - (void) setCancellable:(bool)cancellable {
5066 unsigned cancel(cancel_);
5070 else if (cancel_ == 0)
5073 if (cancel != cancel_)
5074 [self updateCancel];
5077 - (void) setProgressCancellable:(NSNumber *)cancellable {
5078 [self setCancellable:[cancellable boolValue]];
5081 - (void) setProgressPercent:(NSNumber *)percent {
5082 [progress_ setPercent:[percent floatValue]];
5083 [self updateProgress];
5086 - (void) setProgressStatus:(NSDictionary *)status {
5087 if (status == nil) {
5088 [progress_ setCurrent:0];
5089 [progress_ setTotal:0];
5090 [progress_ setSpeed:0];
5092 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5094 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5095 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5096 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5099 [self updateProgress];
5105 /* Package Cell {{{ */
5106 @interface PackageCell : CyteTableViewCell <
5107 CyteTableViewCellDelegate
5111 _H<NSString> description_;
5113 _H<NSString> source_;
5115 _H<Package> package_;
5116 _H<UIImage> placard_;
5120 - (PackageCell *) init;
5121 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5123 - (void) drawContentRect:(CGRect)rect;
5127 @implementation PackageCell
5129 - (PackageCell *) init {
5130 CGRect frame(CGRectMake(0, 0, 320, 74));
5131 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5132 UIView *content([self contentView]);
5133 CGRect bounds([content bounds]);
5135 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5136 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5137 [content addSubview:content_];
5139 [content_ setDelegate:self];
5140 [content_ setOpaque:YES];
5144 - (NSString *) accessibilityLabel {
5145 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5148 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5149 summarized_ = summary;
5161 Source *source = [package source];
5163 icon_ = [package icon];
5165 if (NSString *name = [package name])
5166 name_ = [NSString stringWithString:name];
5168 NSString *description(nil);
5170 if (description == nil && IsWildcat_)
5171 description = [package longDescription];
5172 if (description == nil)
5173 description = [package shortDescription];
5175 if (description != nil)
5176 description_ = [NSString stringWithString:description];
5178 commercial_ = [package isCommercial];
5182 NSString *label = nil;
5183 bool trusted = false;
5185 if (source != nil) {
5186 label = [source label];
5187 trusted = [source trusted];
5188 } else if ([[package id] isEqualToString:@"firmware"])
5189 label = UCLocalize("APPLE");
5191 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5193 NSString *from(label);
5195 NSString *section = [package simpleSection];
5196 if (section != nil && ![section isEqualToString:label]) {
5197 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5198 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5201 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5203 if (NSString *purpose = [package primaryPurpose])
5204 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5209 if (NSString *mode = [package_ mode]) {
5210 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5211 color = RemovingColor_;
5212 //placard = @"removing";
5214 color = InstallingColor_;
5215 //placard = @"installing";
5218 // XXX: the removing/installing placards are not @2x
5221 color = [UIColor whiteColor];
5223 if ([package installed] != nil)
5224 placard = @"installed";
5229 [content_ setBackgroundColor:color];
5232 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5234 [self setNeedsDisplay];
5235 [content_ setNeedsDisplay];
5238 - (void) drawSummaryContentRect:(CGRect)rect {
5239 bool highlighted(highlighted_);
5240 float width([self bounds].size.width);
5244 rect.size = [(UIImage *) icon_ size];
5246 rect.size.width /= 4;
5247 rect.size.height /= 4;
5249 rect.origin.x = 14 - rect.size.width / 4;
5250 rect.origin.y = 14 - rect.size.height / 4;
5252 [icon_ drawInRect:rect];
5255 if (badge_ != nil) {
5257 rect.size = [(UIImage *) badge_ size];
5259 rect.size.width /= 4;
5260 rect.size.height /= 4;
5262 rect.origin.x = 20 - rect.size.width / 4;
5263 rect.origin.y = 20 - rect.size.height / 4;
5265 [badge_ drawInRect:rect];
5272 UISetColor(commercial_ ? Purple_ : Black_);
5273 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5275 if (placard_ != nil)
5276 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5279 - (void) drawNormalContentRect:(CGRect)rect {
5280 bool highlighted(highlighted_);
5281 float width([self bounds].size.width);
5285 rect.size = [(UIImage *) icon_ size];
5287 rect.size.width /= 2;
5288 rect.size.height /= 2;
5290 rect.origin.x = 25 - rect.size.width / 2;
5291 rect.origin.y = 25 - rect.size.height / 2;
5293 [icon_ drawInRect:rect];
5296 if (badge_ != nil) {
5298 rect.size = [(UIImage *) badge_ size];
5300 rect.size.width /= 2;
5301 rect.size.height /= 2;
5303 rect.origin.x = 36 - rect.size.width / 2;
5304 rect.origin.y = 36 - rect.size.height / 2;
5306 [badge_ drawInRect:rect];
5313 UISetColor(commercial_ ? Purple_ : Black_);
5314 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5315 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5318 UISetColor(commercial_ ? Purplish_ : Gray_);
5319 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5321 if (placard_ != nil)
5322 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5325 - (void) drawContentRect:(CGRect)rect {
5327 [self drawSummaryContentRect:rect];
5329 [self drawNormalContentRect:rect];
5334 /* Section Cell {{{ */
5335 @interface SectionCell : CyteTableViewCell <
5336 CyteTableViewCellDelegate
5338 _H<NSString> basic_;
5339 _H<NSString> section_;
5341 _H<NSString> count_;
5343 _H<UISwitch> switch_;
5347 - (void) setSection:(Section *)section editing:(BOOL)editing;
5351 @implementation SectionCell
5353 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5354 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5355 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5356 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5357 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5359 UIView *content([self contentView]);
5360 CGRect bounds([content bounds]);
5362 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5363 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5364 [content addSubview:content_];
5365 [content_ setBackgroundColor:[UIColor whiteColor]];
5367 [content_ setDelegate:self];
5371 - (void) onSwitch:(id)sender {
5372 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5373 if (metadata == nil) {
5374 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5375 [Sections_ setObject:metadata forKey:basic_];
5378 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5382 - (void) setSection:(Section *)section editing:(BOOL)editing {
5383 if (editing != editing_) {
5385 [switch_ removeFromSuperview];
5387 [self addSubview:switch_];
5396 if (section == nil) {
5397 name_ = UCLocalize("ALL_PACKAGES");
5400 basic_ = [section name];
5401 section_ = [section localized];
5403 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5404 count_ = [NSString stringWithFormat:@"%d", [section count]];
5407 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5410 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5411 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5413 [content_ setNeedsDisplay];
5416 - (void) setFrame:(CGRect)frame {
5417 [super setFrame:frame];
5419 CGRect rect([switch_ frame]);
5420 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5423 - (NSString *) accessibilityLabel {
5427 - (void) drawContentRect:(CGRect)rect {
5428 bool highlighted(highlighted_ && !editing_);
5430 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5435 float width(rect.size.width);
5441 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5443 CGSize size = [count_ sizeWithFont:Font14_];
5447 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5453 /* File Table {{{ */
5454 @interface FileTable : CyteViewController <
5455 UITableViewDataSource,
5458 _transient Database *database_;
5459 _H<Package> package_;
5461 _H<NSMutableArray> files_;
5462 _H<UITableView, 2> list_;
5465 - (id) initWithDatabase:(Database *)database;
5466 - (void) setPackage:(Package *)package;
5470 @implementation FileTable
5472 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5473 return files_ == nil ? 0 : [files_ count];
5476 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5480 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5481 static NSString *reuseIdentifier = @"Cell";
5483 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5485 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5486 [cell setFont:[UIFont systemFontOfSize:16]];
5488 [cell setText:[files_ objectAtIndex:indexPath.row]];
5489 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5494 - (NSURL *) navigationURL {
5495 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5499 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5501 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5502 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5503 [list_ setRowHeight:24.0f];
5504 [(UITableView *) list_ setDataSource:self];
5505 [list_ setDelegate:self];
5506 [[self view] addSubview:list_];
5509 - (void) viewDidLoad {
5510 [super viewDidLoad];
5512 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5515 - (void) releaseSubviews {
5518 [super releaseSubviews];
5521 - (id) initWithDatabase:(Database *)database {
5522 if ((self = [super init]) != nil) {
5523 database_ = database;
5525 files_ = [NSMutableArray arrayWithCapacity:32];
5529 - (void) setPackage:(Package *)package {
5533 [files_ removeAllObjects];
5535 if (package != nil) {
5537 name_ = [package id];
5539 if (NSArray *files = [package files])
5540 [files_ addObjectsFromArray:files];
5542 if ([files_ count] != 0) {
5543 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5544 [files_ removeObjectAtIndex:0];
5545 [files_ sortUsingSelector:@selector(compareByPath:)];
5547 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5548 [stack addObject:@"/"];
5550 for (int i(0), e([files_ count]); i != e; ++i) {
5551 NSString *file = [files_ objectAtIndex:i];
5552 while (![file hasPrefix:[stack lastObject]])
5553 [stack removeLastObject];
5554 NSString *directory = [stack lastObject];
5555 [stack addObject:[file stringByAppendingString:@"/"]];
5556 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5557 ([stack count] - 2) * 3, "",
5558 [file substringFromIndex:[directory length]]
5567 - (void) reloadData {
5570 [self setPackage:[database_ packageWithName:name_]];
5575 /* Package Controller {{{ */
5576 @interface CYPackageController : CydiaWebViewController <
5577 UIActionSheetDelegate
5579 _transient Database *database_;
5580 _H<Package> package_;
5583 _H<NSMutableArray> buttons_;
5584 _H<UIBarButtonItem> button_;
5587 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5591 @implementation CYPackageController
5593 - (NSURL *) navigationURL {
5594 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5597 /* XXX: this is not safe at all... localization of /fail/ */
5598 - (void) _clickButtonWithName:(NSString *)name {
5599 if ([name isEqualToString:UCLocalize("CLEAR")])
5600 [delegate_ clearPackage:package_];
5601 else if ([name isEqualToString:UCLocalize("INSTALL")])
5602 [delegate_ installPackage:package_];
5603 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5604 [delegate_ installPackage:package_];
5605 else if ([name isEqualToString:UCLocalize("REMOVE")])
5606 [delegate_ removePackage:package_];
5607 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5608 [delegate_ installPackage:package_];
5609 else _assert(false);
5612 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5613 NSString *context([sheet context]);
5615 if ([context isEqualToString:@"modify"]) {
5616 if (button != [sheet cancelButtonIndex]) {
5617 NSString *buttonName = [buttons_ objectAtIndex:button];
5618 [self _clickButtonWithName:buttonName];
5621 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5625 - (bool) _allowJavaScriptPanel {
5630 - (void) _customButtonClicked {
5631 int count([buttons_ count]);
5636 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5638 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5639 [buttons addObjectsFromArray:buttons_];
5641 UIActionSheet *sheet = [[[UIActionSheet alloc]
5644 cancelButtonTitle:nil
5645 destructiveButtonTitle:nil
5646 otherButtonTitles:nil
5649 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5651 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5652 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5654 [sheet setContext:@"modify"];
5656 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5660 // We don't want to allow non-commercial packages to do custom things to the install button,
5661 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5662 - (void) customButtonClicked {
5664 [super customButtonClicked];
5666 [self _customButtonClicked];
5669 - (void) reloadButtonClicked {
5670 // Don't reload a commerical package by tapping the loading button,
5671 // but if it's not an Install button, we should forward it on.
5672 if (![package_ uninstalled])
5673 [self _customButtonClicked];
5676 - (void) applyLoadingTitle {
5677 // Don't show "Loading" as the title. Ever.
5680 - (UIBarButtonItem *) rightButton {
5685 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5686 if ((self = [super init]) != nil) {
5687 database_ = database;
5688 buttons_ = [NSMutableArray arrayWithCapacity:4];
5689 name_ = [NSString stringWithString:name];
5690 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5694 - (void) reloadData {
5697 package_ = [database_ packageWithName:name_];
5699 [buttons_ removeAllObjects];
5701 if (package_ != nil) {
5702 [(Package *) package_ parse];
5704 commercial_ = [package_ isCommercial];
5706 if ([package_ mode] != nil)
5707 [buttons_ addObject:UCLocalize("CLEAR")];
5708 if ([package_ source] == nil);
5709 else if ([package_ upgradableAndEssential:NO])
5710 [buttons_ addObject:UCLocalize("UPGRADE")];
5711 else if ([package_ uninstalled])
5712 [buttons_ addObject:UCLocalize("INSTALL")];
5714 [buttons_ addObject:UCLocalize("REINSTALL")];
5715 if (![package_ uninstalled])
5716 [buttons_ addObject:UCLocalize("REMOVE")];
5720 switch ([buttons_ count]) {
5721 case 0: title = nil; break;
5722 case 1: title = [buttons_ objectAtIndex:0]; break;
5723 default: title = UCLocalize("MODIFY"); break;
5726 button_ = [[[UIBarButtonItem alloc]
5728 style:UIBarButtonItemStylePlain
5730 action:@selector(customButtonClicked)
5734 - (bool) isLoading {
5735 return commercial_ ? [super isLoading] : false;
5741 /* Package List Controller {{{ */
5742 @interface PackageListController : CyteViewController <
5743 UITableViewDataSource,
5746 _transient Database *database_;
5748 _H<NSArray> packages_;
5749 _H<NSMutableArray> sections_;
5750 _H<UITableView, 2> list_;
5751 _H<NSMutableArray> index_;
5752 _H<NSMutableDictionary> indices_;
5753 _H<NSString> title_;
5754 unsigned reloading_;
5757 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5758 - (void) setDelegate:(id)delegate;
5759 - (void) resetCursor;
5764 @implementation PackageListController
5766 - (bool) isSummarized {
5770 - (bool) showsSections {
5774 - (void) deselectWithAnimation:(BOOL)animated {
5775 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5778 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5779 CGRect base = [[self view] bounds];
5780 base.size.height -= bounds.size.height;
5781 base.origin = [list_ frame].origin;
5783 [UIView beginAnimations:nil context:NULL];
5784 [UIView setAnimationBeginsFromCurrentState:YES];
5785 [UIView setAnimationCurve:curve];
5786 [UIView setAnimationDuration:duration];
5787 [list_ setFrame:base];
5788 [UIView commitAnimations];
5791 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5792 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5795 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5796 [self resizeForKeyboardBounds:bounds duration:0];
5799 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5800 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5801 *curve = UIViewAnimationCurveEaseInOut;
5803 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5805 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5808 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5811 - (void) keyboardWillShow:(NSNotification *)notification {
5814 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5815 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5817 NSTimeInterval duration;
5818 UIViewAnimationCurve curve;
5819 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5821 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);
5822 UIViewController *base = self;
5823 while ([base parentViewController] != nil)
5824 base = [base parentViewController];
5825 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5826 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5828 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5829 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5831 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5834 - (void) keyboardWillHide:(NSNotification *)notification {
5835 NSTimeInterval duration;
5836 UIViewAnimationCurve curve;
5837 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5839 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5842 - (void) viewWillAppear:(BOOL)animated {
5843 [super viewWillAppear:animated];
5845 [self resizeForKeyboardBounds:CGRectZero];
5846 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5847 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5850 - (void) viewWillDisappear:(BOOL)animated {
5851 [super viewWillDisappear:animated];
5853 [self resizeForKeyboardBounds:CGRectZero];
5854 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5855 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5858 - (void) viewDidAppear:(BOOL)animated {
5859 [super viewDidAppear:animated];
5860 [self deselectWithAnimation:animated];
5863 - (void) didSelectPackage:(Package *)package {
5864 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5865 [view setDelegate:delegate_];
5866 [[self navigationController] pushViewController:view animated:YES];
5869 #if TryIndexedCollation
5870 + (BOOL) hasIndexedCollation {
5871 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5875 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5876 NSInteger count([sections_ count]);
5877 return count == 0 ? 1 : count;
5880 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5881 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5883 return [[sections_ objectAtIndex:section] name];
5886 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5887 if ([sections_ count] == 0)
5889 return [[sections_ objectAtIndex:section] count];
5892 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5893 @synchronized (database_) {
5894 if ([database_ era] != era_)
5897 Section *section([sections_ objectAtIndex:[path section]]);
5898 NSInteger row([path row]);
5899 Package *package([packages_ objectAtIndex:([section row] + row)]);
5900 return [[package retain] autorelease];
5903 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5904 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5906 cell = [[[PackageCell alloc] init] autorelease];
5907 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5911 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5912 Package *package([self packageAtIndexPath:path]);
5913 package = [database_ packageWithName:[package id]];
5914 [self didSelectPackage:package];
5917 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5918 if (![self showsSections])
5924 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5925 #if TryIndexedCollation
5926 if ([[self class] hasIndexedCollation]) {
5927 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5934 - (void) updateHeight {
5935 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5938 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5939 if ((self = [super init]) != nil) {
5940 database_ = database;
5941 title_ = [title copy];
5942 [[self navigationItem] setTitle:title_];
5944 #if TryIndexedCollation
5945 if ([[self class] hasIndexedCollation])
5946 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5949 index_ = [NSMutableArray arrayWithCapacity:32];
5951 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5953 packages_ = [NSArray array];
5954 sections_ = [NSMutableArray arrayWithCapacity:16];
5959 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5961 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5962 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5963 [[self view] addSubview:list_];
5965 // XXX: is 20 the most optimal number here?
5966 [list_ setSectionIndexMinimumDisplayRowCount:20];
5968 [(UITableView *) list_ setDataSource:self];
5969 [list_ setDelegate:self];
5971 [self updateHeight];
5974 - (void) releaseSubviews {
5977 [super releaseSubviews];
5980 - (void) setDelegate:(id)delegate {
5981 delegate_ = delegate;
5984 - (bool) shouldYield {
5988 - (bool) shouldBlock {
5992 - (NSMutableArray *) _reloadPackages {
5993 @synchronized (database_) {
5994 era_ = [database_ era];
5995 NSArray *packages([database_ packages]);
5997 return [NSMutableArray arrayWithArray:packages];
6000 - (void) _reloadData {
6001 if (reloading_ != 0) {
6008 if ([self shouldYield]) {
6012 if (![self shouldBlock])
6015 hud = [delegate_ addProgressHUD];
6016 [hud setText:UCLocalize("LOADING")];
6020 packages = [self yieldToSelector:@selector(_reloadPackages)];
6023 [delegate_ removeProgressHUD:hud];
6024 } while (reloading_ == 2);
6028 packages = [self _reloadPackages];
6031 packages_ = packages;
6033 [indices_ removeAllObjects];
6034 [sections_ removeAllObjects];
6036 Section *section = nil;
6038 #if TryIndexedCollation
6039 if ([[self class] hasIndexedCollation]) {
6040 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6041 NSArray *titles = [collation sectionIndexTitles];
6044 _profile(PackageTable$reloadData$Section)
6045 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6049 _profile(PackageTable$reloadData$Section$Package)
6050 package = [packages_ objectAtIndex:offset];
6051 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6054 while (secidx < index) {
6057 _profile(PackageTable$reloadData$Section$Allocate)
6058 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6061 _profile(PackageTable$reloadData$Section$Add)
6062 [sections_ addObject:section];
6066 [section addToCount];
6072 [index_ removeAllObjects];
6074 bool sectioned([self showsSections]);
6076 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6077 [sections_ addObject:section];
6080 _profile(PackageTable$reloadData$Section)
6081 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6085 _profile(PackageTable$reloadData$Section$Package)
6086 package = [packages_ objectAtIndex:offset];
6087 index = [package index];
6090 if (sectioned && (section == nil || [section index] != index)) {
6091 _profile(PackageTable$reloadData$Section$Allocate)
6092 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6095 [index_ addObject:[section name]];
6096 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6098 _profile(PackageTable$reloadData$Section$Add)
6099 [sections_ addObject:section];
6103 [section addToCount];
6108 [self updateHeight];
6110 _profile(PackageTable$reloadData$List)
6111 [(UITableView *) list_ setDataSource:self];
6116 - (void) reloadData {
6118 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6121 - (void) resetCursor {
6122 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6125 - (void) clearData {
6126 [self updateHeight];
6128 [list_ setDataSource:nil];
6136 /* Filtered Package List Controller {{{ */
6137 @interface FilteredPackageListController : PackageListController {
6140 _H<NSObject> object_;
6143 - (void) setObject:(id)object;
6144 - (void) setObject:(id)object forFilter:(SEL)filter;
6147 - (void) setFilter:(SEL)filter;
6149 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6153 @implementation FilteredPackageListController
6159 - (void) setFilter:(SEL)filter {
6160 @synchronized (self) {
6163 /* XXX: this is an unsafe optimization of doomy hell */
6164 Method method(class_getInstanceMethod([Package class], filter));
6165 _assert(method != NULL);
6166 imp_ = method_getImplementation(method);
6167 _assert(imp_ != NULL);
6170 - (void) setObject:(id)object {
6171 @synchronized (self) {
6175 - (void) setObject:(id)object forFilter:(SEL)filter {
6176 @synchronized (self) {
6177 [self setFilter:filter];
6178 [self setObject:object];
6181 - (NSMutableArray *) _reloadPackages {
6182 @synchronized (database_) {
6183 era_ = [database_ era];
6184 NSArray *packages([database_ packages]);
6186 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6190 _H<NSObject> object;
6192 @synchronized (self) {
6198 _profile(PackageTable$reloadData$Filter)
6199 for (Package *package in packages)
6200 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6201 [filtered addObject:package];
6207 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6208 if ((self = [super initWithDatabase:database title:title]) != nil) {
6209 [self setFilter:filter];
6210 [self setObject:object];
6217 /* Home Controller {{{ */
6218 @interface HomeController : CydiaWebViewController {
6223 @implementation HomeController
6226 if ((self = [super init]) != nil) {
6227 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6232 - (NSURL *) navigationURL {
6233 return [NSURL URLWithString:@"cydia://home"];
6236 - (void) aboutButtonClicked {
6237 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6239 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6240 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6241 [alert setCancelButtonIndex:0];
6244 @"Copyright \u00a9 2008-2011\n"
6247 "Jay Freeman (saurik)\n"
6248 "saurik@saurik.com\n"
6249 "http://www.saurik.com/"
6255 - (UIBarButtonItem *) leftButton {
6256 return [[[UIBarButtonItem alloc]
6257 initWithTitle:UCLocalize("ABOUT")
6258 style:UIBarButtonItemStylePlain
6260 action:@selector(aboutButtonClicked)
6266 /* Manage Controller {{{ */
6267 @interface ManageController : CydiaWebViewController {
6270 - (void) queueStatusDidChange;
6274 @implementation ManageController
6277 if ((self = [super init]) != nil) {
6278 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6282 - (NSURL *) navigationURL {
6283 return [NSURL URLWithString:@"cydia://manage"];
6286 - (UIBarButtonItem *) leftButton {
6287 return [[[UIBarButtonItem alloc]
6288 initWithTitle:UCLocalize("SETTINGS")
6289 style:UIBarButtonItemStylePlain
6291 action:@selector(settingsButtonClicked)
6295 - (void) settingsButtonClicked {
6296 [delegate_ showSettings];
6299 - (void) queueButtonClicked {
6303 - (UIBarButtonItem *) customButton {
6304 return Queuing_ ? [[[UIBarButtonItem alloc]
6305 initWithTitle:UCLocalize("QUEUE")
6306 style:UIBarButtonItemStyleDone
6308 action:@selector(queueButtonClicked)
6309 ] autorelease] : [super customButton];
6312 - (void) queueStatusDidChange {
6313 [self applyRightButton];
6316 - (bool) isLoading {
6317 return !Queuing_ && [super isLoading];
6323 /* Refresh Bar {{{ */
6324 @interface RefreshBar : UINavigationBar {
6325 _H<UIProgressIndicator> indicator_;
6326 _H<UITextLabel> prompt_;
6327 _H<UIProgressBar> progress_;
6328 _H<UINavigationButton> cancel_;
6333 @implementation RefreshBar
6335 - (void) positionViews {
6336 CGRect frame = [cancel_ frame];
6337 frame.size = [cancel_ sizeThatFits:frame.size];
6338 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6339 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6340 [cancel_ setFrame:frame];
6342 CGSize prgsize = {75, 100};
6344 [self frame].size.width - prgsize.width - 10,
6345 ([self frame].size.height - prgsize.height) / 2
6347 [progress_ setFrame:prgrect];
6349 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6350 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6351 CGRect indrect = {{indoffset, indoffset}, indsize};
6352 [indicator_ setFrame:indrect];
6354 CGSize prmsize = {215, indsize.height + 4};
6356 indoffset * 2 + indsize.width,
6357 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6359 [prompt_ setFrame:prmrect];
6362 - (void) setFrame:(CGRect)frame {
6363 [super setFrame:frame];
6364 [self positionViews];
6367 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6368 if ((self = [super initWithFrame:frame]) != nil) {
6369 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6371 [self setBarStyle:UIBarStyleBlack];
6373 UIBarStyle barstyle([self _barStyle:NO]);
6374 bool ugly(barstyle == UIBarStyleDefault);
6376 UIProgressIndicatorStyle style = ugly ?
6377 UIProgressIndicatorStyleMediumBrown :
6378 UIProgressIndicatorStyleMediumWhite;
6380 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6381 [(UIProgressIndicator *) indicator_ setStyle:style];
6382 [indicator_ startAnimation];
6383 [self addSubview:indicator_];
6385 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6386 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6387 [prompt_ setBackgroundColor:[UIColor clearColor]];
6388 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6389 [self addSubview:prompt_];
6391 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6392 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6393 [(UIProgressBar *) progress_ setStyle:0];
6394 [self addSubview:progress_];
6396 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6397 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6398 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6399 [cancel_ setBarStyle:barstyle];
6401 [self positionViews];
6405 - (void) setCancellable:(bool)cancellable {
6407 [self addSubview:cancel_];
6409 [cancel_ removeFromSuperview];
6413 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6414 [progress_ setProgress:0];
6418 [self setCancellable:NO];
6421 - (void) setPrompt:(NSString *)prompt {
6422 [prompt_ setText:prompt];
6425 - (void) setProgress:(float)progress {
6426 [progress_ setProgress:progress];
6432 /* Cydia Navigation Controller Interface {{{ */
6433 @interface UINavigationController (Cydia)
6435 - (NSArray *) navigationURLCollection;
6436 - (void) unloadData;
6441 /* Cydia Tab Bar Controller {{{ */
6442 @interface CYTabBarController : UITabBarController <
6443 UITabBarControllerDelegate,
6446 _transient Database *database_;
6447 _H<RefreshBar, 1> refreshbar_;
6451 // XXX: ok, "updatedelegate_"?...
6452 _transient NSObject<CydiaDelegate> *updatedelegate_;
6454 _H<UIViewController> remembered_;
6455 _transient UIViewController *transient_;
6458 - (NSArray *) navigationURLCollection;
6459 - (void) dropBar:(BOOL)animated;
6460 - (void) beginUpdate;
6461 - (void) raiseBar:(BOOL)animated;
6463 - (void) unloadData;
6467 @implementation CYTabBarController
6469 - (void) setUnselectedViewController:(UIViewController *)transient {
6470 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6471 if (transient != nil) {
6472 if (transient_ == nil)
6473 remembered_ = [controllers objectAtIndex:0];
6474 transient_ = transient;
6475 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6476 [controllers replaceObjectAtIndex:0 withObject:transient_];
6477 [self setSelectedIndex:0];
6478 [self setViewControllers:controllers];
6479 [self concealTabBarSelection];
6480 } else if (remembered_ != nil) {
6481 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6482 transient_ = transient;
6483 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6485 [self setViewControllers:controllers];
6486 [self revealTabBarSelection];
6490 - (UIViewController *) unselectedViewController {
6494 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6495 if ([self unselectedViewController])
6496 [self setUnselectedViewController:nil];
6499 - (NSArray *) navigationURLCollection {
6500 NSMutableArray *items([NSMutableArray array]);
6502 // XXX: Should this deal with transient view controllers?
6503 for (id navigation in [self viewControllers]) {
6504 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6506 [items addObject:stack];
6512 - (void) unloadData {
6515 for (UINavigationController *controller in [self viewControllers])
6516 [controller unloadData];
6518 if (UIViewController *selected = [self selectedViewController])
6519 [selected reloadData];
6521 if (UIViewController *unselected = [self unselectedViewController]) {
6522 [unselected unloadData];
6523 [unselected reloadData];
6528 [[NSNotificationCenter defaultCenter] removeObserver:self];
6533 - (id) initWithDatabase:(Database *)database {
6534 if ((self = [super init]) != nil) {
6535 database_ = database;
6536 [self setDelegate:self];
6538 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6539 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6541 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6545 - (void) setUpdate:(NSDate *)date {
6549 - (void) beginUpdate {
6550 [(RefreshBar *) refreshbar_ start];
6553 [updatedelegate_ retainNetworkActivityIndicator];
6557 detachNewThreadSelector:@selector(performUpdate)
6563 - (void) performUpdate {
6564 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6567 status.setDelegate(self);
6568 [database_ updateWithStatus:status];
6571 performSelectorOnMainThread:@selector(completeUpdate)
6579 - (void) stopUpdateWithSelector:(SEL)selector {
6581 [updatedelegate_ releaseNetworkActivityIndicator];
6583 [self raiseBar:YES];
6586 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6589 - (void) completeUpdate {
6592 [self stopUpdateWithSelector:@selector(reloadData)];
6595 - (void) cancelUpdate {
6596 [self stopUpdateWithSelector:@selector(updateData)];
6599 - (void) cancelPressed {
6600 [self cancelUpdate];
6607 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6608 [refreshbar_ setPrompt:[event compoundMessage]];
6611 - (bool) isProgressCancelled {
6615 - (void) setProgressCancellable:(NSNumber *)cancellable {
6616 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6619 - (void) setProgressPercent:(NSNumber *)percent {
6620 [refreshbar_ setProgress:[percent floatValue]];
6623 - (void) setProgressStatus:(NSDictionary *)status {
6625 [self setProgressPercent:[status objectForKey:@"Percent"]];
6628 - (void) setUpdateDelegate:(id)delegate {
6629 updatedelegate_ = delegate;
6632 - (UIView *) transitionView {
6633 if ([self respondsToSelector:@selector(_transitionView)])
6634 return [self _transitionView];
6636 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6639 - (void) dropBar:(BOOL)animated {
6644 UIView *transition([self transitionView]);
6645 [[self view] addSubview:refreshbar_];
6647 CGRect barframe([refreshbar_ frame]);
6649 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6650 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6652 barframe.origin.y = 0;
6654 [refreshbar_ setFrame:barframe];
6657 [UIView beginAnimations:nil context:NULL];
6659 CGRect viewframe = [transition frame];
6660 viewframe.origin.y += barframe.size.height;
6661 viewframe.size.height -= barframe.size.height;
6662 [transition setFrame:viewframe];
6665 [UIView commitAnimations];
6667 // Ensure bar has the proper width for our view, it might have changed
6668 barframe.size.width = viewframe.size.width;
6669 [refreshbar_ setFrame:barframe];
6672 - (void) raiseBar:(BOOL)animated {
6677 UIView *transition([self transitionView]);
6678 [refreshbar_ removeFromSuperview];
6680 CGRect barframe([refreshbar_ frame]);
6683 [UIView beginAnimations:nil context:NULL];
6685 CGRect viewframe = [transition frame];
6686 viewframe.origin.y -= barframe.size.height;
6687 viewframe.size.height += barframe.size.height;
6688 [transition setFrame:viewframe];
6691 [UIView commitAnimations];
6694 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6695 bool dropped(dropped_);
6700 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6706 - (void) statusBarFrameChanged:(NSNotification *)notification {
6716 /* Cydia Navigation Controller Implementation {{{ */
6717 @implementation UINavigationController (Cydia)
6719 - (NSArray *) navigationURLCollection {
6720 NSMutableArray *stack([NSMutableArray array]);
6722 for (CyteViewController *controller in [self viewControllers]) {
6723 NSString *url = [[controller navigationURL] absoluteString];
6725 [stack addObject:url];
6731 - (void) reloadData {
6734 if (UIViewController *visible = [self visibleViewController])
6735 [visible reloadData];
6738 - (void) unloadData {
6739 for (CyteViewController *page in [self viewControllers])
6748 /* Cydia:// Protocol {{{ */
6749 @interface CydiaURLProtocol : NSURLProtocol {
6754 @implementation CydiaURLProtocol
6756 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6757 NSURL *url([request URL]);
6761 NSString *scheme([[url scheme] lowercaseString]);
6762 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6764 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6770 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6774 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6775 id<NSURLProtocolClient> client([self client]);
6777 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6779 NSData *data(UIImagePNGRepresentation(icon));
6781 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6782 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6783 [client URLProtocol:self didLoadData:data];
6784 [client URLProtocolDidFinishLoading:self];
6788 - (void) startLoading {
6789 id<NSURLProtocolClient> client([self client]);
6790 NSURLRequest *request([self request]);
6792 NSURL *url([request URL]);
6793 NSString *href([url absoluteString]);
6794 NSString *scheme([[url scheme] lowercaseString]);
6798 if ([scheme isEqualToString:@"cydia"])
6799 path = [href substringFromIndex:8];
6800 else if ([scheme isEqualToString:@"about"])
6801 path = [href substringFromIndex:12];
6802 else _assert(false);
6804 NSRange slash([path rangeOfString:@"/"]);
6807 if (slash.location == NSNotFound) {
6811 command = [path substringToIndex:slash.location];
6812 path = [path substringFromIndex:(slash.location + 1)];
6815 Database *database([Database sharedInstance]);
6817 if ([command isEqualToString:@"package-icon"]) {
6820 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6821 Package *package([database packageWithName:path]);
6825 UIImage *icon([package icon]);
6826 [self _returnPNGWithImage:icon forRequest:request];
6827 } else if ([command isEqualToString:@"source-icon"]) {
6830 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6831 NSString *source(Simplify(path));
6832 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6834 icon = [UIImage applicationImageNamed:@"unknown.png"];
6835 [self _returnPNGWithImage:icon forRequest:request];
6836 } else if ([command isEqualToString:@"uikit-image"]) {
6839 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6840 UIImage *icon(_UIImageWithName(path));
6841 [self _returnPNGWithImage:icon forRequest:request];
6842 } else if ([command isEqualToString:@"section-icon"]) {
6845 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6846 NSString *section(Simplify(path));
6847 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6849 icon = [UIImage applicationImageNamed:@"unknown.png"];
6850 [self _returnPNGWithImage:icon forRequest:request];
6852 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6856 - (void) stopLoading {
6862 /* Section Controller {{{ */
6863 @interface SectionController : FilteredPackageListController {
6864 _H<NSString> section_;
6867 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6871 @implementation SectionController
6873 - (NSURL *) navigationURL {
6874 NSString *name = section_;
6878 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6881 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6884 title = UCLocalize("ALL_PACKAGES");
6885 else if (![name isEqual:@""])
6886 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6888 title = UCLocalize("NO_SECTION");
6890 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6897 /* Sections Controller {{{ */
6898 @interface SectionsController : CyteViewController <
6899 UITableViewDataSource,
6902 _transient Database *database_;
6903 _H<NSMutableArray> sections_;
6904 _H<NSMutableArray> filtered_;
6905 _H<UITableView, 2> list_;
6908 - (id) initWithDatabase:(Database *)database;
6909 - (void) editButtonClicked;
6913 @implementation SectionsController
6915 - (NSURL *) navigationURL {
6916 return [NSURL URLWithString:@"cydia://sections"];
6919 - (void) updateNavigationItem {
6920 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6921 if ([sections_ count] == 0) {
6922 [[self navigationItem] setRightBarButtonItem:nil];
6924 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6925 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6927 action:@selector(editButtonClicked)
6928 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6932 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6933 [super setEditing:editing animated:animated];
6938 [delegate_ updateData];
6940 [self updateNavigationItem];
6943 - (void) viewDidAppear:(BOOL)animated {
6944 [super viewDidAppear:animated];
6945 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6948 - (void) viewWillDisappear:(BOOL)animated {
6949 [super viewWillDisappear:animated];
6950 if ([self isEditing]) [self setEditing:NO];
6953 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6954 Section *section = nil;
6955 int index = [indexPath row];
6956 if (![self isEditing]) {
6959 section = [filtered_ objectAtIndex:index];
6961 section = [sections_ objectAtIndex:index];
6966 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6967 if ([self isEditing])
6968 return [sections_ count];
6970 return [filtered_ count] + 1;
6973 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6977 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6978 static NSString *reuseIdentifier = @"SectionCell";
6980 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6982 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6984 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6989 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6990 if ([self isEditing])
6993 Section *section = [self sectionAtIndexPath:indexPath];
6995 SectionController *controller = [[[SectionController alloc]
6996 initWithDatabase:database_
6997 section:[section name]
6999 [controller setDelegate:delegate_];
7001 [[self navigationController] pushViewController:controller animated:YES];
7005 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7007 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7008 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7009 [list_ setRowHeight:45.0f];
7010 [(UITableView *) list_ setDataSource:self];
7011 [list_ setDelegate:self];
7012 [[self view] addSubview:list_];
7015 - (void) viewDidLoad {
7016 [super viewDidLoad];
7018 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7021 - (void) releaseSubviews {
7024 [super releaseSubviews];
7027 - (id) initWithDatabase:(Database *)database {
7028 if ((self = [super init]) != nil) {
7029 database_ = database;
7031 sections_ = [NSMutableArray arrayWithCapacity:16];
7032 filtered_ = [NSMutableArray arrayWithCapacity:16];
7036 - (void) reloadData {
7039 NSArray *packages = [database_ packages];
7041 [sections_ removeAllObjects];
7042 [filtered_ removeAllObjects];
7044 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7047 for (Package *package in packages) {
7048 NSString *name([package section]);
7049 NSString *key(name == nil ? @"" : name);
7053 _profile(SectionsView$reloadData$Section)
7054 section = [sections objectForKey:key];
7055 if (section == nil) {
7056 _profile(SectionsView$reloadData$Section$Allocate)
7057 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7058 [sections setObject:section forKey:key];
7063 [section addToCount];
7065 _profile(SectionsView$reloadData$Filter)
7066 if (![package valid] || ![package visible])
7074 [sections_ addObjectsFromArray:[sections allValues]];
7076 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7078 for (Section *section in (id) sections_) {
7079 size_t count([section row]);
7083 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7084 [section setCount:count];
7085 [filtered_ addObject:section];
7088 [self updateNavigationItem];
7093 - (void) editButtonClicked {
7094 [self setEditing:![self isEditing] animated:YES];
7100 /* Changes Controller {{{ */
7101 @interface ChangesController : CyteViewController <
7102 UITableViewDataSource,
7105 _transient Database *database_;
7107 _H<NSArray> packages_;
7108 _H<NSMutableArray> sections_;
7109 _H<UITableView, 2> list_;
7113 - (id) initWithDatabase:(Database *)database;
7117 @implementation ChangesController
7119 - (NSURL *) navigationURL {
7120 return [NSURL URLWithString:@"cydia://changes"];
7123 - (void) viewDidAppear:(BOOL)animated {
7124 [super viewDidAppear:animated];
7125 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7128 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7129 NSInteger count([sections_ count]);
7130 return count == 0 ? 1 : count;
7133 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7134 if ([sections_ count] == 0)
7136 return [[sections_ objectAtIndex:section] name];
7139 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7140 if ([sections_ count] == 0)
7142 return [[sections_ objectAtIndex:section] count];
7145 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7146 @synchronized (database_) {
7147 if ([database_ era] != era_)
7150 NSUInteger sectionIndex([path section]);
7151 if (sectionIndex >= [sections_ count])
7153 Section *section([sections_ objectAtIndex:sectionIndex]);
7154 NSInteger row([path row]);
7155 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7158 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7159 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7161 cell = [[[PackageCell alloc] init] autorelease];
7162 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7166 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7167 Package *package([self packageAtIndexPath:path]);
7168 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7169 [view setDelegate:delegate_];
7170 [[self navigationController] pushViewController:view animated:YES];
7174 - (void) refreshButtonClicked {
7175 [delegate_ beginUpdate];
7176 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7179 - (void) upgradeButtonClicked {
7180 [delegate_ distUpgrade];
7181 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7185 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7187 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7188 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7189 [list_ setRowHeight:73];
7190 [(UITableView *) list_ setDataSource:self];
7191 [list_ setDelegate:self];
7192 [[self view] addSubview:list_];
7195 - (void) viewDidLoad {
7196 [super viewDidLoad];
7198 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7201 - (void) releaseSubviews {
7204 [super releaseSubviews];
7207 - (id) initWithDatabase:(Database *)database {
7208 if ((self = [super init]) != nil) {
7209 database_ = database;
7211 packages_ = [NSArray array];
7212 sections_ = [NSMutableArray arrayWithCapacity:16];
7216 - (NSMutableArray *) _reloadPackages {
7217 @synchronized (database_) {
7218 era_ = [database_ era];
7219 NSArray *packages([database_ packages]);
7221 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7224 _profile(ChangesController$_reloadPackages$Filter)
7225 for (Package *package in packages)
7226 if ([package upgradableAndEssential:YES] || [package visible])
7227 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7230 _profile(ChangesController$_reloadPackages$radixSort)
7231 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7238 - (void) _reloadData {
7243 UIProgressHUD *hud([delegate_ addProgressHUD]);
7244 [hud setText:UCLocalize("LOADING")];
7245 //NSLog(@"HUD:%@::%@", delegate_, hud);
7246 packages = [self yieldToSelector:@selector(_reloadPackages)];
7247 [delegate_ removeProgressHUD:hud];
7249 packages = [self _reloadPackages];
7252 @synchronized (database_) {
7253 if (era_ != [database_ era])
7256 packages_ = packages;
7257 [sections_ removeAllObjects];
7259 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7260 Section *ignored = nil;
7261 Section *section = nil;
7265 bool unseens = false;
7267 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7269 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7270 Package *package = [packages_ objectAtIndex:offset];
7272 BOOL uae = [package upgradableAndEssential:YES];
7276 time_t seen([package seen]);
7278 if (section == nil || last != seen) {
7282 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7285 _profile(ChangesController$reloadData$Allocate)
7286 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7287 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7288 [sections_ addObject:section];
7292 [section addToCount];
7293 } else if ([package ignored]) {
7294 if (ignored == nil) {
7295 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7297 [ignored addToCount];
7300 [upgradable addToCount];
7305 CFRelease(formatter);
7308 Section *last = [sections_ lastObject];
7309 size_t count = [last count];
7310 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7311 [sections_ removeLastObject];
7314 if ([ignored count] != 0)
7315 [sections_ insertObject:ignored atIndex:0];
7317 [sections_ insertObject:upgradable atIndex:0];
7321 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7322 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7323 style:UIBarButtonItemStylePlain
7325 action:@selector(upgradeButtonClicked)
7326 ] autorelease]) animated:YES];
7328 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7329 initWithTitle:UCLocalize("REFRESH")
7330 style:UIBarButtonItemStylePlain
7332 action:@selector(refreshButtonClicked)
7333 ] autorelease]) animated:YES];
7338 - (void) reloadData {
7340 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7345 /* Search Controller {{{ */
7346 @interface SearchController : FilteredPackageListController <
7349 _H<UISearchBar, 1> search_;
7353 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7354 - (void) reloadData;
7358 @implementation SearchController
7360 - (NSURL *) navigationURL {
7361 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7362 return [NSURL URLWithString:@"cydia://search"];
7364 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7367 - (void) useSearch {
7368 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7373 - (void) viewWillAppear:(BOOL)animated {
7374 [super viewWillAppear:animated];
7376 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7380 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7381 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7386 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7387 [search_ resignFirstResponder];
7391 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7392 [search_ setText:@""];
7393 [self searchBarButtonClicked:searchBar];
7396 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7397 [self searchBarButtonClicked:searchBar];
7400 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7401 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7405 - (bool) shouldYield {
7409 - (bool) shouldBlock {
7410 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7413 - (bool) isSummarized {
7414 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7417 - (bool) showsSections {
7421 - (NSMutableArray *) _reloadPackages {
7422 NSMutableArray *packages([super _reloadPackages]);
7423 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7424 [packages radixSortUsingSelector:@selector(rank)];
7428 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7429 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7430 search_ = [[[UISearchBar alloc] init] autorelease];
7431 [search_ setDelegate:self];
7434 [search_ setText:query];
7438 - (void) viewDidAppear:(BOOL)animated {
7439 [super viewDidAppear:animated];
7441 if (!searchloaded_) {
7442 searchloaded_ = YES;
7443 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7444 [search_ layoutSubviews];
7445 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7447 UITextField *textField;
7448 if ([search_ respondsToSelector:@selector(searchField)])
7449 textField = [search_ searchField];
7451 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7453 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7454 [textField setEnablesReturnKeyAutomatically:NO];
7455 [[self navigationItem] setTitleView:textField];
7459 - (void) reloadData {
7460 id object([search_ text]);
7461 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7462 object = [object componentsSeparatedByString:@" "];
7464 [self setObject:object];
7470 - (void) didSelectPackage:(Package *)package {
7471 [search_ resignFirstResponder];
7472 [super didSelectPackage:package];
7477 /* Package Settings Controller {{{ */
7478 @interface PackageSettingsController : CyteViewController <
7479 UITableViewDataSource,
7482 _transient Database *database_;
7484 _H<Package> package_;
7485 _H<UITableView, 2> table_;
7486 _H<UISwitch> subscribedSwitch_;
7487 _H<UISwitch> ignoredSwitch_;
7488 _H<UITableViewCell> subscribedCell_;
7489 _H<UITableViewCell> ignoredCell_;
7492 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7496 @implementation PackageSettingsController
7498 - (NSURL *) navigationURL {
7499 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7502 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7503 if (package_ == nil)
7506 if ([package_ installed] == nil)
7512 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7513 if (package_ == nil)
7516 // both sections contain just one item right now.
7520 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7524 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7526 return UCLocalize("SHOW_ALL_CHANGES_EX");
7528 return UCLocalize("IGNORE_UPGRADES_EX");
7531 - (void) onSubscribed:(id)control {
7532 bool value([control isOn]);
7533 if (package_ == nil)
7535 if ([package_ setSubscribed:value])
7536 [delegate_ updateData];
7539 - (void) _updateIgnored {
7540 const char *package([name_ UTF8String]);
7541 bool on([ignoredSwitch_ isOn]);
7543 pid_t pid(ExecFork());
7545 FILE *dpkg(popen("dpkg --set-selections", "w"));
7546 fwrite(package, strlen(package), 1, dpkg);
7549 fwrite(" hold\n", 6, 1, dpkg);
7551 fwrite(" install\n", 9, 1, dpkg);
7561 int result(waitpid(pid, &status, 0));
7564 _assert(result == pid);
7570 - (void) onIgnored:(id)control {
7571 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7572 [invocation setTarget:self];
7573 [invocation setSelector:@selector(_updateIgnored)];
7575 [delegate_ reloadDataWithInvocation:invocation];
7578 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7579 if (package_ == nil)
7582 switch ([indexPath section]) {
7583 case 0: return subscribedCell_;
7584 case 1: return ignoredCell_;
7593 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7595 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7596 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7597 [(UITableView *) table_ setDataSource:self];
7598 [table_ setDelegate:self];
7599 [[self view] addSubview:table_];
7601 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7602 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7603 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7605 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7606 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7607 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7609 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7610 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7611 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7612 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7614 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7615 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7616 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7617 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7620 - (void) viewDidLoad {
7621 [super viewDidLoad];
7623 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7626 - (void) releaseSubviews {
7628 subscribedCell_ = nil;
7630 ignoredSwitch_ = nil;
7631 subscribedSwitch_ = nil;
7633 [super releaseSubviews];
7636 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7637 if ((self = [super init]) != nil) {
7638 database_ = database;
7643 - (void) reloadData {
7646 package_ = [database_ packageWithName:name_];
7648 if (package_ != nil) {
7649 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7650 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7651 } // XXX: what now, G?
7653 [table_ reloadData];
7659 /* Installed Controller {{{ */
7660 @interface InstalledController : FilteredPackageListController {
7664 - (id) initWithDatabase:(Database *)database;
7666 - (void) updateRoleButton;
7667 - (void) queueStatusDidChange;
7671 @implementation InstalledController
7673 - (NSURL *) navigationURL {
7674 return [NSURL URLWithString:@"cydia://installed"];
7677 - (id) initWithDatabase:(Database *)database {
7678 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7679 [self updateRoleButton];
7680 [self queueStatusDidChange];
7685 - (void) queueButtonClicked {
7690 - (void) queueStatusDidChange {
7694 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7695 initWithTitle:UCLocalize("QUEUE")
7696 style:UIBarButtonItemStyleDone
7698 action:@selector(queueButtonClicked)
7701 [[self navigationItem] setLeftBarButtonItem:nil];
7707 - (void) updateRoleButton {
7708 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7709 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7710 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7711 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7713 action:@selector(roleButtonClicked)
7717 - (void) roleButtonClicked {
7718 [self setObject:[NSNumber numberWithBool:expert_]];
7722 [self updateRoleButton];
7728 /* Source Cell {{{ */
7729 @interface SourceCell : CyteTableViewCell <
7730 CyteTableViewCellDelegate
7733 _H<NSString> origin_;
7734 _H<NSString> label_;
7737 - (void) setSource:(Source *)source;
7741 @implementation SourceCell
7743 - (void) _setImage:(UIImage *)image {
7745 [content_ setNeedsDisplay];
7748 - (void) _setSource:(Source *)source {
7749 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7751 if (NSString *base = [source base])
7752 if ([base length] != 0) {
7753 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7755 if (NSData *data = [NSURLConnection
7756 sendSynchronousRequest:[NSURLRequest
7758 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7762 returningResponse:NULL
7765 if (UIImage *image = [UIImage imageWithData:data])
7766 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7772 - (void) setSource:(Source *)source {
7773 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7775 origin_ = [source name];
7776 label_ = [source uri];
7778 [content_ setNeedsDisplay];
7780 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7783 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7784 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7785 UIView *content([self contentView]);
7786 CGRect bounds([content bounds]);
7788 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7789 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7790 [content_ setBackgroundColor:[UIColor whiteColor]];
7791 [content addSubview:content_];
7793 [content_ setDelegate:self];
7794 [content_ setOpaque:YES];
7798 - (NSString *) accessibilityLabel {
7802 - (void) drawContentRect:(CGRect)rect {
7803 bool highlighted(highlighted_);
7804 float width(rect.size.width);
7807 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7814 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7818 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7823 /* Source Controller {{{ */
7824 @interface SourceController : FilteredPackageListController {
7825 _transient Source *source_;
7829 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7833 @implementation SourceController
7835 - (NSURL *) navigationURL {
7836 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7839 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7840 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7842 key_ = [source key];
7846 - (void) reloadData {
7847 source_ = [database_ sourceWithKey:key_];
7848 key_ = [source_ key];
7849 [self setObject:source_];
7851 [[self navigationItem] setTitle:[source_ label]];
7858 /* Sources Controller {{{ */
7859 @interface SourcesController : CyteViewController <
7860 UITableViewDataSource,
7863 _transient Database *database_;
7864 _H<UITableView, 2> list_;
7865 _H<NSMutableArray> sources_;
7869 _H<UIProgressHUD> hud_;
7872 //NSURLConnection *installer_;
7873 NSURLConnection *trivial_;
7874 NSURLConnection *trivial_bz2_;
7875 NSURLConnection *trivial_gz_;
7876 //NSURLConnection *automatic_;
7881 - (id) initWithDatabase:(Database *)database;
7882 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7886 @implementation SourcesController
7888 - (void) _releaseConnection:(NSURLConnection *)connection {
7889 if (connection != nil) {
7890 [connection cancel];
7891 //[connection setDelegate:nil];
7892 [connection release];
7897 //[self _releaseConnection:installer_];
7898 [self _releaseConnection:trivial_];
7899 [self _releaseConnection:trivial_gz_];
7900 [self _releaseConnection:trivial_bz2_];
7901 //[self _releaseConnection:automatic_];
7906 - (NSURL *) navigationURL {
7907 return [NSURL URLWithString:@"cydia://sources"];
7910 - (void) viewDidAppear:(BOOL)animated {
7911 [super viewDidAppear:animated];
7912 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7915 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7916 return offset_ == 0 ? 1 : 2;
7919 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7920 switch (section + (offset_ == 0 ? 1 : 0)) {
7921 case 0: return UCLocalize("ENTERED_BY_USER");
7922 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7928 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7929 int count = [sources_ count];
7931 case 0: return (offset_ == 0 ? count : offset_);
7932 case 1: return count - offset_;
7938 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7940 switch (indexPath.section) {
7941 case 0: idx = indexPath.row; break;
7942 case 1: idx = indexPath.row + offset_; break;
7946 return [sources_ objectAtIndex:idx];
7949 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7950 static NSString *cellIdentifier = @"SourceCell";
7952 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7953 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7954 [cell setSource:[self sourceAtIndexPath:indexPath]];
7955 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7960 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7961 Source *source = [self sourceAtIndexPath:indexPath];
7963 SourceController *controller = [[[SourceController alloc]
7964 initWithDatabase:database_
7968 [controller setDelegate:delegate_];
7970 [[self navigationController] pushViewController:controller animated:YES];
7973 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7974 Source *source = [self sourceAtIndexPath:indexPath];
7975 return [source record] != nil;
7978 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7979 if (editingStyle == UITableViewCellEditingStyleDelete) {
7980 Source *source = [self sourceAtIndexPath:indexPath];
7981 [Sources_ removeObjectForKey:[source key]];
7982 [delegate_ syncData];
7987 [delegate_ addTrivialSource:href_];
7988 [delegate_ syncData];
7991 - (NSString *) getWarning {
7992 NSString *href(href_);
7993 NSRange colon([href rangeOfString:@"://"]);
7994 if (colon.location != NSNotFound)
7995 href = [href substringFromIndex:(colon.location + 3)];
7996 href = [href stringByAddingPercentEscapes];
7997 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7998 href = [href stringByCachingURLWithCurrentCDN];
8000 NSURL *url([NSURL URLWithString:href]);
8002 NSStringEncoding encoding;
8003 NSError *error(nil);
8005 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8006 return [warning length] == 0 ? nil : warning;
8010 - (void) _endConnection:(NSURLConnection *)connection {
8011 // XXX: the memory management in this method is horribly awkward
8013 NSURLConnection **field = NULL;
8014 if (connection == trivial_)
8016 else if (connection == trivial_bz2_)
8017 field = &trivial_bz2_;
8018 else if (connection == trivial_gz_)
8019 field = &trivial_gz_;
8020 _assert(field != NULL);
8021 [connection release];
8026 trivial_bz2_ == nil &&
8029 [delegate_ releaseNetworkActivityIndicator];
8031 [delegate_ removeProgressHUD:hud_];
8037 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8040 UIAlertView *alert = [[[UIAlertView alloc]
8041 initWithTitle:UCLocalize("SOURCE_WARNING")
8044 cancelButtonTitle:UCLocalize("CANCEL")
8046 UCLocalize("ADD_ANYWAY"),
8050 [alert setContext:@"warning"];
8051 [alert setNumberOfRows:1];
8055 } else if (error_ != nil) {
8056 UIAlertView *alert = [[[UIAlertView alloc]
8057 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8058 message:[error_ localizedDescription]
8060 cancelButtonTitle:UCLocalize("OK")
8061 otherButtonTitles:nil
8064 [alert setContext:@"urlerror"];
8067 UIAlertView *alert = [[[UIAlertView alloc]
8068 initWithTitle:UCLocalize("NOT_REPOSITORY")
8069 message:UCLocalize("NOT_REPOSITORY_EX")
8071 cancelButtonTitle:UCLocalize("OK")
8072 otherButtonTitles:nil
8075 [alert setContext:@"trivial"];
8084 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8085 switch ([response statusCode]) {
8091 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8092 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8094 [self _endConnection:connection];
8097 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8098 [self _endConnection:connection];
8101 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8102 NSURL *url([NSURL URLWithString:href]);
8104 NSMutableURLRequest *request = [NSMutableURLRequest
8106 cachePolicy:NSURLRequestUseProtocolCachePolicy
8107 timeoutInterval:120.0
8110 [request setHTTPMethod:method];
8112 if (Machine_ != NULL)
8113 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8115 if ([url isCydiaSecure]) {
8116 if (UniqueID_ != nil)
8117 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8120 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8123 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8124 NSString *context([alert context]);
8126 if ([context isEqualToString:@"source"]) {
8129 NSString *href = [[alert textField] text];
8131 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8133 if (![href hasSuffix:@"/"])
8134 href_ = [href stringByAppendingString:@"/"];
8138 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8139 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8140 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8141 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8145 // XXX: this is stupid
8146 hud_ = [delegate_ addProgressHUD];
8147 [hud_ setText:UCLocalize("VERIFYING_URL")];
8148 [delegate_ retainNetworkActivityIndicator];
8157 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8158 } else if ([context isEqualToString:@"trivial"])
8159 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8160 else if ([context isEqualToString:@"urlerror"])
8161 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8162 else if ([context isEqualToString:@"warning"]) {
8176 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8181 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8183 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8184 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8185 [list_ setRowHeight:56];
8186 [(UITableView *) list_ setDataSource:self];
8187 [list_ setDelegate:self];
8188 [[self view] addSubview:list_];
8191 - (void) viewDidLoad {
8192 [super viewDidLoad];
8194 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8195 [self updateButtonsForEditingStatus:NO animated:NO];
8198 - (void) releaseSubviews {
8201 [super releaseSubviews];
8204 - (id) initWithDatabase:(Database *)database {
8205 if ((self = [super init]) != nil) {
8206 database_ = database;
8207 sources_ = [NSMutableArray arrayWithCapacity:16];
8211 - (void) reloadData {
8215 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8218 [sources_ removeAllObjects];
8219 [sources_ addObjectsFromArray:[database_ sources]];
8221 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8224 int count([sources_ count]);
8226 for (int i = 0; i != count; i++) {
8227 if ([[sources_ objectAtIndex:i] record] == nil)
8232 [list_ setEditing:NO];
8233 [self updateButtonsForEditingStatus:NO animated:NO];
8237 - (void) showAddSourcePrompt {
8238 UIAlertView *alert = [[[UIAlertView alloc]
8239 initWithTitle:UCLocalize("ENTER_APT_URL")
8242 cancelButtonTitle:UCLocalize("CANCEL")
8244 UCLocalize("ADD_SOURCE"),
8248 [alert setContext:@"source"];
8250 [alert setNumberOfRows:1];
8251 [alert addTextFieldWithValue:@"http://" label:@""];
8253 UITextInputTraits *traits = [[alert textField] textInputTraits];
8254 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8255 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8256 [traits setKeyboardType:UIKeyboardTypeURL];
8257 // XXX: UIReturnKeyDone
8258 [traits setReturnKeyType:UIReturnKeyNext];
8263 - (void) addButtonClicked {
8264 [self showAddSourcePrompt];
8267 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8268 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8269 initWithTitle:UCLocalize("ADD")
8270 style:UIBarButtonItemStylePlain
8272 action:@selector(addButtonClicked)
8273 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8275 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8276 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8277 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8279 action:@selector(editButtonClicked)
8280 ] autorelease] animated:animated];
8282 if (IsWildcat_ && !editing)
8283 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8284 initWithTitle:UCLocalize("SETTINGS")
8285 style:UIBarButtonItemStylePlain
8287 action:@selector(settingsButtonClicked)
8291 - (void) settingsButtonClicked {
8292 [delegate_ showSettings];
8295 - (void) editButtonClicked {
8296 [list_ setEditing:![list_ isEditing] animated:YES];
8298 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8304 /* Settings Controller {{{ */
8305 @interface SettingsController : CyteViewController <
8306 UITableViewDataSource,
8309 _transient Database *database_;
8310 // XXX: ok, "roledelegate_"?...
8311 _transient id roledelegate_;
8312 _H<UITableView, 2> table_;
8313 _H<UISegmentedControl> segment_;
8314 _H<UIView> container_;
8317 - (void) showDoneButton;
8318 - (void) resizeSegmentedControl;
8322 @implementation SettingsController
8325 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8327 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8328 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8329 [table_ setDelegate:self];
8330 [(UITableView *) table_ setDataSource:self];
8331 [[self view] addSubview:table_];
8333 NSArray *items = [NSArray arrayWithObjects:
8335 UCLocalize("HACKER"),
8336 UCLocalize("DEVELOPER"),
8338 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8339 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8340 [container_ addSubview:segment_];
8343 - (void) viewDidLoad {
8344 [super viewDidLoad];
8346 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8349 if ([Role_ isEqualToString:@"User"]) index = 0;
8350 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8351 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8353 [segment_ setSelectedSegmentIndex:index];
8354 [self showDoneButton];
8357 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8358 [self resizeSegmentedControl];
8361 - (void) releaseSubviews {
8366 [super releaseSubviews];
8369 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8370 if ((self = [super init]) != nil) {
8371 database_ = database;
8372 roledelegate_ = delegate;
8376 - (void) resizeSegmentedControl {
8377 CGFloat width = [[self view] frame].size.width;
8378 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8381 - (void) viewWillAppear:(BOOL)animated {
8382 [super viewWillAppear:animated];
8384 [self resizeSegmentedControl];
8387 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8388 [self resizeSegmentedControl];
8391 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8392 [self resizeSegmentedControl];
8396 NSString *role(nil);
8398 switch ([segment_ selectedSegmentIndex]) {
8399 case 0: role = @"User"; break;
8400 case 1: role = @"Hacker"; break;
8401 case 2: role = @"Developer"; break;
8406 if (![role isEqualToString:Role_]) {
8407 bool rolling(Role_ == nil);
8410 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8414 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8418 [roledelegate_ loadData];
8420 [roledelegate_ updateData];
8424 - (void) segmentChanged:(UISegmentedControl *)control {
8425 [self showDoneButton];
8428 - (void) saveAndClose {
8431 [[self navigationItem] setRightBarButtonItem:nil];
8432 [[self navigationController] dismissModalViewControllerAnimated:YES];
8435 - (void) doneButtonClicked {
8436 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8437 [spinner startAnimating];
8438 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8439 [[self navigationItem] setRightBarButtonItem:spinItem];
8441 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8444 - (void) showDoneButton {
8445 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8446 initWithTitle:UCLocalize("DONE")
8447 style:UIBarButtonItemStyleDone
8449 action:@selector(doneButtonClicked)
8450 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8453 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8454 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8458 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8462 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8463 return nil; // This method is required by the protocol.
8466 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8468 return UCLocalize("ROLE_EX");
8470 return [NSString stringWithFormat:
8471 @"%@: %@\n%@: %@\n%@: %@",
8472 UCLocalize("USER"), UCLocalize("USER_EX"),
8473 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8474 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8479 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8480 return section == 3 ? 44.0f : 0;
8483 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8484 return section == 3 ? container_ : nil;
8487 - (void) reloadData {
8490 [table_ reloadData];
8495 /* Stash Controller {{{ */
8496 @interface StashController : CyteViewController {
8497 _H<UIActivityIndicatorView> spinner_;
8498 _H<UILabel> status_;
8499 _H<UILabel> caption_;
8504 @implementation StashController
8507 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8508 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8510 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8511 CGRect spinrect = [spinner_ frame];
8512 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8513 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8514 [spinner_ setFrame:spinrect];
8515 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8516 [[self view] addSubview:spinner_];
8517 [spinner_ startAnimating];
8520 captrect.size.width = [[self view] frame].size.width;
8521 captrect.size.height = 40.0f;
8522 captrect.origin.x = 0;
8523 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8524 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8525 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8526 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8527 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8528 [caption_ setTextColor:[UIColor whiteColor]];
8529 [caption_ setBackgroundColor:[UIColor clearColor]];
8530 [caption_ setShadowColor:[UIColor blackColor]];
8531 [caption_ setTextAlignment:UITextAlignmentCenter];
8532 [[self view] addSubview:caption_];
8535 statusrect.size.width = [[self view] frame].size.width;
8536 statusrect.size.height = 30.0f;
8537 statusrect.origin.x = 0;
8538 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8539 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8540 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8541 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8542 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8543 [status_ setTextColor:[UIColor whiteColor]];
8544 [status_ setBackgroundColor:[UIColor clearColor]];
8545 [status_ setShadowColor:[UIColor blackColor]];
8546 [status_ setTextAlignment:UITextAlignmentCenter];
8547 [[self view] addSubview:status_];
8550 - (void) releaseSubviews {
8555 [super releaseSubviews];
8561 @interface CYURLCache : SDURLCache {
8566 @implementation CYURLCache
8568 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8571 else if ([event isEqualToString:@"no-cache"])
8573 else if ([event isEqualToString:@"store"])
8575 else if ([event isEqualToString:@"invalid"])
8577 else if ([event isEqualToString:@"memory"])
8579 else if ([event isEqualToString:@"disk"])
8581 else if ([event isEqualToString:@"miss"])
8584 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8588 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8589 if (NSURLResponse *response = [cached response])
8590 if (NSString *mime = [response MIMEType])
8591 if ([mime isEqualToString:@"text/cache-manifest"]) {
8592 NSURL *url([response URL]);
8595 NSLog(@"###: %@", [url absoluteString]);
8598 @synchronized (HostConfig_) {
8599 [CachedURLs_ addObject:url];
8603 [super storeCachedResponse:cached forRequest:request];
8608 @interface Cydia : UIApplication <
8609 ConfirmationControllerDelegate,
8612 UINavigationControllerDelegate,
8613 UITabBarControllerDelegate
8615 _H<UIWindow> window_;
8616 _H<CYTabBarController> tabbar_;
8617 _H<CydiaLoadingViewController> emulated_;
8619 _H<NSMutableArray> essential_;
8620 _H<NSMutableArray> broken_;
8622 Database *database_;
8624 _H<NSURL> starturl_;
8629 _H<StashController> stash_;
8638 @implementation Cydia
8640 - (void) beginUpdate {
8641 [tabbar_ beginUpdate];
8645 return [tabbar_ updating];
8649 if ([broken_ count] != 0) {
8650 int count = [broken_ count];
8652 UIAlertView *alert = [[[UIAlertView alloc]
8653 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8654 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8656 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8658 UCLocalize("TEMPORARY_IGNORE"),
8662 [alert setContext:@"fixhalf"];
8663 [alert setNumberOfRows:2];
8665 } else if (!Ignored_ && [essential_ count] != 0) {
8666 int count = [essential_ count];
8668 UIAlertView *alert = [[[UIAlertView alloc]
8669 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8670 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8672 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8674 UCLocalize("UPGRADE_ESSENTIAL"),
8675 UCLocalize("COMPLETE_UPGRADE"),
8679 [alert setContext:@"upgrade"];
8684 - (void) _saveConfig {
8690 NSString *error(nil);
8692 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8694 NSError *error(nil);
8695 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8696 NSLog(@"failure to save metadata data: %@", error);
8701 NSLog(@"failure to serialize metadata: %@", error);
8706 // Navigation controller for the queuing badge.
8707 - (UINavigationController *) queueNavigationController {
8708 NSArray *controllers = [tabbar_ viewControllers];
8709 return [controllers objectAtIndex:3];
8712 - (void) unloadData {
8713 [tabbar_ unloadData];
8716 - (void) _updateData {
8721 UINavigationController *navigation = [self queueNavigationController];
8723 id queuedelegate = nil;
8724 if ([[navigation viewControllers] count] > 0)
8725 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8727 [queuedelegate queueStatusDidChange];
8728 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8731 - (void) _refreshIfPossible:(NSDate *)update {
8732 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8734 bool recently = false;
8735 if (update != nil) {
8736 NSTimeInterval interval([update timeIntervalSinceNow]);
8737 if (interval <= 0 && interval > -(15*60))
8741 // Don't automatic refresh if:
8742 // - We already refreshed recently.
8743 // - We already auto-refreshed this launch.
8744 // - Auto-refresh is disabled.
8745 if (recently || loaded_ || ManualRefresh) {
8746 // If we are cancelling, we need to make sure it knows it's already loaded.
8749 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8751 // We are going to load, so remember that.
8754 SCNetworkReachabilityFlags flags; {
8755 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8756 SCNetworkReachabilityGetFlags(reachability, &flags);
8757 CFRelease(reachability);
8760 // XXX: this elaborate mess is what Apple is using to determine this? :(
8761 // XXX: do we care if the user has to intervene? maybe that's ok?
8763 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8764 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8765 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8766 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8767 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8768 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8772 // If we can reach the server, auto-refresh!
8774 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8780 - (void) refreshIfPossible {
8781 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8784 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8785 @synchronized (self) {
8786 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8787 [hud setText:UCLocalize("RELOADING_DATA")];
8789 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8792 [self removeProgressHUD:hud];
8796 [essential_ removeAllObjects];
8797 [broken_ removeAllObjects];
8799 NSArray *packages([database_ packages]);
8800 for (Package *package in packages) {
8802 [broken_ addObject:package];
8803 if ([package upgradableAndEssential:NO]) {
8804 if ([package essential])
8805 [essential_ addObject:package];
8810 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8813 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8814 [changesItem setBadgeValue:badge];
8815 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8816 [self setApplicationIconBadgeNumber:changes];
8819 [changesItem setBadgeValue:nil];
8820 [changesItem setAnimatedBadge:NO];
8821 [self setApplicationIconBadgeNumber:0];
8826 [self refreshIfPossible];
8829 - (void) updateData {
8835 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8838 - (void) disemulate {
8839 if (emulated_ == nil)
8842 [window_ addSubview:[tabbar_ view]];
8843 [[emulated_ view] removeFromSuperview];
8845 [window_ setUserInteractionEnabled:YES];
8848 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8849 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8851 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8853 UIViewController *parent;
8854 if (emulated_ == nil)
8863 [parent presentModalViewController:navigation animated:YES];
8866 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8867 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8869 if (navigation != nil)
8870 [navigation pushViewController:progress animated:YES];
8872 [self presentModalViewController:progress force:YES];
8874 [progress invoke:invocation withTitle:title];
8878 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8879 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8882 - (void) repairWithInvocation:(NSInvocation *)invocation {
8884 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8888 - (void) repairWithSelector:(SEL)selector {
8889 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8892 - (void) reloadData {
8893 [self reloadDataWithInvocation:nil];
8899 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8900 _assert(file != NULL);
8902 for (NSString *key in [Sources_ allKeys]) {
8903 NSDictionary *source([Sources_ objectForKey:key]);
8905 fprintf(file, "%s %s %s\n",
8906 [[source objectForKey:@"Type"] UTF8String],
8907 [[source objectForKey:@"URI"] UTF8String],
8908 [[source objectForKey:@"Distribution"] UTF8String]
8914 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8917 - (void) addTrivialSource:(NSString *)href {
8918 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8921 @"./", @"Distribution",
8922 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8927 - (void) updateValues {
8932 pkgProblemResolver *resolver = [database_ resolver];
8934 resolver->InstallProtect();
8935 if (!resolver->Resolve(true))
8940 // XXX: this is a really crappy way of doing this.
8941 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8942 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8943 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8944 if ([tabbar_ updating])
8945 [tabbar_ cancelUpdate];
8947 if (![database_ prepare])
8950 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8951 [page setDelegate:self];
8952 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8955 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8956 [tabbar_ presentModalViewController:confirm_ animated:YES];
8962 @synchronized (self) {
8967 - (void) clearPackage:(Package *)package {
8968 @synchronized (self) {
8975 - (void) installPackages:(NSArray *)packages {
8976 @synchronized (self) {
8977 for (Package *package in packages)
8984 - (void) installPackage:(Package *)package {
8985 @synchronized (self) {
8992 - (void) removePackage:(Package *)package {
8993 @synchronized (self) {
9000 - (void) distUpgrade {
9001 @synchronized (self) {
9002 if (![database_ upgrade])
9009 [database_ perform];
9010 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9013 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9016 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9020 - (void) showSettings {
9021 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9024 - (void) retainNetworkActivityIndicator {
9025 if (activity_++ == 0)
9026 [self setNetworkActivityIndicatorVisible:YES];
9029 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9033 - (void) releaseNetworkActivityIndicator {
9034 if (--activity_ == 0)
9035 [self setNetworkActivityIndicatorVisible:NO];
9038 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9043 - (void) cancelAndClear:(bool)clear {
9044 @synchronized (self) {
9056 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9057 NSString *context([alert context]);
9059 if ([context isEqualToString:@"conffile"]) {
9060 FILE *input = [database_ input];
9061 if (button == [alert cancelButtonIndex])
9062 fprintf(input, "N\n");
9063 else if (button == [alert firstOtherButtonIndex])
9064 fprintf(input, "Y\n");
9067 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9068 } else if ([context isEqualToString:@"fixhalf"]) {
9069 if (button == [alert cancelButtonIndex]) {
9070 @synchronized (self) {
9071 for (Package *broken in (id) broken_) {
9074 NSString *id = [broken id];
9075 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9076 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9077 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9078 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9084 } else if (button == [alert firstOtherButtonIndex]) {
9085 [broken_ removeAllObjects];
9089 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9090 } else if ([context isEqualToString:@"upgrade"]) {
9091 if (button == [alert firstOtherButtonIndex]) {
9092 @synchronized (self) {
9093 for (Package *essential in (id) essential_)
9094 [essential install];
9099 } else if (button == [alert firstOtherButtonIndex] + 1) {
9101 } else if (button == [alert cancelButtonIndex]) {
9105 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9109 - (void) system:(NSString *)command {
9110 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9113 system([command UTF8String]);
9119 - (void) applicationWillSuspend {
9121 [super applicationWillSuspend];
9124 - (BOOL) isSafeToSuspend {
9127 NSLog(@"isSafeToSuspend: locked_ != 0");
9132 // Use external process status API internally.
9133 // This is probably a really bad idea.
9134 // XXX: what is the point of this? does this solve anything at all?
9135 uint64_t status = 0;
9137 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9138 notify_get_state(notify_token, &status);
9139 notify_cancel(notify_token);
9144 NSLog(@"isSafeToSuspend: status != 0");
9150 NSLog(@"isSafeToSuspend: -> true");
9155 - (void) applicationSuspend:(__GSEvent *)event {
9156 if ([self isSafeToSuspend])
9157 [super applicationSuspend:event];
9160 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9161 if ([self isSafeToSuspend])
9162 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9165 - (void) _setSuspended:(BOOL)value {
9166 if ([self isSafeToSuspend])
9167 [super _setSuspended:value];
9170 - (UIProgressHUD *) addProgressHUD {
9171 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9172 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9174 [window_ setUserInteractionEnabled:NO];
9176 UIViewController *target(tabbar_);
9177 if (UIViewController *modal = [target modalViewController])
9180 UIView *view([target view]);
9181 [view addSubview:hud];
9189 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9192 [hud removeFromSuperview];
9193 [window_ setUserInteractionEnabled:YES];
9196 - (CyteViewController *) pageForPackage:(NSString *)name {
9197 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9200 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9201 NSString *scheme([[url scheme] lowercaseString]);
9202 if ([[url absoluteString] length] <= [scheme length] + 3)
9204 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9205 NSArray *components([path pathComponents]);
9207 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9208 return [self pageForPackage:[components objectAtIndex:1]];
9210 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9213 NSString *base([components objectAtIndex:0]);
9215 CyteViewController *controller = nil;
9217 if ([base isEqualToString:@"url"]) {
9218 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9219 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9220 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9221 } else if (!external && [components count] == 1) {
9222 if ([base isEqualToString:@"manage"]) {
9223 controller = [[[ManageController alloc] init] autorelease];
9226 if ([base isEqualToString:@"sources"]) {
9227 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9230 if ([base isEqualToString:@"home"]) {
9231 controller = [[[HomeController alloc] init] autorelease];
9234 if ([base isEqualToString:@"sections"]) {
9235 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9238 if ([base isEqualToString:@"search"]) {
9239 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9242 if ([base isEqualToString:@"changes"]) {
9243 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9246 if ([base isEqualToString:@"installed"]) {
9247 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9249 } else if ([components count] == 2) {
9250 NSString *argument = [components objectAtIndex:1];
9252 if ([base isEqualToString:@"package"]) {
9253 controller = [self pageForPackage:argument];
9256 if (!external && [base isEqualToString:@"search"]) {
9257 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9260 if (!external && [base isEqualToString:@"sections"]) {
9261 if ([argument isEqualToString:@"all"])
9263 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9266 if (!external && [base isEqualToString:@"sources"]) {
9267 if ([argument isEqualToString:@"add"]) {
9268 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9269 [(SourcesController *)controller showAddSourcePrompt];
9271 Source *source = [database_ sourceWithKey:argument];
9272 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9276 if (!external && [base isEqualToString:@"launch"]) {
9277 [self launchApplicationWithIdentifier:argument suspended:NO];
9280 } else if (!external && [components count] == 3) {
9281 NSString *arg1 = [components objectAtIndex:1];
9282 NSString *arg2 = [components objectAtIndex:2];
9284 if ([base isEqualToString:@"package"]) {
9285 if ([arg2 isEqualToString:@"settings"]) {
9286 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9287 } else if ([arg2 isEqualToString:@"files"]) {
9288 if (Package *package = [database_ packageWithName:arg1]) {
9289 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9290 [(FileTable *)controller setPackage:package];
9296 [controller setDelegate:self];
9300 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9301 CyteViewController *page([self pageForURL:url forExternal:external]);
9304 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9305 [nav setViewControllers:[NSArray arrayWithObject:page]];
9306 [tabbar_ setUnselectedViewController:nav];
9312 - (void) applicationOpenURL:(NSURL *)url {
9313 [super applicationOpenURL:url];
9318 [self openCydiaURL:url forExternal:YES];
9321 - (void) applicationWillResignActive:(UIApplication *)application {
9322 // Stop refreshing if you get a phone call or lock the device.
9323 if ([tabbar_ updating])
9324 [tabbar_ cancelUpdate];
9326 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9327 [super applicationWillResignActive:application];
9330 - (void) applicationWillTerminate:(UIApplication *)application {
9332 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9333 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9334 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9339 - (void) setConfigurationData:(NSString *)data {
9340 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9342 if (!conffile_r(data)) {
9343 lprintf("E:invalid conffile\n");
9347 NSString *ofile = conffile_r[1];
9348 //NSString *nfile = conffile_r[2];
9350 UIAlertView *alert = [[[UIAlertView alloc]
9351 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9352 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9354 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9356 UCLocalize("ACCEPT_NEW_COPY"),
9357 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9361 [alert setContext:@"conffile"];
9362 [alert setNumberOfRows:2];
9366 - (void) addStashController {
9368 stash_ = [[[StashController alloc] init] autorelease];
9369 [window_ addSubview:[stash_ view]];
9372 - (void) removeStashController {
9373 [[stash_ view] removeFromSuperview];
9379 [self setIdleTimerDisabled:YES];
9381 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9382 UpdateExternalStatus(1);
9383 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9384 UpdateExternalStatus(0);
9386 [self removeStashController];
9388 if (ExecFork() == 0) {
9389 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9390 perror("launchctl stop");
9394 - (void) setupViewControllers {
9395 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9397 NSMutableArray *items([NSMutableArray arrayWithObjects:
9398 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9399 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9400 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9401 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9405 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9406 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9408 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9411 NSMutableArray *controllers([NSMutableArray array]);
9412 for (UITabBarItem *item in items) {
9413 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9414 [controller setTabBarItem:item];
9415 [controllers addObject:controller];
9417 [tabbar_ setViewControllers:controllers];
9419 [tabbar_ setUpdateDelegate:self];
9422 - (void) applicationDidFinishLaunching:(id)unused {
9424 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9425 [self setApplicationSupportsShakeToEdit:NO];
9427 @synchronized (HostConfig_) {
9428 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9431 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9432 initWithMemoryCapacity:524288
9433 diskCapacity:10485760
9434 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9437 [CydiaWebViewController _initialize];
9439 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9441 // this would disallow http{,s} URLs from accessing this data
9442 //[WebView registerURLSchemeAsLocal:@"cydia"];
9444 Font12_ = [UIFont systemFontOfSize:12];
9445 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9446 Font14_ = [UIFont systemFontOfSize:14];
9447 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9448 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9450 essential_ = [NSMutableArray arrayWithCapacity:4];
9451 broken_ = [NSMutableArray arrayWithCapacity:4];
9453 // XXX: I really need this thing... like, seriously... I'm sorry
9454 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9456 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9457 [window_ orderFront:self];
9458 [window_ makeKey:self];
9459 [window_ setHidden:NO];
9462 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9463 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9464 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9465 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9466 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9467 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9468 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9469 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9470 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9473 [self addStashController];
9474 // XXX: this would be much cleaner as a yieldToSelector:
9475 // that way the removeStashController could happen right here inline
9476 // we also could no longer require the useless stash_ field anymore
9477 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9481 database_ = [Database sharedInstance];
9482 [database_ setDelegate:self];
9484 [window_ setUserInteractionEnabled:NO];
9485 [self setupViewControllers];
9487 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9488 [window_ addSubview:[emulated_ view]];
9490 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9494 - (NSArray *) defaultStartPages {
9495 NSMutableArray *standard = [NSMutableArray array];
9496 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9497 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9498 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9500 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9502 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9503 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9505 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9512 [window_ setUserInteractionEnabled:YES];
9513 [self showSettings];
9516 if ([emulated_ modalViewController] != nil)
9517 [emulated_ dismissModalViewControllerAnimated:YES];
9518 [window_ setUserInteractionEnabled:NO];
9526 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9527 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9528 int standardIndex = 0;
9529 NSArray *standard = [self defaultStartPages];
9536 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9537 if (valid && closed != nil) {
9538 NSTimeInterval interval([closed timeIntervalSinceNow]);
9539 // XXX: Is 15 minutes the optimal time here?
9540 if (interval > 0 && interval <= -(15*60))
9544 if (valid && [saved count] != [standard count])
9548 for (unsigned int i = 0; i < [standard count]; i++) {
9549 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9550 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9551 // but it's good enough for now.
9552 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9559 NSArray *items = nil;
9561 [tabbar_ setSelectedIndex:savedIndex];
9564 [tabbar_ setSelectedIndex:standardIndex];
9568 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9569 NSArray *stack = [items objectAtIndex:tab];
9570 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9571 NSMutableArray *current = [NSMutableArray array];
9573 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9574 NSString *addr = [stack objectAtIndex:nav];
9575 NSURL *url = [NSURL URLWithString:addr];
9576 CyteViewController *page = [self pageForURL:url forExternal:NO];
9578 [current addObject:page];
9581 [navigation setViewControllers:current];
9584 // (Try to) show the startup URL.
9585 if (starturl_ != nil) {
9586 [self openCydiaURL:starturl_ forExternal:NO];
9591 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9592 if (item != nil && IsWildcat_) {
9593 [sheet showFromBarButtonItem:item animated:YES];
9595 [sheet showInView:window_];
9599 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9600 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9601 [progress setTitle:task];
9602 [progress addProgressEvent:event];
9605 - (void) addProgressEventForTask:(NSArray *)data {
9606 CydiaProgressEvent *event([data objectAtIndex:0]);
9607 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9608 [self addProgressEvent:event forTask:task];
9611 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9612 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9618 id Alloc_(id self, SEL selector) {
9619 id object = alloc_(self, selector);
9620 lprintf("[%s]A-%p\n", self->isa->name, object);
9625 id Dealloc_(id self, SEL selector) {
9626 id object = dealloc_(self, selector);
9627 lprintf("[%s]D-%p\n", self->isa->name, object);
9631 Class $WebDefaultUIKitDelegate;
9633 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9634 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9635 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9636 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9639 static NSSet *MobilizedFiles_;
9641 static NSURL *MobilizeURL(NSURL *url) {
9642 NSString *path([url path]);
9643 if ([path hasPrefix:@"/var/root/"]) {
9644 NSString *file([path substringFromIndex:10]);
9645 if ([MobilizedFiles_ containsObject:file])
9646 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9652 Class $CFXPreferencesPropertyListSource;
9653 @class CFXPreferencesPropertyListSource;
9655 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9656 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9657 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9658 url = MobilizeURL(url);
9659 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9660 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9666 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9667 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9668 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9669 url = MobilizeURL(url);
9670 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9671 //NSLog(@"%@ %@", [url absoluteString], value);
9677 Class $NSURLConnection;
9679 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9680 NSMutableURLRequest *copy([request mutableCopy]);
9682 NSURL *url([copy URL]);
9684 NSString *href([url absoluteString]);
9685 NSString *host([url host]);
9686 NSString *scheme([[url scheme] lowercaseString]);
9688 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9690 @synchronized (HostConfig_) {
9691 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9692 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9693 [copy setHTTPShouldUsePipelining:YES];
9695 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9696 if ([control isEqualToString:@"max-age=0"])
9697 if ([CachedURLs_ containsObject:href]) {
9699 NSLog(@"~~~: %@", href);
9702 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9704 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9705 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9706 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9710 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9714 int main(int argc, char *argv[]) {
9715 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9719 UpdateExternalStatus(0);
9721 if (Class $UIDevice = objc_getClass("UIDevice")) {
9722 UIDevice *device([$UIDevice currentDevice]);
9723 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9727 UIScreen *screen([UIScreen mainScreen]);
9728 if ([screen respondsToSelector:@selector(scale)])
9729 ScreenScale_ = [screen scale];
9733 UIDevice *device([UIDevice currentDevice]);
9734 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9737 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9738 if (idiom == UIUserInterfaceIdiomPhone)
9740 else if (idiom == UIUserInterfaceIdiomPad)
9743 NSLog(@"unknown UIUserInterfaceIdiom!");
9746 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9748 HostConfig_ = [[[NSObject alloc] init] autorelease];
9749 @synchronized (HostConfig_) {
9750 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9751 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9752 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9753 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9754 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9757 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9759 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9761 MobilizedFiles_ = [NSMutableSet setWithObjects:
9762 @"Library/Preferences/com.apple.Accessibility.plist",
9763 @"Library/Preferences/com.apple.preferences.sounds.plist",
9766 /* Library Hacks {{{ */
9767 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9769 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9771 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9772 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9773 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9774 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9777 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9778 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9779 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9780 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9783 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9784 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9785 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9786 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9787 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9790 $NSURLConnection = objc_getClass("NSURLConnection");
9791 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9792 if (NSURLConnection$init$ != NULL) {
9793 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9794 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9797 /* Set Locale {{{ */
9798 Locale_ = CFLocaleCopyCurrent();
9799 Languages_ = [NSLocale preferredLanguages];
9801 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9802 //NSLog(@"%@", [Languages_ description]);
9805 if (Locale_ != NULL)
9806 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9807 else if (Languages_ != nil && [Languages_ count] != 0)
9808 lang = [[Languages_ objectAtIndex:0] UTF8String];
9810 // XXX: consider just setting to C and then falling through?
9814 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9815 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9818 NSLog(@"Setting Language: %s", lang);
9821 setenv("LANG", lang, true);
9822 std::setlocale(LC_ALL, lang);
9826 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9828 /* Parse Arguments {{{ */
9829 bool substrate(false);
9835 for (int argi(1); argi != argc; ++argi)
9836 if (strcmp(argv[argi], "--") == 0) {
9838 argv[argi] = argv[0];
9844 for (int argi(1); argi != arge; ++argi)
9845 if (strcmp(args[argi], "--substrate") == 0)
9848 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9852 App_ = [[NSBundle mainBundle] bundlePath];
9858 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9859 alloc_ = alloc->method_imp;
9860 alloc->method_imp = (IMP) &Alloc_;*/
9862 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9863 dealloc_ = dealloc->method_imp;
9864 dealloc->method_imp = (IMP) &Dealloc_;*/
9866 /* System Information {{{ */
9870 size = sizeof(maxproc);
9871 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9872 perror("sysctlbyname(\"kern.maxproc\", ?)");
9873 else if (maxproc < 64) {
9875 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9876 perror("sysctlbyname(\"kern.maxproc\", #)");
9879 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9880 char *osversion = new char[size];
9881 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9882 perror("sysctlbyname(\"kern.osversion\", ?)");
9884 System_ = [NSString stringWithUTF8String:osversion];
9886 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9887 char *machine = new char[size];
9888 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9889 perror("sysctlbyname(\"hw.machine\", ?)");
9893 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9894 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9895 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9897 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9899 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9900 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9901 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9903 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9904 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9905 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9907 if (mcc != NULL && mnc != NULL)
9908 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9915 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9916 Build_ = [system objectForKey:@"ProductBuildVersion"];
9917 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9918 Product_ = [info objectForKey:@"SafariProductVersion"];
9919 Safari_ = [info objectForKey:@"CFBundleVersion"];
9922 /* Load Database {{{ */
9924 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9926 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9928 if (Metadata_ == NULL)
9929 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9931 Settings_ = [Metadata_ objectForKey:@"Settings"];
9933 Packages_ = [Metadata_ objectForKey:@"Packages"];
9935 Values_ = [Metadata_ objectForKey:@"Values"];
9936 Sections_ = [Metadata_ objectForKey:@"Sections"];
9937 Sources_ = [Metadata_ objectForKey:@"Sources"];
9939 Token_ = [Metadata_ objectForKey:@"Token"];
9942 if (Settings_ != nil)
9943 Role_ = [Settings_ objectForKey:@"Role"];
9945 if (Values_ == nil) {
9946 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
9947 [Metadata_ setObject:Values_ forKey:@"Values"];
9950 if (Sections_ == nil) {
9951 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9952 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9955 if (Sources_ == nil) {
9956 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9957 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9962 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9965 if (Packages_ != nil) {
9967 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9971 [Metadata_ removeObjectForKey:@"Packages"];
9977 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9979 #define MobileSubstrate_(name) \
9980 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9981 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9982 if (handle == NULL) \
9983 NSLog(@"%s", dlerror()); \
9986 MobileSubstrate_(Activator)
9987 MobileSubstrate_(libstatusbar)
9988 MobileSubstrate_(SimulatedKeyEvents)
9989 MobileSubstrate_(WinterBoard)
9991 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9992 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9994 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9996 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9997 unlink("/tmp/.cydia.fw");
9999 } else if (access("/User", F_OK) != 0 || version < 4) {
10002 system("/usr/libexec/cydia/firmware.sh");
10006 _assert([[NSFileManager defaultManager]
10007 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10008 withIntermediateDirectories:YES
10013 if (access("/tmp/cydia.chk", F_OK) == 0) {
10014 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10015 _assert(errno == ENOENT);
10016 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10017 _assert(errno == ENOENT);
10020 /* APT Initialization {{{ */
10021 _assert(pkgInitConfig(*_config));
10022 _assert(pkgInitSystem(*_config, _system));
10025 _config->Set("APT::Acquire::Translation", lang);
10027 // XXX: this timeout might be important :(
10028 //_config->Set("Acquire::http::Timeout", 15);
10030 _config->Set("Acquire::http::MaxParallel", 3);
10032 /* Color Choices {{{ */
10033 space_ = CGColorSpaceCreateDeviceRGB();
10035 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10036 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10037 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10038 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10039 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10040 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10041 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10042 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10043 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10045 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10046 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10048 /* UIKit Configuration {{{ */
10049 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10050 if ($GSFontSetUseLegacyFontMetrics != NULL)
10051 $GSFontSetUseLegacyFontMetrics(YES);
10053 // XXX: I have a feeling this was important
10054 //UIKeyboardDisableAutomaticAppearance();
10057 Colon_ = UCLocalize("COLON_DELIMITED");
10058 Elision_ = UCLocalize("ELISION");
10059 Error_ = UCLocalize("ERROR");
10060 Warning_ = UCLocalize("WARNING");
10063 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10065 CGColorSpaceRelease(space_);
10066 CFRelease(Locale_);