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 *Sections_;
701 static _transient NSMutableDictionary *Sources_;
702 static bool Changed_;
706 static CGFloat ScreenScale_;
707 static NSString *Idiom_;
709 static _H<NSMutableDictionary> SessionData_;
710 static _H<NSObject> HostConfig_;
711 static _H<NSMutableSet> BridgedHosts_;
712 static _H<NSMutableSet> TokenHosts_;
713 static _H<NSMutableSet> InsecureHosts_;
714 static _H<NSMutableSet> PipelinedHosts_;
715 static _H<NSMutableSet> CachedURLs_;
717 static NSString *kCydiaProgressEventTypeError = @"Error";
718 static NSString *kCydiaProgressEventTypeInformation = @"Information";
719 static NSString *kCydiaProgressEventTypeStatus = @"Status";
720 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
723 /* Display Helpers {{{ */
724 inline float Interpolate(float begin, float end, float fraction) {
725 return (end - begin) * fraction + begin;
728 static _finline const char *StripVersion_(const char *version) {
729 const char *colon(strchr(version, ':'));
730 return colon == NULL ? version : colon + 1;
733 NSString *LocalizeSection(NSString *section) {
734 static Pcre title_r("^(.*?) \\((.*)\\)$");
735 if (title_r(section)) {
736 NSString *parent(title_r[1]);
737 NSString *child(title_r[2]);
739 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
740 LocalizeSection(parent),
741 LocalizeSection(child)
745 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
748 NSString *Simplify(NSString *title) {
749 const char *data = [title UTF8String];
750 size_t size = [title length];
752 static Pcre square_r("^\\[(.*)\\]$");
753 if (square_r(data, size))
754 return Simplify(square_r[1]);
756 static Pcre paren_r("^\\((.*)\\)$");
757 if (paren_r(data, size))
758 return Simplify(paren_r[1]);
760 static Pcre title_r("^(.*?) \\((.*)\\)$");
761 if (title_r(data, size))
762 return Simplify(title_r[1]);
768 NSString *GetLastUpdate() {
769 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
772 return UCLocalize("NEVER_OR_UNKNOWN");
774 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
775 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
777 CFRelease(formatter);
779 return [(NSString *) formatted autorelease];
782 bool isSectionVisible(NSString *section) {
783 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
784 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
785 return hidden == nil || ![hidden boolValue];
788 static NSObject *CYIOGetValue(const char *path, NSString *property) {
789 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
790 if (entry == MACH_PORT_NULL)
793 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
794 IOObjectRelease(entry);
798 return [(id) value autorelease];
801 static NSString *CYHex(NSData *data, bool reverse = false) {
805 size_t length([data length]);
806 uint8_t bytes[length];
807 [data getBytes:bytes];
809 char string[length * 2 + 1];
810 for (size_t i(0); i != length; ++i)
811 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
813 return [NSString stringWithUTF8String:string];
818 /* Delegate Prototypes {{{ */
821 @class CydiaProgressEvent;
823 @protocol DatabaseDelegate
824 - (void) repairWithSelector:(SEL)selector;
825 - (void) setConfigurationData:(NSString *)data;
826 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
829 @class CYPackageController;
831 @protocol CydiaDelegate
832 - (void) retainNetworkActivityIndicator;
833 - (void) releaseNetworkActivityIndicator;
834 - (void) clearPackage:(Package *)package;
835 - (void) installPackage:(Package *)package;
836 - (void) installPackages:(NSArray *)packages;
837 - (void) removePackage:(Package *)package;
838 - (void) beginUpdate;
840 - (void) distUpgrade;
844 - (void) addTrivialSource:(NSString *)href;
845 - (void) showSettings;
846 - (UIProgressHUD *) addProgressHUD;
847 - (void) removeProgressHUD:(UIProgressHUD *)hud;
848 - (CyteViewController *) pageForPackage:(NSString *)name;
849 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
850 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
854 /* Status Delegation {{{ */
856 public pkgAcquireStatus
859 _transient NSObject<ProgressDelegate> *delegate_;
869 void setDelegate(NSObject<ProgressDelegate> *delegate) {
870 delegate_ = delegate;
873 NSObject<ProgressDelegate> *getDelegate() const {
877 virtual bool MediaChange(std::string media, std::string drive) {
881 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
884 virtual void Fetch(pkgAcquire::ItemDesc &item) {
885 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
886 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
887 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
890 virtual void Done(pkgAcquire::ItemDesc &item) {
893 virtual void Fail(pkgAcquire::ItemDesc &item) {
895 item.Owner->Status == pkgAcquire::Item::StatIdle ||
896 item.Owner->Status == pkgAcquire::Item::StatDone
900 std::string &error(item.Owner->ErrorText);
904 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
905 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
908 virtual bool Pulse(pkgAcquire *Owner) {
909 bool value = pkgAcquireStatus::Pulse(Owner);
912 double(CurrentBytes + CurrentItems) /
913 double(TotalBytes + TotalItems)
916 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
917 [NSNumber numberWithDouble:percent], @"Percent",
919 [NSNumber numberWithDouble:CurrentBytes], @"Current",
920 [NSNumber numberWithDouble:TotalBytes], @"Total",
921 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
922 nil] waitUntilDone:YES];
924 if (value && ![delegate_ isProgressCancelled])
932 _finline bool WasCancelled() const {
936 virtual void Start() {
937 pkgAcquireStatus::Start();
938 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
941 virtual void Stop() {
942 pkgAcquireStatus::Stop();
943 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
944 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
948 /* Database Interface {{{ */
949 typedef std::map< unsigned long, _H<Source> > SourceMap;
951 @interface Database : NSObject {
958 pkgDepCache::Policy *policy_;
959 pkgRecords *records_;
960 pkgProblemResolver *resolver_;
961 pkgAcquire *fetcher_;
963 SPtr<pkgPackageManager> manager_;
964 pkgSourceList *list_;
966 SourceMap sourceMap_;
967 _H<NSMutableArray> sourceList_;
969 CFMutableArrayRef packages_;
971 _transient NSObject<DatabaseDelegate> *delegate_;
972 _transient NSObject<ProgressDelegate> *progress_;
980 std::map<const char *, _H<NSString> > sections_;
983 + (Database *) sharedInstance;
986 - (void) _readCydia:(NSNumber *)fd;
987 - (void) _readStatus:(NSNumber *)fd;
988 - (void) _readOutput:(NSNumber *)fd;
992 - (Package *) packageWithName:(NSString *)name;
994 - (pkgCacheFile &) cache;
995 - (pkgDepCache::Policy *) policy;
996 - (pkgRecords *) records;
997 - (pkgProblemResolver *) resolver;
998 - (pkgAcquire &) fetcher;
999 - (pkgSourceList &) list;
1000 - (NSArray *) packages;
1001 - (NSArray *) sources;
1002 - (Source *) sourceWithKey:(NSString *)key;
1003 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1011 - (void) updateWithStatus:(Status &)status;
1013 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1015 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1016 - (NSObject<ProgressDelegate> *) progressDelegate;
1018 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1020 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1024 /* ProgressEvent Implementation {{{ */
1025 @implementation CydiaProgressEvent
1027 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1028 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1031 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1032 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1033 [event setPackage:package];
1037 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1038 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1040 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1041 NSArray *fields([description componentsSeparatedByString:@" "]);
1042 [event setItem:fields];
1044 if ([fields count] > 3) {
1045 [event setPackage:[fields objectAtIndex:2]];
1046 [event setVersion:[fields objectAtIndex:3]];
1049 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1054 + (NSArray *) _attributeKeys {
1055 return [NSArray arrayWithObjects:
1065 - (NSArray *) attributeKeys {
1066 return [[self class] _attributeKeys];
1069 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1070 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1073 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1074 if ((self = [super init]) != nil) {
1080 - (NSString *) message {
1084 - (NSString *) type {
1088 - (NSArray *) item {
1089 return (id) item_ ?: [NSNull null];
1092 - (void) setItem:(NSArray *)item {
1096 - (NSString *) package {
1097 return (id) package_ ?: [NSNull null];
1100 - (void) setPackage:(NSString *)package {
1104 - (NSString *) url {
1105 return (id) url_ ?: [NSNull null];
1108 - (void) setURL:(NSString *)url {
1112 - (void) setVersion:(NSString *)version {
1116 - (NSString *) version {
1117 return (id) version_ ?: [NSNull null];
1120 - (NSString *) compound:(NSString *)value {
1122 NSString *mode(nil); {
1123 NSString *type([self type]);
1124 if ([type isEqualToString:kCydiaProgressEventTypeError])
1125 mode = UCLocalize("ERROR");
1126 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1127 mode = UCLocalize("WARNING");
1131 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1137 - (NSString *) compoundMessage {
1138 return [self compound:[self message]];
1141 - (NSString *) compoundTitle {
1144 if (package_ == nil)
1146 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1147 title = [package name];
1151 return [self compound:title];
1157 // Cytore Definitions {{{
1158 struct PackageValue :
1161 Cytore::Offset<PackageValue> next_;
1163 uint32_t index_ : 23;
1164 uint32_t subscribed_ : 1;
1181 Cytore::Offset<PackageValue> packages_[1 << 16];
1184 static Cytore::File<MetaValue> MetaFile_;
1186 // Cytore Helper Functions {{{
1187 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1188 SplitHash nhash = { hashlittle(name, length) };
1190 PackageValue *metadata;
1192 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1193 offset: if (offset->IsNull()) {
1194 *offset = MetaFile_.New<PackageValue>(length + 1);
1195 metadata = &MetaFile_.Get(*offset);
1197 if (metadata == NULL) {
1201 metadata = new PackageValue();
1202 memset(metadata, 0, sizeof(*metadata));
1205 memcpy(metadata->name_, name, length + 1);
1206 metadata->nhash_ = nhash.u16[1];
1208 metadata = &MetaFile_.Get(*offset);
1210 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1211 offset = &metadata->next_;
1219 static void PackageImport(const void *key, const void *value, void *context) {
1220 bool &fail(*reinterpret_cast<bool *>(context));
1223 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1224 NSLog(@"failed to import package %@", key);
1228 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1229 NSDictionary *package((NSDictionary *) value);
1231 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1232 if ([subscribed boolValue] && !metadata->subscribed_)
1233 metadata->subscribed_ = true;
1235 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1236 time_t time([date timeIntervalSince1970]);
1237 if (metadata->first_ > time || metadata->first_ == 0)
1238 metadata->first_ = time;
1241 NSDate *date([package objectForKey:@"LastSeen"]);
1242 NSString *version([package objectForKey:@"LastVersion"]);
1244 if (date != nil && version != nil) {
1245 time_t time([date timeIntervalSince1970]);
1246 if (metadata->last_ < time || metadata->last_ == 0)
1247 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1248 size_t length(strlen(buffer));
1249 uint16_t vhash(hashlittle(buffer, length));
1251 size_t capped(std::min<size_t>(8, length));
1252 char *latest(buffer + length - capped);
1254 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1255 metadata->vhash_ = vhash;
1257 metadata->last_ = time;
1263 /* Source Class {{{ */
1264 @interface Source : NSObject {
1265 CYString depiction_;
1266 CYString description_;
1272 CYString distribution_;
1278 _H<NSString> authority_;
1280 CYString defaultIcon_;
1282 _H<NSDictionary> record_;
1286 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1288 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1290 - (NSString *) depictionForPackage:(NSString *)package;
1291 - (NSString *) supportForPackage:(NSString *)package;
1293 - (NSDictionary *) record;
1297 - (NSString *) distribution;
1298 - (NSString *) type;
1300 - (NSString *) base;
1303 - (NSString *) host;
1305 - (NSString *) name;
1306 - (NSString *) shortDescription;
1307 - (NSString *) label;
1308 - (NSString *) origin;
1309 - (NSString *) version;
1311 - (NSString *) defaultIcon;
1315 @implementation Source
1319 distribution_.clear();
1324 description_.clear();
1330 defaultIcon_.clear();
1337 + (NSArray *) _attributeKeys {
1338 return [NSArray arrayWithObjects:
1345 @"shortDescription",
1353 - (NSArray *) attributeKeys {
1354 return [[self class] _attributeKeys];
1357 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1358 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1361 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1364 trusted_ = index->IsTrusted();
1366 uri_.set(pool, index->GetURI());
1367 distribution_.set(pool, index->GetDist());
1368 type_.set(pool, index->GetType());
1370 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1371 if (dindex != NULL) {
1372 base_.set(pool, dindex->MetaIndexURI(""));
1375 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1378 pkgTagFile tags(&fd);
1380 pkgTagSection section;
1387 {"default-icon", &defaultIcon_},
1388 {"depiction", &depiction_},
1389 {"description", &description_},
1391 {"origin", &origin_},
1392 {"support", &support_},
1393 {"version", &version_},
1396 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1397 const char *start, *end;
1399 if (section.Find(names[i].name_, start, end)) {
1400 CYString &value(*names[i].value_);
1401 value.set(pool, start, end - start);
1407 record_ = [Sources_ objectForKey:[self key]];
1409 NSURL *url([NSURL URLWithString:uri_]);
1413 host_ = [host_ lowercaseString];
1418 authority_ = [url path];
1421 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1422 if ((self = [super init]) != nil) {
1423 [self setMetaIndex:index inPool:pool];
1427 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1428 NSDictionary *lhr = [self record];
1429 NSDictionary *rhr = [source record];
1432 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1434 NSString *lhs = [self name];
1435 NSString *rhs = [source name];
1437 if ([lhs length] != 0 && [rhs length] != 0) {
1438 unichar lhc = [lhs characterAtIndex:0];
1439 unichar rhc = [rhs characterAtIndex:0];
1441 if (isalpha(lhc) && !isalpha(rhc))
1442 return NSOrderedAscending;
1443 else if (!isalpha(lhc) && isalpha(rhc))
1444 return NSOrderedDescending;
1447 return [lhs compare:rhs options:LaxCompareOptions_];
1450 - (NSString *) depictionForPackage:(NSString *)package {
1451 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1454 - (NSString *) supportForPackage:(NSString *)package {
1455 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1458 - (NSDictionary *) record {
1466 - (NSString *) uri {
1470 - (NSString *) distribution {
1471 return distribution_;
1474 - (NSString *) type {
1478 - (NSString *) base {
1482 - (NSString *) key {
1483 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1486 - (NSString *) host {
1490 - (NSString *) name {
1491 return origin_.empty() ? (id) authority_ : origin_;
1494 - (NSString *) shortDescription {
1495 return description_;
1498 - (NSString *) label {
1499 return label_.empty() ? (id) authority_ : label_;
1502 - (NSString *) origin {
1506 - (NSString *) version {
1510 - (NSString *) defaultIcon {
1511 return defaultIcon_;
1516 /* CydiaOperation Class {{{ */
1517 @interface CydiaOperation : NSObject {
1518 _H<NSString> operator_;
1519 _H<NSString> value_;
1522 - (NSString *) operator;
1523 - (NSString *) value;
1527 @implementation CydiaOperation
1529 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1530 if ((self = [super init]) != nil) {
1531 operator_ = [NSString stringWithUTF8String:_operator];
1532 value_ = [NSString stringWithUTF8String:value];
1536 + (NSArray *) _attributeKeys {
1537 return [NSArray arrayWithObjects:
1543 - (NSArray *) attributeKeys {
1544 return [[self class] _attributeKeys];
1547 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1548 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1551 - (NSString *) operator {
1555 - (NSString *) value {
1561 /* CydiaClause Class {{{ */
1562 @interface CydiaClause : NSObject {
1563 _H<NSString> package_;
1564 _H<CydiaOperation> version_;
1567 - (NSString *) package;
1568 - (CydiaOperation *) version;
1572 @implementation CydiaClause
1574 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1575 if ((self = [super init]) != nil) {
1576 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1578 if (const char *version = dep.TargetVer())
1579 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1581 version_ = (id) [NSNull null];
1585 + (NSArray *) _attributeKeys {
1586 return [NSArray arrayWithObjects:
1592 - (NSArray *) attributeKeys {
1593 return [[self class] _attributeKeys];
1596 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1597 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1600 - (NSString *) package {
1604 - (CydiaOperation *) version {
1610 /* CydiaRelation Class {{{ */
1611 @interface CydiaRelation : NSObject {
1612 _H<NSString> relationship_;
1613 _H<NSMutableArray> clauses_;
1616 - (NSString *) relationship;
1617 - (NSArray *) clauses;
1621 @implementation CydiaRelation
1623 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1624 if ((self = [super init]) != nil) {
1625 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1626 clauses_ = [NSMutableArray arrayWithCapacity:8];
1628 pkgCache::DepIterator start;
1629 pkgCache::DepIterator end;
1630 dep.GlobOr(start, end); // ++dep
1633 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1635 // yes, seriously. (wtf?)
1643 + (NSArray *) _attributeKeys {
1644 return [NSArray arrayWithObjects:
1650 - (NSArray *) attributeKeys {
1651 return [[self class] _attributeKeys];
1654 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1655 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1658 - (NSString *) relationship {
1659 return relationship_;
1662 - (NSArray *) clauses {
1666 - (void) addClause:(CydiaClause *)clause {
1667 [clauses_ addObject:clause];
1672 /* Package Class {{{ */
1673 struct ParsedPackage {
1678 CYString depiction_;
1688 @interface Package : NSObject {
1691 uint32_t essential_ : 1;
1692 uint32_t obsolete_ : 1;
1693 uint32_t ignored_ : 1;
1699 _transient Database *database_;
1701 pkgCache::VerIterator version_;
1702 pkgCache::PkgIterator iterator_;
1703 pkgCache::VerFileIterator file_;
1709 CYString installed_;
1711 const char *section_;
1712 _transient NSString *section$_;
1716 PackageValue *metadata_;
1717 ParsedPackage *parsed_;
1719 _H<NSMutableArray> tags_;
1722 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1723 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1725 - (pkgCache::PkgIterator) iterator;
1728 - (NSString *) section;
1729 - (NSString *) simpleSection;
1731 - (NSString *) longSection;
1732 - (NSString *) shortSection;
1736 - (MIMEAddress *) maintainer;
1738 - (NSString *) longDescription;
1739 - (NSString *) shortDescription;
1742 - (PackageValue *) metadata;
1745 - (bool) subscribed;
1746 - (bool) setSubscribed:(bool)subscribed;
1750 - (NSString *) latest;
1751 - (NSString *) installed;
1752 - (BOOL) uninstalled;
1755 - (BOOL) upgradableAndEssential:(BOOL)essential;
1758 - (BOOL) unfiltered;
1762 - (BOOL) halfConfigured;
1763 - (BOOL) halfInstalled;
1765 - (NSString *) mode;
1768 - (NSString *) name;
1770 - (NSString *) homepage;
1771 - (NSString *) depiction;
1772 - (MIMEAddress *) author;
1774 - (NSString *) support;
1776 - (NSArray *) files;
1777 - (NSArray *) warnings;
1778 - (NSArray *) applications;
1780 - (Source *) source;
1783 - (BOOL) matches:(NSArray *)query;
1785 - (bool) hasSupportingRole;
1786 - (BOOL) hasTag:(NSString *)tag;
1787 - (NSString *) primaryPurpose;
1788 - (NSArray *) purposes;
1789 - (bool) isCommercial;
1791 - (void) setIndex:(size_t)index;
1793 - (CYString &) cyname;
1795 - (uint32_t) compareBySection:(NSArray *)sections;
1800 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1801 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1802 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1803 - (bool) isVisibleInSection:(NSString *)section;
1804 - (bool) isVisibleInSource:(Source *)source;
1808 uint32_t PackageChangesRadix(Package *self, void *) {
1813 uint32_t timestamp : 30;
1814 uint32_t ignored : 1;
1815 uint32_t upgradable : 1;
1819 bool upgradable([self upgradableAndEssential:YES]);
1820 value.bits.upgradable = upgradable ? 1 : 0;
1823 value.bits.timestamp = 0;
1824 value.bits.ignored = [self ignored] ? 0 : 1;
1825 value.bits.upgradable = 1;
1827 value.bits.timestamp = [self seen] >> 2;
1828 value.bits.ignored = 0;
1829 value.bits.upgradable = 0;
1832 return _not(uint32_t) - value.key;
1835 uint32_t PackagePrefixRadix(Package *self, void *context) {
1836 size_t offset(reinterpret_cast<size_t>(context));
1837 CYString &name([self cyname]);
1839 size_t size(name.size());
1842 char *text(name.data());
1845 if (!isdigit(text[0]))
1849 while (size != digits && isdigit(text[digits]))
1857 if (offset == 0 && zeros != 0) {
1858 memset(data, '0', zeros);
1859 memcpy(data + zeros, text, 4 - zeros);
1861 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1862 if (size <= offset - zeros)
1865 text += offset - zeros;
1866 size -= offset - zeros;
1869 memcpy(data, text, 4);
1871 memcpy(data, text, size);
1872 memset(data + size, 0, 4 - size);
1875 for (size_t i(0); i != 4; ++i)
1876 if (isalpha(data[i]))
1884 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1886 /* XXX: ntohl may be more honest */
1887 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1890 CYString &(*PackageName)(Package *self, SEL sel);
1892 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1893 _profile(PackageNameCompare)
1894 CYString &lhi(PackageName(lhs, @selector(cyname)));
1895 CYString &rhi(PackageName(rhs, @selector(cyname)));
1896 CFStringRef lhn(lhi), rhn(rhi);
1899 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1900 else if (rhn == NULL)
1901 return NSOrderedDescending;
1903 _profile(PackageNameCompare$NumbersLast)
1904 if (!lhi.empty() && !rhi.empty()) {
1905 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1906 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1907 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1908 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1909 return lha ? NSOrderedAscending : NSOrderedDescending;
1913 CFIndex length = CFStringGetLength(lhn);
1915 _profile(PackageNameCompare$Compare)
1916 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1921 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1922 return PackageNameCompare(*lhs, *rhs, context);
1925 struct PackageNameOrdering :
1926 std::binary_function<Package *, Package *, bool>
1928 _finline bool operator ()(Package *lhs, Package *rhs) const {
1929 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1933 @implementation Package
1935 - (NSString *) description {
1936 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1940 if (parsed_ != NULL)
1945 + (NSString *) webScriptNameForSelector:(SEL)selector {
1947 else if (selector == @selector(clear))
1949 else if (selector == @selector(getField:))
1951 else if (selector == @selector(hasTag:))
1953 else if (selector == @selector(install))
1955 else if (selector == @selector(remove))
1961 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1962 return [self webScriptNameForSelector:selector] == nil;
1965 + (NSArray *) _attributeKeys {
1966 return [NSArray arrayWithObjects:
1985 @"shortDescription",
1998 - (NSArray *) attributeKeys {
1999 return [[self class] _attributeKeys];
2002 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2003 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2006 - (NSArray *) relations {
2007 @synchronized (database_) {
2008 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2009 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2010 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2014 - (NSString *) getField:(NSString *)name {
2015 @synchronized (database_) {
2016 if ([database_ era] != era_ || file_.end())
2019 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2021 const char *start, *end;
2022 if (!parser.Find([name UTF8String], start, end))
2023 return (NSString *) [NSNull null];
2025 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2029 if (parsed_ != NULL)
2031 @synchronized (database_) {
2032 if ([database_ era] != era_ || file_.end())
2035 ParsedPackage *parsed(new ParsedPackage);
2038 _profile(Package$parse)
2039 pkgRecords::Parser *parser;
2041 _profile(Package$parse$Lookup)
2042 parser = &[database_ records]->Lookup(file_);
2047 _profile(Package$parse$Find)
2052 {"icon", &parsed->icon_},
2053 {"depiction", &parsed->depiction_},
2054 {"homepage", &parsed->homepage_},
2055 {"website", &website},
2056 {"bugs", &parsed->bugs_},
2057 {"support", &parsed->support_},
2058 {"sponsor", &parsed->sponsor_},
2059 {"author", &parsed->author_},
2062 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2063 const char *start, *end;
2065 if (parser->Find(names[i].name_, start, end)) {
2066 CYString &value(*names[i].value_);
2067 _profile(Package$parse$Value)
2068 value.set(pool_, start, end - start);
2074 _profile(Package$parse$Tagline)
2075 const char *start, *end;
2076 if (parser->ShortDesc(start, end)) {
2077 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2080 while (stop != start && stop[-1] == '\r')
2082 parsed->tagline_.set(pool_, start, stop - start);
2086 _profile(Package$parse$Retain)
2087 if (parsed->homepage_.empty())
2088 parsed->homepage_ = website;
2089 if (parsed->homepage_ == parsed->depiction_)
2090 parsed->homepage_.clear();
2095 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2096 if ((self = [super init]) != nil) {
2097 _profile(Package$initWithVersion)
2100 database_ = database;
2101 era_ = [database era];
2105 pkgCache::PkgIterator iterator(version.ParentPkg());
2106 iterator_ = iterator;
2108 _profile(Package$initWithVersion$Version)
2109 if (!version_.end())
2110 file_ = version_.FileList();
2112 pkgCache &cache([database_ cache]);
2113 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2117 _profile(Package$initWithVersion$Cache)
2118 name_.set(NULL, iterator.Display());
2120 latest_.set(NULL, StripVersion_(version_.VerStr()));
2122 pkgCache::VerIterator current(iterator.CurrentVer());
2124 installed_.set(NULL, StripVersion_(current.VerStr()));
2127 _profile(Package$initWithVersion$Tags)
2128 pkgCache::TagIterator tag(iterator.TagList());
2130 tags_ = [NSMutableArray arrayWithCapacity:8];
2132 const char *name(tag.Name());
2133 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2135 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2136 if (strcmp(name + 6, "enduser") == 0)
2138 else if (strcmp(name + 6, "hacker") == 0)
2140 else if (strcmp(name + 6, "developer") == 0)
2142 else if (strcmp(name + 6, "cydia") == 0)
2148 if (strncmp(name, "cydia::", 7) == 0) {
2149 if (strcmp(name + 7, "essential") == 0)
2151 else if (strcmp(name + 7, "obsolete") == 0)
2156 } while (!tag.end());
2160 _profile(Package$initWithVersion$Metadata)
2161 const char *mixed(iterator.Name());
2162 size_t size(strlen(mixed));
2163 char lower[size + 1];
2165 for (size_t i(0); i != size; ++i)
2166 lower[i] = mixed[i] | 0x20;
2169 PackageValue *metadata(PackageFind(lower, size));
2170 metadata_ = metadata;
2172 id_.set(NULL, metadata->name_, size);
2174 const char *latest(version_.VerStr());
2175 size_t length(strlen(latest));
2177 uint16_t vhash(hashlittle(latest, length));
2179 size_t capped(std::min<size_t>(8, length));
2180 latest = latest + length - capped;
2182 if (metadata->first_ == 0)
2183 metadata->first_ = now_;
2185 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2186 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2187 metadata->vhash_ = vhash;
2188 metadata->last_ = now_;
2189 } else if (metadata->last_ == 0)
2190 metadata->last_ = metadata->first_;
2193 _profile(Package$initWithVersion$Section)
2194 section_ = iterator.Section();
2197 _profile(Package$initWithVersion$Flags)
2198 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2199 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2204 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2205 pkgCache::VerIterator version;
2207 _profile(Package$packageWithIterator$GetCandidateVer)
2208 version = [database policy]->GetCandidateVer(iterator);
2216 _profile(Package$packageWithIterator$Allocate)
2217 package = [Package allocWithZone:zone];
2220 _profile(Package$packageWithIterator$Initialize)
2222 initWithVersion:version
2229 _profile(Package$packageWithIterator$Autorelease)
2230 package = [package autorelease];
2236 - (pkgCache::PkgIterator) iterator {
2240 - (NSString *) section {
2241 if (section$_ == nil) {
2242 if (section_ == NULL)
2245 _profile(Package$section$mappedSectionForPointer)
2246 section$_ = [database_ mappedSectionForPointer:section_];
2251 - (NSString *) simpleSection {
2252 if (NSString *section = [self section])
2253 return Simplify(section);
2258 - (NSString *) longSection {
2259 return LocalizeSection([self section]);
2262 - (NSString *) shortSection {
2263 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2266 - (NSString *) uri {
2269 pkgIndexFile *index;
2270 pkgCache::PkgFileIterator file(file_.File());
2271 if (![database_ list].FindIndex(file, index))
2273 return [NSString stringWithUTF8String:iterator_->Path];
2274 //return [NSString stringWithUTF8String:file.Site()];
2275 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2279 - (MIMEAddress *) maintainer {
2280 @synchronized (database_) {
2281 if ([database_ era] != era_ || file_.end())
2284 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2285 const std::string &maintainer(parser->Maintainer());
2286 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2290 @synchronized (database_) {
2291 if ([database_ era] != era_ || version_.end())
2294 return version_->InstalledSize;
2297 - (NSString *) longDescription {
2298 @synchronized (database_) {
2299 if ([database_ era] != era_ || file_.end())
2302 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2303 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2305 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2306 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2307 if ([lines count] < 2)
2310 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2311 for (size_t i(1), e([lines count]); i != e; ++i) {
2312 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2313 [trimmed addObject:trim];
2316 return [trimmed componentsJoinedByString:@"\n"];
2319 - (NSString *) shortDescription {
2320 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2324 _profile(Package$index)
2325 CFStringRef name((CFStringRef) [self name]);
2326 if (CFStringGetLength(name) == 0)
2328 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2329 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2331 return toupper(character);
2335 - (PackageValue *) metadata {
2340 PackageValue *metadata([self metadata]);
2341 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2344 - (bool) subscribed {
2345 return [self metadata]->subscribed_;
2348 - (bool) setSubscribed:(bool)subscribed {
2349 PackageValue *metadata([self metadata]);
2350 if (metadata->subscribed_ == subscribed)
2352 metadata->subscribed_ = subscribed;
2360 - (NSString *) latest {
2364 - (NSString *) installed {
2368 - (BOOL) uninstalled {
2369 return installed_.empty();
2373 return !version_.end();
2376 - (BOOL) upgradableAndEssential:(BOOL)essential {
2377 _profile(Package$upgradableAndEssential)
2378 pkgCache::VerIterator current(iterator_.CurrentVer());
2380 return essential && essential_;
2382 return !version_.end() && version_ != current;
2386 - (BOOL) essential {
2391 return [database_ cache][iterator_].InstBroken();
2394 - (BOOL) unfiltered {
2395 _profile(Package$unfiltered$obsolete)
2396 if (_unlikely(obsolete_))
2400 _profile(Package$unfiltered$hasSupportingRole)
2401 if (_unlikely(![self hasSupportingRole]))
2409 if (![self unfiltered])
2414 _profile(Package$visible$section)
2415 section = [self section];
2418 _profile(Package$visible$isSectionVisible)
2419 if (!isSectionVisible(section))
2427 unsigned char current(iterator_->CurrentState);
2428 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2431 - (BOOL) halfConfigured {
2432 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2435 - (BOOL) halfInstalled {
2436 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2440 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2441 return state.Mode != pkgDepCache::ModeKeep;
2444 - (NSString *) mode {
2445 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2447 switch (state.Mode) {
2448 case pkgDepCache::ModeDelete:
2449 if ((state.iFlags & pkgDepCache::Purge) != 0)
2453 case pkgDepCache::ModeKeep:
2454 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2455 return @"REINSTALL";
2456 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2460 case pkgDepCache::ModeInstall:
2461 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2462 return @"REINSTALL";
2463 else*/ switch (state.Status) {
2465 return @"DOWNGRADE";
2471 return @"NEW_INSTALL";
2482 - (NSString *) name {
2483 return name_.empty() ? id_ : name_;
2486 - (UIImage *) icon {
2487 NSString *section = [self simpleSection];
2490 if (parsed_ != NULL)
2491 if (NSString *href = parsed_->icon_)
2492 if ([href hasPrefix:@"file:///"])
2493 // XXX: correct escaping
2494 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2495 if (icon == nil) if (section != nil)
2496 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2497 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2498 if ([dicon hasPrefix:@"file:///"])
2499 // XXX: correct escaping
2500 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2502 icon = [UIImage applicationImageNamed:@"unknown.png"];
2506 - (NSString *) homepage {
2507 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2510 - (NSString *) depiction {
2511 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2514 - (MIMEAddress *) sponsor {
2515 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2518 - (MIMEAddress *) author {
2519 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2522 - (NSString *) support {
2523 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2526 - (NSArray *) files {
2527 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2528 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2531 fin.open([path UTF8String]);
2536 while (std::getline(fin, line))
2537 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2542 - (NSString *) state {
2543 @synchronized (database_) {
2544 if ([database_ era] != era_ || file_.end())
2547 switch (iterator_->CurrentState) {
2548 case pkgCache::State::NotInstalled:
2549 return @"NotInstalled";
2550 case pkgCache::State::UnPacked:
2552 case pkgCache::State::HalfConfigured:
2553 return @"HalfConfigured";
2554 case pkgCache::State::HalfInstalled:
2555 return @"HalfInstalled";
2556 case pkgCache::State::ConfigFiles:
2557 return @"ConfigFiles";
2558 case pkgCache::State::Installed:
2559 return @"Installed";
2560 case pkgCache::State::TriggersAwaited:
2561 return @"TriggersAwaited";
2562 case pkgCache::State::TriggersPending:
2563 return @"TriggersPending";
2566 return (NSString *) [NSNull null];
2569 - (NSString *) selection {
2570 @synchronized (database_) {
2571 if ([database_ era] != era_ || file_.end())
2574 switch (iterator_->SelectedState) {
2575 case pkgCache::State::Unknown:
2577 case pkgCache::State::Install:
2579 case pkgCache::State::Hold:
2581 case pkgCache::State::DeInstall:
2582 return @"DeInstall";
2583 case pkgCache::State::Purge:
2587 return (NSString *) [NSNull null];
2590 - (NSArray *) warnings {
2591 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2592 const char *name(iterator_.Name());
2594 size_t length(strlen(name));
2595 if (length < 2) invalid:
2596 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2597 else for (size_t i(0); i != length; ++i)
2599 /* XXX: technically this is not allowed */
2600 (name[i] < 'A' || name[i] > 'Z') &&
2601 (name[i] < 'a' || name[i] > 'z') &&
2602 (name[i] < '0' || name[i] > '9') &&
2603 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2606 if (strcmp(name, "cydia") != 0) {
2609 bool _private = false;
2612 bool repository = [[self section] isEqualToString:@"Repositories"];
2614 if (NSArray *files = [self files])
2615 for (NSString *file in files)
2616 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2618 else if (!user && [file isEqualToString:@"/User"])
2620 else if (!_private && [file isEqualToString:@"/private"])
2622 else if (!stash && [file isEqualToString:@"/var/stash"])
2625 /* XXX: this is not sensitive enough. only some folders are valid. */
2626 if (cydia && !repository)
2627 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2629 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2631 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2633 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2636 return [warnings count] == 0 ? nil : warnings;
2639 - (NSArray *) applications {
2640 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2642 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2644 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2645 if (NSArray *files = [self files])
2646 for (NSString *file in files)
2647 if (application_r(file)) {
2648 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2649 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2650 if ([id isEqualToString:me])
2653 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2655 display = application_r[1];
2657 NSString *bundle([file stringByDeletingLastPathComponent]);
2658 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2659 if (icon == nil || [icon length] == 0)
2661 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2663 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2664 [applications addObject:application];
2666 [application addObject:id];
2667 [application addObject:display];
2668 [application addObject:url];
2671 return [applications count] == 0 ? nil : applications;
2674 - (Source *) source {
2675 if (source_ == nil) {
2676 @synchronized (database_) {
2677 if ([database_ era] != era_ || file_.end())
2678 source_ = (Source *) [NSNull null];
2680 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2684 return source_ == (Source *) [NSNull null] ? nil : source_;
2691 - (BOOL) matches:(NSArray *)query {
2692 if (query == nil || [query count] == 0)
2704 length = [string length];
2706 for (NSString *term in query) {
2707 range = [string rangeOfString:term options:MatchCompareOptions_];
2708 if (range.location != NSNotFound)
2709 rank_ -= 10 * 100000 / length;
2712 string = [self name];
2714 for (NSString *term in query) {
2715 range = [string rangeOfString:term options:MatchCompareOptions_];
2716 if (range.location != NSNotFound)
2717 rank_ -= 6 * 100000 / length;
2720 string = [self shortDescription];
2721 length = [string length];
2722 NSUInteger stop(std::min<NSUInteger>(length, 100));
2724 for (NSString *term in query) {
2725 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2726 if (range.location != NSNotFound)
2727 rank_ -= 2 * 100000 / length;
2733 - (bool) hasSupportingRole {
2738 if ([Role_ isEqualToString:@"User"])
2742 if ([Role_ isEqualToString:@"Hacker"])
2746 if ([Role_ isEqualToString:@"Developer"])
2751 - (NSArray *) tags {
2755 - (BOOL) hasTag:(NSString *)tag {
2756 return tags_ == nil ? NO : [tags_ containsObject:tag];
2759 - (NSString *) primaryPurpose {
2760 for (NSString *tag in (NSArray *) tags_)
2761 if ([tag hasPrefix:@"purpose::"])
2762 return [tag substringFromIndex:9];
2766 - (NSArray *) purposes {
2767 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2768 for (NSString *tag in (NSArray *) tags_)
2769 if ([tag hasPrefix:@"purpose::"])
2770 [purposes addObject:[tag substringFromIndex:9]];
2771 return [purposes count] == 0 ? nil : purposes;
2774 - (bool) isCommercial {
2775 return [self hasTag:@"cydia::commercial"];
2778 - (void) setIndex:(size_t)index {
2779 if (metadata_->index_ != index)
2780 metadata_->index_ = index;
2783 - (CYString &) cyname {
2784 return name_.empty() ? id_ : name_;
2787 - (uint32_t) compareBySection:(NSArray *)sections {
2788 NSString *section([self section]);
2789 for (size_t i(0), e([sections count]); i != e; ++i) {
2790 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2794 return _not(uint32_t);
2798 @synchronized (database_) {
2799 pkgProblemResolver *resolver = [database_ resolver];
2800 resolver->Clear(iterator_);
2802 pkgCacheFile &cache([database_ cache]);
2803 cache->SetReInstall(iterator_, false);
2804 cache->MarkKeep(iterator_, false);
2808 @synchronized (database_) {
2809 pkgProblemResolver *resolver = [database_ resolver];
2810 resolver->Clear(iterator_);
2811 resolver->Protect(iterator_);
2813 pkgCacheFile &cache([database_ cache]);
2814 cache->SetReInstall(iterator_, false);
2815 cache->MarkInstall(iterator_, false);
2817 pkgDepCache::StateCache &state((*cache)[iterator_]);
2818 if (!state.Install())
2819 cache->SetReInstall(iterator_, true);
2823 @synchronized (database_) {
2824 pkgProblemResolver *resolver = [database_ resolver];
2825 resolver->Clear(iterator_);
2826 resolver->Remove(iterator_);
2827 resolver->Protect(iterator_);
2829 pkgCacheFile &cache([database_ cache]);
2830 cache->SetReInstall(iterator_, false);
2831 cache->MarkDelete(iterator_, true);
2834 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2835 _profile(Package$isUnfilteredAndSearchedForBy)
2838 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2839 value &= [self unfiltered];
2842 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2843 value &= [self matches:query];
2850 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2851 if ([search length] == 0)
2854 _profile(Package$isUnfilteredAndSelectedForBy)
2857 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2858 value &= [self unfiltered];
2861 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2862 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2869 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2870 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2873 - (bool) isVisibleInSection:(NSString *)name {
2874 NSString *section([self section]);
2878 section == nil && [name length] == 0 ||
2879 [name isEqualToString:section]
2880 ) && [self visible];
2883 - (bool) isVisibleInSource:(Source *)source {
2884 return [self source] == source && [self visible];
2889 /* Section Class {{{ */
2890 @interface Section : NSObject {
2895 _H<NSString> localized_;
2898 - (NSComparisonResult) compareByLocalized:(Section *)section;
2899 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2900 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2901 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2902 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2903 - (NSString *) name;
2910 - (void) addToCount;
2912 - (void) setCount:(size_t)count;
2913 - (NSString *) localized;
2917 @implementation Section
2919 - (NSComparisonResult) compareByLocalized:(Section *)section {
2920 NSString *lhs(localized_);
2921 NSString *rhs([section localized]);
2923 /*if ([lhs length] != 0 && [rhs length] != 0) {
2924 unichar lhc = [lhs characterAtIndex:0];
2925 unichar rhc = [rhs characterAtIndex:0];
2927 if (isalpha(lhc) && !isalpha(rhc))
2928 return NSOrderedAscending;
2929 else if (!isalpha(lhc) && isalpha(rhc))
2930 return NSOrderedDescending;
2933 return [lhs compare:rhs options:LaxCompareOptions_];
2936 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2937 if ((self = [self initWithName:name localize:NO]) != nil) {
2938 if (localized != nil)
2939 localized_ = localized;
2943 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2944 return [self initWithName:name row:0 localize:localize];
2947 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2948 if ((self = [super init]) != nil) {
2953 localized_ = LocalizeSection(name_);
2957 /* XXX: localize the index thingees */
2958 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2959 if ((self = [super init]) != nil) {
2960 name_ = [NSString stringWithCharacters:&index length:1];
2966 - (NSString *) name {
2986 - (void) addToCount {
2990 - (void) setCount:(size_t)count {
2994 - (NSString *) localized {
3001 static NSString *Colon_;
3003 static NSString *Error_;
3004 static NSString *Warning_;
3006 class CydiaLogCleaner :
3007 public pkgArchiveCleaner
3010 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3015 /* Database Implementation {{{ */
3016 @implementation Database
3018 + (Database *) sharedInstance {
3019 static _H<Database> instance;
3020 if (instance == nil)
3021 instance = [[[Database alloc] init] autorelease];
3029 - (void) releasePackages {
3030 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3031 CFArrayRemoveAllValues(packages_);
3035 // XXX: actually implement this thing
3037 [self releasePackages];
3038 apr_pool_destroy(pool_);
3039 NSRecycleZone(zone_);
3043 - (void) _readCydia:(NSNumber *)fd {
3044 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3045 std::istream is(&ib);
3048 static Pcre finish_r("^finish:([^:]*)$");
3050 while (std::getline(is, line)) {
3051 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3053 const char *data(line.c_str());
3054 size_t size = line.size();
3055 lprintf("C:%s\n", data);
3057 if (finish_r(data, size)) {
3058 NSString *finish = finish_r[1];
3059 int index = [Finishes_ indexOfObject:finish];
3060 if (index != INT_MAX && index > Finish_)
3070 - (void) _readStatus:(NSNumber *)fd {
3071 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3072 std::istream is(&ib);
3075 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3076 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3078 while (std::getline(is, line)) {
3079 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3081 const char *data(line.c_str());
3082 size_t size(line.size());
3083 lprintf("S:%s\n", data);
3085 if (conffile_r(data, size)) {
3086 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3087 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3088 } else if (strncmp(data, "status: ", 8) == 0) {
3089 // status: <package>: {unpacked,half-configured,installed}
3090 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3091 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3092 } else if (strncmp(data, "processing: ", 12) == 0) {
3093 // processing: configure: config-test
3094 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3095 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3096 } else if (pmstatus_r(data, size)) {
3097 std::string type([pmstatus_r[1] UTF8String]);
3099 NSString *package = pmstatus_r[2];
3100 if ([package isEqualToString:@"dpkg-exec"])
3103 float percent([pmstatus_r[3] floatValue]);
3104 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3106 NSString *string = pmstatus_r[4];
3108 if (type == "pmerror") {
3109 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3110 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3111 } else if (type == "pmstatus") {
3112 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3113 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3114 } else if (type == "pmconffile")
3115 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3117 lprintf("E:unknown pmstatus\n");
3119 lprintf("E:unknown status\n");
3127 - (void) _readOutput:(NSNumber *)fd {
3128 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3129 std::istream is(&ib);
3132 while (std::getline(is, line)) {
3133 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3135 lprintf("O:%s\n", line.c_str());
3137 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3138 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3150 - (Package *) packageWithName:(NSString *)name {
3151 @synchronized (self) {
3152 if (static_cast<pkgDepCache *>(cache_) == NULL)
3154 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3155 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3159 if ((self = [super init]) != nil) {
3166 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3167 apr_pool_create(&pool_, NULL);
3169 size_t capacity(MetaFile_->active_);
3175 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3176 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3180 _assert(pipe(fds) != -1);
3183 _config->Set("APT::Keep-Fds::", cydiafd_);
3184 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3187 detachNewThreadSelector:@selector(_readCydia:)
3189 withObject:[NSNumber numberWithInt:fds[0]]
3192 _assert(pipe(fds) != -1);
3196 detachNewThreadSelector:@selector(_readStatus:)
3198 withObject:[NSNumber numberWithInt:fds[0]]
3201 _assert(pipe(fds) != -1);
3202 _assert(dup2(fds[0], 0) != -1);
3203 _assert(close(fds[0]) != -1);
3205 input_ = fdopen(fds[1], "a");
3207 _assert(pipe(fds) != -1);
3208 _assert(dup2(fds[1], 1) != -1);
3209 _assert(close(fds[1]) != -1);
3212 detachNewThreadSelector:@selector(_readOutput:)
3214 withObject:[NSNumber numberWithInt:fds[0]]
3219 - (pkgCacheFile &) cache {
3223 - (pkgDepCache::Policy *) policy {
3227 - (pkgRecords *) records {
3231 - (pkgProblemResolver *) resolver {
3235 - (pkgAcquire &) fetcher {
3239 - (pkgSourceList &) list {
3243 - (NSArray *) packages {
3244 return (NSArray *) packages_;
3247 - (NSArray *) sources {
3251 - (Source *) sourceWithKey:(NSString *)key {
3252 for (Source *source in [self sources]) {
3253 if ([[source key] isEqualToString:key])
3258 - (bool) popErrorWithTitle:(NSString *)title {
3261 while (!_error->empty()) {
3263 bool warning(!_error->PopMessage(error));
3268 size_t size(error.size());
3269 if (size == 0 || error[size - 1] != '\n')
3271 error.resize(size - 1);
3274 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3276 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3282 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3283 return [self popErrorWithTitle:title] || !success;
3286 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3287 @synchronized (self) {
3290 [self releasePackages];
3293 [sourceList_ removeAllObjects];
3313 apr_pool_clear(pool_);
3315 NSRecycleZone(zone_);
3316 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3318 int chk(creat("/tmp/cydia.chk", 0644));
3322 if (invocation != nil)
3323 [invocation invoke];
3325 NSString *title(UCLocalize("DATABASE"));
3328 OpProgress progress;
3329 while (!cache_.Open(progress, true)) { pop:
3331 bool warning(!_error->PopMessage(error));
3332 lprintf("cache_.Open():[%s]\n", error.c_str());
3334 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3335 [delegate_ repairWithSelector:@selector(configure)];
3336 else if (error == "The package lists or status file could not be parsed or opened.")
3337 [delegate_ repairWithSelector:@selector(update)];
3338 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3339 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3340 // else if (error == "Malformed Status line")
3341 // else if (error == "The list of sources could not be read.")
3343 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3353 unlink("/tmp/cydia.chk");
3355 now_ = [[NSDate date] timeIntervalSince1970];
3357 policy_ = new pkgDepCache::Policy();
3358 records_ = new pkgRecords(cache_);
3359 resolver_ = new pkgProblemResolver(cache_);
3360 fetcher_ = new pkgAcquire(&status_);
3363 list_ = new pkgSourceList();
3364 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3367 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3368 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3372 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3375 if (cache_->BrokenCount() != 0) {
3376 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3379 if (cache_->BrokenCount() != 0) {
3380 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3384 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3388 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3389 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3390 [sourceList_ addObject:object];
3392 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3393 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3394 // XXX: this could be more intelligent
3395 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3396 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3398 sourceMap_[cached->ID] = object;
3403 /*std::vector<Package *> packages;
3404 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3409 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3410 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3411 //packages.push_back(package);
3412 CFArrayAppendValue(packages_, CFRetain(package));
3416 /*if (packages.empty())
3417 packages_ = [[NSArray alloc] init];
3419 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3422 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3423 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3424 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3432 /*if (!packages.empty())
3433 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3434 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3436 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3438 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3440 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3444 size_t count(CFArrayGetCount(packages_));
3445 MetaFile_->active_ = count;
3447 for (size_t index(0); index != count; ++index)
3448 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3455 @synchronized (self) {
3457 resolver_ = new pkgProblemResolver(cache_);
3459 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3460 if (!cache_[iterator].Keep())
3461 cache_->MarkKeep(iterator, false);
3462 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3463 cache_->SetReInstall(iterator, false);
3466 - (void) configure {
3467 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3469 system([dpkg UTF8String]);
3474 // XXX: I don't remember this condition
3479 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3481 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3483 if ([self popErrorWithTitle:title])
3487 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3489 CydiaLogCleaner cleaner;
3490 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3497 fetcher_->Shutdown();
3499 pkgRecords records(cache_);
3501 lock_ = new FileFd();
3502 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3504 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3506 if ([self popErrorWithTitle:title])
3510 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3513 manager_ = (_system->CreatePM(cache_));
3514 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3521 bool substrate(RestartSubstrate_);
3522 RestartSubstrate_ = false;
3524 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3526 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3528 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3530 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3531 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3534 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3536 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3538 [self popErrorWithTitle:title];
3542 bool failed = false;
3543 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3544 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3546 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3552 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3560 RestartSubstrate_ = true;
3563 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3565 if (_error->PendingError()) {
3570 if (result == pkgPackageManager::Failed) {
3575 if (result != pkgPackageManager::Completed) {
3580 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3582 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3584 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3585 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3588 if (![before isEqualToArray:after])
3593 NSString *title(UCLocalize("UPGRADE"));
3594 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3600 [self updateWithStatus:status_];
3603 - (void) updateWithStatus:(Status &)status {
3604 NSString *title(UCLocalize("REFRESHING_DATA"));
3607 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3611 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3612 if ([self popErrorWithTitle:title])
3615 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3617 bool success(ListUpdate(status, list, PulseInterval_));
3618 if (status.WasCancelled())
3621 [self popErrorWithTitle:title forOperation:success];
3622 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3626 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3629 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3630 delegate_ = delegate;
3633 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3634 progress_ = delegate;
3635 status_.setDelegate(delegate);
3638 - (NSObject<ProgressDelegate> *) progressDelegate {
3642 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3643 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3644 return i == sourceMap_.end() ? nil : i->second;
3647 - (NSString *) mappedSectionForPointer:(const char *)section {
3648 _H<NSString> *mapped;
3650 _profile(Database$mappedSectionForPointer$Cache)
3651 mapped = §ions_[section];
3654 if (*mapped == NULL) {
3655 size_t length(strlen(section));
3656 char spaced[length + 1];
3658 _profile(Database$mappedSectionForPointer$Replace)
3659 for (size_t index(0); index != length; ++index)
3660 spaced[index] = section[index] == '_' ? ' ' : section[index];
3661 spaced[length] = '\0';
3666 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3667 string = [NSString stringWithUTF8String:spaced];
3670 _profile(Database$mappedSectionForPointer$Map)
3671 string = [SectionMap_ objectForKey:string] ?: string;
3681 static _H<NSMutableSet> Diversions_;
3683 @interface Diversion : NSObject {
3686 _H<NSString> format_;
3691 @implementation Diversion
3693 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3694 if ((self = [super init]) != nil) {
3695 pattern_ = [from UTF8String];
3701 - (NSString *) divert:(NSString *)url {
3702 return !pattern_(url) ? nil : pattern_->*format_;
3705 + (NSURL *) divertURL:(NSURL *)url {
3707 NSString *href([url absoluteString]);
3709 for (Diversion *diversion in (id) Diversions_)
3710 if (NSString *diverted = [diversion divert:href]) {
3712 NSLog(@"div: %@", diverted);
3714 url = [NSURL URLWithString:diverted];
3721 - (NSString *) key {
3725 - (NSUInteger) hash {
3729 - (BOOL) isEqual:(Diversion *)object {
3730 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3735 @interface CydiaObject : NSObject {
3736 _H<IndirectDelegate> indirect_;
3737 _transient id delegate_;
3740 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3744 @interface CydiaWebViewController : CyteWebViewController {
3745 _H<CydiaObject> cydia_;
3748 + (void) addDiversion:(Diversion *)diversion;
3752 /* Web Scripting {{{ */
3753 @implementation CydiaObject
3755 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3756 if ((self = [super init]) != nil) {
3757 indirect_ = indirect;
3761 - (void) setDelegate:(id)delegate {
3762 delegate_ = delegate;
3765 + (NSArray *) _attributeKeys {
3766 return [NSArray arrayWithObjects:
3782 - (NSArray *) attributeKeys {
3783 return [[self class] _attributeKeys];
3786 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3787 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3790 - (NSString *) version {
3794 - (NSString *) device {
3795 return [[UIDevice currentDevice] uniqueIdentifier];
3798 - (NSString *) firmware {
3799 return [[UIDevice currentDevice] systemVersion];
3802 - (NSString *) hostname {
3803 return [[UIDevice currentDevice] name];
3806 - (NSString *) idiom {
3807 return (id) Idiom_ ?: [NSNull null];
3810 - (NSString *) plmn {
3811 return (id) PLMN_ ?: [NSNull null];
3814 - (NSString *) bbsnum {
3815 return (id) BBSNum_ ?: [NSNull null];
3818 - (NSString *) ecid {
3819 return (id) ChipID_ ?: [NSNull null];
3822 - (NSString *) serial {
3823 return SerialNumber_;
3826 - (NSString *) role {
3827 return (id) Role_ ?: [NSNull null];
3830 - (NSString *) model {
3831 return [NSString stringWithUTF8String:Machine_];
3834 - (NSString *) token {
3835 return (id) Token_ ?: [NSNull null];
3838 + (NSString *) webScriptNameForSelector:(SEL)selector {
3840 else if (selector == @selector(addBridgedHost:))
3841 return @"addBridgedHost";
3842 else if (selector == @selector(addInsecureHost:))
3843 return @"addInsecureHost";
3844 else if (selector == @selector(addInternalRedirect::))
3845 return @"addInternalRedirect";
3846 else if (selector == @selector(addPipelinedHost:scheme:))
3847 return @"addPipelinedHost";
3848 else if (selector == @selector(addTokenHost:))
3849 return @"addTokenHost";
3850 else if (selector == @selector(addTrivialSource:))
3851 return @"addTrivialSource";
3852 else if (selector == @selector(close))
3854 else if (selector == @selector(du:))
3856 else if (selector == @selector(stringWithFormat:arguments:))
3858 else if (selector == @selector(getAllSources))
3859 return @"getAllSourcs";
3860 else if (selector == @selector(getKernelNumber:))
3861 return @"getKernelNumber";
3862 else if (selector == @selector(getKernelString:))
3863 return @"getKernelString";
3864 else if (selector == @selector(getInstalledPackages))
3865 return @"getInstalledPackages";
3866 else if (selector == @selector(getIORegistryEntry::))
3867 return @"getIORegistryEntry";
3868 else if (selector == @selector(getLocaleIdentifier))
3869 return @"getLocaleIdentifier";
3870 else if (selector == @selector(getPreferredLanguages))
3871 return @"getPreferredLanguages";
3872 else if (selector == @selector(getPackageById:))
3873 return @"getPackageById";
3874 else if (selector == @selector(getSessionValue:))
3875 return @"getSessionValue";
3876 else if (selector == @selector(installPackages:))
3877 return @"installPackages";
3878 else if (selector == @selector(localizedStringForKey:value:table:))
3880 else if (selector == @selector(popViewController:))
3881 return @"popViewController";
3882 else if (selector == @selector(refreshSources))
3883 return @"refreshSources";
3884 else if (selector == @selector(removeButton))
3885 return @"removeButton";
3886 else if (selector == @selector(setSessionValue::))
3887 return @"setSessionValue";
3888 else if (selector == @selector(substitutePackageNames:))
3889 return @"substitutePackageNames";
3890 else if (selector == @selector(scrollToBottom:))
3891 return @"scrollToBottom";
3892 else if (selector == @selector(setAllowsNavigationAction:))
3893 return @"setAllowsNavigationAction";
3894 else if (selector == @selector(setBadgeValue:))
3895 return @"setBadgeValue";
3896 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3897 return @"setButtonImage";
3898 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3899 return @"setButtonTitle";
3900 else if (selector == @selector(setHidesBackButton:))
3901 return @"setHidesBackButton";
3902 else if (selector == @selector(setHidesNavigationBar:))
3903 return @"setHidesNavigationBar";
3904 else if (selector == @selector(setNavigationBarStyle:))
3905 return @"setNavigationBarStyle";
3906 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3907 return @"setNavigationBarTintColor";
3908 else if (selector == @selector(setPasteboardString:))
3909 return @"setPasteboardString";
3910 else if (selector == @selector(setPasteboardURL:))
3911 return @"setPasteboardURL";
3912 else if (selector == @selector(setToken:))
3914 else if (selector == @selector(setViewportWidth:))
3915 return @"setViewportWidth";
3916 else if (selector == @selector(statfs:))
3918 else if (selector == @selector(supports:))
3920 else if (selector == @selector(unload))
3926 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3927 return [self webScriptNameForSelector:selector] == nil;
3930 - (BOOL) supports:(NSString *)feature {
3931 return [feature isEqualToString:@"window.open"];
3935 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
3938 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3939 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3942 - (NSNumber *) getKernelNumber:(NSString *)name {
3943 const char *string([name UTF8String]);
3946 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3947 return (id) [NSNull null];
3949 if (size != sizeof(int))
3950 return (id) [NSNull null];
3953 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3954 return (id) [NSNull null];
3956 return [NSNumber numberWithInt:value];
3959 - (NSString *) getKernelString:(NSString *)name {
3960 const char *string([name UTF8String]);
3963 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3964 return (id) [NSNull null];
3966 char value[size + 1];
3967 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3968 return (id) [NSNull null];
3970 // XXX: just in case you request something ludicrous
3973 return [NSString stringWithCString:value];
3976 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3977 NSObject *value(CYIOGetValue([path UTF8String], entry));
3980 if ([value isKindOfClass:[NSData class]])
3981 value = CYHex((NSData *) value);
3986 - (id) getSessionValue:(NSString *)key {
3987 @synchronized (SessionData_) {
3988 return [SessionData_ objectForKey:key];
3991 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3992 @synchronized (SessionData_) {
3993 if (value == (id) [WebUndefined undefined])
3994 [SessionData_ removeObjectForKey:key];
3996 [SessionData_ setObject:value forKey:key];
3999 - (void) addBridgedHost:(NSString *)host {
4000 @synchronized (HostConfig_) {
4001 [BridgedHosts_ addObject:host];
4004 - (void) addInsecureHost:(NSString *)host {
4005 @synchronized (HostConfig_) {
4006 [InsecureHosts_ addObject:host];
4009 - (void) addTokenHost:(NSString *)host {
4010 @synchronized (HostConfig_) {
4011 [TokenHosts_ addObject:host];
4014 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4015 @synchronized (HostConfig_) {
4016 if (scheme != (id) [WebUndefined undefined])
4017 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4019 [PipelinedHosts_ addObject:host];
4022 - (void) popViewController:(NSNumber *)value {
4023 if (value == (id) [WebUndefined undefined])
4024 value = [NSNumber numberWithBool:YES];
4025 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4028 - (void) addTrivialSource:(NSString *)href {
4029 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4032 - (void) refreshSources {
4033 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4036 - (NSArray *) getAllSources {
4037 return [[Database sharedInstance] sources];
4040 - (NSArray *) getInstalledPackages {
4041 Database *database([Database sharedInstance]);
4042 @synchronized (database) {
4043 NSArray *packages([database packages]);
4044 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4045 for (Package *package in packages)
4046 if (![package uninstalled])
4047 [installed addObject:package];
4051 - (Package *) getPackageById:(NSString *)id {
4052 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4056 return (Package *) [NSNull null];
4059 - (NSString *) getLocaleIdentifier {
4060 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4063 - (NSArray *) getPreferredLanguages {
4067 - (NSArray *) statfs:(NSString *)path {
4070 if (path == nil || statfs([path UTF8String], &stat) == -1)
4073 return [NSArray arrayWithObjects:
4074 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4075 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4076 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4080 - (NSNumber *) du:(NSString *)path {
4081 NSNumber *value(nil);
4084 _assert(pipe(fds) != -1);
4086 pid_t pid(ExecFork());
4088 _assert(dup2(fds[1], 1) != -1);
4089 _assert(close(fds[0]) != -1);
4090 _assert(close(fds[1]) != -1);
4091 /* XXX: this should probably not use du */
4092 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4097 _assert(close(fds[1]) != -1);
4099 if (FILE *du = fdopen(fds[0], "r")) {
4101 while (fgets(line, sizeof(line), du) != NULL) {
4102 size_t length(strlen(line));
4103 while (length != 0 && line[length - 1] == '\n')
4104 line[--length] = '\0';
4105 if (char *tab = strchr(line, '\t')) {
4107 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4112 } else _assert(close(fds[0]));
4116 if (waitpid(pid, &status, 0) == -1)
4119 else _assert(false);
4125 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4128 - (void) installPackages:(NSArray *)packages {
4129 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4132 - (NSString *) substitutePackageNames:(NSString *)message {
4133 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4134 for (size_t i(0), e([words count]); i != e; ++i) {
4135 NSString *word([words objectAtIndex:i]);
4136 if (Package *package = [[Database sharedInstance] packageWithName:word])
4137 [words replaceObjectAtIndex:i withObject:[package name]];
4140 return [words componentsJoinedByString:@" "];
4143 - (void) removeButton {
4144 [indirect_ removeButton];
4147 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4148 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4151 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4152 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4155 - (void) setBadgeValue:(id)value {
4156 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4159 - (void) setAllowsNavigationAction:(NSString *)value {
4160 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4163 - (void) setHidesBackButton:(NSString *)value {
4164 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4167 - (void) setHidesNavigationBar:(NSString *)value {
4168 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4171 - (void) setNavigationBarStyle:(NSString *)value {
4172 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4175 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4176 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4177 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4178 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4181 - (void) setPasteboardString:(NSString *)value {
4182 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4185 - (void) setPasteboardURL:(NSString *)value {
4186 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4189 - (void) _setToken:(NSString *)token {
4193 [Metadata_ removeObjectForKey:@"Token"];
4195 [Metadata_ setObject:Token_ forKey:@"Token"];
4200 - (void) setToken:(NSString *)token {
4201 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4204 - (void) scrollToBottom:(NSNumber *)animated {
4205 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4208 - (void) setViewportWidth:(float)width {
4209 [indirect_ setViewportWidthOnMainThread:width];
4212 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4213 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4214 unsigned count([arguments count]);
4216 for (unsigned i(0); i != count; ++i)
4217 values[i] = [arguments objectAtIndex:i];
4218 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4221 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4222 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4224 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4226 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4232 @interface NSURL (CydiaSecure)
4235 @implementation NSURL (CydiaSecure)
4237 - (bool) isCydiaSecure {
4238 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4241 @synchronized (HostConfig_) {
4242 if ([InsecureHosts_ containsObject:[self host]])
4251 /* Cydia Browser Controller {{{ */
4252 @implementation CydiaWebViewController
4254 - (NSURL *) navigationURL {
4255 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4258 + (void) initialize {
4259 Diversions_ = [NSMutableSet setWithCapacity:0];
4262 + (void) addDiversion:(Diversion *)diversion {
4263 [Diversions_ addObject:diversion];
4266 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4267 [super webView:view didClearWindowObject:window forFrame:frame];
4269 WebDataSource *source([frame dataSource]);
4270 NSURLResponse *response([source response]);
4271 NSURL *url([response URL]);
4272 NSString *scheme([[url scheme] lowercaseString]);
4274 bool bridged(false);
4276 @synchronized (HostConfig_) {
4277 if ([scheme isEqualToString:@"file"])
4279 else if ([scheme isEqualToString:@"https"])
4280 if ([BridgedHosts_ containsObject:[url host]])
4285 [window setValue:cydia_ forKey:@"cydia"];
4288 - (void) _setupMail:(MFMailComposeViewController *)controller {
4289 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4291 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4292 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4295 - (NSURL *) URLWithURL:(NSURL *)url {
4296 return [Diversion divertURL:url];
4299 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4300 NSURL *url([request URL]);
4301 NSString *host([url host]);
4303 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4305 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4306 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4307 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4308 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4311 @synchronized (HostConfig_) {
4312 token = [TokenHosts_ containsObject:host];
4315 if ([url isCydiaSecure] && token) {
4316 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4317 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4323 - (void) setDelegate:(id)delegate {
4324 [super setDelegate:delegate];
4325 [cydia_ setDelegate:delegate];
4328 - (NSString *) applicationNameForUserAgent {
4329 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4332 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4334 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4335 if (Product_ != nil)
4336 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4342 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4343 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4351 @interface NSObject (CydiaScript)
4352 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4355 @implementation NSObject (CydiaScript)
4357 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4363 @implementation NSArray (CydiaScript)
4365 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4366 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4367 for (size_t i(0), e([self count]); i != e; ++i)
4368 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4374 @implementation NSDictionary (CydiaScript)
4376 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4377 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4379 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4386 /* Confirmation Controller {{{ */
4387 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4388 if (!iterator.end())
4389 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4390 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4392 pkgCache::PkgIterator package(dep.TargetPkg());
4395 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4402 @protocol ConfirmationControllerDelegate
4403 - (void) cancelAndClear:(bool)clear;
4404 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4408 @interface ConfirmationController : CydiaWebViewController {
4409 _transient Database *database_;
4411 _H<UIAlertView> essential_;
4413 _H<NSDictionary> changes_;
4414 _H<NSMutableArray> issues_;
4415 _H<NSDictionary> sizes_;
4420 - (id) initWithDatabase:(Database *)database;
4424 @implementation ConfirmationController
4428 RestartSubstrate_ = true;
4429 [delegate_ confirmWithNavigationController:[self navigationController]];
4432 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4433 NSString *context([alert context]);
4435 if ([context isEqualToString:@"remove"]) {
4436 if (button == [alert cancelButtonIndex])
4437 [self dismissModalViewControllerAnimated:YES];
4438 else if (button == [alert firstOtherButtonIndex]) {
4442 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4443 } else if ([context isEqualToString:@"unable"]) {
4444 [self dismissModalViewControllerAnimated:YES];
4445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4447 [super alertView:alert clickedButtonAtIndex:button];
4451 - (void) _doContinue {
4452 [self dismissModalViewControllerAnimated:YES];
4453 [delegate_ cancelAndClear:NO];
4456 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4457 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4461 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4462 [super webView:view didClearWindowObject:window forFrame:frame];
4464 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4465 (id) changes_, @"changes",
4466 (id) issues_, @"issues",
4467 (id) sizes_, @"sizes",
4469 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4472 - (id) initWithDatabase:(Database *)database {
4473 if ((self = [super init]) != nil) {
4474 database_ = database;
4476 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4477 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4478 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4479 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4480 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4484 pkgCacheFile &cache([database_ cache]);
4485 NSArray *packages([database_ packages]);
4486 pkgDepCache::Policy *policy([database_ policy]);
4488 issues_ = [NSMutableArray arrayWithCapacity:4];
4490 for (Package *package in packages) {
4491 pkgCache::PkgIterator iterator([package iterator]);
4492 NSString *name([package id]);
4494 if ([package broken]) {
4495 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4497 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4499 reasons, @"reasons",
4502 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4506 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4507 pkgCache::DepIterator start;
4508 pkgCache::DepIterator end;
4509 dep.GlobOr(start, end); // ++dep
4511 if (!cache->IsImportantDep(end))
4513 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4516 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4518 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4519 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4520 clauses, @"clauses",
4524 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4526 pkgCache::PkgIterator target(start.TargetPkg());
4527 if (target->ProvidesList != 0)
4528 reason = @"missing";
4530 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4532 reason = @"installed";
4533 installed = [NSString stringWithUTF8String:ver.VerStr()];
4534 } else if (!cache[target].CandidateVerIter(cache).end())
4535 reason = @"uninstalled";
4536 else if (target->ProvidesList == 0)
4537 reason = @"uninstallable";
4539 reason = @"virtual";
4542 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4543 [NSString stringWithUTF8String:start.CompType()], @"operator",
4544 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4547 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4548 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4549 version, @"version",
4551 installed, @"installed",
4554 // yes, seriously. (wtf?)
4562 pkgDepCache::StateCache &state(cache[iterator]);
4564 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4566 if (state.NewInstall())
4567 [installs addObject:name];
4568 // XXX: else if (state.Install())
4569 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4570 [reinstalls addObject:name];
4571 // XXX: move before previous if
4572 else if (state.Upgrade())
4573 [upgrades addObject:name];
4574 else if (state.Downgrade())
4575 [downgrades addObject:name];
4576 else if (!state.Delete())
4577 // XXX: _assert(state.Keep());
4579 else if (special_r(name))
4580 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4581 [NSNull null], @"package",
4582 [NSArray arrayWithObjects:
4583 [NSDictionary dictionaryWithObjectsAndKeys:
4584 @"Conflicts", @"relationship",
4585 [NSArray arrayWithObjects:
4586 [NSDictionary dictionaryWithObjectsAndKeys:
4588 [NSNull null], @"version",
4589 @"installed", @"reason",
4596 if ([package essential])
4598 [removes addObject:name];
4601 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4602 substrate_ |= DepSubstrate(iterator.CurrentVer());
4607 else if (Advanced_) {
4608 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4610 essential_ = [[[UIAlertView alloc]
4611 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4612 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4614 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4616 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4620 [essential_ setContext:@"remove"];
4622 essential_ = [[[UIAlertView alloc]
4623 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4624 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4626 cancelButtonTitle:UCLocalize("OKAY")
4627 otherButtonTitles:nil
4630 [essential_ setContext:@"unable"];
4633 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4634 installs, @"installs",
4635 reinstalls, @"reinstalls",
4636 upgrades, @"upgrades",
4637 downgrades, @"downgrades",
4638 removes, @"removes",
4641 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4642 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4643 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4646 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4650 - (UIBarButtonItem *) leftButton {
4651 return [[[UIBarButtonItem alloc]
4652 initWithTitle:UCLocalize("CANCEL")
4653 style:UIBarButtonItemStylePlain
4655 action:@selector(cancelButtonClicked)
4660 - (void) applyRightButton {
4661 if ([issues_ count] == 0 && ![self isLoading])
4662 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4663 initWithTitle:UCLocalize("CONFIRM")
4664 style:UIBarButtonItemStyleDone
4666 action:@selector(confirmButtonClicked)
4669 [[self navigationItem] setRightBarButtonItem:nil];
4673 - (void) cancelButtonClicked {
4674 [self dismissModalViewControllerAnimated:YES];
4675 [delegate_ cancelAndClear:YES];
4679 - (void) confirmButtonClicked {
4680 if (essential_ != nil)
4690 /* Progress Data {{{ */
4691 @interface CydiaProgressData : NSObject {
4692 _transient id delegate_;
4701 _H<NSMutableArray> events_;
4702 _H<NSString> title_;
4704 _H<NSString> status_;
4705 _H<NSString> finish_;
4710 @implementation CydiaProgressData
4712 + (NSArray *) _attributeKeys {
4713 return [NSArray arrayWithObjects:
4725 - (NSArray *) attributeKeys {
4726 return [[self class] _attributeKeys];
4729 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4730 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4734 if ((self = [super init]) != nil) {
4735 events_ = [NSMutableArray arrayWithCapacity:32];
4739 - (void) setDelegate:(id)delegate {
4740 delegate_ = delegate;
4743 - (void) setPercent:(float)value {
4747 - (NSNumber *) percent {
4748 return [NSNumber numberWithFloat:percent_];
4751 - (void) setCurrent:(float)value {
4755 - (NSNumber *) current {
4756 return [NSNumber numberWithFloat:current_];
4759 - (void) setTotal:(float)value {
4763 - (NSNumber *) total {
4764 return [NSNumber numberWithFloat:total_];
4767 - (void) setSpeed:(float)value {
4771 - (NSNumber *) speed {
4772 return [NSNumber numberWithFloat:speed_];
4775 - (NSArray *) events {
4779 - (void) removeAllEvents {
4780 [events_ removeAllObjects];
4783 - (void) addEvent:(CydiaProgressEvent *)event {
4784 [events_ addObject:event];
4787 - (void) setTitle:(NSString *)text {
4791 - (NSString *) title {
4795 - (void) setFinish:(NSString *)text {
4799 - (NSString *) finish {
4800 return (id) finish_ ?: [NSNull null];
4803 - (void) setRunning:(bool)running {
4807 - (NSNumber *) running {
4808 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4813 /* Progress Controller {{{ */
4814 @interface ProgressController : CydiaWebViewController <
4817 _transient Database *database_;
4818 _H<CydiaProgressData, 1> progress_;
4822 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4824 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4826 - (void) setTitle:(NSString *)title;
4827 - (void) setCancellable:(bool)cancellable;
4831 @implementation ProgressController
4834 [database_ setProgressDelegate:nil];
4838 - (UIBarButtonItem *) leftButton {
4839 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4840 initWithTitle:UCLocalize("CANCEL")
4841 style:UIBarButtonItemStylePlain
4843 action:@selector(cancel)
4844 ] autorelease] : nil;
4847 - (void) updateCancel {
4848 [super applyLeftButton];
4851 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4852 if ((self = [super init]) != nil) {
4853 database_ = database;
4854 delegate_ = delegate;
4856 [database_ setProgressDelegate:self];
4858 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4859 [progress_ setDelegate:self];
4861 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4863 [scroller_ setBackgroundColor:[UIColor blackColor]];
4865 [[self navigationItem] setHidesBackButton:YES];
4867 [self updateCancel];
4871 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4872 [super webView:view didClearWindowObject:window forFrame:frame];
4873 [window setValue:progress_ forKey:@"cydiaProgress"];
4876 - (void) updateProgress {
4877 [self dispatchEvent:@"CydiaProgressUpdate"];
4880 - (void) viewWillAppear:(BOOL)animated {
4881 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4882 [super viewWillAppear:animated];
4886 UpdateExternalStatus(0);
4893 [delegate_ terminateWithSuccess];
4894 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4895 [delegate_ suspendWithAnimation:YES];
4897 [delegate_ suspend];*/
4909 system("/usr/bin/sbreload");
4915 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4916 SBReboot(SBSSpringBoardServerPort());
4918 reboot2(RB_AUTOBOOT);
4925 - (void) setTitle:(NSString *)title {
4926 [progress_ setTitle:title];
4927 [self updateProgress];
4930 - (UIBarButtonItem *) rightButton {
4931 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4932 initWithTitle:UCLocalize("CLOSE")
4933 style:UIBarButtonItemStylePlain
4935 action:@selector(close)
4939 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4940 UpdateExternalStatus(1);
4942 [progress_ setRunning:true];
4943 [self setTitle:title];
4944 // implicit updateProgress
4946 SHA1SumValue notifyconf; {
4948 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4951 MMap mmap(file, MMap::ReadOnly);
4953 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4954 notifyconf = sha1.Result();
4958 SHA1SumValue springlist; {
4960 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4963 MMap mmap(file, MMap::ReadOnly);
4965 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4966 springlist = sha1.Result();
4970 if (invocation != nil) {
4971 [invocation yieldToSelector:@selector(invoke)];
4972 [self setTitle:@"COMPLETE"];
4977 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4980 MMap mmap(file, MMap::ReadOnly);
4982 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4983 if (!(notifyconf == sha1.Result()))
4990 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4993 MMap mmap(file, MMap::ReadOnly);
4995 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4996 if (!(springlist == sha1.Result()))
5002 if (RestartSubstrate_)
5006 RestartSubstrate_ = false;
5009 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5010 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5011 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5012 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5013 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5017 system("su -c /usr/bin/uicache mobile");
5020 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5022 [progress_ setRunning:false];
5023 [self updateProgress];
5025 [self applyRightButton];
5028 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5029 [progress_ addEvent:event];
5030 [self updateProgress];
5033 - (bool) isProgressCancelled {
5034 return cancel_ == 2;
5039 [self updateCancel];
5042 - (void) setCancellable:(bool)cancellable {
5043 unsigned cancel(cancel_);
5047 else if (cancel_ == 0)
5050 if (cancel != cancel_)
5051 [self updateCancel];
5054 - (void) setProgressCancellable:(NSNumber *)cancellable {
5055 [self setCancellable:[cancellable boolValue]];
5058 - (void) setProgressPercent:(NSNumber *)percent {
5059 [progress_ setPercent:[percent floatValue]];
5060 [self updateProgress];
5063 - (void) setProgressStatus:(NSDictionary *)status {
5064 if (status == nil) {
5065 [progress_ setCurrent:0];
5066 [progress_ setTotal:0];
5067 [progress_ setSpeed:0];
5069 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5071 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5072 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5073 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5076 [self updateProgress];
5082 /* Package Cell {{{ */
5083 @interface PackageCell : CyteTableViewCell <
5084 CyteTableViewCellDelegate
5088 _H<NSString> description_;
5090 _H<NSString> source_;
5092 _H<Package> package_;
5093 _H<UIImage> placard_;
5097 - (PackageCell *) init;
5098 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5100 - (void) drawContentRect:(CGRect)rect;
5104 @implementation PackageCell
5106 - (PackageCell *) init {
5107 CGRect frame(CGRectMake(0, 0, 320, 74));
5108 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5109 UIView *content([self contentView]);
5110 CGRect bounds([content bounds]);
5112 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5113 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5114 [content addSubview:content_];
5116 [content_ setDelegate:self];
5117 [content_ setOpaque:YES];
5121 - (NSString *) accessibilityLabel {
5122 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5125 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5126 summarized_ = summary;
5138 Source *source = [package source];
5140 icon_ = [package icon];
5142 if (NSString *name = [package name])
5143 name_ = [NSString stringWithString:name];
5145 NSString *description(nil);
5147 if (description == nil && IsWildcat_)
5148 description = [package longDescription];
5149 if (description == nil)
5150 description = [package shortDescription];
5152 if (description != nil)
5153 description_ = [NSString stringWithString:description];
5155 commercial_ = [package isCommercial];
5159 NSString *label = nil;
5160 bool trusted = false;
5162 if (source != nil) {
5163 label = [source label];
5164 trusted = [source trusted];
5165 } else if ([[package id] isEqualToString:@"firmware"])
5166 label = UCLocalize("APPLE");
5168 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5170 NSString *from(label);
5172 NSString *section = [package simpleSection];
5173 if (section != nil && ![section isEqualToString:label]) {
5174 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5175 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5178 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5180 if (NSString *purpose = [package primaryPurpose])
5181 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5186 if (NSString *mode = [package_ mode]) {
5187 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5188 color = RemovingColor_;
5189 //placard = @"removing";
5191 color = InstallingColor_;
5192 //placard = @"installing";
5195 // XXX: the removing/installing placards are not @2x
5198 color = [UIColor whiteColor];
5200 if ([package installed] != nil)
5201 placard = @"installed";
5206 [content_ setBackgroundColor:color];
5209 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5211 [self setNeedsDisplay];
5212 [content_ setNeedsDisplay];
5215 - (void) drawSummaryContentRect:(CGRect)rect {
5216 bool highlighted(highlighted_);
5217 float width([self bounds].size.width);
5221 rect.size = [(UIImage *) icon_ size];
5223 rect.size.width /= 4;
5224 rect.size.height /= 4;
5226 rect.origin.x = 14 - rect.size.width / 4;
5227 rect.origin.y = 14 - rect.size.height / 4;
5229 [icon_ drawInRect:rect];
5232 if (badge_ != nil) {
5234 rect.size = [(UIImage *) badge_ size];
5236 rect.size.width /= 4;
5237 rect.size.height /= 4;
5239 rect.origin.x = 20 - rect.size.width / 4;
5240 rect.origin.y = 20 - rect.size.height / 4;
5242 [badge_ drawInRect:rect];
5249 UISetColor(commercial_ ? Purple_ : Black_);
5250 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5252 if (placard_ != nil)
5253 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5256 - (void) drawNormalContentRect:(CGRect)rect {
5257 bool highlighted(highlighted_);
5258 float width([self bounds].size.width);
5262 rect.size = [(UIImage *) icon_ size];
5264 rect.size.width /= 2;
5265 rect.size.height /= 2;
5267 rect.origin.x = 25 - rect.size.width / 2;
5268 rect.origin.y = 25 - rect.size.height / 2;
5270 [icon_ drawInRect:rect];
5273 if (badge_ != nil) {
5275 rect.size = [(UIImage *) badge_ size];
5277 rect.size.width /= 2;
5278 rect.size.height /= 2;
5280 rect.origin.x = 36 - rect.size.width / 2;
5281 rect.origin.y = 36 - rect.size.height / 2;
5283 [badge_ drawInRect:rect];
5290 UISetColor(commercial_ ? Purple_ : Black_);
5291 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5292 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5295 UISetColor(commercial_ ? Purplish_ : Gray_);
5296 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5298 if (placard_ != nil)
5299 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5302 - (void) drawContentRect:(CGRect)rect {
5304 [self drawSummaryContentRect:rect];
5306 [self drawNormalContentRect:rect];
5311 /* Section Cell {{{ */
5312 @interface SectionCell : CyteTableViewCell <
5313 CyteTableViewCellDelegate
5315 _H<NSString> basic_;
5316 _H<NSString> section_;
5318 _H<NSString> count_;
5320 _H<UISwitch> switch_;
5324 - (void) setSection:(Section *)section editing:(BOOL)editing;
5328 @implementation SectionCell
5330 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5331 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5332 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5333 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5334 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5336 UIView *content([self contentView]);
5337 CGRect bounds([content bounds]);
5339 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5340 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5341 [content addSubview:content_];
5342 [content_ setBackgroundColor:[UIColor whiteColor]];
5344 [content_ setDelegate:self];
5348 - (void) onSwitch:(id)sender {
5349 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5350 if (metadata == nil) {
5351 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5352 [Sections_ setObject:metadata forKey:basic_];
5355 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5359 - (void) setSection:(Section *)section editing:(BOOL)editing {
5360 if (editing != editing_) {
5362 [switch_ removeFromSuperview];
5364 [self addSubview:switch_];
5373 if (section == nil) {
5374 name_ = UCLocalize("ALL_PACKAGES");
5377 basic_ = [section name];
5378 section_ = [section localized];
5380 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5381 count_ = [NSString stringWithFormat:@"%d", [section count]];
5384 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5387 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5388 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5390 [content_ setNeedsDisplay];
5393 - (void) setFrame:(CGRect)frame {
5394 [super setFrame:frame];
5396 CGRect rect([switch_ frame]);
5397 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5400 - (NSString *) accessibilityLabel {
5404 - (void) drawContentRect:(CGRect)rect {
5405 bool highlighted(highlighted_ && !editing_);
5407 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5412 float width(rect.size.width);
5418 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5420 CGSize size = [count_ sizeWithFont:Font14_];
5424 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5430 /* File Table {{{ */
5431 @interface FileTable : CyteViewController <
5432 UITableViewDataSource,
5435 _transient Database *database_;
5436 _H<Package> package_;
5438 _H<NSMutableArray> files_;
5439 _H<UITableView, 2> list_;
5442 - (id) initWithDatabase:(Database *)database;
5443 - (void) setPackage:(Package *)package;
5447 @implementation FileTable
5449 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5450 return files_ == nil ? 0 : [files_ count];
5453 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5457 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5458 static NSString *reuseIdentifier = @"Cell";
5460 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5462 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5463 [cell setFont:[UIFont systemFontOfSize:16]];
5465 [cell setText:[files_ objectAtIndex:indexPath.row]];
5466 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5471 - (NSURL *) navigationURL {
5472 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5476 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5478 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5479 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5480 [list_ setRowHeight:24.0f];
5481 [(UITableView *) list_ setDataSource:self];
5482 [list_ setDelegate:self];
5483 [[self view] addSubview:list_];
5486 - (void) viewDidLoad {
5487 [super viewDidLoad];
5489 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5492 - (void) releaseSubviews {
5495 [super releaseSubviews];
5498 - (id) initWithDatabase:(Database *)database {
5499 if ((self = [super init]) != nil) {
5500 database_ = database;
5502 files_ = [NSMutableArray arrayWithCapacity:32];
5506 - (void) setPackage:(Package *)package {
5510 [files_ removeAllObjects];
5512 if (package != nil) {
5514 name_ = [package id];
5516 if (NSArray *files = [package files])
5517 [files_ addObjectsFromArray:files];
5519 if ([files_ count] != 0) {
5520 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5521 [files_ removeObjectAtIndex:0];
5522 [files_ sortUsingSelector:@selector(compareByPath:)];
5524 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5525 [stack addObject:@"/"];
5527 for (int i(0), e([files_ count]); i != e; ++i) {
5528 NSString *file = [files_ objectAtIndex:i];
5529 while (![file hasPrefix:[stack lastObject]])
5530 [stack removeLastObject];
5531 NSString *directory = [stack lastObject];
5532 [stack addObject:[file stringByAppendingString:@"/"]];
5533 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5534 ([stack count] - 2) * 3, "",
5535 [file substringFromIndex:[directory length]]
5544 - (void) reloadData {
5547 [self setPackage:[database_ packageWithName:name_]];
5552 /* Package Controller {{{ */
5553 @interface CYPackageController : CydiaWebViewController <
5554 UIActionSheetDelegate
5556 _transient Database *database_;
5557 _H<Package> package_;
5560 _H<NSMutableArray> buttons_;
5561 _H<UIBarButtonItem> button_;
5564 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5568 @implementation CYPackageController
5570 - (NSURL *) navigationURL {
5571 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5574 /* XXX: this is not safe at all... localization of /fail/ */
5575 - (void) _clickButtonWithName:(NSString *)name {
5576 if ([name isEqualToString:UCLocalize("CLEAR")])
5577 [delegate_ clearPackage:package_];
5578 else if ([name isEqualToString:UCLocalize("INSTALL")])
5579 [delegate_ installPackage:package_];
5580 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5581 [delegate_ installPackage:package_];
5582 else if ([name isEqualToString:UCLocalize("REMOVE")])
5583 [delegate_ removePackage:package_];
5584 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5585 [delegate_ installPackage:package_];
5586 else _assert(false);
5589 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5590 NSString *context([sheet context]);
5592 if ([context isEqualToString:@"modify"]) {
5593 if (button != [sheet cancelButtonIndex]) {
5594 NSString *buttonName = [buttons_ objectAtIndex:button];
5595 [self _clickButtonWithName:buttonName];
5598 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5602 - (bool) _allowJavaScriptPanel {
5607 - (void) _customButtonClicked {
5608 int count([buttons_ count]);
5613 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5615 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5616 [buttons addObjectsFromArray:buttons_];
5618 UIActionSheet *sheet = [[[UIActionSheet alloc]
5621 cancelButtonTitle:nil
5622 destructiveButtonTitle:nil
5623 otherButtonTitles:nil
5626 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5628 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5629 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5631 [sheet setContext:@"modify"];
5633 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5637 // We don't want to allow non-commercial packages to do custom things to the install button,
5638 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5639 - (void) customButtonClicked {
5641 [super customButtonClicked];
5643 [self _customButtonClicked];
5646 - (void) reloadButtonClicked {
5647 // Don't reload a commerical package by tapping the loading button,
5648 // but if it's not an Install button, we should forward it on.
5649 if (![package_ uninstalled])
5650 [self _customButtonClicked];
5653 - (void) applyLoadingTitle {
5654 // Don't show "Loading" as the title. Ever.
5657 - (UIBarButtonItem *) rightButton {
5662 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5663 if ((self = [super init]) != nil) {
5664 database_ = database;
5665 buttons_ = [NSMutableArray arrayWithCapacity:4];
5666 name_ = [NSString stringWithString:name];
5667 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5671 - (void) reloadData {
5674 package_ = [database_ packageWithName:name_];
5676 [buttons_ removeAllObjects];
5678 if (package_ != nil) {
5679 [(Package *) package_ parse];
5681 commercial_ = [package_ isCommercial];
5683 if ([package_ mode] != nil)
5684 [buttons_ addObject:UCLocalize("CLEAR")];
5685 if ([package_ source] == nil);
5686 else if ([package_ upgradableAndEssential:NO])
5687 [buttons_ addObject:UCLocalize("UPGRADE")];
5688 else if ([package_ uninstalled])
5689 [buttons_ addObject:UCLocalize("INSTALL")];
5691 [buttons_ addObject:UCLocalize("REINSTALL")];
5692 if (![package_ uninstalled])
5693 [buttons_ addObject:UCLocalize("REMOVE")];
5697 switch ([buttons_ count]) {
5698 case 0: title = nil; break;
5699 case 1: title = [buttons_ objectAtIndex:0]; break;
5700 default: title = UCLocalize("MODIFY"); break;
5703 button_ = [[[UIBarButtonItem alloc]
5705 style:UIBarButtonItemStylePlain
5707 action:@selector(customButtonClicked)
5711 - (bool) isLoading {
5712 return commercial_ ? [super isLoading] : false;
5718 /* Package List Controller {{{ */
5719 @interface PackageListController : CyteViewController <
5720 UITableViewDataSource,
5723 _transient Database *database_;
5725 _H<NSArray> packages_;
5726 _H<NSMutableArray> sections_;
5727 _H<UITableView, 2> list_;
5728 _H<NSMutableArray> index_;
5729 _H<NSMutableDictionary> indices_;
5730 _H<NSString> title_;
5731 unsigned reloading_;
5734 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5735 - (void) setDelegate:(id)delegate;
5736 - (void) resetCursor;
5741 @implementation PackageListController
5743 - (bool) isSummarized {
5747 - (bool) showsSections {
5751 - (void) deselectWithAnimation:(BOOL)animated {
5752 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5755 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5756 CGRect base = [[self view] bounds];
5757 base.size.height -= bounds.size.height;
5758 base.origin = [list_ frame].origin;
5760 [UIView beginAnimations:nil context:NULL];
5761 [UIView setAnimationBeginsFromCurrentState:YES];
5762 [UIView setAnimationCurve:curve];
5763 [UIView setAnimationDuration:duration];
5764 [list_ setFrame:base];
5765 [UIView commitAnimations];
5768 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5769 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5772 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5773 [self resizeForKeyboardBounds:bounds duration:0];
5776 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5777 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5778 *curve = UIViewAnimationCurveEaseInOut;
5780 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5782 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5785 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5788 - (void) keyboardWillShow:(NSNotification *)notification {
5791 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5792 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5794 NSTimeInterval duration;
5795 UIViewAnimationCurve curve;
5796 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5798 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);
5799 UIViewController *base = self;
5800 while ([base parentViewController] != nil)
5801 base = [base parentViewController];
5802 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5803 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5805 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5806 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5808 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5811 - (void) keyboardWillHide:(NSNotification *)notification {
5812 NSTimeInterval duration;
5813 UIViewAnimationCurve curve;
5814 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5816 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5819 - (void) viewWillAppear:(BOOL)animated {
5820 [super viewWillAppear:animated];
5822 [self resizeForKeyboardBounds:CGRectZero];
5823 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5824 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5827 - (void) viewWillDisappear:(BOOL)animated {
5828 [super viewWillDisappear:animated];
5830 [self resizeForKeyboardBounds:CGRectZero];
5831 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5832 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5835 - (void) viewDidAppear:(BOOL)animated {
5836 [super viewDidAppear:animated];
5837 [self deselectWithAnimation:animated];
5840 - (void) didSelectPackage:(Package *)package {
5841 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5842 [view setDelegate:delegate_];
5843 [[self navigationController] pushViewController:view animated:YES];
5846 #if TryIndexedCollation
5847 + (BOOL) hasIndexedCollation {
5848 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5852 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5853 NSInteger count([sections_ count]);
5854 return count == 0 ? 1 : count;
5857 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5858 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5860 return [[sections_ objectAtIndex:section] name];
5863 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5864 if ([sections_ count] == 0)
5866 return [[sections_ objectAtIndex:section] count];
5869 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5870 @synchronized (database_) {
5871 if ([database_ era] != era_)
5874 Section *section([sections_ objectAtIndex:[path section]]);
5875 NSInteger row([path row]);
5876 Package *package([packages_ objectAtIndex:([section row] + row)]);
5877 return [[package retain] autorelease];
5880 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5881 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5883 cell = [[[PackageCell alloc] init] autorelease];
5884 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5888 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5889 Package *package([self packageAtIndexPath:path]);
5890 package = [database_ packageWithName:[package id]];
5891 [self didSelectPackage:package];
5894 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5895 if ([self showsSections])
5901 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5902 #if TryIndexedCollation
5903 if ([[self class] hasIndexedCollation]) {
5904 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5911 - (void) updateHeight {
5912 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5915 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5916 if ((self = [super init]) != nil) {
5917 database_ = database;
5918 title_ = [title copy];
5919 [[self navigationItem] setTitle:title_];
5921 #if TryIndexedCollation
5922 if ([[self class] hasIndexedCollation])
5923 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5926 index_ = [NSMutableArray arrayWithCapacity:32];
5928 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5930 packages_ = [NSArray array];
5931 sections_ = [NSMutableArray arrayWithCapacity:16];
5936 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5938 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5939 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5940 [[self view] addSubview:list_];
5942 // XXX: is 20 the most optimal number here?
5943 [list_ setSectionIndexMinimumDisplayRowCount:20];
5945 [(UITableView *) list_ setDataSource:self];
5946 [list_ setDelegate:self];
5948 [self updateHeight];
5951 - (void) releaseSubviews {
5954 [super releaseSubviews];
5957 - (void) setDelegate:(id)delegate {
5958 delegate_ = delegate;
5961 - (bool) shouldYield {
5965 - (bool) shouldBlock {
5969 - (NSMutableArray *) _reloadPackages {
5970 @synchronized (database_) {
5971 era_ = [database_ era];
5972 NSArray *packages([database_ packages]);
5974 return [NSMutableArray arrayWithArray:packages];
5977 - (void) _reloadData {
5978 if (reloading_ != 0) {
5985 if ([self shouldYield]) {
5989 if (![self shouldBlock])
5992 hud = [delegate_ addProgressHUD];
5993 [hud setText:UCLocalize("LOADING")];
5997 packages = [self yieldToSelector:@selector(_reloadPackages)];
6000 [delegate_ removeProgressHUD:hud];
6001 } while (reloading_ == 2);
6005 packages = [self _reloadPackages];
6008 packages_ = packages;
6010 [indices_ removeAllObjects];
6011 [sections_ removeAllObjects];
6013 Section *section = nil;
6015 #if TryIndexedCollation
6016 if ([[self class] hasIndexedCollation]) {
6017 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6018 NSArray *titles = [collation sectionIndexTitles];
6021 _profile(PackageTable$reloadData$Section)
6022 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6026 _profile(PackageTable$reloadData$Section$Package)
6027 package = [packages_ objectAtIndex:offset];
6028 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6031 while (secidx < index) {
6034 _profile(PackageTable$reloadData$Section$Allocate)
6035 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6038 _profile(PackageTable$reloadData$Section$Add)
6039 [sections_ addObject:section];
6043 [section addToCount];
6049 [index_ removeAllObjects];
6051 bool sectioned([self showsSections]);
6053 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6054 [sections_ addObject:section];
6057 _profile(PackageTable$reloadData$Section)
6058 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6062 _profile(PackageTable$reloadData$Section$Package)
6063 package = [packages_ objectAtIndex:offset];
6064 index = [package index];
6067 if (sectioned && (section == nil || [section index] != index)) {
6068 _profile(PackageTable$reloadData$Section$Allocate)
6069 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6072 [index_ addObject:[section name]];
6073 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6075 _profile(PackageTable$reloadData$Section$Add)
6076 [sections_ addObject:section];
6080 [section addToCount];
6085 [self updateHeight];
6087 _profile(PackageTable$reloadData$List)
6088 [(UITableView *) list_ setDataSource:self];
6093 - (void) reloadData {
6095 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6098 - (void) resetCursor {
6099 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6102 - (void) clearData {
6103 [self updateHeight];
6105 [list_ setDataSource:nil];
6113 /* Filtered Package List Controller {{{ */
6114 @interface FilteredPackageListController : PackageListController {
6117 _H<NSObject> object_;
6120 - (void) setObject:(id)object;
6121 - (void) setObject:(id)object forFilter:(SEL)filter;
6124 - (void) setFilter:(SEL)filter;
6126 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6130 @implementation FilteredPackageListController
6136 - (void) setFilter:(SEL)filter {
6137 @synchronized (self) {
6140 /* XXX: this is an unsafe optimization of doomy hell */
6141 Method method(class_getInstanceMethod([Package class], filter));
6142 _assert(method != NULL);
6143 imp_ = method_getImplementation(method);
6144 _assert(imp_ != NULL);
6147 - (void) setObject:(id)object {
6148 @synchronized (self) {
6152 - (void) setObject:(id)object forFilter:(SEL)filter {
6153 @synchronized (self) {
6154 [self setFilter:filter];
6155 [self setObject:object];
6158 - (NSMutableArray *) _reloadPackages {
6159 @synchronized (database_) {
6160 era_ = [database_ era];
6161 NSArray *packages([database_ packages]);
6163 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6167 _H<NSObject> object;
6169 @synchronized (self) {
6175 _profile(PackageTable$reloadData$Filter)
6176 for (Package *package in packages)
6177 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6178 [filtered addObject:package];
6184 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6185 if ((self = [super initWithDatabase:database title:title]) != nil) {
6186 [self setFilter:filter];
6187 [self setObject:object];
6194 /* Home Controller {{{ */
6195 @interface HomeController : CydiaWebViewController {
6200 @implementation HomeController
6203 if ((self = [super init]) != nil) {
6204 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6209 - (NSURL *) navigationURL {
6210 return [NSURL URLWithString:@"cydia://home"];
6213 - (void) aboutButtonClicked {
6214 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6216 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6217 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6218 [alert setCancelButtonIndex:0];
6221 @"Copyright \u00a9 2008-2011\n"
6224 "Jay Freeman (saurik)\n"
6225 "saurik@saurik.com\n"
6226 "http://www.saurik.com/"
6232 - (UIBarButtonItem *) leftButton {
6233 return [[[UIBarButtonItem alloc]
6234 initWithTitle:UCLocalize("ABOUT")
6235 style:UIBarButtonItemStylePlain
6237 action:@selector(aboutButtonClicked)
6243 /* Manage Controller {{{ */
6244 @interface ManageController : CydiaWebViewController {
6247 - (void) queueStatusDidChange;
6251 @implementation ManageController
6254 if ((self = [super init]) != nil) {
6255 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6259 - (NSURL *) navigationURL {
6260 return [NSURL URLWithString:@"cydia://manage"];
6263 - (UIBarButtonItem *) leftButton {
6264 return [[[UIBarButtonItem alloc]
6265 initWithTitle:UCLocalize("SETTINGS")
6266 style:UIBarButtonItemStylePlain
6268 action:@selector(settingsButtonClicked)
6272 - (void) settingsButtonClicked {
6273 [delegate_ showSettings];
6276 - (void) queueButtonClicked {
6280 - (UIBarButtonItem *) customButton {
6281 return Queuing_ ? [[[UIBarButtonItem alloc]
6282 initWithTitle:UCLocalize("QUEUE")
6283 style:UIBarButtonItemStyleDone
6285 action:@selector(queueButtonClicked)
6286 ] autorelease] : [super customButton];
6289 - (void) queueStatusDidChange {
6290 [self applyRightButton];
6293 - (bool) isLoading {
6294 return !Queuing_ && [super isLoading];
6300 /* Refresh Bar {{{ */
6301 @interface RefreshBar : UINavigationBar {
6302 _H<UIProgressIndicator> indicator_;
6303 _H<UITextLabel> prompt_;
6304 _H<UIProgressBar> progress_;
6305 _H<UINavigationButton> cancel_;
6310 @implementation RefreshBar
6312 - (void) positionViews {
6313 CGRect frame = [cancel_ frame];
6314 frame.size = [cancel_ sizeThatFits:frame.size];
6315 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6316 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6317 [cancel_ setFrame:frame];
6319 CGSize prgsize = {75, 100};
6321 [self frame].size.width - prgsize.width - 10,
6322 ([self frame].size.height - prgsize.height) / 2
6324 [progress_ setFrame:prgrect];
6326 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6327 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6328 CGRect indrect = {{indoffset, indoffset}, indsize};
6329 [indicator_ setFrame:indrect];
6331 CGSize prmsize = {215, indsize.height + 4};
6333 indoffset * 2 + indsize.width,
6334 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6336 [prompt_ setFrame:prmrect];
6339 - (void) setFrame:(CGRect)frame {
6340 [super setFrame:frame];
6341 [self positionViews];
6344 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6345 if ((self = [super initWithFrame:frame]) != nil) {
6346 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6348 [self setBarStyle:UIBarStyleBlack];
6350 UIBarStyle barstyle([self _barStyle:NO]);
6351 bool ugly(barstyle == UIBarStyleDefault);
6353 UIProgressIndicatorStyle style = ugly ?
6354 UIProgressIndicatorStyleMediumBrown :
6355 UIProgressIndicatorStyleMediumWhite;
6357 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6358 [(UIProgressIndicator *) indicator_ setStyle:style];
6359 [indicator_ startAnimation];
6360 [self addSubview:indicator_];
6362 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6363 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6364 [prompt_ setBackgroundColor:[UIColor clearColor]];
6365 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6366 [self addSubview:prompt_];
6368 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6369 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6370 [(UIProgressBar *) progress_ setStyle:0];
6371 [self addSubview:progress_];
6373 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6374 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6375 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6376 [cancel_ setBarStyle:barstyle];
6378 [self positionViews];
6382 - (void) setCancellable:(bool)cancellable {
6384 [self addSubview:cancel_];
6386 [cancel_ removeFromSuperview];
6390 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6391 [progress_ setProgress:0];
6395 [self setCancellable:NO];
6398 - (void) setPrompt:(NSString *)prompt {
6399 [prompt_ setText:prompt];
6402 - (void) setProgress:(float)progress {
6403 [progress_ setProgress:progress];
6409 /* Cydia Navigation Controller Interface {{{ */
6410 @interface UINavigationController (Cydia)
6412 - (NSArray *) navigationURLCollection;
6413 - (void) unloadData;
6418 /* Cydia Tab Bar Controller {{{ */
6419 @interface CYTabBarController : UITabBarController <
6420 UITabBarControllerDelegate,
6423 _transient Database *database_;
6424 _H<RefreshBar, 1> refreshbar_;
6428 // XXX: ok, "updatedelegate_"?...
6429 _transient NSObject<CydiaDelegate> *updatedelegate_;
6431 _H<UIViewController> remembered_;
6432 _transient UIViewController *transient_;
6435 - (NSArray *) navigationURLCollection;
6436 - (void) dropBar:(BOOL)animated;
6437 - (void) beginUpdate;
6438 - (void) raiseBar:(BOOL)animated;
6440 - (void) unloadData;
6444 @implementation CYTabBarController
6446 - (void) setUnselectedViewController:(UIViewController *)transient {
6447 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6448 if (transient != nil) {
6449 if (transient_ == nil)
6450 remembered_ = [controllers objectAtIndex:0];
6451 transient_ = transient;
6452 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6453 [controllers replaceObjectAtIndex:0 withObject:transient_];
6454 [self setSelectedIndex:0];
6455 [self setViewControllers:controllers];
6456 [self concealTabBarSelection];
6457 } else if (remembered_ != nil) {
6458 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6459 transient_ = transient;
6460 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6462 [self setViewControllers:controllers];
6463 [self revealTabBarSelection];
6467 - (UIViewController *) unselectedViewController {
6471 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6472 if ([self unselectedViewController])
6473 [self setUnselectedViewController:nil];
6476 - (NSArray *) navigationURLCollection {
6477 NSMutableArray *items([NSMutableArray array]);
6479 // XXX: Should this deal with transient view controllers?
6480 for (id navigation in [self viewControllers]) {
6481 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6483 [items addObject:stack];
6489 - (void) unloadData {
6492 for (UINavigationController *controller in [self viewControllers])
6493 [controller unloadData];
6495 if (UIViewController *selected = [self selectedViewController])
6496 [selected reloadData];
6498 if (UIViewController *unselected = [self unselectedViewController]) {
6499 [unselected unloadData];
6500 [unselected reloadData];
6505 [[NSNotificationCenter defaultCenter] removeObserver:self];
6510 - (id) initWithDatabase:(Database *)database {
6511 if ((self = [super init]) != nil) {
6512 database_ = database;
6513 [self setDelegate:self];
6515 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6516 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6518 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6522 - (void) setUpdate:(NSDate *)date {
6526 - (void) beginUpdate {
6527 [(RefreshBar *) refreshbar_ start];
6530 [updatedelegate_ retainNetworkActivityIndicator];
6534 detachNewThreadSelector:@selector(performUpdate)
6540 - (void) performUpdate {
6541 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6544 status.setDelegate(self);
6545 [database_ updateWithStatus:status];
6548 performSelectorOnMainThread:@selector(completeUpdate)
6556 - (void) stopUpdateWithSelector:(SEL)selector {
6558 [updatedelegate_ releaseNetworkActivityIndicator];
6560 [self raiseBar:YES];
6563 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6566 - (void) completeUpdate {
6569 [self stopUpdateWithSelector:@selector(reloadData)];
6572 - (void) cancelUpdate {
6573 [self stopUpdateWithSelector:@selector(updateData)];
6576 - (void) cancelPressed {
6577 [self cancelUpdate];
6584 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6585 [refreshbar_ setPrompt:[event compoundMessage]];
6588 - (bool) isProgressCancelled {
6592 - (void) setProgressCancellable:(NSNumber *)cancellable {
6593 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6596 - (void) setProgressPercent:(NSNumber *)percent {
6597 [refreshbar_ setProgress:[percent floatValue]];
6600 - (void) setProgressStatus:(NSDictionary *)status {
6602 [self setProgressPercent:[status objectForKey:@"Percent"]];
6605 - (void) setUpdateDelegate:(id)delegate {
6606 updatedelegate_ = delegate;
6609 - (UIView *) transitionView {
6610 if ([self respondsToSelector:@selector(_transitionView)])
6611 return [self _transitionView];
6613 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6616 - (void) dropBar:(BOOL)animated {
6621 UIView *transition([self transitionView]);
6622 [[self view] addSubview:refreshbar_];
6624 CGRect barframe([refreshbar_ frame]);
6626 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6627 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6629 barframe.origin.y = 0;
6631 [refreshbar_ setFrame:barframe];
6634 [UIView beginAnimations:nil context:NULL];
6636 CGRect viewframe = [transition frame];
6637 viewframe.origin.y += barframe.size.height;
6638 viewframe.size.height -= barframe.size.height;
6639 [transition setFrame:viewframe];
6642 [UIView commitAnimations];
6644 // Ensure bar has the proper width for our view, it might have changed
6645 barframe.size.width = viewframe.size.width;
6646 [refreshbar_ setFrame:barframe];
6649 - (void) raiseBar:(BOOL)animated {
6654 UIView *transition([self transitionView]);
6655 [refreshbar_ removeFromSuperview];
6657 CGRect barframe([refreshbar_ frame]);
6660 [UIView beginAnimations:nil context:NULL];
6662 CGRect viewframe = [transition frame];
6663 viewframe.origin.y -= barframe.size.height;
6664 viewframe.size.height += barframe.size.height;
6665 [transition setFrame:viewframe];
6668 [UIView commitAnimations];
6671 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6672 bool dropped(dropped_);
6677 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6683 - (void) statusBarFrameChanged:(NSNotification *)notification {
6693 /* Cydia Navigation Controller Implementation {{{ */
6694 @implementation UINavigationController (Cydia)
6696 - (NSArray *) navigationURLCollection {
6697 NSMutableArray *stack([NSMutableArray array]);
6699 for (CyteViewController *controller in [self viewControllers]) {
6700 NSString *url = [[controller navigationURL] absoluteString];
6702 [stack addObject:url];
6708 - (void) reloadData {
6711 if (UIViewController *visible = [self visibleViewController])
6712 [visible reloadData];
6715 - (void) unloadData {
6716 for (CyteViewController *page in [self viewControllers])
6725 /* Cydia:// Protocol {{{ */
6726 @interface CydiaURLProtocol : NSURLProtocol {
6731 @implementation CydiaURLProtocol
6733 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6734 NSURL *url([request URL]);
6738 NSString *scheme([[url scheme] lowercaseString]);
6739 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6741 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6747 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6751 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6752 id<NSURLProtocolClient> client([self client]);
6754 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6756 NSData *data(UIImagePNGRepresentation(icon));
6758 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6759 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6760 [client URLProtocol:self didLoadData:data];
6761 [client URLProtocolDidFinishLoading:self];
6765 - (void) startLoading {
6766 id<NSURLProtocolClient> client([self client]);
6767 NSURLRequest *request([self request]);
6769 NSURL *url([request URL]);
6770 NSString *href([url absoluteString]);
6771 NSString *scheme([[url scheme] lowercaseString]);
6775 if ([scheme isEqualToString:@"cydia"])
6776 path = [href substringFromIndex:8];
6777 else if ([scheme isEqualToString:@"about"])
6778 path = [href substringFromIndex:12];
6779 else _assert(false);
6781 NSRange slash([path rangeOfString:@"/"]);
6784 if (slash.location == NSNotFound) {
6788 command = [path substringToIndex:slash.location];
6789 path = [path substringFromIndex:(slash.location + 1)];
6792 Database *database([Database sharedInstance]);
6794 if ([command isEqualToString:@"package-icon"]) {
6797 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6798 Package *package([database packageWithName:path]);
6802 UIImage *icon([package icon]);
6803 [self _returnPNGWithImage:icon forRequest:request];
6804 } else if ([command isEqualToString:@"source-icon"]) {
6807 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6808 NSString *source(Simplify(path));
6809 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6811 icon = [UIImage applicationImageNamed:@"unknown.png"];
6812 [self _returnPNGWithImage:icon forRequest:request];
6813 } else if ([command isEqualToString:@"uikit-image"]) {
6816 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6817 UIImage *icon(_UIImageWithName(path));
6818 [self _returnPNGWithImage:icon forRequest:request];
6819 } else if ([command isEqualToString:@"section-icon"]) {
6822 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6823 NSString *section(Simplify(path));
6824 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6826 icon = [UIImage applicationImageNamed:@"unknown.png"];
6827 [self _returnPNGWithImage:icon forRequest:request];
6829 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6833 - (void) stopLoading {
6839 /* Section Controller {{{ */
6840 @interface SectionController : FilteredPackageListController {
6841 _H<NSString> section_;
6844 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6848 @implementation SectionController
6850 - (NSURL *) navigationURL {
6851 NSString *name = section_;
6855 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6858 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6861 title = UCLocalize("ALL_PACKAGES");
6862 else if (![name isEqual:@""])
6863 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6865 title = UCLocalize("NO_SECTION");
6867 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6874 /* Sections Controller {{{ */
6875 @interface SectionsController : CyteViewController <
6876 UITableViewDataSource,
6879 _transient Database *database_;
6880 _H<NSMutableArray> sections_;
6881 _H<NSMutableArray> filtered_;
6882 _H<UITableView, 2> list_;
6885 - (id) initWithDatabase:(Database *)database;
6886 - (void) editButtonClicked;
6890 @implementation SectionsController
6892 - (NSURL *) navigationURL {
6893 return [NSURL URLWithString:@"cydia://sections"];
6896 - (void) updateNavigationItem {
6897 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6898 if ([sections_ count] == 0) {
6899 [[self navigationItem] setRightBarButtonItem:nil];
6901 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6902 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6904 action:@selector(editButtonClicked)
6905 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6909 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6910 [super setEditing:editing animated:animated];
6915 [delegate_ updateData];
6917 [self updateNavigationItem];
6920 - (void) viewDidAppear:(BOOL)animated {
6921 [super viewDidAppear:animated];
6922 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6925 - (void) viewWillDisappear:(BOOL)animated {
6926 [super viewWillDisappear:animated];
6927 if ([self isEditing]) [self setEditing:NO];
6930 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6931 Section *section = nil;
6932 int index = [indexPath row];
6933 if (![self isEditing]) {
6936 section = [filtered_ objectAtIndex:index];
6938 section = [sections_ objectAtIndex:index];
6943 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6944 if ([self isEditing])
6945 return [sections_ count];
6947 return [filtered_ count] + 1;
6950 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6954 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6955 static NSString *reuseIdentifier = @"SectionCell";
6957 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6959 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6961 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6966 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6967 if ([self isEditing])
6970 Section *section = [self sectionAtIndexPath:indexPath];
6972 SectionController *controller = [[[SectionController alloc]
6973 initWithDatabase:database_
6974 section:[section name]
6976 [controller setDelegate:delegate_];
6978 [[self navigationController] pushViewController:controller animated:YES];
6982 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6984 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6985 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6986 [list_ setRowHeight:45.0f];
6987 [(UITableView *) list_ setDataSource:self];
6988 [list_ setDelegate:self];
6989 [[self view] addSubview:list_];
6992 - (void) viewDidLoad {
6993 [super viewDidLoad];
6995 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6998 - (void) releaseSubviews {
7001 [super releaseSubviews];
7004 - (id) initWithDatabase:(Database *)database {
7005 if ((self = [super init]) != nil) {
7006 database_ = database;
7008 sections_ = [NSMutableArray arrayWithCapacity:16];
7009 filtered_ = [NSMutableArray arrayWithCapacity:16];
7013 - (void) reloadData {
7016 NSArray *packages = [database_ packages];
7018 [sections_ removeAllObjects];
7019 [filtered_ removeAllObjects];
7021 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7024 for (Package *package in packages) {
7025 NSString *name([package section]);
7026 NSString *key(name == nil ? @"" : name);
7030 _profile(SectionsView$reloadData$Section)
7031 section = [sections objectForKey:key];
7032 if (section == nil) {
7033 _profile(SectionsView$reloadData$Section$Allocate)
7034 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7035 [sections setObject:section forKey:key];
7040 [section addToCount];
7042 _profile(SectionsView$reloadData$Filter)
7043 if (![package valid] || ![package visible])
7051 [sections_ addObjectsFromArray:[sections allValues]];
7053 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7055 for (Section *section in (id) sections_) {
7056 size_t count([section row]);
7060 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7061 [section setCount:count];
7062 [filtered_ addObject:section];
7065 [self updateNavigationItem];
7070 - (void) editButtonClicked {
7071 [self setEditing:![self isEditing] animated:YES];
7077 /* Changes Controller {{{ */
7078 @interface ChangesController : CyteViewController <
7079 UITableViewDataSource,
7082 _transient Database *database_;
7084 _H<NSArray> packages_;
7085 _H<NSMutableArray> sections_;
7086 _H<UITableView, 2> list_;
7090 - (id) initWithDatabase:(Database *)database;
7094 @implementation ChangesController
7096 - (NSURL *) navigationURL {
7097 return [NSURL URLWithString:@"cydia://changes"];
7100 - (void) viewDidAppear:(BOOL)animated {
7101 [super viewDidAppear:animated];
7102 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7105 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7106 NSInteger count([sections_ count]);
7107 return count == 0 ? 1 : count;
7110 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7111 if ([sections_ count] == 0)
7113 return [[sections_ objectAtIndex:section] name];
7116 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7117 if ([sections_ count] == 0)
7119 return [[sections_ objectAtIndex:section] count];
7122 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7123 @synchronized (database_) {
7124 if ([database_ era] != era_)
7127 NSUInteger sectionIndex([path section]);
7128 if (sectionIndex >= [sections_ count])
7130 Section *section([sections_ objectAtIndex:sectionIndex]);
7131 NSInteger row([path row]);
7132 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7135 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7136 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7138 cell = [[[PackageCell alloc] init] autorelease];
7139 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7143 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7144 Package *package([self packageAtIndexPath:path]);
7145 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7146 [view setDelegate:delegate_];
7147 [[self navigationController] pushViewController:view animated:YES];
7151 - (void) refreshButtonClicked {
7152 [delegate_ beginUpdate];
7153 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7156 - (void) upgradeButtonClicked {
7157 [delegate_ distUpgrade];
7161 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7163 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7164 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7165 [list_ setRowHeight:73];
7166 [(UITableView *) list_ setDataSource:self];
7167 [list_ setDelegate:self];
7168 [[self view] addSubview:list_];
7171 - (void) viewDidLoad {
7172 [super viewDidLoad];
7174 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7177 - (void) releaseSubviews {
7180 [super releaseSubviews];
7183 - (id) initWithDatabase:(Database *)database {
7184 if ((self = [super init]) != nil) {
7185 database_ = database;
7187 packages_ = [NSArray array];
7188 sections_ = [NSMutableArray arrayWithCapacity:16];
7192 - (NSMutableArray *) _reloadPackages {
7193 @synchronized (database_) {
7194 era_ = [database_ era];
7195 NSArray *packages([database_ packages]);
7197 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7200 _profile(ChangesController$_reloadPackages$Filter)
7201 for (Package *package in packages)
7202 if ([package upgradableAndEssential:YES] || [package visible])
7203 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7206 _profile(ChangesController$_reloadPackages$radixSort)
7207 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7214 - (void) _reloadData {
7219 UIProgressHUD *hud([delegate_ addProgressHUD]);
7220 [hud setText:UCLocalize("LOADING")];
7221 //NSLog(@"HUD:%@::%@", delegate_, hud);
7222 packages = [self yieldToSelector:@selector(_reloadPackages)];
7223 [delegate_ removeProgressHUD:hud];
7225 packages = [self _reloadPackages];
7228 @synchronized (database_) {
7229 if (era_ != [database_ era])
7232 packages_ = packages;
7233 [sections_ removeAllObjects];
7235 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7236 Section *ignored = nil;
7237 Section *section = nil;
7241 bool unseens = false;
7243 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7245 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7246 Package *package = [packages_ objectAtIndex:offset];
7248 BOOL uae = [package upgradableAndEssential:YES];
7252 time_t seen([package seen]);
7254 if (section == nil || last != seen) {
7258 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7261 _profile(ChangesController$reloadData$Allocate)
7262 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7263 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7264 [sections_ addObject:section];
7268 [section addToCount];
7269 } else if ([package ignored]) {
7270 if (ignored == nil) {
7271 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7273 [ignored addToCount];
7276 [upgradable addToCount];
7281 CFRelease(formatter);
7284 Section *last = [sections_ lastObject];
7285 size_t count = [last count];
7286 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7287 [sections_ removeLastObject];
7290 if ([ignored count] != 0)
7291 [sections_ insertObject:ignored atIndex:0];
7293 [sections_ insertObject:upgradable atIndex:0];
7298 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7299 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7300 style:UIBarButtonItemStylePlain
7302 action:@selector(upgradeButtonClicked)
7305 if (![delegate_ updating])
7306 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7307 initWithTitle:UCLocalize("REFRESH")
7308 style:UIBarButtonItemStylePlain
7310 action:@selector(refreshButtonClicked)
7316 - (void) reloadData {
7318 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7323 /* Search Controller {{{ */
7324 @interface SearchController : FilteredPackageListController <
7327 _H<UISearchBar, 1> search_;
7331 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7332 - (void) reloadData;
7336 @implementation SearchController
7338 - (NSURL *) navigationURL {
7339 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7340 return [NSURL URLWithString:@"cydia://search"];
7342 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7345 - (void) useSearch {
7346 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7351 - (void) viewWillAppear:(BOOL)animated {
7352 [super viewWillAppear:animated];
7354 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7358 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7359 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7364 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7365 [search_ resignFirstResponder];
7369 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7370 [search_ setText:@""];
7371 [self searchBarButtonClicked:searchBar];
7374 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7375 [self searchBarButtonClicked:searchBar];
7378 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7379 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7383 - (bool) shouldYield {
7387 - (bool) shouldBlock {
7388 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7391 - (bool) isSummarized {
7392 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7395 - (bool) showsSections {
7399 - (NSMutableArray *) _reloadPackages {
7400 NSMutableArray *packages([super _reloadPackages]);
7401 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7402 [packages radixSortUsingSelector:@selector(rank)];
7406 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7407 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7408 search_ = [[[UISearchBar alloc] init] autorelease];
7409 [search_ setDelegate:self];
7412 [search_ setText:query];
7416 - (void) viewDidAppear:(BOOL)animated {
7417 [super viewDidAppear:animated];
7419 if (!searchloaded_) {
7420 searchloaded_ = YES;
7421 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7422 [search_ layoutSubviews];
7423 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7425 UITextField *textField;
7426 if ([search_ respondsToSelector:@selector(searchField)])
7427 textField = [search_ searchField];
7429 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7431 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7432 [textField setEnablesReturnKeyAutomatically:NO];
7433 [[self navigationItem] setTitleView:textField];
7437 - (void) reloadData {
7438 id object([search_ text]);
7439 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7440 object = [object componentsSeparatedByString:@" "];
7442 [self setObject:object];
7448 - (void) didSelectPackage:(Package *)package {
7449 [search_ resignFirstResponder];
7450 [super didSelectPackage:package];
7455 /* Package Settings Controller {{{ */
7456 @interface PackageSettingsController : CyteViewController <
7457 UITableViewDataSource,
7460 _transient Database *database_;
7462 _H<Package> package_;
7463 _H<UITableView, 2> table_;
7464 _H<UISwitch> subscribedSwitch_;
7465 _H<UISwitch> ignoredSwitch_;
7466 _H<UITableViewCell> subscribedCell_;
7467 _H<UITableViewCell> ignoredCell_;
7470 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7474 @implementation PackageSettingsController
7476 - (NSURL *) navigationURL {
7477 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7480 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7481 if (package_ == nil)
7484 if ([package_ installed] == nil)
7490 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7491 if (package_ == nil)
7494 // both sections contain just one item right now.
7498 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7502 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7504 return UCLocalize("SHOW_ALL_CHANGES_EX");
7506 return UCLocalize("IGNORE_UPGRADES_EX");
7509 - (void) onSubscribed:(id)control {
7510 bool value([control isOn]);
7511 if (package_ == nil)
7513 if ([package_ setSubscribed:value])
7514 [delegate_ updateData];
7517 - (void) _updateIgnored {
7518 const char *package([name_ UTF8String]);
7519 bool on([ignoredSwitch_ isOn]);
7521 pid_t pid(ExecFork());
7523 FILE *dpkg(popen("dpkg --set-selections", "w"));
7524 fwrite(package, strlen(package), 1, dpkg);
7527 fwrite(" hold\n", 6, 1, dpkg);
7529 fwrite(" install\n", 9, 1, dpkg);
7539 int result(waitpid(pid, &status, 0));
7542 _assert(result == pid);
7548 - (void) onIgnored:(id)control {
7549 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7550 [invocation setTarget:self];
7551 [invocation setSelector:@selector(_updateIgnored)];
7553 [delegate_ reloadDataWithInvocation:invocation];
7556 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7557 if (package_ == nil)
7560 switch ([indexPath section]) {
7561 case 0: return subscribedCell_;
7562 case 1: return ignoredCell_;
7571 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7573 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7574 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7575 [(UITableView *) table_ setDataSource:self];
7576 [table_ setDelegate:self];
7577 [[self view] addSubview:table_];
7579 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7580 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7581 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7583 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7584 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7585 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7587 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7588 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7589 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7590 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7592 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7593 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7594 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7595 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7598 - (void) viewDidLoad {
7599 [super viewDidLoad];
7601 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7604 - (void) releaseSubviews {
7606 subscribedCell_ = nil;
7608 ignoredSwitch_ = nil;
7609 subscribedSwitch_ = nil;
7611 [super releaseSubviews];
7614 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7615 if ((self = [super init]) != nil) {
7616 database_ = database;
7621 - (void) reloadData {
7624 package_ = [database_ packageWithName:name_];
7626 if (package_ != nil) {
7627 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7628 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7629 } // XXX: what now, G?
7631 [table_ reloadData];
7637 /* Installed Controller {{{ */
7638 @interface InstalledController : FilteredPackageListController {
7642 - (id) initWithDatabase:(Database *)database;
7644 - (void) updateRoleButton;
7645 - (void) queueStatusDidChange;
7649 @implementation InstalledController
7651 - (NSURL *) navigationURL {
7652 return [NSURL URLWithString:@"cydia://installed"];
7655 - (id) initWithDatabase:(Database *)database {
7656 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7657 [self updateRoleButton];
7658 [self queueStatusDidChange];
7663 - (void) queueButtonClicked {
7668 - (void) queueStatusDidChange {
7672 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7673 initWithTitle:UCLocalize("QUEUE")
7674 style:UIBarButtonItemStyleDone
7676 action:@selector(queueButtonClicked)
7679 [[self navigationItem] setLeftBarButtonItem:nil];
7685 - (void) updateRoleButton {
7686 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7687 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7688 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7689 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7691 action:@selector(roleButtonClicked)
7695 - (void) roleButtonClicked {
7696 [self setObject:[NSNumber numberWithBool:expert_]];
7700 [self updateRoleButton];
7706 /* Source Cell {{{ */
7707 @interface SourceCell : CyteTableViewCell <
7708 CyteTableViewCellDelegate
7711 _H<NSString> origin_;
7712 _H<NSString> label_;
7715 - (void) setSource:(Source *)source;
7719 @implementation SourceCell
7721 - (void) _setImage:(UIImage *)image {
7723 [content_ setNeedsDisplay];
7726 - (void) _setSource:(Source *)source {
7727 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7729 if (NSString *base = [source base])
7730 if ([base length] != 0) {
7731 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7733 if (NSData *data = [NSURLConnection
7734 sendSynchronousRequest:[NSURLRequest
7736 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7740 returningResponse:NULL
7743 if (UIImage *image = [UIImage imageWithData:data])
7744 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7750 - (void) setSource:(Source *)source {
7751 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7753 origin_ = [source name];
7754 label_ = [source uri];
7756 [content_ setNeedsDisplay];
7758 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7761 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7762 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7763 UIView *content([self contentView]);
7764 CGRect bounds([content bounds]);
7766 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7767 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7768 [content_ setBackgroundColor:[UIColor whiteColor]];
7769 [content addSubview:content_];
7771 [content_ setDelegate:self];
7772 [content_ setOpaque:YES];
7776 - (NSString *) accessibilityLabel {
7780 - (void) drawContentRect:(CGRect)rect {
7781 bool highlighted(highlighted_);
7782 float width(rect.size.width);
7785 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7792 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7796 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7801 /* Source Controller {{{ */
7802 @interface SourceController : FilteredPackageListController {
7803 _transient Source *source_;
7807 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7811 @implementation SourceController
7813 - (NSURL *) navigationURL {
7814 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7817 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7818 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7820 key_ = [source key];
7824 - (void) reloadData {
7825 source_ = [database_ sourceWithKey:key_];
7826 key_ = [source_ key];
7827 [self setObject:source_];
7829 [[self navigationItem] setTitle:[source_ label]];
7836 /* Sources Controller {{{ */
7837 @interface SourcesController : CyteViewController <
7838 UITableViewDataSource,
7841 _transient Database *database_;
7842 _H<UITableView, 2> list_;
7843 _H<NSMutableArray> sources_;
7847 _H<UIProgressHUD> hud_;
7850 //NSURLConnection *installer_;
7851 NSURLConnection *trivial_;
7852 NSURLConnection *trivial_bz2_;
7853 NSURLConnection *trivial_gz_;
7854 //NSURLConnection *automatic_;
7859 - (id) initWithDatabase:(Database *)database;
7860 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7864 @implementation SourcesController
7866 - (void) _releaseConnection:(NSURLConnection *)connection {
7867 if (connection != nil) {
7868 [connection cancel];
7869 //[connection setDelegate:nil];
7870 [connection release];
7875 //[self _releaseConnection:installer_];
7876 [self _releaseConnection:trivial_];
7877 [self _releaseConnection:trivial_gz_];
7878 [self _releaseConnection:trivial_bz2_];
7879 //[self _releaseConnection:automatic_];
7884 - (NSURL *) navigationURL {
7885 return [NSURL URLWithString:@"cydia://sources"];
7888 - (void) viewDidAppear:(BOOL)animated {
7889 [super viewDidAppear:animated];
7890 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7893 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7894 return offset_ == 0 ? 1 : 2;
7897 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7898 switch (section + (offset_ == 0 ? 1 : 0)) {
7899 case 0: return UCLocalize("ENTERED_BY_USER");
7900 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7906 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7907 int count = [sources_ count];
7909 case 0: return (offset_ == 0 ? count : offset_);
7910 case 1: return count - offset_;
7916 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7918 switch (indexPath.section) {
7919 case 0: idx = indexPath.row; break;
7920 case 1: idx = indexPath.row + offset_; break;
7924 return [sources_ objectAtIndex:idx];
7927 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7928 static NSString *cellIdentifier = @"SourceCell";
7930 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7931 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7932 [cell setSource:[self sourceAtIndexPath:indexPath]];
7933 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7938 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7939 Source *source = [self sourceAtIndexPath:indexPath];
7941 SourceController *controller = [[[SourceController alloc]
7942 initWithDatabase:database_
7946 [controller setDelegate:delegate_];
7948 [[self navigationController] pushViewController:controller animated:YES];
7951 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7952 Source *source = [self sourceAtIndexPath:indexPath];
7953 return [source record] != nil;
7956 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7957 if (editingStyle == UITableViewCellEditingStyleDelete) {
7958 Source *source = [self sourceAtIndexPath:indexPath];
7959 [Sources_ removeObjectForKey:[source key]];
7960 [delegate_ syncData];
7965 [delegate_ addTrivialSource:href_];
7966 [delegate_ syncData];
7969 - (NSString *) getWarning {
7970 NSString *href(href_);
7971 NSRange colon([href rangeOfString:@"://"]);
7972 if (colon.location != NSNotFound)
7973 href = [href substringFromIndex:(colon.location + 3)];
7974 href = [href stringByAddingPercentEscapes];
7975 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7976 href = [href stringByCachingURLWithCurrentCDN];
7978 NSURL *url([NSURL URLWithString:href]);
7980 NSStringEncoding encoding;
7981 NSError *error(nil);
7983 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7984 return [warning length] == 0 ? nil : warning;
7988 - (void) _endConnection:(NSURLConnection *)connection {
7989 // XXX: the memory management in this method is horribly awkward
7991 NSURLConnection **field = NULL;
7992 if (connection == trivial_)
7994 else if (connection == trivial_bz2_)
7995 field = &trivial_bz2_;
7996 else if (connection == trivial_gz_)
7997 field = &trivial_gz_;
7998 _assert(field != NULL);
7999 [connection release];
8004 trivial_bz2_ == nil &&
8007 [delegate_ releaseNetworkActivityIndicator];
8009 [delegate_ removeProgressHUD:hud_];
8015 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8018 UIAlertView *alert = [[[UIAlertView alloc]
8019 initWithTitle:UCLocalize("SOURCE_WARNING")
8022 cancelButtonTitle:UCLocalize("CANCEL")
8024 UCLocalize("ADD_ANYWAY"),
8028 [alert setContext:@"warning"];
8029 [alert setNumberOfRows:1];
8033 } else if (error_ != nil) {
8034 UIAlertView *alert = [[[UIAlertView alloc]
8035 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8036 message:[error_ localizedDescription]
8038 cancelButtonTitle:UCLocalize("OK")
8039 otherButtonTitles:nil
8042 [alert setContext:@"urlerror"];
8045 UIAlertView *alert = [[[UIAlertView alloc]
8046 initWithTitle:UCLocalize("NOT_REPOSITORY")
8047 message:UCLocalize("NOT_REPOSITORY_EX")
8049 cancelButtonTitle:UCLocalize("OK")
8050 otherButtonTitles:nil
8053 [alert setContext:@"trivial"];
8062 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8063 switch ([response statusCode]) {
8069 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8070 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8072 [self _endConnection:connection];
8075 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8076 [self _endConnection:connection];
8079 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8080 NSURL *url([NSURL URLWithString:href]);
8082 NSMutableURLRequest *request = [NSMutableURLRequest
8084 cachePolicy:NSURLRequestUseProtocolCachePolicy
8085 timeoutInterval:120.0
8088 [request setHTTPMethod:method];
8090 if (Machine_ != NULL)
8091 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8093 if ([url isCydiaSecure]) {
8094 if (UniqueID_ != nil)
8095 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8098 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8101 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8102 NSString *context([alert context]);
8104 if ([context isEqualToString:@"source"]) {
8107 NSString *href = [[alert textField] text];
8109 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8111 if (![href hasSuffix:@"/"])
8112 href_ = [href stringByAppendingString:@"/"];
8116 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8117 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8118 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8119 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8123 // XXX: this is stupid
8124 hud_ = [delegate_ addProgressHUD];
8125 [hud_ setText:UCLocalize("VERIFYING_URL")];
8126 [delegate_ retainNetworkActivityIndicator];
8135 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8136 } else if ([context isEqualToString:@"trivial"])
8137 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8138 else if ([context isEqualToString:@"urlerror"])
8139 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8140 else if ([context isEqualToString:@"warning"]) {
8154 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8159 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8161 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8162 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8163 [list_ setRowHeight:56];
8164 [(UITableView *) list_ setDataSource:self];
8165 [list_ setDelegate:self];
8166 [[self view] addSubview:list_];
8169 - (void) viewDidLoad {
8170 [super viewDidLoad];
8172 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8173 [self updateButtonsForEditingStatus:NO animated:NO];
8176 - (void) releaseSubviews {
8179 [super releaseSubviews];
8182 - (id) initWithDatabase:(Database *)database {
8183 if ((self = [super init]) != nil) {
8184 database_ = database;
8185 sources_ = [NSMutableArray arrayWithCapacity:16];
8189 - (void) reloadData {
8193 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8196 [sources_ removeAllObjects];
8197 [sources_ addObjectsFromArray:[database_ sources]];
8199 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8202 int count([sources_ count]);
8204 for (int i = 0; i != count; i++) {
8205 if ([[sources_ objectAtIndex:i] record] == nil)
8210 [list_ setEditing:NO];
8211 [self updateButtonsForEditingStatus:NO animated:NO];
8215 - (void) showAddSourcePrompt {
8216 UIAlertView *alert = [[[UIAlertView alloc]
8217 initWithTitle:UCLocalize("ENTER_APT_URL")
8220 cancelButtonTitle:UCLocalize("CANCEL")
8222 UCLocalize("ADD_SOURCE"),
8226 [alert setContext:@"source"];
8228 [alert setNumberOfRows:1];
8229 [alert addTextFieldWithValue:@"http://" label:@""];
8231 UITextInputTraits *traits = [[alert textField] textInputTraits];
8232 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8233 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8234 [traits setKeyboardType:UIKeyboardTypeURL];
8235 // XXX: UIReturnKeyDone
8236 [traits setReturnKeyType:UIReturnKeyNext];
8241 - (void) addButtonClicked {
8242 [self showAddSourcePrompt];
8245 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8246 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8247 initWithTitle:UCLocalize("ADD")
8248 style:UIBarButtonItemStylePlain
8250 action:@selector(addButtonClicked)
8251 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8253 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8254 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8255 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8257 action:@selector(editButtonClicked)
8258 ] autorelease] animated:animated];
8260 if (IsWildcat_ && !editing)
8261 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8262 initWithTitle:UCLocalize("SETTINGS")
8263 style:UIBarButtonItemStylePlain
8265 action:@selector(settingsButtonClicked)
8269 - (void) settingsButtonClicked {
8270 [delegate_ showSettings];
8273 - (void) editButtonClicked {
8274 [list_ setEditing:![list_ isEditing] animated:YES];
8276 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8282 /* Settings Controller {{{ */
8283 @interface SettingsController : CyteViewController <
8284 UITableViewDataSource,
8287 _transient Database *database_;
8288 // XXX: ok, "roledelegate_"?...
8289 _transient id roledelegate_;
8290 _H<UITableView, 2> table_;
8291 _H<UISegmentedControl> segment_;
8292 _H<UIView> container_;
8295 - (void) showDoneButton;
8296 - (void) resizeSegmentedControl;
8300 @implementation SettingsController
8303 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8305 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8306 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8307 [table_ setDelegate:self];
8308 [(UITableView *) table_ setDataSource:self];
8309 [[self view] addSubview:table_];
8311 NSArray *items = [NSArray arrayWithObjects:
8313 UCLocalize("HACKER"),
8314 UCLocalize("DEVELOPER"),
8316 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8317 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8318 [container_ addSubview:segment_];
8321 - (void) viewDidLoad {
8322 [super viewDidLoad];
8324 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8327 if ([Role_ isEqualToString:@"User"]) index = 0;
8328 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8329 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8331 [segment_ setSelectedSegmentIndex:index];
8332 [self showDoneButton];
8335 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8336 [self resizeSegmentedControl];
8339 - (void) releaseSubviews {
8344 [super releaseSubviews];
8347 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8348 if ((self = [super init]) != nil) {
8349 database_ = database;
8350 roledelegate_ = delegate;
8354 - (void) resizeSegmentedControl {
8355 CGFloat width = [[self view] frame].size.width;
8356 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8359 - (void) viewWillAppear:(BOOL)animated {
8360 [super viewWillAppear:animated];
8362 [self resizeSegmentedControl];
8365 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8366 [self resizeSegmentedControl];
8369 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8370 [self resizeSegmentedControl];
8374 NSString *role(nil);
8376 switch ([segment_ selectedSegmentIndex]) {
8377 case 0: role = @"User"; break;
8378 case 1: role = @"Hacker"; break;
8379 case 2: role = @"Developer"; break;
8384 if (![role isEqualToString:Role_]) {
8385 bool rolling(Role_ == nil);
8388 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8392 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8396 [roledelegate_ loadData];
8398 [roledelegate_ updateData];
8402 - (void) segmentChanged:(UISegmentedControl *)control {
8403 [self showDoneButton];
8406 - (void) saveAndClose {
8409 [[self navigationItem] setRightBarButtonItem:nil];
8410 [[self navigationController] dismissModalViewControllerAnimated:YES];
8413 - (void) doneButtonClicked {
8414 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8415 [spinner startAnimating];
8416 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8417 [[self navigationItem] setRightBarButtonItem:spinItem];
8419 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8422 - (void) showDoneButton {
8423 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8424 initWithTitle:UCLocalize("DONE")
8425 style:UIBarButtonItemStyleDone
8427 action:@selector(doneButtonClicked)
8428 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8431 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8432 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8436 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8440 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8441 return nil; // This method is required by the protocol.
8444 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8446 return UCLocalize("ROLE_EX");
8448 return [NSString stringWithFormat:
8449 @"%@: %@\n%@: %@\n%@: %@",
8450 UCLocalize("USER"), UCLocalize("USER_EX"),
8451 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8452 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8457 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8458 return section == 3 ? 44.0f : 0;
8461 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8462 return section == 3 ? container_ : nil;
8465 - (void) reloadData {
8468 [table_ reloadData];
8473 /* Stash Controller {{{ */
8474 @interface StashController : CyteViewController {
8475 _H<UIActivityIndicatorView> spinner_;
8476 _H<UILabel> status_;
8477 _H<UILabel> caption_;
8482 @implementation StashController
8485 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8486 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8488 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8489 CGRect spinrect = [spinner_ frame];
8490 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8491 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8492 [spinner_ setFrame:spinrect];
8493 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8494 [[self view] addSubview:spinner_];
8495 [spinner_ startAnimating];
8498 captrect.size.width = [[self view] frame].size.width;
8499 captrect.size.height = 40.0f;
8500 captrect.origin.x = 0;
8501 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8502 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8503 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8504 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8505 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8506 [caption_ setTextColor:[UIColor whiteColor]];
8507 [caption_ setBackgroundColor:[UIColor clearColor]];
8508 [caption_ setShadowColor:[UIColor blackColor]];
8509 [caption_ setTextAlignment:UITextAlignmentCenter];
8510 [[self view] addSubview:caption_];
8513 statusrect.size.width = [[self view] frame].size.width;
8514 statusrect.size.height = 30.0f;
8515 statusrect.origin.x = 0;
8516 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8517 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8518 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8519 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8520 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8521 [status_ setTextColor:[UIColor whiteColor]];
8522 [status_ setBackgroundColor:[UIColor clearColor]];
8523 [status_ setShadowColor:[UIColor blackColor]];
8524 [status_ setTextAlignment:UITextAlignmentCenter];
8525 [[self view] addSubview:status_];
8528 - (void) releaseSubviews {
8533 [super releaseSubviews];
8539 @interface CYURLCache : SDURLCache {
8544 @implementation CYURLCache
8546 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8549 else if ([event isEqualToString:@"no-cache"])
8551 else if ([event isEqualToString:@"store"])
8553 else if ([event isEqualToString:@"invalid"])
8555 else if ([event isEqualToString:@"memory"])
8557 else if ([event isEqualToString:@"disk"])
8559 else if ([event isEqualToString:@"miss"])
8562 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8566 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8567 if (NSURLResponse *response = [cached response])
8568 if (NSString *mime = [response MIMEType])
8569 if ([mime isEqualToString:@"text/cache-manifest"]) {
8570 NSURL *url([response URL]);
8573 NSLog(@"###: %@", [url absoluteString]);
8576 @synchronized (HostConfig_) {
8577 [CachedURLs_ addObject:url];
8581 [super storeCachedResponse:cached forRequest:request];
8586 @interface Cydia : UIApplication <
8587 ConfirmationControllerDelegate,
8590 UINavigationControllerDelegate,
8591 UITabBarControllerDelegate
8593 _H<UIWindow> window_;
8594 _H<CYTabBarController> tabbar_;
8595 _H<CydiaLoadingViewController> emulated_;
8597 _H<NSMutableArray> essential_;
8598 _H<NSMutableArray> broken_;
8600 Database *database_;
8602 _H<NSURL> starturl_;
8607 _H<StashController> stash_;
8616 @implementation Cydia
8618 - (void) beginUpdate {
8619 [tabbar_ beginUpdate];
8623 return [tabbar_ updating];
8627 if ([broken_ count] != 0) {
8628 int count = [broken_ count];
8630 UIAlertView *alert = [[[UIAlertView alloc]
8631 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8632 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8634 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8636 UCLocalize("TEMPORARY_IGNORE"),
8640 [alert setContext:@"fixhalf"];
8641 [alert setNumberOfRows:2];
8643 } else if (!Ignored_ && [essential_ count] != 0) {
8644 int count = [essential_ count];
8646 UIAlertView *alert = [[[UIAlertView alloc]
8647 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8648 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8650 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8652 UCLocalize("UPGRADE_ESSENTIAL"),
8653 UCLocalize("COMPLETE_UPGRADE"),
8657 [alert setContext:@"upgrade"];
8662 - (void) _saveConfig {
8668 NSString *error(nil);
8670 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8672 NSError *error(nil);
8673 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8674 NSLog(@"failure to save metadata data: %@", error);
8679 NSLog(@"failure to serialize metadata: %@", error);
8684 // Navigation controller for the queuing badge.
8685 - (UINavigationController *) queueNavigationController {
8686 NSArray *controllers = [tabbar_ viewControllers];
8687 return [controllers objectAtIndex:3];
8690 - (void) unloadData {
8691 [tabbar_ unloadData];
8694 - (void) _updateData {
8699 UINavigationController *navigation = [self queueNavigationController];
8701 id queuedelegate = nil;
8702 if ([[navigation viewControllers] count] > 0)
8703 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8705 [queuedelegate queueStatusDidChange];
8706 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8709 - (void) _refreshIfPossible:(NSDate *)update {
8710 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8712 bool recently = false;
8713 if (update != nil) {
8714 NSTimeInterval interval([update timeIntervalSinceNow]);
8715 if (interval <= 0 && interval > -(15*60))
8719 // Don't automatic refresh if:
8720 // - We already refreshed recently.
8721 // - We already auto-refreshed this launch.
8722 // - Auto-refresh is disabled.
8723 if (recently || loaded_ || ManualRefresh) {
8724 // If we are cancelling, we need to make sure it knows it's already loaded.
8727 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8729 // We are going to load, so remember that.
8732 SCNetworkReachabilityFlags flags; {
8733 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8734 SCNetworkReachabilityGetFlags(reachability, &flags);
8735 CFRelease(reachability);
8738 // XXX: this elaborate mess is what Apple is using to determine this? :(
8739 // XXX: do we care if the user has to intervene? maybe that's ok?
8741 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8742 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8743 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8744 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8745 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8746 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8750 // If we can reach the server, auto-refresh!
8752 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8758 - (void) refreshIfPossible {
8759 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8762 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8763 @synchronized (self) {
8764 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8765 [hud setText:UCLocalize("RELOADING_DATA")];
8767 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8770 [self removeProgressHUD:hud];
8774 [essential_ removeAllObjects];
8775 [broken_ removeAllObjects];
8777 NSArray *packages([database_ packages]);
8778 for (Package *package in packages) {
8780 [broken_ addObject:package];
8781 if ([package upgradableAndEssential:NO]) {
8782 if ([package essential])
8783 [essential_ addObject:package];
8788 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8791 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8792 [changesItem setBadgeValue:badge];
8793 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8794 [self setApplicationIconBadgeNumber:changes];
8797 [changesItem setBadgeValue:nil];
8798 [changesItem setAnimatedBadge:NO];
8799 [self setApplicationIconBadgeNumber:0];
8804 [self refreshIfPossible];
8807 - (void) updateData {
8813 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8816 - (void) disemulate {
8817 if (emulated_ == nil)
8820 [window_ addSubview:[tabbar_ view]];
8821 [[emulated_ view] removeFromSuperview];
8823 [window_ setUserInteractionEnabled:YES];
8826 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8827 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8829 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8831 UIViewController *parent;
8832 if (emulated_ == nil)
8841 [parent presentModalViewController:navigation animated:YES];
8844 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8845 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8847 if (navigation != nil)
8848 [navigation pushViewController:progress animated:YES];
8850 [self presentModalViewController:progress force:YES];
8852 [progress invoke:invocation withTitle:title];
8856 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8857 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8860 - (void) repairWithInvocation:(NSInvocation *)invocation {
8862 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8866 - (void) repairWithSelector:(SEL)selector {
8867 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8870 - (void) reloadData {
8871 [self reloadDataWithInvocation:nil];
8877 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8878 _assert(file != NULL);
8880 for (NSString *key in [Sources_ allKeys]) {
8881 NSDictionary *source([Sources_ objectForKey:key]);
8883 fprintf(file, "%s %s %s\n",
8884 [[source objectForKey:@"Type"] UTF8String],
8885 [[source objectForKey:@"URI"] UTF8String],
8886 [[source objectForKey:@"Distribution"] UTF8String]
8892 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8895 - (void) addTrivialSource:(NSString *)href {
8896 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8899 @"./", @"Distribution",
8900 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8906 pkgProblemResolver *resolver = [database_ resolver];
8908 resolver->InstallProtect();
8909 if (!resolver->Resolve(true))
8914 // XXX: this is a really crappy way of doing this.
8915 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8916 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8917 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8918 if ([tabbar_ updating])
8919 [tabbar_ cancelUpdate];
8921 if (![database_ prepare])
8924 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8925 [page setDelegate:self];
8926 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8929 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8930 [tabbar_ presentModalViewController:confirm_ animated:YES];
8936 @synchronized (self) {
8941 - (void) clearPackage:(Package *)package {
8942 @synchronized (self) {
8949 - (void) installPackages:(NSArray *)packages {
8950 @synchronized (self) {
8951 for (Package *package in packages)
8958 - (void) installPackage:(Package *)package {
8959 @synchronized (self) {
8966 - (void) removePackage:(Package *)package {
8967 @synchronized (self) {
8974 - (void) distUpgrade {
8975 @synchronized (self) {
8976 if (![database_ upgrade])
8983 [database_ perform];
8984 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8987 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8990 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8994 - (void) showSettings {
8995 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8998 - (void) retainNetworkActivityIndicator {
8999 if (activity_++ == 0)
9000 [self setNetworkActivityIndicatorVisible:YES];
9003 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9007 - (void) releaseNetworkActivityIndicator {
9008 if (--activity_ == 0)
9009 [self setNetworkActivityIndicatorVisible:NO];
9012 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9017 - (void) cancelAndClear:(bool)clear {
9018 @synchronized (self) {
9030 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9031 NSString *context([alert context]);
9033 if ([context isEqualToString:@"conffile"]) {
9034 FILE *input = [database_ input];
9035 if (button == [alert cancelButtonIndex])
9036 fprintf(input, "N\n");
9037 else if (button == [alert firstOtherButtonIndex])
9038 fprintf(input, "Y\n");
9041 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9042 } else if ([context isEqualToString:@"fixhalf"]) {
9043 if (button == [alert cancelButtonIndex]) {
9044 @synchronized (self) {
9045 for (Package *broken in (id) broken_) {
9048 NSString *id = [broken id];
9049 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9050 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9051 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9052 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9058 } else if (button == [alert firstOtherButtonIndex]) {
9059 [broken_ removeAllObjects];
9063 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9064 } else if ([context isEqualToString:@"upgrade"]) {
9065 if (button == [alert firstOtherButtonIndex]) {
9066 @synchronized (self) {
9067 for (Package *essential in (id) essential_)
9068 [essential install];
9073 } else if (button == [alert firstOtherButtonIndex] + 1) {
9075 } else if (button == [alert cancelButtonIndex]) {
9079 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9083 - (void) system:(NSString *)command {
9084 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9087 system([command UTF8String]);
9093 - (void) applicationWillSuspend {
9095 [super applicationWillSuspend];
9098 - (BOOL) isSafeToSuspend {
9101 NSLog(@"isSafeToSuspend: locked_ != 0");
9106 // Use external process status API internally.
9107 // This is probably a really bad idea.
9108 // XXX: what is the point of this? does this solve anything at all?
9109 uint64_t status = 0;
9111 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9112 notify_get_state(notify_token, &status);
9113 notify_cancel(notify_token);
9118 NSLog(@"isSafeToSuspend: status != 0");
9124 NSLog(@"isSafeToSuspend: -> true");
9129 - (void) applicationSuspend:(__GSEvent *)event {
9130 if ([self isSafeToSuspend])
9131 [super applicationSuspend:event];
9134 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9135 if ([self isSafeToSuspend])
9136 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9139 - (void) _setSuspended:(BOOL)value {
9140 if ([self isSafeToSuspend])
9141 [super _setSuspended:value];
9144 - (UIProgressHUD *) addProgressHUD {
9145 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9146 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9148 [window_ setUserInteractionEnabled:NO];
9150 UIViewController *target(tabbar_);
9151 if (UIViewController *modal = [target modalViewController])
9154 UIView *view([target view]);
9155 [view addSubview:hud];
9163 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9166 [hud removeFromSuperview];
9167 [window_ setUserInteractionEnabled:YES];
9170 - (CyteViewController *) pageForPackage:(NSString *)name {
9171 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9174 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9175 NSString *scheme([[url scheme] lowercaseString]);
9176 if ([[url absoluteString] length] <= [scheme length] + 3)
9178 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9179 NSArray *components([path pathComponents]);
9181 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9182 return [self pageForPackage:[components objectAtIndex:1]];
9184 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9187 NSString *base([components objectAtIndex:0]);
9189 CyteViewController *controller = nil;
9191 if ([base isEqualToString:@"url"]) {
9192 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9193 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9194 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9195 } else if (!external && [components count] == 1) {
9196 if ([base isEqualToString:@"manage"]) {
9197 controller = [[[ManageController alloc] init] autorelease];
9200 if ([base isEqualToString:@"sources"]) {
9201 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9204 if ([base isEqualToString:@"home"]) {
9205 controller = [[[HomeController alloc] init] autorelease];
9208 if ([base isEqualToString:@"sections"]) {
9209 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9212 if ([base isEqualToString:@"search"]) {
9213 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9216 if ([base isEqualToString:@"changes"]) {
9217 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9220 if ([base isEqualToString:@"installed"]) {
9221 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9223 } else if ([components count] == 2) {
9224 NSString *argument = [components objectAtIndex:1];
9226 if ([base isEqualToString:@"package"]) {
9227 controller = [self pageForPackage:argument];
9230 if (!external && [base isEqualToString:@"search"]) {
9231 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9234 if (!external && [base isEqualToString:@"sections"]) {
9235 if ([argument isEqualToString:@"all"])
9237 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9240 if (!external && [base isEqualToString:@"sources"]) {
9241 if ([argument isEqualToString:@"add"]) {
9242 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9243 [(SourcesController *)controller showAddSourcePrompt];
9245 Source *source = [database_ sourceWithKey:argument];
9246 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9250 if (!external && [base isEqualToString:@"launch"]) {
9251 [self launchApplicationWithIdentifier:argument suspended:NO];
9254 } else if (!external && [components count] == 3) {
9255 NSString *arg1 = [components objectAtIndex:1];
9256 NSString *arg2 = [components objectAtIndex:2];
9258 if ([base isEqualToString:@"package"]) {
9259 if ([arg2 isEqualToString:@"settings"]) {
9260 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9261 } else if ([arg2 isEqualToString:@"files"]) {
9262 if (Package *package = [database_ packageWithName:arg1]) {
9263 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9264 [(FileTable *)controller setPackage:package];
9270 [controller setDelegate:self];
9274 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9275 CyteViewController *page([self pageForURL:url forExternal:external]);
9278 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9279 [nav setViewControllers:[NSArray arrayWithObject:page]];
9280 [tabbar_ setUnselectedViewController:nav];
9286 - (void) applicationOpenURL:(NSURL *)url {
9287 [super applicationOpenURL:url];
9292 [self openCydiaURL:url forExternal:YES];
9295 - (void) applicationWillResignActive:(UIApplication *)application {
9296 // Stop refreshing if you get a phone call or lock the device.
9297 if ([tabbar_ updating])
9298 [tabbar_ cancelUpdate];
9300 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9301 [super applicationWillResignActive:application];
9304 - (void) applicationWillTerminate:(UIApplication *)application {
9306 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9307 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9308 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9313 - (void) setConfigurationData:(NSString *)data {
9314 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9316 if (!conffile_r(data)) {
9317 lprintf("E:invalid conffile\n");
9321 NSString *ofile = conffile_r[1];
9322 //NSString *nfile = conffile_r[2];
9324 UIAlertView *alert = [[[UIAlertView alloc]
9325 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9326 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9328 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9330 UCLocalize("ACCEPT_NEW_COPY"),
9331 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9335 [alert setContext:@"conffile"];
9336 [alert setNumberOfRows:2];
9340 - (void) addStashController {
9342 stash_ = [[[StashController alloc] init] autorelease];
9343 [window_ addSubview:[stash_ view]];
9346 - (void) removeStashController {
9347 [[stash_ view] removeFromSuperview];
9353 [self setIdleTimerDisabled:YES];
9355 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9356 UpdateExternalStatus(1);
9357 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9358 UpdateExternalStatus(0);
9360 [self removeStashController];
9362 if (ExecFork() == 0) {
9363 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9364 perror("launchctl stop");
9368 - (void) setupViewControllers {
9369 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9371 NSMutableArray *items([NSMutableArray arrayWithObjects:
9372 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9373 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9374 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9375 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9379 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9380 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9382 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9385 NSMutableArray *controllers([NSMutableArray array]);
9386 for (UITabBarItem *item in items) {
9387 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9388 [controller setTabBarItem:item];
9389 [controllers addObject:controller];
9391 [tabbar_ setViewControllers:controllers];
9393 [tabbar_ setUpdateDelegate:self];
9396 - (void) applicationDidFinishLaunching:(id)unused {
9398 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9399 [self setApplicationSupportsShakeToEdit:NO];
9401 @synchronized (HostConfig_) {
9402 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9405 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9406 initWithMemoryCapacity:524288
9407 diskCapacity:10485760
9408 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9411 [CydiaWebViewController _initialize];
9413 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9415 // this would disallow http{,s} URLs from accessing this data
9416 //[WebView registerURLSchemeAsLocal:@"cydia"];
9418 Font12_ = [UIFont systemFontOfSize:12];
9419 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9420 Font14_ = [UIFont systemFontOfSize:14];
9421 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9422 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9424 essential_ = [NSMutableArray arrayWithCapacity:4];
9425 broken_ = [NSMutableArray arrayWithCapacity:4];
9427 // XXX: I really need this thing... like, seriously... I'm sorry
9428 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9430 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9431 [window_ orderFront:self];
9432 [window_ makeKey:self];
9433 [window_ setHidden:NO];
9436 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9437 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9438 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9439 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9440 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9441 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9442 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9443 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9444 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9447 [self addStashController];
9448 // XXX: this would be much cleaner as a yieldToSelector:
9449 // that way the removeStashController could happen right here inline
9450 // we also could no longer require the useless stash_ field anymore
9451 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9455 database_ = [Database sharedInstance];
9456 [database_ setDelegate:self];
9458 [window_ setUserInteractionEnabled:NO];
9459 [self setupViewControllers];
9461 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9462 [window_ addSubview:[emulated_ view]];
9464 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9468 - (NSArray *) defaultStartPages {
9469 NSMutableArray *standard = [NSMutableArray array];
9470 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9471 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9472 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9474 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9476 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9477 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9479 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9486 [window_ setUserInteractionEnabled:YES];
9487 [self showSettings];
9490 if ([emulated_ modalViewController] != nil)
9491 [emulated_ dismissModalViewControllerAnimated:YES];
9492 [window_ setUserInteractionEnabled:NO];
9500 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9501 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9502 int standardIndex = 0;
9503 NSArray *standard = [self defaultStartPages];
9510 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9511 if (valid && closed != nil) {
9512 NSTimeInterval interval([closed timeIntervalSinceNow]);
9513 // XXX: Is 15 minutes the optimal time here?
9514 if (interval > 0 && interval <= -(15*60))
9518 if (valid && [saved count] != [standard count])
9522 for (unsigned int i = 0; i < [standard count]; i++) {
9523 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9524 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9525 // but it's good enough for now.
9526 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9533 NSArray *items = nil;
9535 [tabbar_ setSelectedIndex:savedIndex];
9538 [tabbar_ setSelectedIndex:standardIndex];
9542 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9543 NSArray *stack = [items objectAtIndex:tab];
9544 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9545 NSMutableArray *current = [NSMutableArray array];
9547 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9548 NSString *addr = [stack objectAtIndex:nav];
9549 NSURL *url = [NSURL URLWithString:addr];
9550 CyteViewController *page = [self pageForURL:url forExternal:NO];
9552 [current addObject:page];
9555 [navigation setViewControllers:current];
9558 // (Try to) show the startup URL.
9559 if (starturl_ != nil) {
9560 [self openCydiaURL:starturl_ forExternal:NO];
9565 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9566 if (item != nil && IsWildcat_) {
9567 [sheet showFromBarButtonItem:item animated:YES];
9569 [sheet showInView:window_];
9573 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9574 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9575 [progress setTitle:task];
9576 [progress addProgressEvent:event];
9579 - (void) addProgressEventForTask:(NSArray *)data {
9580 CydiaProgressEvent *event([data objectAtIndex:0]);
9581 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9582 [self addProgressEvent:event forTask:task];
9585 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9586 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9592 id Alloc_(id self, SEL selector) {
9593 id object = alloc_(self, selector);
9594 lprintf("[%s]A-%p\n", self->isa->name, object);
9599 id Dealloc_(id self, SEL selector) {
9600 id object = dealloc_(self, selector);
9601 lprintf("[%s]D-%p\n", self->isa->name, object);
9605 Class $WebDefaultUIKitDelegate;
9607 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9608 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9609 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9610 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9613 static NSSet *MobilizedFiles_;
9615 static NSURL *MobilizeURL(NSURL *url) {
9616 NSString *path([url path]);
9617 if ([path hasPrefix:@"/var/root/"]) {
9618 NSString *file([path substringFromIndex:10]);
9619 if ([MobilizedFiles_ containsObject:file])
9620 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9626 Class $CFXPreferencesPropertyListSource;
9627 @class CFXPreferencesPropertyListSource;
9629 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9630 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9631 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9632 url = MobilizeURL(url);
9633 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9634 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9640 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9641 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9642 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9643 url = MobilizeURL(url);
9644 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9645 //NSLog(@"%@ %@", [url absoluteString], value);
9651 Class $NSURLConnection;
9653 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9654 NSMutableURLRequest *copy([request mutableCopy]);
9656 NSURL *url([copy URL]);
9658 NSString *href([url absoluteString]);
9659 NSString *host([url host]);
9660 NSString *scheme([[url scheme] lowercaseString]);
9662 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9664 @synchronized (HostConfig_) {
9665 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9666 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9667 [copy setHTTPShouldUsePipelining:YES];
9669 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9670 if ([control isEqualToString:@"max-age=0"])
9671 if ([CachedURLs_ containsObject:href]) {
9673 NSLog(@"~~~: %@", href);
9676 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9678 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9679 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9680 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9684 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9688 int main(int argc, char *argv[]) {
9689 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9693 UpdateExternalStatus(0);
9695 if (Class $UIDevice = objc_getClass("UIDevice")) {
9696 UIDevice *device([$UIDevice currentDevice]);
9697 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9701 UIScreen *screen([UIScreen mainScreen]);
9702 if ([screen respondsToSelector:@selector(scale)])
9703 ScreenScale_ = [screen scale];
9707 UIDevice *device([UIDevice currentDevice]);
9708 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9711 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9712 if (idiom == UIUserInterfaceIdiomPhone)
9714 else if (idiom == UIUserInterfaceIdiomPad)
9717 NSLog(@"unknown UIUserInterfaceIdiom!");
9720 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9722 HostConfig_ = [[[NSObject alloc] init] autorelease];
9723 @synchronized (HostConfig_) {
9724 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9725 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9726 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9727 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9728 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9731 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9733 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9735 MobilizedFiles_ = [NSMutableSet setWithObjects:
9736 @"Library/Preferences/com.apple.Accessibility.plist",
9737 @"Library/Preferences/com.apple.preferences.sounds.plist",
9740 /* Library Hacks {{{ */
9741 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9743 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9745 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9746 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9747 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9748 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9751 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9752 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9753 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9754 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9757 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9758 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9759 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9760 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9761 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9764 $NSURLConnection = objc_getClass("NSURLConnection");
9765 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9766 if (NSURLConnection$init$ != NULL) {
9767 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9768 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9771 /* Set Locale {{{ */
9772 Locale_ = CFLocaleCopyCurrent();
9773 Languages_ = [NSLocale preferredLanguages];
9775 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9776 //NSLog(@"%@", [Languages_ description]);
9779 if (Locale_ != NULL)
9780 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9781 else if (Languages_ != nil && [Languages_ count] != 0)
9782 lang = [[Languages_ objectAtIndex:0] UTF8String];
9784 // XXX: consider just setting to C and then falling through?
9788 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9789 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9792 NSLog(@"Setting Language: %s", lang);
9795 setenv("LANG", lang, true);
9796 std::setlocale(LC_ALL, lang);
9800 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9802 /* Parse Arguments {{{ */
9803 bool substrate(false);
9809 for (int argi(1); argi != argc; ++argi)
9810 if (strcmp(argv[argi], "--") == 0) {
9812 argv[argi] = argv[0];
9818 for (int argi(1); argi != arge; ++argi)
9819 if (strcmp(args[argi], "--substrate") == 0)
9822 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9826 App_ = [[NSBundle mainBundle] bundlePath];
9832 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9833 alloc_ = alloc->method_imp;
9834 alloc->method_imp = (IMP) &Alloc_;*/
9836 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9837 dealloc_ = dealloc->method_imp;
9838 dealloc->method_imp = (IMP) &Dealloc_;*/
9840 /* System Information {{{ */
9844 size = sizeof(maxproc);
9845 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9846 perror("sysctlbyname(\"kern.maxproc\", ?)");
9847 else if (maxproc < 64) {
9849 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9850 perror("sysctlbyname(\"kern.maxproc\", #)");
9853 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9854 char *osversion = new char[size];
9855 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9856 perror("sysctlbyname(\"kern.osversion\", ?)");
9858 System_ = [NSString stringWithUTF8String:osversion];
9860 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9861 char *machine = new char[size];
9862 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9863 perror("sysctlbyname(\"hw.machine\", ?)");
9867 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9868 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9869 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9871 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9873 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9874 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9875 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9877 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9878 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9879 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9881 if (mcc != NULL && mnc != NULL)
9882 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9889 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9890 Build_ = [system objectForKey:@"ProductBuildVersion"];
9891 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9892 Product_ = [info objectForKey:@"SafariProductVersion"];
9893 Safari_ = [info objectForKey:@"CFBundleVersion"];
9896 /* Load Database {{{ */
9898 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9900 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9902 if (Metadata_ == NULL)
9903 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9905 Settings_ = [Metadata_ objectForKey:@"Settings"];
9907 Packages_ = [Metadata_ objectForKey:@"Packages"];
9908 Sections_ = [Metadata_ objectForKey:@"Sections"];
9909 Sources_ = [Metadata_ objectForKey:@"Sources"];
9911 Token_ = [Metadata_ objectForKey:@"Token"];
9914 if (Settings_ != nil)
9915 Role_ = [Settings_ objectForKey:@"Role"];
9917 if (Sections_ == nil) {
9918 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9919 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9922 if (Sources_ == nil) {
9923 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9924 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9929 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9932 if (Packages_ != nil) {
9934 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9938 [Metadata_ removeObjectForKey:@"Packages"];
9944 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9946 #define MobileSubstrate_(name) \
9947 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9948 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9949 if (handle == NULL) \
9950 NSLog(@"%s", dlerror()); \
9953 MobileSubstrate_(Activator)
9954 MobileSubstrate_(libstatusbar)
9955 MobileSubstrate_(SimulatedKeyEvents)
9956 MobileSubstrate_(WinterBoard)
9958 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9959 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9961 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9963 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9964 unlink("/tmp/.cydia.fw");
9966 } else if (access("/User", F_OK) != 0 || version < 4) {
9969 system("/usr/libexec/cydia/firmware.sh");
9973 _assert([[NSFileManager defaultManager]
9974 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9975 withIntermediateDirectories:YES
9980 if (access("/tmp/cydia.chk", F_OK) == 0) {
9981 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9982 _assert(errno == ENOENT);
9983 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9984 _assert(errno == ENOENT);
9987 /* APT Initialization {{{ */
9988 _assert(pkgInitConfig(*_config));
9989 _assert(pkgInitSystem(*_config, _system));
9992 _config->Set("APT::Acquire::Translation", lang);
9994 // XXX: this timeout might be important :(
9995 //_config->Set("Acquire::http::Timeout", 15);
9997 _config->Set("Acquire::http::MaxParallel", 3);
9999 /* Color Choices {{{ */
10000 space_ = CGColorSpaceCreateDeviceRGB();
10002 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10003 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10004 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10005 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10006 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10007 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10008 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10009 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10010 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10012 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10013 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10015 /* UIKit Configuration {{{ */
10016 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10017 if ($GSFontSetUseLegacyFontMetrics != NULL)
10018 $GSFontSetUseLegacyFontMetrics(YES);
10020 // XXX: I have a feeling this was important
10021 //UIKeyboardDisableAutomaticAppearance();
10024 Colon_ = UCLocalize("COLON_DELIMITED");
10025 Elision_ = UCLocalize("ELISION");
10026 Error_ = UCLocalize("ERROR");
10027 Warning_ = UCLocalize("WARNING");
10030 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10032 CGColorSpaceRelease(space_);
10033 CFRelease(Locale_);