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);
209 #define Cydia_ CYDIA_VERSION
211 #define lprintf(args...) fprintf(stderr, args)
214 #define TraceLogging (1 && !ForRelease)
215 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
216 #define ProfileTimes (0 && !ForRelease)
217 #define ForSaurik (0 && !ForRelease)
218 #define LogBrowser (0 && !ForRelease)
219 #define TrackResize (0 && !ForRelease)
220 #define ManualRefresh (1 && !ForRelease)
221 #define ShowInternals (0 && !ForRelease)
222 #define AlwaysReload (0 && !ForRelease)
223 #define TryIndexedCollation (0 && !ForRelease)
227 #define _trace(args...)
232 #define _profile(name) {
235 #define PrintTimes() do {} while (false)
238 // Hash Functions/Structures {{{
239 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
247 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
249 static _finline NSString *CydiaURL(NSString *path) {
251 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
252 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
253 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
254 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
255 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
257 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
260 static _finline void UpdateExternalStatus(uint64_t newStatus) {
262 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
263 notify_set_state(notify_token, newStatus);
264 notify_cancel(notify_token);
266 notify_post("com.saurik.Cydia.status");
269 /* NSForcedOrderingSearch doesn't work on the iPhone */
270 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
271 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
272 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
274 /* Insertion Sort {{{ */
276 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
277 const char *ptr = (const char *)list;
279 CFIndex half = count / 2;
280 const char *probe = ptr + elementSize * half;
281 CFComparisonResult cr = comparator(element, probe, context);
282 if (0 == cr) return (probe - (const char *)list) / elementSize;
283 ptr = (cr < 0) ? ptr : probe + elementSize;
284 count = (cr < 0) ? half : (half + (count & 1) - 1);
286 return (ptr - (const char *)list) / elementSize;
289 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
290 const char *ptr = (const char *)list;
292 CFIndex half = count / 2;
293 const char *probe = ptr + elementSize * half;
294 CFComparisonResult cr = comparator(element, probe, context);
295 if (0 == cr) return (probe - (const char *)list) / elementSize;
296 ptr = (cr < 0) ? ptr : probe + elementSize;
297 count = (cr < 0) ? half : (half + (count & 1) - 1);
299 return (ptr - (const char *)list) / elementSize;
302 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
303 if (range.length == 0)
305 const void **values(new const void *[range.length]);
306 CFArrayGetValues(array, range, values);
308 #if HistogramInsertionSort > 0
309 uint32_t total(0), *offsets(new uint32_t[range.length]);
312 for (CFIndex index(1); index != range.length; ++index) {
313 const void *value(values[index]);
314 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
315 CFIndex correct(index);
316 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
317 #if HistogramInsertionSort > 1
318 NSLog(@"%@ < %@", value, values[correct - 1]);
323 if (correct != index) {
324 size_t offset(index - correct);
325 #if HistogramInsertionSort
329 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
331 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
332 values[correct] = value;
336 CFArrayReplaceValues(array, range, values, range.length);
339 #if HistogramInsertionSort > 0
340 for (CFIndex index(0); index != range.length; ++index)
341 if (offsets[index] != 0)
342 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
343 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
350 /* Apple Bug Fixes {{{ */
351 @implementation UIWebDocumentView (Cydia)
353 - (void) _setScrollerOffset:(CGPoint)offset {
354 UIScroller *scroller([self _scroller]);
356 CGSize size([scroller contentSize]);
357 CGSize bounds([scroller bounds].size);
360 max.x = size.width - bounds.width;
361 max.y = size.height - bounds.height;
369 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
370 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
372 [scroller setOffset:offset];
378 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
379 size_t length([self length] - state->state);
382 else if (length > count)
384 for (size_t i(0); i != length; ++i)
385 objects[i] = [self item:state->state++];
386 state->itemsPtr = objects;
387 state->mutationsPtr = (unsigned long *) self;
391 /* Cydia NSString Additions {{{ */
392 @interface NSString (Cydia)
393 - (NSComparisonResult) compareByPath:(NSString *)other;
394 - (NSString *) stringByCachingURLWithCurrentCDN;
395 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
398 @implementation NSString (Cydia)
400 - (NSComparisonResult) compareByPath:(NSString *)other {
401 NSString *prefix = [self commonPrefixWithString:other options:0];
402 size_t length = [prefix length];
404 NSRange lrange = NSMakeRange(length, [self length] - length);
405 NSRange rrange = NSMakeRange(length, [other length] - length);
407 lrange = [self rangeOfString:@"/" options:0 range:lrange];
408 rrange = [other rangeOfString:@"/" options:0 range:rrange];
410 NSComparisonResult value;
412 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
413 value = NSOrderedSame;
414 else if (lrange.location == NSNotFound)
415 value = NSOrderedAscending;
416 else if (rrange.location == NSNotFound)
417 value = NSOrderedDescending;
419 value = NSOrderedSame;
421 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
422 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
423 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
424 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
426 NSComparisonResult result = [lpath compare:rpath];
427 return result == NSOrderedSame ? value : result;
430 - (NSString *) stringByCachingURLWithCurrentCDN {
432 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
433 withString:@"://cache.cydia.saurik.com/"
437 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
438 return [(id)CFURLCreateStringByAddingPercentEscapes(
443 kCFStringEncodingUTF8
450 /* C++ NSString Wrapper Cache {{{ */
451 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
452 return size == 0 ? NULL :
453 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
454 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
457 static _finline CFStringRef CYStringCreate(const char *data) {
458 return CYStringCreate(data, strlen(data));
467 _finline void clear_() {
468 if (cache_ != NULL) {
475 _finline bool empty() const {
479 _finline size_t size() const {
483 _finline char *data() const {
487 _finline void clear() {
492 _finline CYString() :
499 _finline ~CYString() {
503 void operator =(const CYString &rhs) {
507 if (rhs.cache_ == nil)
510 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
513 void copy(apr_pool_t *pool) {
514 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
515 memcpy(temp, data_, size_);
520 void set(apr_pool_t *pool, const char *data, size_t size) {
526 data_ = const_cast<char *>(data);
534 _finline void set(apr_pool_t *pool, const char *data) {
535 set(pool, data, data == NULL ? 0 : strlen(data));
538 _finline void set(apr_pool_t *pool, const std::string &rhs) {
539 set(pool, rhs.data(), rhs.size());
542 bool operator ==(const CYString &rhs) const {
543 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
546 _finline operator CFStringRef() {
548 cache_ = CYStringCreate(data_, size_);
552 _finline operator id() {
553 return (NSString *) static_cast<CFStringRef>(*this);
556 _finline operator const char *() {
557 return reinterpret_cast<const char *>(data_);
561 /* C++ NSString Algorithm Adapters {{{ */
563 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
566 struct NSStringMapHash :
567 std::unary_function<NSString *, size_t>
569 _finline size_t operator ()(NSString *value) const {
570 return CFStringHashNSString((CFStringRef) value);
574 struct NSStringMapLess :
575 std::binary_function<NSString *, NSString *, bool>
577 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
578 return [lhs compare:rhs] == NSOrderedAscending;
582 struct NSStringMapEqual :
583 std::binary_function<NSString *, NSString *, bool>
585 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
586 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
587 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
588 //[lhs isEqualToString:rhs];
593 /* CoreGraphics Primitives {{{ */
598 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
599 CGFloat color[] = {red, green, blue, alpha};
600 return CGColorCreate(space, color);
609 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
610 color_(Create_(space, red, green, blue, alpha))
612 Set(space, red, green, blue, alpha);
617 CGColorRelease(color_);
624 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
626 color_ = Create_(space, red, green, blue, alpha);
629 operator CGColorRef() {
635 /* Random Global Variables {{{ */
636 static const int PulseInterval_ = 50000;
638 static const NSString *UI_;
641 static bool RestartSubstrate_;
642 static NSArray *Finishes_;
644 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
645 #define NotifyConfig_ "/etc/notify.conf"
647 static bool Queuing_;
649 static CYColor Blue_;
650 static CYColor Blueish_;
651 static CYColor Black_;
653 static CYColor White_;
654 static CYColor Gray_;
655 static CYColor Green_;
656 static CYColor Purple_;
657 static CYColor Purplish_;
659 static UIColor *InstallingColor_;
660 static UIColor *RemovingColor_;
662 static NSString *App_;
664 static BOOL Advanced_;
665 static BOOL Ignored_;
667 static _H<UIFont> Font12_;
668 static _H<UIFont> Font12Bold_;
669 static _H<UIFont> Font14_;
670 static _H<UIFont> Font18Bold_;
671 static _H<UIFont> Font22Bold_;
673 static const char *Machine_ = NULL;
674 static NSString *System_ = nil;
675 static NSString *SerialNumber_ = nil;
676 static NSString *ChipID_ = nil;
677 static NSString *BBSNum_ = nil;
678 static _H<NSString> Token_;
679 static NSString *UniqueID_ = nil;
680 static NSString *PLMN_ = nil;
681 static NSString *Build_ = nil;
682 static NSString *Product_ = nil;
683 static NSString *Safari_ = nil;
685 static CFLocaleRef Locale_;
686 static NSArray *Languages_;
687 static CGColorSpaceRef space_;
689 static NSDictionary *SectionMap_;
690 static NSMutableDictionary *Metadata_;
691 static _transient NSMutableDictionary *Settings_;
692 static _transient NSString *Role_;
693 static _transient NSMutableDictionary *Packages_;
694 static _transient NSMutableDictionary *Sections_;
695 static _transient NSMutableDictionary *Sources_;
696 static bool Changed_;
700 static CGFloat ScreenScale_;
701 static NSString *Idiom_;
703 static _H<NSMutableDictionary> SessionData_;
704 static _H<NSObject> HostConfig_;
705 static _H<NSMutableSet> BridgedHosts_;
706 static _H<NSMutableSet> PipelinedHosts_;
708 static NSString *kCydiaProgressEventTypeError = @"Error";
709 static NSString *kCydiaProgressEventTypeInformation = @"Information";
710 static NSString *kCydiaProgressEventTypeStatus = @"Status";
711 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
714 /* Display Helpers {{{ */
715 inline float Interpolate(float begin, float end, float fraction) {
716 return (end - begin) * fraction + begin;
719 static _finline const char *StripVersion_(const char *version) {
720 const char *colon(strchr(version, ':'));
721 return colon == NULL ? version : colon + 1;
724 NSString *LocalizeSection(NSString *section) {
725 static Pcre title_r("^(.*?) \\((.*)\\)$");
726 if (title_r(section)) {
727 NSString *parent(title_r[1]);
728 NSString *child(title_r[2]);
730 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
731 LocalizeSection(parent),
732 LocalizeSection(child)
736 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
739 NSString *Simplify(NSString *title) {
740 const char *data = [title UTF8String];
741 size_t size = [title length];
743 static Pcre square_r("^\\[(.*)\\]$");
744 if (square_r(data, size))
745 return Simplify(square_r[1]);
747 static Pcre paren_r("^\\((.*)\\)$");
748 if (paren_r(data, size))
749 return Simplify(paren_r[1]);
751 static Pcre title_r("^(.*?) \\((.*)\\)$");
752 if (title_r(data, size))
753 return Simplify(title_r[1]);
759 NSString *GetLastUpdate() {
760 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
763 return UCLocalize("NEVER_OR_UNKNOWN");
765 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
766 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
768 CFRelease(formatter);
770 return [(NSString *) formatted autorelease];
773 bool isSectionVisible(NSString *section) {
774 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
775 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
776 return hidden == nil || ![hidden boolValue];
779 static NSObject *CYIOGetValue(const char *path, NSString *property) {
780 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
781 if (entry == MACH_PORT_NULL)
784 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
785 IOObjectRelease(entry);
789 return [(id) value autorelease];
792 static NSString *CYHex(NSData *data, bool reverse = false) {
796 size_t length([data length]);
797 uint8_t bytes[length];
798 [data getBytes:bytes];
800 char string[length * 2 + 1];
801 for (size_t i(0); i != length; ++i)
802 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
804 return [NSString stringWithUTF8String:string];
809 /* Delegate Prototypes {{{ */
812 @class CydiaProgressEvent;
814 @protocol DatabaseDelegate
815 - (void) repairWithSelector:(SEL)selector;
816 - (void) setConfigurationData:(NSString *)data;
817 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
820 @class CYPackageController;
822 @protocol CydiaDelegate
823 - (void) retainNetworkActivityIndicator;
824 - (void) releaseNetworkActivityIndicator;
825 - (void) clearPackage:(Package *)package;
826 - (void) installPackage:(Package *)package;
827 - (void) installPackages:(NSArray *)packages;
828 - (void) removePackage:(Package *)package;
829 - (void) beginUpdate;
831 - (void) distUpgrade;
835 - (void) addTrivialSource:(NSString *)href;
836 - (void) showSettings;
837 - (UIProgressHUD *) addProgressHUD;
838 - (void) removeProgressHUD:(UIProgressHUD *)hud;
839 - (CyteViewController *) pageForPackage:(NSString *)name;
840 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
841 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
845 /* Status Delegation {{{ */
847 public pkgAcquireStatus
850 _transient NSObject<ProgressDelegate> *delegate_;
860 void setDelegate(NSObject<ProgressDelegate> *delegate) {
861 delegate_ = delegate;
864 NSObject<ProgressDelegate> *getDelegate() const {
868 virtual bool MediaChange(std::string media, std::string drive) {
872 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
875 virtual void Fetch(pkgAcquire::ItemDesc &item) {
876 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
877 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
878 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
881 virtual void Done(pkgAcquire::ItemDesc &item) {
884 virtual void Fail(pkgAcquire::ItemDesc &item) {
886 item.Owner->Status == pkgAcquire::Item::StatIdle ||
887 item.Owner->Status == pkgAcquire::Item::StatDone
891 std::string &error(item.Owner->ErrorText);
895 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
896 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
899 virtual bool Pulse(pkgAcquire *Owner) {
900 bool value = pkgAcquireStatus::Pulse(Owner);
903 double(CurrentBytes + CurrentItems) /
904 double(TotalBytes + TotalItems)
907 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
908 [NSNumber numberWithDouble:percent], @"Percent",
910 [NSNumber numberWithDouble:CurrentBytes], @"Current",
911 [NSNumber numberWithDouble:TotalBytes], @"Total",
912 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
913 nil] waitUntilDone:YES];
915 if (value && ![delegate_ isProgressCancelled])
923 _finline bool WasCancelled() const {
927 virtual void Start() {
928 pkgAcquireStatus::Start();
929 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
932 virtual void Stop() {
933 pkgAcquireStatus::Stop();
934 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
935 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
939 /* Database Interface {{{ */
940 typedef std::map< unsigned long, _H<Source> > SourceMap;
942 @interface Database : NSObject {
949 pkgDepCache::Policy *policy_;
950 pkgRecords *records_;
951 pkgProblemResolver *resolver_;
952 pkgAcquire *fetcher_;
954 SPtr<pkgPackageManager> manager_;
955 pkgSourceList *list_;
957 SourceMap sourceMap_;
958 _H<NSMutableArray> sourceList_;
960 CFMutableArrayRef packages_;
962 _transient NSObject<DatabaseDelegate> *delegate_;
963 _transient NSObject<ProgressDelegate> *progress_;
971 std::map<const char *, _H<NSString> > sections_;
974 + (Database *) sharedInstance;
977 - (void) _readCydia:(NSNumber *)fd;
978 - (void) _readStatus:(NSNumber *)fd;
979 - (void) _readOutput:(NSNumber *)fd;
983 - (Package *) packageWithName:(NSString *)name;
985 - (pkgCacheFile &) cache;
986 - (pkgDepCache::Policy *) policy;
987 - (pkgRecords *) records;
988 - (pkgProblemResolver *) resolver;
989 - (pkgAcquire &) fetcher;
990 - (pkgSourceList &) list;
991 - (NSArray *) packages;
992 - (NSArray *) sources;
993 - (Source *) sourceWithKey:(NSString *)key;
994 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1002 - (void) updateWithStatus:(Status &)status;
1004 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1006 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1007 - (NSObject<ProgressDelegate> *) progressDelegate;
1009 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1011 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1015 /* ProgressEvent Implementation {{{ */
1016 @implementation CydiaProgressEvent
1018 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1019 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1022 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1023 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1024 [event setPackage:package];
1028 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1029 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1031 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1032 NSArray *fields([description componentsSeparatedByString:@" "]);
1033 [event setItem:fields];
1035 if ([fields count] > 3) {
1036 [event setPackage:[fields objectAtIndex:2]];
1037 [event setVersion:[fields objectAtIndex:3]];
1040 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1045 + (NSArray *) _attributeKeys {
1046 return [NSArray arrayWithObjects:
1056 - (NSArray *) attributeKeys {
1057 return [[self class] _attributeKeys];
1060 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1061 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1064 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1065 if ((self = [super init]) != nil) {
1071 - (NSString *) message {
1075 - (NSString *) type {
1079 - (NSArray *) item {
1080 return (id) item_ ?: [NSNull null];
1083 - (void) setItem:(NSArray *)item {
1087 - (NSString *) package {
1088 return (id) package_ ?: [NSNull null];
1091 - (void) setPackage:(NSString *)package {
1095 - (NSString *) url {
1096 return (id) url_ ?: [NSNull null];
1099 - (void) setURL:(NSString *)url {
1103 - (void) setVersion:(NSString *)version {
1107 - (NSString *) version {
1108 return (id) version_ ?: [NSNull null];
1111 - (NSString *) compound:(NSString *)value {
1113 NSString *mode(nil); {
1114 NSString *type([self type]);
1115 if ([type isEqualToString:kCydiaProgressEventTypeError])
1116 mode = UCLocalize("ERROR");
1117 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1118 mode = UCLocalize("WARNING");
1122 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1128 - (NSString *) compoundMessage {
1129 return [self compound:[self message]];
1132 - (NSString *) compoundTitle {
1135 if (package_ == nil)
1137 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1138 title = [package name];
1142 return [self compound:title];
1148 // Cytore Definitions {{{
1149 struct PackageValue :
1152 Cytore::Offset<PackageValue> next_;
1154 uint32_t index_ : 23;
1155 uint32_t subscribed_ : 1;
1172 Cytore::Offset<PackageValue> packages_[1 << 16];
1175 static Cytore::File<MetaValue> MetaFile_;
1177 // Cytore Helper Functions {{{
1178 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1179 SplitHash nhash = { hashlittle(name, length) };
1181 PackageValue *metadata;
1183 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1184 offset: if (offset->IsNull()) {
1185 *offset = MetaFile_.New<PackageValue>(length + 1);
1186 metadata = &MetaFile_.Get(*offset);
1188 if (metadata == NULL) {
1192 metadata = new PackageValue();
1193 memset(metadata, 0, sizeof(*metadata));
1196 memcpy(metadata->name_, name, length + 1);
1197 metadata->nhash_ = nhash.u16[1];
1199 metadata = &MetaFile_.Get(*offset);
1201 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1202 offset = &metadata->next_;
1210 static void PackageImport(const void *key, const void *value, void *context) {
1211 bool &fail(*reinterpret_cast<bool *>(context));
1214 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1215 NSLog(@"failed to import package %@", key);
1219 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1220 NSDictionary *package((NSDictionary *) value);
1222 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1223 if ([subscribed boolValue] && !metadata->subscribed_)
1224 metadata->subscribed_ = true;
1226 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1227 time_t time([date timeIntervalSince1970]);
1228 if (metadata->first_ > time || metadata->first_ == 0)
1229 metadata->first_ = time;
1232 NSDate *date([package objectForKey:@"LastSeen"]);
1233 NSString *version([package objectForKey:@"LastVersion"]);
1235 if (date != nil && version != nil) {
1236 time_t time([date timeIntervalSince1970]);
1237 if (metadata->last_ < time || metadata->last_ == 0)
1238 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1239 size_t length(strlen(buffer));
1240 uint16_t vhash(hashlittle(buffer, length));
1242 size_t capped(std::min<size_t>(8, length));
1243 char *latest(buffer + length - capped);
1245 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1246 metadata->vhash_ = vhash;
1248 metadata->last_ = time;
1254 /* Source Class {{{ */
1255 @interface Source : NSObject {
1256 CYString depiction_;
1257 CYString description_;
1263 CYString distribution_;
1269 _H<NSString> authority_;
1271 CYString defaultIcon_;
1273 _H<NSDictionary> record_;
1277 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1279 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1281 - (NSString *) depictionForPackage:(NSString *)package;
1282 - (NSString *) supportForPackage:(NSString *)package;
1284 - (NSDictionary *) record;
1288 - (NSString *) distribution;
1289 - (NSString *) type;
1291 - (NSString *) base;
1294 - (NSString *) host;
1296 - (NSString *) name;
1297 - (NSString *) shortDescription;
1298 - (NSString *) label;
1299 - (NSString *) origin;
1300 - (NSString *) version;
1302 - (NSString *) defaultIcon;
1306 @implementation Source
1310 distribution_.clear();
1315 description_.clear();
1321 defaultIcon_.clear();
1328 + (NSArray *) _attributeKeys {
1329 return [NSArray arrayWithObjects:
1336 @"shortDescription",
1344 - (NSArray *) attributeKeys {
1345 return [[self class] _attributeKeys];
1348 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1349 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1352 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1355 trusted_ = index->IsTrusted();
1357 uri_.set(pool, index->GetURI());
1358 distribution_.set(pool, index->GetDist());
1359 type_.set(pool, index->GetType());
1361 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1362 if (dindex != NULL) {
1363 base_.set(pool, dindex->MetaIndexURI(""));
1366 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1369 pkgTagFile tags(&fd);
1371 pkgTagSection section;
1378 {"default-icon", &defaultIcon_},
1379 {"depiction", &depiction_},
1380 {"description", &description_},
1382 {"origin", &origin_},
1383 {"support", &support_},
1384 {"version", &version_},
1387 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1388 const char *start, *end;
1390 if (section.Find(names[i].name_, start, end)) {
1391 CYString &value(*names[i].value_);
1392 value.set(pool, start, end - start);
1398 record_ = [Sources_ objectForKey:[self key]];
1400 NSURL *url([NSURL URLWithString:uri_]);
1404 host_ = [host_ lowercaseString];
1409 authority_ = [url path];
1412 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1413 if ((self = [super init]) != nil) {
1414 [self setMetaIndex:index inPool:pool];
1418 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1419 NSDictionary *lhr = [self record];
1420 NSDictionary *rhr = [source record];
1423 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1425 NSString *lhs = [self name];
1426 NSString *rhs = [source name];
1428 if ([lhs length] != 0 && [rhs length] != 0) {
1429 unichar lhc = [lhs characterAtIndex:0];
1430 unichar rhc = [rhs characterAtIndex:0];
1432 if (isalpha(lhc) && !isalpha(rhc))
1433 return NSOrderedAscending;
1434 else if (!isalpha(lhc) && isalpha(rhc))
1435 return NSOrderedDescending;
1438 return [lhs compare:rhs options:LaxCompareOptions_];
1441 - (NSString *) depictionForPackage:(NSString *)package {
1442 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1445 - (NSString *) supportForPackage:(NSString *)package {
1446 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1449 - (NSDictionary *) record {
1457 - (NSString *) uri {
1461 - (NSString *) distribution {
1462 return distribution_;
1465 - (NSString *) type {
1469 - (NSString *) base {
1473 - (NSString *) key {
1474 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1477 - (NSString *) host {
1481 - (NSString *) name {
1482 return origin_.empty() ? (id) authority_ : origin_;
1485 - (NSString *) shortDescription {
1486 return description_;
1489 - (NSString *) label {
1490 return label_.empty() ? (id) authority_ : label_;
1493 - (NSString *) origin {
1497 - (NSString *) version {
1501 - (NSString *) defaultIcon {
1502 return defaultIcon_;
1507 /* CydiaOperation Class {{{ */
1508 @interface CydiaOperation : NSObject {
1509 _H<NSString> operator_;
1510 _H<NSString> value_;
1513 - (NSString *) operator;
1514 - (NSString *) value;
1518 @implementation CydiaOperation
1520 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1521 if ((self = [super init]) != nil) {
1522 operator_ = [NSString stringWithUTF8String:_operator];
1523 value_ = [NSString stringWithUTF8String:value];
1527 + (NSArray *) _attributeKeys {
1528 return [NSArray arrayWithObjects:
1534 - (NSArray *) attributeKeys {
1535 return [[self class] _attributeKeys];
1538 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1539 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1542 - (NSString *) operator {
1546 - (NSString *) value {
1552 /* CydiaClause Class {{{ */
1553 @interface CydiaClause : NSObject {
1554 _H<NSString> package_;
1555 _H<CydiaOperation> version_;
1558 - (NSString *) package;
1559 - (CydiaOperation *) version;
1563 @implementation CydiaClause
1565 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1566 if ((self = [super init]) != nil) {
1567 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1569 if (const char *version = dep.TargetVer())
1570 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1572 version_ = (id) [NSNull null];
1576 + (NSArray *) _attributeKeys {
1577 return [NSArray arrayWithObjects:
1583 - (NSArray *) attributeKeys {
1584 return [[self class] _attributeKeys];
1587 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1588 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1591 - (NSString *) package {
1595 - (CydiaOperation *) version {
1601 /* CydiaRelation Class {{{ */
1602 @interface CydiaRelation : NSObject {
1603 _H<NSString> relationship_;
1604 _H<NSMutableArray> clauses_;
1607 - (NSString *) relationship;
1608 - (NSArray *) clauses;
1612 @implementation CydiaRelation
1614 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1615 if ((self = [super init]) != nil) {
1616 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1617 clauses_ = [NSMutableArray arrayWithCapacity:8];
1619 pkgCache::DepIterator start;
1620 pkgCache::DepIterator end;
1621 dep.GlobOr(start, end); // ++dep
1624 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1626 // yes, seriously. (wtf?)
1634 + (NSArray *) _attributeKeys {
1635 return [NSArray arrayWithObjects:
1641 - (NSArray *) attributeKeys {
1642 return [[self class] _attributeKeys];
1645 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1646 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1649 - (NSString *) relationship {
1650 return relationship_;
1653 - (NSArray *) clauses {
1657 - (void) addClause:(CydiaClause *)clause {
1658 [clauses_ addObject:clause];
1663 /* Package Class {{{ */
1664 struct ParsedPackage {
1669 CYString depiction_;
1679 @interface Package : NSObject {
1682 uint32_t essential_ : 1;
1683 uint32_t obsolete_ : 1;
1684 uint32_t ignored_ : 1;
1690 _transient Database *database_;
1692 pkgCache::VerIterator version_;
1693 pkgCache::PkgIterator iterator_;
1694 pkgCache::VerFileIterator file_;
1700 CYString installed_;
1702 const char *section_;
1703 _transient NSString *section$_;
1707 PackageValue *metadata_;
1708 ParsedPackage *parsed_;
1710 _H<NSMutableArray> tags_;
1713 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1714 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1716 - (pkgCache::PkgIterator) iterator;
1719 - (NSString *) section;
1720 - (NSString *) simpleSection;
1722 - (NSString *) longSection;
1723 - (NSString *) shortSection;
1727 - (MIMEAddress *) maintainer;
1729 - (NSString *) longDescription;
1730 - (NSString *) shortDescription;
1733 - (PackageValue *) metadata;
1736 - (bool) subscribed;
1737 - (bool) setSubscribed:(bool)subscribed;
1741 - (NSString *) latest;
1742 - (NSString *) installed;
1743 - (BOOL) uninstalled;
1746 - (BOOL) upgradableAndEssential:(BOOL)essential;
1749 - (BOOL) unfiltered;
1753 - (BOOL) halfConfigured;
1754 - (BOOL) halfInstalled;
1756 - (NSString *) mode;
1759 - (NSString *) name;
1761 - (NSString *) homepage;
1762 - (NSString *) depiction;
1763 - (MIMEAddress *) author;
1765 - (NSString *) support;
1767 - (NSArray *) files;
1768 - (NSArray *) warnings;
1769 - (NSArray *) applications;
1771 - (Source *) source;
1774 - (BOOL) matches:(NSString *)text;
1776 - (bool) hasSupportingRole;
1777 - (BOOL) hasTag:(NSString *)tag;
1778 - (NSString *) primaryPurpose;
1779 - (NSArray *) purposes;
1780 - (bool) isCommercial;
1782 - (void) setIndex:(size_t)index;
1784 - (CYString &) cyname;
1786 - (uint32_t) compareBySection:(NSArray *)sections;
1791 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1792 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1793 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1794 - (bool) isVisibleInSection:(NSString *)section;
1795 - (bool) isVisibleInSource:(Source *)source;
1799 uint32_t PackageChangesRadix(Package *self, void *) {
1804 uint32_t timestamp : 30;
1805 uint32_t ignored : 1;
1806 uint32_t upgradable : 1;
1810 bool upgradable([self upgradableAndEssential:YES]);
1811 value.bits.upgradable = upgradable ? 1 : 0;
1814 value.bits.timestamp = 0;
1815 value.bits.ignored = [self ignored] ? 0 : 1;
1816 value.bits.upgradable = 1;
1818 value.bits.timestamp = [self seen] >> 2;
1819 value.bits.ignored = 0;
1820 value.bits.upgradable = 0;
1823 return _not(uint32_t) - value.key;
1826 uint32_t PackagePrefixRadix(Package *self, void *context) {
1827 size_t offset(reinterpret_cast<size_t>(context));
1828 CYString &name([self cyname]);
1830 size_t size(name.size());
1833 char *text(name.data());
1836 if (!isdigit(text[0]))
1840 while (size != digits && isdigit(text[digits]))
1848 if (offset == 0 && zeros != 0) {
1849 memset(data, '0', zeros);
1850 memcpy(data + zeros, text, 4 - zeros);
1852 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1853 if (size <= offset - zeros)
1856 text += offset - zeros;
1857 size -= offset - zeros;
1860 memcpy(data, text, 4);
1862 memcpy(data, text, size);
1863 memset(data + size, 0, 4 - size);
1866 for (size_t i(0); i != 4; ++i)
1867 if (isalpha(data[i]))
1875 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1877 /* XXX: ntohl may be more honest */
1878 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1881 CYString &(*PackageName)(Package *self, SEL sel);
1883 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1884 _profile(PackageNameCompare)
1885 CYString &lhi(PackageName(lhs, @selector(cyname)));
1886 CYString &rhi(PackageName(rhs, @selector(cyname)));
1887 CFStringRef lhn(lhi), rhn(rhi);
1890 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1891 else if (rhn == NULL)
1892 return NSOrderedDescending;
1894 _profile(PackageNameCompare$NumbersLast)
1895 if (!lhi.empty() && !rhi.empty()) {
1896 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1897 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1898 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1899 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1900 return lha ? NSOrderedAscending : NSOrderedDescending;
1904 CFIndex length = CFStringGetLength(lhn);
1906 _profile(PackageNameCompare$Compare)
1907 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1912 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1913 return PackageNameCompare(*lhs, *rhs, context);
1916 struct PackageNameOrdering :
1917 std::binary_function<Package *, Package *, bool>
1919 _finline bool operator ()(Package *lhs, Package *rhs) const {
1920 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1924 @implementation Package
1926 - (NSString *) description {
1927 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1931 if (parsed_ != NULL)
1936 + (NSString *) webScriptNameForSelector:(SEL)selector {
1938 else if (selector == @selector(clear))
1940 else if (selector == @selector(getField:))
1942 else if (selector == @selector(hasTag:))
1944 else if (selector == @selector(install))
1946 else if (selector == @selector(remove))
1952 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1953 return [self webScriptNameForSelector:selector] == nil;
1956 + (NSArray *) _attributeKeys {
1957 return [NSArray arrayWithObjects:
1976 @"shortDescription",
1989 - (NSArray *) attributeKeys {
1990 return [[self class] _attributeKeys];
1993 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1994 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1997 - (NSArray *) relations {
1998 @synchronized (database_) {
1999 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2000 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2001 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2005 - (NSString *) getField:(NSString *)name {
2006 @synchronized (database_) {
2007 if ([database_ era] != era_ || file_.end())
2010 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2012 const char *start, *end;
2013 if (!parser.Find([name UTF8String], start, end))
2014 return (NSString *) [NSNull null];
2016 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2020 if (parsed_ != NULL)
2022 @synchronized (database_) {
2023 if ([database_ era] != era_ || file_.end())
2026 ParsedPackage *parsed(new ParsedPackage);
2029 _profile(Package$parse)
2030 pkgRecords::Parser *parser;
2032 _profile(Package$parse$Lookup)
2033 parser = &[database_ records]->Lookup(file_);
2038 _profile(Package$parse$Find)
2043 {"icon", &parsed->icon_},
2044 {"depiction", &parsed->depiction_},
2045 {"homepage", &parsed->homepage_},
2046 {"website", &website},
2047 {"bugs", &parsed->bugs_},
2048 {"support", &parsed->support_},
2049 {"sponsor", &parsed->sponsor_},
2050 {"author", &parsed->author_},
2053 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2054 const char *start, *end;
2056 if (parser->Find(names[i].name_, start, end)) {
2057 CYString &value(*names[i].value_);
2058 _profile(Package$parse$Value)
2059 value.set(pool_, start, end - start);
2065 _profile(Package$parse$Tagline)
2066 const char *start, *end;
2067 if (parser->ShortDesc(start, end)) {
2068 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2071 while (stop != start && stop[-1] == '\r')
2073 parsed->tagline_.set(pool_, start, stop - start);
2077 _profile(Package$parse$Retain)
2078 if (parsed->homepage_.empty())
2079 parsed->homepage_ = website;
2080 if (parsed->homepage_ == parsed->depiction_)
2081 parsed->homepage_.clear();
2086 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2087 if ((self = [super init]) != nil) {
2088 _profile(Package$initWithVersion)
2091 database_ = database;
2092 era_ = [database era];
2096 pkgCache::PkgIterator iterator(version.ParentPkg());
2097 iterator_ = iterator;
2099 _profile(Package$initWithVersion$Version)
2100 if (!version_.end())
2101 file_ = version_.FileList();
2103 pkgCache &cache([database_ cache]);
2104 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2108 _profile(Package$initWithVersion$Cache)
2109 name_.set(NULL, iterator.Display());
2111 latest_.set(NULL, StripVersion_(version_.VerStr()));
2113 pkgCache::VerIterator current(iterator.CurrentVer());
2115 installed_.set(NULL, StripVersion_(current.VerStr()));
2118 _profile(Package$initWithVersion$Tags)
2119 pkgCache::TagIterator tag(iterator.TagList());
2121 tags_ = [NSMutableArray arrayWithCapacity:8];
2123 const char *name(tag.Name());
2124 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2126 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2127 if (strcmp(name + 6, "enduser") == 0)
2129 else if (strcmp(name + 6, "hacker") == 0)
2131 else if (strcmp(name + 6, "developer") == 0)
2133 else if (strcmp(name + 6, "cydia") == 0)
2139 if (strncmp(name, "cydia::", 7) == 0) {
2140 if (strcmp(name + 7, "essential") == 0)
2142 else if (strcmp(name + 7, "obsolete") == 0)
2147 } while (!tag.end());
2151 _profile(Package$initWithVersion$Metadata)
2152 const char *mixed(iterator.Name());
2153 size_t size(strlen(mixed));
2154 char lower[size + 1];
2156 for (size_t i(0); i != size; ++i)
2157 lower[i] = mixed[i] | 0x20;
2160 PackageValue *metadata(PackageFind(lower, size));
2161 metadata_ = metadata;
2163 id_.set(NULL, metadata->name_, size);
2165 const char *latest(version_.VerStr());
2166 size_t length(strlen(latest));
2168 uint16_t vhash(hashlittle(latest, length));
2170 size_t capped(std::min<size_t>(8, length));
2171 latest = latest + length - capped;
2173 if (metadata->first_ == 0)
2174 metadata->first_ = now_;
2176 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2177 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2178 metadata->vhash_ = vhash;
2179 metadata->last_ = now_;
2180 } else if (metadata->last_ == 0)
2181 metadata->last_ = metadata->first_;
2184 _profile(Package$initWithVersion$Section)
2185 section_ = iterator.Section();
2188 _profile(Package$initWithVersion$Flags)
2189 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2190 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2195 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2196 pkgCache::VerIterator version;
2198 _profile(Package$packageWithIterator$GetCandidateVer)
2199 version = [database policy]->GetCandidateVer(iterator);
2207 _profile(Package$packageWithIterator$Allocate)
2208 package = [Package allocWithZone:zone];
2211 _profile(Package$packageWithIterator$Initialize)
2213 initWithVersion:version
2220 _profile(Package$packageWithIterator$Autorelease)
2221 package = [package autorelease];
2227 - (pkgCache::PkgIterator) iterator {
2231 - (NSString *) section {
2232 if (section$_ == nil) {
2233 if (section_ == NULL)
2236 _profile(Package$section$mappedSectionForPointer)
2237 section$_ = [database_ mappedSectionForPointer:section_];
2242 - (NSString *) simpleSection {
2243 if (NSString *section = [self section])
2244 return Simplify(section);
2249 - (NSString *) longSection {
2250 return LocalizeSection([self section]);
2253 - (NSString *) shortSection {
2254 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2257 - (NSString *) uri {
2260 pkgIndexFile *index;
2261 pkgCache::PkgFileIterator file(file_.File());
2262 if (![database_ list].FindIndex(file, index))
2264 return [NSString stringWithUTF8String:iterator_->Path];
2265 //return [NSString stringWithUTF8String:file.Site()];
2266 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2270 - (MIMEAddress *) maintainer {
2271 @synchronized (database_) {
2272 if ([database_ era] != era_ || file_.end())
2275 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2276 const std::string &maintainer(parser->Maintainer());
2277 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2281 @synchronized (database_) {
2282 if ([database_ era] != era_ || version_.end())
2285 return version_->InstalledSize;
2288 - (NSString *) longDescription {
2289 @synchronized (database_) {
2290 if ([database_ era] != era_ || file_.end())
2293 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2294 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2296 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2297 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2298 if ([lines count] < 2)
2301 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2302 for (size_t i(1), e([lines count]); i != e; ++i) {
2303 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2304 [trimmed addObject:trim];
2307 return [trimmed componentsJoinedByString:@"\n"];
2310 - (NSString *) shortDescription {
2311 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2315 _profile(Package$index)
2316 CFStringRef name((CFStringRef) [self name]);
2317 if (CFStringGetLength(name) == 0)
2319 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2320 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2322 return toupper(character);
2326 - (PackageValue *) metadata {
2331 PackageValue *metadata([self metadata]);
2332 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2335 - (bool) subscribed {
2336 return [self metadata]->subscribed_;
2339 - (bool) setSubscribed:(bool)subscribed {
2340 PackageValue *metadata([self metadata]);
2341 if (metadata->subscribed_ == subscribed)
2343 metadata->subscribed_ = subscribed;
2351 - (NSString *) latest {
2355 - (NSString *) installed {
2359 - (BOOL) uninstalled {
2360 return installed_.empty();
2364 return !version_.end();
2367 - (BOOL) upgradableAndEssential:(BOOL)essential {
2368 _profile(Package$upgradableAndEssential)
2369 pkgCache::VerIterator current(iterator_.CurrentVer());
2371 return essential && essential_;
2373 return !version_.end() && version_ != current;
2377 - (BOOL) essential {
2382 return [database_ cache][iterator_].InstBroken();
2385 - (BOOL) unfiltered {
2386 _profile(Package$unfiltered$obsolete)
2387 if (_unlikely(obsolete_))
2391 _profile(Package$unfiltered$hasSupportingRole)
2392 if (_unlikely(![self hasSupportingRole]))
2400 if (![self unfiltered])
2405 _profile(Package$visible$section)
2406 section = [self section];
2409 _profile(Package$visible$isSectionVisible)
2410 if (!isSectionVisible(section))
2418 unsigned char current(iterator_->CurrentState);
2419 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2422 - (BOOL) halfConfigured {
2423 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2426 - (BOOL) halfInstalled {
2427 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2431 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2432 return state.Mode != pkgDepCache::ModeKeep;
2435 - (NSString *) mode {
2436 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2438 switch (state.Mode) {
2439 case pkgDepCache::ModeDelete:
2440 if ((state.iFlags & pkgDepCache::Purge) != 0)
2444 case pkgDepCache::ModeKeep:
2445 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2446 return @"REINSTALL";
2447 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2451 case pkgDepCache::ModeInstall:
2452 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2453 return @"REINSTALL";
2454 else*/ switch (state.Status) {
2456 return @"DOWNGRADE";
2462 return @"NEW_INSTALL";
2473 - (NSString *) name {
2474 return name_.empty() ? id_ : name_;
2477 - (UIImage *) icon {
2478 NSString *section = [self simpleSection];
2481 if (parsed_ != NULL)
2482 if (NSString *href = parsed_->icon_)
2483 if ([href hasPrefix:@"file:///"])
2484 // XXX: correct escaping
2485 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2486 if (icon == nil) if (section != nil)
2487 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2488 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2489 if ([dicon hasPrefix:@"file:///"])
2490 // XXX: correct escaping
2491 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2493 icon = [UIImage applicationImageNamed:@"unknown.png"];
2497 - (NSString *) homepage {
2498 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2501 - (NSString *) depiction {
2502 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2505 - (MIMEAddress *) sponsor {
2506 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2509 - (MIMEAddress *) author {
2510 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2513 - (NSString *) support {
2514 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2517 - (NSArray *) files {
2518 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2519 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2522 fin.open([path UTF8String]);
2527 while (std::getline(fin, line))
2528 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2533 - (NSString *) state {
2534 @synchronized (database_) {
2535 if ([database_ era] != era_ || file_.end())
2538 switch (iterator_->CurrentState) {
2539 case pkgCache::State::NotInstalled:
2540 return @"NotInstalled";
2541 case pkgCache::State::UnPacked:
2543 case pkgCache::State::HalfConfigured:
2544 return @"HalfConfigured";
2545 case pkgCache::State::HalfInstalled:
2546 return @"HalfInstalled";
2547 case pkgCache::State::ConfigFiles:
2548 return @"ConfigFiles";
2549 case pkgCache::State::Installed:
2550 return @"Installed";
2551 case pkgCache::State::TriggersAwaited:
2552 return @"TriggersAwaited";
2553 case pkgCache::State::TriggersPending:
2554 return @"TriggersPending";
2557 return (NSString *) [NSNull null];
2560 - (NSString *) selection {
2561 @synchronized (database_) {
2562 if ([database_ era] != era_ || file_.end())
2565 switch (iterator_->SelectedState) {
2566 case pkgCache::State::Unknown:
2568 case pkgCache::State::Install:
2570 case pkgCache::State::Hold:
2572 case pkgCache::State::DeInstall:
2573 return @"DeInstall";
2574 case pkgCache::State::Purge:
2578 return (NSString *) [NSNull null];
2581 - (NSArray *) warnings {
2582 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2583 const char *name(iterator_.Name());
2585 size_t length(strlen(name));
2586 if (length < 2) invalid:
2587 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2588 else for (size_t i(0); i != length; ++i)
2590 /* XXX: technically this is not allowed */
2591 (name[i] < 'A' || name[i] > 'Z') &&
2592 (name[i] < 'a' || name[i] > 'z') &&
2593 (name[i] < '0' || name[i] > '9') &&
2594 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2597 if (strcmp(name, "cydia") != 0) {
2600 bool _private = false;
2603 bool repository = [[self section] isEqualToString:@"Repositories"];
2605 if (NSArray *files = [self files])
2606 for (NSString *file in files)
2607 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2609 else if (!user && [file isEqualToString:@"/User"])
2611 else if (!_private && [file isEqualToString:@"/private"])
2613 else if (!stash && [file isEqualToString:@"/var/stash"])
2616 /* XXX: this is not sensitive enough. only some folders are valid. */
2617 if (cydia && !repository)
2618 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2620 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2622 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2624 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2627 return [warnings count] == 0 ? nil : warnings;
2630 - (NSArray *) applications {
2631 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2633 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2635 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2636 if (NSArray *files = [self files])
2637 for (NSString *file in files)
2638 if (application_r(file)) {
2639 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2640 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2641 if ([id isEqualToString:me])
2644 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2646 display = application_r[1];
2648 NSString *bundle([file stringByDeletingLastPathComponent]);
2649 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2650 if (icon == nil || [icon length] == 0)
2652 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2654 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2655 [applications addObject:application];
2657 [application addObject:id];
2658 [application addObject:display];
2659 [application addObject:url];
2662 return [applications count] == 0 ? nil : applications;
2665 - (Source *) source {
2666 if (source_ == nil) {
2667 @synchronized (database_) {
2668 if ([database_ era] != era_ || file_.end())
2669 source_ = (Source *) [NSNull null];
2671 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2675 return source_ == (Source *) [NSNull null] ? nil : source_;
2682 - (BOOL) matches:(NSString *)text {
2693 range = [string rangeOfString:text options:MatchCompareOptions_];
2694 if (range.location != NSNotFound)
2695 rank_ -= 10 * (100000 / [string length]);
2697 string = [self name];
2698 range = [string rangeOfString:text options:MatchCompareOptions_];
2699 if (range.location != NSNotFound)
2700 rank_ -= 6 * (100000 / [string length]);
2704 string = [self shortDescription];
2705 length = [string length];
2707 range = [string rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2708 if (range.location != NSNotFound)
2709 rank_ -= 2 * (100000 / length);
2714 - (bool) hasSupportingRole {
2719 if ([Role_ isEqualToString:@"User"])
2723 if ([Role_ isEqualToString:@"Hacker"])
2727 if ([Role_ isEqualToString:@"Developer"])
2732 - (NSArray *) tags {
2736 - (BOOL) hasTag:(NSString *)tag {
2737 return tags_ == nil ? NO : [tags_ containsObject:tag];
2740 - (NSString *) primaryPurpose {
2741 for (NSString *tag in (NSArray *) tags_)
2742 if ([tag hasPrefix:@"purpose::"])
2743 return [tag substringFromIndex:9];
2747 - (NSArray *) purposes {
2748 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2749 for (NSString *tag in (NSArray *) tags_)
2750 if ([tag hasPrefix:@"purpose::"])
2751 [purposes addObject:[tag substringFromIndex:9]];
2752 return [purposes count] == 0 ? nil : purposes;
2755 - (bool) isCommercial {
2756 return [self hasTag:@"cydia::commercial"];
2759 - (void) setIndex:(size_t)index {
2760 if (metadata_->index_ != index)
2761 metadata_->index_ = index;
2764 - (CYString &) cyname {
2765 return name_.empty() ? id_ : name_;
2768 - (uint32_t) compareBySection:(NSArray *)sections {
2769 NSString *section([self section]);
2770 for (size_t i(0), e([sections count]); i != e; ++i) {
2771 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2775 return _not(uint32_t);
2779 @synchronized (database_) {
2780 pkgProblemResolver *resolver = [database_ resolver];
2781 resolver->Clear(iterator_);
2783 pkgCacheFile &cache([database_ cache]);
2784 cache->SetReInstall(iterator_, false);
2785 cache->MarkKeep(iterator_, false);
2789 @synchronized (database_) {
2790 pkgProblemResolver *resolver = [database_ resolver];
2791 resolver->Clear(iterator_);
2792 resolver->Protect(iterator_);
2794 pkgCacheFile &cache([database_ cache]);
2795 cache->SetReInstall(iterator_, false);
2796 cache->MarkInstall(iterator_, false);
2798 pkgDepCache::StateCache &state((*cache)[iterator_]);
2799 if (!state.Install())
2800 cache->SetReInstall(iterator_, true);
2804 @synchronized (database_) {
2805 pkgProblemResolver *resolver = [database_ resolver];
2806 resolver->Clear(iterator_);
2807 resolver->Remove(iterator_);
2808 resolver->Protect(iterator_);
2810 pkgCacheFile &cache([database_ cache]);
2811 cache->SetReInstall(iterator_, false);
2812 cache->MarkDelete(iterator_, true);
2815 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2816 _profile(Package$isUnfilteredAndSearchedForBy)
2819 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2820 value &= [self unfiltered];
2823 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2824 value &= [self matches:search];
2831 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2832 if ([search length] == 0)
2835 _profile(Package$isUnfilteredAndSelectedForBy)
2838 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2839 value &= [self unfiltered];
2842 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2843 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2850 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2851 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2854 - (bool) isVisibleInSection:(NSString *)name {
2855 NSString *section([self section]);
2859 section == nil && [name length] == 0 ||
2860 [name isEqualToString:section]
2861 ) && [self visible];
2864 - (bool) isVisibleInSource:(Source *)source {
2865 return [self source] == source && [self visible];
2870 /* Section Class {{{ */
2871 @interface Section : NSObject {
2876 _H<NSString> localized_;
2879 - (NSComparisonResult) compareByLocalized:(Section *)section;
2880 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2881 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2882 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2883 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2884 - (NSString *) name;
2891 - (void) addToCount;
2893 - (void) setCount:(size_t)count;
2894 - (NSString *) localized;
2898 @implementation Section
2900 - (NSComparisonResult) compareByLocalized:(Section *)section {
2901 NSString *lhs(localized_);
2902 NSString *rhs([section localized]);
2904 /*if ([lhs length] != 0 && [rhs length] != 0) {
2905 unichar lhc = [lhs characterAtIndex:0];
2906 unichar rhc = [rhs characterAtIndex:0];
2908 if (isalpha(lhc) && !isalpha(rhc))
2909 return NSOrderedAscending;
2910 else if (!isalpha(lhc) && isalpha(rhc))
2911 return NSOrderedDescending;
2914 return [lhs compare:rhs options:LaxCompareOptions_];
2917 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2918 if ((self = [self initWithName:name localize:NO]) != nil) {
2919 if (localized != nil)
2920 localized_ = localized;
2924 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2925 return [self initWithName:name row:0 localize:localize];
2928 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2929 if ((self = [super init]) != nil) {
2934 localized_ = LocalizeSection(name_);
2938 /* XXX: localize the index thingees */
2939 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2940 if ((self = [super init]) != nil) {
2941 name_ = [NSString stringWithCharacters:&index length:1];
2947 - (NSString *) name {
2967 - (void) addToCount {
2971 - (void) setCount:(size_t)count {
2975 - (NSString *) localized {
2982 static NSString *Colon_;
2984 static NSString *Error_;
2985 static NSString *Warning_;
2987 class CydiaLogCleaner :
2988 public pkgArchiveCleaner
2991 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
2996 /* Database Implementation {{{ */
2997 @implementation Database
2999 + (Database *) sharedInstance {
3000 static _H<Database> instance;
3001 if (instance == nil)
3002 instance = [[[Database alloc] init] autorelease];
3010 - (void) releasePackages {
3011 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3012 CFArrayRemoveAllValues(packages_);
3016 // XXX: actually implement this thing
3018 [self releasePackages];
3019 apr_pool_destroy(pool_);
3020 NSRecycleZone(zone_);
3024 - (void) _readCydia:(NSNumber *)fd {
3025 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3026 std::istream is(&ib);
3029 static Pcre finish_r("^finish:([^:]*)$");
3031 while (std::getline(is, line)) {
3032 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3034 const char *data(line.c_str());
3035 size_t size = line.size();
3036 lprintf("C:%s\n", data);
3038 if (finish_r(data, size)) {
3039 NSString *finish = finish_r[1];
3040 int index = [Finishes_ indexOfObject:finish];
3041 if (index != INT_MAX && index > Finish_)
3051 - (void) _readStatus:(NSNumber *)fd {
3052 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3053 std::istream is(&ib);
3056 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3057 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3059 while (std::getline(is, line)) {
3060 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3062 const char *data(line.c_str());
3063 size_t size(line.size());
3064 lprintf("S:%s\n", data);
3066 if (conffile_r(data, size)) {
3067 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3068 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3069 } else if (strncmp(data, "status: ", 8) == 0) {
3070 // status: <package>: {unpacked,half-configured,installed}
3071 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3072 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3073 } else if (strncmp(data, "processing: ", 12) == 0) {
3074 // processing: configure: config-test
3075 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3076 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3077 } else if (pmstatus_r(data, size)) {
3078 std::string type([pmstatus_r[1] UTF8String]);
3080 NSString *package = pmstatus_r[2];
3081 if ([package isEqualToString:@"dpkg-exec"])
3084 float percent([pmstatus_r[3] floatValue]);
3085 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3087 NSString *string = pmstatus_r[4];
3089 if (type == "pmerror") {
3090 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3091 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3092 } else if (type == "pmstatus") {
3093 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3094 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3095 } else if (type == "pmconffile")
3096 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3098 lprintf("E:unknown pmstatus\n");
3100 lprintf("E:unknown status\n");
3108 - (void) _readOutput:(NSNumber *)fd {
3109 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3110 std::istream is(&ib);
3113 while (std::getline(is, line)) {
3114 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3116 lprintf("O:%s\n", line.c_str());
3118 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3119 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3131 - (Package *) packageWithName:(NSString *)name {
3132 @synchronized (self) {
3133 if (static_cast<pkgDepCache *>(cache_) == NULL)
3135 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3136 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3140 if ((self = [super init]) != nil) {
3147 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3148 apr_pool_create(&pool_, NULL);
3150 size_t capacity(MetaFile_->active_);
3156 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3157 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3161 _assert(pipe(fds) != -1);
3164 _config->Set("APT::Keep-Fds::", cydiafd_);
3165 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3168 detachNewThreadSelector:@selector(_readCydia:)
3170 withObject:[NSNumber numberWithInt:fds[0]]
3173 _assert(pipe(fds) != -1);
3177 detachNewThreadSelector:@selector(_readStatus:)
3179 withObject:[NSNumber numberWithInt:fds[0]]
3182 _assert(pipe(fds) != -1);
3183 _assert(dup2(fds[0], 0) != -1);
3184 _assert(close(fds[0]) != -1);
3186 input_ = fdopen(fds[1], "a");
3188 _assert(pipe(fds) != -1);
3189 _assert(dup2(fds[1], 1) != -1);
3190 _assert(close(fds[1]) != -1);
3193 detachNewThreadSelector:@selector(_readOutput:)
3195 withObject:[NSNumber numberWithInt:fds[0]]
3200 - (pkgCacheFile &) cache {
3204 - (pkgDepCache::Policy *) policy {
3208 - (pkgRecords *) records {
3212 - (pkgProblemResolver *) resolver {
3216 - (pkgAcquire &) fetcher {
3220 - (pkgSourceList &) list {
3224 - (NSArray *) packages {
3225 return (NSArray *) packages_;
3228 - (NSArray *) sources {
3232 - (Source *) sourceWithKey:(NSString *)key {
3233 for (Source *source in [self sources]) {
3234 if ([[source key] isEqualToString:key])
3239 - (bool) popErrorWithTitle:(NSString *)title {
3242 while (!_error->empty()) {
3244 bool warning(!_error->PopMessage(error));
3249 size_t size(error.size());
3250 if (size == 0 || error[size - 1] != '\n')
3252 error.resize(size - 1);
3255 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3257 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3263 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3264 return [self popErrorWithTitle:title] || !success;
3267 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3268 @synchronized (self) {
3271 [self releasePackages];
3274 [sourceList_ removeAllObjects];
3294 apr_pool_clear(pool_);
3296 NSRecycleZone(zone_);
3297 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3299 int chk(creat("/tmp/cydia.chk", 0644));
3303 if (invocation != nil)
3304 [invocation invoke];
3306 NSString *title(UCLocalize("DATABASE"));
3309 OpProgress progress;
3310 while (!cache_.Open(progress, true)) { pop:
3312 bool warning(!_error->PopMessage(error));
3313 lprintf("cache_.Open():[%s]\n", error.c_str());
3315 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3316 [delegate_ repairWithSelector:@selector(configure)];
3317 else if (error == "The package lists or status file could not be parsed or opened.")
3318 [delegate_ repairWithSelector:@selector(update)];
3319 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3320 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3321 // else if (error == "Malformed Status line")
3322 // else if (error == "The list of sources could not be read.")
3324 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3334 unlink("/tmp/cydia.chk");
3336 now_ = [[NSDate date] timeIntervalSince1970];
3338 policy_ = new pkgDepCache::Policy();
3339 records_ = new pkgRecords(cache_);
3340 resolver_ = new pkgProblemResolver(cache_);
3341 fetcher_ = new pkgAcquire(&status_);
3344 list_ = new pkgSourceList();
3345 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3348 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3349 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3353 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3356 if (cache_->BrokenCount() != 0) {
3357 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3360 if (cache_->BrokenCount() != 0) {
3361 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3365 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3369 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3370 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3371 [sourceList_ addObject:object];
3373 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3374 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3375 // XXX: this could be more intelligent
3376 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3377 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3379 sourceMap_[cached->ID] = object;
3384 /*std::vector<Package *> packages;
3385 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3390 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3391 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3392 //packages.push_back(package);
3393 CFArrayAppendValue(packages_, CFRetain(package));
3397 /*if (packages.empty())
3398 packages_ = [[NSArray alloc] init];
3400 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3403 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3404 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3405 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3413 /*if (!packages.empty())
3414 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3415 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3417 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3419 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3421 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3425 size_t count(CFArrayGetCount(packages_));
3426 MetaFile_->active_ = count;
3428 for (size_t index(0); index != count; ++index)
3429 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3436 @synchronized (self) {
3438 resolver_ = new pkgProblemResolver(cache_);
3440 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3441 if (!cache_[iterator].Keep())
3442 cache_->MarkKeep(iterator, false);
3443 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3444 cache_->SetReInstall(iterator, false);
3447 - (void) configure {
3448 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3450 system([dpkg UTF8String]);
3455 // XXX: I don't remember this condition
3460 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3462 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3464 if ([self popErrorWithTitle:title])
3468 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3470 CydiaLogCleaner cleaner;
3471 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3478 fetcher_->Shutdown();
3480 pkgRecords records(cache_);
3482 lock_ = new FileFd();
3483 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3485 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3487 if ([self popErrorWithTitle:title])
3491 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3494 manager_ = (_system->CreatePM(cache_));
3495 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3502 bool substrate(RestartSubstrate_);
3503 RestartSubstrate_ = false;
3505 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3507 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3509 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3511 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3512 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3515 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3517 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3519 [self popErrorWithTitle:title];
3523 bool failed = false;
3524 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3525 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3527 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3533 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3541 RestartSubstrate_ = true;
3544 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3546 if (_error->PendingError()) {
3551 if (result == pkgPackageManager::Failed) {
3556 if (result != pkgPackageManager::Completed) {
3561 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3563 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3565 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3566 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3569 if (![before isEqualToArray:after])
3574 NSString *title(UCLocalize("UPGRADE"));
3575 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3581 [self updateWithStatus:status_];
3584 - (void) updateWithStatus:(Status &)status {
3585 NSString *title(UCLocalize("REFRESHING_DATA"));
3588 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3592 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3593 if ([self popErrorWithTitle:title])
3596 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3598 bool success(ListUpdate(status, list, PulseInterval_));
3599 if (status.WasCancelled())
3602 [self popErrorWithTitle:title forOperation:success];
3603 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3607 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3610 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3611 delegate_ = delegate;
3614 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3615 progress_ = delegate;
3616 status_.setDelegate(delegate);
3619 - (NSObject<ProgressDelegate> *) progressDelegate {
3623 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3624 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3625 return i == sourceMap_.end() ? nil : i->second;
3628 - (NSString *) mappedSectionForPointer:(const char *)section {
3629 _H<NSString> *mapped;
3631 _profile(Database$mappedSectionForPointer$Cache)
3632 mapped = §ions_[section];
3635 if (*mapped == NULL) {
3636 size_t length(strlen(section));
3637 char spaced[length + 1];
3639 _profile(Database$mappedSectionForPointer$Replace)
3640 for (size_t index(0); index != length; ++index)
3641 spaced[index] = section[index] == '_' ? ' ' : section[index];
3642 spaced[length] = '\0';
3647 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3648 string = [NSString stringWithUTF8String:spaced];
3651 _profile(Database$mappedSectionForPointer$Map)
3652 string = [SectionMap_ objectForKey:string] ?: string;
3662 static _H<NSMutableSet> Diversions_;
3664 @interface Diversion : NSObject {
3667 _H<NSString> format_;
3672 @implementation Diversion
3674 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3675 if ((self = [super init]) != nil) {
3676 pattern_ = [from UTF8String];
3682 - (NSString *) divert:(NSString *)url {
3683 return !pattern_(url) ? nil : pattern_->*format_;
3686 + (NSURL *) divertURL:(NSURL *)url {
3688 NSString *href([url absoluteString]);
3690 for (Diversion *diversion in (id) Diversions_)
3691 if (NSString *diverted = [diversion divert:href]) {
3693 NSLog(@"div: %@", diverted);
3695 url = [NSURL URLWithString:diverted];
3702 - (NSString *) key {
3706 - (NSUInteger) hash {
3710 - (BOOL) isEqual:(Diversion *)object {
3711 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3716 @interface CydiaObject : NSObject {
3717 _H<IndirectDelegate> indirect_;
3718 _transient id delegate_;
3721 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3725 @interface CydiaWebViewController : CyteWebViewController {
3726 _H<CydiaObject> cydia_;
3729 + (void) addDiversion:(Diversion *)diversion;
3733 /* Web Scripting {{{ */
3734 @implementation CydiaObject
3736 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3737 if ((self = [super init]) != nil) {
3738 indirect_ = indirect;
3742 - (void) setDelegate:(id)delegate {
3743 delegate_ = delegate;
3746 + (NSArray *) _attributeKeys {
3747 return [NSArray arrayWithObjects:
3763 - (NSArray *) attributeKeys {
3764 return [[self class] _attributeKeys];
3767 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3768 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3771 - (NSString *) version {
3775 - (NSString *) device {
3776 return [[UIDevice currentDevice] uniqueIdentifier];
3779 - (NSString *) firmware {
3780 return [[UIDevice currentDevice] systemVersion];
3783 - (NSString *) hostname {
3784 return [[UIDevice currentDevice] name];
3787 - (NSString *) idiom {
3788 return (id) Idiom_ ?: [NSNull null];
3791 - (NSString *) plmn {
3792 return (id) PLMN_ ?: [NSNull null];
3795 - (NSString *) bbsnum {
3796 return (id) BBSNum_ ?: [NSNull null];
3799 - (NSString *) ecid {
3800 return (id) ChipID_ ?: [NSNull null];
3803 - (NSString *) serial {
3804 return SerialNumber_;
3807 - (NSString *) role {
3808 return (id) Role_ ?: [NSNull null];
3811 - (NSString *) model {
3812 return [NSString stringWithUTF8String:Machine_];
3815 - (NSString *) token {
3816 return (id) Token_ ?: [NSNull null];
3819 + (NSString *) webScriptNameForSelector:(SEL)selector {
3821 else if (selector == @selector(addBridgedHost:))
3822 return @"addBridgedHost";
3823 else if (selector == @selector(addInternalRedirect::))
3824 return @"addInternalRedirect";
3825 else if (selector == @selector(addPipelinedHost:scheme:))
3826 return @"addPipelinedHost";
3827 else if (selector == @selector(addTrivialSource:))
3828 return @"addTrivialSource";
3829 else if (selector == @selector(close))
3831 else if (selector == @selector(du:))
3833 else if (selector == @selector(stringWithFormat:arguments:))
3835 else if (selector == @selector(getAllSources))
3836 return @"getAllSourcs";
3837 else if (selector == @selector(getKernelNumber:))
3838 return @"getKernelNumber";
3839 else if (selector == @selector(getKernelString:))
3840 return @"getKernelString";
3841 else if (selector == @selector(getInstalledPackages))
3842 return @"getInstalledPackages";
3843 else if (selector == @selector(getIORegistryEntry::))
3844 return @"getIORegistryEntry";
3845 else if (selector == @selector(getLocaleIdentifier))
3846 return @"getLocaleIdentifier";
3847 else if (selector == @selector(getPreferredLanguages))
3848 return @"getPreferredLanguages";
3849 else if (selector == @selector(getPackageById:))
3850 return @"getPackageById";
3851 else if (selector == @selector(getSessionValue:))
3852 return @"getSessionValue";
3853 else if (selector == @selector(installPackages:))
3854 return @"installPackages";
3855 else if (selector == @selector(localizedStringForKey:value:table:))
3857 else if (selector == @selector(popViewController:))
3858 return @"popViewController";
3859 else if (selector == @selector(refreshSources))
3860 return @"refreshSources";
3861 else if (selector == @selector(removeButton))
3862 return @"removeButton";
3863 else if (selector == @selector(setSessionValue::))
3864 return @"setSessionValue";
3865 else if (selector == @selector(substitutePackageNames:))
3866 return @"substitutePackageNames";
3867 else if (selector == @selector(scrollToBottom:))
3868 return @"scrollToBottom";
3869 else if (selector == @selector(setAllowsNavigationAction:))
3870 return @"setAllowsNavigationAction";
3871 else if (selector == @selector(setBadgeValue:))
3872 return @"setBadgeValue";
3873 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3874 return @"setButtonImage";
3875 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3876 return @"setButtonTitle";
3877 else if (selector == @selector(setHidesBackButton:))
3878 return @"setHidesBackButton";
3879 else if (selector == @selector(setHidesNavigationBar:))
3880 return @"setHidesNavigationBar";
3881 else if (selector == @selector(setNavigationBarStyle:))
3882 return @"setNavigationBarStyle";
3883 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3884 return @"setNavigationBarTintColor";
3885 else if (selector == @selector(setPasteboardString:))
3886 return @"setPasteboardString";
3887 else if (selector == @selector(setPasteboardURL:))
3888 return @"setPasteboardURL";
3889 else if (selector == @selector(setToken:))
3891 else if (selector == @selector(setViewportWidth:))
3892 return @"setViewportWidth";
3893 else if (selector == @selector(statfs:))
3895 else if (selector == @selector(supports:))
3901 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3902 return [self webScriptNameForSelector:selector] == nil;
3905 - (BOOL) supports:(NSString *)feature {
3906 return [feature isEqualToString:@"window.open"];
3909 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3910 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3913 - (NSNumber *) getKernelNumber:(NSString *)name {
3914 const char *string([name UTF8String]);
3917 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3918 return (id) [NSNull null];
3920 if (size != sizeof(int))
3921 return (id) [NSNull null];
3924 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3925 return (id) [NSNull null];
3927 return [NSNumber numberWithInt:value];
3930 - (NSString *) getKernelString:(NSString *)name {
3931 const char *string([name UTF8String]);
3934 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3935 return (id) [NSNull null];
3937 char value[size + 1];
3938 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3939 return (id) [NSNull null];
3941 // XXX: just in case you request something ludicrous
3944 return [NSString stringWithCString:value];
3947 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3948 NSObject *value(CYIOGetValue([path UTF8String], entry));
3951 if ([value isKindOfClass:[NSData class]])
3952 value = CYHex((NSData *) value);
3957 - (id) getSessionValue:(NSString *)key {
3958 @synchronized (SessionData_) {
3959 return [SessionData_ objectForKey:key];
3962 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3963 @synchronized (SessionData_) {
3964 if (value == (id) [WebUndefined undefined])
3965 [SessionData_ removeObjectForKey:key];
3967 [SessionData_ setObject:value forKey:key];
3970 - (void) addBridgedHost:(NSString *)host {
3971 @synchronized (HostConfig_) {
3972 [BridgedHosts_ addObject:host];
3975 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
3976 @synchronized (HostConfig_) {
3977 if (scheme != (id) [WebUndefined undefined])
3978 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
3980 [PipelinedHosts_ addObject:host];
3983 - (void) popViewController:(NSNumber *)value {
3984 if (value == (id) [WebUndefined undefined])
3985 value = [NSNumber numberWithBool:YES];
3986 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
3989 - (void) addTrivialSource:(NSString *)href {
3990 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3993 - (void) refreshSources {
3994 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3997 - (NSArray *) getAllSources {
3998 return [[Database sharedInstance] sources];
4001 - (NSArray *) getInstalledPackages {
4002 Database *database([Database sharedInstance]);
4003 @synchronized (database) {
4004 NSArray *packages([database packages]);
4005 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4006 for (Package *package in packages)
4007 if (![package uninstalled])
4008 [installed addObject:package];
4012 - (Package *) getPackageById:(NSString *)id {
4013 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4017 return (Package *) [NSNull null];
4020 - (NSString *) getLocaleIdentifier {
4021 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4024 - (NSArray *) getPreferredLanguages {
4028 - (NSArray *) statfs:(NSString *)path {
4031 if (path == nil || statfs([path UTF8String], &stat) == -1)
4034 return [NSArray arrayWithObjects:
4035 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4036 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4037 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4041 - (NSNumber *) du:(NSString *)path {
4042 NSNumber *value(nil);
4045 _assert(pipe(fds) != -1);
4047 pid_t pid(ExecFork());
4049 _assert(dup2(fds[1], 1) != -1);
4050 _assert(close(fds[0]) != -1);
4051 _assert(close(fds[1]) != -1);
4052 /* XXX: this should probably not use du */
4053 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4058 _assert(close(fds[1]) != -1);
4060 if (FILE *du = fdopen(fds[0], "r")) {
4062 while (fgets(line, sizeof(line), du) != NULL) {
4063 size_t length(strlen(line));
4064 while (length != 0 && line[length - 1] == '\n')
4065 line[--length] = '\0';
4066 if (char *tab = strchr(line, '\t')) {
4068 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4073 } else _assert(close(fds[0]));
4077 if (waitpid(pid, &status, 0) == -1)
4080 else _assert(false);
4086 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4089 - (void) installPackages:(NSArray *)packages {
4090 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4093 - (NSString *) substitutePackageNames:(NSString *)message {
4094 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4095 for (size_t i(0), e([words count]); i != e; ++i) {
4096 NSString *word([words objectAtIndex:i]);
4097 if (Package *package = [[Database sharedInstance] packageWithName:word])
4098 [words replaceObjectAtIndex:i withObject:[package name]];
4101 return [words componentsJoinedByString:@" "];
4104 - (void) removeButton {
4105 [indirect_ removeButton];
4108 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4109 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4112 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4113 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4116 - (void) setBadgeValue:(id)value {
4117 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4120 - (void) setAllowsNavigationAction:(NSString *)value {
4121 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4124 - (void) setHidesBackButton:(NSString *)value {
4125 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4128 - (void) setHidesNavigationBar:(NSString *)value {
4129 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4132 - (void) setNavigationBarStyle:(NSString *)value {
4133 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4136 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4137 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4138 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4139 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4142 - (void) setPasteboardString:(NSString *)value {
4143 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4146 - (void) setPasteboardURL:(NSString *)value {
4147 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4150 - (void) _setToken:(NSString *)token {
4154 [Metadata_ removeObjectForKey:@"Token"];
4156 [Metadata_ setObject:Token_ forKey:@"Token"];
4161 - (void) setToken:(NSString *)token {
4162 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4165 - (void) scrollToBottom:(NSNumber *)animated {
4166 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4169 - (void) setViewportWidth:(float)width {
4170 [indirect_ setViewportWidthOnMainThread:width];
4173 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4174 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4175 unsigned count([arguments count]);
4177 for (unsigned i(0); i != count; ++i)
4178 values[i] = [arguments objectAtIndex:i];
4179 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4182 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4183 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4185 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4187 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4194 /* Cydia Browser Controller {{{ */
4195 @implementation CydiaWebViewController
4197 - (NSURL *) navigationURL {
4198 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4201 + (void) initialize {
4202 Diversions_ = [NSMutableSet setWithCapacity:0];
4205 + (void) addDiversion:(Diversion *)diversion {
4206 [Diversions_ addObject:diversion];
4209 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4210 [super webView:view didClearWindowObject:window forFrame:frame];
4212 WebDataSource *source([frame dataSource]);
4213 NSURLResponse *response([source response]);
4214 NSURL *url([response URL]);
4215 NSString *scheme([[url scheme] lowercaseString]);
4217 bool bridged(false);
4219 @synchronized (HostConfig_) {
4220 if ([scheme isEqualToString:@"file"])
4222 else if ([scheme isEqualToString:@"https"])
4223 if ([BridgedHosts_ containsObject:[url host]])
4228 [window setValue:cydia_ forKey:@"cydia"];
4231 - (NSURL *) URLWithURL:(NSURL *)url {
4232 return [Diversion divertURL:url];
4235 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4236 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4238 if (System_ != NULL)
4239 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4240 if (Machine_ != NULL)
4241 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4243 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4248 - (void) setDelegate:(id)delegate {
4249 [super setDelegate:delegate];
4250 [cydia_ setDelegate:delegate];
4254 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4255 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4257 WebView *webview([[webview_ _documentView] webView]);
4259 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4262 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4264 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4265 if (Product_ != nil)
4266 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4268 [webview setApplicationNameForUserAgent:application];
4276 @interface NSObject (CydiaScript)
4277 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4280 @implementation NSObject (CydiaScript)
4282 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4288 @implementation NSArray (CydiaScript)
4290 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4291 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4292 for (size_t i(0), e([self count]); i != e; ++i)
4293 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4299 @implementation NSDictionary (CydiaScript)
4301 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4302 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4304 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4311 /* Confirmation Controller {{{ */
4312 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4313 if (!iterator.end())
4314 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4315 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4317 pkgCache::PkgIterator package(dep.TargetPkg());
4320 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4327 @protocol ConfirmationControllerDelegate
4328 - (void) cancelAndClear:(bool)clear;
4329 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4333 @interface ConfirmationController : CydiaWebViewController {
4334 _transient Database *database_;
4336 _H<UIAlertView> essential_;
4338 _H<NSDictionary> changes_;
4339 _H<NSMutableArray> issues_;
4340 _H<NSDictionary> sizes_;
4345 - (id) initWithDatabase:(Database *)database;
4349 @implementation ConfirmationController
4353 RestartSubstrate_ = true;
4354 [delegate_ confirmWithNavigationController:[self navigationController]];
4357 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4358 NSString *context([alert context]);
4360 if ([context isEqualToString:@"remove"]) {
4361 if (button == [alert cancelButtonIndex])
4362 [self dismissModalViewControllerAnimated:YES];
4363 else if (button == [alert firstOtherButtonIndex]) {
4367 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4368 } else if ([context isEqualToString:@"unable"]) {
4369 [self dismissModalViewControllerAnimated:YES];
4370 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4372 [super alertView:alert clickedButtonAtIndex:button];
4376 - (void) _doContinue {
4377 [self dismissModalViewControllerAnimated:YES];
4378 [delegate_ cancelAndClear:NO];
4381 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4382 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4386 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4387 [super webView:view didClearWindowObject:window forFrame:frame];
4389 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4390 (id) changes_, @"changes",
4391 (id) issues_, @"issues",
4392 (id) sizes_, @"sizes",
4394 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4397 - (id) initWithDatabase:(Database *)database {
4398 if ((self = [super init]) != nil) {
4399 database_ = database;
4401 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4402 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4403 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4404 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4405 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4409 pkgCacheFile &cache([database_ cache]);
4410 NSArray *packages([database_ packages]);
4411 pkgDepCache::Policy *policy([database_ policy]);
4413 issues_ = [NSMutableArray arrayWithCapacity:4];
4415 for (Package *package in packages) {
4416 pkgCache::PkgIterator iterator([package iterator]);
4417 NSString *name([package id]);
4419 if ([package broken]) {
4420 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4422 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4424 reasons, @"reasons",
4427 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4431 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4432 pkgCache::DepIterator start;
4433 pkgCache::DepIterator end;
4434 dep.GlobOr(start, end); // ++dep
4436 if (!cache->IsImportantDep(end))
4438 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4441 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4443 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4444 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4445 clauses, @"clauses",
4449 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4451 pkgCache::PkgIterator target(start.TargetPkg());
4452 if (target->ProvidesList != 0)
4453 reason = @"missing";
4455 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4457 reason = @"installed";
4458 installed = [NSString stringWithUTF8String:ver.VerStr()];
4459 } else if (!cache[target].CandidateVerIter(cache).end())
4460 reason = @"uninstalled";
4461 else if (target->ProvidesList == 0)
4462 reason = @"uninstallable";
4464 reason = @"virtual";
4467 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4468 [NSString stringWithUTF8String:start.CompType()], @"operator",
4469 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4472 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4473 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4474 version, @"version",
4476 installed, @"installed",
4479 // yes, seriously. (wtf?)
4487 pkgDepCache::StateCache &state(cache[iterator]);
4489 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4491 if (state.NewInstall())
4492 [installs addObject:name];
4493 // XXX: else if (state.Install())
4494 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4495 [reinstalls addObject:name];
4496 // XXX: move before previous if
4497 else if (state.Upgrade())
4498 [upgrades addObject:name];
4499 else if (state.Downgrade())
4500 [downgrades addObject:name];
4501 else if (!state.Delete())
4502 // XXX: _assert(state.Keep());
4504 else if (special_r(name))
4505 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4506 [NSNull null], @"package",
4507 [NSArray arrayWithObjects:
4508 [NSDictionary dictionaryWithObjectsAndKeys:
4509 @"Conflicts", @"relationship",
4510 [NSArray arrayWithObjects:
4511 [NSDictionary dictionaryWithObjectsAndKeys:
4513 [NSNull null], @"version",
4514 @"installed", @"reason",
4521 if ([package essential])
4523 [removes addObject:name];
4526 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4527 substrate_ |= DepSubstrate(iterator.CurrentVer());
4532 else if (Advanced_) {
4533 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4535 essential_ = [[[UIAlertView alloc]
4536 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4537 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4539 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4541 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4545 [essential_ setContext:@"remove"];
4547 essential_ = [[[UIAlertView alloc]
4548 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4549 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4551 cancelButtonTitle:UCLocalize("OKAY")
4552 otherButtonTitles:nil
4555 [essential_ setContext:@"unable"];
4558 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4559 installs, @"installs",
4560 reinstalls, @"reinstalls",
4561 upgrades, @"upgrades",
4562 downgrades, @"downgrades",
4563 removes, @"removes",
4566 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4567 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4568 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4571 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4575 - (UIBarButtonItem *) leftButton {
4576 return [[[UIBarButtonItem alloc]
4577 initWithTitle:UCLocalize("CANCEL")
4578 style:UIBarButtonItemStylePlain
4580 action:@selector(cancelButtonClicked)
4585 - (void) applyRightButton {
4586 if ([issues_ count] == 0 && ![self isLoading])
4587 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4588 initWithTitle:UCLocalize("CONFIRM")
4589 style:UIBarButtonItemStyleDone
4591 action:@selector(confirmButtonClicked)
4594 [[self navigationItem] setRightBarButtonItem:nil];
4598 - (void) cancelButtonClicked {
4599 [self dismissModalViewControllerAnimated:YES];
4600 [delegate_ cancelAndClear:YES];
4604 - (void) confirmButtonClicked {
4605 if (essential_ != nil)
4615 /* Progress Data {{{ */
4616 @interface CydiaProgressData : NSObject {
4617 _transient id delegate_;
4626 _H<NSMutableArray> events_;
4627 _H<NSString> title_;
4629 _H<NSString> status_;
4630 _H<NSString> finish_;
4635 @implementation CydiaProgressData
4637 + (NSArray *) _attributeKeys {
4638 return [NSArray arrayWithObjects:
4650 - (NSArray *) attributeKeys {
4651 return [[self class] _attributeKeys];
4654 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4655 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4659 if ((self = [super init]) != nil) {
4660 events_ = [NSMutableArray arrayWithCapacity:32];
4664 - (void) setDelegate:(id)delegate {
4665 delegate_ = delegate;
4668 - (void) setPercent:(float)value {
4672 - (NSNumber *) percent {
4673 return [NSNumber numberWithFloat:percent_];
4676 - (void) setCurrent:(float)value {
4680 - (NSNumber *) current {
4681 return [NSNumber numberWithFloat:current_];
4684 - (void) setTotal:(float)value {
4688 - (NSNumber *) total {
4689 return [NSNumber numberWithFloat:total_];
4692 - (void) setSpeed:(float)value {
4696 - (NSNumber *) speed {
4697 return [NSNumber numberWithFloat:speed_];
4700 - (NSArray *) events {
4704 - (void) removeAllEvents {
4705 [events_ removeAllObjects];
4708 - (void) addEvent:(CydiaProgressEvent *)event {
4709 [events_ addObject:event];
4712 - (void) setTitle:(NSString *)text {
4716 - (NSString *) title {
4720 - (void) setFinish:(NSString *)text {
4724 - (NSString *) finish {
4725 return (id) finish_ ?: [NSNull null];
4728 - (void) setRunning:(bool)running {
4732 - (NSNumber *) running {
4733 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4738 /* Progress Controller {{{ */
4739 @interface ProgressController : CydiaWebViewController <
4742 _transient Database *database_;
4743 _H<CydiaProgressData, 1> progress_;
4747 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4749 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4751 - (void) setTitle:(NSString *)title;
4752 - (void) setCancellable:(bool)cancellable;
4756 @implementation ProgressController
4759 [database_ setProgressDelegate:nil];
4763 - (UIBarButtonItem *) leftButton {
4764 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4765 initWithTitle:UCLocalize("CANCEL")
4766 style:UIBarButtonItemStylePlain
4768 action:@selector(cancel)
4769 ] autorelease] : nil;
4772 - (void) updateCancel {
4773 [super applyLeftButton];
4776 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4777 if ((self = [super init]) != nil) {
4778 database_ = database;
4779 delegate_ = delegate;
4781 [database_ setProgressDelegate:self];
4783 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4784 [progress_ setDelegate:self];
4786 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4788 [scroller_ setBackgroundColor:[UIColor blackColor]];
4790 [[self navigationItem] setHidesBackButton:YES];
4792 [self updateCancel];
4796 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4797 [super webView:view didClearWindowObject:window forFrame:frame];
4798 [window setValue:progress_ forKey:@"cydiaProgress"];
4801 - (void) updateProgress {
4802 [self dispatchEvent:@"CydiaProgressUpdate"];
4805 - (void) viewWillAppear:(BOOL)animated {
4806 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4807 [super viewWillAppear:animated];
4811 UpdateExternalStatus(0);
4818 [delegate_ terminateWithSuccess];
4819 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4820 [delegate_ suspendWithAnimation:YES];
4822 [delegate_ suspend];*/
4834 system("/usr/bin/sbreload");
4840 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4841 SBReboot(SBSSpringBoardServerPort());
4843 reboot2(RB_AUTOBOOT);
4850 - (void) setTitle:(NSString *)title {
4851 [progress_ setTitle:title];
4852 [self updateProgress];
4855 - (UIBarButtonItem *) rightButton {
4856 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4857 initWithTitle:UCLocalize("CLOSE")
4858 style:UIBarButtonItemStylePlain
4860 action:@selector(close)
4864 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4865 UpdateExternalStatus(1);
4867 [progress_ setRunning:true];
4868 [self setTitle:title];
4869 // implicit updateProgress
4871 SHA1SumValue notifyconf; {
4873 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4876 MMap mmap(file, MMap::ReadOnly);
4878 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4879 notifyconf = sha1.Result();
4883 SHA1SumValue springlist; {
4885 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4888 MMap mmap(file, MMap::ReadOnly);
4890 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4891 springlist = sha1.Result();
4895 if (invocation != nil) {
4896 [invocation yieldToSelector:@selector(invoke)];
4897 [self setTitle:@"COMPLETE"];
4902 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4905 MMap mmap(file, MMap::ReadOnly);
4907 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4908 if (!(notifyconf == sha1.Result()))
4915 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4918 MMap mmap(file, MMap::ReadOnly);
4920 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4921 if (!(springlist == sha1.Result()))
4927 if (RestartSubstrate_)
4931 RestartSubstrate_ = false;
4934 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4935 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
4936 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
4937 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4938 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
4942 system("su -c /usr/bin/uicache mobile");
4945 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
4947 [progress_ setRunning:false];
4948 [self updateProgress];
4950 [self applyRightButton];
4953 - (void) addProgressEvent:(CydiaProgressEvent *)event {
4954 [progress_ addEvent:event];
4955 [self updateProgress];
4958 - (bool) isProgressCancelled {
4959 return cancel_ == 2;
4964 [self updateCancel];
4967 - (void) setCancellable:(bool)cancellable {
4968 unsigned cancel(cancel_);
4972 else if (cancel_ == 0)
4975 if (cancel != cancel_)
4976 [self updateCancel];
4979 - (void) setProgressCancellable:(NSNumber *)cancellable {
4980 [self setCancellable:[cancellable boolValue]];
4983 - (void) setProgressPercent:(NSNumber *)percent {
4984 [progress_ setPercent:[percent floatValue]];
4985 [self updateProgress];
4988 - (void) setProgressStatus:(NSDictionary *)status {
4989 if (status == nil) {
4990 [progress_ setCurrent:0];
4991 [progress_ setTotal:0];
4992 [progress_ setSpeed:0];
4994 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
4996 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
4997 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
4998 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5001 [self updateProgress];
5007 /* Package Cell {{{ */
5008 @interface PackageCell : CyteTableViewCell <
5009 CyteTableViewCellDelegate
5013 _H<NSString> description_;
5015 _H<NSString> source_;
5017 _H<Package> package_;
5018 _H<UIImage> placard_;
5022 - (PackageCell *) init;
5023 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5025 - (void) drawContentRect:(CGRect)rect;
5029 @implementation PackageCell
5031 - (PackageCell *) init {
5032 CGRect frame(CGRectMake(0, 0, 320, 74));
5033 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5034 UIView *content([self contentView]);
5035 CGRect bounds([content bounds]);
5037 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5038 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5039 [content addSubview:content_];
5041 [content_ setDelegate:self];
5042 [content_ setOpaque:YES];
5046 - (NSString *) accessibilityLabel {
5047 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5050 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5051 summarized_ = summary;
5063 Source *source = [package source];
5065 icon_ = [package icon];
5066 name_ = [package name];
5069 description_ = [package longDescription];
5070 if (description_ == nil)
5071 description_ = [package shortDescription];
5073 commercial_ = [package isCommercial];
5077 NSString *label = nil;
5078 bool trusted = false;
5080 if (source != nil) {
5081 label = [source label];
5082 trusted = [source trusted];
5083 } else if ([[package id] isEqualToString:@"firmware"])
5084 label = UCLocalize("APPLE");
5086 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5088 NSString *from(label);
5090 NSString *section = [package simpleSection];
5091 if (section != nil && ![section isEqualToString:label]) {
5092 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5093 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5096 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5098 if (NSString *purpose = [package primaryPurpose])
5099 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5104 if (NSString *mode = [package_ mode]) {
5105 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5106 color = RemovingColor_;
5107 //placard = @"removing";
5109 color = InstallingColor_;
5110 //placard = @"installing";
5113 // XXX: the removing/installing placards are not @2x
5116 color = [UIColor whiteColor];
5118 if ([package installed] != nil)
5119 placard = @"installed";
5124 [content_ setBackgroundColor:color];
5127 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5129 [self setNeedsDisplay];
5130 [content_ setNeedsDisplay];
5133 - (void) drawSummaryContentRect:(CGRect)rect {
5134 bool highlighted(highlighted_);
5135 float width([self bounds].size.width);
5139 rect.size = [(UIImage *) icon_ size];
5141 rect.size.width /= 4;
5142 rect.size.height /= 4;
5144 rect.origin.x = 14 - rect.size.width / 4;
5145 rect.origin.y = 14 - rect.size.height / 4;
5147 [icon_ drawInRect:rect];
5150 if (badge_ != nil) {
5152 rect.size = [(UIImage *) badge_ size];
5154 rect.size.width /= 4;
5155 rect.size.height /= 4;
5157 rect.origin.x = 20 - rect.size.width / 4;
5158 rect.origin.y = 20 - rect.size.height / 4;
5160 [badge_ drawInRect:rect];
5167 UISetColor(commercial_ ? Purple_ : Black_);
5168 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5170 if (placard_ != nil)
5171 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5174 - (void) drawNormalContentRect:(CGRect)rect {
5175 bool highlighted(highlighted_);
5176 float width([self bounds].size.width);
5180 rect.size = [(UIImage *) icon_ size];
5182 rect.size.width /= 2;
5183 rect.size.height /= 2;
5185 rect.origin.x = 25 - rect.size.width / 2;
5186 rect.origin.y = 25 - rect.size.height / 2;
5188 [icon_ drawInRect:rect];
5191 if (badge_ != nil) {
5193 rect.size = [(UIImage *) badge_ size];
5195 rect.size.width /= 2;
5196 rect.size.height /= 2;
5198 rect.origin.x = 36 - rect.size.width / 2;
5199 rect.origin.y = 36 - rect.size.height / 2;
5201 [badge_ drawInRect:rect];
5208 UISetColor(commercial_ ? Purple_ : Black_);
5209 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5210 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5213 UISetColor(commercial_ ? Purplish_ : Gray_);
5214 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5216 if (placard_ != nil)
5217 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5220 - (void) drawContentRect:(CGRect)rect {
5222 [self drawSummaryContentRect:rect];
5224 [self drawNormalContentRect:rect];
5229 /* Section Cell {{{ */
5230 @interface SectionCell : CyteTableViewCell <
5231 CyteTableViewCellDelegate
5233 _H<NSString> basic_;
5234 _H<NSString> section_;
5236 _H<NSString> count_;
5238 _H<UISwitch> switch_;
5242 - (void) setSection:(Section *)section editing:(BOOL)editing;
5246 @implementation SectionCell
5248 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5249 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5250 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5251 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5252 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5254 UIView *content([self contentView]);
5255 CGRect bounds([content bounds]);
5257 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5258 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5259 [content addSubview:content_];
5260 [content_ setBackgroundColor:[UIColor whiteColor]];
5262 [content_ setDelegate:self];
5266 - (void) onSwitch:(id)sender {
5267 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5268 if (metadata == nil) {
5269 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5270 [Sections_ setObject:metadata forKey:basic_];
5273 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5277 - (void) setSection:(Section *)section editing:(BOOL)editing {
5278 if (editing != editing_) {
5280 [switch_ removeFromSuperview];
5282 [self addSubview:switch_];
5291 if (section == nil) {
5292 name_ = UCLocalize("ALL_PACKAGES");
5295 basic_ = [section name];
5296 section_ = [section localized];
5298 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5299 count_ = [NSString stringWithFormat:@"%d", [section count]];
5302 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5305 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5306 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5308 [content_ setNeedsDisplay];
5311 - (void) setFrame:(CGRect)frame {
5312 [super setFrame:frame];
5314 CGRect rect([switch_ frame]);
5315 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5318 - (NSString *) accessibilityLabel {
5322 - (void) drawContentRect:(CGRect)rect {
5323 bool highlighted(highlighted_ && !editing_);
5325 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5330 float width(rect.size.width);
5336 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5338 CGSize size = [count_ sizeWithFont:Font14_];
5342 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5348 /* File Table {{{ */
5349 @interface FileTable : CyteViewController <
5350 UITableViewDataSource,
5353 _transient Database *database_;
5354 _H<Package> package_;
5356 _H<NSMutableArray> files_;
5357 _H<UITableView, 2> list_;
5360 - (id) initWithDatabase:(Database *)database;
5361 - (void) setPackage:(Package *)package;
5365 @implementation FileTable
5367 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5368 return files_ == nil ? 0 : [files_ count];
5371 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5375 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5376 static NSString *reuseIdentifier = @"Cell";
5378 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5380 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5381 [cell setFont:[UIFont systemFontOfSize:16]];
5383 [cell setText:[files_ objectAtIndex:indexPath.row]];
5384 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5389 - (NSURL *) navigationURL {
5390 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5394 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5396 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5397 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5398 [list_ setRowHeight:24.0f];
5399 [(UITableView *) list_ setDataSource:self];
5400 [list_ setDelegate:self];
5401 [[self view] addSubview:list_];
5404 - (void) viewDidLoad {
5405 [super viewDidLoad];
5407 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5410 - (void) releaseSubviews {
5414 - (id) initWithDatabase:(Database *)database {
5415 if ((self = [super init]) != nil) {
5416 database_ = database;
5418 files_ = [NSMutableArray arrayWithCapacity:32];
5422 - (void) setPackage:(Package *)package {
5426 [files_ removeAllObjects];
5428 if (package != nil) {
5430 name_ = [package id];
5432 if (NSArray *files = [package files])
5433 [files_ addObjectsFromArray:files];
5435 if ([files_ count] != 0) {
5436 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5437 [files_ removeObjectAtIndex:0];
5438 [files_ sortUsingSelector:@selector(compareByPath:)];
5440 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5441 [stack addObject:@"/"];
5443 for (int i(0), e([files_ count]); i != e; ++i) {
5444 NSString *file = [files_ objectAtIndex:i];
5445 while (![file hasPrefix:[stack lastObject]])
5446 [stack removeLastObject];
5447 NSString *directory = [stack lastObject];
5448 [stack addObject:[file stringByAppendingString:@"/"]];
5449 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5450 ([stack count] - 2) * 3, "",
5451 [file substringFromIndex:[directory length]]
5460 - (void) reloadData {
5463 [self setPackage:[database_ packageWithName:name_]];
5468 /* Package Controller {{{ */
5469 @interface CYPackageController : CydiaWebViewController <
5470 UIActionSheetDelegate
5472 _transient Database *database_;
5473 _H<Package> package_;
5476 _H<NSMutableArray> buttons_;
5477 _H<UIBarButtonItem> button_;
5480 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5484 @implementation CYPackageController
5486 - (NSURL *) navigationURL {
5487 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5490 /* XXX: this is not safe at all... localization of /fail/ */
5491 - (void) _clickButtonWithName:(NSString *)name {
5492 if ([name isEqualToString:UCLocalize("CLEAR")])
5493 [delegate_ clearPackage:package_];
5494 else if ([name isEqualToString:UCLocalize("INSTALL")])
5495 [delegate_ installPackage:package_];
5496 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5497 [delegate_ installPackage:package_];
5498 else if ([name isEqualToString:UCLocalize("REMOVE")])
5499 [delegate_ removePackage:package_];
5500 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5501 [delegate_ installPackage:package_];
5502 else _assert(false);
5505 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5506 NSString *context([sheet context]);
5508 if ([context isEqualToString:@"modify"]) {
5509 if (button != [sheet cancelButtonIndex]) {
5510 NSString *buttonName = [buttons_ objectAtIndex:button];
5511 [self _clickButtonWithName:buttonName];
5514 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5518 - (bool) _allowJavaScriptPanel {
5523 - (void) _customButtonClicked {
5524 int count([buttons_ count]);
5529 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5531 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5532 [buttons addObjectsFromArray:buttons_];
5534 UIActionSheet *sheet = [[[UIActionSheet alloc]
5537 cancelButtonTitle:nil
5538 destructiveButtonTitle:nil
5539 otherButtonTitles:nil
5542 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5544 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5545 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5547 [sheet setContext:@"modify"];
5549 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5553 // We don't want to allow non-commercial packages to do custom things to the install button,
5554 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5555 - (void) customButtonClicked {
5557 [super customButtonClicked];
5559 [self _customButtonClicked];
5562 - (void) reloadButtonClicked {
5563 // Don't reload a commerical package by tapping the loading button,
5564 // but if it's not an Install button, we should forward it on.
5565 if (![package_ uninstalled])
5566 [self _customButtonClicked];
5569 - (void) applyLoadingTitle {
5570 // Don't show "Loading" as the title. Ever.
5573 - (UIBarButtonItem *) rightButton {
5578 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5579 if ((self = [super init]) != nil) {
5580 database_ = database;
5581 buttons_ = [NSMutableArray arrayWithCapacity:4];
5582 name_ = [NSString stringWithString:name];
5583 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5587 - (void) reloadData {
5590 package_ = [database_ packageWithName:name_];
5592 [buttons_ removeAllObjects];
5594 if (package_ != nil) {
5595 [(Package *) package_ parse];
5597 commercial_ = [package_ isCommercial];
5599 if ([package_ mode] != nil)
5600 [buttons_ addObject:UCLocalize("CLEAR")];
5601 if ([package_ source] == nil);
5602 else if ([package_ upgradableAndEssential:NO])
5603 [buttons_ addObject:UCLocalize("UPGRADE")];
5604 else if ([package_ uninstalled])
5605 [buttons_ addObject:UCLocalize("INSTALL")];
5607 [buttons_ addObject:UCLocalize("REINSTALL")];
5608 if (![package_ uninstalled])
5609 [buttons_ addObject:UCLocalize("REMOVE")];
5613 switch ([buttons_ count]) {
5614 case 0: title = nil; break;
5615 case 1: title = [buttons_ objectAtIndex:0]; break;
5616 default: title = UCLocalize("MODIFY"); break;
5619 button_ = [[[UIBarButtonItem alloc]
5621 style:UIBarButtonItemStylePlain
5623 action:@selector(customButtonClicked)
5627 - (bool) isLoading {
5628 return commercial_ ? [super isLoading] : false;
5634 /* Package List Controller {{{ */
5635 @interface PackageListController : CyteViewController <
5636 UITableViewDataSource,
5639 _transient Database *database_;
5641 _H<NSArray> packages_;
5642 _H<NSMutableArray> sections_;
5643 _H<UITableView, 2> list_;
5644 _H<NSMutableArray> index_;
5645 _H<NSMutableDictionary> indices_;
5646 _H<NSString> title_;
5647 unsigned reloading_;
5650 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5651 - (void) setDelegate:(id)delegate;
5652 - (void) resetCursor;
5657 @implementation PackageListController
5659 - (bool) isSummarized {
5663 - (bool) showsSections {
5667 - (void) deselectWithAnimation:(BOOL)animated {
5668 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5671 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5672 CGRect base = [[self view] bounds];
5673 base.size.height -= bounds.size.height;
5674 base.origin = [list_ frame].origin;
5676 [UIView beginAnimations:nil context:NULL];
5677 [UIView setAnimationBeginsFromCurrentState:YES];
5678 [UIView setAnimationCurve:curve];
5679 [UIView setAnimationDuration:duration];
5680 [list_ setFrame:base];
5681 [UIView commitAnimations];
5684 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5685 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5688 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5689 [self resizeForKeyboardBounds:bounds duration:0];
5692 - (void) keyboardWillShow:(NSNotification *)notification {
5695 NSTimeInterval duration;
5696 UIViewAnimationCurve curve;
5697 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5698 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5699 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5700 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5702 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);
5703 UIViewController *base = self;
5704 while ([base parentViewController] != nil)
5705 base = [base parentViewController];
5706 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5707 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5709 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5712 - (void) keyboardWillHide:(NSNotification *)notification {
5713 NSTimeInterval duration;
5714 UIViewAnimationCurve curve;
5715 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5716 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5718 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5721 - (void) viewWillAppear:(BOOL)animated {
5722 [super viewWillAppear:animated];
5724 [self resizeForKeyboardBounds:CGRectZero];
5725 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5726 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5729 - (void) viewWillDisappear:(BOOL)animated {
5730 [super viewWillDisappear:animated];
5732 [self resizeForKeyboardBounds:CGRectZero];
5733 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5734 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5737 - (void) viewDidAppear:(BOOL)animated {
5738 [super viewDidAppear:animated];
5739 [self deselectWithAnimation:animated];
5742 - (void) didSelectPackage:(Package *)package {
5743 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5744 [view setDelegate:delegate_];
5745 [[self navigationController] pushViewController:view animated:YES];
5748 #if TryIndexedCollation
5749 + (BOOL) hasIndexedCollation {
5750 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5754 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5755 NSInteger count([sections_ count]);
5756 return count == 0 ? 1 : count;
5759 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5760 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5762 return [[sections_ objectAtIndex:section] name];
5765 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5766 if ([sections_ count] == 0)
5768 return [[sections_ objectAtIndex:section] count];
5771 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5772 @synchronized (database_) {
5773 if ([database_ era] != era_)
5776 Section *section([sections_ objectAtIndex:[path section]]);
5777 NSInteger row([path row]);
5778 Package *package([packages_ objectAtIndex:([section row] + row)]);
5779 return [[package retain] autorelease];
5782 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5783 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5785 cell = [[[PackageCell alloc] init] autorelease];
5786 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5790 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5791 Package *package([self packageAtIndexPath:path]);
5792 package = [database_ packageWithName:[package id]];
5793 [self didSelectPackage:package];
5796 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5797 if ([self showsSections])
5803 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5804 #if TryIndexedCollation
5805 if ([[self class] hasIndexedCollation]) {
5806 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5813 - (void) updateHeight {
5814 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5817 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5818 if ((self = [super init]) != nil) {
5819 database_ = database;
5820 title_ = [title copy];
5821 [[self navigationItem] setTitle:title_];
5823 #if TryIndexedCollation
5824 if ([[self class] hasIndexedCollation])
5825 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5828 index_ = [NSMutableArray arrayWithCapacity:32];
5830 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5832 packages_ = [NSArray array];
5833 sections_ = [NSMutableArray arrayWithCapacity:16];
5835 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5836 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5837 [[self view] addSubview:list_];
5839 // XXX: is 20 the most optimal number here?
5840 [list_ setSectionIndexMinimumDisplayRowCount:20];
5842 [(UITableView *) list_ setDataSource:self];
5843 [list_ setDelegate:self];
5845 [self updateHeight];
5849 - (void) setDelegate:(id)delegate {
5850 delegate_ = delegate;
5853 - (bool) shouldYield {
5857 - (bool) shouldBlock {
5861 - (NSMutableArray *) _reloadPackages {
5862 @synchronized (database_) {
5863 era_ = [database_ era];
5864 NSArray *packages([database_ packages]);
5866 return [NSMutableArray arrayWithArray:packages];
5869 - (void) _reloadData {
5870 if (reloading_ != 0) {
5875 if ([self shouldYield]) {
5879 if (![self shouldBlock])
5882 hud = [delegate_ addProgressHUD];
5883 [hud setText:UCLocalize("LOADING")];
5887 packages_ = [self yieldToSelector:@selector(_reloadPackages)];
5890 [delegate_ removeProgressHUD:hud];
5891 } while (reloading_ == 2);
5895 packages_ = [self _reloadPackages];
5898 [indices_ removeAllObjects];
5899 [sections_ removeAllObjects];
5901 Section *section = nil;
5903 #if TryIndexedCollation
5904 if ([[self class] hasIndexedCollation]) {
5905 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5906 NSArray *titles = [collation sectionIndexTitles];
5909 _profile(PackageTable$reloadData$Section)
5910 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5914 _profile(PackageTable$reloadData$Section$Package)
5915 package = [packages_ objectAtIndex:offset];
5916 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5919 while (secidx < index) {
5922 _profile(PackageTable$reloadData$Section$Allocate)
5923 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5926 _profile(PackageTable$reloadData$Section$Add)
5927 [sections_ addObject:section];
5931 [section addToCount];
5937 [index_ removeAllObjects];
5939 bool sectioned([self showsSections]);
5941 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
5942 [sections_ addObject:section];
5945 _profile(PackageTable$reloadData$Section)
5946 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5950 _profile(PackageTable$reloadData$Section$Package)
5951 package = [packages_ objectAtIndex:offset];
5952 index = [package index];
5955 if (sectioned && (section == nil || [section index] != index)) {
5956 _profile(PackageTable$reloadData$Section$Allocate)
5957 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5960 [index_ addObject:[section name]];
5961 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5963 _profile(PackageTable$reloadData$Section$Add)
5964 [sections_ addObject:section];
5968 [section addToCount];
5973 [self updateHeight];
5975 _profile(PackageTable$reloadData$List)
5976 [(UITableView *) list_ setDataSource:self];
5981 - (void) reloadData {
5983 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
5986 - (void) resetCursor {
5987 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
5990 - (void) clearData {
5991 [self updateHeight];
5993 [list_ setDataSource:nil];
6001 /* Filtered Package List Controller {{{ */
6002 @interface FilteredPackageListController : PackageListController {
6005 _H<NSObject> object_;
6008 - (void) setObject:(id)object;
6009 - (void) setObject:(id)object forFilter:(SEL)filter;
6012 - (void) setFilter:(SEL)filter;
6014 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6018 @implementation FilteredPackageListController
6024 - (void) setFilter:(SEL)filter {
6025 @synchronized (self) {
6028 /* XXX: this is an unsafe optimization of doomy hell */
6029 Method method(class_getInstanceMethod([Package class], filter));
6030 _assert(method != NULL);
6031 imp_ = method_getImplementation(method);
6032 _assert(imp_ != NULL);
6035 - (void) setObject:(id)object {
6036 @synchronized (self) {
6040 - (void) setObject:(id)object forFilter:(SEL)filter {
6041 [self setFilter:filter];
6042 [self setObject:object];
6045 - (NSMutableArray *) _reloadPackages {
6046 @synchronized (database_) {
6047 era_ = [database_ era];
6048 NSArray *packages([database_ packages]);
6050 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6054 _H<NSObject> object;
6056 @synchronized (self) {
6062 _profile(PackageTable$reloadData$Filter)
6063 for (Package *package in packages)
6064 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6065 [filtered addObject:package];
6071 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6072 if ((self = [super initWithDatabase:database title:title]) != nil) {
6073 [self setFilter:filter];
6074 [self setObject:object];
6081 /* Home Controller {{{ */
6082 @interface HomeController : CydiaWebViewController {
6087 @implementation HomeController
6090 if ((self = [super init]) != nil) {
6091 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6096 - (NSURL *) navigationURL {
6097 return [NSURL URLWithString:@"cydia://home"];
6100 - (void) aboutButtonClicked {
6101 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6103 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6104 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6105 [alert setCancelButtonIndex:0];
6108 @"Copyright \u00a9 2008-2011\n"
6111 "Jay Freeman (saurik)\n"
6112 "saurik@saurik.com\n"
6113 "http://www.saurik.com/"
6119 - (UIBarButtonItem *) leftButton {
6120 return [[[UIBarButtonItem alloc]
6121 initWithTitle:UCLocalize("ABOUT")
6122 style:UIBarButtonItemStylePlain
6124 action:@selector(aboutButtonClicked)
6128 - (void) unloadData {
6135 /* Manage Controller {{{ */
6136 @interface ManageController : CydiaWebViewController {
6139 - (void) queueStatusDidChange;
6143 @implementation ManageController
6146 if ((self = [super init]) != nil) {
6147 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6151 - (NSURL *) navigationURL {
6152 return [NSURL URLWithString:@"cydia://manage"];
6155 - (UIBarButtonItem *) leftButton {
6156 return [[[UIBarButtonItem alloc]
6157 initWithTitle:UCLocalize("SETTINGS")
6158 style:UIBarButtonItemStylePlain
6160 action:@selector(settingsButtonClicked)
6164 - (void) settingsButtonClicked {
6165 [delegate_ showSettings];
6168 - (void) queueButtonClicked {
6172 - (UIBarButtonItem *) customButton {
6173 return Queuing_ ? [[[UIBarButtonItem alloc]
6174 initWithTitle:UCLocalize("QUEUE")
6175 style:UIBarButtonItemStyleDone
6177 action:@selector(queueButtonClicked)
6178 ] autorelease] : [super customButton];
6181 - (void) queueStatusDidChange {
6182 [self applyRightButton];
6185 - (bool) isLoading {
6186 return !Queuing_ && [super isLoading];
6192 /* Refresh Bar {{{ */
6193 @interface RefreshBar : UINavigationBar {
6194 _H<UIProgressIndicator> indicator_;
6195 _H<UITextLabel> prompt_;
6196 _H<UIProgressBar> progress_;
6197 _H<UINavigationButton> cancel_;
6202 @implementation RefreshBar
6204 - (void) positionViews {
6205 CGRect frame = [cancel_ frame];
6206 frame.size = [cancel_ sizeThatFits:frame.size];
6207 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6208 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6209 [cancel_ setFrame:frame];
6211 CGSize prgsize = {75, 100};
6213 [self frame].size.width - prgsize.width - 10,
6214 ([self frame].size.height - prgsize.height) / 2
6216 [progress_ setFrame:prgrect];
6218 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6219 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6220 CGRect indrect = {{indoffset, indoffset}, indsize};
6221 [indicator_ setFrame:indrect];
6223 CGSize prmsize = {215, indsize.height + 4};
6225 indoffset * 2 + indsize.width,
6226 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6228 [prompt_ setFrame:prmrect];
6231 - (void) setFrame:(CGRect)frame {
6232 [super setFrame:frame];
6233 [self positionViews];
6236 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6237 if ((self = [super initWithFrame:frame]) != nil) {
6238 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6240 [self setBarStyle:UIBarStyleBlack];
6242 UIBarStyle barstyle([self _barStyle:NO]);
6243 bool ugly(barstyle == UIBarStyleDefault);
6245 UIProgressIndicatorStyle style = ugly ?
6246 UIProgressIndicatorStyleMediumBrown :
6247 UIProgressIndicatorStyleMediumWhite;
6249 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6250 [(UIProgressIndicator *) indicator_ setStyle:style];
6251 [indicator_ startAnimation];
6252 [self addSubview:indicator_];
6254 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6255 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6256 [prompt_ setBackgroundColor:[UIColor clearColor]];
6257 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6258 [self addSubview:prompt_];
6260 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6261 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6262 [(UIProgressBar *) progress_ setStyle:0];
6263 [self addSubview:progress_];
6265 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6266 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6267 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6268 [cancel_ setBarStyle:barstyle];
6270 [self positionViews];
6274 - (void) setCancellable:(bool)cancellable {
6276 [self addSubview:cancel_];
6278 [cancel_ removeFromSuperview];
6282 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6283 [progress_ setProgress:0];
6287 [self setCancellable:NO];
6290 - (void) setPrompt:(NSString *)prompt {
6291 [prompt_ setText:prompt];
6294 - (void) setProgress:(float)progress {
6295 [progress_ setProgress:progress];
6301 /* Cydia Navigation Controller Interface {{{ */
6302 @interface UINavigationController (Cydia)
6304 - (NSArray *) navigationURLCollection;
6305 - (void) unloadData;
6310 /* Cydia Tab Bar Controller {{{ */
6311 @interface CYTabBarController : UITabBarController <
6312 UITabBarControllerDelegate,
6315 _transient Database *database_;
6316 _H<RefreshBar, 1> refreshbar_;
6320 // XXX: ok, "updatedelegate_"?...
6321 _transient NSObject<CydiaDelegate> *updatedelegate_;
6323 _H<UIViewController> remembered_;
6324 _transient UIViewController *transient_;
6327 - (NSArray *) navigationURLCollection;
6328 - (void) dropBar:(BOOL)animated;
6329 - (void) beginUpdate;
6330 - (void) raiseBar:(BOOL)animated;
6332 - (void) unloadData;
6336 @implementation CYTabBarController
6338 - (void) setUnselectedViewController:(UIViewController *)transient {
6339 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6340 if (transient != nil) {
6341 if (transient_ == nil)
6342 remembered_ = [controllers objectAtIndex:0];
6343 transient_ = transient;
6344 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6345 [controllers replaceObjectAtIndex:0 withObject:transient_];
6346 [self setSelectedIndex:0];
6347 [self setViewControllers:controllers];
6348 [self concealTabBarSelection];
6349 } else if (remembered_ != nil) {
6350 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6351 transient_ = transient;
6352 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6354 [self setViewControllers:controllers];
6355 [self revealTabBarSelection];
6359 - (UIViewController *) unselectedViewController {
6363 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6364 if ([self unselectedViewController])
6365 [self setUnselectedViewController:nil];
6368 - (NSArray *) navigationURLCollection {
6369 NSMutableArray *items([NSMutableArray array]);
6371 // XXX: Should this deal with transient view controllers?
6372 for (id navigation in [self viewControllers]) {
6373 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6375 [items addObject:stack];
6381 - (void) unloadData {
6382 UIViewController *selected([self selectedViewController]);
6383 for (UINavigationController *controller in [self viewControllers])
6384 [controller unloadData];
6386 [selected reloadData];
6388 if (UIViewController *unselected = [self unselectedViewController])
6389 [unselected reloadData];
6395 [[NSNotificationCenter defaultCenter] removeObserver:self];
6400 - (id) initWithDatabase:(Database *)database {
6401 if ((self = [super init]) != nil) {
6402 database_ = database;
6403 [self setDelegate:self];
6405 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6406 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6408 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6412 - (void) setUpdate:(NSDate *)date {
6416 - (void) beginUpdate {
6417 [(RefreshBar *) refreshbar_ start];
6420 [updatedelegate_ retainNetworkActivityIndicator];
6424 detachNewThreadSelector:@selector(performUpdate)
6430 - (void) performUpdate {
6431 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6434 status.setDelegate(self);
6435 [database_ updateWithStatus:status];
6438 performSelectorOnMainThread:@selector(completeUpdate)
6446 - (void) stopUpdateWithSelector:(SEL)selector {
6448 [updatedelegate_ releaseNetworkActivityIndicator];
6450 [self raiseBar:YES];
6453 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6456 - (void) completeUpdate {
6459 [self stopUpdateWithSelector:@selector(reloadData)];
6462 - (void) cancelUpdate {
6463 [self stopUpdateWithSelector:@selector(updateData)];
6466 - (void) cancelPressed {
6467 [self cancelUpdate];
6474 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6475 [refreshbar_ setPrompt:[event compoundMessage]];
6478 - (bool) isProgressCancelled {
6482 - (void) setProgressCancellable:(NSNumber *)cancellable {
6483 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6486 - (void) setProgressPercent:(NSNumber *)percent {
6487 [refreshbar_ setProgress:[percent floatValue]];
6490 - (void) setProgressStatus:(NSDictionary *)status {
6492 [self setProgressPercent:[status objectForKey:@"Percent"]];
6495 - (void) setUpdateDelegate:(id)delegate {
6496 updatedelegate_ = delegate;
6499 - (CGFloat) statusBarHeight {
6500 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6501 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6503 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6507 - (UIView *) transitionView {
6508 if ([self respondsToSelector:@selector(_transitionView)])
6509 return [self _transitionView];
6511 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6514 - (void) dropBar:(BOOL)animated {
6519 UIView *transition([self transitionView]);
6520 [[self view] addSubview:refreshbar_];
6522 CGRect barframe([refreshbar_ frame]);
6524 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6525 barframe.origin.y = [self statusBarHeight];
6527 barframe.origin.y = 0;
6529 [refreshbar_ setFrame:barframe];
6532 [UIView beginAnimations:nil context:NULL];
6534 CGRect viewframe = [transition frame];
6535 viewframe.origin.y += barframe.size.height;
6536 viewframe.size.height -= barframe.size.height;
6537 [transition setFrame:viewframe];
6540 [UIView commitAnimations];
6542 // Ensure bar has the proper width for our view, it might have changed
6543 barframe.size.width = viewframe.size.width;
6544 [refreshbar_ setFrame:barframe];
6547 - (void) raiseBar:(BOOL)animated {
6552 UIView *transition([self transitionView]);
6553 [refreshbar_ removeFromSuperview];
6555 CGRect barframe([refreshbar_ frame]);
6558 [UIView beginAnimations:nil context:NULL];
6560 CGRect viewframe = [transition frame];
6561 viewframe.origin.y -= barframe.size.height;
6562 viewframe.size.height += barframe.size.height;
6563 [transition setFrame:viewframe];
6566 [UIView commitAnimations];
6569 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6570 bool dropped(dropped_);
6575 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6581 - (void) statusBarFrameChanged:(NSNotification *)notification {
6591 /* Cydia Navigation Controller Implementation {{{ */
6592 @implementation UINavigationController (Cydia)
6594 - (NSArray *) navigationURLCollection {
6595 NSMutableArray *stack([NSMutableArray array]);
6597 for (CyteViewController *controller in [self viewControllers]) {
6598 NSString *url = [[controller navigationURL] absoluteString];
6600 [stack addObject:url];
6606 - (void) reloadData {
6609 if (UIViewController *visible = [self visibleViewController])
6610 [visible reloadData];
6613 - (void) unloadData {
6614 for (CyteViewController *page in [self viewControllers])
6623 /* Cydia:// Protocol {{{ */
6624 @interface CydiaURLProtocol : NSURLProtocol {
6629 @implementation CydiaURLProtocol
6631 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6632 NSURL *url([request URL]);
6636 NSString *scheme([[url scheme] lowercaseString]);
6637 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6639 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6645 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6649 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6650 id<NSURLProtocolClient> client([self client]);
6652 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6654 NSData *data(UIImagePNGRepresentation(icon));
6656 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6657 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6658 [client URLProtocol:self didLoadData:data];
6659 [client URLProtocolDidFinishLoading:self];
6663 - (void) startLoading {
6664 id<NSURLProtocolClient> client([self client]);
6665 NSURLRequest *request([self request]);
6667 NSURL *url([request URL]);
6668 NSString *href([url absoluteString]);
6669 NSString *scheme([[url scheme] lowercaseString]);
6673 if ([scheme isEqualToString:@"cydia"])
6674 path = [href substringFromIndex:8];
6675 else if ([scheme isEqualToString:@"about"])
6676 path = [href substringFromIndex:12];
6677 else _assert(false);
6679 NSRange slash([path rangeOfString:@"/"]);
6682 if (slash.location == NSNotFound) {
6686 command = [path substringToIndex:slash.location];
6687 path = [path substringFromIndex:(slash.location + 1)];
6690 Database *database([Database sharedInstance]);
6692 if ([command isEqualToString:@"package-icon"]) {
6695 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6696 Package *package([database packageWithName:path]);
6700 UIImage *icon([package icon]);
6701 [self _returnPNGWithImage:icon forRequest:request];
6702 } else if ([command isEqualToString:@"source-icon"]) {
6705 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6706 NSString *source(Simplify(path));
6707 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6709 icon = [UIImage applicationImageNamed:@"unknown.png"];
6710 [self _returnPNGWithImage:icon forRequest:request];
6711 } else if ([command isEqualToString:@"uikit-image"]) {
6714 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6715 UIImage *icon(_UIImageWithName(path));
6716 [self _returnPNGWithImage:icon forRequest:request];
6717 } else if ([command isEqualToString:@"section-icon"]) {
6720 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6721 NSString *section(Simplify(path));
6722 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6724 icon = [UIImage applicationImageNamed:@"unknown.png"];
6725 [self _returnPNGWithImage:icon forRequest:request];
6727 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6731 - (void) stopLoading {
6737 /* Section Controller {{{ */
6738 @interface SectionController : FilteredPackageListController {
6739 _H<NSString> section_;
6742 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6746 @implementation SectionController
6748 - (NSURL *) navigationURL {
6749 NSString *name = section_;
6753 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6756 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6759 title = UCLocalize("ALL_PACKAGES");
6760 else if (![name isEqual:@""])
6761 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6763 title = UCLocalize("NO_SECTION");
6765 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6772 /* Sections Controller {{{ */
6773 @interface SectionsController : CyteViewController <
6774 UITableViewDataSource,
6777 _transient Database *database_;
6778 _H<NSMutableArray> sections_;
6779 _H<NSMutableArray> filtered_;
6780 _H<UITableView, 2> list_;
6783 - (id) initWithDatabase:(Database *)database;
6784 - (void) editButtonClicked;
6788 @implementation SectionsController
6790 - (NSURL *) navigationURL {
6791 return [NSURL URLWithString:@"cydia://sections"];
6794 - (void) updateNavigationItem {
6795 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6796 if ([sections_ count] == 0) {
6797 [[self navigationItem] setRightBarButtonItem:nil];
6799 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6800 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6802 action:@selector(editButtonClicked)
6803 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6807 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6808 [super setEditing:editing animated:animated];
6813 [delegate_ updateData];
6815 [self updateNavigationItem];
6818 - (void) viewDidAppear:(BOOL)animated {
6819 [super viewDidAppear:animated];
6820 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6823 - (void) viewWillDisappear:(BOOL)animated {
6824 [super viewWillDisappear:animated];
6825 if ([self isEditing]) [self setEditing:NO];
6828 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6829 Section *section = nil;
6830 int index = [indexPath row];
6831 if (![self isEditing]) {
6834 section = [filtered_ objectAtIndex:index];
6836 section = [sections_ objectAtIndex:index];
6841 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6842 if ([self isEditing])
6843 return [sections_ count];
6845 return [filtered_ count] + 1;
6848 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6852 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6853 static NSString *reuseIdentifier = @"SectionCell";
6855 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6857 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6859 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6864 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6865 if ([self isEditing])
6868 Section *section = [self sectionAtIndexPath:indexPath];
6870 SectionController *controller = [[[SectionController alloc]
6871 initWithDatabase:database_
6872 section:[section name]
6874 [controller setDelegate:delegate_];
6876 [[self navigationController] pushViewController:controller animated:YES];
6880 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6882 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6883 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6884 [list_ setRowHeight:45.0f];
6885 [(UITableView *) list_ setDataSource:self];
6886 [list_ setDelegate:self];
6887 [[self view] addSubview:list_];
6890 - (void) viewDidLoad {
6891 [super viewDidLoad];
6893 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6896 - (void) releaseSubviews {
6900 - (id) initWithDatabase:(Database *)database {
6901 if ((self = [super init]) != nil) {
6902 database_ = database;
6904 sections_ = [NSMutableArray arrayWithCapacity:16];
6905 filtered_ = [NSMutableArray arrayWithCapacity:16];
6909 - (void) reloadData {
6912 NSArray *packages = [database_ packages];
6914 [sections_ removeAllObjects];
6915 [filtered_ removeAllObjects];
6917 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6920 for (Package *package in packages) {
6921 NSString *name([package section]);
6922 NSString *key(name == nil ? @"" : name);
6926 _profile(SectionsView$reloadData$Section)
6927 section = [sections objectForKey:key];
6928 if (section == nil) {
6929 _profile(SectionsView$reloadData$Section$Allocate)
6930 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6931 [sections setObject:section forKey:key];
6936 [section addToCount];
6938 _profile(SectionsView$reloadData$Filter)
6939 if (![package valid] || ![package visible])
6947 [sections_ addObjectsFromArray:[sections allValues]];
6949 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6951 for (Section *section in (id) sections_) {
6952 size_t count([section row]);
6956 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6957 [section setCount:count];
6958 [filtered_ addObject:section];
6961 [self updateNavigationItem];
6966 - (void) editButtonClicked {
6967 [self setEditing:![self isEditing] animated:YES];
6973 /* Changes Controller {{{ */
6974 @interface ChangesController : CyteViewController <
6975 UITableViewDataSource,
6978 _transient Database *database_;
6980 _H<NSArray> packages_;
6981 _H<NSMutableArray> sections_;
6982 _H<UITableView, 2> list_;
6986 - (id) initWithDatabase:(Database *)database;
6990 @implementation ChangesController
6992 - (NSURL *) navigationURL {
6993 return [NSURL URLWithString:@"cydia://changes"];
6996 - (void) viewDidAppear:(BOOL)animated {
6997 [super viewDidAppear:animated];
6998 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7001 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7002 NSInteger count([sections_ count]);
7003 return count == 0 ? 1 : count;
7006 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7007 if ([sections_ count] == 0)
7009 return [[sections_ objectAtIndex:section] name];
7012 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7013 if ([sections_ count] == 0)
7015 return [[sections_ objectAtIndex:section] count];
7018 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7019 @synchronized (database_) {
7020 if ([database_ era] != era_)
7023 NSUInteger sectionIndex([path section]);
7024 if (sectionIndex >= [sections_ count])
7026 Section *section([sections_ objectAtIndex:sectionIndex]);
7027 NSInteger row([path row]);
7028 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7031 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7032 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7034 cell = [[[PackageCell alloc] init] autorelease];
7035 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7039 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7040 Package *package([self packageAtIndexPath:path]);
7041 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7042 [view setDelegate:delegate_];
7043 [[self navigationController] pushViewController:view animated:YES];
7047 - (void) refreshButtonClicked {
7048 [delegate_ beginUpdate];
7049 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7052 - (void) upgradeButtonClicked {
7053 [delegate_ distUpgrade];
7057 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7059 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7060 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7061 [list_ setRowHeight:73];
7062 [(UITableView *) list_ setDataSource:self];
7063 [list_ setDelegate:self];
7064 [[self view] addSubview:list_];
7067 - (void) viewDidLoad {
7068 [super viewDidLoad];
7070 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7073 - (void) releaseSubviews {
7077 - (id) initWithDatabase:(Database *)database {
7078 if ((self = [super init]) != nil) {
7079 database_ = database;
7081 packages_ = [NSArray array];
7082 sections_ = [NSMutableArray arrayWithCapacity:16];
7086 - (NSMutableArray *) _reloadPackages {
7087 @synchronized (database_) {
7088 era_ = [database_ era];
7089 NSArray *packages([database_ packages]);
7091 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7094 _profile(ChangesController$_reloadPackages$Filter)
7095 for (Package *package in packages)
7096 if ([package upgradableAndEssential:YES] || [package visible])
7097 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7100 _profile(ChangesController$_reloadPackages$radixSort)
7101 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7108 - (void) _reloadData {
7111 UIProgressHUD *hud([delegate_ addProgressHUD]);
7112 [hud setText:UCLocalize("LOADING")];
7113 //NSLog(@"HUD:%@::%@", delegate_, hud);
7114 packages_ = [self yieldToSelector:@selector(_reloadPackages)];
7115 [delegate_ removeProgressHUD:hud];
7117 packages_ = [self _reloadPackages];
7120 @synchronized (database_) {
7121 if (era_ != [database_ era])
7124 [sections_ removeAllObjects];
7126 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7127 Section *ignored = nil;
7128 Section *section = nil;
7132 bool unseens = false;
7134 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7136 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7137 Package *package = [packages_ objectAtIndex:offset];
7139 BOOL uae = [package upgradableAndEssential:YES];
7143 time_t seen([package seen]);
7145 if (section == nil || last != seen) {
7149 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7152 _profile(ChangesController$reloadData$Allocate)
7153 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7154 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7155 [sections_ addObject:section];
7159 [section addToCount];
7160 } else if ([package ignored]) {
7161 if (ignored == nil) {
7162 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7164 [ignored addToCount];
7167 [upgradable addToCount];
7172 CFRelease(formatter);
7175 Section *last = [sections_ lastObject];
7176 size_t count = [last count];
7177 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7178 [sections_ removeLastObject];
7181 if ([ignored count] != 0)
7182 [sections_ insertObject:ignored atIndex:0];
7184 [sections_ insertObject:upgradable atIndex:0];
7189 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7190 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7191 style:UIBarButtonItemStylePlain
7193 action:@selector(upgradeButtonClicked)
7196 if (![delegate_ updating])
7197 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7198 initWithTitle:UCLocalize("REFRESH")
7199 style:UIBarButtonItemStylePlain
7201 action:@selector(refreshButtonClicked)
7207 - (void) reloadData {
7209 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7214 /* Search Controller {{{ */
7215 @interface SearchController : FilteredPackageListController <
7218 _H<UISearchBar, 1> search_;
7222 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7223 - (void) reloadData;
7227 @implementation SearchController
7229 - (NSURL *) navigationURL {
7230 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7231 return [NSURL URLWithString:@"cydia://search"];
7233 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7236 - (void) useSearch {
7237 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7242 - (void) viewWillAppear:(BOOL)animated {
7243 [super viewWillAppear:animated];
7245 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7249 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7250 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7255 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7256 [search_ resignFirstResponder];
7260 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7261 [search_ setText:@""];
7262 [self searchBarButtonClicked:searchBar];
7265 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7266 [self searchBarButtonClicked:searchBar];
7269 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7270 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7274 - (bool) shouldYield {
7278 - (bool) shouldBlock {
7279 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7282 - (bool) isSummarized {
7283 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7286 - (bool) showsSections {
7290 - (NSMutableArray *) _reloadPackages {
7291 NSMutableArray *packages([super _reloadPackages]);
7292 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7293 [packages radixSortUsingSelector:@selector(rank)];
7297 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7298 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7299 search_ = [[[UISearchBar alloc] init] autorelease];
7300 [search_ setDelegate:self];
7303 [search_ setText:query];
7307 - (void) viewDidAppear:(BOOL)animated {
7308 [super viewDidAppear:animated];
7310 if (!searchloaded_) {
7311 searchloaded_ = YES;
7312 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7313 [search_ layoutSubviews];
7314 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7316 UITextField *textField;
7317 if ([search_ respondsToSelector:@selector(searchField)])
7318 textField = [search_ searchField];
7320 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7322 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7323 [textField setEnablesReturnKeyAutomatically:NO];
7324 [[self navigationItem] setTitleView:textField];
7328 - (void) reloadData {
7329 [self setObject:[search_ text]];
7335 - (void) didSelectPackage:(Package *)package {
7336 [search_ resignFirstResponder];
7337 [super didSelectPackage:package];
7342 /* Package Settings Controller {{{ */
7343 @interface PackageSettingsController : CyteViewController <
7344 UITableViewDataSource,
7347 _transient Database *database_;
7349 _H<Package> package_;
7350 _H<UITableView, 2> table_;
7351 _H<UISwitch> subscribedSwitch_;
7352 _H<UISwitch> ignoredSwitch_;
7353 _H<UITableViewCell> subscribedCell_;
7354 _H<UITableViewCell> ignoredCell_;
7357 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7361 @implementation PackageSettingsController
7363 - (NSURL *) navigationURL {
7364 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7367 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7368 if (package_ == nil)
7371 if ([package_ installed] == nil)
7377 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7378 if (package_ == nil)
7381 // both sections contain just one item right now.
7385 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7389 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7391 return UCLocalize("SHOW_ALL_CHANGES_EX");
7393 return UCLocalize("IGNORE_UPGRADES_EX");
7396 - (void) onSubscribed:(id)control {
7397 bool value([control isOn]);
7398 if (package_ == nil)
7400 if ([package_ setSubscribed:value])
7401 [delegate_ updateData];
7404 - (void) _updateIgnored {
7405 const char *package([name_ UTF8String]);
7406 bool on([ignoredSwitch_ isOn]);
7408 pid_t pid(ExecFork());
7410 FILE *dpkg(popen("dpkg --set-selections", "w"));
7411 fwrite(package, strlen(package), 1, dpkg);
7414 fwrite(" hold\n", 6, 1, dpkg);
7416 fwrite(" install\n", 9, 1, dpkg);
7426 int result(waitpid(pid, &status, 0));
7429 _assert(result == pid);
7435 - (void) onIgnored:(id)control {
7436 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7437 [invocation setTarget:self];
7438 [invocation setSelector:@selector(_updateIgnored)];
7440 [delegate_ reloadDataWithInvocation:invocation];
7443 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7444 if (package_ == nil)
7447 switch ([indexPath section]) {
7448 case 0: return subscribedCell_;
7449 case 1: return ignoredCell_;
7458 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7460 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7461 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7462 [(UITableView *) table_ setDataSource:self];
7463 [table_ setDelegate:self];
7464 [[self view] addSubview:table_];
7466 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7467 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7468 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7470 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7471 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7472 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7474 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7475 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7476 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7477 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7479 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7480 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7481 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7482 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7485 - (void) viewDidLoad {
7486 [super viewDidLoad];
7488 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7491 - (void) releaseSubviews {
7493 subscribedCell_ = nil;
7495 ignoredSwitch_ = nil;
7496 subscribedSwitch_ = nil;
7499 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7500 if ((self = [super init]) != nil) {
7501 database_ = database;
7506 - (void) reloadData {
7509 package_ = [database_ packageWithName:name_];
7511 if (package_ != nil) {
7512 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7513 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7514 } // XXX: what now, G?
7516 [table_ reloadData];
7522 /* Installed Controller {{{ */
7523 @interface InstalledController : FilteredPackageListController {
7527 - (id) initWithDatabase:(Database *)database;
7529 - (void) updateRoleButton;
7530 - (void) queueStatusDidChange;
7534 @implementation InstalledController
7536 - (NSURL *) navigationURL {
7537 return [NSURL URLWithString:@"cydia://installed"];
7540 - (id) initWithDatabase:(Database *)database {
7541 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7542 [self updateRoleButton];
7543 [self queueStatusDidChange];
7548 - (void) queueButtonClicked {
7553 - (void) queueStatusDidChange {
7557 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7558 initWithTitle:UCLocalize("QUEUE")
7559 style:UIBarButtonItemStyleDone
7561 action:@selector(queueButtonClicked)
7564 [[self navigationItem] setLeftBarButtonItem:nil];
7570 - (void) updateRoleButton {
7571 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7572 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7573 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7574 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7576 action:@selector(roleButtonClicked)
7580 - (void) roleButtonClicked {
7581 [self setObject:[NSNumber numberWithBool:expert_]];
7585 [self updateRoleButton];
7591 /* Source Cell {{{ */
7592 @interface SourceCell : CyteTableViewCell <
7593 CyteTableViewCellDelegate
7596 _H<NSString> origin_;
7597 _H<NSString> label_;
7600 - (void) setSource:(Source *)source;
7604 @implementation SourceCell
7606 - (void) _setImage:(UIImage *)image {
7608 [content_ setNeedsDisplay];
7611 - (void) _setSource:(Source *)source {
7612 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7614 if (NSString *base = [source base])
7615 if ([base length] != 0) {
7616 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7618 if (NSData *data = [NSURLConnection
7619 sendSynchronousRequest:[NSURLRequest
7621 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7625 returningResponse:NULL
7628 if (UIImage *image = [UIImage imageWithData:data])
7629 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7635 - (void) setSource:(Source *)source {
7636 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7638 origin_ = [source name];
7639 label_ = [source uri];
7641 [content_ setNeedsDisplay];
7643 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7646 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7647 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7648 UIView *content([self contentView]);
7649 CGRect bounds([content bounds]);
7651 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7652 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7653 [content_ setBackgroundColor:[UIColor whiteColor]];
7654 [content addSubview:content_];
7656 [content_ setDelegate:self];
7657 [content_ setOpaque:YES];
7661 - (NSString *) accessibilityLabel {
7665 - (void) drawContentRect:(CGRect)rect {
7666 bool highlighted(highlighted_);
7667 float width(rect.size.width);
7670 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7677 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7681 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7686 /* Source Controller {{{ */
7687 @interface SourceController : FilteredPackageListController {
7688 _transient Source *source_;
7692 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7696 @implementation SourceController
7698 - (NSURL *) navigationURL {
7699 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7702 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7703 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7705 key_ = [source key];
7709 - (void) reloadData {
7710 source_ = [database_ sourceWithKey:key_];
7711 key_ = [source_ key];
7712 [self setObject:source_];
7714 [[self navigationItem] setTitle:[source_ label]];
7721 /* Sources Controller {{{ */
7722 @interface SourcesController : CyteViewController <
7723 UITableViewDataSource,
7726 _transient Database *database_;
7727 _H<UITableView, 2> list_;
7728 _H<NSMutableArray> sources_;
7732 _H<UIProgressHUD> hud_;
7735 //NSURLConnection *installer_;
7736 NSURLConnection *trivial_;
7737 NSURLConnection *trivial_bz2_;
7738 NSURLConnection *trivial_gz_;
7739 //NSURLConnection *automatic_;
7744 - (id) initWithDatabase:(Database *)database;
7745 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7749 @implementation SourcesController
7751 - (void) _releaseConnection:(NSURLConnection *)connection {
7752 if (connection != nil) {
7753 [connection cancel];
7754 //[connection setDelegate:nil];
7755 [connection release];
7760 //[self _releaseConnection:installer_];
7761 [self _releaseConnection:trivial_];
7762 [self _releaseConnection:trivial_gz_];
7763 [self _releaseConnection:trivial_bz2_];
7764 //[self _releaseConnection:automatic_];
7769 - (NSURL *) navigationURL {
7770 return [NSURL URLWithString:@"cydia://sources"];
7773 - (void) viewDidAppear:(BOOL)animated {
7774 [super viewDidAppear:animated];
7775 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7778 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7779 return offset_ == 0 ? 1 : 2;
7782 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7783 switch (section + (offset_ == 0 ? 1 : 0)) {
7784 case 0: return UCLocalize("ENTERED_BY_USER");
7785 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7791 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7792 int count = [sources_ count];
7794 case 0: return (offset_ == 0 ? count : offset_);
7795 case 1: return count - offset_;
7801 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7803 switch (indexPath.section) {
7804 case 0: idx = indexPath.row; break;
7805 case 1: idx = indexPath.row + offset_; break;
7809 return [sources_ objectAtIndex:idx];
7812 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7813 static NSString *cellIdentifier = @"SourceCell";
7815 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7816 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7817 [cell setSource:[self sourceAtIndexPath:indexPath]];
7818 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7823 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7824 Source *source = [self sourceAtIndexPath:indexPath];
7826 SourceController *controller = [[[SourceController alloc]
7827 initWithDatabase:database_
7831 [controller setDelegate:delegate_];
7833 [[self navigationController] pushViewController:controller animated:YES];
7836 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7837 Source *source = [self sourceAtIndexPath:indexPath];
7838 return [source record] != nil;
7841 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7842 if (editingStyle == UITableViewCellEditingStyleDelete) {
7843 Source *source = [self sourceAtIndexPath:indexPath];
7844 [Sources_ removeObjectForKey:[source key]];
7845 [delegate_ syncData];
7850 [delegate_ addTrivialSource:href_];
7851 [delegate_ syncData];
7854 - (NSString *) getWarning {
7855 NSString *href(href_);
7856 NSRange colon([href rangeOfString:@"://"]);
7857 if (colon.location != NSNotFound)
7858 href = [href substringFromIndex:(colon.location + 3)];
7859 href = [href stringByAddingPercentEscapes];
7860 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7861 href = [href stringByCachingURLWithCurrentCDN];
7863 NSURL *url([NSURL URLWithString:href]);
7865 NSStringEncoding encoding;
7866 NSError *error(nil);
7868 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7869 return [warning length] == 0 ? nil : warning;
7873 - (void) _endConnection:(NSURLConnection *)connection {
7874 // XXX: the memory management in this method is horribly awkward
7876 NSURLConnection **field = NULL;
7877 if (connection == trivial_)
7879 else if (connection == trivial_bz2_)
7880 field = &trivial_bz2_;
7881 else if (connection == trivial_gz_)
7882 field = &trivial_gz_;
7883 _assert(field != NULL);
7884 [connection release];
7889 trivial_bz2_ == nil &&
7892 [delegate_ releaseNetworkActivityIndicator];
7894 [delegate_ removeProgressHUD:hud_];
7900 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7903 UIAlertView *alert = [[[UIAlertView alloc]
7904 initWithTitle:UCLocalize("SOURCE_WARNING")
7907 cancelButtonTitle:UCLocalize("CANCEL")
7909 UCLocalize("ADD_ANYWAY"),
7913 [alert setContext:@"warning"];
7914 [alert setNumberOfRows:1];
7918 } else if (error_ != nil) {
7919 UIAlertView *alert = [[[UIAlertView alloc]
7920 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7921 message:[error_ localizedDescription]
7923 cancelButtonTitle:UCLocalize("OK")
7924 otherButtonTitles:nil
7927 [alert setContext:@"urlerror"];
7930 UIAlertView *alert = [[[UIAlertView alloc]
7931 initWithTitle:UCLocalize("NOT_REPOSITORY")
7932 message:UCLocalize("NOT_REPOSITORY_EX")
7934 cancelButtonTitle:UCLocalize("OK")
7935 otherButtonTitles:nil
7938 [alert setContext:@"trivial"];
7947 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7948 switch ([response statusCode]) {
7954 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7955 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7957 [self _endConnection:connection];
7960 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7961 [self _endConnection:connection];
7964 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7965 NSMutableURLRequest *request = [NSMutableURLRequest
7966 requestWithURL:[NSURL URLWithString:href]
7967 cachePolicy:NSURLRequestUseProtocolCachePolicy
7968 timeoutInterval:120.0
7971 [request setHTTPMethod:method];
7973 if (Machine_ != NULL)
7974 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7975 if (UniqueID_ != nil)
7976 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7978 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7981 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7982 NSString *context([alert context]);
7984 if ([context isEqualToString:@"source"]) {
7987 NSString *href = [[alert textField] text];
7989 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7991 if (![href hasSuffix:@"/"])
7992 href_ = [href stringByAppendingString:@"/"];
7996 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7997 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7998 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7999 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8003 // XXX: this is stupid
8004 hud_ = [delegate_ addProgressHUD];
8005 [hud_ setText:UCLocalize("VERIFYING_URL")];
8006 [delegate_ retainNetworkActivityIndicator];
8015 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8016 } else if ([context isEqualToString:@"trivial"])
8017 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8018 else if ([context isEqualToString:@"urlerror"])
8019 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8020 else if ([context isEqualToString:@"warning"]) {
8034 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8039 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8041 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8042 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8043 [list_ setRowHeight:56];
8044 [(UITableView *) list_ setDataSource:self];
8045 [list_ setDelegate:self];
8046 [[self view] addSubview:list_];
8049 - (void) viewDidLoad {
8050 [super viewDidLoad];
8052 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8053 [self updateButtonsForEditingStatus:NO animated:NO];
8056 - (void) releaseSubviews {
8060 - (id) initWithDatabase:(Database *)database {
8061 if ((self = [super init]) != nil) {
8062 database_ = database;
8063 sources_ = [NSMutableArray arrayWithCapacity:16];
8067 - (void) reloadData {
8071 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8074 [sources_ removeAllObjects];
8075 [sources_ addObjectsFromArray:[database_ sources]];
8077 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8080 int count([sources_ count]);
8082 for (int i = 0; i != count; i++) {
8083 if ([[sources_ objectAtIndex:i] record] == nil)
8088 [list_ setEditing:NO];
8089 [self updateButtonsForEditingStatus:NO animated:NO];
8093 - (void) showAddSourcePrompt {
8094 UIAlertView *alert = [[[UIAlertView alloc]
8095 initWithTitle:UCLocalize("ENTER_APT_URL")
8098 cancelButtonTitle:UCLocalize("CANCEL")
8100 UCLocalize("ADD_SOURCE"),
8104 [alert setContext:@"source"];
8106 [alert setNumberOfRows:1];
8107 [alert addTextFieldWithValue:@"http://" label:@""];
8109 UITextInputTraits *traits = [[alert textField] textInputTraits];
8110 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8111 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8112 [traits setKeyboardType:UIKeyboardTypeURL];
8113 // XXX: UIReturnKeyDone
8114 [traits setReturnKeyType:UIReturnKeyNext];
8119 - (void) addButtonClicked {
8120 [self showAddSourcePrompt];
8123 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8124 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8125 initWithTitle:UCLocalize("ADD")
8126 style:UIBarButtonItemStylePlain
8128 action:@selector(addButtonClicked)
8129 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8131 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8132 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8133 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8135 action:@selector(editButtonClicked)
8136 ] autorelease] animated:animated];
8138 if (IsWildcat_ && !editing)
8139 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8140 initWithTitle:UCLocalize("SETTINGS")
8141 style:UIBarButtonItemStylePlain
8143 action:@selector(settingsButtonClicked)
8147 - (void) settingsButtonClicked {
8148 [delegate_ showSettings];
8151 - (void) editButtonClicked {
8152 [list_ setEditing:![list_ isEditing] animated:YES];
8154 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8160 /* Settings Controller {{{ */
8161 @interface SettingsController : CyteViewController <
8162 UITableViewDataSource,
8165 _transient Database *database_;
8166 // XXX: ok, "roledelegate_"?...
8167 _transient id roledelegate_;
8168 _H<UITableView, 2> table_;
8169 _H<UISegmentedControl> segment_;
8170 _H<UIView> container_;
8173 - (void) showDoneButton;
8174 - (void) resizeSegmentedControl;
8178 @implementation SettingsController
8181 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8183 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8184 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8185 [table_ setDelegate:self];
8186 [(UITableView *) table_ setDataSource:self];
8187 [[self view] addSubview:table_];
8189 NSArray *items = [NSArray arrayWithObjects:
8191 UCLocalize("HACKER"),
8192 UCLocalize("DEVELOPER"),
8194 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8195 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8196 [container_ addSubview:segment_];
8199 - (void) viewDidLoad {
8200 [super viewDidLoad];
8202 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8205 if ([Role_ isEqualToString:@"User"]) index = 0;
8206 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8207 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8209 [segment_ setSelectedSegmentIndex:index];
8210 [self showDoneButton];
8213 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8214 [self resizeSegmentedControl];
8217 - (void) releaseSubviews {
8223 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8224 if ((self = [super init]) != nil) {
8225 database_ = database;
8226 roledelegate_ = delegate;
8230 - (void) resizeSegmentedControl {
8231 CGFloat width = [[self view] frame].size.width;
8232 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8235 - (void) viewWillAppear:(BOOL)animated {
8236 [super viewWillAppear:animated];
8238 [self resizeSegmentedControl];
8241 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8242 [self resizeSegmentedControl];
8245 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8246 [self resizeSegmentedControl];
8250 NSString *role(nil);
8252 switch ([segment_ selectedSegmentIndex]) {
8253 case 0: role = @"User"; break;
8254 case 1: role = @"Hacker"; break;
8255 case 2: role = @"Developer"; break;
8260 if (![role isEqualToString:Role_]) {
8261 bool rolling(Role_ == nil);
8264 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8268 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8272 [roledelegate_ loadData];
8274 [roledelegate_ updateData];
8278 - (void) segmentChanged:(UISegmentedControl *)control {
8279 [self showDoneButton];
8282 - (void) saveAndClose {
8285 [[self navigationItem] setRightBarButtonItem:nil];
8286 [[self navigationController] dismissModalViewControllerAnimated:YES];
8289 - (void) doneButtonClicked {
8290 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8291 [spinner startAnimating];
8292 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8293 [[self navigationItem] setRightBarButtonItem:spinItem];
8295 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8298 - (void) showDoneButton {
8299 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8300 initWithTitle:UCLocalize("DONE")
8301 style:UIBarButtonItemStyleDone
8303 action:@selector(doneButtonClicked)
8304 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8307 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8308 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8312 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8316 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8317 return nil; // This method is required by the protocol.
8320 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8322 return UCLocalize("ROLE_EX");
8324 return [NSString stringWithFormat:
8325 @"%@: %@\n%@: %@\n%@: %@",
8326 UCLocalize("USER"), UCLocalize("USER_EX"),
8327 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8328 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8333 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8334 return section == 3 ? 44.0f : 0;
8337 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8338 return section == 3 ? container_ : nil;
8341 - (void) reloadData {
8344 [table_ reloadData];
8349 /* Stash Controller {{{ */
8350 @interface StashController : CyteViewController {
8351 _H<UIActivityIndicatorView> spinner_;
8352 _H<UILabel> status_;
8353 _H<UILabel> caption_;
8358 @implementation StashController
8361 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8362 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8364 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8365 CGRect spinrect = [spinner_ frame];
8366 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8367 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8368 [spinner_ setFrame:spinrect];
8369 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8370 [[self view] addSubview:spinner_];
8371 [spinner_ startAnimating];
8374 captrect.size.width = [[self view] frame].size.width;
8375 captrect.size.height = 40.0f;
8376 captrect.origin.x = 0;
8377 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8378 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8379 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8380 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8381 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8382 [caption_ setTextColor:[UIColor whiteColor]];
8383 [caption_ setBackgroundColor:[UIColor clearColor]];
8384 [caption_ setShadowColor:[UIColor blackColor]];
8385 [caption_ setTextAlignment:UITextAlignmentCenter];
8386 [[self view] addSubview:caption_];
8389 statusrect.size.width = [[self view] frame].size.width;
8390 statusrect.size.height = 30.0f;
8391 statusrect.origin.x = 0;
8392 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8393 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8394 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8395 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8396 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8397 [status_ setTextColor:[UIColor whiteColor]];
8398 [status_ setBackgroundColor:[UIColor clearColor]];
8399 [status_ setShadowColor:[UIColor blackColor]];
8400 [status_ setTextAlignment:UITextAlignmentCenter];
8401 [[self view] addSubview:status_];
8407 @interface CYURLCache : SDURLCache {
8412 @implementation CYURLCache
8414 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8417 else if ([event isEqualToString:@"no-cache"])
8419 else if ([event isEqualToString:@"store"])
8421 else if ([event isEqualToString:@"invalid"])
8423 else if ([event isEqualToString:@"memory"])
8425 else if ([event isEqualToString:@"disk"])
8427 else if ([event isEqualToString:@"miss"])
8430 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8436 @interface Cydia : UIApplication <
8437 ConfirmationControllerDelegate,
8440 UINavigationControllerDelegate,
8441 UITabBarControllerDelegate
8443 _H<UIWindow> window_;
8444 _H<CYTabBarController> tabbar_;
8445 _H<CydiaLoadingViewController> emulated_;
8447 _H<NSMutableArray> essential_;
8448 _H<NSMutableArray> broken_;
8450 Database *database_;
8452 _H<NSURL> starturl_;
8457 _H<StashController> stash_;
8466 @implementation Cydia
8468 - (void) beginUpdate {
8469 [tabbar_ beginUpdate];
8473 return [tabbar_ updating];
8477 if ([broken_ count] != 0) {
8478 int count = [broken_ count];
8480 UIAlertView *alert = [[[UIAlertView alloc]
8481 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8482 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8484 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8486 UCLocalize("TEMPORARY_IGNORE"),
8490 [alert setContext:@"fixhalf"];
8491 [alert setNumberOfRows:2];
8493 } else if (!Ignored_ && [essential_ count] != 0) {
8494 int count = [essential_ count];
8496 UIAlertView *alert = [[[UIAlertView alloc]
8497 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8498 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8500 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8502 UCLocalize("UPGRADE_ESSENTIAL"),
8503 UCLocalize("COMPLETE_UPGRADE"),
8507 [alert setContext:@"upgrade"];
8512 - (void) _saveConfig {
8518 NSString *error(nil);
8520 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8522 NSError *error(nil);
8523 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8524 NSLog(@"failure to save metadata data: %@", error);
8529 NSLog(@"failure to serialize metadata: %@", error);
8534 // Navigation controller for the queuing badge.
8535 - (UINavigationController *) queueNavigationController {
8536 NSArray *controllers = [tabbar_ viewControllers];
8537 return [controllers objectAtIndex:3];
8540 - (void) unloadData {
8541 [tabbar_ unloadData];
8544 - (void) _updateData {
8549 UINavigationController *navigation = [self queueNavigationController];
8551 id queuedelegate = nil;
8552 if ([[navigation viewControllers] count] > 0)
8553 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8555 [queuedelegate queueStatusDidChange];
8556 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8559 - (void) _refreshIfPossible:(NSDate *)update {
8560 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8562 bool recently = false;
8563 if (update != nil) {
8564 NSTimeInterval interval([update timeIntervalSinceNow]);
8565 if (interval <= 0 && interval > -(15*60))
8569 // Don't automatic refresh if:
8570 // - We already refreshed recently.
8571 // - We already auto-refreshed this launch.
8572 // - Auto-refresh is disabled.
8573 if (recently || loaded_ || ManualRefresh) {
8574 // If we are cancelling, we need to make sure it knows it's already loaded.
8577 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8579 // We are going to load, so remember that.
8582 SCNetworkReachabilityFlags flags; {
8583 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8584 SCNetworkReachabilityGetFlags(reachability, &flags);
8585 CFRelease(reachability);
8588 // XXX: this elaborate mess is what Apple is using to determine this? :(
8589 // XXX: do we care if the user has to intervene? maybe that's ok?
8591 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8592 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8593 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8594 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8595 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8596 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8600 // If we can reach the server, auto-refresh!
8602 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8608 - (void) refreshIfPossible {
8609 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8612 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8613 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8614 [hud setText:UCLocalize("RELOADING_DATA")];
8616 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8619 [self removeProgressHUD:hud];
8623 [essential_ removeAllObjects];
8624 [broken_ removeAllObjects];
8626 NSArray *packages([database_ packages]);
8627 for (Package *package in packages) {
8629 [broken_ addObject:package];
8630 if ([package upgradableAndEssential:NO]) {
8631 if ([package essential])
8632 [essential_ addObject:package];
8637 NSLog(@"changes:#%u", changes);
8639 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8642 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8643 [changesItem setBadgeValue:badge];
8644 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8645 [self setApplicationIconBadgeNumber:changes];
8648 [changesItem setBadgeValue:nil];
8649 [changesItem setAnimatedBadge:NO];
8650 [self setApplicationIconBadgeNumber:0];
8655 [self refreshIfPossible];
8658 - (void) updateData {
8667 @synchronized (self) {
8668 [self _reloadDataWithInvocation:nil];
8672 - (void) disemulate {
8673 if (emulated_ == nil)
8676 [window_ addSubview:[tabbar_ view]];
8677 [[emulated_ view] removeFromSuperview];
8679 [window_ setUserInteractionEnabled:YES];
8682 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8683 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8685 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8687 UIViewController *parent;
8688 if (emulated_ == nil)
8697 [parent presentModalViewController:navigation animated:YES];
8700 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8701 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8703 if (navigation != nil)
8704 [navigation pushViewController:progress animated:YES];
8706 [self presentModalViewController:progress force:YES];
8708 [progress invoke:invocation withTitle:title];
8712 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8713 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8716 - (void) repairWithInvocation:(NSInvocation *)invocation {
8718 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8722 - (void) repairWithSelector:(SEL)selector {
8723 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8729 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8730 _assert(file != NULL);
8732 for (NSString *key in [Sources_ allKeys]) {
8733 NSDictionary *source([Sources_ objectForKey:key]);
8735 fprintf(file, "%s %s %s\n",
8736 [[source objectForKey:@"Type"] UTF8String],
8737 [[source objectForKey:@"URI"] UTF8String],
8738 [[source objectForKey:@"Distribution"] UTF8String]
8744 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8749 - (void) addTrivialSource:(NSString *)href {
8750 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8753 @"./", @"Distribution",
8754 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8759 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8760 @synchronized (self) {
8761 [self _reloadDataWithInvocation:invocation];
8765 - (void) reloadData {
8766 [self reloadDataWithInvocation:nil];
8770 pkgProblemResolver *resolver = [database_ resolver];
8772 resolver->InstallProtect();
8773 if (!resolver->Resolve(true))
8778 // XXX: this is a really crappy way of doing this.
8779 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8780 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8781 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8782 if ([tabbar_ updating])
8783 [tabbar_ cancelUpdate];
8785 if (![database_ prepare])
8788 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8789 [page setDelegate:self];
8790 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8793 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8794 [tabbar_ presentModalViewController:confirm_ animated:YES];
8800 @synchronized (self) {
8805 - (void) clearPackage:(Package *)package {
8806 @synchronized (self) {
8813 - (void) installPackages:(NSArray *)packages {
8814 @synchronized (self) {
8815 for (Package *package in packages)
8822 - (void) installPackage:(Package *)package {
8823 @synchronized (self) {
8830 - (void) removePackage:(Package *)package {
8831 @synchronized (self) {
8838 - (void) distUpgrade {
8839 @synchronized (self) {
8840 if (![database_ upgrade])
8846 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8849 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8854 - (void) showSettings {
8855 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8858 - (void) retainNetworkActivityIndicator {
8859 if (activity_++ == 0)
8860 [self setNetworkActivityIndicatorVisible:YES];
8863 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8867 - (void) releaseNetworkActivityIndicator {
8868 if (--activity_ == 0)
8869 [self setNetworkActivityIndicatorVisible:NO];
8872 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8877 - (void) cancelAndClear:(bool)clear {
8878 @synchronized (self) {
8890 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8891 NSString *context([alert context]);
8893 if ([context isEqualToString:@"conffile"]) {
8894 FILE *input = [database_ input];
8895 if (button == [alert cancelButtonIndex])
8896 fprintf(input, "N\n");
8897 else if (button == [alert firstOtherButtonIndex])
8898 fprintf(input, "Y\n");
8901 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8902 } else if ([context isEqualToString:@"fixhalf"]) {
8903 if (button == [alert cancelButtonIndex]) {
8904 @synchronized (self) {
8905 for (Package *broken in (id) broken_) {
8908 NSString *id = [broken id];
8909 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8910 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8911 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8912 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8918 } else if (button == [alert firstOtherButtonIndex]) {
8919 [broken_ removeAllObjects];
8923 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8924 } else if ([context isEqualToString:@"upgrade"]) {
8925 if (button == [alert firstOtherButtonIndex]) {
8926 @synchronized (self) {
8927 for (Package *essential in (id) essential_)
8928 [essential install];
8933 } else if (button == [alert firstOtherButtonIndex] + 1) {
8935 } else if (button == [alert cancelButtonIndex]) {
8939 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8943 - (void) system:(NSString *)command {
8944 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8947 system([command UTF8String]);
8953 - (void) applicationWillSuspend {
8955 [super applicationWillSuspend];
8958 - (BOOL) isSafeToSuspend {
8961 NSLog(@"isSafeToSuspend: locked_ != 0");
8966 // Use external process status API internally.
8967 // This is probably a really bad idea.
8968 // XXX: what is the point of this? does this solve anything at all?
8969 uint64_t status = 0;
8971 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8972 notify_get_state(notify_token, &status);
8973 notify_cancel(notify_token);
8978 NSLog(@"isSafeToSuspend: status != 0");
8984 NSLog(@"isSafeToSuspend: -> true");
8989 - (void) applicationSuspend:(__GSEvent *)event {
8990 if ([self isSafeToSuspend])
8991 [super applicationSuspend:event];
8994 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8995 if ([self isSafeToSuspend])
8996 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8999 - (void) _setSuspended:(BOOL)value {
9000 if ([self isSafeToSuspend])
9001 [super _setSuspended:value];
9004 - (UIProgressHUD *) addProgressHUD {
9005 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9006 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9008 [window_ setUserInteractionEnabled:NO];
9010 UIViewController *target(tabbar_);
9011 if (UIViewController *modal = [target modalViewController])
9014 UIView *view([target view]);
9015 [view addSubview:hud];
9023 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9026 [hud removeFromSuperview];
9027 [window_ setUserInteractionEnabled:YES];
9030 - (CyteViewController *) pageForPackage:(NSString *)name {
9031 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9034 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9035 NSString *scheme([[url scheme] lowercaseString]);
9036 if ([[url absoluteString] length] <= [scheme length] + 3)
9038 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9039 NSArray *components([path pathComponents]);
9041 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9042 return [self pageForPackage:[components objectAtIndex:1]];
9044 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9047 NSString *base([components objectAtIndex:0]);
9049 CyteViewController *controller = nil;
9051 if ([base isEqualToString:@"url"]) {
9052 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9053 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9054 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9055 } else if (!external && [components count] == 1) {
9056 if ([base isEqualToString:@"manage"]) {
9057 controller = [[[ManageController alloc] init] autorelease];
9060 if ([base isEqualToString:@"sources"]) {
9061 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9064 if ([base isEqualToString:@"home"]) {
9065 controller = [[[HomeController alloc] init] autorelease];
9068 if ([base isEqualToString:@"sections"]) {
9069 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9072 if ([base isEqualToString:@"search"]) {
9073 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9076 if ([base isEqualToString:@"changes"]) {
9077 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9080 if ([base isEqualToString:@"installed"]) {
9081 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9083 } else if ([components count] == 2) {
9084 NSString *argument = [components objectAtIndex:1];
9086 if ([base isEqualToString:@"package"]) {
9087 controller = [self pageForPackage:argument];
9090 if (!external && [base isEqualToString:@"search"]) {
9091 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9094 if (!external && [base isEqualToString:@"sections"]) {
9095 if ([argument isEqualToString:@"all"])
9097 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9100 if (!external && [base isEqualToString:@"sources"]) {
9101 if ([argument isEqualToString:@"add"]) {
9102 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9103 [(SourcesController *)controller showAddSourcePrompt];
9105 Source *source = [database_ sourceWithKey:argument];
9106 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9110 if (!external && [base isEqualToString:@"launch"]) {
9111 [self launchApplicationWithIdentifier:argument suspended:NO];
9114 } else if (!external && [components count] == 3) {
9115 NSString *arg1 = [components objectAtIndex:1];
9116 NSString *arg2 = [components objectAtIndex:2];
9118 if ([base isEqualToString:@"package"]) {
9119 if ([arg2 isEqualToString:@"settings"]) {
9120 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9121 } else if ([arg2 isEqualToString:@"files"]) {
9122 if (Package *package = [database_ packageWithName:arg1]) {
9123 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9124 [(FileTable *)controller setPackage:package];
9130 [controller setDelegate:self];
9134 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9135 CyteViewController *page([self pageForURL:url forExternal:external]);
9138 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9139 [nav setViewControllers:[NSArray arrayWithObject:page]];
9140 [tabbar_ setUnselectedViewController:nav];
9146 - (void) applicationOpenURL:(NSURL *)url {
9147 [super applicationOpenURL:url];
9152 [self openCydiaURL:url forExternal:YES];
9155 - (void) applicationWillResignActive:(UIApplication *)application {
9156 // Stop refreshing if you get a phone call or lock the device.
9157 if ([tabbar_ updating])
9158 [tabbar_ cancelUpdate];
9160 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9161 [super applicationWillResignActive:application];
9164 - (void) applicationWillTerminate:(UIApplication *)application {
9166 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9167 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9168 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9173 - (void) setConfigurationData:(NSString *)data {
9174 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9176 if (!conffile_r(data)) {
9177 lprintf("E:invalid conffile\n");
9181 NSString *ofile = conffile_r[1];
9182 //NSString *nfile = conffile_r[2];
9184 UIAlertView *alert = [[[UIAlertView alloc]
9185 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9186 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9188 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9190 UCLocalize("ACCEPT_NEW_COPY"),
9191 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9195 [alert setContext:@"conffile"];
9196 [alert setNumberOfRows:2];
9200 - (void) addStashController {
9202 stash_ = [[[StashController alloc] init] autorelease];
9203 [window_ addSubview:[stash_ view]];
9206 - (void) removeStashController {
9207 [[stash_ view] removeFromSuperview];
9213 [self setIdleTimerDisabled:YES];
9215 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9216 UpdateExternalStatus(1);
9217 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9218 UpdateExternalStatus(0);
9220 [self removeStashController];
9222 if (ExecFork() == 0) {
9223 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9224 perror("launchctl stop");
9228 - (void) setupViewControllers {
9229 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9231 NSMutableArray *items([NSMutableArray arrayWithObjects:
9232 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9233 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9234 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9235 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9239 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9240 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9242 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9245 NSMutableArray *controllers([NSMutableArray array]);
9246 for (UITabBarItem *item in items) {
9247 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9248 [controller setTabBarItem:item];
9249 [controllers addObject:controller];
9251 [tabbar_ setViewControllers:controllers];
9253 [tabbar_ setUpdateDelegate:self];
9256 - (void) applicationDidFinishLaunching:(id)unused {
9258 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9259 [self setApplicationSupportsShakeToEdit:NO];
9261 @synchronized (HostConfig_) {
9262 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9265 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9266 initWithMemoryCapacity:524288
9267 diskCapacity:10485760
9268 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9271 [CydiaWebViewController _initialize];
9273 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9275 // this would disallow http{,s} URLs from accessing this data
9276 //[WebView registerURLSchemeAsLocal:@"cydia"];
9278 Font12_ = [UIFont systemFontOfSize:12];
9279 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9280 Font14_ = [UIFont systemFontOfSize:14];
9281 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9282 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9284 essential_ = [NSMutableArray arrayWithCapacity:4];
9285 broken_ = [NSMutableArray arrayWithCapacity:4];
9287 // XXX: I really need this thing... like, seriously... I'm sorry
9288 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9290 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9291 [window_ orderFront:self];
9292 [window_ makeKey:self];
9293 [window_ setHidden:NO];
9296 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9297 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9298 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9299 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9300 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9301 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9302 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9303 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9304 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9307 [self addStashController];
9308 // XXX: this would be much cleaner as a yieldToSelector:
9309 // that way the removeStashController could happen right here inline
9310 // we also could no longer require the useless stash_ field anymore
9311 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9315 database_ = [Database sharedInstance];
9316 [database_ setDelegate:self];
9318 [window_ setUserInteractionEnabled:NO];
9319 [self setupViewControllers];
9321 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9322 [window_ addSubview:[emulated_ view]];
9324 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9328 - (NSArray *) defaultStartPages {
9329 NSMutableArray *standard = [NSMutableArray array];
9330 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9331 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9332 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9334 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9336 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9337 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9339 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9346 [window_ setUserInteractionEnabled:YES];
9347 [self showSettings];
9350 if ([emulated_ modalViewController] != nil)
9351 [emulated_ dismissModalViewControllerAnimated:YES];
9352 [window_ setUserInteractionEnabled:NO];
9360 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9361 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9362 int standardIndex = 0;
9363 NSArray *standard = [self defaultStartPages];
9370 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9371 if (valid && closed != nil) {
9372 NSTimeInterval interval([closed timeIntervalSinceNow]);
9373 // XXX: Is 15 minutes the optimal time here?
9374 if (interval > 0 && interval <= -(15*60))
9378 if (valid && [saved count] != [standard count])
9382 for (unsigned int i = 0; i < [standard count]; i++) {
9383 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9384 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9385 // but it's good enough for now.
9386 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9393 NSArray *items = nil;
9395 [tabbar_ setSelectedIndex:savedIndex];
9398 [tabbar_ setSelectedIndex:standardIndex];
9402 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9403 NSArray *stack = [items objectAtIndex:tab];
9404 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9405 NSMutableArray *current = [NSMutableArray array];
9407 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9408 NSString *addr = [stack objectAtIndex:nav];
9409 NSURL *url = [NSURL URLWithString:addr];
9410 CyteViewController *page = [self pageForURL:url forExternal:NO];
9412 [current addObject:page];
9415 [navigation setViewControllers:current];
9418 // (Try to) show the startup URL.
9419 if (starturl_ != nil) {
9420 [self openCydiaURL:starturl_ forExternal:NO];
9425 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9426 if (item != nil && IsWildcat_) {
9427 [sheet showFromBarButtonItem:item animated:YES];
9429 [sheet showInView:window_];
9433 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9434 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9435 [progress setTitle:task];
9436 [progress addProgressEvent:event];
9439 - (void) addProgressEventForTask:(NSArray *)data {
9440 CydiaProgressEvent *event([data objectAtIndex:0]);
9441 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9442 [self addProgressEvent:event forTask:task];
9445 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9446 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9452 id Alloc_(id self, SEL selector) {
9453 id object = alloc_(self, selector);
9454 lprintf("[%s]A-%p\n", self->isa->name, object);
9459 id Dealloc_(id self, SEL selector) {
9460 id object = dealloc_(self, selector);
9461 lprintf("[%s]D-%p\n", self->isa->name, object);
9465 Class $WebDefaultUIKitDelegate;
9467 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9468 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9469 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9470 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9473 static NSSet *MobilizedFiles_;
9475 static NSURL *MobilizeURL(NSURL *url) {
9476 NSString *path([url path]);
9477 if ([path hasPrefix:@"/var/root/"]) {
9478 NSString *file([path substringFromIndex:10]);
9479 if ([MobilizedFiles_ containsObject:file])
9480 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9486 Class $CFXPreferencesPropertyListSource;
9487 @class CFXPreferencesPropertyListSource;
9489 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9490 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9491 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9492 url = MobilizeURL(url);
9493 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9494 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9500 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9501 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9502 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9503 url = MobilizeURL(url);
9504 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9505 //NSLog(@"%@ %@", [url absoluteString], value);
9511 Class $NSURLConnection;
9513 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9514 NSMutableURLRequest *copy([request mutableCopy]);
9516 NSURL *url([copy URL]);
9517 NSString *host([url host]);
9518 NSString *scheme([[url scheme] lowercaseString]);
9520 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9522 @synchronized (HostConfig_) {
9523 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9524 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9525 [copy setHTTPShouldUsePipelining:YES];
9528 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9532 int main(int argc, char *argv[]) {
9533 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9537 UpdateExternalStatus(0);
9539 if (Class $UIDevice = objc_getClass("UIDevice")) {
9540 UIDevice *device([$UIDevice currentDevice]);
9541 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9545 UIScreen *screen([UIScreen mainScreen]);
9546 if ([screen respondsToSelector:@selector(scale)])
9547 ScreenScale_ = [screen scale];
9551 UIDevice *device([UIDevice currentDevice]);
9552 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9555 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9556 if (idiom == UIUserInterfaceIdiomPhone)
9558 else if (idiom == UIUserInterfaceIdiomPad)
9561 NSLog(@"unknown UIUserInterfaceIdiom!");
9564 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9566 HostConfig_ = [[[NSObject alloc] init] autorelease];
9567 @synchronized (HostConfig_) {
9568 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9569 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9572 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9574 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9576 MobilizedFiles_ = [NSMutableSet setWithObjects:
9577 @"Library/Preferences/com.apple.Accessibility.plist",
9578 @"Library/Preferences/com.apple.preferences.sounds.plist",
9581 /* Library Hacks {{{ */
9582 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9584 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9586 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9587 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9588 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9589 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9592 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9593 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9594 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9595 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9598 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9599 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9600 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9601 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9602 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9605 $NSURLConnection = objc_getClass("NSURLConnection");
9606 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9607 if (NSURLConnection$init$ != NULL) {
9608 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9609 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9612 /* Set Locale {{{ */
9613 Locale_ = CFLocaleCopyCurrent();
9614 Languages_ = [NSLocale preferredLanguages];
9616 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9617 //NSLog(@"%@", [Languages_ description]);
9620 if (Locale_ != NULL)
9621 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9622 else if (Languages_ != nil && [Languages_ count] != 0)
9623 lang = [[Languages_ objectAtIndex:0] UTF8String];
9625 // XXX: consider just setting to C and then falling through?
9629 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9630 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9633 NSLog(@"Setting Language: %s", lang);
9636 setenv("LANG", lang, true);
9637 std::setlocale(LC_ALL, lang);
9641 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9643 /* Parse Arguments {{{ */
9644 bool substrate(false);
9650 for (int argi(1); argi != argc; ++argi)
9651 if (strcmp(argv[argi], "--") == 0) {
9653 argv[argi] = argv[0];
9659 for (int argi(1); argi != arge; ++argi)
9660 if (strcmp(args[argi], "--substrate") == 0)
9663 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9667 App_ = [[NSBundle mainBundle] bundlePath];
9673 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9674 alloc_ = alloc->method_imp;
9675 alloc->method_imp = (IMP) &Alloc_;*/
9677 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9678 dealloc_ = dealloc->method_imp;
9679 dealloc->method_imp = (IMP) &Dealloc_;*/
9681 /* System Information {{{ */
9685 size = sizeof(maxproc);
9686 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9687 perror("sysctlbyname(\"kern.maxproc\", ?)");
9688 else if (maxproc < 64) {
9690 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9691 perror("sysctlbyname(\"kern.maxproc\", #)");
9694 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9695 char *osversion = new char[size];
9696 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9697 perror("sysctlbyname(\"kern.osversion\", ?)");
9699 System_ = [NSString stringWithUTF8String:osversion];
9701 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9702 char *machine = new char[size];
9703 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9704 perror("sysctlbyname(\"hw.machine\", ?)");
9708 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9709 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9710 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9712 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9714 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9715 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9716 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9718 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9719 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9720 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9722 if (mcc != NULL && mnc != NULL)
9723 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9730 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9731 Build_ = [system objectForKey:@"ProductBuildVersion"];
9732 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9733 Product_ = [info objectForKey:@"SafariProductVersion"];
9734 Safari_ = [info objectForKey:@"CFBundleVersion"];
9737 /* Load Database {{{ */
9739 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9741 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9743 if (Metadata_ == NULL)
9744 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9746 Settings_ = [Metadata_ objectForKey:@"Settings"];
9748 Packages_ = [Metadata_ objectForKey:@"Packages"];
9749 Sections_ = [Metadata_ objectForKey:@"Sections"];
9750 Sources_ = [Metadata_ objectForKey:@"Sources"];
9752 Token_ = [Metadata_ objectForKey:@"Token"];
9755 if (Settings_ != nil)
9756 Role_ = [Settings_ objectForKey:@"Role"];
9758 if (Sections_ == nil) {
9759 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9760 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9763 if (Sources_ == nil) {
9764 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9765 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9770 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9773 if (Packages_ != nil) {
9775 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9779 [Metadata_ removeObjectForKey:@"Packages"];
9785 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9787 #define MobileSubstrate_(name) \
9788 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9789 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9790 if (handle == NULL) \
9791 NSLog(@"%s", dlerror()); \
9794 MobileSubstrate_(Activator)
9795 MobileSubstrate_(libstatusbar)
9796 MobileSubstrate_(SimulatedKeyEvents)
9797 MobileSubstrate_(WinterBoard)
9799 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9800 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9802 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9804 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9805 unlink("/tmp/.cydia.fw");
9807 } else if (access("/User", F_OK) != 0 || version < 4) {
9810 system("/usr/libexec/cydia/firmware.sh");
9814 _assert([[NSFileManager defaultManager]
9815 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9816 withIntermediateDirectories:YES
9821 if (access("/tmp/cydia.chk", F_OK) == 0) {
9822 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9823 _assert(errno == ENOENT);
9824 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9825 _assert(errno == ENOENT);
9828 /* APT Initialization {{{ */
9829 _assert(pkgInitConfig(*_config));
9830 _assert(pkgInitSystem(*_config, _system));
9833 _config->Set("APT::Acquire::Translation", lang);
9835 // XXX: this timeout might be important :(
9836 //_config->Set("Acquire::http::Timeout", 15);
9838 _config->Set("Acquire::http::MaxParallel", 3);
9840 /* Color Choices {{{ */
9841 space_ = CGColorSpaceCreateDeviceRGB();
9843 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9844 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9845 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9846 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9847 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9848 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9849 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9850 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9851 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9853 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9854 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9856 /* UIKit Configuration {{{ */
9857 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9858 if ($GSFontSetUseLegacyFontMetrics != NULL)
9859 $GSFontSetUseLegacyFontMetrics(YES);
9861 // XXX: I have a feeling this was important
9862 //UIKeyboardDisableAutomaticAppearance();
9865 Colon_ = UCLocalize("COLON_DELIMITED");
9866 Elision_ = UCLocalize("ELISION");
9867 Error_ = UCLocalize("ERROR");
9868 Warning_ = UCLocalize("WARNING");
9871 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9873 CGColorSpaceRelease(space_);