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;
1688 _transient Database *database_;
1690 pkgCache::VerIterator version_;
1691 pkgCache::PkgIterator iterator_;
1692 pkgCache::VerFileIterator file_;
1698 CYString installed_;
1700 const char *section_;
1701 _transient NSString *section$_;
1705 PackageValue *metadata_;
1706 ParsedPackage *parsed_;
1708 _H<NSMutableArray> tags_;
1711 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1712 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1714 - (pkgCache::PkgIterator) iterator;
1717 - (NSString *) section;
1718 - (NSString *) simpleSection;
1720 - (NSString *) longSection;
1721 - (NSString *) shortSection;
1725 - (MIMEAddress *) maintainer;
1727 - (NSString *) longDescription;
1728 - (NSString *) shortDescription;
1731 - (PackageValue *) metadata;
1734 - (bool) subscribed;
1735 - (bool) setSubscribed:(bool)subscribed;
1739 - (NSString *) latest;
1740 - (NSString *) installed;
1741 - (BOOL) uninstalled;
1744 - (BOOL) upgradableAndEssential:(BOOL)essential;
1747 - (BOOL) unfiltered;
1751 - (BOOL) halfConfigured;
1752 - (BOOL) halfInstalled;
1754 - (NSString *) mode;
1757 - (NSString *) name;
1759 - (NSString *) homepage;
1760 - (NSString *) depiction;
1761 - (MIMEAddress *) author;
1763 - (NSString *) support;
1765 - (NSArray *) files;
1766 - (NSArray *) warnings;
1767 - (NSArray *) applications;
1769 - (Source *) source;
1771 - (BOOL) matches:(NSString *)text;
1773 - (bool) hasSupportingRole;
1774 - (BOOL) hasTag:(NSString *)tag;
1775 - (NSString *) primaryPurpose;
1776 - (NSArray *) purposes;
1777 - (bool) isCommercial;
1779 - (void) setIndex:(size_t)index;
1781 - (CYString &) cyname;
1783 - (uint32_t) compareBySection:(NSArray *)sections;
1788 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1789 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1790 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1791 - (bool) isVisibleInSection:(NSString *)section;
1792 - (bool) isVisibleInSource:(Source *)source;
1796 uint32_t PackageChangesRadix(Package *self, void *) {
1801 uint32_t timestamp : 30;
1802 uint32_t ignored : 1;
1803 uint32_t upgradable : 1;
1807 bool upgradable([self upgradableAndEssential:YES]);
1808 value.bits.upgradable = upgradable ? 1 : 0;
1811 value.bits.timestamp = 0;
1812 value.bits.ignored = [self ignored] ? 0 : 1;
1813 value.bits.upgradable = 1;
1815 value.bits.timestamp = [self seen] >> 2;
1816 value.bits.ignored = 0;
1817 value.bits.upgradable = 0;
1820 return _not(uint32_t) - value.key;
1823 uint32_t PackagePrefixRadix(Package *self, void *context) {
1824 size_t offset(reinterpret_cast<size_t>(context));
1825 CYString &name([self cyname]);
1827 size_t size(name.size());
1830 char *text(name.data());
1833 if (!isdigit(text[0]))
1837 while (size != digits && isdigit(text[digits]))
1845 if (offset == 0 && zeros != 0) {
1846 memset(data, '0', zeros);
1847 memcpy(data + zeros, text, 4 - zeros);
1849 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1850 if (size <= offset - zeros)
1853 text += offset - zeros;
1854 size -= offset - zeros;
1857 memcpy(data, text, 4);
1859 memcpy(data, text, size);
1860 memset(data + size, 0, 4 - size);
1863 for (size_t i(0); i != 4; ++i)
1864 if (isalpha(data[i]))
1872 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1874 /* XXX: ntohl may be more honest */
1875 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1878 CYString &(*PackageName)(Package *self, SEL sel);
1880 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1881 _profile(PackageNameCompare)
1882 CYString &lhi(PackageName(lhs, @selector(cyname)));
1883 CYString &rhi(PackageName(rhs, @selector(cyname)));
1884 CFStringRef lhn(lhi), rhn(rhi);
1887 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1888 else if (rhn == NULL)
1889 return NSOrderedDescending;
1891 _profile(PackageNameCompare$NumbersLast)
1892 if (!lhi.empty() && !rhi.empty()) {
1893 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1894 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1895 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1896 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1897 return lha ? NSOrderedAscending : NSOrderedDescending;
1901 CFIndex length = CFStringGetLength(lhn);
1903 _profile(PackageNameCompare$Compare)
1904 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1909 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1910 return PackageNameCompare(*lhs, *rhs, context);
1913 struct PackageNameOrdering :
1914 std::binary_function<Package *, Package *, bool>
1916 _finline bool operator ()(Package *lhs, Package *rhs) const {
1917 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1921 @implementation Package
1923 - (NSString *) description {
1924 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1928 if (parsed_ != NULL)
1933 + (NSString *) webScriptNameForSelector:(SEL)selector {
1935 else if (selector == @selector(clear))
1937 else if (selector == @selector(getField:))
1939 else if (selector == @selector(hasTag:))
1941 else if (selector == @selector(install))
1943 else if (selector == @selector(remove))
1949 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1950 return [self webScriptNameForSelector:selector] == nil;
1953 + (NSArray *) _attributeKeys {
1954 return [NSArray arrayWithObjects:
1973 @"shortDescription",
1986 - (NSArray *) attributeKeys {
1987 return [[self class] _attributeKeys];
1990 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1991 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1994 - (NSArray *) relations {
1995 @synchronized (database_) {
1996 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
1997 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
1998 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2002 - (NSString *) getField:(NSString *)name {
2003 @synchronized (database_) {
2004 if ([database_ era] != era_ || file_.end())
2007 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2009 const char *start, *end;
2010 if (!parser.Find([name UTF8String], start, end))
2011 return (NSString *) [NSNull null];
2013 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2017 if (parsed_ != NULL)
2019 @synchronized (database_) {
2020 if ([database_ era] != era_ || file_.end())
2023 ParsedPackage *parsed(new ParsedPackage);
2026 _profile(Package$parse)
2027 pkgRecords::Parser *parser;
2029 _profile(Package$parse$Lookup)
2030 parser = &[database_ records]->Lookup(file_);
2035 _profile(Package$parse$Find)
2040 {"icon", &parsed->icon_},
2041 {"depiction", &parsed->depiction_},
2042 {"homepage", &parsed->homepage_},
2043 {"website", &website},
2044 {"bugs", &parsed->bugs_},
2045 {"support", &parsed->support_},
2046 {"sponsor", &parsed->sponsor_},
2047 {"author", &parsed->author_},
2050 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2051 const char *start, *end;
2053 if (parser->Find(names[i].name_, start, end)) {
2054 CYString &value(*names[i].value_);
2055 _profile(Package$parse$Value)
2056 value.set(pool_, start, end - start);
2062 _profile(Package$parse$Tagline)
2063 const char *start, *end;
2064 if (parser->ShortDesc(start, end)) {
2065 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2068 while (stop != start && stop[-1] == '\r')
2070 parsed->tagline_.set(pool_, start, stop - start);
2074 _profile(Package$parse$Retain)
2075 if (parsed->homepage_.empty())
2076 parsed->homepage_ = website;
2077 if (parsed->homepage_ == parsed->depiction_)
2078 parsed->homepage_.clear();
2083 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2084 if ((self = [super init]) != nil) {
2085 _profile(Package$initWithVersion)
2088 database_ = database;
2089 era_ = [database era];
2093 pkgCache::PkgIterator iterator(version.ParentPkg());
2094 iterator_ = iterator;
2096 _profile(Package$initWithVersion$Version)
2097 if (!version_.end())
2098 file_ = version_.FileList();
2100 pkgCache &cache([database_ cache]);
2101 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2105 _profile(Package$initWithVersion$Cache)
2106 name_.set(NULL, iterator.Display());
2108 latest_.set(NULL, StripVersion_(version_.VerStr()));
2110 pkgCache::VerIterator current(iterator.CurrentVer());
2112 installed_.set(NULL, StripVersion_(current.VerStr()));
2115 _profile(Package$initWithVersion$Tags)
2116 pkgCache::TagIterator tag(iterator.TagList());
2118 tags_ = [NSMutableArray arrayWithCapacity:8];
2120 const char *name(tag.Name());
2121 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2123 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2124 if (strcmp(name + 6, "enduser") == 0)
2126 else if (strcmp(name + 6, "hacker") == 0)
2128 else if (strcmp(name + 6, "developer") == 0)
2130 else if (strcmp(name + 6, "cydia") == 0)
2136 if (strncmp(name, "cydia::", 7) == 0) {
2137 if (strcmp(name + 7, "essential") == 0)
2139 else if (strcmp(name + 7, "obsolete") == 0)
2144 } while (!tag.end());
2148 _profile(Package$initWithVersion$Metadata)
2149 const char *mixed(iterator.Name());
2150 size_t size(strlen(mixed));
2151 char lower[size + 1];
2153 for (size_t i(0); i != size; ++i)
2154 lower[i] = mixed[i] | 0x20;
2157 PackageValue *metadata(PackageFind(lower, size));
2158 metadata_ = metadata;
2160 id_.set(NULL, metadata->name_, size);
2162 const char *latest(version_.VerStr());
2163 size_t length(strlen(latest));
2165 uint16_t vhash(hashlittle(latest, length));
2167 size_t capped(std::min<size_t>(8, length));
2168 latest = latest + length - capped;
2170 if (metadata->first_ == 0)
2171 metadata->first_ = now_;
2173 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2174 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2175 metadata->vhash_ = vhash;
2176 metadata->last_ = now_;
2177 } else if (metadata->last_ == 0)
2178 metadata->last_ = metadata->first_;
2181 _profile(Package$initWithVersion$Section)
2182 section_ = iterator.Section();
2185 _profile(Package$initWithVersion$Flags)
2186 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2187 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2192 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2193 pkgCache::VerIterator version;
2195 _profile(Package$packageWithIterator$GetCandidateVer)
2196 version = [database policy]->GetCandidateVer(iterator);
2204 _profile(Package$packageWithIterator$Allocate)
2205 package = [Package allocWithZone:zone];
2208 _profile(Package$packageWithIterator$Initialize)
2210 initWithVersion:version
2217 _profile(Package$packageWithIterator$Autorelease)
2218 package = [package autorelease];
2224 - (pkgCache::PkgIterator) iterator {
2228 - (NSString *) section {
2229 if (section$_ == nil) {
2230 if (section_ == NULL)
2233 _profile(Package$section$mappedSectionForPointer)
2234 section$_ = [database_ mappedSectionForPointer:section_];
2239 - (NSString *) simpleSection {
2240 if (NSString *section = [self section])
2241 return Simplify(section);
2246 - (NSString *) longSection {
2247 return LocalizeSection([self section]);
2250 - (NSString *) shortSection {
2251 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2254 - (NSString *) uri {
2257 pkgIndexFile *index;
2258 pkgCache::PkgFileIterator file(file_.File());
2259 if (![database_ list].FindIndex(file, index))
2261 return [NSString stringWithUTF8String:iterator_->Path];
2262 //return [NSString stringWithUTF8String:file.Site()];
2263 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2267 - (MIMEAddress *) maintainer {
2268 @synchronized (database_) {
2269 if ([database_ era] != era_ || file_.end())
2272 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2273 const std::string &maintainer(parser->Maintainer());
2274 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2278 @synchronized (database_) {
2279 if ([database_ era] != era_ || version_.end())
2282 return version_->InstalledSize;
2285 - (NSString *) longDescription {
2286 @synchronized (database_) {
2287 if ([database_ era] != era_ || file_.end())
2290 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2291 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2293 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2294 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2295 if ([lines count] < 2)
2298 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2299 for (size_t i(1), e([lines count]); i != e; ++i) {
2300 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2301 [trimmed addObject:trim];
2304 return [trimmed componentsJoinedByString:@"\n"];
2307 - (NSString *) shortDescription {
2308 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2312 _profile(Package$index)
2313 CFStringRef name((CFStringRef) [self name]);
2314 if (CFStringGetLength(name) == 0)
2316 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2317 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2319 return toupper(character);
2323 - (PackageValue *) metadata {
2328 PackageValue *metadata([self metadata]);
2329 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2332 - (bool) subscribed {
2333 return [self metadata]->subscribed_;
2336 - (bool) setSubscribed:(bool)subscribed {
2337 PackageValue *metadata([self metadata]);
2338 if (metadata->subscribed_ == subscribed)
2340 metadata->subscribed_ = subscribed;
2348 - (NSString *) latest {
2352 - (NSString *) installed {
2356 - (BOOL) uninstalled {
2357 return installed_.empty();
2361 return !version_.end();
2364 - (BOOL) upgradableAndEssential:(BOOL)essential {
2365 _profile(Package$upgradableAndEssential)
2366 pkgCache::VerIterator current(iterator_.CurrentVer());
2368 return essential && essential_;
2370 return !version_.end() && version_ != current;
2374 - (BOOL) essential {
2379 return [database_ cache][iterator_].InstBroken();
2382 - (BOOL) unfiltered {
2383 _profile(Package$unfiltered$obsolete)
2384 if (_unlikely(obsolete_))
2388 _profile(Package$unfiltered$hasSupportingRole)
2389 if (_unlikely(![self hasSupportingRole]))
2397 if (![self unfiltered])
2402 _profile(Package$visible$section)
2403 section = [self section];
2406 _profile(Package$visible$isSectionVisible)
2407 if (!isSectionVisible(section))
2415 unsigned char current(iterator_->CurrentState);
2416 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2419 - (BOOL) halfConfigured {
2420 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2423 - (BOOL) halfInstalled {
2424 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2428 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2429 return state.Mode != pkgDepCache::ModeKeep;
2432 - (NSString *) mode {
2433 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2435 switch (state.Mode) {
2436 case pkgDepCache::ModeDelete:
2437 if ((state.iFlags & pkgDepCache::Purge) != 0)
2441 case pkgDepCache::ModeKeep:
2442 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2443 return @"REINSTALL";
2444 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2448 case pkgDepCache::ModeInstall:
2449 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2450 return @"REINSTALL";
2451 else*/ switch (state.Status) {
2453 return @"DOWNGRADE";
2459 return @"NEW_INSTALL";
2470 - (NSString *) name {
2471 return name_.empty() ? id_ : name_;
2474 - (UIImage *) icon {
2475 NSString *section = [self simpleSection];
2478 if (parsed_ != NULL)
2479 if (NSString *href = parsed_->icon_)
2480 if ([href hasPrefix:@"file:///"])
2481 // XXX: correct escaping
2482 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2483 if (icon == nil) if (section != nil)
2484 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2485 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2486 if ([dicon hasPrefix:@"file:///"])
2487 // XXX: correct escaping
2488 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2490 icon = [UIImage applicationImageNamed:@"unknown.png"];
2494 - (NSString *) homepage {
2495 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2498 - (NSString *) depiction {
2499 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2502 - (MIMEAddress *) sponsor {
2503 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2506 - (MIMEAddress *) author {
2507 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2510 - (NSString *) support {
2511 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2514 - (NSArray *) files {
2515 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2516 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2519 fin.open([path UTF8String]);
2524 while (std::getline(fin, line))
2525 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2530 - (NSString *) state {
2531 @synchronized (database_) {
2532 if ([database_ era] != era_ || file_.end())
2535 switch (iterator_->CurrentState) {
2536 case pkgCache::State::NotInstalled:
2537 return @"NotInstalled";
2538 case pkgCache::State::UnPacked:
2540 case pkgCache::State::HalfConfigured:
2541 return @"HalfConfigured";
2542 case pkgCache::State::HalfInstalled:
2543 return @"HalfInstalled";
2544 case pkgCache::State::ConfigFiles:
2545 return @"ConfigFiles";
2546 case pkgCache::State::Installed:
2547 return @"Installed";
2548 case pkgCache::State::TriggersAwaited:
2549 return @"TriggersAwaited";
2550 case pkgCache::State::TriggersPending:
2551 return @"TriggersPending";
2554 return (NSString *) [NSNull null];
2557 - (NSString *) selection {
2558 @synchronized (database_) {
2559 if ([database_ era] != era_ || file_.end())
2562 switch (iterator_->SelectedState) {
2563 case pkgCache::State::Unknown:
2565 case pkgCache::State::Install:
2567 case pkgCache::State::Hold:
2569 case pkgCache::State::DeInstall:
2570 return @"DeInstall";
2571 case pkgCache::State::Purge:
2575 return (NSString *) [NSNull null];
2578 - (NSArray *) warnings {
2579 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2580 const char *name(iterator_.Name());
2582 size_t length(strlen(name));
2583 if (length < 2) invalid:
2584 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2585 else for (size_t i(0); i != length; ++i)
2587 /* XXX: technically this is not allowed */
2588 (name[i] < 'A' || name[i] > 'Z') &&
2589 (name[i] < 'a' || name[i] > 'z') &&
2590 (name[i] < '0' || name[i] > '9') &&
2591 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2594 if (strcmp(name, "cydia") != 0) {
2597 bool _private = false;
2600 bool repository = [[self section] isEqualToString:@"Repositories"];
2602 if (NSArray *files = [self files])
2603 for (NSString *file in files)
2604 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2606 else if (!user && [file isEqualToString:@"/User"])
2608 else if (!_private && [file isEqualToString:@"/private"])
2610 else if (!stash && [file isEqualToString:@"/var/stash"])
2613 /* XXX: this is not sensitive enough. only some folders are valid. */
2614 if (cydia && !repository)
2615 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2617 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2619 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2621 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2624 return [warnings count] == 0 ? nil : warnings;
2627 - (NSArray *) applications {
2628 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2630 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2632 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2633 if (NSArray *files = [self files])
2634 for (NSString *file in files)
2635 if (application_r(file)) {
2636 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2637 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2638 if ([id isEqualToString:me])
2641 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2643 display = application_r[1];
2645 NSString *bundle([file stringByDeletingLastPathComponent]);
2646 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2647 if (icon == nil || [icon length] == 0)
2649 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2651 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2652 [applications addObject:application];
2654 [application addObject:id];
2655 [application addObject:display];
2656 [application addObject:url];
2659 return [applications count] == 0 ? nil : applications;
2662 - (Source *) source {
2663 if (source_ == nil) {
2664 @synchronized (database_) {
2665 if ([database_ era] != era_ || file_.end())
2666 source_ = (Source *) [NSNull null];
2668 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2672 return source_ == (Source *) [NSNull null] ? nil : source_;
2675 - (BOOL) matches:(NSString *)text {
2681 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2682 if (range.location != NSNotFound)
2685 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2686 if (range.location != NSNotFound)
2691 NSString *description([self shortDescription]);
2692 NSUInteger length([description length]);
2694 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2695 if (range.location != NSNotFound)
2701 - (bool) hasSupportingRole {
2706 if ([Role_ isEqualToString:@"User"])
2710 if ([Role_ isEqualToString:@"Hacker"])
2714 if ([Role_ isEqualToString:@"Developer"])
2719 - (NSArray *) tags {
2723 - (BOOL) hasTag:(NSString *)tag {
2724 return tags_ == nil ? NO : [tags_ containsObject:tag];
2727 - (NSString *) primaryPurpose {
2728 for (NSString *tag in (NSArray *) tags_)
2729 if ([tag hasPrefix:@"purpose::"])
2730 return [tag substringFromIndex:9];
2734 - (NSArray *) purposes {
2735 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2736 for (NSString *tag in (NSArray *) tags_)
2737 if ([tag hasPrefix:@"purpose::"])
2738 [purposes addObject:[tag substringFromIndex:9]];
2739 return [purposes count] == 0 ? nil : purposes;
2742 - (bool) isCommercial {
2743 return [self hasTag:@"cydia::commercial"];
2746 - (void) setIndex:(size_t)index {
2747 if (metadata_->index_ != index)
2748 metadata_->index_ = index;
2751 - (CYString &) cyname {
2752 return name_.empty() ? id_ : name_;
2755 - (uint32_t) compareBySection:(NSArray *)sections {
2756 NSString *section([self section]);
2757 for (size_t i(0), e([sections count]); i != e; ++i) {
2758 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2762 return _not(uint32_t);
2766 @synchronized (database_) {
2767 pkgProblemResolver *resolver = [database_ resolver];
2768 resolver->Clear(iterator_);
2770 pkgCacheFile &cache([database_ cache]);
2771 cache->SetReInstall(iterator_, false);
2772 cache->MarkKeep(iterator_, false);
2776 @synchronized (database_) {
2777 pkgProblemResolver *resolver = [database_ resolver];
2778 resolver->Clear(iterator_);
2779 resolver->Protect(iterator_);
2781 pkgCacheFile &cache([database_ cache]);
2782 cache->SetReInstall(iterator_, false);
2783 cache->MarkInstall(iterator_, false);
2785 pkgDepCache::StateCache &state((*cache)[iterator_]);
2786 if (!state.Install())
2787 cache->SetReInstall(iterator_, true);
2791 @synchronized (database_) {
2792 pkgProblemResolver *resolver = [database_ resolver];
2793 resolver->Clear(iterator_);
2794 resolver->Remove(iterator_);
2795 resolver->Protect(iterator_);
2797 pkgCacheFile &cache([database_ cache]);
2798 cache->SetReInstall(iterator_, false);
2799 cache->MarkDelete(iterator_, true);
2802 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2803 _profile(Package$isUnfilteredAndSearchedForBy)
2806 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2807 value &= [self unfiltered];
2810 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2811 value &= [self matches:search];
2818 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2819 if ([search length] == 0)
2822 _profile(Package$isUnfilteredAndSelectedForBy)
2825 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2826 value &= [self unfiltered];
2829 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2830 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2837 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2838 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2841 - (bool) isVisibleInSection:(NSString *)name {
2842 NSString *section([self section]);
2846 section == nil && [name length] == 0 ||
2847 [name isEqualToString:section]
2848 ) && [self visible];
2851 - (bool) isVisibleInSource:(Source *)source {
2852 return [self source] == source && [self visible];
2857 /* Section Class {{{ */
2858 @interface Section : NSObject {
2863 _H<NSString> localized_;
2866 - (NSComparisonResult) compareByLocalized:(Section *)section;
2867 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2868 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2869 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2870 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2871 - (NSString *) name;
2878 - (void) addToCount;
2880 - (void) setCount:(size_t)count;
2881 - (NSString *) localized;
2885 @implementation Section
2887 - (NSComparisonResult) compareByLocalized:(Section *)section {
2888 NSString *lhs(localized_);
2889 NSString *rhs([section localized]);
2891 /*if ([lhs length] != 0 && [rhs length] != 0) {
2892 unichar lhc = [lhs characterAtIndex:0];
2893 unichar rhc = [rhs characterAtIndex:0];
2895 if (isalpha(lhc) && !isalpha(rhc))
2896 return NSOrderedAscending;
2897 else if (!isalpha(lhc) && isalpha(rhc))
2898 return NSOrderedDescending;
2901 return [lhs compare:rhs options:LaxCompareOptions_];
2904 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2905 if ((self = [self initWithName:name localize:NO]) != nil) {
2906 if (localized != nil)
2907 localized_ = localized;
2911 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2912 return [self initWithName:name row:0 localize:localize];
2915 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2916 if ((self = [super init]) != nil) {
2921 localized_ = LocalizeSection(name_);
2925 /* XXX: localize the index thingees */
2926 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2927 if ((self = [super init]) != nil) {
2928 name_ = [NSString stringWithCharacters:&index length:1];
2934 - (NSString *) name {
2954 - (void) addToCount {
2958 - (void) setCount:(size_t)count {
2962 - (NSString *) localized {
2969 static NSString *Colon_;
2971 static NSString *Error_;
2972 static NSString *Warning_;
2974 class CydiaLogCleaner :
2975 public pkgArchiveCleaner
2978 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
2983 /* Database Implementation {{{ */
2984 @implementation Database
2986 + (Database *) sharedInstance {
2987 static _H<Database> instance;
2988 if (instance == nil)
2989 instance = [[[Database alloc] init] autorelease];
2997 - (void) releasePackages {
2998 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
2999 CFArrayRemoveAllValues(packages_);
3003 // XXX: actually implement this thing
3005 [self releasePackages];
3006 apr_pool_destroy(pool_);
3007 NSRecycleZone(zone_);
3011 - (void) _readCydia:(NSNumber *)fd {
3012 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3013 std::istream is(&ib);
3016 static Pcre finish_r("^finish:([^:]*)$");
3018 while (std::getline(is, line)) {
3019 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3021 const char *data(line.c_str());
3022 size_t size = line.size();
3023 lprintf("C:%s\n", data);
3025 if (finish_r(data, size)) {
3026 NSString *finish = finish_r[1];
3027 int index = [Finishes_ indexOfObject:finish];
3028 if (index != INT_MAX && index > Finish_)
3038 - (void) _readStatus:(NSNumber *)fd {
3039 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3040 std::istream is(&ib);
3043 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3044 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3046 while (std::getline(is, line)) {
3047 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3049 const char *data(line.c_str());
3050 size_t size(line.size());
3051 lprintf("S:%s\n", data);
3053 if (conffile_r(data, size)) {
3054 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3055 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3056 } else if (strncmp(data, "status: ", 8) == 0) {
3057 // status: <package>: {unpacked,half-configured,installed}
3058 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3059 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3060 } else if (strncmp(data, "processing: ", 12) == 0) {
3061 // processing: configure: config-test
3062 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3063 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3064 } else if (pmstatus_r(data, size)) {
3065 std::string type([pmstatus_r[1] UTF8String]);
3067 NSString *package = pmstatus_r[2];
3068 if ([package isEqualToString:@"dpkg-exec"])
3071 float percent([pmstatus_r[3] floatValue]);
3072 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3074 NSString *string = pmstatus_r[4];
3076 if (type == "pmerror") {
3077 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3078 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3079 } else if (type == "pmstatus") {
3080 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3081 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3082 } else if (type == "pmconffile")
3083 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3085 lprintf("E:unknown pmstatus\n");
3087 lprintf("E:unknown status\n");
3095 - (void) _readOutput:(NSNumber *)fd {
3096 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3097 std::istream is(&ib);
3100 while (std::getline(is, line)) {
3101 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3103 lprintf("O:%s\n", line.c_str());
3105 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3106 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3118 - (Package *) packageWithName:(NSString *)name {
3119 @synchronized (self) {
3120 if (static_cast<pkgDepCache *>(cache_) == NULL)
3122 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3123 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3127 if ((self = [super init]) != nil) {
3134 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3135 apr_pool_create(&pool_, NULL);
3137 size_t capacity(MetaFile_->active_);
3143 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3144 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3148 _assert(pipe(fds) != -1);
3151 _config->Set("APT::Keep-Fds::", cydiafd_);
3152 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3155 detachNewThreadSelector:@selector(_readCydia:)
3157 withObject:[NSNumber numberWithInt:fds[0]]
3160 _assert(pipe(fds) != -1);
3164 detachNewThreadSelector:@selector(_readStatus:)
3166 withObject:[NSNumber numberWithInt:fds[0]]
3169 _assert(pipe(fds) != -1);
3170 _assert(dup2(fds[0], 0) != -1);
3171 _assert(close(fds[0]) != -1);
3173 input_ = fdopen(fds[1], "a");
3175 _assert(pipe(fds) != -1);
3176 _assert(dup2(fds[1], 1) != -1);
3177 _assert(close(fds[1]) != -1);
3180 detachNewThreadSelector:@selector(_readOutput:)
3182 withObject:[NSNumber numberWithInt:fds[0]]
3187 - (pkgCacheFile &) cache {
3191 - (pkgDepCache::Policy *) policy {
3195 - (pkgRecords *) records {
3199 - (pkgProblemResolver *) resolver {
3203 - (pkgAcquire &) fetcher {
3207 - (pkgSourceList &) list {
3211 - (NSArray *) packages {
3212 return (NSArray *) packages_;
3215 - (NSArray *) sources {
3219 - (Source *) sourceWithKey:(NSString *)key {
3220 for (Source *source in [self sources]) {
3221 if ([[source key] isEqualToString:key])
3226 - (bool) popErrorWithTitle:(NSString *)title {
3229 while (!_error->empty()) {
3231 bool warning(!_error->PopMessage(error));
3236 size_t size(error.size());
3237 if (size == 0 || error[size - 1] != '\n')
3239 error.resize(size - 1);
3242 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3244 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3250 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3251 return [self popErrorWithTitle:title] || !success;
3254 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3255 @synchronized (self) {
3258 [self releasePackages];
3261 [sourceList_ removeAllObjects];
3281 apr_pool_clear(pool_);
3283 NSRecycleZone(zone_);
3284 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3286 int chk(creat("/tmp/cydia.chk", 0644));
3290 if (invocation != nil)
3291 [invocation invoke];
3293 NSString *title(UCLocalize("DATABASE"));
3296 OpProgress progress;
3297 while (!cache_.Open(progress, true)) { pop:
3299 bool warning(!_error->PopMessage(error));
3300 lprintf("cache_.Open():[%s]\n", error.c_str());
3302 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3303 [delegate_ repairWithSelector:@selector(configure)];
3304 else if (error == "The package lists or status file could not be parsed or opened.")
3305 [delegate_ repairWithSelector:@selector(update)];
3306 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3307 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3308 // else if (error == "Malformed Status line")
3309 // else if (error == "The list of sources could not be read.")
3311 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3321 unlink("/tmp/cydia.chk");
3323 now_ = [[NSDate date] timeIntervalSince1970];
3325 policy_ = new pkgDepCache::Policy();
3326 records_ = new pkgRecords(cache_);
3327 resolver_ = new pkgProblemResolver(cache_);
3328 fetcher_ = new pkgAcquire(&status_);
3331 list_ = new pkgSourceList();
3332 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3335 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3336 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3340 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3343 if (cache_->BrokenCount() != 0) {
3344 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3347 if (cache_->BrokenCount() != 0) {
3348 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3352 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3356 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3357 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3358 [sourceList_ addObject:object];
3360 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3361 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3362 // XXX: this could be more intelligent
3363 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3364 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3366 sourceMap_[cached->ID] = object;
3371 /*std::vector<Package *> packages;
3372 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3377 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3378 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3379 //packages.push_back(package);
3380 CFArrayAppendValue(packages_, CFRetain(package));
3384 /*if (packages.empty())
3385 packages_ = [[NSArray alloc] init];
3387 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3390 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3391 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3392 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3400 /*if (!packages.empty())
3401 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3402 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3404 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3406 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3408 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3412 size_t count(CFArrayGetCount(packages_));
3413 MetaFile_->active_ = count;
3415 for (size_t index(0); index != count; ++index)
3416 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3423 @synchronized (self) {
3425 resolver_ = new pkgProblemResolver(cache_);
3427 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3428 if (!cache_[iterator].Keep())
3429 cache_->MarkKeep(iterator, false);
3430 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3431 cache_->SetReInstall(iterator, false);
3434 - (void) configure {
3435 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3437 system([dpkg UTF8String]);
3442 // XXX: I don't remember this condition
3447 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3449 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3451 if ([self popErrorWithTitle:title])
3455 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3457 CydiaLogCleaner cleaner;
3458 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3465 fetcher_->Shutdown();
3467 pkgRecords records(cache_);
3469 lock_ = new FileFd();
3470 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3472 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3474 if ([self popErrorWithTitle:title])
3478 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3481 manager_ = (_system->CreatePM(cache_));
3482 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3489 bool substrate(RestartSubstrate_);
3490 RestartSubstrate_ = false;
3492 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3494 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3496 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3498 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3499 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3502 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3504 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3506 [self popErrorWithTitle:title];
3510 bool failed = false;
3511 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3512 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3514 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3520 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3528 RestartSubstrate_ = true;
3531 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3533 if (_error->PendingError()) {
3538 if (result == pkgPackageManager::Failed) {
3543 if (result != pkgPackageManager::Completed) {
3548 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3550 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3552 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3553 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3556 if (![before isEqualToArray:after])
3561 NSString *title(UCLocalize("UPGRADE"));
3562 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3568 [self updateWithStatus:status_];
3571 - (void) updateWithStatus:(Status &)status {
3572 NSString *title(UCLocalize("REFRESHING_DATA"));
3575 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3579 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3580 if ([self popErrorWithTitle:title])
3583 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3585 bool success(ListUpdate(status, list, PulseInterval_));
3586 if (status.WasCancelled())
3589 [self popErrorWithTitle:title forOperation:success];
3590 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3594 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3597 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3598 delegate_ = delegate;
3601 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3602 progress_ = delegate;
3603 status_.setDelegate(delegate);
3606 - (NSObject<ProgressDelegate> *) progressDelegate {
3610 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3611 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3612 return i == sourceMap_.end() ? nil : i->second;
3615 - (NSString *) mappedSectionForPointer:(const char *)section {
3616 _H<NSString> *mapped;
3618 _profile(Database$mappedSectionForPointer$Cache)
3619 mapped = §ions_[section];
3622 if (*mapped == NULL) {
3623 size_t length(strlen(section));
3624 char spaced[length + 1];
3626 _profile(Database$mappedSectionForPointer$Replace)
3627 for (size_t index(0); index != length; ++index)
3628 spaced[index] = section[index] == '_' ? ' ' : section[index];
3629 spaced[length] = '\0';
3634 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3635 string = [NSString stringWithUTF8String:spaced];
3638 _profile(Database$mappedSectionForPointer$Map)
3639 string = [SectionMap_ objectForKey:string] ?: string;
3649 static _H<NSMutableSet> Diversions_;
3651 @interface Diversion : NSObject {
3654 _H<NSString> format_;
3659 @implementation Diversion
3661 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3662 if ((self = [super init]) != nil) {
3663 pattern_ = [from UTF8String];
3669 - (NSString *) divert:(NSString *)url {
3670 return !pattern_(url) ? nil : pattern_->*format_;
3673 + (NSURL *) divertURL:(NSURL *)url {
3675 NSString *href([url absoluteString]);
3677 for (Diversion *diversion in (id) Diversions_)
3678 if (NSString *diverted = [diversion divert:href]) {
3680 NSLog(@"div: %@", diverted);
3682 url = [NSURL URLWithString:diverted];
3689 - (NSString *) key {
3693 - (NSUInteger) hash {
3697 - (BOOL) isEqual:(Diversion *)object {
3698 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3703 @interface CydiaObject : NSObject {
3704 _H<IndirectDelegate> indirect_;
3705 _transient id delegate_;
3708 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3712 @interface CydiaWebViewController : CyteWebViewController {
3713 _H<CydiaObject> cydia_;
3716 + (void) addDiversion:(Diversion *)diversion;
3720 /* Web Scripting {{{ */
3721 @implementation CydiaObject
3723 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3724 if ((self = [super init]) != nil) {
3725 indirect_ = indirect;
3729 - (void) setDelegate:(id)delegate {
3730 delegate_ = delegate;
3733 + (NSArray *) _attributeKeys {
3734 return [NSArray arrayWithObjects:
3750 - (NSArray *) attributeKeys {
3751 return [[self class] _attributeKeys];
3754 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3755 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3758 - (NSString *) version {
3762 - (NSString *) device {
3763 return [[UIDevice currentDevice] uniqueIdentifier];
3766 - (NSString *) firmware {
3767 return [[UIDevice currentDevice] systemVersion];
3770 - (NSString *) hostname {
3771 return [[UIDevice currentDevice] name];
3774 - (NSString *) idiom {
3775 return (id) Idiom_ ?: [NSNull null];
3778 - (NSString *) plmn {
3779 return (id) PLMN_ ?: [NSNull null];
3782 - (NSString *) bbsnum {
3783 return (id) BBSNum_ ?: [NSNull null];
3786 - (NSString *) ecid {
3787 return (id) ChipID_ ?: [NSNull null];
3790 - (NSString *) serial {
3791 return SerialNumber_;
3794 - (NSString *) role {
3795 return (id) Role_ ?: [NSNull null];
3798 - (NSString *) model {
3799 return [NSString stringWithUTF8String:Machine_];
3802 - (NSString *) token {
3803 return (id) Token_ ?: [NSNull null];
3806 + (NSString *) webScriptNameForSelector:(SEL)selector {
3808 else if (selector == @selector(addBridgedHost:))
3809 return @"addBridgedHost";
3810 else if (selector == @selector(addInternalRedirect::))
3811 return @"addInternalRedirect";
3812 else if (selector == @selector(addPipelinedHost:scheme:))
3813 return @"addPipelinedHost";
3814 else if (selector == @selector(addTrivialSource:))
3815 return @"addTrivialSource";
3816 else if (selector == @selector(close))
3818 else if (selector == @selector(du:))
3820 else if (selector == @selector(stringWithFormat:arguments:))
3822 else if (selector == @selector(getAllSources))
3823 return @"getAllSourcs";
3824 else if (selector == @selector(getKernelNumber:))
3825 return @"getKernelNumber";
3826 else if (selector == @selector(getKernelString:))
3827 return @"getKernelString";
3828 else if (selector == @selector(getInstalledPackages))
3829 return @"getInstalledPackages";
3830 else if (selector == @selector(getIORegistryEntry::))
3831 return @"getIORegistryEntry";
3832 else if (selector == @selector(getLocaleIdentifier))
3833 return @"getLocaleIdentifier";
3834 else if (selector == @selector(getPreferredLanguages))
3835 return @"getPreferredLanguages";
3836 else if (selector == @selector(getPackageById:))
3837 return @"getPackageById";
3838 else if (selector == @selector(getSessionValue:))
3839 return @"getSessionValue";
3840 else if (selector == @selector(installPackages:))
3841 return @"installPackages";
3842 else if (selector == @selector(localizedStringForKey:value:table:))
3844 else if (selector == @selector(popViewController:))
3845 return @"popViewController";
3846 else if (selector == @selector(refreshSources))
3847 return @"refreshSources";
3848 else if (selector == @selector(removeButton))
3849 return @"removeButton";
3850 else if (selector == @selector(setSessionValue::))
3851 return @"setSessionValue";
3852 else if (selector == @selector(substitutePackageNames:))
3853 return @"substitutePackageNames";
3854 else if (selector == @selector(scrollToBottom:))
3855 return @"scrollToBottom";
3856 else if (selector == @selector(setAllowsNavigationAction:))
3857 return @"setAllowsNavigationAction";
3858 else if (selector == @selector(setBadgeValue:))
3859 return @"setBadgeValue";
3860 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3861 return @"setButtonImage";
3862 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3863 return @"setButtonTitle";
3864 else if (selector == @selector(setHidesBackButton:))
3865 return @"setHidesBackButton";
3866 else if (selector == @selector(setHidesNavigationBar:))
3867 return @"setHidesNavigationBar";
3868 else if (selector == @selector(setNavigationBarStyle:))
3869 return @"setNavigationBarStyle";
3870 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3871 return @"setNavigationBarTintColor";
3872 else if (selector == @selector(setPasteboardString:))
3873 return @"setPasteboardString";
3874 else if (selector == @selector(setPasteboardURL:))
3875 return @"setPasteboardURL";
3876 else if (selector == @selector(setToken:))
3878 else if (selector == @selector(setViewportWidth:))
3879 return @"setViewportWidth";
3880 else if (selector == @selector(statfs:))
3882 else if (selector == @selector(supports:))
3888 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3889 return [self webScriptNameForSelector:selector] == nil;
3892 - (BOOL) supports:(NSString *)feature {
3893 return [feature isEqualToString:@"window.open"];
3896 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3897 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3900 - (NSNumber *) getKernelNumber:(NSString *)name {
3901 const char *string([name UTF8String]);
3904 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3905 return (id) [NSNull null];
3907 if (size != sizeof(int))
3908 return (id) [NSNull null];
3911 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3912 return (id) [NSNull null];
3914 return [NSNumber numberWithInt:value];
3917 - (NSString *) getKernelString:(NSString *)name {
3918 const char *string([name UTF8String]);
3921 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3922 return (id) [NSNull null];
3924 char value[size + 1];
3925 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3926 return (id) [NSNull null];
3928 // XXX: just in case you request something ludicrous
3931 return [NSString stringWithCString:value];
3934 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3935 NSObject *value(CYIOGetValue([path UTF8String], entry));
3938 if ([value isKindOfClass:[NSData class]])
3939 value = CYHex((NSData *) value);
3944 - (id) getSessionValue:(NSString *)key {
3945 @synchronized (SessionData_) {
3946 return [SessionData_ objectForKey:key];
3949 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3950 @synchronized (SessionData_) {
3951 if (value == (id) [WebUndefined undefined])
3952 [SessionData_ removeObjectForKey:key];
3954 [SessionData_ setObject:value forKey:key];
3957 - (void) addBridgedHost:(NSString *)host {
3958 @synchronized (HostConfig_) {
3959 [BridgedHosts_ addObject:host];
3962 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
3963 @synchronized (HostConfig_) {
3964 if (scheme != (id) [WebUndefined undefined])
3965 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
3967 [PipelinedHosts_ addObject:host];
3970 - (void) popViewController:(NSNumber *)value {
3971 if (value == (id) [WebUndefined undefined])
3972 value = [NSNumber numberWithBool:YES];
3973 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
3976 - (void) addTrivialSource:(NSString *)href {
3977 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3980 - (void) refreshSources {
3981 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3984 - (NSArray *) getAllSources {
3985 return [[Database sharedInstance] sources];
3988 - (NSArray *) getInstalledPackages {
3989 Database *database([Database sharedInstance]);
3990 @synchronized (database) {
3991 NSArray *packages([database packages]);
3992 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3993 for (Package *package in packages)
3994 if (![package uninstalled])
3995 [installed addObject:package];
3999 - (Package *) getPackageById:(NSString *)id {
4000 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4004 return (Package *) [NSNull null];
4007 - (NSString *) getLocaleIdentifier {
4008 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4011 - (NSArray *) getPreferredLanguages {
4015 - (NSArray *) statfs:(NSString *)path {
4018 if (path == nil || statfs([path UTF8String], &stat) == -1)
4021 return [NSArray arrayWithObjects:
4022 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4023 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4024 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4028 - (NSNumber *) du:(NSString *)path {
4029 NSNumber *value(nil);
4032 _assert(pipe(fds) != -1);
4034 pid_t pid(ExecFork());
4036 _assert(dup2(fds[1], 1) != -1);
4037 _assert(close(fds[0]) != -1);
4038 _assert(close(fds[1]) != -1);
4039 /* XXX: this should probably not use du */
4040 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4045 _assert(close(fds[1]) != -1);
4047 if (FILE *du = fdopen(fds[0], "r")) {
4049 while (fgets(line, sizeof(line), du) != NULL) {
4050 size_t length(strlen(line));
4051 while (length != 0 && line[length - 1] == '\n')
4052 line[--length] = '\0';
4053 if (char *tab = strchr(line, '\t')) {
4055 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4060 } else _assert(close(fds[0]));
4064 if (waitpid(pid, &status, 0) == -1)
4067 else _assert(false);
4073 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4076 - (void) installPackages:(NSArray *)packages {
4077 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4080 - (NSString *) substitutePackageNames:(NSString *)message {
4081 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4082 for (size_t i(0), e([words count]); i != e; ++i) {
4083 NSString *word([words objectAtIndex:i]);
4084 if (Package *package = [[Database sharedInstance] packageWithName:word])
4085 [words replaceObjectAtIndex:i withObject:[package name]];
4088 return [words componentsJoinedByString:@" "];
4091 - (void) removeButton {
4092 [indirect_ removeButton];
4095 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4096 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4099 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4100 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4103 - (void) setBadgeValue:(id)value {
4104 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4107 - (void) setAllowsNavigationAction:(NSString *)value {
4108 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4111 - (void) setHidesBackButton:(NSString *)value {
4112 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4115 - (void) setHidesNavigationBar:(NSString *)value {
4116 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4119 - (void) setNavigationBarStyle:(NSString *)value {
4120 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4123 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4124 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4125 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4126 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4129 - (void) setPasteboardString:(NSString *)value {
4130 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4133 - (void) setPasteboardURL:(NSString *)value {
4134 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4137 - (void) _setToken:(NSString *)token {
4141 [Metadata_ removeObjectForKey:@"Token"];
4143 [Metadata_ setObject:Token_ forKey:@"Token"];
4148 - (void) setToken:(NSString *)token {
4149 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4152 - (void) scrollToBottom:(NSNumber *)animated {
4153 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4156 - (void) setViewportWidth:(float)width {
4157 [indirect_ setViewportWidthOnMainThread:width];
4160 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4161 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4162 unsigned count([arguments count]);
4164 for (unsigned i(0); i != count; ++i)
4165 values[i] = [arguments objectAtIndex:i];
4166 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4169 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4170 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4172 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4174 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4181 /* Cydia Browser Controller {{{ */
4182 @implementation CydiaWebViewController
4184 - (NSURL *) navigationURL {
4185 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4188 + (void) initialize {
4189 Diversions_ = [NSMutableSet setWithCapacity:0];
4192 + (void) addDiversion:(Diversion *)diversion {
4193 [Diversions_ addObject:diversion];
4196 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4197 [super webView:view didClearWindowObject:window forFrame:frame];
4199 WebDataSource *source([frame dataSource]);
4200 NSURLResponse *response([source response]);
4201 NSURL *url([response URL]);
4202 NSString *scheme([[url scheme] lowercaseString]);
4204 bool bridged(false);
4206 @synchronized (HostConfig_) {
4207 if ([scheme isEqualToString:@"file"])
4209 else if ([scheme isEqualToString:@"https"])
4210 if ([BridgedHosts_ containsObject:[url host]])
4215 [window setValue:cydia_ forKey:@"cydia"];
4218 - (NSURL *) URLWithURL:(NSURL *)url {
4219 return [Diversion divertURL:url];
4222 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4223 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4225 if (System_ != NULL)
4226 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4227 if (Machine_ != NULL)
4228 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4230 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4235 - (void) setDelegate:(id)delegate {
4236 [super setDelegate:delegate];
4237 [cydia_ setDelegate:delegate];
4241 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4242 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4244 WebView *webview([[webview_ _documentView] webView]);
4246 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4249 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4251 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4252 if (Product_ != nil)
4253 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4255 [webview setApplicationNameForUserAgent:application];
4263 @interface NSObject (CydiaScript)
4264 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4267 @implementation NSObject (CydiaScript)
4269 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4275 @implementation NSArray (CydiaScript)
4277 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4278 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4279 for (size_t i(0), e([self count]); i != e; ++i)
4280 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4286 @implementation NSDictionary (CydiaScript)
4288 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4289 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4291 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4298 /* Confirmation Controller {{{ */
4299 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4300 if (!iterator.end())
4301 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4302 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4304 pkgCache::PkgIterator package(dep.TargetPkg());
4307 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4314 @protocol ConfirmationControllerDelegate
4315 - (void) cancelAndClear:(bool)clear;
4316 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4320 @interface ConfirmationController : CydiaWebViewController {
4321 _transient Database *database_;
4323 _H<UIAlertView> essential_;
4325 _H<NSDictionary> changes_;
4326 _H<NSMutableArray> issues_;
4327 _H<NSDictionary> sizes_;
4332 - (id) initWithDatabase:(Database *)database;
4336 @implementation ConfirmationController
4340 RestartSubstrate_ = true;
4341 [delegate_ confirmWithNavigationController:[self navigationController]];
4344 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4345 NSString *context([alert context]);
4347 if ([context isEqualToString:@"remove"]) {
4348 if (button == [alert cancelButtonIndex])
4349 [self dismissModalViewControllerAnimated:YES];
4350 else if (button == [alert firstOtherButtonIndex]) {
4354 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4355 } else if ([context isEqualToString:@"unable"]) {
4356 [self dismissModalViewControllerAnimated:YES];
4357 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4359 [super alertView:alert clickedButtonAtIndex:button];
4363 - (void) _doContinue {
4364 [self dismissModalViewControllerAnimated:YES];
4365 [delegate_ cancelAndClear:NO];
4368 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4369 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4373 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4374 [super webView:view didClearWindowObject:window forFrame:frame];
4376 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4377 (id) changes_, @"changes",
4378 (id) issues_, @"issues",
4379 (id) sizes_, @"sizes",
4381 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4384 - (id) initWithDatabase:(Database *)database {
4385 if ((self = [super init]) != nil) {
4386 database_ = database;
4388 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4389 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4390 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4391 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4392 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4396 pkgCacheFile &cache([database_ cache]);
4397 NSArray *packages([database_ packages]);
4398 pkgDepCache::Policy *policy([database_ policy]);
4400 issues_ = [NSMutableArray arrayWithCapacity:4];
4402 for (Package *package in packages) {
4403 pkgCache::PkgIterator iterator([package iterator]);
4404 NSString *name([package id]);
4406 if ([package broken]) {
4407 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4409 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4411 reasons, @"reasons",
4414 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4418 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4419 pkgCache::DepIterator start;
4420 pkgCache::DepIterator end;
4421 dep.GlobOr(start, end); // ++dep
4423 if (!cache->IsImportantDep(end))
4425 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4428 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4430 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4431 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4432 clauses, @"clauses",
4436 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4438 pkgCache::PkgIterator target(start.TargetPkg());
4439 if (target->ProvidesList != 0)
4440 reason = @"missing";
4442 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4444 reason = @"installed";
4445 installed = [NSString stringWithUTF8String:ver.VerStr()];
4446 } else if (!cache[target].CandidateVerIter(cache).end())
4447 reason = @"uninstalled";
4448 else if (target->ProvidesList == 0)
4449 reason = @"uninstallable";
4451 reason = @"virtual";
4454 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4455 [NSString stringWithUTF8String:start.CompType()], @"operator",
4456 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4459 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4460 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4461 version, @"version",
4463 installed, @"installed",
4466 // yes, seriously. (wtf?)
4474 pkgDepCache::StateCache &state(cache[iterator]);
4476 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4478 if (state.NewInstall())
4479 [installs addObject:name];
4480 // XXX: else if (state.Install())
4481 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4482 [reinstalls addObject:name];
4483 // XXX: move before previous if
4484 else if (state.Upgrade())
4485 [upgrades addObject:name];
4486 else if (state.Downgrade())
4487 [downgrades addObject:name];
4488 else if (!state.Delete())
4489 // XXX: _assert(state.Keep());
4491 else if (special_r(name))
4492 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4493 [NSNull null], @"package",
4494 [NSArray arrayWithObjects:
4495 [NSDictionary dictionaryWithObjectsAndKeys:
4496 @"Conflicts", @"relationship",
4497 [NSArray arrayWithObjects:
4498 [NSDictionary dictionaryWithObjectsAndKeys:
4500 [NSNull null], @"version",
4501 @"installed", @"reason",
4508 if ([package essential])
4510 [removes addObject:name];
4513 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4514 substrate_ |= DepSubstrate(iterator.CurrentVer());
4519 else if (Advanced_) {
4520 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4522 essential_ = [[[UIAlertView alloc]
4523 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4524 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4526 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4528 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4532 [essential_ setContext:@"remove"];
4534 essential_ = [[[UIAlertView alloc]
4535 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4536 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4538 cancelButtonTitle:UCLocalize("OKAY")
4539 otherButtonTitles:nil
4542 [essential_ setContext:@"unable"];
4545 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4546 installs, @"installs",
4547 reinstalls, @"reinstalls",
4548 upgrades, @"upgrades",
4549 downgrades, @"downgrades",
4550 removes, @"removes",
4553 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4554 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4555 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4558 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4562 - (UIBarButtonItem *) leftButton {
4563 return [[[UIBarButtonItem alloc]
4564 initWithTitle:UCLocalize("CANCEL")
4565 style:UIBarButtonItemStylePlain
4567 action:@selector(cancelButtonClicked)
4572 - (void) applyRightButton {
4573 if ([issues_ count] == 0 && ![self isLoading])
4574 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4575 initWithTitle:UCLocalize("CONFIRM")
4576 style:UIBarButtonItemStyleDone
4578 action:@selector(confirmButtonClicked)
4581 [[self navigationItem] setRightBarButtonItem:nil];
4585 - (void) cancelButtonClicked {
4586 [self dismissModalViewControllerAnimated:YES];
4587 [delegate_ cancelAndClear:YES];
4591 - (void) confirmButtonClicked {
4592 if (essential_ != nil)
4602 /* Progress Data {{{ */
4603 @interface CydiaProgressData : NSObject {
4604 _transient id delegate_;
4613 _H<NSMutableArray> events_;
4614 _H<NSString> title_;
4616 _H<NSString> status_;
4617 _H<NSString> finish_;
4622 @implementation CydiaProgressData
4624 + (NSArray *) _attributeKeys {
4625 return [NSArray arrayWithObjects:
4637 - (NSArray *) attributeKeys {
4638 return [[self class] _attributeKeys];
4641 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4642 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4646 if ((self = [super init]) != nil) {
4647 events_ = [NSMutableArray arrayWithCapacity:32];
4651 - (void) setDelegate:(id)delegate {
4652 delegate_ = delegate;
4655 - (void) setPercent:(float)value {
4659 - (NSNumber *) percent {
4660 return [NSNumber numberWithFloat:percent_];
4663 - (void) setCurrent:(float)value {
4667 - (NSNumber *) current {
4668 return [NSNumber numberWithFloat:current_];
4671 - (void) setTotal:(float)value {
4675 - (NSNumber *) total {
4676 return [NSNumber numberWithFloat:total_];
4679 - (void) setSpeed:(float)value {
4683 - (NSNumber *) speed {
4684 return [NSNumber numberWithFloat:speed_];
4687 - (NSArray *) events {
4691 - (void) removeAllEvents {
4692 [events_ removeAllObjects];
4695 - (void) addEvent:(CydiaProgressEvent *)event {
4696 [events_ addObject:event];
4699 - (void) setTitle:(NSString *)text {
4703 - (NSString *) title {
4707 - (void) setFinish:(NSString *)text {
4711 - (NSString *) finish {
4712 return (id) finish_ ?: [NSNull null];
4715 - (void) setRunning:(bool)running {
4719 - (NSNumber *) running {
4720 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4725 /* Progress Controller {{{ */
4726 @interface ProgressController : CydiaWebViewController <
4729 _transient Database *database_;
4730 _H<CydiaProgressData, 1> progress_;
4734 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4736 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4738 - (void) setTitle:(NSString *)title;
4739 - (void) setCancellable:(bool)cancellable;
4743 @implementation ProgressController
4746 [database_ setProgressDelegate:nil];
4750 - (UIBarButtonItem *) leftButton {
4751 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4752 initWithTitle:UCLocalize("CANCEL")
4753 style:UIBarButtonItemStylePlain
4755 action:@selector(cancel)
4756 ] autorelease] : nil;
4759 - (void) updateCancel {
4760 [super applyLeftButton];
4763 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4764 if ((self = [super init]) != nil) {
4765 database_ = database;
4766 delegate_ = delegate;
4768 [database_ setProgressDelegate:self];
4770 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4771 [progress_ setDelegate:self];
4773 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4775 [scroller_ setBackgroundColor:[UIColor blackColor]];
4777 [[self navigationItem] setHidesBackButton:YES];
4779 [self updateCancel];
4783 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4784 [super webView:view didClearWindowObject:window forFrame:frame];
4785 [window setValue:progress_ forKey:@"cydiaProgress"];
4788 - (void) updateProgress {
4789 [self dispatchEvent:@"CydiaProgressUpdate"];
4792 - (void) viewWillAppear:(BOOL)animated {
4793 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4794 [super viewWillAppear:animated];
4798 UpdateExternalStatus(0);
4805 [delegate_ terminateWithSuccess];
4806 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4807 [delegate_ suspendWithAnimation:YES];
4809 [delegate_ suspend];*/
4821 system("/usr/bin/sbreload");
4827 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4828 SBReboot(SBSSpringBoardServerPort());
4830 reboot2(RB_AUTOBOOT);
4837 - (void) setTitle:(NSString *)title {
4838 [progress_ setTitle:title];
4839 [self updateProgress];
4842 - (UIBarButtonItem *) rightButton {
4843 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4844 initWithTitle:UCLocalize("CLOSE")
4845 style:UIBarButtonItemStylePlain
4847 action:@selector(close)
4851 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4852 UpdateExternalStatus(1);
4854 [progress_ setRunning:true];
4855 [self setTitle:title];
4856 // implicit updateProgress
4858 SHA1SumValue notifyconf; {
4860 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4863 MMap mmap(file, MMap::ReadOnly);
4865 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4866 notifyconf = sha1.Result();
4870 SHA1SumValue springlist; {
4872 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4875 MMap mmap(file, MMap::ReadOnly);
4877 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4878 springlist = sha1.Result();
4882 if (invocation != nil) {
4883 [invocation yieldToSelector:@selector(invoke)];
4884 [self setTitle:@"COMPLETE"];
4889 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4892 MMap mmap(file, MMap::ReadOnly);
4894 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4895 if (!(notifyconf == sha1.Result()))
4902 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4905 MMap mmap(file, MMap::ReadOnly);
4907 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4908 if (!(springlist == sha1.Result()))
4914 if (RestartSubstrate_)
4918 RestartSubstrate_ = false;
4921 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4922 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
4923 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
4924 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4925 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
4929 system("su -c /usr/bin/uicache mobile");
4932 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
4934 [progress_ setRunning:false];
4935 [self updateProgress];
4937 [self applyRightButton];
4940 - (void) addProgressEvent:(CydiaProgressEvent *)event {
4941 [progress_ addEvent:event];
4942 [self updateProgress];
4945 - (bool) isProgressCancelled {
4946 return cancel_ == 2;
4951 [self updateCancel];
4954 - (void) setCancellable:(bool)cancellable {
4955 unsigned cancel(cancel_);
4959 else if (cancel_ == 0)
4962 if (cancel != cancel_)
4963 [self updateCancel];
4966 - (void) setProgressCancellable:(NSNumber *)cancellable {
4967 [self setCancellable:[cancellable boolValue]];
4970 - (void) setProgressPercent:(NSNumber *)percent {
4971 [progress_ setPercent:[percent floatValue]];
4972 [self updateProgress];
4975 - (void) setProgressStatus:(NSDictionary *)status {
4976 if (status == nil) {
4977 [progress_ setCurrent:0];
4978 [progress_ setTotal:0];
4979 [progress_ setSpeed:0];
4981 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
4983 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
4984 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
4985 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
4988 [self updateProgress];
4994 /* Package Cell {{{ */
4995 @interface PackageCell : CyteTableViewCell <
4996 CyteTableViewCellDelegate
5000 _H<NSString> description_;
5002 _H<NSString> source_;
5004 _H<Package> package_;
5005 _H<UIImage> placard_;
5009 - (PackageCell *) init;
5010 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5012 - (void) drawContentRect:(CGRect)rect;
5016 @implementation PackageCell
5018 - (PackageCell *) init {
5019 CGRect frame(CGRectMake(0, 0, 320, 74));
5020 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5021 UIView *content([self contentView]);
5022 CGRect bounds([content bounds]);
5024 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5025 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5026 [content addSubview:content_];
5028 [content_ setDelegate:self];
5029 [content_ setOpaque:YES];
5033 - (NSString *) accessibilityLabel {
5034 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5037 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5038 summarized_ = summary;
5050 Source *source = [package source];
5052 icon_ = [package icon];
5053 name_ = [package name];
5056 description_ = [package longDescription];
5057 if (description_ == nil)
5058 description_ = [package shortDescription];
5060 commercial_ = [package isCommercial];
5064 NSString *label = nil;
5065 bool trusted = false;
5067 if (source != nil) {
5068 label = [source label];
5069 trusted = [source trusted];
5070 } else if ([[package id] isEqualToString:@"firmware"])
5071 label = UCLocalize("APPLE");
5073 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5075 NSString *from(label);
5077 NSString *section = [package simpleSection];
5078 if (section != nil && ![section isEqualToString:label]) {
5079 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5080 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5083 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5085 if (NSString *purpose = [package primaryPurpose])
5086 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5091 if (NSString *mode = [package_ mode]) {
5092 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5093 color = RemovingColor_;
5094 //placard = @"removing";
5096 color = InstallingColor_;
5097 //placard = @"installing";
5100 // XXX: the removing/installing placards are not @2x
5103 color = [UIColor whiteColor];
5105 if ([package installed] != nil)
5106 placard = @"installed";
5111 [content_ setBackgroundColor:color];
5114 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5116 [self setNeedsDisplay];
5117 [content_ setNeedsDisplay];
5120 - (void) drawSummaryContentRect:(CGRect)rect {
5121 bool highlighted(highlighted_);
5122 float width([self bounds].size.width);
5126 rect.size = [(UIImage *) icon_ size];
5128 rect.size.width /= 4;
5129 rect.size.height /= 4;
5131 rect.origin.x = 14 - rect.size.width / 4;
5132 rect.origin.y = 14 - rect.size.height / 4;
5134 [icon_ drawInRect:rect];
5137 if (badge_ != nil) {
5139 rect.size = [(UIImage *) badge_ size];
5141 rect.size.width /= 4;
5142 rect.size.height /= 4;
5144 rect.origin.x = 20 - rect.size.width / 4;
5145 rect.origin.y = 20 - rect.size.height / 4;
5147 [badge_ drawInRect:rect];
5154 UISetColor(commercial_ ? Purple_ : Black_);
5155 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5157 if (placard_ != nil)
5158 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5161 - (void) drawNormalContentRect:(CGRect)rect {
5162 bool highlighted(highlighted_);
5163 float width([self bounds].size.width);
5167 rect.size = [(UIImage *) icon_ size];
5169 rect.size.width /= 2;
5170 rect.size.height /= 2;
5172 rect.origin.x = 25 - rect.size.width / 2;
5173 rect.origin.y = 25 - rect.size.height / 2;
5175 [icon_ drawInRect:rect];
5178 if (badge_ != nil) {
5180 rect.size = [(UIImage *) badge_ size];
5182 rect.size.width /= 2;
5183 rect.size.height /= 2;
5185 rect.origin.x = 36 - rect.size.width / 2;
5186 rect.origin.y = 36 - rect.size.height / 2;
5188 [badge_ drawInRect:rect];
5195 UISetColor(commercial_ ? Purple_ : Black_);
5196 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5197 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5200 UISetColor(commercial_ ? Purplish_ : Gray_);
5201 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5203 if (placard_ != nil)
5204 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5207 - (void) drawContentRect:(CGRect)rect {
5209 [self drawSummaryContentRect:rect];
5211 [self drawNormalContentRect:rect];
5216 /* Section Cell {{{ */
5217 @interface SectionCell : CyteTableViewCell <
5218 CyteTableViewCellDelegate
5220 _H<NSString> basic_;
5221 _H<NSString> section_;
5223 _H<NSString> count_;
5225 _H<UISwitch> switch_;
5229 - (void) setSection:(Section *)section editing:(BOOL)editing;
5233 @implementation SectionCell
5235 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5236 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5237 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5238 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5239 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5241 UIView *content([self contentView]);
5242 CGRect bounds([content bounds]);
5244 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5245 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5246 [content addSubview:content_];
5247 [content_ setBackgroundColor:[UIColor whiteColor]];
5249 [content_ setDelegate:self];
5253 - (void) onSwitch:(id)sender {
5254 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5255 if (metadata == nil) {
5256 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5257 [Sections_ setObject:metadata forKey:basic_];
5260 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5264 - (void) setSection:(Section *)section editing:(BOOL)editing {
5265 if (editing != editing_) {
5267 [switch_ removeFromSuperview];
5269 [self addSubview:switch_];
5278 if (section == nil) {
5279 name_ = UCLocalize("ALL_PACKAGES");
5282 basic_ = [section name];
5283 section_ = [section localized];
5285 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5286 count_ = [NSString stringWithFormat:@"%d", [section count]];
5289 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5292 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5293 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5295 [content_ setNeedsDisplay];
5298 - (void) setFrame:(CGRect)frame {
5299 [super setFrame:frame];
5301 CGRect rect([switch_ frame]);
5302 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5305 - (NSString *) accessibilityLabel {
5309 - (void) drawContentRect:(CGRect)rect {
5310 bool highlighted(highlighted_ && !editing_);
5312 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5317 float width(rect.size.width);
5323 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5325 CGSize size = [count_ sizeWithFont:Font14_];
5329 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5335 /* File Table {{{ */
5336 @interface FileTable : CyteViewController <
5337 UITableViewDataSource,
5340 _transient Database *database_;
5341 _H<Package> package_;
5343 _H<NSMutableArray> files_;
5344 _H<UITableView, 2> list_;
5347 - (id) initWithDatabase:(Database *)database;
5348 - (void) setPackage:(Package *)package;
5352 @implementation FileTable
5354 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5355 return files_ == nil ? 0 : [files_ count];
5358 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5362 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5363 static NSString *reuseIdentifier = @"Cell";
5365 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5367 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5368 [cell setFont:[UIFont systemFontOfSize:16]];
5370 [cell setText:[files_ objectAtIndex:indexPath.row]];
5371 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5376 - (NSURL *) navigationURL {
5377 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5381 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5383 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5384 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5385 [list_ setRowHeight:24.0f];
5386 [(UITableView *) list_ setDataSource:self];
5387 [list_ setDelegate:self];
5388 [[self view] addSubview:list_];
5391 - (void) viewDidLoad {
5392 [super viewDidLoad];
5394 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5397 - (void) releaseSubviews {
5401 - (id) initWithDatabase:(Database *)database {
5402 if ((self = [super init]) != nil) {
5403 database_ = database;
5405 files_ = [NSMutableArray arrayWithCapacity:32];
5409 - (void) setPackage:(Package *)package {
5413 [files_ removeAllObjects];
5415 if (package != nil) {
5417 name_ = [package id];
5419 if (NSArray *files = [package files])
5420 [files_ addObjectsFromArray:files];
5422 if ([files_ count] != 0) {
5423 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5424 [files_ removeObjectAtIndex:0];
5425 [files_ sortUsingSelector:@selector(compareByPath:)];
5427 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5428 [stack addObject:@"/"];
5430 for (int i(0), e([files_ count]); i != e; ++i) {
5431 NSString *file = [files_ objectAtIndex:i];
5432 while (![file hasPrefix:[stack lastObject]])
5433 [stack removeLastObject];
5434 NSString *directory = [stack lastObject];
5435 [stack addObject:[file stringByAppendingString:@"/"]];
5436 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5437 ([stack count] - 2) * 3, "",
5438 [file substringFromIndex:[directory length]]
5447 - (void) reloadData {
5450 [self setPackage:[database_ packageWithName:name_]];
5455 /* Package Controller {{{ */
5456 @interface CYPackageController : CydiaWebViewController <
5457 UIActionSheetDelegate
5459 _transient Database *database_;
5460 _H<Package> package_;
5463 _H<NSMutableArray> buttons_;
5464 _H<UIBarButtonItem> button_;
5467 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5471 @implementation CYPackageController
5473 - (NSURL *) navigationURL {
5474 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5477 /* XXX: this is not safe at all... localization of /fail/ */
5478 - (void) _clickButtonWithName:(NSString *)name {
5479 if ([name isEqualToString:UCLocalize("CLEAR")])
5480 [delegate_ clearPackage:package_];
5481 else if ([name isEqualToString:UCLocalize("INSTALL")])
5482 [delegate_ installPackage:package_];
5483 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5484 [delegate_ installPackage:package_];
5485 else if ([name isEqualToString:UCLocalize("REMOVE")])
5486 [delegate_ removePackage:package_];
5487 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5488 [delegate_ installPackage:package_];
5489 else _assert(false);
5492 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5493 NSString *context([sheet context]);
5495 if ([context isEqualToString:@"modify"]) {
5496 if (button != [sheet cancelButtonIndex]) {
5497 NSString *buttonName = [buttons_ objectAtIndex:button];
5498 [self _clickButtonWithName:buttonName];
5501 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5505 - (bool) _allowJavaScriptPanel {
5510 - (void) _customButtonClicked {
5511 int count([buttons_ count]);
5516 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5518 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5519 [buttons addObjectsFromArray:buttons_];
5521 UIActionSheet *sheet = [[[UIActionSheet alloc]
5524 cancelButtonTitle:nil
5525 destructiveButtonTitle:nil
5526 otherButtonTitles:nil
5529 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5531 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5532 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5534 [sheet setContext:@"modify"];
5536 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5540 // We don't want to allow non-commercial packages to do custom things to the install button,
5541 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5542 - (void) customButtonClicked {
5544 [super customButtonClicked];
5546 [self _customButtonClicked];
5549 - (void) reloadButtonClicked {
5550 // Don't reload a commerical package by tapping the loading button,
5551 // but if it's not an Install button, we should forward it on.
5552 if (![package_ uninstalled])
5553 [self _customButtonClicked];
5556 - (void) applyLoadingTitle {
5557 // Don't show "Loading" as the title. Ever.
5560 - (UIBarButtonItem *) rightButton {
5565 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5566 if ((self = [super init]) != nil) {
5567 database_ = database;
5568 buttons_ = [NSMutableArray arrayWithCapacity:4];
5569 name_ = [NSString stringWithString:name];
5570 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5574 - (void) reloadData {
5577 package_ = [database_ packageWithName:name_];
5579 [buttons_ removeAllObjects];
5581 if (package_ != nil) {
5582 [(Package *) package_ parse];
5584 commercial_ = [package_ isCommercial];
5586 if ([package_ mode] != nil)
5587 [buttons_ addObject:UCLocalize("CLEAR")];
5588 if ([package_ source] == nil);
5589 else if ([package_ upgradableAndEssential:NO])
5590 [buttons_ addObject:UCLocalize("UPGRADE")];
5591 else if ([package_ uninstalled])
5592 [buttons_ addObject:UCLocalize("INSTALL")];
5594 [buttons_ addObject:UCLocalize("REINSTALL")];
5595 if (![package_ uninstalled])
5596 [buttons_ addObject:UCLocalize("REMOVE")];
5600 switch ([buttons_ count]) {
5601 case 0: title = nil; break;
5602 case 1: title = [buttons_ objectAtIndex:0]; break;
5603 default: title = UCLocalize("MODIFY"); break;
5606 button_ = [[[UIBarButtonItem alloc]
5608 style:UIBarButtonItemStylePlain
5610 action:@selector(customButtonClicked)
5614 - (bool) isLoading {
5615 return commercial_ ? [super isLoading] : false;
5621 /* Package List Controller {{{ */
5622 @interface PackageListController : CyteViewController <
5623 UITableViewDataSource,
5626 _transient Database *database_;
5628 _H<NSArray> packages_;
5629 _H<NSMutableArray> sections_;
5630 _H<UITableView, 2> list_;
5631 _H<NSMutableArray> index_;
5632 _H<NSMutableDictionary> indices_;
5633 _H<NSString> title_;
5634 unsigned reloading_;
5637 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5638 - (void) setDelegate:(id)delegate;
5639 - (void) resetCursor;
5644 @implementation PackageListController
5646 - (bool) isSummarized {
5650 - (void) deselectWithAnimation:(BOOL)animated {
5651 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5654 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5655 CGRect base = [[self view] bounds];
5656 base.size.height -= bounds.size.height;
5657 base.origin = [list_ frame].origin;
5659 [UIView beginAnimations:nil context:NULL];
5660 [UIView setAnimationBeginsFromCurrentState:YES];
5661 [UIView setAnimationCurve:curve];
5662 [UIView setAnimationDuration:duration];
5663 [list_ setFrame:base];
5664 [UIView commitAnimations];
5667 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5668 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5671 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5672 [self resizeForKeyboardBounds:bounds duration:0];
5675 - (void) keyboardWillShow:(NSNotification *)notification {
5678 NSTimeInterval duration;
5679 UIViewAnimationCurve curve;
5680 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5681 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5682 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5683 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5685 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);
5686 UIViewController *base = self;
5687 while ([base parentViewController] != nil)
5688 base = [base parentViewController];
5689 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5690 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5692 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5695 - (void) keyboardWillHide:(NSNotification *)notification {
5696 NSTimeInterval duration;
5697 UIViewAnimationCurve curve;
5698 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5699 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5701 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5704 - (void) viewWillAppear:(BOOL)animated {
5705 [super viewWillAppear:animated];
5707 [self resizeForKeyboardBounds:CGRectZero];
5708 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5709 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5712 - (void) viewWillDisappear:(BOOL)animated {
5713 [super viewWillDisappear:animated];
5715 [self resizeForKeyboardBounds:CGRectZero];
5716 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5717 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5720 - (void) viewDidAppear:(BOOL)animated {
5721 [super viewDidAppear:animated];
5722 [self deselectWithAnimation:animated];
5725 - (void) didSelectPackage:(Package *)package {
5726 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5727 [view setDelegate:delegate_];
5728 [[self navigationController] pushViewController:view animated:YES];
5731 #if TryIndexedCollation
5732 + (BOOL) hasIndexedCollation {
5733 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5737 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5738 NSInteger count([sections_ count]);
5739 return count == 0 ? 1 : count;
5742 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5743 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5745 return [[sections_ objectAtIndex:section] name];
5748 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5749 if ([sections_ count] == 0)
5751 return [[sections_ objectAtIndex:section] count];
5754 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5755 @synchronized (database_) {
5756 if ([database_ era] != era_)
5759 Section *section([sections_ objectAtIndex:[path section]]);
5760 NSInteger row([path row]);
5761 Package *package([packages_ objectAtIndex:([section row] + row)]);
5762 return [[package retain] autorelease];
5765 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5766 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5768 cell = [[[PackageCell alloc] init] autorelease];
5769 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5773 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5774 Package *package([self packageAtIndexPath:path]);
5775 package = [database_ packageWithName:[package id]];
5776 [self didSelectPackage:package];
5779 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5780 if ([self isSummarized])
5786 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5787 #if TryIndexedCollation
5788 if ([[self class] hasIndexedCollation]) {
5789 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5796 - (void) updateHeight {
5797 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5800 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5801 if ((self = [super init]) != nil) {
5802 database_ = database;
5803 title_ = [title copy];
5804 [[self navigationItem] setTitle:title_];
5806 #if TryIndexedCollation
5807 if ([[self class] hasIndexedCollation])
5808 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5811 index_ = [NSMutableArray arrayWithCapacity:32];
5813 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5815 packages_ = [NSArray array];
5816 sections_ = [NSMutableArray arrayWithCapacity:16];
5818 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5819 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5820 [[self view] addSubview:list_];
5822 // XXX: is 20 the most optimal number here?
5823 [list_ setSectionIndexMinimumDisplayRowCount:20];
5825 [(UITableView *) list_ setDataSource:self];
5826 [list_ setDelegate:self];
5828 [self updateHeight];
5832 - (void) setDelegate:(id)delegate {
5833 delegate_ = delegate;
5836 - (bool) shouldYield {
5840 - (bool) shouldBlock {
5844 - (NSArray *) _reloadPackages {
5845 @synchronized (database_) {
5846 era_ = [database_ era];
5847 NSArray *packages([database_ packages]);
5849 return [NSArray arrayWithArray:packages];
5852 - (void) _reloadData {
5853 if (reloading_ != 0) {
5858 if ([self shouldYield]) {
5862 if (![self shouldBlock])
5865 hud = [delegate_ addProgressHUD];
5866 [hud setText:UCLocalize("LOADING")];
5870 packages_ = [self yieldToSelector:@selector(_reloadPackages)];
5873 [delegate_ removeProgressHUD:hud];
5874 } while (reloading_ == 2);
5878 packages_ = [self _reloadPackages];
5881 [indices_ removeAllObjects];
5882 [sections_ removeAllObjects];
5884 Section *section = nil;
5886 #if TryIndexedCollation
5887 if ([[self class] hasIndexedCollation]) {
5888 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5889 NSArray *titles = [collation sectionIndexTitles];
5892 _profile(PackageTable$reloadData$Section)
5893 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5897 _profile(PackageTable$reloadData$Section$Package)
5898 package = [packages_ objectAtIndex:offset];
5899 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5902 while (secidx < index) {
5905 _profile(PackageTable$reloadData$Section$Allocate)
5906 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5909 _profile(PackageTable$reloadData$Section$Add)
5910 [sections_ addObject:section];
5914 [section addToCount];
5920 [index_ removeAllObjects];
5922 bool summary([self isSummarized]);
5924 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
5925 [sections_ addObject:section];
5928 _profile(PackageTable$reloadData$Section)
5929 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5933 _profile(PackageTable$reloadData$Section$Package)
5934 package = [packages_ objectAtIndex:offset];
5935 index = [package index];
5938 if (!summary && (section == nil || [section index] != index)) {
5939 _profile(PackageTable$reloadData$Section$Allocate)
5940 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5943 [index_ addObject:[section name]];
5944 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5946 _profile(PackageTable$reloadData$Section$Add)
5947 [sections_ addObject:section];
5951 [section addToCount];
5956 [self updateHeight];
5958 _profile(PackageTable$reloadData$List)
5959 [(UITableView *) list_ setDataSource:self];
5964 - (void) reloadData {
5966 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
5969 - (void) resetCursor {
5970 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
5973 - (void) clearData {
5974 [self updateHeight];
5976 [list_ setDataSource:nil];
5984 /* Filtered Package List Controller {{{ */
5985 @interface FilteredPackageListController : PackageListController {
5988 _H<NSObject> object_;
5991 - (void) setObject:(id)object;
5992 - (void) setObject:(id)object forFilter:(SEL)filter;
5995 - (void) setFilter:(SEL)filter;
5997 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6001 @implementation FilteredPackageListController
6007 - (void) setFilter:(SEL)filter {
6008 @synchronized (self) {
6011 /* XXX: this is an unsafe optimization of doomy hell */
6012 Method method(class_getInstanceMethod([Package class], filter));
6013 _assert(method != NULL);
6014 imp_ = method_getImplementation(method);
6015 _assert(imp_ != NULL);
6018 - (void) setObject:(id)object {
6019 @synchronized (self) {
6023 - (void) setObject:(id)object forFilter:(SEL)filter {
6024 [self setFilter:filter];
6025 [self setObject:object];
6028 - (NSArray *) _reloadPackages {
6029 @synchronized (database_) {
6030 era_ = [database_ era];
6031 NSArray *packages([database_ packages]);
6033 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6037 _H<NSObject> object;
6039 @synchronized (self) {
6045 _profile(PackageTable$reloadData$Filter)
6046 for (Package *package in packages)
6047 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6048 [filtered addObject:package];
6054 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6055 if ((self = [super initWithDatabase:database title:title]) != nil) {
6056 [self setFilter:filter];
6057 [self setObject:object];
6064 /* Home Controller {{{ */
6065 @interface HomeController : CydiaWebViewController {
6070 @implementation HomeController
6073 if ((self = [super init]) != nil) {
6074 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6079 - (NSURL *) navigationURL {
6080 return [NSURL URLWithString:@"cydia://home"];
6083 - (void) aboutButtonClicked {
6084 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6086 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6087 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6088 [alert setCancelButtonIndex:0];
6091 @"Copyright \u00a9 2008-2011\n"
6094 "Jay Freeman (saurik)\n"
6095 "saurik@saurik.com\n"
6096 "http://www.saurik.com/"
6102 - (UIBarButtonItem *) leftButton {
6103 return [[[UIBarButtonItem alloc]
6104 initWithTitle:UCLocalize("ABOUT")
6105 style:UIBarButtonItemStylePlain
6107 action:@selector(aboutButtonClicked)
6111 - (void) unloadData {
6118 /* Manage Controller {{{ */
6119 @interface ManageController : CydiaWebViewController {
6122 - (void) queueStatusDidChange;
6126 @implementation ManageController
6129 if ((self = [super init]) != nil) {
6130 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6134 - (NSURL *) navigationURL {
6135 return [NSURL URLWithString:@"cydia://manage"];
6138 - (UIBarButtonItem *) leftButton {
6139 return [[[UIBarButtonItem alloc]
6140 initWithTitle:UCLocalize("SETTINGS")
6141 style:UIBarButtonItemStylePlain
6143 action:@selector(settingsButtonClicked)
6147 - (void) settingsButtonClicked {
6148 [delegate_ showSettings];
6151 - (void) queueButtonClicked {
6155 - (UIBarButtonItem *) customButton {
6156 return Queuing_ ? [[[UIBarButtonItem alloc]
6157 initWithTitle:UCLocalize("QUEUE")
6158 style:UIBarButtonItemStyleDone
6160 action:@selector(queueButtonClicked)
6161 ] autorelease] : [super customButton];
6164 - (void) queueStatusDidChange {
6165 [self applyRightButton];
6168 - (bool) isLoading {
6169 return !Queuing_ && [super isLoading];
6175 /* Refresh Bar {{{ */
6176 @interface RefreshBar : UINavigationBar {
6177 _H<UIProgressIndicator> indicator_;
6178 _H<UITextLabel> prompt_;
6179 _H<UIProgressBar> progress_;
6180 _H<UINavigationButton> cancel_;
6185 @implementation RefreshBar
6187 - (void) positionViews {
6188 CGRect frame = [cancel_ frame];
6189 frame.size = [cancel_ sizeThatFits:frame.size];
6190 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6191 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6192 [cancel_ setFrame:frame];
6194 CGSize prgsize = {75, 100};
6196 [self frame].size.width - prgsize.width - 10,
6197 ([self frame].size.height - prgsize.height) / 2
6199 [progress_ setFrame:prgrect];
6201 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6202 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6203 CGRect indrect = {{indoffset, indoffset}, indsize};
6204 [indicator_ setFrame:indrect];
6206 CGSize prmsize = {215, indsize.height + 4};
6208 indoffset * 2 + indsize.width,
6209 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6211 [prompt_ setFrame:prmrect];
6214 - (void) setFrame:(CGRect)frame {
6215 [super setFrame:frame];
6216 [self positionViews];
6219 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6220 if ((self = [super initWithFrame:frame]) != nil) {
6221 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6223 [self setBarStyle:UIBarStyleBlack];
6225 UIBarStyle barstyle([self _barStyle:NO]);
6226 bool ugly(barstyle == UIBarStyleDefault);
6228 UIProgressIndicatorStyle style = ugly ?
6229 UIProgressIndicatorStyleMediumBrown :
6230 UIProgressIndicatorStyleMediumWhite;
6232 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6233 [(UIProgressIndicator *) indicator_ setStyle:style];
6234 [indicator_ startAnimation];
6235 [self addSubview:indicator_];
6237 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6238 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6239 [prompt_ setBackgroundColor:[UIColor clearColor]];
6240 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6241 [self addSubview:prompt_];
6243 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6244 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6245 [(UIProgressBar *) progress_ setStyle:0];
6246 [self addSubview:progress_];
6248 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6249 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6250 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6251 [cancel_ setBarStyle:barstyle];
6253 [self positionViews];
6257 - (void) setCancellable:(bool)cancellable {
6259 [self addSubview:cancel_];
6261 [cancel_ removeFromSuperview];
6265 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6266 [progress_ setProgress:0];
6270 [self setCancellable:NO];
6273 - (void) setPrompt:(NSString *)prompt {
6274 [prompt_ setText:prompt];
6277 - (void) setProgress:(float)progress {
6278 [progress_ setProgress:progress];
6284 /* Cydia Navigation Controller Interface {{{ */
6285 @interface UINavigationController (Cydia)
6287 - (NSArray *) navigationURLCollection;
6288 - (void) unloadData;
6293 /* Cydia Tab Bar Controller {{{ */
6294 @interface CYTabBarController : UITabBarController <
6295 UITabBarControllerDelegate,
6298 _transient Database *database_;
6299 _H<RefreshBar, 1> refreshbar_;
6303 // XXX: ok, "updatedelegate_"?...
6304 _transient NSObject<CydiaDelegate> *updatedelegate_;
6306 _H<UIViewController> remembered_;
6307 _transient UIViewController *transient_;
6310 - (NSArray *) navigationURLCollection;
6311 - (void) dropBar:(BOOL)animated;
6312 - (void) beginUpdate;
6313 - (void) raiseBar:(BOOL)animated;
6315 - (void) unloadData;
6319 @implementation CYTabBarController
6321 - (void) setUnselectedViewController:(UIViewController *)transient {
6322 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6323 if (transient != nil) {
6324 if (transient_ == nil)
6325 remembered_ = [controllers objectAtIndex:0];
6326 transient_ = transient;
6327 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6328 [controllers replaceObjectAtIndex:0 withObject:transient_];
6329 [self setSelectedIndex:0];
6330 [self setViewControllers:controllers];
6331 [self concealTabBarSelection];
6332 } else if (remembered_ != nil) {
6333 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6334 transient_ = transient;
6335 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6337 [self setViewControllers:controllers];
6338 [self revealTabBarSelection];
6342 - (UIViewController *) unselectedViewController {
6346 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6347 if ([self unselectedViewController])
6348 [self setUnselectedViewController:nil];
6351 - (NSArray *) navigationURLCollection {
6352 NSMutableArray *items([NSMutableArray array]);
6354 // XXX: Should this deal with transient view controllers?
6355 for (id navigation in [self viewControllers]) {
6356 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6358 [items addObject:stack];
6364 - (void) unloadData {
6365 UIViewController *selected([self selectedViewController]);
6366 for (UINavigationController *controller in [self viewControllers])
6367 [controller unloadData];
6369 [selected reloadData];
6371 if (UIViewController *unselected = [self unselectedViewController])
6372 [unselected reloadData];
6378 [[NSNotificationCenter defaultCenter] removeObserver:self];
6383 - (id) initWithDatabase:(Database *)database {
6384 if ((self = [super init]) != nil) {
6385 database_ = database;
6386 [self setDelegate:self];
6388 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6389 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6391 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6395 - (void) setUpdate:(NSDate *)date {
6399 - (void) beginUpdate {
6400 [(RefreshBar *) refreshbar_ start];
6403 [updatedelegate_ retainNetworkActivityIndicator];
6407 detachNewThreadSelector:@selector(performUpdate)
6413 - (void) performUpdate {
6414 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6417 status.setDelegate(self);
6418 [database_ updateWithStatus:status];
6421 performSelectorOnMainThread:@selector(completeUpdate)
6429 - (void) stopUpdateWithSelector:(SEL)selector {
6431 [updatedelegate_ releaseNetworkActivityIndicator];
6433 [self raiseBar:YES];
6436 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6439 - (void) completeUpdate {
6442 [self stopUpdateWithSelector:@selector(reloadData)];
6445 - (void) cancelUpdate {
6446 [self stopUpdateWithSelector:@selector(updateData)];
6449 - (void) cancelPressed {
6450 [self cancelUpdate];
6457 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6458 [refreshbar_ setPrompt:[event compoundMessage]];
6461 - (bool) isProgressCancelled {
6465 - (void) setProgressCancellable:(NSNumber *)cancellable {
6466 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6469 - (void) setProgressPercent:(NSNumber *)percent {
6470 [refreshbar_ setProgress:[percent floatValue]];
6473 - (void) setProgressStatus:(NSDictionary *)status {
6475 [self setProgressPercent:[status objectForKey:@"Percent"]];
6478 - (void) setUpdateDelegate:(id)delegate {
6479 updatedelegate_ = delegate;
6482 - (CGFloat) statusBarHeight {
6483 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6484 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6486 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6490 - (UIView *) transitionView {
6491 if ([self respondsToSelector:@selector(_transitionView)])
6492 return [self _transitionView];
6494 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6497 - (void) dropBar:(BOOL)animated {
6502 UIView *transition([self transitionView]);
6503 [[self view] addSubview:refreshbar_];
6505 CGRect barframe([refreshbar_ frame]);
6507 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6508 barframe.origin.y = [self statusBarHeight];
6510 barframe.origin.y = 0;
6512 [refreshbar_ setFrame:barframe];
6515 [UIView beginAnimations:nil context:NULL];
6517 CGRect viewframe = [transition frame];
6518 viewframe.origin.y += barframe.size.height;
6519 viewframe.size.height -= barframe.size.height;
6520 [transition setFrame:viewframe];
6523 [UIView commitAnimations];
6525 // Ensure bar has the proper width for our view, it might have changed
6526 barframe.size.width = viewframe.size.width;
6527 [refreshbar_ setFrame:barframe];
6530 - (void) raiseBar:(BOOL)animated {
6535 UIView *transition([self transitionView]);
6536 [refreshbar_ removeFromSuperview];
6538 CGRect barframe([refreshbar_ frame]);
6541 [UIView beginAnimations:nil context:NULL];
6543 CGRect viewframe = [transition frame];
6544 viewframe.origin.y -= barframe.size.height;
6545 viewframe.size.height += barframe.size.height;
6546 [transition setFrame:viewframe];
6549 [UIView commitAnimations];
6552 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6553 bool dropped(dropped_);
6558 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6564 - (void) statusBarFrameChanged:(NSNotification *)notification {
6574 /* Cydia Navigation Controller Implementation {{{ */
6575 @implementation UINavigationController (Cydia)
6577 - (NSArray *) navigationURLCollection {
6578 NSMutableArray *stack([NSMutableArray array]);
6580 for (CyteViewController *controller in [self viewControllers]) {
6581 NSString *url = [[controller navigationURL] absoluteString];
6583 [stack addObject:url];
6589 - (void) reloadData {
6592 if (UIViewController *visible = [self visibleViewController])
6593 [visible reloadData];
6596 - (void) unloadData {
6597 for (CyteViewController *page in [self viewControllers])
6606 /* Cydia:// Protocol {{{ */
6607 @interface CydiaURLProtocol : NSURLProtocol {
6612 @implementation CydiaURLProtocol
6614 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6615 NSURL *url([request URL]);
6619 NSString *scheme([[url scheme] lowercaseString]);
6620 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6622 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6628 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6632 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6633 id<NSURLProtocolClient> client([self client]);
6635 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6637 NSData *data(UIImagePNGRepresentation(icon));
6639 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6640 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6641 [client URLProtocol:self didLoadData:data];
6642 [client URLProtocolDidFinishLoading:self];
6646 - (void) startLoading {
6647 id<NSURLProtocolClient> client([self client]);
6648 NSURLRequest *request([self request]);
6650 NSURL *url([request URL]);
6651 NSString *href([url absoluteString]);
6652 NSString *scheme([[url scheme] lowercaseString]);
6656 if ([scheme isEqualToString:@"cydia"])
6657 path = [href substringFromIndex:8];
6658 else if ([scheme isEqualToString:@"about"])
6659 path = [href substringFromIndex:12];
6660 else _assert(false);
6662 NSRange slash([path rangeOfString:@"/"]);
6665 if (slash.location == NSNotFound) {
6669 command = [path substringToIndex:slash.location];
6670 path = [path substringFromIndex:(slash.location + 1)];
6673 Database *database([Database sharedInstance]);
6675 if ([command isEqualToString:@"package-icon"]) {
6678 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6679 Package *package([database packageWithName:path]);
6683 UIImage *icon([package icon]);
6684 [self _returnPNGWithImage:icon forRequest:request];
6685 } else if ([command isEqualToString:@"source-icon"]) {
6688 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6689 NSString *source(Simplify(path));
6690 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6692 icon = [UIImage applicationImageNamed:@"unknown.png"];
6693 [self _returnPNGWithImage:icon forRequest:request];
6694 } else if ([command isEqualToString:@"uikit-image"]) {
6697 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6698 UIImage *icon(_UIImageWithName(path));
6699 [self _returnPNGWithImage:icon forRequest:request];
6700 } else if ([command isEqualToString:@"section-icon"]) {
6703 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6704 NSString *section(Simplify(path));
6705 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6707 icon = [UIImage applicationImageNamed:@"unknown.png"];
6708 [self _returnPNGWithImage:icon forRequest:request];
6710 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6714 - (void) stopLoading {
6720 /* Section Controller {{{ */
6721 @interface SectionController : FilteredPackageListController {
6722 _H<NSString> section_;
6725 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6729 @implementation SectionController
6731 - (NSURL *) navigationURL {
6732 NSString *name = section_;
6736 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6739 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6742 title = UCLocalize("ALL_PACKAGES");
6743 else if (![name isEqual:@""])
6744 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6746 title = UCLocalize("NO_SECTION");
6748 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6755 /* Sections Controller {{{ */
6756 @interface SectionsController : CyteViewController <
6757 UITableViewDataSource,
6760 _transient Database *database_;
6761 _H<NSMutableArray> sections_;
6762 _H<NSMutableArray> filtered_;
6763 _H<UITableView, 2> list_;
6766 - (id) initWithDatabase:(Database *)database;
6767 - (void) editButtonClicked;
6771 @implementation SectionsController
6773 - (NSURL *) navigationURL {
6774 return [NSURL URLWithString:@"cydia://sections"];
6777 - (void) updateNavigationItem {
6778 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6779 if ([sections_ count] == 0) {
6780 [[self navigationItem] setRightBarButtonItem:nil];
6782 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6783 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6785 action:@selector(editButtonClicked)
6786 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6790 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6791 [super setEditing:editing animated:animated];
6796 [delegate_ updateData];
6798 [self updateNavigationItem];
6801 - (void) viewDidAppear:(BOOL)animated {
6802 [super viewDidAppear:animated];
6803 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6806 - (void) viewWillDisappear:(BOOL)animated {
6807 [super viewWillDisappear:animated];
6808 if ([self isEditing]) [self setEditing:NO];
6811 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6812 Section *section = nil;
6813 int index = [indexPath row];
6814 if (![self isEditing]) {
6817 section = [filtered_ objectAtIndex:index];
6819 section = [sections_ objectAtIndex:index];
6824 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6825 if ([self isEditing])
6826 return [sections_ count];
6828 return [filtered_ count] + 1;
6831 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6835 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6836 static NSString *reuseIdentifier = @"SectionCell";
6838 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6840 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6842 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6847 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6848 if ([self isEditing])
6851 Section *section = [self sectionAtIndexPath:indexPath];
6853 SectionController *controller = [[[SectionController alloc]
6854 initWithDatabase:database_
6855 section:[section name]
6857 [controller setDelegate:delegate_];
6859 [[self navigationController] pushViewController:controller animated:YES];
6863 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6865 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6866 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6867 [list_ setRowHeight:45.0f];
6868 [(UITableView *) list_ setDataSource:self];
6869 [list_ setDelegate:self];
6870 [[self view] addSubview:list_];
6873 - (void) viewDidLoad {
6874 [super viewDidLoad];
6876 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6879 - (void) releaseSubviews {
6883 - (id) initWithDatabase:(Database *)database {
6884 if ((self = [super init]) != nil) {
6885 database_ = database;
6887 sections_ = [NSMutableArray arrayWithCapacity:16];
6888 filtered_ = [NSMutableArray arrayWithCapacity:16];
6892 - (void) reloadData {
6895 NSArray *packages = [database_ packages];
6897 [sections_ removeAllObjects];
6898 [filtered_ removeAllObjects];
6900 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6903 for (Package *package in packages) {
6904 NSString *name([package section]);
6905 NSString *key(name == nil ? @"" : name);
6909 _profile(SectionsView$reloadData$Section)
6910 section = [sections objectForKey:key];
6911 if (section == nil) {
6912 _profile(SectionsView$reloadData$Section$Allocate)
6913 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6914 [sections setObject:section forKey:key];
6919 [section addToCount];
6921 _profile(SectionsView$reloadData$Filter)
6922 if (![package valid] || ![package visible])
6930 [sections_ addObjectsFromArray:[sections allValues]];
6932 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6934 for (Section *section in (id) sections_) {
6935 size_t count([section row]);
6939 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6940 [section setCount:count];
6941 [filtered_ addObject:section];
6944 [self updateNavigationItem];
6949 - (void) editButtonClicked {
6950 [self setEditing:![self isEditing] animated:YES];
6956 /* Changes Controller {{{ */
6957 @interface ChangesController : CyteViewController <
6958 UITableViewDataSource,
6961 _transient Database *database_;
6963 _H<NSArray> packages_;
6964 _H<NSMutableArray> sections_;
6965 _H<UITableView, 2> list_;
6969 - (id) initWithDatabase:(Database *)database;
6973 @implementation ChangesController
6975 - (NSURL *) navigationURL {
6976 return [NSURL URLWithString:@"cydia://changes"];
6979 - (void) viewDidAppear:(BOOL)animated {
6980 [super viewDidAppear:animated];
6981 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6984 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6985 NSInteger count([sections_ count]);
6986 return count == 0 ? 1 : count;
6989 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6990 if ([sections_ count] == 0)
6992 return [[sections_ objectAtIndex:section] name];
6995 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6996 if ([sections_ count] == 0)
6998 return [[sections_ objectAtIndex:section] count];
7001 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7002 @synchronized (database_) {
7003 if ([database_ era] != era_)
7006 NSUInteger sectionIndex([path section]);
7007 if (sectionIndex >= [sections_ count])
7009 Section *section([sections_ objectAtIndex:sectionIndex]);
7010 NSInteger row([path row]);
7011 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7014 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7015 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7017 cell = [[[PackageCell alloc] init] autorelease];
7018 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7022 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7023 Package *package([self packageAtIndexPath:path]);
7024 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7025 [view setDelegate:delegate_];
7026 [[self navigationController] pushViewController:view animated:YES];
7030 - (void) refreshButtonClicked {
7031 [delegate_ beginUpdate];
7032 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7035 - (void) upgradeButtonClicked {
7036 [delegate_ distUpgrade];
7040 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7042 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7043 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7044 [list_ setRowHeight:73];
7045 [(UITableView *) list_ setDataSource:self];
7046 [list_ setDelegate:self];
7047 [[self view] addSubview:list_];
7050 - (void) viewDidLoad {
7051 [super viewDidLoad];
7053 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7056 - (void) releaseSubviews {
7060 - (id) initWithDatabase:(Database *)database {
7061 if ((self = [super init]) != nil) {
7062 database_ = database;
7064 packages_ = [NSArray array];
7065 sections_ = [NSMutableArray arrayWithCapacity:16];
7069 - (NSArray *) _reloadPackages {
7070 @synchronized (database_) {
7071 era_ = [database_ era];
7072 NSArray *packages([database_ packages]);
7074 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7077 _profile(ChangesController$_reloadPackages$Filter)
7078 for (Package *package in packages)
7079 if ([package upgradableAndEssential:YES] || [package visible])
7080 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7083 _profile(ChangesController$_reloadPackages$radixSort)
7084 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7091 - (void) _reloadData {
7094 UIProgressHUD *hud([delegate_ addProgressHUD]);
7095 [hud setText:UCLocalize("LOADING")];
7096 //NSLog(@"HUD:%@::%@", delegate_, hud);
7097 packages_ = [self yieldToSelector:@selector(_reloadPackages)];
7098 [delegate_ removeProgressHUD:hud];
7100 packages_ = [self _reloadPackages];
7103 @synchronized (database_) {
7104 if (era_ != [database_ era])
7107 [sections_ removeAllObjects];
7109 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7110 Section *ignored = nil;
7111 Section *section = nil;
7115 bool unseens = false;
7117 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7119 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7120 Package *package = [packages_ objectAtIndex:offset];
7122 BOOL uae = [package upgradableAndEssential:YES];
7126 time_t seen([package seen]);
7128 if (section == nil || last != seen) {
7132 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7135 _profile(ChangesController$reloadData$Allocate)
7136 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7137 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7138 [sections_ addObject:section];
7142 [section addToCount];
7143 } else if ([package ignored]) {
7144 if (ignored == nil) {
7145 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7147 [ignored addToCount];
7150 [upgradable addToCount];
7155 CFRelease(formatter);
7158 Section *last = [sections_ lastObject];
7159 size_t count = [last count];
7160 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7161 [sections_ removeLastObject];
7164 if ([ignored count] != 0)
7165 [sections_ insertObject:ignored atIndex:0];
7167 [sections_ insertObject:upgradable atIndex:0];
7172 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7173 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7174 style:UIBarButtonItemStylePlain
7176 action:@selector(upgradeButtonClicked)
7179 if (![delegate_ updating])
7180 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7181 initWithTitle:UCLocalize("REFRESH")
7182 style:UIBarButtonItemStylePlain
7184 action:@selector(refreshButtonClicked)
7190 - (void) reloadData {
7192 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7197 /* Search Controller {{{ */
7198 @interface SearchController : FilteredPackageListController <
7201 _H<UISearchBar, 1> search_;
7205 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7206 - (void) reloadData;
7210 @implementation SearchController
7212 - (NSURL *) navigationURL {
7213 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7214 return [NSURL URLWithString:@"cydia://search"];
7216 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7219 - (void) useSearch {
7220 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7225 - (void) viewWillAppear:(BOOL)animated {
7226 [super viewWillAppear:animated];
7228 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7232 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7233 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7238 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7239 [search_ resignFirstResponder];
7243 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7244 [search_ setText:@""];
7245 [self searchBarButtonClicked:searchBar];
7248 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7249 [self searchBarButtonClicked:searchBar];
7252 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7253 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7257 - (bool) shouldYield {
7261 - (bool) shouldBlock {
7262 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7265 - (bool) isSummarized {
7266 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7269 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7270 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7271 search_ = [[[UISearchBar alloc] init] autorelease];
7272 [search_ setDelegate:self];
7275 [search_ setText:query];
7279 - (void) viewDidAppear:(BOOL)animated {
7280 [super viewDidAppear:animated];
7282 if (!searchloaded_) {
7283 searchloaded_ = YES;
7284 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7285 [search_ layoutSubviews];
7286 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7288 UITextField *textField;
7289 if ([search_ respondsToSelector:@selector(searchField)])
7290 textField = [search_ searchField];
7292 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7294 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7295 [textField setEnablesReturnKeyAutomatically:NO];
7296 [[self navigationItem] setTitleView:textField];
7300 - (void) reloadData {
7301 [self setObject:[search_ text]];
7307 - (void) didSelectPackage:(Package *)package {
7308 [search_ resignFirstResponder];
7309 [super didSelectPackage:package];
7314 /* Package Settings Controller {{{ */
7315 @interface PackageSettingsController : CyteViewController <
7316 UITableViewDataSource,
7319 _transient Database *database_;
7321 _H<Package> package_;
7322 _H<UITableView, 2> table_;
7323 _H<UISwitch> subscribedSwitch_;
7324 _H<UISwitch> ignoredSwitch_;
7325 _H<UITableViewCell> subscribedCell_;
7326 _H<UITableViewCell> ignoredCell_;
7329 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7333 @implementation PackageSettingsController
7335 - (NSURL *) navigationURL {
7336 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7339 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7340 if (package_ == nil)
7343 if ([package_ installed] == nil)
7349 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7350 if (package_ == nil)
7353 // both sections contain just one item right now.
7357 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7361 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7363 return UCLocalize("SHOW_ALL_CHANGES_EX");
7365 return UCLocalize("IGNORE_UPGRADES_EX");
7368 - (void) onSubscribed:(id)control {
7369 bool value([control isOn]);
7370 if (package_ == nil)
7372 if ([package_ setSubscribed:value])
7373 [delegate_ updateData];
7376 - (void) _updateIgnored {
7377 const char *package([name_ UTF8String]);
7378 bool on([ignoredSwitch_ isOn]);
7380 pid_t pid(ExecFork());
7382 FILE *dpkg(popen("dpkg --set-selections", "w"));
7383 fwrite(package, strlen(package), 1, dpkg);
7386 fwrite(" hold\n", 6, 1, dpkg);
7388 fwrite(" install\n", 9, 1, dpkg);
7398 int result(waitpid(pid, &status, 0));
7401 _assert(result == pid);
7407 - (void) onIgnored:(id)control {
7408 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7409 [invocation setTarget:self];
7410 [invocation setSelector:@selector(_updateIgnored)];
7412 [delegate_ reloadDataWithInvocation:invocation];
7415 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7416 if (package_ == nil)
7419 switch ([indexPath section]) {
7420 case 0: return subscribedCell_;
7421 case 1: return ignoredCell_;
7430 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7432 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7433 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7434 [(UITableView *) table_ setDataSource:self];
7435 [table_ setDelegate:self];
7436 [[self view] addSubview:table_];
7438 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7439 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7440 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7442 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7443 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7444 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7446 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7447 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7448 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7449 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7451 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7452 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7453 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7454 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7457 - (void) viewDidLoad {
7458 [super viewDidLoad];
7460 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7463 - (void) releaseSubviews {
7465 subscribedCell_ = nil;
7467 ignoredSwitch_ = nil;
7468 subscribedSwitch_ = nil;
7471 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7472 if ((self = [super init]) != nil) {
7473 database_ = database;
7478 - (void) reloadData {
7481 package_ = [database_ packageWithName:name_];
7483 if (package_ != nil) {
7484 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7485 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7486 } // XXX: what now, G?
7488 [table_ reloadData];
7494 /* Installed Controller {{{ */
7495 @interface InstalledController : FilteredPackageListController {
7499 - (id) initWithDatabase:(Database *)database;
7501 - (void) updateRoleButton;
7502 - (void) queueStatusDidChange;
7506 @implementation InstalledController
7508 - (NSURL *) navigationURL {
7509 return [NSURL URLWithString:@"cydia://installed"];
7512 - (id) initWithDatabase:(Database *)database {
7513 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7514 [self updateRoleButton];
7515 [self queueStatusDidChange];
7520 - (void) queueButtonClicked {
7525 - (void) queueStatusDidChange {
7529 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7530 initWithTitle:UCLocalize("QUEUE")
7531 style:UIBarButtonItemStyleDone
7533 action:@selector(queueButtonClicked)
7536 [[self navigationItem] setLeftBarButtonItem:nil];
7542 - (void) updateRoleButton {
7543 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7544 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7545 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7546 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7548 action:@selector(roleButtonClicked)
7552 - (void) roleButtonClicked {
7553 [self setObject:[NSNumber numberWithBool:expert_]];
7557 [self updateRoleButton];
7563 /* Source Cell {{{ */
7564 @interface SourceCell : CyteTableViewCell <
7565 CyteTableViewCellDelegate
7568 _H<NSString> origin_;
7569 _H<NSString> label_;
7572 - (void) setSource:(Source *)source;
7576 @implementation SourceCell
7578 - (void) _setImage:(UIImage *)image {
7580 [content_ setNeedsDisplay];
7583 - (void) _setSource:(Source *)source {
7584 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7586 if (NSString *base = [source base])
7587 if ([base length] != 0) {
7588 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7590 if (NSData *data = [NSURLConnection
7591 sendSynchronousRequest:[NSURLRequest
7593 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7597 returningResponse:NULL
7600 if (UIImage *image = [UIImage imageWithData:data])
7601 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7607 - (void) setSource:(Source *)source {
7608 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7610 origin_ = [source name];
7611 label_ = [source uri];
7613 [content_ setNeedsDisplay];
7615 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7618 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7619 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7620 UIView *content([self contentView]);
7621 CGRect bounds([content bounds]);
7623 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7624 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7625 [content_ setBackgroundColor:[UIColor whiteColor]];
7626 [content addSubview:content_];
7628 [content_ setDelegate:self];
7629 [content_ setOpaque:YES];
7633 - (NSString *) accessibilityLabel {
7637 - (void) drawContentRect:(CGRect)rect {
7638 bool highlighted(highlighted_);
7639 float width(rect.size.width);
7642 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7649 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7653 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7658 /* Source Controller {{{ */
7659 @interface SourceController : FilteredPackageListController {
7660 _transient Source *source_;
7664 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7668 @implementation SourceController
7670 - (NSURL *) navigationURL {
7671 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7674 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7675 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7677 key_ = [source key];
7681 - (void) reloadData {
7682 source_ = [database_ sourceWithKey:key_];
7683 key_ = [source_ key];
7684 [self setObject:source_];
7686 [[self navigationItem] setTitle:[source_ label]];
7693 /* Sources Controller {{{ */
7694 @interface SourcesController : CyteViewController <
7695 UITableViewDataSource,
7698 _transient Database *database_;
7699 _H<UITableView, 2> list_;
7700 _H<NSMutableArray> sources_;
7704 _H<UIProgressHUD> hud_;
7707 //NSURLConnection *installer_;
7708 NSURLConnection *trivial_;
7709 NSURLConnection *trivial_bz2_;
7710 NSURLConnection *trivial_gz_;
7711 //NSURLConnection *automatic_;
7716 - (id) initWithDatabase:(Database *)database;
7717 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7721 @implementation SourcesController
7723 - (void) _releaseConnection:(NSURLConnection *)connection {
7724 if (connection != nil) {
7725 [connection cancel];
7726 //[connection setDelegate:nil];
7727 [connection release];
7732 //[self _releaseConnection:installer_];
7733 [self _releaseConnection:trivial_];
7734 [self _releaseConnection:trivial_gz_];
7735 [self _releaseConnection:trivial_bz2_];
7736 //[self _releaseConnection:automatic_];
7741 - (NSURL *) navigationURL {
7742 return [NSURL URLWithString:@"cydia://sources"];
7745 - (void) viewDidAppear:(BOOL)animated {
7746 [super viewDidAppear:animated];
7747 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7750 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7751 return offset_ == 0 ? 1 : 2;
7754 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7755 switch (section + (offset_ == 0 ? 1 : 0)) {
7756 case 0: return UCLocalize("ENTERED_BY_USER");
7757 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7763 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7764 int count = [sources_ count];
7766 case 0: return (offset_ == 0 ? count : offset_);
7767 case 1: return count - offset_;
7773 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7775 switch (indexPath.section) {
7776 case 0: idx = indexPath.row; break;
7777 case 1: idx = indexPath.row + offset_; break;
7781 return [sources_ objectAtIndex:idx];
7784 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7785 static NSString *cellIdentifier = @"SourceCell";
7787 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7788 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7789 [cell setSource:[self sourceAtIndexPath:indexPath]];
7790 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7795 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7796 Source *source = [self sourceAtIndexPath:indexPath];
7798 SourceController *controller = [[[SourceController alloc]
7799 initWithDatabase:database_
7803 [controller setDelegate:delegate_];
7805 [[self navigationController] pushViewController:controller animated:YES];
7808 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7809 Source *source = [self sourceAtIndexPath:indexPath];
7810 return [source record] != nil;
7813 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7814 if (editingStyle == UITableViewCellEditingStyleDelete) {
7815 Source *source = [self sourceAtIndexPath:indexPath];
7816 [Sources_ removeObjectForKey:[source key]];
7817 [delegate_ syncData];
7822 [delegate_ addTrivialSource:href_];
7823 [delegate_ syncData];
7826 - (NSString *) getWarning {
7827 NSString *href(href_);
7828 NSRange colon([href rangeOfString:@"://"]);
7829 if (colon.location != NSNotFound)
7830 href = [href substringFromIndex:(colon.location + 3)];
7831 href = [href stringByAddingPercentEscapes];
7832 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7833 href = [href stringByCachingURLWithCurrentCDN];
7835 NSURL *url([NSURL URLWithString:href]);
7837 NSStringEncoding encoding;
7838 NSError *error(nil);
7840 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7841 return [warning length] == 0 ? nil : warning;
7845 - (void) _endConnection:(NSURLConnection *)connection {
7846 // XXX: the memory management in this method is horribly awkward
7848 NSURLConnection **field = NULL;
7849 if (connection == trivial_)
7851 else if (connection == trivial_bz2_)
7852 field = &trivial_bz2_;
7853 else if (connection == trivial_gz_)
7854 field = &trivial_gz_;
7855 _assert(field != NULL);
7856 [connection release];
7861 trivial_bz2_ == nil &&
7864 [delegate_ releaseNetworkActivityIndicator];
7866 [delegate_ removeProgressHUD:hud_];
7872 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7875 UIAlertView *alert = [[[UIAlertView alloc]
7876 initWithTitle:UCLocalize("SOURCE_WARNING")
7879 cancelButtonTitle:UCLocalize("CANCEL")
7881 UCLocalize("ADD_ANYWAY"),
7885 [alert setContext:@"warning"];
7886 [alert setNumberOfRows:1];
7890 } else if (error_ != nil) {
7891 UIAlertView *alert = [[[UIAlertView alloc]
7892 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7893 message:[error_ localizedDescription]
7895 cancelButtonTitle:UCLocalize("OK")
7896 otherButtonTitles:nil
7899 [alert setContext:@"urlerror"];
7902 UIAlertView *alert = [[[UIAlertView alloc]
7903 initWithTitle:UCLocalize("NOT_REPOSITORY")
7904 message:UCLocalize("NOT_REPOSITORY_EX")
7906 cancelButtonTitle:UCLocalize("OK")
7907 otherButtonTitles:nil
7910 [alert setContext:@"trivial"];
7919 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7920 switch ([response statusCode]) {
7926 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7927 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7929 [self _endConnection:connection];
7932 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7933 [self _endConnection:connection];
7936 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7937 NSMutableURLRequest *request = [NSMutableURLRequest
7938 requestWithURL:[NSURL URLWithString:href]
7939 cachePolicy:NSURLRequestUseProtocolCachePolicy
7940 timeoutInterval:120.0
7943 [request setHTTPMethod:method];
7945 if (Machine_ != NULL)
7946 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7947 if (UniqueID_ != nil)
7948 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7950 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7953 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7954 NSString *context([alert context]);
7956 if ([context isEqualToString:@"source"]) {
7959 NSString *href = [[alert textField] text];
7961 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7963 if (![href hasSuffix:@"/"])
7964 href_ = [href stringByAppendingString:@"/"];
7968 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7969 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7970 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7971 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7975 // XXX: this is stupid
7976 hud_ = [delegate_ addProgressHUD];
7977 [hud_ setText:UCLocalize("VERIFYING_URL")];
7978 [delegate_ retainNetworkActivityIndicator];
7987 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7988 } else if ([context isEqualToString:@"trivial"])
7989 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7990 else if ([context isEqualToString:@"urlerror"])
7991 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7992 else if ([context isEqualToString:@"warning"]) {
8006 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8011 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8013 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8014 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8015 [list_ setRowHeight:56];
8016 [(UITableView *) list_ setDataSource:self];
8017 [list_ setDelegate:self];
8018 [[self view] addSubview:list_];
8021 - (void) viewDidLoad {
8022 [super viewDidLoad];
8024 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8025 [self updateButtonsForEditingStatus:NO animated:NO];
8028 - (void) releaseSubviews {
8032 - (id) initWithDatabase:(Database *)database {
8033 if ((self = [super init]) != nil) {
8034 database_ = database;
8035 sources_ = [NSMutableArray arrayWithCapacity:16];
8039 - (void) reloadData {
8043 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8046 [sources_ removeAllObjects];
8047 [sources_ addObjectsFromArray:[database_ sources]];
8049 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8052 int count([sources_ count]);
8054 for (int i = 0; i != count; i++) {
8055 if ([[sources_ objectAtIndex:i] record] == nil)
8060 [list_ setEditing:NO];
8061 [self updateButtonsForEditingStatus:NO animated:NO];
8065 - (void) showAddSourcePrompt {
8066 UIAlertView *alert = [[[UIAlertView alloc]
8067 initWithTitle:UCLocalize("ENTER_APT_URL")
8070 cancelButtonTitle:UCLocalize("CANCEL")
8072 UCLocalize("ADD_SOURCE"),
8076 [alert setContext:@"source"];
8078 [alert setNumberOfRows:1];
8079 [alert addTextFieldWithValue:@"http://" label:@""];
8081 UITextInputTraits *traits = [[alert textField] textInputTraits];
8082 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8083 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8084 [traits setKeyboardType:UIKeyboardTypeURL];
8085 // XXX: UIReturnKeyDone
8086 [traits setReturnKeyType:UIReturnKeyNext];
8091 - (void) addButtonClicked {
8092 [self showAddSourcePrompt];
8095 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8096 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8097 initWithTitle:UCLocalize("ADD")
8098 style:UIBarButtonItemStylePlain
8100 action:@selector(addButtonClicked)
8101 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8103 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8104 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8105 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8107 action:@selector(editButtonClicked)
8108 ] autorelease] animated:animated];
8110 if (IsWildcat_ && !editing)
8111 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8112 initWithTitle:UCLocalize("SETTINGS")
8113 style:UIBarButtonItemStylePlain
8115 action:@selector(settingsButtonClicked)
8119 - (void) settingsButtonClicked {
8120 [delegate_ showSettings];
8123 - (void) editButtonClicked {
8124 [list_ setEditing:![list_ isEditing] animated:YES];
8126 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8132 /* Settings Controller {{{ */
8133 @interface SettingsController : CyteViewController <
8134 UITableViewDataSource,
8137 _transient Database *database_;
8138 // XXX: ok, "roledelegate_"?...
8139 _transient id roledelegate_;
8140 _H<UITableView, 2> table_;
8141 _H<UISegmentedControl> segment_;
8142 _H<UIView> container_;
8145 - (void) showDoneButton;
8146 - (void) resizeSegmentedControl;
8150 @implementation SettingsController
8153 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8155 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8156 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8157 [table_ setDelegate:self];
8158 [(UITableView *) table_ setDataSource:self];
8159 [[self view] addSubview:table_];
8161 NSArray *items = [NSArray arrayWithObjects:
8163 UCLocalize("HACKER"),
8164 UCLocalize("DEVELOPER"),
8166 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8167 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8168 [container_ addSubview:segment_];
8171 - (void) viewDidLoad {
8172 [super viewDidLoad];
8174 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8177 if ([Role_ isEqualToString:@"User"]) index = 0;
8178 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8179 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8181 [segment_ setSelectedSegmentIndex:index];
8182 [self showDoneButton];
8185 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8186 [self resizeSegmentedControl];
8189 - (void) releaseSubviews {
8195 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8196 if ((self = [super init]) != nil) {
8197 database_ = database;
8198 roledelegate_ = delegate;
8202 - (void) resizeSegmentedControl {
8203 CGFloat width = [[self view] frame].size.width;
8204 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8207 - (void) viewWillAppear:(BOOL)animated {
8208 [super viewWillAppear:animated];
8210 [self resizeSegmentedControl];
8213 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8214 [self resizeSegmentedControl];
8217 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8218 [self resizeSegmentedControl];
8222 NSString *role(nil);
8224 switch ([segment_ selectedSegmentIndex]) {
8225 case 0: role = @"User"; break;
8226 case 1: role = @"Hacker"; break;
8227 case 2: role = @"Developer"; break;
8232 if (![role isEqualToString:Role_]) {
8233 bool rolling(Role_ == nil);
8236 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8240 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8244 [roledelegate_ loadData];
8246 [roledelegate_ updateData];
8250 - (void) segmentChanged:(UISegmentedControl *)control {
8251 [self showDoneButton];
8254 - (void) saveAndClose {
8257 [[self navigationItem] setRightBarButtonItem:nil];
8258 [[self navigationController] dismissModalViewControllerAnimated:YES];
8261 - (void) doneButtonClicked {
8262 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8263 [spinner startAnimating];
8264 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8265 [[self navigationItem] setRightBarButtonItem:spinItem];
8267 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8270 - (void) showDoneButton {
8271 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8272 initWithTitle:UCLocalize("DONE")
8273 style:UIBarButtonItemStyleDone
8275 action:@selector(doneButtonClicked)
8276 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8279 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8280 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8284 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8288 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8289 return nil; // This method is required by the protocol.
8292 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8294 return UCLocalize("ROLE_EX");
8296 return [NSString stringWithFormat:
8297 @"%@: %@\n%@: %@\n%@: %@",
8298 UCLocalize("USER"), UCLocalize("USER_EX"),
8299 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8300 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8305 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8306 return section == 3 ? 44.0f : 0;
8309 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8310 return section == 3 ? container_ : nil;
8313 - (void) reloadData {
8316 [table_ reloadData];
8321 /* Stash Controller {{{ */
8322 @interface StashController : CyteViewController {
8323 _H<UIActivityIndicatorView> spinner_;
8324 _H<UILabel> status_;
8325 _H<UILabel> caption_;
8330 @implementation StashController
8333 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8334 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8336 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8337 CGRect spinrect = [spinner_ frame];
8338 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8339 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8340 [spinner_ setFrame:spinrect];
8341 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8342 [[self view] addSubview:spinner_];
8343 [spinner_ startAnimating];
8346 captrect.size.width = [[self view] frame].size.width;
8347 captrect.size.height = 40.0f;
8348 captrect.origin.x = 0;
8349 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8350 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8351 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8352 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8353 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8354 [caption_ setTextColor:[UIColor whiteColor]];
8355 [caption_ setBackgroundColor:[UIColor clearColor]];
8356 [caption_ setShadowColor:[UIColor blackColor]];
8357 [caption_ setTextAlignment:UITextAlignmentCenter];
8358 [[self view] addSubview:caption_];
8361 statusrect.size.width = [[self view] frame].size.width;
8362 statusrect.size.height = 30.0f;
8363 statusrect.origin.x = 0;
8364 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8365 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8366 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8367 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8368 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8369 [status_ setTextColor:[UIColor whiteColor]];
8370 [status_ setBackgroundColor:[UIColor clearColor]];
8371 [status_ setShadowColor:[UIColor blackColor]];
8372 [status_ setTextAlignment:UITextAlignmentCenter];
8373 [[self view] addSubview:status_];
8379 @interface CYURLCache : SDURLCache {
8384 @implementation CYURLCache
8386 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8389 else if ([event isEqualToString:@"no-cache"])
8391 else if ([event isEqualToString:@"store"])
8393 else if ([event isEqualToString:@"invalid"])
8395 else if ([event isEqualToString:@"memory"])
8397 else if ([event isEqualToString:@"disk"])
8399 else if ([event isEqualToString:@"miss"])
8402 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8408 @interface Cydia : UIApplication <
8409 ConfirmationControllerDelegate,
8412 UINavigationControllerDelegate,
8413 UITabBarControllerDelegate
8415 _H<UIWindow> window_;
8416 _H<CYTabBarController> tabbar_;
8417 _H<CydiaLoadingViewController> emulated_;
8419 _H<NSMutableArray> essential_;
8420 _H<NSMutableArray> broken_;
8422 Database *database_;
8424 _H<NSURL> starturl_;
8429 _H<StashController> stash_;
8438 @implementation Cydia
8440 - (void) beginUpdate {
8441 [tabbar_ beginUpdate];
8445 return [tabbar_ updating];
8449 if ([broken_ count] != 0) {
8450 int count = [broken_ count];
8452 UIAlertView *alert = [[[UIAlertView alloc]
8453 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8454 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8456 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8458 UCLocalize("TEMPORARY_IGNORE"),
8462 [alert setContext:@"fixhalf"];
8463 [alert setNumberOfRows:2];
8465 } else if (!Ignored_ && [essential_ count] != 0) {
8466 int count = [essential_ count];
8468 UIAlertView *alert = [[[UIAlertView alloc]
8469 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8470 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8472 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8474 UCLocalize("UPGRADE_ESSENTIAL"),
8475 UCLocalize("COMPLETE_UPGRADE"),
8479 [alert setContext:@"upgrade"];
8484 - (void) _saveConfig {
8490 NSString *error(nil);
8492 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8494 NSError *error(nil);
8495 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8496 NSLog(@"failure to save metadata data: %@", error);
8501 NSLog(@"failure to serialize metadata: %@", error);
8506 // Navigation controller for the queuing badge.
8507 - (UINavigationController *) queueNavigationController {
8508 NSArray *controllers = [tabbar_ viewControllers];
8509 return [controllers objectAtIndex:3];
8512 - (void) unloadData {
8513 [tabbar_ unloadData];
8516 - (void) _updateData {
8521 UINavigationController *navigation = [self queueNavigationController];
8523 id queuedelegate = nil;
8524 if ([[navigation viewControllers] count] > 0)
8525 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8527 [queuedelegate queueStatusDidChange];
8528 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8531 - (void) _refreshIfPossible:(NSDate *)update {
8532 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8534 bool recently = false;
8535 if (update != nil) {
8536 NSTimeInterval interval([update timeIntervalSinceNow]);
8537 if (interval <= 0 && interval > -(15*60))
8541 // Don't automatic refresh if:
8542 // - We already refreshed recently.
8543 // - We already auto-refreshed this launch.
8544 // - Auto-refresh is disabled.
8545 if (recently || loaded_ || ManualRefresh) {
8546 // If we are cancelling, we need to make sure it knows it's already loaded.
8549 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8551 // We are going to load, so remember that.
8554 SCNetworkReachabilityFlags flags; {
8555 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8556 SCNetworkReachabilityGetFlags(reachability, &flags);
8557 CFRelease(reachability);
8560 // XXX: this elaborate mess is what Apple is using to determine this? :(
8561 // XXX: do we care if the user has to intervene? maybe that's ok?
8563 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8564 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8565 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8566 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8567 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8568 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8572 // If we can reach the server, auto-refresh!
8574 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8580 - (void) refreshIfPossible {
8581 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8584 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8585 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8586 [hud setText:UCLocalize("RELOADING_DATA")];
8588 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8591 [self removeProgressHUD:hud];
8595 [essential_ removeAllObjects];
8596 [broken_ removeAllObjects];
8598 NSArray *packages([database_ packages]);
8599 for (Package *package in packages) {
8601 [broken_ addObject:package];
8602 if ([package upgradableAndEssential:NO]) {
8603 if ([package essential])
8604 [essential_ addObject:package];
8609 NSLog(@"changes:#%u", changes);
8611 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8614 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8615 [changesItem setBadgeValue:badge];
8616 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8617 [self setApplicationIconBadgeNumber:changes];
8620 [changesItem setBadgeValue:nil];
8621 [changesItem setAnimatedBadge:NO];
8622 [self setApplicationIconBadgeNumber:0];
8627 [self refreshIfPossible];
8630 - (void) updateData {
8639 @synchronized (self) {
8640 [self _reloadDataWithInvocation:nil];
8644 - (void) disemulate {
8645 if (emulated_ == nil)
8648 [window_ addSubview:[tabbar_ view]];
8649 [[emulated_ view] removeFromSuperview];
8651 [window_ setUserInteractionEnabled:YES];
8654 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8655 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8657 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8659 UIViewController *parent;
8660 if (emulated_ == nil)
8669 [parent presentModalViewController:navigation animated:YES];
8672 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8673 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8675 if (navigation != nil)
8676 [navigation pushViewController:progress animated:YES];
8678 [self presentModalViewController:progress force:YES];
8680 [progress invoke:invocation withTitle:title];
8684 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8685 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8688 - (void) repairWithInvocation:(NSInvocation *)invocation {
8690 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8694 - (void) repairWithSelector:(SEL)selector {
8695 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8701 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8702 _assert(file != NULL);
8704 for (NSString *key in [Sources_ allKeys]) {
8705 NSDictionary *source([Sources_ objectForKey:key]);
8707 fprintf(file, "%s %s %s\n",
8708 [[source objectForKey:@"Type"] UTF8String],
8709 [[source objectForKey:@"URI"] UTF8String],
8710 [[source objectForKey:@"Distribution"] UTF8String]
8716 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8721 - (void) addTrivialSource:(NSString *)href {
8722 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8725 @"./", @"Distribution",
8726 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8731 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8732 @synchronized (self) {
8733 [self _reloadDataWithInvocation:invocation];
8737 - (void) reloadData {
8738 [self reloadDataWithInvocation:nil];
8742 pkgProblemResolver *resolver = [database_ resolver];
8744 resolver->InstallProtect();
8745 if (!resolver->Resolve(true))
8750 // XXX: this is a really crappy way of doing this.
8751 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8752 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8753 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8754 if ([tabbar_ updating])
8755 [tabbar_ cancelUpdate];
8757 if (![database_ prepare])
8760 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8761 [page setDelegate:self];
8762 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8765 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8766 [tabbar_ presentModalViewController:confirm_ animated:YES];
8772 @synchronized (self) {
8777 - (void) clearPackage:(Package *)package {
8778 @synchronized (self) {
8785 - (void) installPackages:(NSArray *)packages {
8786 @synchronized (self) {
8787 for (Package *package in packages)
8794 - (void) installPackage:(Package *)package {
8795 @synchronized (self) {
8802 - (void) removePackage:(Package *)package {
8803 @synchronized (self) {
8810 - (void) distUpgrade {
8811 @synchronized (self) {
8812 if (![database_ upgrade])
8818 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8821 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8826 - (void) showSettings {
8827 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8830 - (void) retainNetworkActivityIndicator {
8831 if (activity_++ == 0)
8832 [self setNetworkActivityIndicatorVisible:YES];
8835 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8839 - (void) releaseNetworkActivityIndicator {
8840 if (--activity_ == 0)
8841 [self setNetworkActivityIndicatorVisible:NO];
8844 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8849 - (void) cancelAndClear:(bool)clear {
8850 @synchronized (self) {
8862 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8863 NSString *context([alert context]);
8865 if ([context isEqualToString:@"conffile"]) {
8866 FILE *input = [database_ input];
8867 if (button == [alert cancelButtonIndex])
8868 fprintf(input, "N\n");
8869 else if (button == [alert firstOtherButtonIndex])
8870 fprintf(input, "Y\n");
8873 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8874 } else if ([context isEqualToString:@"fixhalf"]) {
8875 if (button == [alert cancelButtonIndex]) {
8876 @synchronized (self) {
8877 for (Package *broken in (id) broken_) {
8880 NSString *id = [broken id];
8881 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8882 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8883 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8884 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8890 } else if (button == [alert firstOtherButtonIndex]) {
8891 [broken_ removeAllObjects];
8895 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8896 } else if ([context isEqualToString:@"upgrade"]) {
8897 if (button == [alert firstOtherButtonIndex]) {
8898 @synchronized (self) {
8899 for (Package *essential in (id) essential_)
8900 [essential install];
8905 } else if (button == [alert firstOtherButtonIndex] + 1) {
8907 } else if (button == [alert cancelButtonIndex]) {
8911 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8915 - (void) system:(NSString *)command {
8916 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8919 system([command UTF8String]);
8925 - (void) applicationWillSuspend {
8927 [super applicationWillSuspend];
8930 - (BOOL) isSafeToSuspend {
8933 NSLog(@"isSafeToSuspend: locked_ != 0");
8938 // Use external process status API internally.
8939 // This is probably a really bad idea.
8940 // XXX: what is the point of this? does this solve anything at all?
8941 uint64_t status = 0;
8943 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8944 notify_get_state(notify_token, &status);
8945 notify_cancel(notify_token);
8950 NSLog(@"isSafeToSuspend: status != 0");
8956 NSLog(@"isSafeToSuspend: -> true");
8961 - (void) applicationSuspend:(__GSEvent *)event {
8962 if ([self isSafeToSuspend])
8963 [super applicationSuspend:event];
8966 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8967 if ([self isSafeToSuspend])
8968 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8971 - (void) _setSuspended:(BOOL)value {
8972 if ([self isSafeToSuspend])
8973 [super _setSuspended:value];
8976 - (UIProgressHUD *) addProgressHUD {
8977 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8978 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8980 [window_ setUserInteractionEnabled:NO];
8982 UIViewController *target(tabbar_);
8983 if (UIViewController *modal = [target modalViewController])
8986 UIView *view([target view]);
8987 [view addSubview:hud];
8995 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8998 [hud removeFromSuperview];
8999 [window_ setUserInteractionEnabled:YES];
9002 - (CyteViewController *) pageForPackage:(NSString *)name {
9003 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9006 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9007 NSString *scheme([[url scheme] lowercaseString]);
9008 if ([[url absoluteString] length] <= [scheme length] + 3)
9010 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9011 NSArray *components([path pathComponents]);
9013 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9014 return [self pageForPackage:[components objectAtIndex:1]];
9016 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9019 NSString *base([components objectAtIndex:0]);
9021 CyteViewController *controller = nil;
9023 if ([base isEqualToString:@"url"]) {
9024 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9025 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9026 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9027 } else if (!external && [components count] == 1) {
9028 if ([base isEqualToString:@"manage"]) {
9029 controller = [[[ManageController alloc] init] autorelease];
9032 if ([base isEqualToString:@"sources"]) {
9033 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9036 if ([base isEqualToString:@"home"]) {
9037 controller = [[[HomeController alloc] init] autorelease];
9040 if ([base isEqualToString:@"sections"]) {
9041 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9044 if ([base isEqualToString:@"search"]) {
9045 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9048 if ([base isEqualToString:@"changes"]) {
9049 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9052 if ([base isEqualToString:@"installed"]) {
9053 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9055 } else if ([components count] == 2) {
9056 NSString *argument = [components objectAtIndex:1];
9058 if ([base isEqualToString:@"package"]) {
9059 controller = [self pageForPackage:argument];
9062 if (!external && [base isEqualToString:@"search"]) {
9063 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9066 if (!external && [base isEqualToString:@"sections"]) {
9067 if ([argument isEqualToString:@"all"])
9069 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9072 if (!external && [base isEqualToString:@"sources"]) {
9073 if ([argument isEqualToString:@"add"]) {
9074 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9075 [(SourcesController *)controller showAddSourcePrompt];
9077 Source *source = [database_ sourceWithKey:argument];
9078 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9082 if (!external && [base isEqualToString:@"launch"]) {
9083 [self launchApplicationWithIdentifier:argument suspended:NO];
9086 } else if (!external && [components count] == 3) {
9087 NSString *arg1 = [components objectAtIndex:1];
9088 NSString *arg2 = [components objectAtIndex:2];
9090 if ([base isEqualToString:@"package"]) {
9091 if ([arg2 isEqualToString:@"settings"]) {
9092 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9093 } else if ([arg2 isEqualToString:@"files"]) {
9094 if (Package *package = [database_ packageWithName:arg1]) {
9095 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9096 [(FileTable *)controller setPackage:package];
9102 [controller setDelegate:self];
9106 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9107 CyteViewController *page([self pageForURL:url forExternal:external]);
9110 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9111 [nav setViewControllers:[NSArray arrayWithObject:page]];
9112 [tabbar_ setUnselectedViewController:nav];
9118 - (void) applicationOpenURL:(NSURL *)url {
9119 [super applicationOpenURL:url];
9124 [self openCydiaURL:url forExternal:YES];
9127 - (void) applicationWillResignActive:(UIApplication *)application {
9128 // Stop refreshing if you get a phone call or lock the device.
9129 if ([tabbar_ updating])
9130 [tabbar_ cancelUpdate];
9132 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9133 [super applicationWillResignActive:application];
9136 - (void) applicationWillTerminate:(UIApplication *)application {
9138 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9139 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9140 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9145 - (void) setConfigurationData:(NSString *)data {
9146 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9148 if (!conffile_r(data)) {
9149 lprintf("E:invalid conffile\n");
9153 NSString *ofile = conffile_r[1];
9154 //NSString *nfile = conffile_r[2];
9156 UIAlertView *alert = [[[UIAlertView alloc]
9157 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9158 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9160 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9162 UCLocalize("ACCEPT_NEW_COPY"),
9163 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9167 [alert setContext:@"conffile"];
9168 [alert setNumberOfRows:2];
9172 - (void) addStashController {
9174 stash_ = [[[StashController alloc] init] autorelease];
9175 [window_ addSubview:[stash_ view]];
9178 - (void) removeStashController {
9179 [[stash_ view] removeFromSuperview];
9185 [self setIdleTimerDisabled:YES];
9187 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9188 UpdateExternalStatus(1);
9189 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9190 UpdateExternalStatus(0);
9192 [self removeStashController];
9194 if (ExecFork() == 0) {
9195 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9196 perror("launchctl stop");
9200 - (void) setupViewControllers {
9201 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9203 NSMutableArray *items([NSMutableArray arrayWithObjects:
9204 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9205 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9206 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9207 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9211 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9212 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9214 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9217 NSMutableArray *controllers([NSMutableArray array]);
9218 for (UITabBarItem *item in items) {
9219 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9220 [controller setTabBarItem:item];
9221 [controllers addObject:controller];
9223 [tabbar_ setViewControllers:controllers];
9225 [tabbar_ setUpdateDelegate:self];
9228 - (void) applicationDidFinishLaunching:(id)unused {
9230 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9231 [self setApplicationSupportsShakeToEdit:NO];
9233 @synchronized (HostConfig_) {
9234 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9237 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9238 initWithMemoryCapacity:524288
9239 diskCapacity:10485760
9240 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9243 [CydiaWebViewController _initialize];
9245 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9247 // this would disallow http{,s} URLs from accessing this data
9248 //[WebView registerURLSchemeAsLocal:@"cydia"];
9250 Font12_ = [UIFont systemFontOfSize:12];
9251 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9252 Font14_ = [UIFont systemFontOfSize:14];
9253 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9254 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9256 essential_ = [NSMutableArray arrayWithCapacity:4];
9257 broken_ = [NSMutableArray arrayWithCapacity:4];
9259 // XXX: I really need this thing... like, seriously... I'm sorry
9260 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9262 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9263 [window_ orderFront:self];
9264 [window_ makeKey:self];
9265 [window_ setHidden:NO];
9268 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9269 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9270 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9271 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9272 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9273 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9274 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9275 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9276 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9279 [self addStashController];
9280 // XXX: this would be much cleaner as a yieldToSelector:
9281 // that way the removeStashController could happen right here inline
9282 // we also could no longer require the useless stash_ field anymore
9283 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9287 database_ = [Database sharedInstance];
9288 [database_ setDelegate:self];
9290 [window_ setUserInteractionEnabled:NO];
9291 [self setupViewControllers];
9293 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9294 [window_ addSubview:[emulated_ view]];
9296 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9300 - (NSArray *) defaultStartPages {
9301 NSMutableArray *standard = [NSMutableArray array];
9302 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9303 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9304 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9306 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9308 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9309 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9311 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9318 [window_ setUserInteractionEnabled:YES];
9319 [self showSettings];
9322 if ([emulated_ modalViewController] != nil)
9323 [emulated_ dismissModalViewControllerAnimated:YES];
9324 [window_ setUserInteractionEnabled:NO];
9332 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9333 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9334 int standardIndex = 0;
9335 NSArray *standard = [self defaultStartPages];
9342 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9343 if (valid && closed != nil) {
9344 NSTimeInterval interval([closed timeIntervalSinceNow]);
9345 // XXX: Is 15 minutes the optimal time here?
9346 if (interval > 0 && interval <= -(15*60))
9350 if (valid && [saved count] != [standard count])
9354 for (unsigned int i = 0; i < [standard count]; i++) {
9355 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9356 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9357 // but it's good enough for now.
9358 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9365 NSArray *items = nil;
9367 [tabbar_ setSelectedIndex:savedIndex];
9370 [tabbar_ setSelectedIndex:standardIndex];
9374 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9375 NSArray *stack = [items objectAtIndex:tab];
9376 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9377 NSMutableArray *current = [NSMutableArray array];
9379 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9380 NSString *addr = [stack objectAtIndex:nav];
9381 NSURL *url = [NSURL URLWithString:addr];
9382 CyteViewController *page = [self pageForURL:url forExternal:NO];
9384 [current addObject:page];
9387 [navigation setViewControllers:current];
9390 // (Try to) show the startup URL.
9391 if (starturl_ != nil) {
9392 [self openCydiaURL:starturl_ forExternal:NO];
9397 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9398 if (item != nil && IsWildcat_) {
9399 [sheet showFromBarButtonItem:item animated:YES];
9401 [sheet showInView:window_];
9405 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9406 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9407 [progress setTitle:task];
9408 [progress addProgressEvent:event];
9411 - (void) addProgressEventForTask:(NSArray *)data {
9412 CydiaProgressEvent *event([data objectAtIndex:0]);
9413 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9414 [self addProgressEvent:event forTask:task];
9417 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9418 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9424 id Alloc_(id self, SEL selector) {
9425 id object = alloc_(self, selector);
9426 lprintf("[%s]A-%p\n", self->isa->name, object);
9431 id Dealloc_(id self, SEL selector) {
9432 id object = dealloc_(self, selector);
9433 lprintf("[%s]D-%p\n", self->isa->name, object);
9437 Class $WebDefaultUIKitDelegate;
9439 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9440 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9441 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9442 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9445 static NSSet *MobilizedFiles_;
9447 static NSURL *MobilizeURL(NSURL *url) {
9448 NSString *path([url path]);
9449 if ([path hasPrefix:@"/var/root/"]) {
9450 NSString *file([path substringFromIndex:10]);
9451 if ([MobilizedFiles_ containsObject:file])
9452 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9458 Class $CFXPreferencesPropertyListSource;
9459 @class CFXPreferencesPropertyListSource;
9461 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9462 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9463 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9464 url = MobilizeURL(url);
9465 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9466 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9472 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9473 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9474 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9475 url = MobilizeURL(url);
9476 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9477 //NSLog(@"%@ %@", [url absoluteString], value);
9483 Class $NSURLConnection;
9485 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9486 NSMutableURLRequest *copy([request mutableCopy]);
9488 NSURL *url([copy URL]);
9489 NSString *host([url host]);
9490 NSString *scheme([[url scheme] lowercaseString]);
9492 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9494 @synchronized (HostConfig_) {
9495 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9496 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9497 [copy setHTTPShouldUsePipelining:YES];
9500 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9504 int main(int argc, char *argv[]) {
9505 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9509 UpdateExternalStatus(0);
9511 if (Class $UIDevice = objc_getClass("UIDevice")) {
9512 UIDevice *device([$UIDevice currentDevice]);
9513 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9517 UIScreen *screen([UIScreen mainScreen]);
9518 if ([screen respondsToSelector:@selector(scale)])
9519 ScreenScale_ = [screen scale];
9523 UIDevice *device([UIDevice currentDevice]);
9524 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9527 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9528 if (idiom == UIUserInterfaceIdiomPhone)
9530 else if (idiom == UIUserInterfaceIdiomPad)
9533 NSLog(@"unknown UIUserInterfaceIdiom!");
9536 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9538 HostConfig_ = [[[NSObject alloc] init] autorelease];
9539 @synchronized (HostConfig_) {
9540 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9541 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9544 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9546 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9548 MobilizedFiles_ = [NSMutableSet setWithObjects:
9549 @"Library/Preferences/com.apple.Accessibility.plist",
9550 @"Library/Preferences/com.apple.preferences.sounds.plist",
9553 /* Library Hacks {{{ */
9554 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9556 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9558 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9559 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9560 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9561 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9564 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9565 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9566 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9567 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9570 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9571 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9572 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9573 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9574 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9577 $NSURLConnection = objc_getClass("NSURLConnection");
9578 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9579 if (NSURLConnection$init$ != NULL) {
9580 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9581 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9584 /* Set Locale {{{ */
9585 Locale_ = CFLocaleCopyCurrent();
9586 Languages_ = [NSLocale preferredLanguages];
9588 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9589 //NSLog(@"%@", [Languages_ description]);
9592 if (Locale_ != NULL)
9593 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9594 else if (Languages_ != nil && [Languages_ count] != 0)
9595 lang = [[Languages_ objectAtIndex:0] UTF8String];
9597 // XXX: consider just setting to C and then falling through?
9601 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9602 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9605 NSLog(@"Setting Language: %s", lang);
9608 setenv("LANG", lang, true);
9609 std::setlocale(LC_ALL, lang);
9613 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9615 /* Parse Arguments {{{ */
9616 bool substrate(false);
9622 for (int argi(1); argi != argc; ++argi)
9623 if (strcmp(argv[argi], "--") == 0) {
9625 argv[argi] = argv[0];
9631 for (int argi(1); argi != arge; ++argi)
9632 if (strcmp(args[argi], "--substrate") == 0)
9635 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9639 App_ = [[NSBundle mainBundle] bundlePath];
9645 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9646 alloc_ = alloc->method_imp;
9647 alloc->method_imp = (IMP) &Alloc_;*/
9649 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9650 dealloc_ = dealloc->method_imp;
9651 dealloc->method_imp = (IMP) &Dealloc_;*/
9653 /* System Information {{{ */
9657 size = sizeof(maxproc);
9658 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9659 perror("sysctlbyname(\"kern.maxproc\", ?)");
9660 else if (maxproc < 64) {
9662 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9663 perror("sysctlbyname(\"kern.maxproc\", #)");
9666 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9667 char *osversion = new char[size];
9668 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9669 perror("sysctlbyname(\"kern.osversion\", ?)");
9671 System_ = [NSString stringWithUTF8String:osversion];
9673 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9674 char *machine = new char[size];
9675 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9676 perror("sysctlbyname(\"hw.machine\", ?)");
9680 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9681 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9682 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9684 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9686 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9687 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9688 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9690 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9691 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9692 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9694 if (mcc != NULL && mnc != NULL)
9695 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9702 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9703 Build_ = [system objectForKey:@"ProductBuildVersion"];
9704 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9705 Product_ = [info objectForKey:@"SafariProductVersion"];
9706 Safari_ = [info objectForKey:@"CFBundleVersion"];
9709 /* Load Database {{{ */
9711 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9713 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9715 if (Metadata_ == NULL)
9716 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9718 Settings_ = [Metadata_ objectForKey:@"Settings"];
9720 Packages_ = [Metadata_ objectForKey:@"Packages"];
9721 Sections_ = [Metadata_ objectForKey:@"Sections"];
9722 Sources_ = [Metadata_ objectForKey:@"Sources"];
9724 Token_ = [Metadata_ objectForKey:@"Token"];
9727 if (Settings_ != nil)
9728 Role_ = [Settings_ objectForKey:@"Role"];
9730 if (Sections_ == nil) {
9731 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9732 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9735 if (Sources_ == nil) {
9736 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9737 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9742 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9745 if (Packages_ != nil) {
9747 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9751 [Metadata_ removeObjectForKey:@"Packages"];
9757 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9759 #define MobileSubstrate_(name) \
9760 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9761 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9762 if (handle == NULL) \
9763 NSLog(@"%s", dlerror()); \
9766 MobileSubstrate_(Activator)
9767 MobileSubstrate_(libstatusbar)
9768 MobileSubstrate_(SimulatedKeyEvents)
9769 MobileSubstrate_(WinterBoard)
9771 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9772 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9774 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9776 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9777 unlink("/tmp/.cydia.fw");
9779 } else if (access("/User", F_OK) != 0 || version < 4) {
9782 system("/usr/libexec/cydia/firmware.sh");
9786 _assert([[NSFileManager defaultManager]
9787 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9788 withIntermediateDirectories:YES
9793 if (access("/tmp/cydia.chk", F_OK) == 0) {
9794 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9795 _assert(errno == ENOENT);
9796 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9797 _assert(errno == ENOENT);
9800 /* APT Initialization {{{ */
9801 _assert(pkgInitConfig(*_config));
9802 _assert(pkgInitSystem(*_config, _system));
9805 _config->Set("APT::Acquire::Translation", lang);
9807 // XXX: this timeout might be important :(
9808 //_config->Set("Acquire::http::Timeout", 15);
9810 _config->Set("Acquire::http::MaxParallel", 3);
9812 /* Color Choices {{{ */
9813 space_ = CGColorSpaceCreateDeviceRGB();
9815 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9816 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9817 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9818 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9819 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9820 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9821 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9822 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9823 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9825 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9826 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9828 /* UIKit Configuration {{{ */
9829 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9830 if ($GSFontSetUseLegacyFontMetrics != NULL)
9831 $GSFontSetUseLegacyFontMetrics(YES);
9833 // XXX: I have a feeling this was important
9834 //UIKeyboardDisableAutomaticAppearance();
9837 Colon_ = UCLocalize("COLON_DELIMITED");
9838 Elision_ = UCLocalize("ELISION");
9839 Error_ = UCLocalize("ERROR");
9840 Warning_ = UCLocalize("WARNING");
9843 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9845 CGColorSpaceRelease(space_);