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)
2703 string = [self name];
2704 length = [string length];
2706 for (NSString *term in query) {
2707 range = [string rangeOfString:term options:MatchCompareOptions_];
2708 if (range.location != NSNotFound)
2709 rank_ -= 6 * 1000000 / length;
2714 length = [string length];
2716 for (NSString *term in query) {
2717 range = [string rangeOfString:term options:MatchCompareOptions_];
2718 if (range.location != NSNotFound)
2719 rank_ -= 6 * 1000000 / length;
2723 string = [self shortDescription];
2724 length = [string length];
2725 NSUInteger stop(std::min<NSUInteger>(length, 100));
2727 for (NSString *term in query) {
2728 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2729 if (range.location != NSNotFound)
2730 rank_ -= 2 * 100000;
2736 - (bool) hasSupportingRole {
2741 if ([Role_ isEqualToString:@"User"])
2745 if ([Role_ isEqualToString:@"Hacker"])
2749 if ([Role_ isEqualToString:@"Developer"])
2754 - (NSArray *) tags {
2758 - (BOOL) hasTag:(NSString *)tag {
2759 return tags_ == nil ? NO : [tags_ containsObject:tag];
2762 - (NSString *) primaryPurpose {
2763 for (NSString *tag in (NSArray *) tags_)
2764 if ([tag hasPrefix:@"purpose::"])
2765 return [tag substringFromIndex:9];
2769 - (NSArray *) purposes {
2770 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2771 for (NSString *tag in (NSArray *) tags_)
2772 if ([tag hasPrefix:@"purpose::"])
2773 [purposes addObject:[tag substringFromIndex:9]];
2774 return [purposes count] == 0 ? nil : purposes;
2777 - (bool) isCommercial {
2778 return [self hasTag:@"cydia::commercial"];
2781 - (void) setIndex:(size_t)index {
2782 if (metadata_->index_ != index)
2783 metadata_->index_ = index;
2786 - (CYString &) cyname {
2787 return name_.empty() ? id_ : name_;
2790 - (uint32_t) compareBySection:(NSArray *)sections {
2791 NSString *section([self section]);
2792 for (size_t i(0), e([sections count]); i != e; ++i) {
2793 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2797 return _not(uint32_t);
2801 @synchronized (database_) {
2802 pkgProblemResolver *resolver = [database_ resolver];
2803 resolver->Clear(iterator_);
2805 pkgCacheFile &cache([database_ cache]);
2806 cache->SetReInstall(iterator_, false);
2807 cache->MarkKeep(iterator_, false);
2811 @synchronized (database_) {
2812 pkgProblemResolver *resolver = [database_ resolver];
2813 resolver->Clear(iterator_);
2814 resolver->Protect(iterator_);
2816 pkgCacheFile &cache([database_ cache]);
2817 cache->SetReInstall(iterator_, false);
2818 cache->MarkInstall(iterator_, false);
2820 pkgDepCache::StateCache &state((*cache)[iterator_]);
2821 if (!state.Install())
2822 cache->SetReInstall(iterator_, true);
2826 @synchronized (database_) {
2827 pkgProblemResolver *resolver = [database_ resolver];
2828 resolver->Clear(iterator_);
2829 resolver->Remove(iterator_);
2830 resolver->Protect(iterator_);
2832 pkgCacheFile &cache([database_ cache]);
2833 cache->SetReInstall(iterator_, false);
2834 cache->MarkDelete(iterator_, true);
2837 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2838 _profile(Package$isUnfilteredAndSearchedForBy)
2841 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2842 value &= [self unfiltered];
2845 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2846 value &= [self matches:query];
2853 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2854 if ([search length] == 0)
2857 _profile(Package$isUnfilteredAndSelectedForBy)
2860 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2861 value &= [self unfiltered];
2864 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2865 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2872 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2873 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2876 - (bool) isVisibleInSection:(NSString *)name {
2877 NSString *section([self section]);
2881 section == nil && [name length] == 0 ||
2882 [name isEqualToString:section]
2883 ) && [self visible];
2886 - (bool) isVisibleInSource:(Source *)source {
2887 return [self source] == source && [self visible];
2892 /* Section Class {{{ */
2893 @interface Section : NSObject {
2898 _H<NSString> localized_;
2901 - (NSComparisonResult) compareByLocalized:(Section *)section;
2902 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2903 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2904 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2905 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2906 - (NSString *) name;
2913 - (void) addToCount;
2915 - (void) setCount:(size_t)count;
2916 - (NSString *) localized;
2920 @implementation Section
2922 - (NSComparisonResult) compareByLocalized:(Section *)section {
2923 NSString *lhs(localized_);
2924 NSString *rhs([section localized]);
2926 /*if ([lhs length] != 0 && [rhs length] != 0) {
2927 unichar lhc = [lhs characterAtIndex:0];
2928 unichar rhc = [rhs characterAtIndex:0];
2930 if (isalpha(lhc) && !isalpha(rhc))
2931 return NSOrderedAscending;
2932 else if (!isalpha(lhc) && isalpha(rhc))
2933 return NSOrderedDescending;
2936 return [lhs compare:rhs options:LaxCompareOptions_];
2939 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2940 if ((self = [self initWithName:name localize:NO]) != nil) {
2941 if (localized != nil)
2942 localized_ = localized;
2946 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2947 return [self initWithName:name row:0 localize:localize];
2950 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2951 if ((self = [super init]) != nil) {
2956 localized_ = LocalizeSection(name_);
2960 /* XXX: localize the index thingees */
2961 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2962 if ((self = [super init]) != nil) {
2963 name_ = [NSString stringWithCharacters:&index length:1];
2969 - (NSString *) name {
2989 - (void) addToCount {
2993 - (void) setCount:(size_t)count {
2997 - (NSString *) localized {
3004 static NSString *Colon_;
3006 static NSString *Error_;
3007 static NSString *Warning_;
3009 class CydiaLogCleaner :
3010 public pkgArchiveCleaner
3013 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3018 /* Database Implementation {{{ */
3019 @implementation Database
3021 + (Database *) sharedInstance {
3022 static _H<Database> instance;
3023 if (instance == nil)
3024 instance = [[[Database alloc] init] autorelease];
3032 - (void) releasePackages {
3033 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3034 CFArrayRemoveAllValues(packages_);
3038 // XXX: actually implement this thing
3040 [self releasePackages];
3041 apr_pool_destroy(pool_);
3042 NSRecycleZone(zone_);
3046 - (void) _readCydia:(NSNumber *)fd {
3047 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3048 std::istream is(&ib);
3051 static Pcre finish_r("^finish:([^:]*)$");
3053 while (std::getline(is, line)) {
3054 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3056 const char *data(line.c_str());
3057 size_t size = line.size();
3058 lprintf("C:%s\n", data);
3060 if (finish_r(data, size)) {
3061 NSString *finish = finish_r[1];
3062 int index = [Finishes_ indexOfObject:finish];
3063 if (index != INT_MAX && index > Finish_)
3073 - (void) _readStatus:(NSNumber *)fd {
3074 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3075 std::istream is(&ib);
3078 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3079 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3081 while (std::getline(is, line)) {
3082 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3084 const char *data(line.c_str());
3085 size_t size(line.size());
3086 lprintf("S:%s\n", data);
3088 if (conffile_r(data, size)) {
3089 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3090 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3091 } else if (strncmp(data, "status: ", 8) == 0) {
3092 // status: <package>: {unpacked,half-configured,installed}
3093 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3094 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3095 } else if (strncmp(data, "processing: ", 12) == 0) {
3096 // processing: configure: config-test
3097 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3098 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3099 } else if (pmstatus_r(data, size)) {
3100 std::string type([pmstatus_r[1] UTF8String]);
3102 NSString *package = pmstatus_r[2];
3103 if ([package isEqualToString:@"dpkg-exec"])
3106 float percent([pmstatus_r[3] floatValue]);
3107 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3109 NSString *string = pmstatus_r[4];
3111 if (type == "pmerror") {
3112 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3113 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3114 } else if (type == "pmstatus") {
3115 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3116 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3117 } else if (type == "pmconffile")
3118 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3120 lprintf("E:unknown pmstatus\n");
3122 lprintf("E:unknown status\n");
3130 - (void) _readOutput:(NSNumber *)fd {
3131 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3132 std::istream is(&ib);
3135 while (std::getline(is, line)) {
3136 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3138 lprintf("O:%s\n", line.c_str());
3140 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3141 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3153 - (Package *) packageWithName:(NSString *)name {
3154 @synchronized (self) {
3155 if (static_cast<pkgDepCache *>(cache_) == NULL)
3157 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3158 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3162 if ((self = [super init]) != nil) {
3169 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3170 apr_pool_create(&pool_, NULL);
3172 size_t capacity(MetaFile_->active_);
3178 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3179 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3183 _assert(pipe(fds) != -1);
3186 _config->Set("APT::Keep-Fds::", cydiafd_);
3187 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3190 detachNewThreadSelector:@selector(_readCydia:)
3192 withObject:[NSNumber numberWithInt:fds[0]]
3195 _assert(pipe(fds) != -1);
3199 detachNewThreadSelector:@selector(_readStatus:)
3201 withObject:[NSNumber numberWithInt:fds[0]]
3204 _assert(pipe(fds) != -1);
3205 _assert(dup2(fds[0], 0) != -1);
3206 _assert(close(fds[0]) != -1);
3208 input_ = fdopen(fds[1], "a");
3210 _assert(pipe(fds) != -1);
3211 _assert(dup2(fds[1], 1) != -1);
3212 _assert(close(fds[1]) != -1);
3215 detachNewThreadSelector:@selector(_readOutput:)
3217 withObject:[NSNumber numberWithInt:fds[0]]
3222 - (pkgCacheFile &) cache {
3226 - (pkgDepCache::Policy *) policy {
3230 - (pkgRecords *) records {
3234 - (pkgProblemResolver *) resolver {
3238 - (pkgAcquire &) fetcher {
3242 - (pkgSourceList &) list {
3246 - (NSArray *) packages {
3247 return (NSArray *) packages_;
3250 - (NSArray *) sources {
3254 - (Source *) sourceWithKey:(NSString *)key {
3255 for (Source *source in [self sources]) {
3256 if ([[source key] isEqualToString:key])
3261 - (bool) popErrorWithTitle:(NSString *)title {
3264 while (!_error->empty()) {
3266 bool warning(!_error->PopMessage(error));
3271 size_t size(error.size());
3272 if (size == 0 || error[size - 1] != '\n')
3274 error.resize(size - 1);
3277 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3279 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3285 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3286 return [self popErrorWithTitle:title] || !success;
3289 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3290 @synchronized (self) {
3293 [self releasePackages];
3296 [sourceList_ removeAllObjects];
3316 apr_pool_clear(pool_);
3318 NSRecycleZone(zone_);
3319 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3321 int chk(creat("/tmp/cydia.chk", 0644));
3325 if (invocation != nil)
3326 [invocation invoke];
3328 NSString *title(UCLocalize("DATABASE"));
3331 OpProgress progress;
3332 while (!cache_.Open(progress, true)) { pop:
3334 bool warning(!_error->PopMessage(error));
3335 lprintf("cache_.Open():[%s]\n", error.c_str());
3337 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3338 [delegate_ repairWithSelector:@selector(configure)];
3339 else if (error == "The package lists or status file could not be parsed or opened.")
3340 [delegate_ repairWithSelector:@selector(update)];
3341 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3342 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3343 // else if (error == "Malformed Status line")
3344 // else if (error == "The list of sources could not be read.")
3346 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3356 unlink("/tmp/cydia.chk");
3358 now_ = [[NSDate date] timeIntervalSince1970];
3360 policy_ = new pkgDepCache::Policy();
3361 records_ = new pkgRecords(cache_);
3362 resolver_ = new pkgProblemResolver(cache_);
3363 fetcher_ = new pkgAcquire(&status_);
3366 list_ = new pkgSourceList();
3367 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3370 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3371 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3375 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3378 if (cache_->BrokenCount() != 0) {
3379 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3382 if (cache_->BrokenCount() != 0) {
3383 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3387 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3391 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3392 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3393 [sourceList_ addObject:object];
3395 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3396 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3397 // XXX: this could be more intelligent
3398 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3399 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3401 sourceMap_[cached->ID] = object;
3406 /*std::vector<Package *> packages;
3407 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3412 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3413 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3414 //packages.push_back(package);
3415 CFArrayAppendValue(packages_, CFRetain(package));
3419 /*if (packages.empty())
3420 packages_ = [[NSArray alloc] init];
3422 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3425 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3426 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3427 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3435 /*if (!packages.empty())
3436 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3437 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3439 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3441 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3443 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3447 size_t count(CFArrayGetCount(packages_));
3448 MetaFile_->active_ = count;
3450 for (size_t index(0); index != count; ++index)
3451 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3458 @synchronized (self) {
3460 resolver_ = new pkgProblemResolver(cache_);
3462 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3463 if (!cache_[iterator].Keep())
3464 cache_->MarkKeep(iterator, false);
3465 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3466 cache_->SetReInstall(iterator, false);
3469 - (void) configure {
3470 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3472 system([dpkg UTF8String]);
3477 // XXX: I don't remember this condition
3482 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3484 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3486 if ([self popErrorWithTitle:title])
3490 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3492 CydiaLogCleaner cleaner;
3493 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3500 fetcher_->Shutdown();
3502 pkgRecords records(cache_);
3504 lock_ = new FileFd();
3505 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3507 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3509 if ([self popErrorWithTitle:title])
3513 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3516 manager_ = (_system->CreatePM(cache_));
3517 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3524 bool substrate(RestartSubstrate_);
3525 RestartSubstrate_ = false;
3527 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3529 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3531 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3533 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3534 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3537 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3539 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3541 [self popErrorWithTitle:title];
3545 bool failed = false;
3546 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3547 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3549 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3555 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3563 RestartSubstrate_ = true;
3566 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3568 if (_error->PendingError()) {
3573 if (result == pkgPackageManager::Failed) {
3578 if (result != pkgPackageManager::Completed) {
3583 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3585 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3587 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3588 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3591 if (![before isEqualToArray:after])
3596 NSString *title(UCLocalize("UPGRADE"));
3597 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3603 [self updateWithStatus:status_];
3606 - (void) updateWithStatus:(Status &)status {
3607 NSString *title(UCLocalize("REFRESHING_DATA"));
3610 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3614 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3615 if ([self popErrorWithTitle:title])
3618 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3620 bool success(ListUpdate(status, list, PulseInterval_));
3621 if (status.WasCancelled())
3624 [self popErrorWithTitle:title forOperation:success];
3625 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3629 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3632 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3633 delegate_ = delegate;
3636 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3637 progress_ = delegate;
3638 status_.setDelegate(delegate);
3641 - (NSObject<ProgressDelegate> *) progressDelegate {
3645 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3646 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3647 return i == sourceMap_.end() ? nil : i->second;
3650 - (NSString *) mappedSectionForPointer:(const char *)section {
3651 _H<NSString> *mapped;
3653 _profile(Database$mappedSectionForPointer$Cache)
3654 mapped = §ions_[section];
3657 if (*mapped == NULL) {
3658 size_t length(strlen(section));
3659 char spaced[length + 1];
3661 _profile(Database$mappedSectionForPointer$Replace)
3662 for (size_t index(0); index != length; ++index)
3663 spaced[index] = section[index] == '_' ? ' ' : section[index];
3664 spaced[length] = '\0';
3669 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3670 string = [NSString stringWithUTF8String:spaced];
3673 _profile(Database$mappedSectionForPointer$Map)
3674 string = [SectionMap_ objectForKey:string] ?: string;
3684 static _H<NSMutableSet> Diversions_;
3686 @interface Diversion : NSObject {
3689 _H<NSString> format_;
3694 @implementation Diversion
3696 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3697 if ((self = [super init]) != nil) {
3698 pattern_ = [from UTF8String];
3704 - (NSString *) divert:(NSString *)url {
3705 return !pattern_(url) ? nil : pattern_->*format_;
3708 + (NSURL *) divertURL:(NSURL *)url {
3710 NSString *href([url absoluteString]);
3712 for (Diversion *diversion in (id) Diversions_)
3713 if (NSString *diverted = [diversion divert:href]) {
3715 NSLog(@"div: %@", diverted);
3717 url = [NSURL URLWithString:diverted];
3724 - (NSString *) key {
3728 - (NSUInteger) hash {
3732 - (BOOL) isEqual:(Diversion *)object {
3733 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3738 @interface CydiaObject : NSObject {
3739 _H<IndirectDelegate> indirect_;
3740 _transient id delegate_;
3743 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3747 @interface CydiaWebViewController : CyteWebViewController {
3748 _H<CydiaObject> cydia_;
3751 + (void) addDiversion:(Diversion *)diversion;
3755 /* Web Scripting {{{ */
3756 @implementation CydiaObject
3758 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3759 if ((self = [super init]) != nil) {
3760 indirect_ = indirect;
3764 - (void) setDelegate:(id)delegate {
3765 delegate_ = delegate;
3768 + (NSArray *) _attributeKeys {
3769 return [NSArray arrayWithObjects:
3785 - (NSArray *) attributeKeys {
3786 return [[self class] _attributeKeys];
3789 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3790 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3793 - (NSString *) version {
3797 - (NSString *) device {
3798 return [[UIDevice currentDevice] uniqueIdentifier];
3801 - (NSString *) firmware {
3802 return [[UIDevice currentDevice] systemVersion];
3805 - (NSString *) hostname {
3806 return [[UIDevice currentDevice] name];
3809 - (NSString *) idiom {
3810 return (id) Idiom_ ?: [NSNull null];
3813 - (NSString *) plmn {
3814 return (id) PLMN_ ?: [NSNull null];
3817 - (NSString *) bbsnum {
3818 return (id) BBSNum_ ?: [NSNull null];
3821 - (NSString *) ecid {
3822 return (id) ChipID_ ?: [NSNull null];
3825 - (NSString *) serial {
3826 return SerialNumber_;
3829 - (NSString *) role {
3830 return (id) Role_ ?: [NSNull null];
3833 - (NSString *) model {
3834 return [NSString stringWithUTF8String:Machine_];
3837 - (NSString *) token {
3838 return (id) Token_ ?: [NSNull null];
3841 + (NSString *) webScriptNameForSelector:(SEL)selector {
3843 else if (selector == @selector(addBridgedHost:))
3844 return @"addBridgedHost";
3845 else if (selector == @selector(addInsecureHost:))
3846 return @"addInsecureHost";
3847 else if (selector == @selector(addInternalRedirect::))
3848 return @"addInternalRedirect";
3849 else if (selector == @selector(addPipelinedHost:scheme:))
3850 return @"addPipelinedHost";
3851 else if (selector == @selector(addTokenHost:))
3852 return @"addTokenHost";
3853 else if (selector == @selector(addTrivialSource:))
3854 return @"addTrivialSource";
3855 else if (selector == @selector(close))
3857 else if (selector == @selector(du:))
3859 else if (selector == @selector(stringWithFormat:arguments:))
3861 else if (selector == @selector(getAllSources))
3862 return @"getAllSourcs";
3863 else if (selector == @selector(getKernelNumber:))
3864 return @"getKernelNumber";
3865 else if (selector == @selector(getKernelString:))
3866 return @"getKernelString";
3867 else if (selector == @selector(getInstalledPackages))
3868 return @"getInstalledPackages";
3869 else if (selector == @selector(getIORegistryEntry::))
3870 return @"getIORegistryEntry";
3871 else if (selector == @selector(getLocaleIdentifier))
3872 return @"getLocaleIdentifier";
3873 else if (selector == @selector(getPreferredLanguages))
3874 return @"getPreferredLanguages";
3875 else if (selector == @selector(getPackageById:))
3876 return @"getPackageById";
3877 else if (selector == @selector(getSessionValue:))
3878 return @"getSessionValue";
3879 else if (selector == @selector(installPackages:))
3880 return @"installPackages";
3881 else if (selector == @selector(localizedStringForKey:value:table:))
3883 else if (selector == @selector(popViewController:))
3884 return @"popViewController";
3885 else if (selector == @selector(refreshSources))
3886 return @"refreshSources";
3887 else if (selector == @selector(removeButton))
3888 return @"removeButton";
3889 else if (selector == @selector(setSessionValue::))
3890 return @"setSessionValue";
3891 else if (selector == @selector(substitutePackageNames:))
3892 return @"substitutePackageNames";
3893 else if (selector == @selector(scrollToBottom:))
3894 return @"scrollToBottom";
3895 else if (selector == @selector(setAllowsNavigationAction:))
3896 return @"setAllowsNavigationAction";
3897 else if (selector == @selector(setBadgeValue:))
3898 return @"setBadgeValue";
3899 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3900 return @"setButtonImage";
3901 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3902 return @"setButtonTitle";
3903 else if (selector == @selector(setHidesBackButton:))
3904 return @"setHidesBackButton";
3905 else if (selector == @selector(setHidesNavigationBar:))
3906 return @"setHidesNavigationBar";
3907 else if (selector == @selector(setNavigationBarStyle:))
3908 return @"setNavigationBarStyle";
3909 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3910 return @"setNavigationBarTintColor";
3911 else if (selector == @selector(setPasteboardString:))
3912 return @"setPasteboardString";
3913 else if (selector == @selector(setPasteboardURL:))
3914 return @"setPasteboardURL";
3915 else if (selector == @selector(setToken:))
3917 else if (selector == @selector(setViewportWidth:))
3918 return @"setViewportWidth";
3919 else if (selector == @selector(statfs:))
3921 else if (selector == @selector(supports:))
3923 else if (selector == @selector(unload))
3929 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3930 return [self webScriptNameForSelector:selector] == nil;
3933 - (BOOL) supports:(NSString *)feature {
3934 return [feature isEqualToString:@"window.open"];
3938 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
3941 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3942 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3945 - (NSNumber *) getKernelNumber:(NSString *)name {
3946 const char *string([name UTF8String]);
3949 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3950 return (id) [NSNull null];
3952 if (size != sizeof(int))
3953 return (id) [NSNull null];
3956 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3957 return (id) [NSNull null];
3959 return [NSNumber numberWithInt:value];
3962 - (NSString *) getKernelString:(NSString *)name {
3963 const char *string([name UTF8String]);
3966 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3967 return (id) [NSNull null];
3969 char value[size + 1];
3970 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3971 return (id) [NSNull null];
3973 // XXX: just in case you request something ludicrous
3976 return [NSString stringWithCString:value];
3979 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3980 NSObject *value(CYIOGetValue([path UTF8String], entry));
3983 if ([value isKindOfClass:[NSData class]])
3984 value = CYHex((NSData *) value);
3989 - (id) getSessionValue:(NSString *)key {
3990 @synchronized (SessionData_) {
3991 return [SessionData_ objectForKey:key];
3994 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3995 @synchronized (SessionData_) {
3996 if (value == (id) [WebUndefined undefined])
3997 [SessionData_ removeObjectForKey:key];
3999 [SessionData_ setObject:value forKey:key];
4002 - (void) addBridgedHost:(NSString *)host {
4003 @synchronized (HostConfig_) {
4004 [BridgedHosts_ addObject:host];
4007 - (void) addInsecureHost:(NSString *)host {
4008 @synchronized (HostConfig_) {
4009 [InsecureHosts_ addObject:host];
4012 - (void) addTokenHost:(NSString *)host {
4013 @synchronized (HostConfig_) {
4014 [TokenHosts_ addObject:host];
4017 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4018 @synchronized (HostConfig_) {
4019 if (scheme != (id) [WebUndefined undefined])
4020 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4022 [PipelinedHosts_ addObject:host];
4025 - (void) popViewController:(NSNumber *)value {
4026 if (value == (id) [WebUndefined undefined])
4027 value = [NSNumber numberWithBool:YES];
4028 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4031 - (void) addTrivialSource:(NSString *)href {
4032 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4035 - (void) refreshSources {
4036 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4039 - (NSArray *) getAllSources {
4040 return [[Database sharedInstance] sources];
4043 - (NSArray *) getInstalledPackages {
4044 Database *database([Database sharedInstance]);
4045 @synchronized (database) {
4046 NSArray *packages([database packages]);
4047 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4048 for (Package *package in packages)
4049 if (![package uninstalled])
4050 [installed addObject:package];
4054 - (Package *) getPackageById:(NSString *)id {
4055 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4059 return (Package *) [NSNull null];
4062 - (NSString *) getLocaleIdentifier {
4063 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4066 - (NSArray *) getPreferredLanguages {
4070 - (NSArray *) statfs:(NSString *)path {
4073 if (path == nil || statfs([path UTF8String], &stat) == -1)
4076 return [NSArray arrayWithObjects:
4077 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4078 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4079 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4083 - (NSNumber *) du:(NSString *)path {
4084 NSNumber *value(nil);
4087 _assert(pipe(fds) != -1);
4089 pid_t pid(ExecFork());
4091 _assert(dup2(fds[1], 1) != -1);
4092 _assert(close(fds[0]) != -1);
4093 _assert(close(fds[1]) != -1);
4094 /* XXX: this should probably not use du */
4095 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4100 _assert(close(fds[1]) != -1);
4102 if (FILE *du = fdopen(fds[0], "r")) {
4104 while (fgets(line, sizeof(line), du) != NULL) {
4105 size_t length(strlen(line));
4106 while (length != 0 && line[length - 1] == '\n')
4107 line[--length] = '\0';
4108 if (char *tab = strchr(line, '\t')) {
4110 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4115 } else _assert(close(fds[0]));
4119 if (waitpid(pid, &status, 0) == -1)
4122 else _assert(false);
4128 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4131 - (void) installPackages:(NSArray *)packages {
4132 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4135 - (NSString *) substitutePackageNames:(NSString *)message {
4136 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4137 for (size_t i(0), e([words count]); i != e; ++i) {
4138 NSString *word([words objectAtIndex:i]);
4139 if (Package *package = [[Database sharedInstance] packageWithName:word])
4140 [words replaceObjectAtIndex:i withObject:[package name]];
4143 return [words componentsJoinedByString:@" "];
4146 - (void) removeButton {
4147 [indirect_ removeButton];
4150 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4151 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4154 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4155 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4158 - (void) setBadgeValue:(id)value {
4159 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4162 - (void) setAllowsNavigationAction:(NSString *)value {
4163 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4166 - (void) setHidesBackButton:(NSString *)value {
4167 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4170 - (void) setHidesNavigationBar:(NSString *)value {
4171 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4174 - (void) setNavigationBarStyle:(NSString *)value {
4175 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4178 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4179 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4180 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4181 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4184 - (void) setPasteboardString:(NSString *)value {
4185 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4188 - (void) setPasteboardURL:(NSString *)value {
4189 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4192 - (void) _setToken:(NSString *)token {
4196 [Metadata_ removeObjectForKey:@"Token"];
4198 [Metadata_ setObject:Token_ forKey:@"Token"];
4203 - (void) setToken:(NSString *)token {
4204 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4207 - (void) scrollToBottom:(NSNumber *)animated {
4208 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4211 - (void) setViewportWidth:(float)width {
4212 [indirect_ setViewportWidthOnMainThread:width];
4215 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4216 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4217 unsigned count([arguments count]);
4219 for (unsigned i(0); i != count; ++i)
4220 values[i] = [arguments objectAtIndex:i];
4221 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4224 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4225 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4227 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4229 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4235 @interface NSURL (CydiaSecure)
4238 @implementation NSURL (CydiaSecure)
4240 - (bool) isCydiaSecure {
4241 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4244 @synchronized (HostConfig_) {
4245 if ([InsecureHosts_ containsObject:[self host]])
4254 /* Cydia Browser Controller {{{ */
4255 @implementation CydiaWebViewController
4257 - (NSURL *) navigationURL {
4258 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4261 + (void) initialize {
4262 Diversions_ = [NSMutableSet setWithCapacity:0];
4265 + (void) addDiversion:(Diversion *)diversion {
4266 [Diversions_ addObject:diversion];
4269 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4270 [super webView:view didClearWindowObject:window forFrame:frame];
4272 WebDataSource *source([frame dataSource]);
4273 NSURLResponse *response([source response]);
4274 NSURL *url([response URL]);
4275 NSString *scheme([[url scheme] lowercaseString]);
4277 bool bridged(false);
4279 @synchronized (HostConfig_) {
4280 if ([scheme isEqualToString:@"file"])
4282 else if ([scheme isEqualToString:@"https"])
4283 if ([BridgedHosts_ containsObject:[url host]])
4288 [window setValue:cydia_ forKey:@"cydia"];
4291 - (void) _setupMail:(MFMailComposeViewController *)controller {
4292 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4294 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4295 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4298 - (NSURL *) URLWithURL:(NSURL *)url {
4299 return [Diversion divertURL:url];
4302 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4303 NSURL *url([request URL]);
4304 NSString *host([url host]);
4306 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4308 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4309 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4310 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4311 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4314 @synchronized (HostConfig_) {
4315 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4318 if ([url isCydiaSecure] && token) {
4319 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4320 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4326 - (void) setDelegate:(id)delegate {
4327 [super setDelegate:delegate];
4328 [cydia_ setDelegate:delegate];
4331 - (NSString *) applicationNameForUserAgent {
4332 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4335 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4337 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4338 if (Product_ != nil)
4339 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4345 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4346 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4354 @interface NSObject (CydiaScript)
4355 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4358 @implementation NSObject (CydiaScript)
4360 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4366 @implementation NSArray (CydiaScript)
4368 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4369 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4370 for (size_t i(0), e([self count]); i != e; ++i)
4371 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4377 @implementation NSDictionary (CydiaScript)
4379 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4380 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4382 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4389 /* Confirmation Controller {{{ */
4390 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4391 if (!iterator.end())
4392 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4393 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4395 pkgCache::PkgIterator package(dep.TargetPkg());
4398 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4405 @protocol ConfirmationControllerDelegate
4406 - (void) cancelAndClear:(bool)clear;
4407 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4411 @interface ConfirmationController : CydiaWebViewController {
4412 _transient Database *database_;
4414 _H<UIAlertView> essential_;
4416 _H<NSDictionary> changes_;
4417 _H<NSMutableArray> issues_;
4418 _H<NSDictionary> sizes_;
4423 - (id) initWithDatabase:(Database *)database;
4427 @implementation ConfirmationController
4431 RestartSubstrate_ = true;
4432 [delegate_ confirmWithNavigationController:[self navigationController]];
4435 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4436 NSString *context([alert context]);
4438 if ([context isEqualToString:@"remove"]) {
4439 if (button == [alert cancelButtonIndex])
4440 [self dismissModalViewControllerAnimated:YES];
4441 else if (button == [alert firstOtherButtonIndex]) {
4445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4446 } else if ([context isEqualToString:@"unable"]) {
4447 [self dismissModalViewControllerAnimated:YES];
4448 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4450 [super alertView:alert clickedButtonAtIndex:button];
4454 - (void) _doContinue {
4455 [self dismissModalViewControllerAnimated:YES];
4456 [delegate_ cancelAndClear:NO];
4459 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4460 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4464 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4465 [super webView:view didClearWindowObject:window forFrame:frame];
4467 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4468 (id) changes_, @"changes",
4469 (id) issues_, @"issues",
4470 (id) sizes_, @"sizes",
4472 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4475 - (id) initWithDatabase:(Database *)database {
4476 if ((self = [super init]) != nil) {
4477 database_ = database;
4479 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4480 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4481 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4482 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4483 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4487 pkgCacheFile &cache([database_ cache]);
4488 NSArray *packages([database_ packages]);
4489 pkgDepCache::Policy *policy([database_ policy]);
4491 issues_ = [NSMutableArray arrayWithCapacity:4];
4493 for (Package *package in packages) {
4494 pkgCache::PkgIterator iterator([package iterator]);
4495 NSString *name([package id]);
4497 if ([package broken]) {
4498 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4500 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4502 reasons, @"reasons",
4505 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4509 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4510 pkgCache::DepIterator start;
4511 pkgCache::DepIterator end;
4512 dep.GlobOr(start, end); // ++dep
4514 if (!cache->IsImportantDep(end))
4516 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4519 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4521 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4522 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4523 clauses, @"clauses",
4527 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4529 pkgCache::PkgIterator target(start.TargetPkg());
4530 if (target->ProvidesList != 0)
4531 reason = @"missing";
4533 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4535 reason = @"installed";
4536 installed = [NSString stringWithUTF8String:ver.VerStr()];
4537 } else if (!cache[target].CandidateVerIter(cache).end())
4538 reason = @"uninstalled";
4539 else if (target->ProvidesList == 0)
4540 reason = @"uninstallable";
4542 reason = @"virtual";
4545 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4546 [NSString stringWithUTF8String:start.CompType()], @"operator",
4547 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4550 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4551 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4552 version, @"version",
4554 installed, @"installed",
4557 // yes, seriously. (wtf?)
4565 pkgDepCache::StateCache &state(cache[iterator]);
4567 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4569 if (state.NewInstall())
4570 [installs addObject:name];
4571 // XXX: else if (state.Install())
4572 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4573 [reinstalls addObject:name];
4574 // XXX: move before previous if
4575 else if (state.Upgrade())
4576 [upgrades addObject:name];
4577 else if (state.Downgrade())
4578 [downgrades addObject:name];
4579 else if (!state.Delete())
4580 // XXX: _assert(state.Keep());
4582 else if (special_r(name))
4583 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4584 [NSNull null], @"package",
4585 [NSArray arrayWithObjects:
4586 [NSDictionary dictionaryWithObjectsAndKeys:
4587 @"Conflicts", @"relationship",
4588 [NSArray arrayWithObjects:
4589 [NSDictionary dictionaryWithObjectsAndKeys:
4591 [NSNull null], @"version",
4592 @"installed", @"reason",
4599 if ([package essential])
4601 [removes addObject:name];
4604 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4605 substrate_ |= DepSubstrate(iterator.CurrentVer());
4610 else if (Advanced_) {
4611 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4613 essential_ = [[[UIAlertView alloc]
4614 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4615 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4617 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4619 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4623 [essential_ setContext:@"remove"];
4625 essential_ = [[[UIAlertView alloc]
4626 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4627 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4629 cancelButtonTitle:UCLocalize("OKAY")
4630 otherButtonTitles:nil
4633 [essential_ setContext:@"unable"];
4636 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4637 installs, @"installs",
4638 reinstalls, @"reinstalls",
4639 upgrades, @"upgrades",
4640 downgrades, @"downgrades",
4641 removes, @"removes",
4644 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4645 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4646 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4649 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4653 - (UIBarButtonItem *) leftButton {
4654 return [[[UIBarButtonItem alloc]
4655 initWithTitle:UCLocalize("CANCEL")
4656 style:UIBarButtonItemStylePlain
4658 action:@selector(cancelButtonClicked)
4663 - (void) applyRightButton {
4664 if ([issues_ count] == 0 && ![self isLoading])
4665 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4666 initWithTitle:UCLocalize("CONFIRM")
4667 style:UIBarButtonItemStyleDone
4669 action:@selector(confirmButtonClicked)
4672 [[self navigationItem] setRightBarButtonItem:nil];
4676 - (void) cancelButtonClicked {
4677 [self dismissModalViewControllerAnimated:YES];
4678 [delegate_ cancelAndClear:YES];
4682 - (void) confirmButtonClicked {
4683 if (essential_ != nil)
4693 /* Progress Data {{{ */
4694 @interface CydiaProgressData : NSObject {
4695 _transient id delegate_;
4704 _H<NSMutableArray> events_;
4705 _H<NSString> title_;
4707 _H<NSString> status_;
4708 _H<NSString> finish_;
4713 @implementation CydiaProgressData
4715 + (NSArray *) _attributeKeys {
4716 return [NSArray arrayWithObjects:
4728 - (NSArray *) attributeKeys {
4729 return [[self class] _attributeKeys];
4732 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4733 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4737 if ((self = [super init]) != nil) {
4738 events_ = [NSMutableArray arrayWithCapacity:32];
4742 - (void) setDelegate:(id)delegate {
4743 delegate_ = delegate;
4746 - (void) setPercent:(float)value {
4750 - (NSNumber *) percent {
4751 return [NSNumber numberWithFloat:percent_];
4754 - (void) setCurrent:(float)value {
4758 - (NSNumber *) current {
4759 return [NSNumber numberWithFloat:current_];
4762 - (void) setTotal:(float)value {
4766 - (NSNumber *) total {
4767 return [NSNumber numberWithFloat:total_];
4770 - (void) setSpeed:(float)value {
4774 - (NSNumber *) speed {
4775 return [NSNumber numberWithFloat:speed_];
4778 - (NSArray *) events {
4782 - (void) removeAllEvents {
4783 [events_ removeAllObjects];
4786 - (void) addEvent:(CydiaProgressEvent *)event {
4787 [events_ addObject:event];
4790 - (void) setTitle:(NSString *)text {
4794 - (NSString *) title {
4798 - (void) setFinish:(NSString *)text {
4802 - (NSString *) finish {
4803 return (id) finish_ ?: [NSNull null];
4806 - (void) setRunning:(bool)running {
4810 - (NSNumber *) running {
4811 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4816 /* Progress Controller {{{ */
4817 @interface ProgressController : CydiaWebViewController <
4820 _transient Database *database_;
4821 _H<CydiaProgressData, 1> progress_;
4825 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4827 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4829 - (void) setTitle:(NSString *)title;
4830 - (void) setCancellable:(bool)cancellable;
4834 @implementation ProgressController
4837 [database_ setProgressDelegate:nil];
4841 - (UIBarButtonItem *) leftButton {
4842 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4843 initWithTitle:UCLocalize("CANCEL")
4844 style:UIBarButtonItemStylePlain
4846 action:@selector(cancel)
4847 ] autorelease] : nil;
4850 - (void) updateCancel {
4851 [super applyLeftButton];
4854 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4855 if ((self = [super init]) != nil) {
4856 database_ = database;
4857 delegate_ = delegate;
4859 [database_ setProgressDelegate:self];
4861 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4862 [progress_ setDelegate:self];
4864 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4866 [scroller_ setBackgroundColor:[UIColor blackColor]];
4868 [[self navigationItem] setHidesBackButton:YES];
4870 [self updateCancel];
4874 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4875 [super webView:view didClearWindowObject:window forFrame:frame];
4876 [window setValue:progress_ forKey:@"cydiaProgress"];
4879 - (void) updateProgress {
4880 [self dispatchEvent:@"CydiaProgressUpdate"];
4883 - (void) viewWillAppear:(BOOL)animated {
4884 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4885 [super viewWillAppear:animated];
4889 UpdateExternalStatus(0);
4896 [delegate_ terminateWithSuccess];
4897 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4898 [delegate_ suspendWithAnimation:YES];
4900 [delegate_ suspend];*/
4912 system("/usr/bin/sbreload");
4918 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4919 SBReboot(SBSSpringBoardServerPort());
4921 reboot2(RB_AUTOBOOT);
4928 - (void) setTitle:(NSString *)title {
4929 [progress_ setTitle:title];
4930 [self updateProgress];
4933 - (UIBarButtonItem *) rightButton {
4934 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4935 initWithTitle:UCLocalize("CLOSE")
4936 style:UIBarButtonItemStylePlain
4938 action:@selector(close)
4942 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4943 UpdateExternalStatus(1);
4945 [progress_ setRunning:true];
4946 [self setTitle:title];
4947 // implicit updateProgress
4949 SHA1SumValue notifyconf; {
4951 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4954 MMap mmap(file, MMap::ReadOnly);
4956 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4957 notifyconf = sha1.Result();
4961 SHA1SumValue springlist; {
4963 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4966 MMap mmap(file, MMap::ReadOnly);
4968 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4969 springlist = sha1.Result();
4973 if (invocation != nil) {
4974 [invocation yieldToSelector:@selector(invoke)];
4975 [self setTitle:@"COMPLETE"];
4980 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4983 MMap mmap(file, MMap::ReadOnly);
4985 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4986 if (!(notifyconf == sha1.Result()))
4993 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4996 MMap mmap(file, MMap::ReadOnly);
4998 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4999 if (!(springlist == sha1.Result()))
5005 if (RestartSubstrate_)
5009 RestartSubstrate_ = false;
5012 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5013 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5014 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5015 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5016 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5020 system("su -c /usr/bin/uicache mobile");
5023 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5025 [progress_ setRunning:false];
5026 [self updateProgress];
5028 [self applyRightButton];
5031 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5032 [progress_ addEvent:event];
5033 [self updateProgress];
5036 - (bool) isProgressCancelled {
5037 return cancel_ == 2;
5042 [self updateCancel];
5045 - (void) setCancellable:(bool)cancellable {
5046 unsigned cancel(cancel_);
5050 else if (cancel_ == 0)
5053 if (cancel != cancel_)
5054 [self updateCancel];
5057 - (void) setProgressCancellable:(NSNumber *)cancellable {
5058 [self setCancellable:[cancellable boolValue]];
5061 - (void) setProgressPercent:(NSNumber *)percent {
5062 [progress_ setPercent:[percent floatValue]];
5063 [self updateProgress];
5066 - (void) setProgressStatus:(NSDictionary *)status {
5067 if (status == nil) {
5068 [progress_ setCurrent:0];
5069 [progress_ setTotal:0];
5070 [progress_ setSpeed:0];
5072 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5074 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5075 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5076 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5079 [self updateProgress];
5085 /* Package Cell {{{ */
5086 @interface PackageCell : CyteTableViewCell <
5087 CyteTableViewCellDelegate
5091 _H<NSString> description_;
5093 _H<NSString> source_;
5095 _H<Package> package_;
5096 _H<UIImage> placard_;
5100 - (PackageCell *) init;
5101 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5103 - (void) drawContentRect:(CGRect)rect;
5107 @implementation PackageCell
5109 - (PackageCell *) init {
5110 CGRect frame(CGRectMake(0, 0, 320, 74));
5111 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5112 UIView *content([self contentView]);
5113 CGRect bounds([content bounds]);
5115 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5116 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5117 [content addSubview:content_];
5119 [content_ setDelegate:self];
5120 [content_ setOpaque:YES];
5124 - (NSString *) accessibilityLabel {
5125 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5128 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5129 summarized_ = summary;
5141 Source *source = [package source];
5143 icon_ = [package icon];
5145 if (NSString *name = [package name])
5146 name_ = [NSString stringWithString:name];
5148 NSString *description(nil);
5150 if (description == nil && IsWildcat_)
5151 description = [package longDescription];
5152 if (description == nil)
5153 description = [package shortDescription];
5155 if (description != nil)
5156 description_ = [NSString stringWithString:description];
5158 commercial_ = [package isCommercial];
5162 NSString *label = nil;
5163 bool trusted = false;
5165 if (source != nil) {
5166 label = [source label];
5167 trusted = [source trusted];
5168 } else if ([[package id] isEqualToString:@"firmware"])
5169 label = UCLocalize("APPLE");
5171 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5173 NSString *from(label);
5175 NSString *section = [package simpleSection];
5176 if (section != nil && ![section isEqualToString:label]) {
5177 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5178 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5181 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5183 if (NSString *purpose = [package primaryPurpose])
5184 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5189 if (NSString *mode = [package_ mode]) {
5190 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5191 color = RemovingColor_;
5192 //placard = @"removing";
5194 color = InstallingColor_;
5195 //placard = @"installing";
5198 // XXX: the removing/installing placards are not @2x
5201 color = [UIColor whiteColor];
5203 if ([package installed] != nil)
5204 placard = @"installed";
5209 [content_ setBackgroundColor:color];
5212 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5214 [self setNeedsDisplay];
5215 [content_ setNeedsDisplay];
5218 - (void) drawSummaryContentRect:(CGRect)rect {
5219 bool highlighted(highlighted_);
5220 float width([self bounds].size.width);
5224 rect.size = [(UIImage *) icon_ size];
5226 rect.size.width /= 4;
5227 rect.size.height /= 4;
5229 rect.origin.x = 14 - rect.size.width / 4;
5230 rect.origin.y = 14 - rect.size.height / 4;
5232 [icon_ drawInRect:rect];
5235 if (badge_ != nil) {
5237 rect.size = [(UIImage *) badge_ size];
5239 rect.size.width /= 4;
5240 rect.size.height /= 4;
5242 rect.origin.x = 20 - rect.size.width / 4;
5243 rect.origin.y = 20 - rect.size.height / 4;
5245 [badge_ drawInRect:rect];
5252 UISetColor(commercial_ ? Purple_ : Black_);
5253 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5255 if (placard_ != nil)
5256 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5259 - (void) drawNormalContentRect:(CGRect)rect {
5260 bool highlighted(highlighted_);
5261 float width([self bounds].size.width);
5265 rect.size = [(UIImage *) icon_ size];
5267 rect.size.width /= 2;
5268 rect.size.height /= 2;
5270 rect.origin.x = 25 - rect.size.width / 2;
5271 rect.origin.y = 25 - rect.size.height / 2;
5273 [icon_ drawInRect:rect];
5276 if (badge_ != nil) {
5278 rect.size = [(UIImage *) badge_ size];
5280 rect.size.width /= 2;
5281 rect.size.height /= 2;
5283 rect.origin.x = 36 - rect.size.width / 2;
5284 rect.origin.y = 36 - rect.size.height / 2;
5286 [badge_ drawInRect:rect];
5293 UISetColor(commercial_ ? Purple_ : Black_);
5294 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5295 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5298 UISetColor(commercial_ ? Purplish_ : Gray_);
5299 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5301 if (placard_ != nil)
5302 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5305 - (void) drawContentRect:(CGRect)rect {
5307 [self drawSummaryContentRect:rect];
5309 [self drawNormalContentRect:rect];
5314 /* Section Cell {{{ */
5315 @interface SectionCell : CyteTableViewCell <
5316 CyteTableViewCellDelegate
5318 _H<NSString> basic_;
5319 _H<NSString> section_;
5321 _H<NSString> count_;
5323 _H<UISwitch> switch_;
5327 - (void) setSection:(Section *)section editing:(BOOL)editing;
5331 @implementation SectionCell
5333 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5334 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5335 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5336 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5337 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5339 UIView *content([self contentView]);
5340 CGRect bounds([content bounds]);
5342 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5343 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5344 [content addSubview:content_];
5345 [content_ setBackgroundColor:[UIColor whiteColor]];
5347 [content_ setDelegate:self];
5351 - (void) onSwitch:(id)sender {
5352 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5353 if (metadata == nil) {
5354 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5355 [Sections_ setObject:metadata forKey:basic_];
5358 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5362 - (void) setSection:(Section *)section editing:(BOOL)editing {
5363 if (editing != editing_) {
5365 [switch_ removeFromSuperview];
5367 [self addSubview:switch_];
5376 if (section == nil) {
5377 name_ = UCLocalize("ALL_PACKAGES");
5380 basic_ = [section name];
5381 section_ = [section localized];
5383 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5384 count_ = [NSString stringWithFormat:@"%d", [section count]];
5387 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5390 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5391 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5393 [content_ setNeedsDisplay];
5396 - (void) setFrame:(CGRect)frame {
5397 [super setFrame:frame];
5399 CGRect rect([switch_ frame]);
5400 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5403 - (NSString *) accessibilityLabel {
5407 - (void) drawContentRect:(CGRect)rect {
5408 bool highlighted(highlighted_ && !editing_);
5410 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5415 float width(rect.size.width);
5421 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5423 CGSize size = [count_ sizeWithFont:Font14_];
5427 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5433 /* File Table {{{ */
5434 @interface FileTable : CyteViewController <
5435 UITableViewDataSource,
5438 _transient Database *database_;
5439 _H<Package> package_;
5441 _H<NSMutableArray> files_;
5442 _H<UITableView, 2> list_;
5445 - (id) initWithDatabase:(Database *)database;
5446 - (void) setPackage:(Package *)package;
5450 @implementation FileTable
5452 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5453 return files_ == nil ? 0 : [files_ count];
5456 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5460 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5461 static NSString *reuseIdentifier = @"Cell";
5463 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5465 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5466 [cell setFont:[UIFont systemFontOfSize:16]];
5468 [cell setText:[files_ objectAtIndex:indexPath.row]];
5469 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5474 - (NSURL *) navigationURL {
5475 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5479 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5481 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5482 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5483 [list_ setRowHeight:24.0f];
5484 [(UITableView *) list_ setDataSource:self];
5485 [list_ setDelegate:self];
5486 [[self view] addSubview:list_];
5489 - (void) viewDidLoad {
5490 [super viewDidLoad];
5492 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5495 - (void) releaseSubviews {
5498 [super releaseSubviews];
5501 - (id) initWithDatabase:(Database *)database {
5502 if ((self = [super init]) != nil) {
5503 database_ = database;
5505 files_ = [NSMutableArray arrayWithCapacity:32];
5509 - (void) setPackage:(Package *)package {
5513 [files_ removeAllObjects];
5515 if (package != nil) {
5517 name_ = [package id];
5519 if (NSArray *files = [package files])
5520 [files_ addObjectsFromArray:files];
5522 if ([files_ count] != 0) {
5523 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5524 [files_ removeObjectAtIndex:0];
5525 [files_ sortUsingSelector:@selector(compareByPath:)];
5527 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5528 [stack addObject:@"/"];
5530 for (int i(0), e([files_ count]); i != e; ++i) {
5531 NSString *file = [files_ objectAtIndex:i];
5532 while (![file hasPrefix:[stack lastObject]])
5533 [stack removeLastObject];
5534 NSString *directory = [stack lastObject];
5535 [stack addObject:[file stringByAppendingString:@"/"]];
5536 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5537 ([stack count] - 2) * 3, "",
5538 [file substringFromIndex:[directory length]]
5547 - (void) reloadData {
5550 [self setPackage:[database_ packageWithName:name_]];
5555 /* Package Controller {{{ */
5556 @interface CYPackageController : CydiaWebViewController <
5557 UIActionSheetDelegate
5559 _transient Database *database_;
5560 _H<Package> package_;
5563 _H<NSMutableArray> buttons_;
5564 _H<UIBarButtonItem> button_;
5567 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5571 @implementation CYPackageController
5573 - (NSURL *) navigationURL {
5574 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5577 /* XXX: this is not safe at all... localization of /fail/ */
5578 - (void) _clickButtonWithName:(NSString *)name {
5579 if ([name isEqualToString:UCLocalize("CLEAR")])
5580 [delegate_ clearPackage:package_];
5581 else if ([name isEqualToString:UCLocalize("INSTALL")])
5582 [delegate_ installPackage:package_];
5583 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5584 [delegate_ installPackage:package_];
5585 else if ([name isEqualToString:UCLocalize("REMOVE")])
5586 [delegate_ removePackage:package_];
5587 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5588 [delegate_ installPackage:package_];
5589 else _assert(false);
5592 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5593 NSString *context([sheet context]);
5595 if ([context isEqualToString:@"modify"]) {
5596 if (button != [sheet cancelButtonIndex]) {
5597 NSString *buttonName = [buttons_ objectAtIndex:button];
5598 [self _clickButtonWithName:buttonName];
5601 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5605 - (bool) _allowJavaScriptPanel {
5610 - (void) _customButtonClicked {
5611 int count([buttons_ count]);
5616 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5618 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5619 [buttons addObjectsFromArray:buttons_];
5621 UIActionSheet *sheet = [[[UIActionSheet alloc]
5624 cancelButtonTitle:nil
5625 destructiveButtonTitle:nil
5626 otherButtonTitles:nil
5629 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5631 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5632 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5634 [sheet setContext:@"modify"];
5636 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5640 // We don't want to allow non-commercial packages to do custom things to the install button,
5641 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5642 - (void) customButtonClicked {
5644 [super customButtonClicked];
5646 [self _customButtonClicked];
5649 - (void) reloadButtonClicked {
5650 // Don't reload a commerical package by tapping the loading button,
5651 // but if it's not an Install button, we should forward it on.
5652 if (![package_ uninstalled])
5653 [self _customButtonClicked];
5656 - (void) applyLoadingTitle {
5657 // Don't show "Loading" as the title. Ever.
5660 - (UIBarButtonItem *) rightButton {
5665 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5666 if ((self = [super init]) != nil) {
5667 database_ = database;
5668 buttons_ = [NSMutableArray arrayWithCapacity:4];
5669 name_ = [NSString stringWithString:name];
5670 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5674 - (void) reloadData {
5677 package_ = [database_ packageWithName:name_];
5679 [buttons_ removeAllObjects];
5681 if (package_ != nil) {
5682 [(Package *) package_ parse];
5684 commercial_ = [package_ isCommercial];
5686 if ([package_ mode] != nil)
5687 [buttons_ addObject:UCLocalize("CLEAR")];
5688 if ([package_ source] == nil);
5689 else if ([package_ upgradableAndEssential:NO])
5690 [buttons_ addObject:UCLocalize("UPGRADE")];
5691 else if ([package_ uninstalled])
5692 [buttons_ addObject:UCLocalize("INSTALL")];
5694 [buttons_ addObject:UCLocalize("REINSTALL")];
5695 if (![package_ uninstalled])
5696 [buttons_ addObject:UCLocalize("REMOVE")];
5700 switch ([buttons_ count]) {
5701 case 0: title = nil; break;
5702 case 1: title = [buttons_ objectAtIndex:0]; break;
5703 default: title = UCLocalize("MODIFY"); break;
5706 button_ = [[[UIBarButtonItem alloc]
5708 style:UIBarButtonItemStylePlain
5710 action:@selector(customButtonClicked)
5714 - (bool) isLoading {
5715 return commercial_ ? [super isLoading] : false;
5721 /* Package List Controller {{{ */
5722 @interface PackageListController : CyteViewController <
5723 UITableViewDataSource,
5726 _transient Database *database_;
5728 _H<NSArray> packages_;
5729 _H<NSMutableArray> sections_;
5730 _H<UITableView, 2> list_;
5731 _H<NSMutableArray> index_;
5732 _H<NSMutableDictionary> indices_;
5733 _H<NSString> title_;
5734 unsigned reloading_;
5737 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5738 - (void) setDelegate:(id)delegate;
5739 - (void) resetCursor;
5744 @implementation PackageListController
5746 - (bool) isSummarized {
5750 - (bool) showsSections {
5754 - (void) deselectWithAnimation:(BOOL)animated {
5755 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5758 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5759 CGRect base = [[self view] bounds];
5760 base.size.height -= bounds.size.height;
5761 base.origin = [list_ frame].origin;
5763 [UIView beginAnimations:nil context:NULL];
5764 [UIView setAnimationBeginsFromCurrentState:YES];
5765 [UIView setAnimationCurve:curve];
5766 [UIView setAnimationDuration:duration];
5767 [list_ setFrame:base];
5768 [UIView commitAnimations];
5771 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5772 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5775 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5776 [self resizeForKeyboardBounds:bounds duration:0];
5779 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5780 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5781 *curve = UIViewAnimationCurveEaseInOut;
5783 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5785 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5788 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5791 - (void) keyboardWillShow:(NSNotification *)notification {
5794 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5795 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5797 NSTimeInterval duration;
5798 UIViewAnimationCurve curve;
5799 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5801 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);
5802 UIViewController *base = self;
5803 while ([base parentViewController] != nil)
5804 base = [base parentViewController];
5805 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5806 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5808 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5809 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5811 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5814 - (void) keyboardWillHide:(NSNotification *)notification {
5815 NSTimeInterval duration;
5816 UIViewAnimationCurve curve;
5817 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5819 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5822 - (void) viewWillAppear:(BOOL)animated {
5823 [super viewWillAppear:animated];
5825 [self resizeForKeyboardBounds:CGRectZero];
5826 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5827 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5830 - (void) viewWillDisappear:(BOOL)animated {
5831 [super viewWillDisappear:animated];
5833 [self resizeForKeyboardBounds:CGRectZero];
5834 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5835 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5838 - (void) viewDidAppear:(BOOL)animated {
5839 [super viewDidAppear:animated];
5840 [self deselectWithAnimation:animated];
5843 - (void) didSelectPackage:(Package *)package {
5844 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5845 [view setDelegate:delegate_];
5846 [[self navigationController] pushViewController:view animated:YES];
5849 #if TryIndexedCollation
5850 + (BOOL) hasIndexedCollation {
5851 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5855 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5856 NSInteger count([sections_ count]);
5857 return count == 0 ? 1 : count;
5860 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5861 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5863 return [[sections_ objectAtIndex:section] name];
5866 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5867 if ([sections_ count] == 0)
5869 return [[sections_ objectAtIndex:section] count];
5872 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5873 @synchronized (database_) {
5874 if ([database_ era] != era_)
5877 Section *section([sections_ objectAtIndex:[path section]]);
5878 NSInteger row([path row]);
5879 Package *package([packages_ objectAtIndex:([section row] + row)]);
5880 return [[package retain] autorelease];
5883 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5884 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5886 cell = [[[PackageCell alloc] init] autorelease];
5887 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5891 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5892 Package *package([self packageAtIndexPath:path]);
5893 package = [database_ packageWithName:[package id]];
5894 [self didSelectPackage:package];
5897 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5898 if (![self showsSections])
5904 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5905 #if TryIndexedCollation
5906 if ([[self class] hasIndexedCollation]) {
5907 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5914 - (void) updateHeight {
5915 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5918 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5919 if ((self = [super init]) != nil) {
5920 database_ = database;
5921 title_ = [title copy];
5922 [[self navigationItem] setTitle:title_];
5924 #if TryIndexedCollation
5925 if ([[self class] hasIndexedCollation])
5926 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5929 index_ = [NSMutableArray arrayWithCapacity:32];
5931 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5933 packages_ = [NSArray array];
5934 sections_ = [NSMutableArray arrayWithCapacity:16];
5939 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5941 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5942 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5943 [[self view] addSubview:list_];
5945 // XXX: is 20 the most optimal number here?
5946 [list_ setSectionIndexMinimumDisplayRowCount:20];
5948 [(UITableView *) list_ setDataSource:self];
5949 [list_ setDelegate:self];
5951 [self updateHeight];
5954 - (void) releaseSubviews {
5957 [super releaseSubviews];
5960 - (void) setDelegate:(id)delegate {
5961 delegate_ = delegate;
5964 - (bool) shouldYield {
5968 - (bool) shouldBlock {
5972 - (NSMutableArray *) _reloadPackages {
5973 @synchronized (database_) {
5974 era_ = [database_ era];
5975 NSArray *packages([database_ packages]);
5977 return [NSMutableArray arrayWithArray:packages];
5980 - (void) _reloadData {
5981 if (reloading_ != 0) {
5988 if ([self shouldYield]) {
5992 if (![self shouldBlock])
5995 hud = [delegate_ addProgressHUD];
5996 [hud setText:UCLocalize("LOADING")];
6000 packages = [self yieldToSelector:@selector(_reloadPackages)];
6003 [delegate_ removeProgressHUD:hud];
6004 } while (reloading_ == 2);
6008 packages = [self _reloadPackages];
6011 packages_ = packages;
6013 [indices_ removeAllObjects];
6014 [sections_ removeAllObjects];
6016 Section *section = nil;
6018 #if TryIndexedCollation
6019 if ([[self class] hasIndexedCollation]) {
6020 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6021 NSArray *titles = [collation sectionIndexTitles];
6024 _profile(PackageTable$reloadData$Section)
6025 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6029 _profile(PackageTable$reloadData$Section$Package)
6030 package = [packages_ objectAtIndex:offset];
6031 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6034 while (secidx < index) {
6037 _profile(PackageTable$reloadData$Section$Allocate)
6038 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6041 _profile(PackageTable$reloadData$Section$Add)
6042 [sections_ addObject:section];
6046 [section addToCount];
6052 [index_ removeAllObjects];
6054 bool sectioned([self showsSections]);
6056 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6057 [sections_ addObject:section];
6060 _profile(PackageTable$reloadData$Section)
6061 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6065 _profile(PackageTable$reloadData$Section$Package)
6066 package = [packages_ objectAtIndex:offset];
6067 index = [package index];
6070 if (sectioned && (section == nil || [section index] != index)) {
6071 _profile(PackageTable$reloadData$Section$Allocate)
6072 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6075 [index_ addObject:[section name]];
6076 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6078 _profile(PackageTable$reloadData$Section$Add)
6079 [sections_ addObject:section];
6083 [section addToCount];
6088 [self updateHeight];
6090 _profile(PackageTable$reloadData$List)
6091 [(UITableView *) list_ setDataSource:self];
6096 - (void) reloadData {
6098 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6101 - (void) resetCursor {
6102 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6105 - (void) clearData {
6106 [self updateHeight];
6108 [list_ setDataSource:nil];
6116 /* Filtered Package List Controller {{{ */
6117 @interface FilteredPackageListController : PackageListController {
6120 _H<NSObject> object_;
6123 - (void) setObject:(id)object;
6124 - (void) setObject:(id)object forFilter:(SEL)filter;
6127 - (void) setFilter:(SEL)filter;
6129 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6133 @implementation FilteredPackageListController
6139 - (void) setFilter:(SEL)filter {
6140 @synchronized (self) {
6143 /* XXX: this is an unsafe optimization of doomy hell */
6144 Method method(class_getInstanceMethod([Package class], filter));
6145 _assert(method != NULL);
6146 imp_ = method_getImplementation(method);
6147 _assert(imp_ != NULL);
6150 - (void) setObject:(id)object {
6151 @synchronized (self) {
6155 - (void) setObject:(id)object forFilter:(SEL)filter {
6156 @synchronized (self) {
6157 [self setFilter:filter];
6158 [self setObject:object];
6161 - (NSMutableArray *) _reloadPackages {
6162 @synchronized (database_) {
6163 era_ = [database_ era];
6164 NSArray *packages([database_ packages]);
6166 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6170 _H<NSObject> object;
6172 @synchronized (self) {
6178 _profile(PackageTable$reloadData$Filter)
6179 for (Package *package in packages)
6180 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6181 [filtered addObject:package];
6187 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6188 if ((self = [super initWithDatabase:database title:title]) != nil) {
6189 [self setFilter:filter];
6190 [self setObject:object];
6197 /* Home Controller {{{ */
6198 @interface HomeController : CydiaWebViewController {
6203 @implementation HomeController
6206 if ((self = [super init]) != nil) {
6207 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6212 - (NSURL *) navigationURL {
6213 return [NSURL URLWithString:@"cydia://home"];
6216 - (void) aboutButtonClicked {
6217 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6219 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6220 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6221 [alert setCancelButtonIndex:0];
6224 @"Copyright \u00a9 2008-2011\n"
6227 "Jay Freeman (saurik)\n"
6228 "saurik@saurik.com\n"
6229 "http://www.saurik.com/"
6235 - (UIBarButtonItem *) leftButton {
6236 return [[[UIBarButtonItem alloc]
6237 initWithTitle:UCLocalize("ABOUT")
6238 style:UIBarButtonItemStylePlain
6240 action:@selector(aboutButtonClicked)
6246 /* Manage Controller {{{ */
6247 @interface ManageController : CydiaWebViewController {
6250 - (void) queueStatusDidChange;
6254 @implementation ManageController
6257 if ((self = [super init]) != nil) {
6258 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6262 - (NSURL *) navigationURL {
6263 return [NSURL URLWithString:@"cydia://manage"];
6266 - (UIBarButtonItem *) leftButton {
6267 return [[[UIBarButtonItem alloc]
6268 initWithTitle:UCLocalize("SETTINGS")
6269 style:UIBarButtonItemStylePlain
6271 action:@selector(settingsButtonClicked)
6275 - (void) settingsButtonClicked {
6276 [delegate_ showSettings];
6279 - (void) queueButtonClicked {
6283 - (UIBarButtonItem *) customButton {
6284 return Queuing_ ? [[[UIBarButtonItem alloc]
6285 initWithTitle:UCLocalize("QUEUE")
6286 style:UIBarButtonItemStyleDone
6288 action:@selector(queueButtonClicked)
6289 ] autorelease] : [super customButton];
6292 - (void) queueStatusDidChange {
6293 [self applyRightButton];
6296 - (bool) isLoading {
6297 return !Queuing_ && [super isLoading];
6303 /* Refresh Bar {{{ */
6304 @interface RefreshBar : UINavigationBar {
6305 _H<UIProgressIndicator> indicator_;
6306 _H<UITextLabel> prompt_;
6307 _H<UIProgressBar> progress_;
6308 _H<UINavigationButton> cancel_;
6313 @implementation RefreshBar
6315 - (void) positionViews {
6316 CGRect frame = [cancel_ frame];
6317 frame.size = [cancel_ sizeThatFits:frame.size];
6318 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6319 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6320 [cancel_ setFrame:frame];
6322 CGSize prgsize = {75, 100};
6324 [self frame].size.width - prgsize.width - 10,
6325 ([self frame].size.height - prgsize.height) / 2
6327 [progress_ setFrame:prgrect];
6329 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6330 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6331 CGRect indrect = {{indoffset, indoffset}, indsize};
6332 [indicator_ setFrame:indrect];
6334 CGSize prmsize = {215, indsize.height + 4};
6336 indoffset * 2 + indsize.width,
6337 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6339 [prompt_ setFrame:prmrect];
6342 - (void) setFrame:(CGRect)frame {
6343 [super setFrame:frame];
6344 [self positionViews];
6347 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6348 if ((self = [super initWithFrame:frame]) != nil) {
6349 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6351 [self setBarStyle:UIBarStyleBlack];
6353 UIBarStyle barstyle([self _barStyle:NO]);
6354 bool ugly(barstyle == UIBarStyleDefault);
6356 UIProgressIndicatorStyle style = ugly ?
6357 UIProgressIndicatorStyleMediumBrown :
6358 UIProgressIndicatorStyleMediumWhite;
6360 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6361 [(UIProgressIndicator *) indicator_ setStyle:style];
6362 [indicator_ startAnimation];
6363 [self addSubview:indicator_];
6365 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6366 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6367 [prompt_ setBackgroundColor:[UIColor clearColor]];
6368 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6369 [self addSubview:prompt_];
6371 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6372 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6373 [(UIProgressBar *) progress_ setStyle:0];
6374 [self addSubview:progress_];
6376 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6377 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6378 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6379 [cancel_ setBarStyle:barstyle];
6381 [self positionViews];
6385 - (void) setCancellable:(bool)cancellable {
6387 [self addSubview:cancel_];
6389 [cancel_ removeFromSuperview];
6393 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6394 [progress_ setProgress:0];
6398 [self setCancellable:NO];
6401 - (void) setPrompt:(NSString *)prompt {
6402 [prompt_ setText:prompt];
6405 - (void) setProgress:(float)progress {
6406 [progress_ setProgress:progress];
6412 /* Cydia Navigation Controller Interface {{{ */
6413 @interface UINavigationController (Cydia)
6415 - (NSArray *) navigationURLCollection;
6416 - (void) unloadData;
6421 /* Cydia Tab Bar Controller {{{ */
6422 @interface CYTabBarController : UITabBarController <
6423 UITabBarControllerDelegate,
6426 _transient Database *database_;
6427 _H<RefreshBar, 1> refreshbar_;
6431 // XXX: ok, "updatedelegate_"?...
6432 _transient NSObject<CydiaDelegate> *updatedelegate_;
6434 _H<UIViewController> remembered_;
6435 _transient UIViewController *transient_;
6438 - (NSArray *) navigationURLCollection;
6439 - (void) dropBar:(BOOL)animated;
6440 - (void) beginUpdate;
6441 - (void) raiseBar:(BOOL)animated;
6443 - (void) unloadData;
6447 @implementation CYTabBarController
6449 - (void) setUnselectedViewController:(UIViewController *)transient {
6450 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6451 if (transient != nil) {
6452 if (transient_ == nil)
6453 remembered_ = [controllers objectAtIndex:0];
6454 transient_ = transient;
6455 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6456 [controllers replaceObjectAtIndex:0 withObject:transient_];
6457 [self setSelectedIndex:0];
6458 [self setViewControllers:controllers];
6459 [self concealTabBarSelection];
6460 } else if (remembered_ != nil) {
6461 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6462 transient_ = transient;
6463 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6465 [self setViewControllers:controllers];
6466 [self revealTabBarSelection];
6470 - (UIViewController *) unselectedViewController {
6474 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6475 if ([self unselectedViewController])
6476 [self setUnselectedViewController:nil];
6479 - (NSArray *) navigationURLCollection {
6480 NSMutableArray *items([NSMutableArray array]);
6482 // XXX: Should this deal with transient view controllers?
6483 for (id navigation in [self viewControllers]) {
6484 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6486 [items addObject:stack];
6492 - (void) unloadData {
6495 for (UINavigationController *controller in [self viewControllers])
6496 [controller unloadData];
6498 if (UIViewController *selected = [self selectedViewController])
6499 [selected reloadData];
6501 if (UIViewController *unselected = [self unselectedViewController]) {
6502 [unselected unloadData];
6503 [unselected reloadData];
6508 [[NSNotificationCenter defaultCenter] removeObserver:self];
6513 - (id) initWithDatabase:(Database *)database {
6514 if ((self = [super init]) != nil) {
6515 database_ = database;
6516 [self setDelegate:self];
6518 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6519 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6521 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6525 - (void) setUpdate:(NSDate *)date {
6529 - (void) beginUpdate {
6530 [(RefreshBar *) refreshbar_ start];
6533 [updatedelegate_ retainNetworkActivityIndicator];
6537 detachNewThreadSelector:@selector(performUpdate)
6543 - (void) performUpdate {
6544 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6547 status.setDelegate(self);
6548 [database_ updateWithStatus:status];
6551 performSelectorOnMainThread:@selector(completeUpdate)
6559 - (void) stopUpdateWithSelector:(SEL)selector {
6561 [updatedelegate_ releaseNetworkActivityIndicator];
6563 [self raiseBar:YES];
6566 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6569 - (void) completeUpdate {
6572 [self stopUpdateWithSelector:@selector(reloadData)];
6575 - (void) cancelUpdate {
6576 [self stopUpdateWithSelector:@selector(updateData)];
6579 - (void) cancelPressed {
6580 [self cancelUpdate];
6587 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6588 [refreshbar_ setPrompt:[event compoundMessage]];
6591 - (bool) isProgressCancelled {
6595 - (void) setProgressCancellable:(NSNumber *)cancellable {
6596 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6599 - (void) setProgressPercent:(NSNumber *)percent {
6600 [refreshbar_ setProgress:[percent floatValue]];
6603 - (void) setProgressStatus:(NSDictionary *)status {
6605 [self setProgressPercent:[status objectForKey:@"Percent"]];
6608 - (void) setUpdateDelegate:(id)delegate {
6609 updatedelegate_ = delegate;
6612 - (UIView *) transitionView {
6613 if ([self respondsToSelector:@selector(_transitionView)])
6614 return [self _transitionView];
6616 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6619 - (void) dropBar:(BOOL)animated {
6624 UIView *transition([self transitionView]);
6625 [[self view] addSubview:refreshbar_];
6627 CGRect barframe([refreshbar_ frame]);
6629 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6630 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6632 barframe.origin.y = 0;
6634 [refreshbar_ setFrame:barframe];
6637 [UIView beginAnimations:nil context:NULL];
6639 CGRect viewframe = [transition frame];
6640 viewframe.origin.y += barframe.size.height;
6641 viewframe.size.height -= barframe.size.height;
6642 [transition setFrame:viewframe];
6645 [UIView commitAnimations];
6647 // Ensure bar has the proper width for our view, it might have changed
6648 barframe.size.width = viewframe.size.width;
6649 [refreshbar_ setFrame:barframe];
6652 - (void) raiseBar:(BOOL)animated {
6657 UIView *transition([self transitionView]);
6658 [refreshbar_ removeFromSuperview];
6660 CGRect barframe([refreshbar_ frame]);
6663 [UIView beginAnimations:nil context:NULL];
6665 CGRect viewframe = [transition frame];
6666 viewframe.origin.y -= barframe.size.height;
6667 viewframe.size.height += barframe.size.height;
6668 [transition setFrame:viewframe];
6671 [UIView commitAnimations];
6674 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6675 bool dropped(dropped_);
6680 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6686 - (void) statusBarFrameChanged:(NSNotification *)notification {
6696 /* Cydia Navigation Controller Implementation {{{ */
6697 @implementation UINavigationController (Cydia)
6699 - (NSArray *) navigationURLCollection {
6700 NSMutableArray *stack([NSMutableArray array]);
6702 for (CyteViewController *controller in [self viewControllers]) {
6703 NSString *url = [[controller navigationURL] absoluteString];
6705 [stack addObject:url];
6711 - (void) reloadData {
6714 if (UIViewController *visible = [self visibleViewController])
6715 [visible reloadData];
6718 - (void) unloadData {
6719 for (CyteViewController *page in [self viewControllers])
6728 /* Cydia:// Protocol {{{ */
6729 @interface CydiaURLProtocol : NSURLProtocol {
6734 @implementation CydiaURLProtocol
6736 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6737 NSURL *url([request URL]);
6741 NSString *scheme([[url scheme] lowercaseString]);
6742 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6744 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6750 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6754 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6755 id<NSURLProtocolClient> client([self client]);
6757 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6759 NSData *data(UIImagePNGRepresentation(icon));
6761 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6762 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6763 [client URLProtocol:self didLoadData:data];
6764 [client URLProtocolDidFinishLoading:self];
6768 - (void) startLoading {
6769 id<NSURLProtocolClient> client([self client]);
6770 NSURLRequest *request([self request]);
6772 NSURL *url([request URL]);
6773 NSString *href([url absoluteString]);
6774 NSString *scheme([[url scheme] lowercaseString]);
6778 if ([scheme isEqualToString:@"cydia"])
6779 path = [href substringFromIndex:8];
6780 else if ([scheme isEqualToString:@"about"])
6781 path = [href substringFromIndex:12];
6782 else _assert(false);
6784 NSRange slash([path rangeOfString:@"/"]);
6787 if (slash.location == NSNotFound) {
6791 command = [path substringToIndex:slash.location];
6792 path = [path substringFromIndex:(slash.location + 1)];
6795 Database *database([Database sharedInstance]);
6797 if ([command isEqualToString:@"package-icon"]) {
6800 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6801 Package *package([database packageWithName:path]);
6805 UIImage *icon([package icon]);
6806 [self _returnPNGWithImage:icon forRequest:request];
6807 } else if ([command isEqualToString:@"source-icon"]) {
6810 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6811 NSString *source(Simplify(path));
6812 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6814 icon = [UIImage applicationImageNamed:@"unknown.png"];
6815 [self _returnPNGWithImage:icon forRequest:request];
6816 } else if ([command isEqualToString:@"uikit-image"]) {
6819 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6820 UIImage *icon(_UIImageWithName(path));
6821 [self _returnPNGWithImage:icon forRequest:request];
6822 } else if ([command isEqualToString:@"section-icon"]) {
6825 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6826 NSString *section(Simplify(path));
6827 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6829 icon = [UIImage applicationImageNamed:@"unknown.png"];
6830 [self _returnPNGWithImage:icon forRequest:request];
6832 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6836 - (void) stopLoading {
6842 /* Section Controller {{{ */
6843 @interface SectionController : FilteredPackageListController {
6844 _H<NSString> section_;
6847 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6851 @implementation SectionController
6853 - (NSURL *) navigationURL {
6854 NSString *name = section_;
6858 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6861 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6864 title = UCLocalize("ALL_PACKAGES");
6865 else if (![name isEqual:@""])
6866 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6868 title = UCLocalize("NO_SECTION");
6870 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6877 /* Sections Controller {{{ */
6878 @interface SectionsController : CyteViewController <
6879 UITableViewDataSource,
6882 _transient Database *database_;
6883 _H<NSMutableArray> sections_;
6884 _H<NSMutableArray> filtered_;
6885 _H<UITableView, 2> list_;
6888 - (id) initWithDatabase:(Database *)database;
6889 - (void) editButtonClicked;
6893 @implementation SectionsController
6895 - (NSURL *) navigationURL {
6896 return [NSURL URLWithString:@"cydia://sections"];
6899 - (void) updateNavigationItem {
6900 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6901 if ([sections_ count] == 0) {
6902 [[self navigationItem] setRightBarButtonItem:nil];
6904 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6905 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6907 action:@selector(editButtonClicked)
6908 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6912 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6913 [super setEditing:editing animated:animated];
6918 [delegate_ updateData];
6920 [self updateNavigationItem];
6923 - (void) viewDidAppear:(BOOL)animated {
6924 [super viewDidAppear:animated];
6925 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6928 - (void) viewWillDisappear:(BOOL)animated {
6929 [super viewWillDisappear:animated];
6930 if ([self isEditing]) [self setEditing:NO];
6933 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6934 Section *section = nil;
6935 int index = [indexPath row];
6936 if (![self isEditing]) {
6939 section = [filtered_ objectAtIndex:index];
6941 section = [sections_ objectAtIndex:index];
6946 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6947 if ([self isEditing])
6948 return [sections_ count];
6950 return [filtered_ count] + 1;
6953 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6957 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6958 static NSString *reuseIdentifier = @"SectionCell";
6960 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6962 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6964 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6969 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6970 if ([self isEditing])
6973 Section *section = [self sectionAtIndexPath:indexPath];
6975 SectionController *controller = [[[SectionController alloc]
6976 initWithDatabase:database_
6977 section:[section name]
6979 [controller setDelegate:delegate_];
6981 [[self navigationController] pushViewController:controller animated:YES];
6985 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6987 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6988 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6989 [list_ setRowHeight:45.0f];
6990 [(UITableView *) list_ setDataSource:self];
6991 [list_ setDelegate:self];
6992 [[self view] addSubview:list_];
6995 - (void) viewDidLoad {
6996 [super viewDidLoad];
6998 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7001 - (void) releaseSubviews {
7004 [super releaseSubviews];
7007 - (id) initWithDatabase:(Database *)database {
7008 if ((self = [super init]) != nil) {
7009 database_ = database;
7011 sections_ = [NSMutableArray arrayWithCapacity:16];
7012 filtered_ = [NSMutableArray arrayWithCapacity:16];
7016 - (void) reloadData {
7019 NSArray *packages = [database_ packages];
7021 [sections_ removeAllObjects];
7022 [filtered_ removeAllObjects];
7024 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7027 for (Package *package in packages) {
7028 NSString *name([package section]);
7029 NSString *key(name == nil ? @"" : name);
7033 _profile(SectionsView$reloadData$Section)
7034 section = [sections objectForKey:key];
7035 if (section == nil) {
7036 _profile(SectionsView$reloadData$Section$Allocate)
7037 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7038 [sections setObject:section forKey:key];
7043 [section addToCount];
7045 _profile(SectionsView$reloadData$Filter)
7046 if (![package valid] || ![package visible])
7054 [sections_ addObjectsFromArray:[sections allValues]];
7056 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7058 for (Section *section in (id) sections_) {
7059 size_t count([section row]);
7063 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7064 [section setCount:count];
7065 [filtered_ addObject:section];
7068 [self updateNavigationItem];
7073 - (void) editButtonClicked {
7074 [self setEditing:![self isEditing] animated:YES];
7080 /* Changes Controller {{{ */
7081 @interface ChangesController : CyteViewController <
7082 UITableViewDataSource,
7085 _transient Database *database_;
7087 _H<NSArray> packages_;
7088 _H<NSMutableArray> sections_;
7089 _H<UITableView, 2> list_;
7093 - (id) initWithDatabase:(Database *)database;
7097 @implementation ChangesController
7099 - (NSURL *) navigationURL {
7100 return [NSURL URLWithString:@"cydia://changes"];
7103 - (void) viewDidAppear:(BOOL)animated {
7104 [super viewDidAppear:animated];
7105 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7108 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7109 NSInteger count([sections_ count]);
7110 return count == 0 ? 1 : count;
7113 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7114 if ([sections_ count] == 0)
7116 return [[sections_ objectAtIndex:section] name];
7119 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7120 if ([sections_ count] == 0)
7122 return [[sections_ objectAtIndex:section] count];
7125 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7126 @synchronized (database_) {
7127 if ([database_ era] != era_)
7130 NSUInteger sectionIndex([path section]);
7131 if (sectionIndex >= [sections_ count])
7133 Section *section([sections_ objectAtIndex:sectionIndex]);
7134 NSInteger row([path row]);
7135 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7138 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7139 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7141 cell = [[[PackageCell alloc] init] autorelease];
7142 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7146 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7147 Package *package([self packageAtIndexPath:path]);
7148 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7149 [view setDelegate:delegate_];
7150 [[self navigationController] pushViewController:view animated:YES];
7154 - (void) refreshButtonClicked {
7155 [delegate_ beginUpdate];
7156 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7159 - (void) upgradeButtonClicked {
7160 [delegate_ distUpgrade];
7164 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7166 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7167 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7168 [list_ setRowHeight:73];
7169 [(UITableView *) list_ setDataSource:self];
7170 [list_ setDelegate:self];
7171 [[self view] addSubview:list_];
7174 - (void) viewDidLoad {
7175 [super viewDidLoad];
7177 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7180 - (void) releaseSubviews {
7183 [super releaseSubviews];
7186 - (id) initWithDatabase:(Database *)database {
7187 if ((self = [super init]) != nil) {
7188 database_ = database;
7190 packages_ = [NSArray array];
7191 sections_ = [NSMutableArray arrayWithCapacity:16];
7195 - (NSMutableArray *) _reloadPackages {
7196 @synchronized (database_) {
7197 era_ = [database_ era];
7198 NSArray *packages([database_ packages]);
7200 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7203 _profile(ChangesController$_reloadPackages$Filter)
7204 for (Package *package in packages)
7205 if ([package upgradableAndEssential:YES] || [package visible])
7206 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7209 _profile(ChangesController$_reloadPackages$radixSort)
7210 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7217 - (void) _reloadData {
7222 UIProgressHUD *hud([delegate_ addProgressHUD]);
7223 [hud setText:UCLocalize("LOADING")];
7224 //NSLog(@"HUD:%@::%@", delegate_, hud);
7225 packages = [self yieldToSelector:@selector(_reloadPackages)];
7226 [delegate_ removeProgressHUD:hud];
7228 packages = [self _reloadPackages];
7231 @synchronized (database_) {
7232 if (era_ != [database_ era])
7235 packages_ = packages;
7236 [sections_ removeAllObjects];
7238 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7239 Section *ignored = nil;
7240 Section *section = nil;
7244 bool unseens = false;
7246 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7248 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7249 Package *package = [packages_ objectAtIndex:offset];
7251 BOOL uae = [package upgradableAndEssential:YES];
7255 time_t seen([package seen]);
7257 if (section == nil || last != seen) {
7261 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7264 _profile(ChangesController$reloadData$Allocate)
7265 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7266 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7267 [sections_ addObject:section];
7271 [section addToCount];
7272 } else if ([package ignored]) {
7273 if (ignored == nil) {
7274 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7276 [ignored addToCount];
7279 [upgradable addToCount];
7284 CFRelease(formatter);
7287 Section *last = [sections_ lastObject];
7288 size_t count = [last count];
7289 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7290 [sections_ removeLastObject];
7293 if ([ignored count] != 0)
7294 [sections_ insertObject:ignored atIndex:0];
7296 [sections_ insertObject:upgradable atIndex:0];
7301 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7302 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7303 style:UIBarButtonItemStylePlain
7305 action:@selector(upgradeButtonClicked)
7308 if (![delegate_ updating])
7309 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7310 initWithTitle:UCLocalize("REFRESH")
7311 style:UIBarButtonItemStylePlain
7313 action:@selector(refreshButtonClicked)
7319 - (void) reloadData {
7321 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7326 /* Search Controller {{{ */
7327 @interface SearchController : FilteredPackageListController <
7330 _H<UISearchBar, 1> search_;
7334 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7335 - (void) reloadData;
7339 @implementation SearchController
7341 - (NSURL *) navigationURL {
7342 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7343 return [NSURL URLWithString:@"cydia://search"];
7345 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7348 - (void) useSearch {
7349 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7354 - (void) viewWillAppear:(BOOL)animated {
7355 [super viewWillAppear:animated];
7357 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7361 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7362 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7367 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7368 [search_ resignFirstResponder];
7372 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7373 [search_ setText:@""];
7374 [self searchBarButtonClicked:searchBar];
7377 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7378 [self searchBarButtonClicked:searchBar];
7381 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7382 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7386 - (bool) shouldYield {
7390 - (bool) shouldBlock {
7391 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7394 - (bool) isSummarized {
7395 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7398 - (bool) showsSections {
7402 - (NSMutableArray *) _reloadPackages {
7403 NSMutableArray *packages([super _reloadPackages]);
7404 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7405 [packages radixSortUsingSelector:@selector(rank)];
7409 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7410 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7411 search_ = [[[UISearchBar alloc] init] autorelease];
7412 [search_ setDelegate:self];
7415 [search_ setText:query];
7419 - (void) viewDidAppear:(BOOL)animated {
7420 [super viewDidAppear:animated];
7422 if (!searchloaded_) {
7423 searchloaded_ = YES;
7424 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7425 [search_ layoutSubviews];
7426 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7428 UITextField *textField;
7429 if ([search_ respondsToSelector:@selector(searchField)])
7430 textField = [search_ searchField];
7432 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7434 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7435 [textField setEnablesReturnKeyAutomatically:NO];
7436 [[self navigationItem] setTitleView:textField];
7440 - (void) reloadData {
7441 id object([search_ text]);
7442 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7443 object = [object componentsSeparatedByString:@" "];
7445 [self setObject:object];
7451 - (void) didSelectPackage:(Package *)package {
7452 [search_ resignFirstResponder];
7453 [super didSelectPackage:package];
7458 /* Package Settings Controller {{{ */
7459 @interface PackageSettingsController : CyteViewController <
7460 UITableViewDataSource,
7463 _transient Database *database_;
7465 _H<Package> package_;
7466 _H<UITableView, 2> table_;
7467 _H<UISwitch> subscribedSwitch_;
7468 _H<UISwitch> ignoredSwitch_;
7469 _H<UITableViewCell> subscribedCell_;
7470 _H<UITableViewCell> ignoredCell_;
7473 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7477 @implementation PackageSettingsController
7479 - (NSURL *) navigationURL {
7480 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7483 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7484 if (package_ == nil)
7487 if ([package_ installed] == nil)
7493 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7494 if (package_ == nil)
7497 // both sections contain just one item right now.
7501 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7505 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7507 return UCLocalize("SHOW_ALL_CHANGES_EX");
7509 return UCLocalize("IGNORE_UPGRADES_EX");
7512 - (void) onSubscribed:(id)control {
7513 bool value([control isOn]);
7514 if (package_ == nil)
7516 if ([package_ setSubscribed:value])
7517 [delegate_ updateData];
7520 - (void) _updateIgnored {
7521 const char *package([name_ UTF8String]);
7522 bool on([ignoredSwitch_ isOn]);
7524 pid_t pid(ExecFork());
7526 FILE *dpkg(popen("dpkg --set-selections", "w"));
7527 fwrite(package, strlen(package), 1, dpkg);
7530 fwrite(" hold\n", 6, 1, dpkg);
7532 fwrite(" install\n", 9, 1, dpkg);
7542 int result(waitpid(pid, &status, 0));
7545 _assert(result == pid);
7551 - (void) onIgnored:(id)control {
7552 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7553 [invocation setTarget:self];
7554 [invocation setSelector:@selector(_updateIgnored)];
7556 [delegate_ reloadDataWithInvocation:invocation];
7559 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7560 if (package_ == nil)
7563 switch ([indexPath section]) {
7564 case 0: return subscribedCell_;
7565 case 1: return ignoredCell_;
7574 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7576 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7577 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7578 [(UITableView *) table_ setDataSource:self];
7579 [table_ setDelegate:self];
7580 [[self view] addSubview:table_];
7582 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7583 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7584 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7586 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7587 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7588 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7590 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7591 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7592 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7593 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7595 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7596 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7597 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7598 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7601 - (void) viewDidLoad {
7602 [super viewDidLoad];
7604 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7607 - (void) releaseSubviews {
7609 subscribedCell_ = nil;
7611 ignoredSwitch_ = nil;
7612 subscribedSwitch_ = nil;
7614 [super releaseSubviews];
7617 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7618 if ((self = [super init]) != nil) {
7619 database_ = database;
7624 - (void) reloadData {
7627 package_ = [database_ packageWithName:name_];
7629 if (package_ != nil) {
7630 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7631 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7632 } // XXX: what now, G?
7634 [table_ reloadData];
7640 /* Installed Controller {{{ */
7641 @interface InstalledController : FilteredPackageListController {
7645 - (id) initWithDatabase:(Database *)database;
7647 - (void) updateRoleButton;
7648 - (void) queueStatusDidChange;
7652 @implementation InstalledController
7654 - (NSURL *) navigationURL {
7655 return [NSURL URLWithString:@"cydia://installed"];
7658 - (id) initWithDatabase:(Database *)database {
7659 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7660 [self updateRoleButton];
7661 [self queueStatusDidChange];
7666 - (void) queueButtonClicked {
7671 - (void) queueStatusDidChange {
7675 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7676 initWithTitle:UCLocalize("QUEUE")
7677 style:UIBarButtonItemStyleDone
7679 action:@selector(queueButtonClicked)
7682 [[self navigationItem] setLeftBarButtonItem:nil];
7688 - (void) updateRoleButton {
7689 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7690 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7691 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7692 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7694 action:@selector(roleButtonClicked)
7698 - (void) roleButtonClicked {
7699 [self setObject:[NSNumber numberWithBool:expert_]];
7703 [self updateRoleButton];
7709 /* Source Cell {{{ */
7710 @interface SourceCell : CyteTableViewCell <
7711 CyteTableViewCellDelegate
7714 _H<NSString> origin_;
7715 _H<NSString> label_;
7718 - (void) setSource:(Source *)source;
7722 @implementation SourceCell
7724 - (void) _setImage:(UIImage *)image {
7726 [content_ setNeedsDisplay];
7729 - (void) _setSource:(Source *)source {
7730 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7732 if (NSString *base = [source base])
7733 if ([base length] != 0) {
7734 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7736 if (NSData *data = [NSURLConnection
7737 sendSynchronousRequest:[NSURLRequest
7739 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7743 returningResponse:NULL
7746 if (UIImage *image = [UIImage imageWithData:data])
7747 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7753 - (void) setSource:(Source *)source {
7754 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7756 origin_ = [source name];
7757 label_ = [source uri];
7759 [content_ setNeedsDisplay];
7761 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7764 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7765 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7766 UIView *content([self contentView]);
7767 CGRect bounds([content bounds]);
7769 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7770 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7771 [content_ setBackgroundColor:[UIColor whiteColor]];
7772 [content addSubview:content_];
7774 [content_ setDelegate:self];
7775 [content_ setOpaque:YES];
7779 - (NSString *) accessibilityLabel {
7783 - (void) drawContentRect:(CGRect)rect {
7784 bool highlighted(highlighted_);
7785 float width(rect.size.width);
7788 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7795 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7799 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7804 /* Source Controller {{{ */
7805 @interface SourceController : FilteredPackageListController {
7806 _transient Source *source_;
7810 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7814 @implementation SourceController
7816 - (NSURL *) navigationURL {
7817 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7820 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7821 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7823 key_ = [source key];
7827 - (void) reloadData {
7828 source_ = [database_ sourceWithKey:key_];
7829 key_ = [source_ key];
7830 [self setObject:source_];
7832 [[self navigationItem] setTitle:[source_ label]];
7839 /* Sources Controller {{{ */
7840 @interface SourcesController : CyteViewController <
7841 UITableViewDataSource,
7844 _transient Database *database_;
7845 _H<UITableView, 2> list_;
7846 _H<NSMutableArray> sources_;
7850 _H<UIProgressHUD> hud_;
7853 //NSURLConnection *installer_;
7854 NSURLConnection *trivial_;
7855 NSURLConnection *trivial_bz2_;
7856 NSURLConnection *trivial_gz_;
7857 //NSURLConnection *automatic_;
7862 - (id) initWithDatabase:(Database *)database;
7863 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7867 @implementation SourcesController
7869 - (void) _releaseConnection:(NSURLConnection *)connection {
7870 if (connection != nil) {
7871 [connection cancel];
7872 //[connection setDelegate:nil];
7873 [connection release];
7878 //[self _releaseConnection:installer_];
7879 [self _releaseConnection:trivial_];
7880 [self _releaseConnection:trivial_gz_];
7881 [self _releaseConnection:trivial_bz2_];
7882 //[self _releaseConnection:automatic_];
7887 - (NSURL *) navigationURL {
7888 return [NSURL URLWithString:@"cydia://sources"];
7891 - (void) viewDidAppear:(BOOL)animated {
7892 [super viewDidAppear:animated];
7893 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7896 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7897 return offset_ == 0 ? 1 : 2;
7900 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7901 switch (section + (offset_ == 0 ? 1 : 0)) {
7902 case 0: return UCLocalize("ENTERED_BY_USER");
7903 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7909 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7910 int count = [sources_ count];
7912 case 0: return (offset_ == 0 ? count : offset_);
7913 case 1: return count - offset_;
7919 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7921 switch (indexPath.section) {
7922 case 0: idx = indexPath.row; break;
7923 case 1: idx = indexPath.row + offset_; break;
7927 return [sources_ objectAtIndex:idx];
7930 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7931 static NSString *cellIdentifier = @"SourceCell";
7933 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7934 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7935 [cell setSource:[self sourceAtIndexPath:indexPath]];
7936 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7941 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7942 Source *source = [self sourceAtIndexPath:indexPath];
7944 SourceController *controller = [[[SourceController alloc]
7945 initWithDatabase:database_
7949 [controller setDelegate:delegate_];
7951 [[self navigationController] pushViewController:controller animated:YES];
7954 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7955 Source *source = [self sourceAtIndexPath:indexPath];
7956 return [source record] != nil;
7959 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7960 if (editingStyle == UITableViewCellEditingStyleDelete) {
7961 Source *source = [self sourceAtIndexPath:indexPath];
7962 [Sources_ removeObjectForKey:[source key]];
7963 [delegate_ syncData];
7968 [delegate_ addTrivialSource:href_];
7969 [delegate_ syncData];
7972 - (NSString *) getWarning {
7973 NSString *href(href_);
7974 NSRange colon([href rangeOfString:@"://"]);
7975 if (colon.location != NSNotFound)
7976 href = [href substringFromIndex:(colon.location + 3)];
7977 href = [href stringByAddingPercentEscapes];
7978 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7979 href = [href stringByCachingURLWithCurrentCDN];
7981 NSURL *url([NSURL URLWithString:href]);
7983 NSStringEncoding encoding;
7984 NSError *error(nil);
7986 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7987 return [warning length] == 0 ? nil : warning;
7991 - (void) _endConnection:(NSURLConnection *)connection {
7992 // XXX: the memory management in this method is horribly awkward
7994 NSURLConnection **field = NULL;
7995 if (connection == trivial_)
7997 else if (connection == trivial_bz2_)
7998 field = &trivial_bz2_;
7999 else if (connection == trivial_gz_)
8000 field = &trivial_gz_;
8001 _assert(field != NULL);
8002 [connection release];
8007 trivial_bz2_ == nil &&
8010 [delegate_ releaseNetworkActivityIndicator];
8012 [delegate_ removeProgressHUD:hud_];
8018 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8021 UIAlertView *alert = [[[UIAlertView alloc]
8022 initWithTitle:UCLocalize("SOURCE_WARNING")
8025 cancelButtonTitle:UCLocalize("CANCEL")
8027 UCLocalize("ADD_ANYWAY"),
8031 [alert setContext:@"warning"];
8032 [alert setNumberOfRows:1];
8036 } else if (error_ != nil) {
8037 UIAlertView *alert = [[[UIAlertView alloc]
8038 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8039 message:[error_ localizedDescription]
8041 cancelButtonTitle:UCLocalize("OK")
8042 otherButtonTitles:nil
8045 [alert setContext:@"urlerror"];
8048 UIAlertView *alert = [[[UIAlertView alloc]
8049 initWithTitle:UCLocalize("NOT_REPOSITORY")
8050 message:UCLocalize("NOT_REPOSITORY_EX")
8052 cancelButtonTitle:UCLocalize("OK")
8053 otherButtonTitles:nil
8056 [alert setContext:@"trivial"];
8065 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8066 switch ([response statusCode]) {
8072 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8073 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8075 [self _endConnection:connection];
8078 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8079 [self _endConnection:connection];
8082 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8083 NSURL *url([NSURL URLWithString:href]);
8085 NSMutableURLRequest *request = [NSMutableURLRequest
8087 cachePolicy:NSURLRequestUseProtocolCachePolicy
8088 timeoutInterval:120.0
8091 [request setHTTPMethod:method];
8093 if (Machine_ != NULL)
8094 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8096 if ([url isCydiaSecure]) {
8097 if (UniqueID_ != nil)
8098 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8101 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8104 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8105 NSString *context([alert context]);
8107 if ([context isEqualToString:@"source"]) {
8110 NSString *href = [[alert textField] text];
8112 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8114 if (![href hasSuffix:@"/"])
8115 href_ = [href stringByAppendingString:@"/"];
8119 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8120 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8121 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8122 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8126 // XXX: this is stupid
8127 hud_ = [delegate_ addProgressHUD];
8128 [hud_ setText:UCLocalize("VERIFYING_URL")];
8129 [delegate_ retainNetworkActivityIndicator];
8138 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8139 } else if ([context isEqualToString:@"trivial"])
8140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8141 else if ([context isEqualToString:@"urlerror"])
8142 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8143 else if ([context isEqualToString:@"warning"]) {
8157 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8162 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8164 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8165 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8166 [list_ setRowHeight:56];
8167 [(UITableView *) list_ setDataSource:self];
8168 [list_ setDelegate:self];
8169 [[self view] addSubview:list_];
8172 - (void) viewDidLoad {
8173 [super viewDidLoad];
8175 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8176 [self updateButtonsForEditingStatus:NO animated:NO];
8179 - (void) releaseSubviews {
8182 [super releaseSubviews];
8185 - (id) initWithDatabase:(Database *)database {
8186 if ((self = [super init]) != nil) {
8187 database_ = database;
8188 sources_ = [NSMutableArray arrayWithCapacity:16];
8192 - (void) reloadData {
8196 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8199 [sources_ removeAllObjects];
8200 [sources_ addObjectsFromArray:[database_ sources]];
8202 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8205 int count([sources_ count]);
8207 for (int i = 0; i != count; i++) {
8208 if ([[sources_ objectAtIndex:i] record] == nil)
8213 [list_ setEditing:NO];
8214 [self updateButtonsForEditingStatus:NO animated:NO];
8218 - (void) showAddSourcePrompt {
8219 UIAlertView *alert = [[[UIAlertView alloc]
8220 initWithTitle:UCLocalize("ENTER_APT_URL")
8223 cancelButtonTitle:UCLocalize("CANCEL")
8225 UCLocalize("ADD_SOURCE"),
8229 [alert setContext:@"source"];
8231 [alert setNumberOfRows:1];
8232 [alert addTextFieldWithValue:@"http://" label:@""];
8234 UITextInputTraits *traits = [[alert textField] textInputTraits];
8235 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8236 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8237 [traits setKeyboardType:UIKeyboardTypeURL];
8238 // XXX: UIReturnKeyDone
8239 [traits setReturnKeyType:UIReturnKeyNext];
8244 - (void) addButtonClicked {
8245 [self showAddSourcePrompt];
8248 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8249 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8250 initWithTitle:UCLocalize("ADD")
8251 style:UIBarButtonItemStylePlain
8253 action:@selector(addButtonClicked)
8254 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8256 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8257 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8258 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8260 action:@selector(editButtonClicked)
8261 ] autorelease] animated:animated];
8263 if (IsWildcat_ && !editing)
8264 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8265 initWithTitle:UCLocalize("SETTINGS")
8266 style:UIBarButtonItemStylePlain
8268 action:@selector(settingsButtonClicked)
8272 - (void) settingsButtonClicked {
8273 [delegate_ showSettings];
8276 - (void) editButtonClicked {
8277 [list_ setEditing:![list_ isEditing] animated:YES];
8279 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8285 /* Settings Controller {{{ */
8286 @interface SettingsController : CyteViewController <
8287 UITableViewDataSource,
8290 _transient Database *database_;
8291 // XXX: ok, "roledelegate_"?...
8292 _transient id roledelegate_;
8293 _H<UITableView, 2> table_;
8294 _H<UISegmentedControl> segment_;
8295 _H<UIView> container_;
8298 - (void) showDoneButton;
8299 - (void) resizeSegmentedControl;
8303 @implementation SettingsController
8306 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8308 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8309 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8310 [table_ setDelegate:self];
8311 [(UITableView *) table_ setDataSource:self];
8312 [[self view] addSubview:table_];
8314 NSArray *items = [NSArray arrayWithObjects:
8316 UCLocalize("HACKER"),
8317 UCLocalize("DEVELOPER"),
8319 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8320 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8321 [container_ addSubview:segment_];
8324 - (void) viewDidLoad {
8325 [super viewDidLoad];
8327 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8330 if ([Role_ isEqualToString:@"User"]) index = 0;
8331 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8332 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8334 [segment_ setSelectedSegmentIndex:index];
8335 [self showDoneButton];
8338 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8339 [self resizeSegmentedControl];
8342 - (void) releaseSubviews {
8347 [super releaseSubviews];
8350 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8351 if ((self = [super init]) != nil) {
8352 database_ = database;
8353 roledelegate_ = delegate;
8357 - (void) resizeSegmentedControl {
8358 CGFloat width = [[self view] frame].size.width;
8359 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8362 - (void) viewWillAppear:(BOOL)animated {
8363 [super viewWillAppear:animated];
8365 [self resizeSegmentedControl];
8368 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8369 [self resizeSegmentedControl];
8372 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8373 [self resizeSegmentedControl];
8377 NSString *role(nil);
8379 switch ([segment_ selectedSegmentIndex]) {
8380 case 0: role = @"User"; break;
8381 case 1: role = @"Hacker"; break;
8382 case 2: role = @"Developer"; break;
8387 if (![role isEqualToString:Role_]) {
8388 bool rolling(Role_ == nil);
8391 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8395 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8399 [roledelegate_ loadData];
8401 [roledelegate_ updateData];
8405 - (void) segmentChanged:(UISegmentedControl *)control {
8406 [self showDoneButton];
8409 - (void) saveAndClose {
8412 [[self navigationItem] setRightBarButtonItem:nil];
8413 [[self navigationController] dismissModalViewControllerAnimated:YES];
8416 - (void) doneButtonClicked {
8417 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8418 [spinner startAnimating];
8419 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8420 [[self navigationItem] setRightBarButtonItem:spinItem];
8422 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8425 - (void) showDoneButton {
8426 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8427 initWithTitle:UCLocalize("DONE")
8428 style:UIBarButtonItemStyleDone
8430 action:@selector(doneButtonClicked)
8431 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8434 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8435 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8439 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8443 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8444 return nil; // This method is required by the protocol.
8447 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8449 return UCLocalize("ROLE_EX");
8451 return [NSString stringWithFormat:
8452 @"%@: %@\n%@: %@\n%@: %@",
8453 UCLocalize("USER"), UCLocalize("USER_EX"),
8454 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8455 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8460 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8461 return section == 3 ? 44.0f : 0;
8464 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8465 return section == 3 ? container_ : nil;
8468 - (void) reloadData {
8471 [table_ reloadData];
8476 /* Stash Controller {{{ */
8477 @interface StashController : CyteViewController {
8478 _H<UIActivityIndicatorView> spinner_;
8479 _H<UILabel> status_;
8480 _H<UILabel> caption_;
8485 @implementation StashController
8488 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8489 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8491 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8492 CGRect spinrect = [spinner_ frame];
8493 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8494 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8495 [spinner_ setFrame:spinrect];
8496 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8497 [[self view] addSubview:spinner_];
8498 [spinner_ startAnimating];
8501 captrect.size.width = [[self view] frame].size.width;
8502 captrect.size.height = 40.0f;
8503 captrect.origin.x = 0;
8504 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8505 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8506 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8507 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8508 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8509 [caption_ setTextColor:[UIColor whiteColor]];
8510 [caption_ setBackgroundColor:[UIColor clearColor]];
8511 [caption_ setShadowColor:[UIColor blackColor]];
8512 [caption_ setTextAlignment:UITextAlignmentCenter];
8513 [[self view] addSubview:caption_];
8516 statusrect.size.width = [[self view] frame].size.width;
8517 statusrect.size.height = 30.0f;
8518 statusrect.origin.x = 0;
8519 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8520 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8521 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8522 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8523 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8524 [status_ setTextColor:[UIColor whiteColor]];
8525 [status_ setBackgroundColor:[UIColor clearColor]];
8526 [status_ setShadowColor:[UIColor blackColor]];
8527 [status_ setTextAlignment:UITextAlignmentCenter];
8528 [[self view] addSubview:status_];
8531 - (void) releaseSubviews {
8536 [super releaseSubviews];
8542 @interface CYURLCache : SDURLCache {
8547 @implementation CYURLCache
8549 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8552 else if ([event isEqualToString:@"no-cache"])
8554 else if ([event isEqualToString:@"store"])
8556 else if ([event isEqualToString:@"invalid"])
8558 else if ([event isEqualToString:@"memory"])
8560 else if ([event isEqualToString:@"disk"])
8562 else if ([event isEqualToString:@"miss"])
8565 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8569 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8570 if (NSURLResponse *response = [cached response])
8571 if (NSString *mime = [response MIMEType])
8572 if ([mime isEqualToString:@"text/cache-manifest"]) {
8573 NSURL *url([response URL]);
8576 NSLog(@"###: %@", [url absoluteString]);
8579 @synchronized (HostConfig_) {
8580 [CachedURLs_ addObject:url];
8584 [super storeCachedResponse:cached forRequest:request];
8589 @interface Cydia : UIApplication <
8590 ConfirmationControllerDelegate,
8593 UINavigationControllerDelegate,
8594 UITabBarControllerDelegate
8596 _H<UIWindow> window_;
8597 _H<CYTabBarController> tabbar_;
8598 _H<CydiaLoadingViewController> emulated_;
8600 _H<NSMutableArray> essential_;
8601 _H<NSMutableArray> broken_;
8603 Database *database_;
8605 _H<NSURL> starturl_;
8610 _H<StashController> stash_;
8619 @implementation Cydia
8621 - (void) beginUpdate {
8622 [tabbar_ beginUpdate];
8626 return [tabbar_ updating];
8630 if ([broken_ count] != 0) {
8631 int count = [broken_ count];
8633 UIAlertView *alert = [[[UIAlertView alloc]
8634 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8635 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8637 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8639 UCLocalize("TEMPORARY_IGNORE"),
8643 [alert setContext:@"fixhalf"];
8644 [alert setNumberOfRows:2];
8646 } else if (!Ignored_ && [essential_ count] != 0) {
8647 int count = [essential_ count];
8649 UIAlertView *alert = [[[UIAlertView alloc]
8650 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8651 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8653 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8655 UCLocalize("UPGRADE_ESSENTIAL"),
8656 UCLocalize("COMPLETE_UPGRADE"),
8660 [alert setContext:@"upgrade"];
8665 - (void) _saveConfig {
8671 NSString *error(nil);
8673 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8675 NSError *error(nil);
8676 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8677 NSLog(@"failure to save metadata data: %@", error);
8682 NSLog(@"failure to serialize metadata: %@", error);
8687 // Navigation controller for the queuing badge.
8688 - (UINavigationController *) queueNavigationController {
8689 NSArray *controllers = [tabbar_ viewControllers];
8690 return [controllers objectAtIndex:3];
8693 - (void) unloadData {
8694 [tabbar_ unloadData];
8697 - (void) _updateData {
8702 UINavigationController *navigation = [self queueNavigationController];
8704 id queuedelegate = nil;
8705 if ([[navigation viewControllers] count] > 0)
8706 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8708 [queuedelegate queueStatusDidChange];
8709 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8712 - (void) _refreshIfPossible:(NSDate *)update {
8713 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8715 bool recently = false;
8716 if (update != nil) {
8717 NSTimeInterval interval([update timeIntervalSinceNow]);
8718 if (interval <= 0 && interval > -(15*60))
8722 // Don't automatic refresh if:
8723 // - We already refreshed recently.
8724 // - We already auto-refreshed this launch.
8725 // - Auto-refresh is disabled.
8726 if (recently || loaded_ || ManualRefresh) {
8727 // If we are cancelling, we need to make sure it knows it's already loaded.
8730 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8732 // We are going to load, so remember that.
8735 SCNetworkReachabilityFlags flags; {
8736 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8737 SCNetworkReachabilityGetFlags(reachability, &flags);
8738 CFRelease(reachability);
8741 // XXX: this elaborate mess is what Apple is using to determine this? :(
8742 // XXX: do we care if the user has to intervene? maybe that's ok?
8744 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8745 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8746 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8747 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8748 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8749 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8753 // If we can reach the server, auto-refresh!
8755 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8761 - (void) refreshIfPossible {
8762 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8765 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8766 @synchronized (self) {
8767 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8768 [hud setText:UCLocalize("RELOADING_DATA")];
8770 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8773 [self removeProgressHUD:hud];
8777 [essential_ removeAllObjects];
8778 [broken_ removeAllObjects];
8780 NSArray *packages([database_ packages]);
8781 for (Package *package in packages) {
8783 [broken_ addObject:package];
8784 if ([package upgradableAndEssential:NO]) {
8785 if ([package essential])
8786 [essential_ addObject:package];
8791 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8794 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8795 [changesItem setBadgeValue:badge];
8796 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8797 [self setApplicationIconBadgeNumber:changes];
8800 [changesItem setBadgeValue:nil];
8801 [changesItem setAnimatedBadge:NO];
8802 [self setApplicationIconBadgeNumber:0];
8807 [self refreshIfPossible];
8810 - (void) updateData {
8816 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8819 - (void) disemulate {
8820 if (emulated_ == nil)
8823 [window_ addSubview:[tabbar_ view]];
8824 [[emulated_ view] removeFromSuperview];
8826 [window_ setUserInteractionEnabled:YES];
8829 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8830 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8832 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8834 UIViewController *parent;
8835 if (emulated_ == nil)
8844 [parent presentModalViewController:navigation animated:YES];
8847 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8848 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8850 if (navigation != nil)
8851 [navigation pushViewController:progress animated:YES];
8853 [self presentModalViewController:progress force:YES];
8855 [progress invoke:invocation withTitle:title];
8859 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8860 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8863 - (void) repairWithInvocation:(NSInvocation *)invocation {
8865 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8869 - (void) repairWithSelector:(SEL)selector {
8870 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8873 - (void) reloadData {
8874 [self reloadDataWithInvocation:nil];
8880 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8881 _assert(file != NULL);
8883 for (NSString *key in [Sources_ allKeys]) {
8884 NSDictionary *source([Sources_ objectForKey:key]);
8886 fprintf(file, "%s %s %s\n",
8887 [[source objectForKey:@"Type"] UTF8String],
8888 [[source objectForKey:@"URI"] UTF8String],
8889 [[source objectForKey:@"Distribution"] UTF8String]
8895 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8898 - (void) addTrivialSource:(NSString *)href {
8899 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8902 @"./", @"Distribution",
8903 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8909 pkgProblemResolver *resolver = [database_ resolver];
8911 resolver->InstallProtect();
8912 if (!resolver->Resolve(true))
8917 // XXX: this is a really crappy way of doing this.
8918 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8919 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8920 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8921 if ([tabbar_ updating])
8922 [tabbar_ cancelUpdate];
8924 if (![database_ prepare])
8927 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8928 [page setDelegate:self];
8929 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8932 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8933 [tabbar_ presentModalViewController:confirm_ animated:YES];
8939 @synchronized (self) {
8944 - (void) clearPackage:(Package *)package {
8945 @synchronized (self) {
8952 - (void) installPackages:(NSArray *)packages {
8953 @synchronized (self) {
8954 for (Package *package in packages)
8961 - (void) installPackage:(Package *)package {
8962 @synchronized (self) {
8969 - (void) removePackage:(Package *)package {
8970 @synchronized (self) {
8977 - (void) distUpgrade {
8978 @synchronized (self) {
8979 if (![database_ upgrade])
8986 [database_ perform];
8987 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8990 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8993 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8997 - (void) showSettings {
8998 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9001 - (void) retainNetworkActivityIndicator {
9002 if (activity_++ == 0)
9003 [self setNetworkActivityIndicatorVisible:YES];
9006 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9010 - (void) releaseNetworkActivityIndicator {
9011 if (--activity_ == 0)
9012 [self setNetworkActivityIndicatorVisible:NO];
9015 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9020 - (void) cancelAndClear:(bool)clear {
9021 @synchronized (self) {
9033 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9034 NSString *context([alert context]);
9036 if ([context isEqualToString:@"conffile"]) {
9037 FILE *input = [database_ input];
9038 if (button == [alert cancelButtonIndex])
9039 fprintf(input, "N\n");
9040 else if (button == [alert firstOtherButtonIndex])
9041 fprintf(input, "Y\n");
9044 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9045 } else if ([context isEqualToString:@"fixhalf"]) {
9046 if (button == [alert cancelButtonIndex]) {
9047 @synchronized (self) {
9048 for (Package *broken in (id) broken_) {
9051 NSString *id = [broken id];
9052 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9053 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9054 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9055 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9061 } else if (button == [alert firstOtherButtonIndex]) {
9062 [broken_ removeAllObjects];
9066 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9067 } else if ([context isEqualToString:@"upgrade"]) {
9068 if (button == [alert firstOtherButtonIndex]) {
9069 @synchronized (self) {
9070 for (Package *essential in (id) essential_)
9071 [essential install];
9076 } else if (button == [alert firstOtherButtonIndex] + 1) {
9078 } else if (button == [alert cancelButtonIndex]) {
9082 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9086 - (void) system:(NSString *)command {
9087 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9090 system([command UTF8String]);
9096 - (void) applicationWillSuspend {
9098 [super applicationWillSuspend];
9101 - (BOOL) isSafeToSuspend {
9104 NSLog(@"isSafeToSuspend: locked_ != 0");
9109 // Use external process status API internally.
9110 // This is probably a really bad idea.
9111 // XXX: what is the point of this? does this solve anything at all?
9112 uint64_t status = 0;
9114 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9115 notify_get_state(notify_token, &status);
9116 notify_cancel(notify_token);
9121 NSLog(@"isSafeToSuspend: status != 0");
9127 NSLog(@"isSafeToSuspend: -> true");
9132 - (void) applicationSuspend:(__GSEvent *)event {
9133 if ([self isSafeToSuspend])
9134 [super applicationSuspend:event];
9137 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9138 if ([self isSafeToSuspend])
9139 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9142 - (void) _setSuspended:(BOOL)value {
9143 if ([self isSafeToSuspend])
9144 [super _setSuspended:value];
9147 - (UIProgressHUD *) addProgressHUD {
9148 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9149 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9151 [window_ setUserInteractionEnabled:NO];
9153 UIViewController *target(tabbar_);
9154 if (UIViewController *modal = [target modalViewController])
9157 UIView *view([target view]);
9158 [view addSubview:hud];
9166 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9169 [hud removeFromSuperview];
9170 [window_ setUserInteractionEnabled:YES];
9173 - (CyteViewController *) pageForPackage:(NSString *)name {
9174 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9177 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9178 NSString *scheme([[url scheme] lowercaseString]);
9179 if ([[url absoluteString] length] <= [scheme length] + 3)
9181 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9182 NSArray *components([path pathComponents]);
9184 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9185 return [self pageForPackage:[components objectAtIndex:1]];
9187 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9190 NSString *base([components objectAtIndex:0]);
9192 CyteViewController *controller = nil;
9194 if ([base isEqualToString:@"url"]) {
9195 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9196 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9197 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9198 } else if (!external && [components count] == 1) {
9199 if ([base isEqualToString:@"manage"]) {
9200 controller = [[[ManageController alloc] init] autorelease];
9203 if ([base isEqualToString:@"sources"]) {
9204 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9207 if ([base isEqualToString:@"home"]) {
9208 controller = [[[HomeController alloc] init] autorelease];
9211 if ([base isEqualToString:@"sections"]) {
9212 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9215 if ([base isEqualToString:@"search"]) {
9216 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9219 if ([base isEqualToString:@"changes"]) {
9220 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9223 if ([base isEqualToString:@"installed"]) {
9224 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9226 } else if ([components count] == 2) {
9227 NSString *argument = [components objectAtIndex:1];
9229 if ([base isEqualToString:@"package"]) {
9230 controller = [self pageForPackage:argument];
9233 if (!external && [base isEqualToString:@"search"]) {
9234 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9237 if (!external && [base isEqualToString:@"sections"]) {
9238 if ([argument isEqualToString:@"all"])
9240 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9243 if (!external && [base isEqualToString:@"sources"]) {
9244 if ([argument isEqualToString:@"add"]) {
9245 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9246 [(SourcesController *)controller showAddSourcePrompt];
9248 Source *source = [database_ sourceWithKey:argument];
9249 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9253 if (!external && [base isEqualToString:@"launch"]) {
9254 [self launchApplicationWithIdentifier:argument suspended:NO];
9257 } else if (!external && [components count] == 3) {
9258 NSString *arg1 = [components objectAtIndex:1];
9259 NSString *arg2 = [components objectAtIndex:2];
9261 if ([base isEqualToString:@"package"]) {
9262 if ([arg2 isEqualToString:@"settings"]) {
9263 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9264 } else if ([arg2 isEqualToString:@"files"]) {
9265 if (Package *package = [database_ packageWithName:arg1]) {
9266 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9267 [(FileTable *)controller setPackage:package];
9273 [controller setDelegate:self];
9277 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9278 CyteViewController *page([self pageForURL:url forExternal:external]);
9281 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9282 [nav setViewControllers:[NSArray arrayWithObject:page]];
9283 [tabbar_ setUnselectedViewController:nav];
9289 - (void) applicationOpenURL:(NSURL *)url {
9290 [super applicationOpenURL:url];
9295 [self openCydiaURL:url forExternal:YES];
9298 - (void) applicationWillResignActive:(UIApplication *)application {
9299 // Stop refreshing if you get a phone call or lock the device.
9300 if ([tabbar_ updating])
9301 [tabbar_ cancelUpdate];
9303 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9304 [super applicationWillResignActive:application];
9307 - (void) applicationWillTerminate:(UIApplication *)application {
9309 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9310 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9311 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9316 - (void) setConfigurationData:(NSString *)data {
9317 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9319 if (!conffile_r(data)) {
9320 lprintf("E:invalid conffile\n");
9324 NSString *ofile = conffile_r[1];
9325 //NSString *nfile = conffile_r[2];
9327 UIAlertView *alert = [[[UIAlertView alloc]
9328 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9329 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9331 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9333 UCLocalize("ACCEPT_NEW_COPY"),
9334 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9338 [alert setContext:@"conffile"];
9339 [alert setNumberOfRows:2];
9343 - (void) addStashController {
9345 stash_ = [[[StashController alloc] init] autorelease];
9346 [window_ addSubview:[stash_ view]];
9349 - (void) removeStashController {
9350 [[stash_ view] removeFromSuperview];
9356 [self setIdleTimerDisabled:YES];
9358 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9359 UpdateExternalStatus(1);
9360 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9361 UpdateExternalStatus(0);
9363 [self removeStashController];
9365 if (ExecFork() == 0) {
9366 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9367 perror("launchctl stop");
9371 - (void) setupViewControllers {
9372 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9374 NSMutableArray *items([NSMutableArray arrayWithObjects:
9375 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9376 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9377 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9378 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9382 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9383 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9385 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9388 NSMutableArray *controllers([NSMutableArray array]);
9389 for (UITabBarItem *item in items) {
9390 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9391 [controller setTabBarItem:item];
9392 [controllers addObject:controller];
9394 [tabbar_ setViewControllers:controllers];
9396 [tabbar_ setUpdateDelegate:self];
9399 - (void) applicationDidFinishLaunching:(id)unused {
9401 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9402 [self setApplicationSupportsShakeToEdit:NO];
9404 @synchronized (HostConfig_) {
9405 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9408 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9409 initWithMemoryCapacity:524288
9410 diskCapacity:10485760
9411 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9414 [CydiaWebViewController _initialize];
9416 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9418 // this would disallow http{,s} URLs from accessing this data
9419 //[WebView registerURLSchemeAsLocal:@"cydia"];
9421 Font12_ = [UIFont systemFontOfSize:12];
9422 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9423 Font14_ = [UIFont systemFontOfSize:14];
9424 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9425 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9427 essential_ = [NSMutableArray arrayWithCapacity:4];
9428 broken_ = [NSMutableArray arrayWithCapacity:4];
9430 // XXX: I really need this thing... like, seriously... I'm sorry
9431 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9433 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9434 [window_ orderFront:self];
9435 [window_ makeKey:self];
9436 [window_ setHidden:NO];
9439 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9440 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9441 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9442 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9443 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9444 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9445 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9446 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9447 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9450 [self addStashController];
9451 // XXX: this would be much cleaner as a yieldToSelector:
9452 // that way the removeStashController could happen right here inline
9453 // we also could no longer require the useless stash_ field anymore
9454 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9458 database_ = [Database sharedInstance];
9459 [database_ setDelegate:self];
9461 [window_ setUserInteractionEnabled:NO];
9462 [self setupViewControllers];
9464 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9465 [window_ addSubview:[emulated_ view]];
9467 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9471 - (NSArray *) defaultStartPages {
9472 NSMutableArray *standard = [NSMutableArray array];
9473 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9474 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9475 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9477 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9479 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9480 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9482 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9489 [window_ setUserInteractionEnabled:YES];
9490 [self showSettings];
9493 if ([emulated_ modalViewController] != nil)
9494 [emulated_ dismissModalViewControllerAnimated:YES];
9495 [window_ setUserInteractionEnabled:NO];
9503 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9504 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9505 int standardIndex = 0;
9506 NSArray *standard = [self defaultStartPages];
9513 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9514 if (valid && closed != nil) {
9515 NSTimeInterval interval([closed timeIntervalSinceNow]);
9516 // XXX: Is 15 minutes the optimal time here?
9517 if (interval > 0 && interval <= -(15*60))
9521 if (valid && [saved count] != [standard count])
9525 for (unsigned int i = 0; i < [standard count]; i++) {
9526 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9527 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9528 // but it's good enough for now.
9529 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9536 NSArray *items = nil;
9538 [tabbar_ setSelectedIndex:savedIndex];
9541 [tabbar_ setSelectedIndex:standardIndex];
9545 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9546 NSArray *stack = [items objectAtIndex:tab];
9547 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9548 NSMutableArray *current = [NSMutableArray array];
9550 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9551 NSString *addr = [stack objectAtIndex:nav];
9552 NSURL *url = [NSURL URLWithString:addr];
9553 CyteViewController *page = [self pageForURL:url forExternal:NO];
9555 [current addObject:page];
9558 [navigation setViewControllers:current];
9561 // (Try to) show the startup URL.
9562 if (starturl_ != nil) {
9563 [self openCydiaURL:starturl_ forExternal:NO];
9568 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9569 if (item != nil && IsWildcat_) {
9570 [sheet showFromBarButtonItem:item animated:YES];
9572 [sheet showInView:window_];
9576 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9577 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9578 [progress setTitle:task];
9579 [progress addProgressEvent:event];
9582 - (void) addProgressEventForTask:(NSArray *)data {
9583 CydiaProgressEvent *event([data objectAtIndex:0]);
9584 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9585 [self addProgressEvent:event forTask:task];
9588 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9589 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9595 id Alloc_(id self, SEL selector) {
9596 id object = alloc_(self, selector);
9597 lprintf("[%s]A-%p\n", self->isa->name, object);
9602 id Dealloc_(id self, SEL selector) {
9603 id object = dealloc_(self, selector);
9604 lprintf("[%s]D-%p\n", self->isa->name, object);
9608 Class $WebDefaultUIKitDelegate;
9610 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9611 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9612 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9613 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9616 static NSSet *MobilizedFiles_;
9618 static NSURL *MobilizeURL(NSURL *url) {
9619 NSString *path([url path]);
9620 if ([path hasPrefix:@"/var/root/"]) {
9621 NSString *file([path substringFromIndex:10]);
9622 if ([MobilizedFiles_ containsObject:file])
9623 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9629 Class $CFXPreferencesPropertyListSource;
9630 @class CFXPreferencesPropertyListSource;
9632 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9633 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9634 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9635 url = MobilizeURL(url);
9636 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9637 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9643 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9644 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9645 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9646 url = MobilizeURL(url);
9647 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9648 //NSLog(@"%@ %@", [url absoluteString], value);
9654 Class $NSURLConnection;
9656 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9657 NSMutableURLRequest *copy([request mutableCopy]);
9659 NSURL *url([copy URL]);
9661 NSString *href([url absoluteString]);
9662 NSString *host([url host]);
9663 NSString *scheme([[url scheme] lowercaseString]);
9665 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9667 @synchronized (HostConfig_) {
9668 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9669 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9670 [copy setHTTPShouldUsePipelining:YES];
9672 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9673 if ([control isEqualToString:@"max-age=0"])
9674 if ([CachedURLs_ containsObject:href]) {
9676 NSLog(@"~~~: %@", href);
9679 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9681 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9682 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9683 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9687 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9691 int main(int argc, char *argv[]) {
9692 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9696 UpdateExternalStatus(0);
9698 if (Class $UIDevice = objc_getClass("UIDevice")) {
9699 UIDevice *device([$UIDevice currentDevice]);
9700 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9704 UIScreen *screen([UIScreen mainScreen]);
9705 if ([screen respondsToSelector:@selector(scale)])
9706 ScreenScale_ = [screen scale];
9710 UIDevice *device([UIDevice currentDevice]);
9711 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9714 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9715 if (idiom == UIUserInterfaceIdiomPhone)
9717 else if (idiom == UIUserInterfaceIdiomPad)
9720 NSLog(@"unknown UIUserInterfaceIdiom!");
9723 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9725 HostConfig_ = [[[NSObject alloc] init] autorelease];
9726 @synchronized (HostConfig_) {
9727 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9728 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9729 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9730 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9731 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9734 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9736 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9738 MobilizedFiles_ = [NSMutableSet setWithObjects:
9739 @"Library/Preferences/com.apple.Accessibility.plist",
9740 @"Library/Preferences/com.apple.preferences.sounds.plist",
9743 /* Library Hacks {{{ */
9744 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9746 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9748 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9749 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9750 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9751 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9754 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9755 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9756 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9757 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9760 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9761 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9762 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9763 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9764 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9767 $NSURLConnection = objc_getClass("NSURLConnection");
9768 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9769 if (NSURLConnection$init$ != NULL) {
9770 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9771 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9774 /* Set Locale {{{ */
9775 Locale_ = CFLocaleCopyCurrent();
9776 Languages_ = [NSLocale preferredLanguages];
9778 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9779 //NSLog(@"%@", [Languages_ description]);
9782 if (Locale_ != NULL)
9783 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9784 else if (Languages_ != nil && [Languages_ count] != 0)
9785 lang = [[Languages_ objectAtIndex:0] UTF8String];
9787 // XXX: consider just setting to C and then falling through?
9791 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9792 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9795 NSLog(@"Setting Language: %s", lang);
9798 setenv("LANG", lang, true);
9799 std::setlocale(LC_ALL, lang);
9803 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9805 /* Parse Arguments {{{ */
9806 bool substrate(false);
9812 for (int argi(1); argi != argc; ++argi)
9813 if (strcmp(argv[argi], "--") == 0) {
9815 argv[argi] = argv[0];
9821 for (int argi(1); argi != arge; ++argi)
9822 if (strcmp(args[argi], "--substrate") == 0)
9825 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9829 App_ = [[NSBundle mainBundle] bundlePath];
9835 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9836 alloc_ = alloc->method_imp;
9837 alloc->method_imp = (IMP) &Alloc_;*/
9839 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9840 dealloc_ = dealloc->method_imp;
9841 dealloc->method_imp = (IMP) &Dealloc_;*/
9843 /* System Information {{{ */
9847 size = sizeof(maxproc);
9848 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9849 perror("sysctlbyname(\"kern.maxproc\", ?)");
9850 else if (maxproc < 64) {
9852 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9853 perror("sysctlbyname(\"kern.maxproc\", #)");
9856 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9857 char *osversion = new char[size];
9858 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9859 perror("sysctlbyname(\"kern.osversion\", ?)");
9861 System_ = [NSString stringWithUTF8String:osversion];
9863 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9864 char *machine = new char[size];
9865 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9866 perror("sysctlbyname(\"hw.machine\", ?)");
9870 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9871 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9872 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9874 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9876 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9877 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9878 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9880 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9881 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9882 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9884 if (mcc != NULL && mnc != NULL)
9885 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9892 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9893 Build_ = [system objectForKey:@"ProductBuildVersion"];
9894 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9895 Product_ = [info objectForKey:@"SafariProductVersion"];
9896 Safari_ = [info objectForKey:@"CFBundleVersion"];
9899 /* Load Database {{{ */
9901 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9903 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9905 if (Metadata_ == NULL)
9906 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9908 Settings_ = [Metadata_ objectForKey:@"Settings"];
9910 Packages_ = [Metadata_ objectForKey:@"Packages"];
9911 Sections_ = [Metadata_ objectForKey:@"Sections"];
9912 Sources_ = [Metadata_ objectForKey:@"Sources"];
9914 Token_ = [Metadata_ objectForKey:@"Token"];
9917 if (Settings_ != nil)
9918 Role_ = [Settings_ objectForKey:@"Role"];
9920 if (Sections_ == nil) {
9921 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9922 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9925 if (Sources_ == nil) {
9926 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9927 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9932 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9935 if (Packages_ != nil) {
9937 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9941 [Metadata_ removeObjectForKey:@"Packages"];
9947 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9949 #define MobileSubstrate_(name) \
9950 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9951 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9952 if (handle == NULL) \
9953 NSLog(@"%s", dlerror()); \
9956 MobileSubstrate_(Activator)
9957 MobileSubstrate_(libstatusbar)
9958 MobileSubstrate_(SimulatedKeyEvents)
9959 MobileSubstrate_(WinterBoard)
9961 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9962 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9964 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9966 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9967 unlink("/tmp/.cydia.fw");
9969 } else if (access("/User", F_OK) != 0 || version < 4) {
9972 system("/usr/libexec/cydia/firmware.sh");
9976 _assert([[NSFileManager defaultManager]
9977 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9978 withIntermediateDirectories:YES
9983 if (access("/tmp/cydia.chk", F_OK) == 0) {
9984 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9985 _assert(errno == ENOENT);
9986 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9987 _assert(errno == ENOENT);
9990 /* APT Initialization {{{ */
9991 _assert(pkgInitConfig(*_config));
9992 _assert(pkgInitSystem(*_config, _system));
9995 _config->Set("APT::Acquire::Translation", lang);
9997 // XXX: this timeout might be important :(
9998 //_config->Set("Acquire::http::Timeout", 15);
10000 _config->Set("Acquire::http::MaxParallel", 3);
10002 /* Color Choices {{{ */
10003 space_ = CGColorSpaceCreateDeviceRGB();
10005 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10006 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10007 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10008 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10009 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10010 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10011 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10012 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10013 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10015 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10016 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10018 /* UIKit Configuration {{{ */
10019 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10020 if ($GSFontSetUseLegacyFontMetrics != NULL)
10021 $GSFontSetUseLegacyFontMetrics(YES);
10023 // XXX: I have a feeling this was important
10024 //UIKeyboardDisableAutomaticAppearance();
10027 Colon_ = UCLocalize("COLON_DELIMITED");
10028 Elision_ = UCLocalize("ELISION");
10029 Error_ = UCLocalize("ERROR");
10030 Warning_ = UCLocalize("WARNING");
10033 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10035 CGColorSpaceRelease(space_);
10036 CFRelease(Locale_);