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_;
707 static _H<NSMutableSet> CachedURLs_;
709 static NSString *kCydiaProgressEventTypeError = @"Error";
710 static NSString *kCydiaProgressEventTypeInformation = @"Information";
711 static NSString *kCydiaProgressEventTypeStatus = @"Status";
712 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
715 /* Display Helpers {{{ */
716 inline float Interpolate(float begin, float end, float fraction) {
717 return (end - begin) * fraction + begin;
720 static _finline const char *StripVersion_(const char *version) {
721 const char *colon(strchr(version, ':'));
722 return colon == NULL ? version : colon + 1;
725 NSString *LocalizeSection(NSString *section) {
726 static Pcre title_r("^(.*?) \\((.*)\\)$");
727 if (title_r(section)) {
728 NSString *parent(title_r[1]);
729 NSString *child(title_r[2]);
731 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
732 LocalizeSection(parent),
733 LocalizeSection(child)
737 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
740 NSString *Simplify(NSString *title) {
741 const char *data = [title UTF8String];
742 size_t size = [title length];
744 static Pcre square_r("^\\[(.*)\\]$");
745 if (square_r(data, size))
746 return Simplify(square_r[1]);
748 static Pcre paren_r("^\\((.*)\\)$");
749 if (paren_r(data, size))
750 return Simplify(paren_r[1]);
752 static Pcre title_r("^(.*?) \\((.*)\\)$");
753 if (title_r(data, size))
754 return Simplify(title_r[1]);
760 NSString *GetLastUpdate() {
761 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
764 return UCLocalize("NEVER_OR_UNKNOWN");
766 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
767 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
769 CFRelease(formatter);
771 return [(NSString *) formatted autorelease];
774 bool isSectionVisible(NSString *section) {
775 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
776 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
777 return hidden == nil || ![hidden boolValue];
780 static NSObject *CYIOGetValue(const char *path, NSString *property) {
781 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
782 if (entry == MACH_PORT_NULL)
785 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
786 IOObjectRelease(entry);
790 return [(id) value autorelease];
793 static NSString *CYHex(NSData *data, bool reverse = false) {
797 size_t length([data length]);
798 uint8_t bytes[length];
799 [data getBytes:bytes];
801 char string[length * 2 + 1];
802 for (size_t i(0); i != length; ++i)
803 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
805 return [NSString stringWithUTF8String:string];
810 /* Delegate Prototypes {{{ */
813 @class CydiaProgressEvent;
815 @protocol DatabaseDelegate
816 - (void) repairWithSelector:(SEL)selector;
817 - (void) setConfigurationData:(NSString *)data;
818 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
821 @class CYPackageController;
823 @protocol CydiaDelegate
824 - (void) retainNetworkActivityIndicator;
825 - (void) releaseNetworkActivityIndicator;
826 - (void) clearPackage:(Package *)package;
827 - (void) installPackage:(Package *)package;
828 - (void) installPackages:(NSArray *)packages;
829 - (void) removePackage:(Package *)package;
830 - (void) beginUpdate;
832 - (void) distUpgrade;
836 - (void) addTrivialSource:(NSString *)href;
837 - (void) showSettings;
838 - (UIProgressHUD *) addProgressHUD;
839 - (void) removeProgressHUD:(UIProgressHUD *)hud;
840 - (CyteViewController *) pageForPackage:(NSString *)name;
841 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
842 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
846 /* Status Delegation {{{ */
848 public pkgAcquireStatus
851 _transient NSObject<ProgressDelegate> *delegate_;
861 void setDelegate(NSObject<ProgressDelegate> *delegate) {
862 delegate_ = delegate;
865 NSObject<ProgressDelegate> *getDelegate() const {
869 virtual bool MediaChange(std::string media, std::string drive) {
873 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
876 virtual void Fetch(pkgAcquire::ItemDesc &item) {
877 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
878 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
879 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
882 virtual void Done(pkgAcquire::ItemDesc &item) {
885 virtual void Fail(pkgAcquire::ItemDesc &item) {
887 item.Owner->Status == pkgAcquire::Item::StatIdle ||
888 item.Owner->Status == pkgAcquire::Item::StatDone
892 std::string &error(item.Owner->ErrorText);
896 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
897 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
900 virtual bool Pulse(pkgAcquire *Owner) {
901 bool value = pkgAcquireStatus::Pulse(Owner);
904 double(CurrentBytes + CurrentItems) /
905 double(TotalBytes + TotalItems)
908 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
909 [NSNumber numberWithDouble:percent], @"Percent",
911 [NSNumber numberWithDouble:CurrentBytes], @"Current",
912 [NSNumber numberWithDouble:TotalBytes], @"Total",
913 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
914 nil] waitUntilDone:YES];
916 if (value && ![delegate_ isProgressCancelled])
924 _finline bool WasCancelled() const {
928 virtual void Start() {
929 pkgAcquireStatus::Start();
930 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
933 virtual void Stop() {
934 pkgAcquireStatus::Stop();
935 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
936 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
940 /* Database Interface {{{ */
941 typedef std::map< unsigned long, _H<Source> > SourceMap;
943 @interface Database : NSObject {
950 pkgDepCache::Policy *policy_;
951 pkgRecords *records_;
952 pkgProblemResolver *resolver_;
953 pkgAcquire *fetcher_;
955 SPtr<pkgPackageManager> manager_;
956 pkgSourceList *list_;
958 SourceMap sourceMap_;
959 _H<NSMutableArray> sourceList_;
961 CFMutableArrayRef packages_;
963 _transient NSObject<DatabaseDelegate> *delegate_;
964 _transient NSObject<ProgressDelegate> *progress_;
972 std::map<const char *, _H<NSString> > sections_;
975 + (Database *) sharedInstance;
978 - (void) _readCydia:(NSNumber *)fd;
979 - (void) _readStatus:(NSNumber *)fd;
980 - (void) _readOutput:(NSNumber *)fd;
984 - (Package *) packageWithName:(NSString *)name;
986 - (pkgCacheFile &) cache;
987 - (pkgDepCache::Policy *) policy;
988 - (pkgRecords *) records;
989 - (pkgProblemResolver *) resolver;
990 - (pkgAcquire &) fetcher;
991 - (pkgSourceList &) list;
992 - (NSArray *) packages;
993 - (NSArray *) sources;
994 - (Source *) sourceWithKey:(NSString *)key;
995 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1003 - (void) updateWithStatus:(Status &)status;
1005 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1007 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1008 - (NSObject<ProgressDelegate> *) progressDelegate;
1010 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1012 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1016 /* ProgressEvent Implementation {{{ */
1017 @implementation CydiaProgressEvent
1019 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1020 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1023 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1024 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1025 [event setPackage:package];
1029 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1030 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1032 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1033 NSArray *fields([description componentsSeparatedByString:@" "]);
1034 [event setItem:fields];
1036 if ([fields count] > 3) {
1037 [event setPackage:[fields objectAtIndex:2]];
1038 [event setVersion:[fields objectAtIndex:3]];
1041 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1046 + (NSArray *) _attributeKeys {
1047 return [NSArray arrayWithObjects:
1057 - (NSArray *) attributeKeys {
1058 return [[self class] _attributeKeys];
1061 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1062 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1065 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1066 if ((self = [super init]) != nil) {
1072 - (NSString *) message {
1076 - (NSString *) type {
1080 - (NSArray *) item {
1081 return (id) item_ ?: [NSNull null];
1084 - (void) setItem:(NSArray *)item {
1088 - (NSString *) package {
1089 return (id) package_ ?: [NSNull null];
1092 - (void) setPackage:(NSString *)package {
1096 - (NSString *) url {
1097 return (id) url_ ?: [NSNull null];
1100 - (void) setURL:(NSString *)url {
1104 - (void) setVersion:(NSString *)version {
1108 - (NSString *) version {
1109 return (id) version_ ?: [NSNull null];
1112 - (NSString *) compound:(NSString *)value {
1114 NSString *mode(nil); {
1115 NSString *type([self type]);
1116 if ([type isEqualToString:kCydiaProgressEventTypeError])
1117 mode = UCLocalize("ERROR");
1118 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1119 mode = UCLocalize("WARNING");
1123 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1129 - (NSString *) compoundMessage {
1130 return [self compound:[self message]];
1133 - (NSString *) compoundTitle {
1136 if (package_ == nil)
1138 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1139 title = [package name];
1143 return [self compound:title];
1149 // Cytore Definitions {{{
1150 struct PackageValue :
1153 Cytore::Offset<PackageValue> next_;
1155 uint32_t index_ : 23;
1156 uint32_t subscribed_ : 1;
1173 Cytore::Offset<PackageValue> packages_[1 << 16];
1176 static Cytore::File<MetaValue> MetaFile_;
1178 // Cytore Helper Functions {{{
1179 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1180 SplitHash nhash = { hashlittle(name, length) };
1182 PackageValue *metadata;
1184 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1185 offset: if (offset->IsNull()) {
1186 *offset = MetaFile_.New<PackageValue>(length + 1);
1187 metadata = &MetaFile_.Get(*offset);
1189 if (metadata == NULL) {
1193 metadata = new PackageValue();
1194 memset(metadata, 0, sizeof(*metadata));
1197 memcpy(metadata->name_, name, length + 1);
1198 metadata->nhash_ = nhash.u16[1];
1200 metadata = &MetaFile_.Get(*offset);
1202 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1203 offset = &metadata->next_;
1211 static void PackageImport(const void *key, const void *value, void *context) {
1212 bool &fail(*reinterpret_cast<bool *>(context));
1215 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1216 NSLog(@"failed to import package %@", key);
1220 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1221 NSDictionary *package((NSDictionary *) value);
1223 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1224 if ([subscribed boolValue] && !metadata->subscribed_)
1225 metadata->subscribed_ = true;
1227 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1228 time_t time([date timeIntervalSince1970]);
1229 if (metadata->first_ > time || metadata->first_ == 0)
1230 metadata->first_ = time;
1233 NSDate *date([package objectForKey:@"LastSeen"]);
1234 NSString *version([package objectForKey:@"LastVersion"]);
1236 if (date != nil && version != nil) {
1237 time_t time([date timeIntervalSince1970]);
1238 if (metadata->last_ < time || metadata->last_ == 0)
1239 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1240 size_t length(strlen(buffer));
1241 uint16_t vhash(hashlittle(buffer, length));
1243 size_t capped(std::min<size_t>(8, length));
1244 char *latest(buffer + length - capped);
1246 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1247 metadata->vhash_ = vhash;
1249 metadata->last_ = time;
1255 /* Source Class {{{ */
1256 @interface Source : NSObject {
1257 CYString depiction_;
1258 CYString description_;
1264 CYString distribution_;
1270 _H<NSString> authority_;
1272 CYString defaultIcon_;
1274 _H<NSDictionary> record_;
1278 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1280 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1282 - (NSString *) depictionForPackage:(NSString *)package;
1283 - (NSString *) supportForPackage:(NSString *)package;
1285 - (NSDictionary *) record;
1289 - (NSString *) distribution;
1290 - (NSString *) type;
1292 - (NSString *) base;
1295 - (NSString *) host;
1297 - (NSString *) name;
1298 - (NSString *) shortDescription;
1299 - (NSString *) label;
1300 - (NSString *) origin;
1301 - (NSString *) version;
1303 - (NSString *) defaultIcon;
1307 @implementation Source
1311 distribution_.clear();
1316 description_.clear();
1322 defaultIcon_.clear();
1329 + (NSArray *) _attributeKeys {
1330 return [NSArray arrayWithObjects:
1337 @"shortDescription",
1345 - (NSArray *) attributeKeys {
1346 return [[self class] _attributeKeys];
1349 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1350 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1353 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1356 trusted_ = index->IsTrusted();
1358 uri_.set(pool, index->GetURI());
1359 distribution_.set(pool, index->GetDist());
1360 type_.set(pool, index->GetType());
1362 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1363 if (dindex != NULL) {
1364 base_.set(pool, dindex->MetaIndexURI(""));
1367 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1370 pkgTagFile tags(&fd);
1372 pkgTagSection section;
1379 {"default-icon", &defaultIcon_},
1380 {"depiction", &depiction_},
1381 {"description", &description_},
1383 {"origin", &origin_},
1384 {"support", &support_},
1385 {"version", &version_},
1388 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1389 const char *start, *end;
1391 if (section.Find(names[i].name_, start, end)) {
1392 CYString &value(*names[i].value_);
1393 value.set(pool, start, end - start);
1399 record_ = [Sources_ objectForKey:[self key]];
1401 NSURL *url([NSURL URLWithString:uri_]);
1405 host_ = [host_ lowercaseString];
1410 authority_ = [url path];
1413 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1414 if ((self = [super init]) != nil) {
1415 [self setMetaIndex:index inPool:pool];
1419 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1420 NSDictionary *lhr = [self record];
1421 NSDictionary *rhr = [source record];
1424 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1426 NSString *lhs = [self name];
1427 NSString *rhs = [source name];
1429 if ([lhs length] != 0 && [rhs length] != 0) {
1430 unichar lhc = [lhs characterAtIndex:0];
1431 unichar rhc = [rhs characterAtIndex:0];
1433 if (isalpha(lhc) && !isalpha(rhc))
1434 return NSOrderedAscending;
1435 else if (!isalpha(lhc) && isalpha(rhc))
1436 return NSOrderedDescending;
1439 return [lhs compare:rhs options:LaxCompareOptions_];
1442 - (NSString *) depictionForPackage:(NSString *)package {
1443 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1446 - (NSString *) supportForPackage:(NSString *)package {
1447 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1450 - (NSDictionary *) record {
1458 - (NSString *) uri {
1462 - (NSString *) distribution {
1463 return distribution_;
1466 - (NSString *) type {
1470 - (NSString *) base {
1474 - (NSString *) key {
1475 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1478 - (NSString *) host {
1482 - (NSString *) name {
1483 return origin_.empty() ? (id) authority_ : origin_;
1486 - (NSString *) shortDescription {
1487 return description_;
1490 - (NSString *) label {
1491 return label_.empty() ? (id) authority_ : label_;
1494 - (NSString *) origin {
1498 - (NSString *) version {
1502 - (NSString *) defaultIcon {
1503 return defaultIcon_;
1508 /* CydiaOperation Class {{{ */
1509 @interface CydiaOperation : NSObject {
1510 _H<NSString> operator_;
1511 _H<NSString> value_;
1514 - (NSString *) operator;
1515 - (NSString *) value;
1519 @implementation CydiaOperation
1521 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1522 if ((self = [super init]) != nil) {
1523 operator_ = [NSString stringWithUTF8String:_operator];
1524 value_ = [NSString stringWithUTF8String:value];
1528 + (NSArray *) _attributeKeys {
1529 return [NSArray arrayWithObjects:
1535 - (NSArray *) attributeKeys {
1536 return [[self class] _attributeKeys];
1539 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1540 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1543 - (NSString *) operator {
1547 - (NSString *) value {
1553 /* CydiaClause Class {{{ */
1554 @interface CydiaClause : NSObject {
1555 _H<NSString> package_;
1556 _H<CydiaOperation> version_;
1559 - (NSString *) package;
1560 - (CydiaOperation *) version;
1564 @implementation CydiaClause
1566 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1567 if ((self = [super init]) != nil) {
1568 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1570 if (const char *version = dep.TargetVer())
1571 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1573 version_ = (id) [NSNull null];
1577 + (NSArray *) _attributeKeys {
1578 return [NSArray arrayWithObjects:
1584 - (NSArray *) attributeKeys {
1585 return [[self class] _attributeKeys];
1588 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1589 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1592 - (NSString *) package {
1596 - (CydiaOperation *) version {
1602 /* CydiaRelation Class {{{ */
1603 @interface CydiaRelation : NSObject {
1604 _H<NSString> relationship_;
1605 _H<NSMutableArray> clauses_;
1608 - (NSString *) relationship;
1609 - (NSArray *) clauses;
1613 @implementation CydiaRelation
1615 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1616 if ((self = [super init]) != nil) {
1617 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1618 clauses_ = [NSMutableArray arrayWithCapacity:8];
1620 pkgCache::DepIterator start;
1621 pkgCache::DepIterator end;
1622 dep.GlobOr(start, end); // ++dep
1625 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1627 // yes, seriously. (wtf?)
1635 + (NSArray *) _attributeKeys {
1636 return [NSArray arrayWithObjects:
1642 - (NSArray *) attributeKeys {
1643 return [[self class] _attributeKeys];
1646 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1647 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1650 - (NSString *) relationship {
1651 return relationship_;
1654 - (NSArray *) clauses {
1658 - (void) addClause:(CydiaClause *)clause {
1659 [clauses_ addObject:clause];
1664 /* Package Class {{{ */
1665 struct ParsedPackage {
1670 CYString depiction_;
1680 @interface Package : NSObject {
1683 uint32_t essential_ : 1;
1684 uint32_t obsolete_ : 1;
1685 uint32_t ignored_ : 1;
1691 _transient Database *database_;
1693 pkgCache::VerIterator version_;
1694 pkgCache::PkgIterator iterator_;
1695 pkgCache::VerFileIterator file_;
1701 CYString installed_;
1703 const char *section_;
1704 _transient NSString *section$_;
1708 PackageValue *metadata_;
1709 ParsedPackage *parsed_;
1711 _H<NSMutableArray> tags_;
1714 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1715 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1717 - (pkgCache::PkgIterator) iterator;
1720 - (NSString *) section;
1721 - (NSString *) simpleSection;
1723 - (NSString *) longSection;
1724 - (NSString *) shortSection;
1728 - (MIMEAddress *) maintainer;
1730 - (NSString *) longDescription;
1731 - (NSString *) shortDescription;
1734 - (PackageValue *) metadata;
1737 - (bool) subscribed;
1738 - (bool) setSubscribed:(bool)subscribed;
1742 - (NSString *) latest;
1743 - (NSString *) installed;
1744 - (BOOL) uninstalled;
1747 - (BOOL) upgradableAndEssential:(BOOL)essential;
1750 - (BOOL) unfiltered;
1754 - (BOOL) halfConfigured;
1755 - (BOOL) halfInstalled;
1757 - (NSString *) mode;
1760 - (NSString *) name;
1762 - (NSString *) homepage;
1763 - (NSString *) depiction;
1764 - (MIMEAddress *) author;
1766 - (NSString *) support;
1768 - (NSArray *) files;
1769 - (NSArray *) warnings;
1770 - (NSArray *) applications;
1772 - (Source *) source;
1775 - (BOOL) matches:(NSArray *)query;
1777 - (bool) hasSupportingRole;
1778 - (BOOL) hasTag:(NSString *)tag;
1779 - (NSString *) primaryPurpose;
1780 - (NSArray *) purposes;
1781 - (bool) isCommercial;
1783 - (void) setIndex:(size_t)index;
1785 - (CYString &) cyname;
1787 - (uint32_t) compareBySection:(NSArray *)sections;
1792 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1793 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1794 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1795 - (bool) isVisibleInSection:(NSString *)section;
1796 - (bool) isVisibleInSource:(Source *)source;
1800 uint32_t PackageChangesRadix(Package *self, void *) {
1805 uint32_t timestamp : 30;
1806 uint32_t ignored : 1;
1807 uint32_t upgradable : 1;
1811 bool upgradable([self upgradableAndEssential:YES]);
1812 value.bits.upgradable = upgradable ? 1 : 0;
1815 value.bits.timestamp = 0;
1816 value.bits.ignored = [self ignored] ? 0 : 1;
1817 value.bits.upgradable = 1;
1819 value.bits.timestamp = [self seen] >> 2;
1820 value.bits.ignored = 0;
1821 value.bits.upgradable = 0;
1824 return _not(uint32_t) - value.key;
1827 uint32_t PackagePrefixRadix(Package *self, void *context) {
1828 size_t offset(reinterpret_cast<size_t>(context));
1829 CYString &name([self cyname]);
1831 size_t size(name.size());
1834 char *text(name.data());
1837 if (!isdigit(text[0]))
1841 while (size != digits && isdigit(text[digits]))
1849 if (offset == 0 && zeros != 0) {
1850 memset(data, '0', zeros);
1851 memcpy(data + zeros, text, 4 - zeros);
1853 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1854 if (size <= offset - zeros)
1857 text += offset - zeros;
1858 size -= offset - zeros;
1861 memcpy(data, text, 4);
1863 memcpy(data, text, size);
1864 memset(data + size, 0, 4 - size);
1867 for (size_t i(0); i != 4; ++i)
1868 if (isalpha(data[i]))
1876 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1878 /* XXX: ntohl may be more honest */
1879 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1882 CYString &(*PackageName)(Package *self, SEL sel);
1884 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1885 _profile(PackageNameCompare)
1886 CYString &lhi(PackageName(lhs, @selector(cyname)));
1887 CYString &rhi(PackageName(rhs, @selector(cyname)));
1888 CFStringRef lhn(lhi), rhn(rhi);
1891 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1892 else if (rhn == NULL)
1893 return NSOrderedDescending;
1895 _profile(PackageNameCompare$NumbersLast)
1896 if (!lhi.empty() && !rhi.empty()) {
1897 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1898 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1899 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1900 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1901 return lha ? NSOrderedAscending : NSOrderedDescending;
1905 CFIndex length = CFStringGetLength(lhn);
1907 _profile(PackageNameCompare$Compare)
1908 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1913 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1914 return PackageNameCompare(*lhs, *rhs, context);
1917 struct PackageNameOrdering :
1918 std::binary_function<Package *, Package *, bool>
1920 _finline bool operator ()(Package *lhs, Package *rhs) const {
1921 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1925 @implementation Package
1927 - (NSString *) description {
1928 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1932 if (parsed_ != NULL)
1937 + (NSString *) webScriptNameForSelector:(SEL)selector {
1939 else if (selector == @selector(clear))
1941 else if (selector == @selector(getField:))
1943 else if (selector == @selector(hasTag:))
1945 else if (selector == @selector(install))
1947 else if (selector == @selector(remove))
1953 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1954 return [self webScriptNameForSelector:selector] == nil;
1957 + (NSArray *) _attributeKeys {
1958 return [NSArray arrayWithObjects:
1977 @"shortDescription",
1990 - (NSArray *) attributeKeys {
1991 return [[self class] _attributeKeys];
1994 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1995 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1998 - (NSArray *) relations {
1999 @synchronized (database_) {
2000 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2001 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2002 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2006 - (NSString *) getField:(NSString *)name {
2007 @synchronized (database_) {
2008 if ([database_ era] != era_ || file_.end())
2011 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2013 const char *start, *end;
2014 if (!parser.Find([name UTF8String], start, end))
2015 return (NSString *) [NSNull null];
2017 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2021 if (parsed_ != NULL)
2023 @synchronized (database_) {
2024 if ([database_ era] != era_ || file_.end())
2027 ParsedPackage *parsed(new ParsedPackage);
2030 _profile(Package$parse)
2031 pkgRecords::Parser *parser;
2033 _profile(Package$parse$Lookup)
2034 parser = &[database_ records]->Lookup(file_);
2039 _profile(Package$parse$Find)
2044 {"icon", &parsed->icon_},
2045 {"depiction", &parsed->depiction_},
2046 {"homepage", &parsed->homepage_},
2047 {"website", &website},
2048 {"bugs", &parsed->bugs_},
2049 {"support", &parsed->support_},
2050 {"sponsor", &parsed->sponsor_},
2051 {"author", &parsed->author_},
2054 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2055 const char *start, *end;
2057 if (parser->Find(names[i].name_, start, end)) {
2058 CYString &value(*names[i].value_);
2059 _profile(Package$parse$Value)
2060 value.set(pool_, start, end - start);
2066 _profile(Package$parse$Tagline)
2067 const char *start, *end;
2068 if (parser->ShortDesc(start, end)) {
2069 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2072 while (stop != start && stop[-1] == '\r')
2074 parsed->tagline_.set(pool_, start, stop - start);
2078 _profile(Package$parse$Retain)
2079 if (parsed->homepage_.empty())
2080 parsed->homepage_ = website;
2081 if (parsed->homepage_ == parsed->depiction_)
2082 parsed->homepage_.clear();
2087 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2088 if ((self = [super init]) != nil) {
2089 _profile(Package$initWithVersion)
2092 database_ = database;
2093 era_ = [database era];
2097 pkgCache::PkgIterator iterator(version.ParentPkg());
2098 iterator_ = iterator;
2100 _profile(Package$initWithVersion$Version)
2101 if (!version_.end())
2102 file_ = version_.FileList();
2104 pkgCache &cache([database_ cache]);
2105 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2109 _profile(Package$initWithVersion$Cache)
2110 name_.set(NULL, iterator.Display());
2112 latest_.set(NULL, StripVersion_(version_.VerStr()));
2114 pkgCache::VerIterator current(iterator.CurrentVer());
2116 installed_.set(NULL, StripVersion_(current.VerStr()));
2119 _profile(Package$initWithVersion$Tags)
2120 pkgCache::TagIterator tag(iterator.TagList());
2122 tags_ = [NSMutableArray arrayWithCapacity:8];
2124 const char *name(tag.Name());
2125 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2127 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2128 if (strcmp(name + 6, "enduser") == 0)
2130 else if (strcmp(name + 6, "hacker") == 0)
2132 else if (strcmp(name + 6, "developer") == 0)
2134 else if (strcmp(name + 6, "cydia") == 0)
2140 if (strncmp(name, "cydia::", 7) == 0) {
2141 if (strcmp(name + 7, "essential") == 0)
2143 else if (strcmp(name + 7, "obsolete") == 0)
2148 } while (!tag.end());
2152 _profile(Package$initWithVersion$Metadata)
2153 const char *mixed(iterator.Name());
2154 size_t size(strlen(mixed));
2155 char lower[size + 1];
2157 for (size_t i(0); i != size; ++i)
2158 lower[i] = mixed[i] | 0x20;
2161 PackageValue *metadata(PackageFind(lower, size));
2162 metadata_ = metadata;
2164 id_.set(NULL, metadata->name_, size);
2166 const char *latest(version_.VerStr());
2167 size_t length(strlen(latest));
2169 uint16_t vhash(hashlittle(latest, length));
2171 size_t capped(std::min<size_t>(8, length));
2172 latest = latest + length - capped;
2174 if (metadata->first_ == 0)
2175 metadata->first_ = now_;
2177 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2178 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2179 metadata->vhash_ = vhash;
2180 metadata->last_ = now_;
2181 } else if (metadata->last_ == 0)
2182 metadata->last_ = metadata->first_;
2185 _profile(Package$initWithVersion$Section)
2186 section_ = iterator.Section();
2189 _profile(Package$initWithVersion$Flags)
2190 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2191 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2196 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2197 pkgCache::VerIterator version;
2199 _profile(Package$packageWithIterator$GetCandidateVer)
2200 version = [database policy]->GetCandidateVer(iterator);
2208 _profile(Package$packageWithIterator$Allocate)
2209 package = [Package allocWithZone:zone];
2212 _profile(Package$packageWithIterator$Initialize)
2214 initWithVersion:version
2221 _profile(Package$packageWithIterator$Autorelease)
2222 package = [package autorelease];
2228 - (pkgCache::PkgIterator) iterator {
2232 - (NSString *) section {
2233 if (section$_ == nil) {
2234 if (section_ == NULL)
2237 _profile(Package$section$mappedSectionForPointer)
2238 section$_ = [database_ mappedSectionForPointer:section_];
2243 - (NSString *) simpleSection {
2244 if (NSString *section = [self section])
2245 return Simplify(section);
2250 - (NSString *) longSection {
2251 return LocalizeSection([self section]);
2254 - (NSString *) shortSection {
2255 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2258 - (NSString *) uri {
2261 pkgIndexFile *index;
2262 pkgCache::PkgFileIterator file(file_.File());
2263 if (![database_ list].FindIndex(file, index))
2265 return [NSString stringWithUTF8String:iterator_->Path];
2266 //return [NSString stringWithUTF8String:file.Site()];
2267 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2271 - (MIMEAddress *) maintainer {
2272 @synchronized (database_) {
2273 if ([database_ era] != era_ || file_.end())
2276 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2277 const std::string &maintainer(parser->Maintainer());
2278 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2282 @synchronized (database_) {
2283 if ([database_ era] != era_ || version_.end())
2286 return version_->InstalledSize;
2289 - (NSString *) longDescription {
2290 @synchronized (database_) {
2291 if ([database_ era] != era_ || file_.end())
2294 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2295 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2297 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2298 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2299 if ([lines count] < 2)
2302 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2303 for (size_t i(1), e([lines count]); i != e; ++i) {
2304 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2305 [trimmed addObject:trim];
2308 return [trimmed componentsJoinedByString:@"\n"];
2311 - (NSString *) shortDescription {
2312 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2316 _profile(Package$index)
2317 CFStringRef name((CFStringRef) [self name]);
2318 if (CFStringGetLength(name) == 0)
2320 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2321 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2323 return toupper(character);
2327 - (PackageValue *) metadata {
2332 PackageValue *metadata([self metadata]);
2333 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2336 - (bool) subscribed {
2337 return [self metadata]->subscribed_;
2340 - (bool) setSubscribed:(bool)subscribed {
2341 PackageValue *metadata([self metadata]);
2342 if (metadata->subscribed_ == subscribed)
2344 metadata->subscribed_ = subscribed;
2352 - (NSString *) latest {
2356 - (NSString *) installed {
2360 - (BOOL) uninstalled {
2361 return installed_.empty();
2365 return !version_.end();
2368 - (BOOL) upgradableAndEssential:(BOOL)essential {
2369 _profile(Package$upgradableAndEssential)
2370 pkgCache::VerIterator current(iterator_.CurrentVer());
2372 return essential && essential_;
2374 return !version_.end() && version_ != current;
2378 - (BOOL) essential {
2383 return [database_ cache][iterator_].InstBroken();
2386 - (BOOL) unfiltered {
2387 _profile(Package$unfiltered$obsolete)
2388 if (_unlikely(obsolete_))
2392 _profile(Package$unfiltered$hasSupportingRole)
2393 if (_unlikely(![self hasSupportingRole]))
2401 if (![self unfiltered])
2406 _profile(Package$visible$section)
2407 section = [self section];
2410 _profile(Package$visible$isSectionVisible)
2411 if (!isSectionVisible(section))
2419 unsigned char current(iterator_->CurrentState);
2420 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2423 - (BOOL) halfConfigured {
2424 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2427 - (BOOL) halfInstalled {
2428 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2432 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2433 return state.Mode != pkgDepCache::ModeKeep;
2436 - (NSString *) mode {
2437 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2439 switch (state.Mode) {
2440 case pkgDepCache::ModeDelete:
2441 if ((state.iFlags & pkgDepCache::Purge) != 0)
2445 case pkgDepCache::ModeKeep:
2446 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2447 return @"REINSTALL";
2448 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2452 case pkgDepCache::ModeInstall:
2453 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2454 return @"REINSTALL";
2455 else*/ switch (state.Status) {
2457 return @"DOWNGRADE";
2463 return @"NEW_INSTALL";
2474 - (NSString *) name {
2475 return name_.empty() ? id_ : name_;
2478 - (UIImage *) icon {
2479 NSString *section = [self simpleSection];
2482 if (parsed_ != NULL)
2483 if (NSString *href = parsed_->icon_)
2484 if ([href hasPrefix:@"file:///"])
2485 // XXX: correct escaping
2486 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2487 if (icon == nil) if (section != nil)
2488 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2489 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2490 if ([dicon hasPrefix:@"file:///"])
2491 // XXX: correct escaping
2492 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2494 icon = [UIImage applicationImageNamed:@"unknown.png"];
2498 - (NSString *) homepage {
2499 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2502 - (NSString *) depiction {
2503 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2506 - (MIMEAddress *) sponsor {
2507 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2510 - (MIMEAddress *) author {
2511 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2514 - (NSString *) support {
2515 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2518 - (NSArray *) files {
2519 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2520 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2523 fin.open([path UTF8String]);
2528 while (std::getline(fin, line))
2529 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2534 - (NSString *) state {
2535 @synchronized (database_) {
2536 if ([database_ era] != era_ || file_.end())
2539 switch (iterator_->CurrentState) {
2540 case pkgCache::State::NotInstalled:
2541 return @"NotInstalled";
2542 case pkgCache::State::UnPacked:
2544 case pkgCache::State::HalfConfigured:
2545 return @"HalfConfigured";
2546 case pkgCache::State::HalfInstalled:
2547 return @"HalfInstalled";
2548 case pkgCache::State::ConfigFiles:
2549 return @"ConfigFiles";
2550 case pkgCache::State::Installed:
2551 return @"Installed";
2552 case pkgCache::State::TriggersAwaited:
2553 return @"TriggersAwaited";
2554 case pkgCache::State::TriggersPending:
2555 return @"TriggersPending";
2558 return (NSString *) [NSNull null];
2561 - (NSString *) selection {
2562 @synchronized (database_) {
2563 if ([database_ era] != era_ || file_.end())
2566 switch (iterator_->SelectedState) {
2567 case pkgCache::State::Unknown:
2569 case pkgCache::State::Install:
2571 case pkgCache::State::Hold:
2573 case pkgCache::State::DeInstall:
2574 return @"DeInstall";
2575 case pkgCache::State::Purge:
2579 return (NSString *) [NSNull null];
2582 - (NSArray *) warnings {
2583 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2584 const char *name(iterator_.Name());
2586 size_t length(strlen(name));
2587 if (length < 2) invalid:
2588 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2589 else for (size_t i(0); i != length; ++i)
2591 /* XXX: technically this is not allowed */
2592 (name[i] < 'A' || name[i] > 'Z') &&
2593 (name[i] < 'a' || name[i] > 'z') &&
2594 (name[i] < '0' || name[i] > '9') &&
2595 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2598 if (strcmp(name, "cydia") != 0) {
2601 bool _private = false;
2604 bool repository = [[self section] isEqualToString:@"Repositories"];
2606 if (NSArray *files = [self files])
2607 for (NSString *file in files)
2608 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2610 else if (!user && [file isEqualToString:@"/User"])
2612 else if (!_private && [file isEqualToString:@"/private"])
2614 else if (!stash && [file isEqualToString:@"/var/stash"])
2617 /* XXX: this is not sensitive enough. only some folders are valid. */
2618 if (cydia && !repository)
2619 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2621 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2623 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2625 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2628 return [warnings count] == 0 ? nil : warnings;
2631 - (NSArray *) applications {
2632 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2634 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2636 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2637 if (NSArray *files = [self files])
2638 for (NSString *file in files)
2639 if (application_r(file)) {
2640 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2641 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2642 if ([id isEqualToString:me])
2645 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2647 display = application_r[1];
2649 NSString *bundle([file stringByDeletingLastPathComponent]);
2650 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2651 if (icon == nil || [icon length] == 0)
2653 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2655 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2656 [applications addObject:application];
2658 [application addObject:id];
2659 [application addObject:display];
2660 [application addObject:url];
2663 return [applications count] == 0 ? nil : applications;
2666 - (Source *) source {
2667 if (source_ == nil) {
2668 @synchronized (database_) {
2669 if ([database_ era] != era_ || file_.end())
2670 source_ = (Source *) [NSNull null];
2672 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2676 return source_ == (Source *) [NSNull null] ? nil : source_;
2683 - (BOOL) matches:(NSArray *)query {
2684 if (query == nil || [query count] == 0)
2696 length = [string length];
2698 for (NSString *term in query) {
2699 range = [string rangeOfString:term options:MatchCompareOptions_];
2700 if (range.location != NSNotFound)
2701 rank_ -= 10 * 100000 / length;
2704 string = [self name];
2706 for (NSString *term in query) {
2707 range = [string rangeOfString:term options:MatchCompareOptions_];
2708 if (range.location != NSNotFound)
2709 rank_ -= 6 * 100000 / length;
2712 string = [self shortDescription];
2713 length = [string length];
2714 NSUInteger stop(std::min<NSUInteger>(length, 100));
2716 for (NSString *term in query) {
2717 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2718 if (range.location != NSNotFound)
2719 rank_ -= 2 * 100000 / length;
2725 - (bool) hasSupportingRole {
2730 if ([Role_ isEqualToString:@"User"])
2734 if ([Role_ isEqualToString:@"Hacker"])
2738 if ([Role_ isEqualToString:@"Developer"])
2743 - (NSArray *) tags {
2747 - (BOOL) hasTag:(NSString *)tag {
2748 return tags_ == nil ? NO : [tags_ containsObject:tag];
2751 - (NSString *) primaryPurpose {
2752 for (NSString *tag in (NSArray *) tags_)
2753 if ([tag hasPrefix:@"purpose::"])
2754 return [tag substringFromIndex:9];
2758 - (NSArray *) purposes {
2759 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2760 for (NSString *tag in (NSArray *) tags_)
2761 if ([tag hasPrefix:@"purpose::"])
2762 [purposes addObject:[tag substringFromIndex:9]];
2763 return [purposes count] == 0 ? nil : purposes;
2766 - (bool) isCommercial {
2767 return [self hasTag:@"cydia::commercial"];
2770 - (void) setIndex:(size_t)index {
2771 if (metadata_->index_ != index)
2772 metadata_->index_ = index;
2775 - (CYString &) cyname {
2776 return name_.empty() ? id_ : name_;
2779 - (uint32_t) compareBySection:(NSArray *)sections {
2780 NSString *section([self section]);
2781 for (size_t i(0), e([sections count]); i != e; ++i) {
2782 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2786 return _not(uint32_t);
2790 @synchronized (database_) {
2791 pkgProblemResolver *resolver = [database_ resolver];
2792 resolver->Clear(iterator_);
2794 pkgCacheFile &cache([database_ cache]);
2795 cache->SetReInstall(iterator_, false);
2796 cache->MarkKeep(iterator_, false);
2800 @synchronized (database_) {
2801 pkgProblemResolver *resolver = [database_ resolver];
2802 resolver->Clear(iterator_);
2803 resolver->Protect(iterator_);
2805 pkgCacheFile &cache([database_ cache]);
2806 cache->SetReInstall(iterator_, false);
2807 cache->MarkInstall(iterator_, false);
2809 pkgDepCache::StateCache &state((*cache)[iterator_]);
2810 if (!state.Install())
2811 cache->SetReInstall(iterator_, true);
2815 @synchronized (database_) {
2816 pkgProblemResolver *resolver = [database_ resolver];
2817 resolver->Clear(iterator_);
2818 resolver->Remove(iterator_);
2819 resolver->Protect(iterator_);
2821 pkgCacheFile &cache([database_ cache]);
2822 cache->SetReInstall(iterator_, false);
2823 cache->MarkDelete(iterator_, true);
2826 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2827 _profile(Package$isUnfilteredAndSearchedForBy)
2830 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2831 value &= [self unfiltered];
2834 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2835 value &= [self matches:query];
2842 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2843 if ([search length] == 0)
2846 _profile(Package$isUnfilteredAndSelectedForBy)
2849 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2850 value &= [self unfiltered];
2853 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2854 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2861 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2862 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2865 - (bool) isVisibleInSection:(NSString *)name {
2866 NSString *section([self section]);
2870 section == nil && [name length] == 0 ||
2871 [name isEqualToString:section]
2872 ) && [self visible];
2875 - (bool) isVisibleInSource:(Source *)source {
2876 return [self source] == source && [self visible];
2881 /* Section Class {{{ */
2882 @interface Section : NSObject {
2887 _H<NSString> localized_;
2890 - (NSComparisonResult) compareByLocalized:(Section *)section;
2891 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2892 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2893 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2894 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2895 - (NSString *) name;
2902 - (void) addToCount;
2904 - (void) setCount:(size_t)count;
2905 - (NSString *) localized;
2909 @implementation Section
2911 - (NSComparisonResult) compareByLocalized:(Section *)section {
2912 NSString *lhs(localized_);
2913 NSString *rhs([section localized]);
2915 /*if ([lhs length] != 0 && [rhs length] != 0) {
2916 unichar lhc = [lhs characterAtIndex:0];
2917 unichar rhc = [rhs characterAtIndex:0];
2919 if (isalpha(lhc) && !isalpha(rhc))
2920 return NSOrderedAscending;
2921 else if (!isalpha(lhc) && isalpha(rhc))
2922 return NSOrderedDescending;
2925 return [lhs compare:rhs options:LaxCompareOptions_];
2928 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2929 if ((self = [self initWithName:name localize:NO]) != nil) {
2930 if (localized != nil)
2931 localized_ = localized;
2935 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2936 return [self initWithName:name row:0 localize:localize];
2939 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2940 if ((self = [super init]) != nil) {
2945 localized_ = LocalizeSection(name_);
2949 /* XXX: localize the index thingees */
2950 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2951 if ((self = [super init]) != nil) {
2952 name_ = [NSString stringWithCharacters:&index length:1];
2958 - (NSString *) name {
2978 - (void) addToCount {
2982 - (void) setCount:(size_t)count {
2986 - (NSString *) localized {
2993 static NSString *Colon_;
2995 static NSString *Error_;
2996 static NSString *Warning_;
2998 class CydiaLogCleaner :
2999 public pkgArchiveCleaner
3002 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3007 /* Database Implementation {{{ */
3008 @implementation Database
3010 + (Database *) sharedInstance {
3011 static _H<Database> instance;
3012 if (instance == nil)
3013 instance = [[[Database alloc] init] autorelease];
3021 - (void) releasePackages {
3022 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3023 CFArrayRemoveAllValues(packages_);
3027 // XXX: actually implement this thing
3029 [self releasePackages];
3030 apr_pool_destroy(pool_);
3031 NSRecycleZone(zone_);
3035 - (void) _readCydia:(NSNumber *)fd {
3036 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3037 std::istream is(&ib);
3040 static Pcre finish_r("^finish:([^:]*)$");
3042 while (std::getline(is, line)) {
3043 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3045 const char *data(line.c_str());
3046 size_t size = line.size();
3047 lprintf("C:%s\n", data);
3049 if (finish_r(data, size)) {
3050 NSString *finish = finish_r[1];
3051 int index = [Finishes_ indexOfObject:finish];
3052 if (index != INT_MAX && index > Finish_)
3062 - (void) _readStatus:(NSNumber *)fd {
3063 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3064 std::istream is(&ib);
3067 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3068 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3070 while (std::getline(is, line)) {
3071 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3073 const char *data(line.c_str());
3074 size_t size(line.size());
3075 lprintf("S:%s\n", data);
3077 if (conffile_r(data, size)) {
3078 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3079 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3080 } else if (strncmp(data, "status: ", 8) == 0) {
3081 // status: <package>: {unpacked,half-configured,installed}
3082 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3083 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3084 } else if (strncmp(data, "processing: ", 12) == 0) {
3085 // processing: configure: config-test
3086 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3087 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3088 } else if (pmstatus_r(data, size)) {
3089 std::string type([pmstatus_r[1] UTF8String]);
3091 NSString *package = pmstatus_r[2];
3092 if ([package isEqualToString:@"dpkg-exec"])
3095 float percent([pmstatus_r[3] floatValue]);
3096 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3098 NSString *string = pmstatus_r[4];
3100 if (type == "pmerror") {
3101 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3102 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3103 } else if (type == "pmstatus") {
3104 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3105 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3106 } else if (type == "pmconffile")
3107 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3109 lprintf("E:unknown pmstatus\n");
3111 lprintf("E:unknown status\n");
3119 - (void) _readOutput:(NSNumber *)fd {
3120 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3121 std::istream is(&ib);
3124 while (std::getline(is, line)) {
3125 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3127 lprintf("O:%s\n", line.c_str());
3129 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3130 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3142 - (Package *) packageWithName:(NSString *)name {
3143 @synchronized (self) {
3144 if (static_cast<pkgDepCache *>(cache_) == NULL)
3146 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3147 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3151 if ((self = [super init]) != nil) {
3158 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3159 apr_pool_create(&pool_, NULL);
3161 size_t capacity(MetaFile_->active_);
3167 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3168 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3172 _assert(pipe(fds) != -1);
3175 _config->Set("APT::Keep-Fds::", cydiafd_);
3176 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3179 detachNewThreadSelector:@selector(_readCydia:)
3181 withObject:[NSNumber numberWithInt:fds[0]]
3184 _assert(pipe(fds) != -1);
3188 detachNewThreadSelector:@selector(_readStatus:)
3190 withObject:[NSNumber numberWithInt:fds[0]]
3193 _assert(pipe(fds) != -1);
3194 _assert(dup2(fds[0], 0) != -1);
3195 _assert(close(fds[0]) != -1);
3197 input_ = fdopen(fds[1], "a");
3199 _assert(pipe(fds) != -1);
3200 _assert(dup2(fds[1], 1) != -1);
3201 _assert(close(fds[1]) != -1);
3204 detachNewThreadSelector:@selector(_readOutput:)
3206 withObject:[NSNumber numberWithInt:fds[0]]
3211 - (pkgCacheFile &) cache {
3215 - (pkgDepCache::Policy *) policy {
3219 - (pkgRecords *) records {
3223 - (pkgProblemResolver *) resolver {
3227 - (pkgAcquire &) fetcher {
3231 - (pkgSourceList &) list {
3235 - (NSArray *) packages {
3236 return (NSArray *) packages_;
3239 - (NSArray *) sources {
3243 - (Source *) sourceWithKey:(NSString *)key {
3244 for (Source *source in [self sources]) {
3245 if ([[source key] isEqualToString:key])
3250 - (bool) popErrorWithTitle:(NSString *)title {
3253 while (!_error->empty()) {
3255 bool warning(!_error->PopMessage(error));
3260 size_t size(error.size());
3261 if (size == 0 || error[size - 1] != '\n')
3263 error.resize(size - 1);
3266 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3268 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3274 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3275 return [self popErrorWithTitle:title] || !success;
3278 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3279 @synchronized (self) {
3282 [self releasePackages];
3285 [sourceList_ removeAllObjects];
3305 apr_pool_clear(pool_);
3307 NSRecycleZone(zone_);
3308 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3310 int chk(creat("/tmp/cydia.chk", 0644));
3314 if (invocation != nil)
3315 [invocation invoke];
3317 NSString *title(UCLocalize("DATABASE"));
3320 OpProgress progress;
3321 while (!cache_.Open(progress, true)) { pop:
3323 bool warning(!_error->PopMessage(error));
3324 lprintf("cache_.Open():[%s]\n", error.c_str());
3326 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3327 [delegate_ repairWithSelector:@selector(configure)];
3328 else if (error == "The package lists or status file could not be parsed or opened.")
3329 [delegate_ repairWithSelector:@selector(update)];
3330 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3331 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3332 // else if (error == "Malformed Status line")
3333 // else if (error == "The list of sources could not be read.")
3335 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3345 unlink("/tmp/cydia.chk");
3347 now_ = [[NSDate date] timeIntervalSince1970];
3349 policy_ = new pkgDepCache::Policy();
3350 records_ = new pkgRecords(cache_);
3351 resolver_ = new pkgProblemResolver(cache_);
3352 fetcher_ = new pkgAcquire(&status_);
3355 list_ = new pkgSourceList();
3356 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3359 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3360 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3364 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3367 if (cache_->BrokenCount() != 0) {
3368 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3371 if (cache_->BrokenCount() != 0) {
3372 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3376 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3380 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3381 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3382 [sourceList_ addObject:object];
3384 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3385 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3386 // XXX: this could be more intelligent
3387 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3388 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3390 sourceMap_[cached->ID] = object;
3395 /*std::vector<Package *> packages;
3396 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3401 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3402 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3403 //packages.push_back(package);
3404 CFArrayAppendValue(packages_, CFRetain(package));
3408 /*if (packages.empty())
3409 packages_ = [[NSArray alloc] init];
3411 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3414 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3415 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3416 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3424 /*if (!packages.empty())
3425 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3426 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3428 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3430 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3432 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3436 size_t count(CFArrayGetCount(packages_));
3437 MetaFile_->active_ = count;
3439 for (size_t index(0); index != count; ++index)
3440 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3447 @synchronized (self) {
3449 resolver_ = new pkgProblemResolver(cache_);
3451 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3452 if (!cache_[iterator].Keep())
3453 cache_->MarkKeep(iterator, false);
3454 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3455 cache_->SetReInstall(iterator, false);
3458 - (void) configure {
3459 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3461 system([dpkg UTF8String]);
3466 // XXX: I don't remember this condition
3471 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3473 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3475 if ([self popErrorWithTitle:title])
3479 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3481 CydiaLogCleaner cleaner;
3482 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3489 fetcher_->Shutdown();
3491 pkgRecords records(cache_);
3493 lock_ = new FileFd();
3494 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3496 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3498 if ([self popErrorWithTitle:title])
3502 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3505 manager_ = (_system->CreatePM(cache_));
3506 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3513 bool substrate(RestartSubstrate_);
3514 RestartSubstrate_ = false;
3516 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3518 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3520 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3522 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3523 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3526 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3528 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3530 [self popErrorWithTitle:title];
3534 bool failed = false;
3535 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3536 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3538 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3544 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3552 RestartSubstrate_ = true;
3555 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3557 if (_error->PendingError()) {
3562 if (result == pkgPackageManager::Failed) {
3567 if (result != pkgPackageManager::Completed) {
3572 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3574 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3576 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3577 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3580 if (![before isEqualToArray:after])
3585 NSString *title(UCLocalize("UPGRADE"));
3586 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3592 [self updateWithStatus:status_];
3595 - (void) updateWithStatus:(Status &)status {
3596 NSString *title(UCLocalize("REFRESHING_DATA"));
3599 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3603 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3604 if ([self popErrorWithTitle:title])
3607 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3609 bool success(ListUpdate(status, list, PulseInterval_));
3610 if (status.WasCancelled())
3613 [self popErrorWithTitle:title forOperation:success];
3614 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3618 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3621 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3622 delegate_ = delegate;
3625 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3626 progress_ = delegate;
3627 status_.setDelegate(delegate);
3630 - (NSObject<ProgressDelegate> *) progressDelegate {
3634 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3635 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3636 return i == sourceMap_.end() ? nil : i->second;
3639 - (NSString *) mappedSectionForPointer:(const char *)section {
3640 _H<NSString> *mapped;
3642 _profile(Database$mappedSectionForPointer$Cache)
3643 mapped = §ions_[section];
3646 if (*mapped == NULL) {
3647 size_t length(strlen(section));
3648 char spaced[length + 1];
3650 _profile(Database$mappedSectionForPointer$Replace)
3651 for (size_t index(0); index != length; ++index)
3652 spaced[index] = section[index] == '_' ? ' ' : section[index];
3653 spaced[length] = '\0';
3658 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3659 string = [NSString stringWithUTF8String:spaced];
3662 _profile(Database$mappedSectionForPointer$Map)
3663 string = [SectionMap_ objectForKey:string] ?: string;
3673 static _H<NSMutableSet> Diversions_;
3675 @interface Diversion : NSObject {
3678 _H<NSString> format_;
3683 @implementation Diversion
3685 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3686 if ((self = [super init]) != nil) {
3687 pattern_ = [from UTF8String];
3693 - (NSString *) divert:(NSString *)url {
3694 return !pattern_(url) ? nil : pattern_->*format_;
3697 + (NSURL *) divertURL:(NSURL *)url {
3699 NSString *href([url absoluteString]);
3701 for (Diversion *diversion in (id) Diversions_)
3702 if (NSString *diverted = [diversion divert:href]) {
3704 NSLog(@"div: %@", diverted);
3706 url = [NSURL URLWithString:diverted];
3713 - (NSString *) key {
3717 - (NSUInteger) hash {
3721 - (BOOL) isEqual:(Diversion *)object {
3722 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3727 @interface CydiaObject : NSObject {
3728 _H<IndirectDelegate> indirect_;
3729 _transient id delegate_;
3732 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3736 @interface CydiaWebViewController : CyteWebViewController {
3737 _H<CydiaObject> cydia_;
3740 + (void) addDiversion:(Diversion *)diversion;
3744 /* Web Scripting {{{ */
3745 @implementation CydiaObject
3747 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3748 if ((self = [super init]) != nil) {
3749 indirect_ = indirect;
3753 - (void) setDelegate:(id)delegate {
3754 delegate_ = delegate;
3757 + (NSArray *) _attributeKeys {
3758 return [NSArray arrayWithObjects:
3774 - (NSArray *) attributeKeys {
3775 return [[self class] _attributeKeys];
3778 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3779 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3782 - (NSString *) version {
3786 - (NSString *) device {
3787 return [[UIDevice currentDevice] uniqueIdentifier];
3790 - (NSString *) firmware {
3791 return [[UIDevice currentDevice] systemVersion];
3794 - (NSString *) hostname {
3795 return [[UIDevice currentDevice] name];
3798 - (NSString *) idiom {
3799 return (id) Idiom_ ?: [NSNull null];
3802 - (NSString *) plmn {
3803 return (id) PLMN_ ?: [NSNull null];
3806 - (NSString *) bbsnum {
3807 return (id) BBSNum_ ?: [NSNull null];
3810 - (NSString *) ecid {
3811 return (id) ChipID_ ?: [NSNull null];
3814 - (NSString *) serial {
3815 return SerialNumber_;
3818 - (NSString *) role {
3819 return (id) Role_ ?: [NSNull null];
3822 - (NSString *) model {
3823 return [NSString stringWithUTF8String:Machine_];
3826 - (NSString *) token {
3827 return (id) Token_ ?: [NSNull null];
3830 + (NSString *) webScriptNameForSelector:(SEL)selector {
3832 else if (selector == @selector(addBridgedHost:))
3833 return @"addBridgedHost";
3834 else if (selector == @selector(addInternalRedirect::))
3835 return @"addInternalRedirect";
3836 else if (selector == @selector(addPipelinedHost:scheme:))
3837 return @"addPipelinedHost";
3838 else if (selector == @selector(addTrivialSource:))
3839 return @"addTrivialSource";
3840 else if (selector == @selector(close))
3842 else if (selector == @selector(du:))
3844 else if (selector == @selector(stringWithFormat:arguments:))
3846 else if (selector == @selector(getAllSources))
3847 return @"getAllSourcs";
3848 else if (selector == @selector(getKernelNumber:))
3849 return @"getKernelNumber";
3850 else if (selector == @selector(getKernelString:))
3851 return @"getKernelString";
3852 else if (selector == @selector(getInstalledPackages))
3853 return @"getInstalledPackages";
3854 else if (selector == @selector(getIORegistryEntry::))
3855 return @"getIORegistryEntry";
3856 else if (selector == @selector(getLocaleIdentifier))
3857 return @"getLocaleIdentifier";
3858 else if (selector == @selector(getPreferredLanguages))
3859 return @"getPreferredLanguages";
3860 else if (selector == @selector(getPackageById:))
3861 return @"getPackageById";
3862 else if (selector == @selector(getSessionValue:))
3863 return @"getSessionValue";
3864 else if (selector == @selector(installPackages:))
3865 return @"installPackages";
3866 else if (selector == @selector(localizedStringForKey:value:table:))
3868 else if (selector == @selector(popViewController:))
3869 return @"popViewController";
3870 else if (selector == @selector(refreshSources))
3871 return @"refreshSources";
3872 else if (selector == @selector(removeButton))
3873 return @"removeButton";
3874 else if (selector == @selector(setSessionValue::))
3875 return @"setSessionValue";
3876 else if (selector == @selector(substitutePackageNames:))
3877 return @"substitutePackageNames";
3878 else if (selector == @selector(scrollToBottom:))
3879 return @"scrollToBottom";
3880 else if (selector == @selector(setAllowsNavigationAction:))
3881 return @"setAllowsNavigationAction";
3882 else if (selector == @selector(setBadgeValue:))
3883 return @"setBadgeValue";
3884 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3885 return @"setButtonImage";
3886 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3887 return @"setButtonTitle";
3888 else if (selector == @selector(setHidesBackButton:))
3889 return @"setHidesBackButton";
3890 else if (selector == @selector(setHidesNavigationBar:))
3891 return @"setHidesNavigationBar";
3892 else if (selector == @selector(setNavigationBarStyle:))
3893 return @"setNavigationBarStyle";
3894 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3895 return @"setNavigationBarTintColor";
3896 else if (selector == @selector(setPasteboardString:))
3897 return @"setPasteboardString";
3898 else if (selector == @selector(setPasteboardURL:))
3899 return @"setPasteboardURL";
3900 else if (selector == @selector(setToken:))
3902 else if (selector == @selector(setViewportWidth:))
3903 return @"setViewportWidth";
3904 else if (selector == @selector(statfs:))
3906 else if (selector == @selector(supports:))
3908 else if (selector == @selector(unload))
3914 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3915 return [self webScriptNameForSelector:selector] == nil;
3918 - (BOOL) supports:(NSString *)feature {
3919 return [feature isEqualToString:@"window.open"];
3923 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
3926 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3927 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3930 - (NSNumber *) getKernelNumber:(NSString *)name {
3931 const char *string([name UTF8String]);
3934 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3935 return (id) [NSNull null];
3937 if (size != sizeof(int))
3938 return (id) [NSNull null];
3941 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3942 return (id) [NSNull null];
3944 return [NSNumber numberWithInt:value];
3947 - (NSString *) getKernelString:(NSString *)name {
3948 const char *string([name UTF8String]);
3951 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3952 return (id) [NSNull null];
3954 char value[size + 1];
3955 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3956 return (id) [NSNull null];
3958 // XXX: just in case you request something ludicrous
3961 return [NSString stringWithCString:value];
3964 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3965 NSObject *value(CYIOGetValue([path UTF8String], entry));
3968 if ([value isKindOfClass:[NSData class]])
3969 value = CYHex((NSData *) value);
3974 - (id) getSessionValue:(NSString *)key {
3975 @synchronized (SessionData_) {
3976 return [SessionData_ objectForKey:key];
3979 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3980 @synchronized (SessionData_) {
3981 if (value == (id) [WebUndefined undefined])
3982 [SessionData_ removeObjectForKey:key];
3984 [SessionData_ setObject:value forKey:key];
3987 - (void) addBridgedHost:(NSString *)host {
3988 @synchronized (HostConfig_) {
3989 [BridgedHosts_ addObject:host];
3992 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
3993 @synchronized (HostConfig_) {
3994 if (scheme != (id) [WebUndefined undefined])
3995 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
3997 [PipelinedHosts_ addObject:host];
4000 - (void) popViewController:(NSNumber *)value {
4001 if (value == (id) [WebUndefined undefined])
4002 value = [NSNumber numberWithBool:YES];
4003 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4006 - (void) addTrivialSource:(NSString *)href {
4007 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4010 - (void) refreshSources {
4011 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4014 - (NSArray *) getAllSources {
4015 return [[Database sharedInstance] sources];
4018 - (NSArray *) getInstalledPackages {
4019 Database *database([Database sharedInstance]);
4020 @synchronized (database) {
4021 NSArray *packages([database packages]);
4022 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4023 for (Package *package in packages)
4024 if (![package uninstalled])
4025 [installed addObject:package];
4029 - (Package *) getPackageById:(NSString *)id {
4030 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4034 return (Package *) [NSNull null];
4037 - (NSString *) getLocaleIdentifier {
4038 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4041 - (NSArray *) getPreferredLanguages {
4045 - (NSArray *) statfs:(NSString *)path {
4048 if (path == nil || statfs([path UTF8String], &stat) == -1)
4051 return [NSArray arrayWithObjects:
4052 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4053 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4054 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4058 - (NSNumber *) du:(NSString *)path {
4059 NSNumber *value(nil);
4062 _assert(pipe(fds) != -1);
4064 pid_t pid(ExecFork());
4066 _assert(dup2(fds[1], 1) != -1);
4067 _assert(close(fds[0]) != -1);
4068 _assert(close(fds[1]) != -1);
4069 /* XXX: this should probably not use du */
4070 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4075 _assert(close(fds[1]) != -1);
4077 if (FILE *du = fdopen(fds[0], "r")) {
4079 while (fgets(line, sizeof(line), du) != NULL) {
4080 size_t length(strlen(line));
4081 while (length != 0 && line[length - 1] == '\n')
4082 line[--length] = '\0';
4083 if (char *tab = strchr(line, '\t')) {
4085 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4090 } else _assert(close(fds[0]));
4094 if (waitpid(pid, &status, 0) == -1)
4097 else _assert(false);
4103 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4106 - (void) installPackages:(NSArray *)packages {
4107 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4110 - (NSString *) substitutePackageNames:(NSString *)message {
4111 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4112 for (size_t i(0), e([words count]); i != e; ++i) {
4113 NSString *word([words objectAtIndex:i]);
4114 if (Package *package = [[Database sharedInstance] packageWithName:word])
4115 [words replaceObjectAtIndex:i withObject:[package name]];
4118 return [words componentsJoinedByString:@" "];
4121 - (void) removeButton {
4122 [indirect_ removeButton];
4125 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4126 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4129 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4130 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4133 - (void) setBadgeValue:(id)value {
4134 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4137 - (void) setAllowsNavigationAction:(NSString *)value {
4138 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4141 - (void) setHidesBackButton:(NSString *)value {
4142 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4145 - (void) setHidesNavigationBar:(NSString *)value {
4146 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4149 - (void) setNavigationBarStyle:(NSString *)value {
4150 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4153 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4154 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4155 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4156 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4159 - (void) setPasteboardString:(NSString *)value {
4160 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4163 - (void) setPasteboardURL:(NSString *)value {
4164 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4167 - (void) _setToken:(NSString *)token {
4171 [Metadata_ removeObjectForKey:@"Token"];
4173 [Metadata_ setObject:Token_ forKey:@"Token"];
4178 - (void) setToken:(NSString *)token {
4179 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4182 - (void) scrollToBottom:(NSNumber *)animated {
4183 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4186 - (void) setViewportWidth:(float)width {
4187 [indirect_ setViewportWidthOnMainThread:width];
4190 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4191 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4192 unsigned count([arguments count]);
4194 for (unsigned i(0); i != count; ++i)
4195 values[i] = [arguments objectAtIndex:i];
4196 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4199 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4200 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4202 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4204 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4211 /* Cydia Browser Controller {{{ */
4212 @implementation CydiaWebViewController
4214 - (NSURL *) navigationURL {
4215 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4218 + (void) initialize {
4219 Diversions_ = [NSMutableSet setWithCapacity:0];
4222 + (void) addDiversion:(Diversion *)diversion {
4223 [Diversions_ addObject:diversion];
4226 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4227 [super webView:view didClearWindowObject:window forFrame:frame];
4229 WebDataSource *source([frame dataSource]);
4230 NSURLResponse *response([source response]);
4231 NSURL *url([response URL]);
4232 NSString *scheme([[url scheme] lowercaseString]);
4234 bool bridged(false);
4236 @synchronized (HostConfig_) {
4237 if ([scheme isEqualToString:@"file"])
4239 else if ([scheme isEqualToString:@"https"])
4240 if ([BridgedHosts_ containsObject:[url host]])
4245 [window setValue:cydia_ forKey:@"cydia"];
4248 - (void) _setupMail:(MFMailComposeViewController *)controller {
4249 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4251 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4252 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4255 - (NSURL *) URLWithURL:(NSURL *)url {
4256 return [Diversion divertURL:url];
4259 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4260 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4262 if (System_ != NULL)
4263 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4264 if (Machine_ != NULL)
4265 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4267 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4272 - (void) setDelegate:(id)delegate {
4273 [super setDelegate:delegate];
4274 [cydia_ setDelegate:delegate];
4278 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4279 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4281 WebView *webview([[webview_ _documentView] webView]);
4283 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4286 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4288 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4289 if (Product_ != nil)
4290 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4292 [webview setApplicationNameForUserAgent:application];
4300 @interface NSObject (CydiaScript)
4301 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4304 @implementation NSObject (CydiaScript)
4306 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4312 @implementation NSArray (CydiaScript)
4314 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4315 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4316 for (size_t i(0), e([self count]); i != e; ++i)
4317 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4323 @implementation NSDictionary (CydiaScript)
4325 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4326 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4328 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4335 /* Confirmation Controller {{{ */
4336 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4337 if (!iterator.end())
4338 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4339 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4341 pkgCache::PkgIterator package(dep.TargetPkg());
4344 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4351 @protocol ConfirmationControllerDelegate
4352 - (void) cancelAndClear:(bool)clear;
4353 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4357 @interface ConfirmationController : CydiaWebViewController {
4358 _transient Database *database_;
4360 _H<UIAlertView> essential_;
4362 _H<NSDictionary> changes_;
4363 _H<NSMutableArray> issues_;
4364 _H<NSDictionary> sizes_;
4369 - (id) initWithDatabase:(Database *)database;
4373 @implementation ConfirmationController
4377 RestartSubstrate_ = true;
4378 [delegate_ confirmWithNavigationController:[self navigationController]];
4381 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4382 NSString *context([alert context]);
4384 if ([context isEqualToString:@"remove"]) {
4385 if (button == [alert cancelButtonIndex])
4386 [self dismissModalViewControllerAnimated:YES];
4387 else if (button == [alert firstOtherButtonIndex]) {
4391 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4392 } else if ([context isEqualToString:@"unable"]) {
4393 [self dismissModalViewControllerAnimated:YES];
4394 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4396 [super alertView:alert clickedButtonAtIndex:button];
4400 - (void) _doContinue {
4401 [self dismissModalViewControllerAnimated:YES];
4402 [delegate_ cancelAndClear:NO];
4405 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4406 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4410 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4411 [super webView:view didClearWindowObject:window forFrame:frame];
4413 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4414 (id) changes_, @"changes",
4415 (id) issues_, @"issues",
4416 (id) sizes_, @"sizes",
4418 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4421 - (id) initWithDatabase:(Database *)database {
4422 if ((self = [super init]) != nil) {
4423 database_ = database;
4425 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4426 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4427 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4428 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4429 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4433 pkgCacheFile &cache([database_ cache]);
4434 NSArray *packages([database_ packages]);
4435 pkgDepCache::Policy *policy([database_ policy]);
4437 issues_ = [NSMutableArray arrayWithCapacity:4];
4439 for (Package *package in packages) {
4440 pkgCache::PkgIterator iterator([package iterator]);
4441 NSString *name([package id]);
4443 if ([package broken]) {
4444 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4446 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4448 reasons, @"reasons",
4451 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4455 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4456 pkgCache::DepIterator start;
4457 pkgCache::DepIterator end;
4458 dep.GlobOr(start, end); // ++dep
4460 if (!cache->IsImportantDep(end))
4462 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4465 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4467 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4468 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4469 clauses, @"clauses",
4473 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4475 pkgCache::PkgIterator target(start.TargetPkg());
4476 if (target->ProvidesList != 0)
4477 reason = @"missing";
4479 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4481 reason = @"installed";
4482 installed = [NSString stringWithUTF8String:ver.VerStr()];
4483 } else if (!cache[target].CandidateVerIter(cache).end())
4484 reason = @"uninstalled";
4485 else if (target->ProvidesList == 0)
4486 reason = @"uninstallable";
4488 reason = @"virtual";
4491 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4492 [NSString stringWithUTF8String:start.CompType()], @"operator",
4493 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4496 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4497 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4498 version, @"version",
4500 installed, @"installed",
4503 // yes, seriously. (wtf?)
4511 pkgDepCache::StateCache &state(cache[iterator]);
4513 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4515 if (state.NewInstall())
4516 [installs addObject:name];
4517 // XXX: else if (state.Install())
4518 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4519 [reinstalls addObject:name];
4520 // XXX: move before previous if
4521 else if (state.Upgrade())
4522 [upgrades addObject:name];
4523 else if (state.Downgrade())
4524 [downgrades addObject:name];
4525 else if (!state.Delete())
4526 // XXX: _assert(state.Keep());
4528 else if (special_r(name))
4529 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4530 [NSNull null], @"package",
4531 [NSArray arrayWithObjects:
4532 [NSDictionary dictionaryWithObjectsAndKeys:
4533 @"Conflicts", @"relationship",
4534 [NSArray arrayWithObjects:
4535 [NSDictionary dictionaryWithObjectsAndKeys:
4537 [NSNull null], @"version",
4538 @"installed", @"reason",
4545 if ([package essential])
4547 [removes addObject:name];
4550 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4551 substrate_ |= DepSubstrate(iterator.CurrentVer());
4556 else if (Advanced_) {
4557 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4559 essential_ = [[[UIAlertView alloc]
4560 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4561 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4563 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4565 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4569 [essential_ setContext:@"remove"];
4571 essential_ = [[[UIAlertView alloc]
4572 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4573 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4575 cancelButtonTitle:UCLocalize("OKAY")
4576 otherButtonTitles:nil
4579 [essential_ setContext:@"unable"];
4582 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4583 installs, @"installs",
4584 reinstalls, @"reinstalls",
4585 upgrades, @"upgrades",
4586 downgrades, @"downgrades",
4587 removes, @"removes",
4590 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4591 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4592 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4595 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4599 - (UIBarButtonItem *) leftButton {
4600 return [[[UIBarButtonItem alloc]
4601 initWithTitle:UCLocalize("CANCEL")
4602 style:UIBarButtonItemStylePlain
4604 action:@selector(cancelButtonClicked)
4609 - (void) applyRightButton {
4610 if ([issues_ count] == 0 && ![self isLoading])
4611 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4612 initWithTitle:UCLocalize("CONFIRM")
4613 style:UIBarButtonItemStyleDone
4615 action:@selector(confirmButtonClicked)
4618 [[self navigationItem] setRightBarButtonItem:nil];
4622 - (void) cancelButtonClicked {
4623 [self dismissModalViewControllerAnimated:YES];
4624 [delegate_ cancelAndClear:YES];
4628 - (void) confirmButtonClicked {
4629 if (essential_ != nil)
4639 /* Progress Data {{{ */
4640 @interface CydiaProgressData : NSObject {
4641 _transient id delegate_;
4650 _H<NSMutableArray> events_;
4651 _H<NSString> title_;
4653 _H<NSString> status_;
4654 _H<NSString> finish_;
4659 @implementation CydiaProgressData
4661 + (NSArray *) _attributeKeys {
4662 return [NSArray arrayWithObjects:
4674 - (NSArray *) attributeKeys {
4675 return [[self class] _attributeKeys];
4678 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4679 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4683 if ((self = [super init]) != nil) {
4684 events_ = [NSMutableArray arrayWithCapacity:32];
4688 - (void) setDelegate:(id)delegate {
4689 delegate_ = delegate;
4692 - (void) setPercent:(float)value {
4696 - (NSNumber *) percent {
4697 return [NSNumber numberWithFloat:percent_];
4700 - (void) setCurrent:(float)value {
4704 - (NSNumber *) current {
4705 return [NSNumber numberWithFloat:current_];
4708 - (void) setTotal:(float)value {
4712 - (NSNumber *) total {
4713 return [NSNumber numberWithFloat:total_];
4716 - (void) setSpeed:(float)value {
4720 - (NSNumber *) speed {
4721 return [NSNumber numberWithFloat:speed_];
4724 - (NSArray *) events {
4728 - (void) removeAllEvents {
4729 [events_ removeAllObjects];
4732 - (void) addEvent:(CydiaProgressEvent *)event {
4733 [events_ addObject:event];
4736 - (void) setTitle:(NSString *)text {
4740 - (NSString *) title {
4744 - (void) setFinish:(NSString *)text {
4748 - (NSString *) finish {
4749 return (id) finish_ ?: [NSNull null];
4752 - (void) setRunning:(bool)running {
4756 - (NSNumber *) running {
4757 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4762 /* Progress Controller {{{ */
4763 @interface ProgressController : CydiaWebViewController <
4766 _transient Database *database_;
4767 _H<CydiaProgressData, 1> progress_;
4771 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4773 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4775 - (void) setTitle:(NSString *)title;
4776 - (void) setCancellable:(bool)cancellable;
4780 @implementation ProgressController
4783 [database_ setProgressDelegate:nil];
4787 - (UIBarButtonItem *) leftButton {
4788 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4789 initWithTitle:UCLocalize("CANCEL")
4790 style:UIBarButtonItemStylePlain
4792 action:@selector(cancel)
4793 ] autorelease] : nil;
4796 - (void) updateCancel {
4797 [super applyLeftButton];
4800 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4801 if ((self = [super init]) != nil) {
4802 database_ = database;
4803 delegate_ = delegate;
4805 [database_ setProgressDelegate:self];
4807 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4808 [progress_ setDelegate:self];
4810 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4812 [scroller_ setBackgroundColor:[UIColor blackColor]];
4814 [[self navigationItem] setHidesBackButton:YES];
4816 [self updateCancel];
4820 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4821 [super webView:view didClearWindowObject:window forFrame:frame];
4822 [window setValue:progress_ forKey:@"cydiaProgress"];
4825 - (void) updateProgress {
4826 [self dispatchEvent:@"CydiaProgressUpdate"];
4829 - (void) viewWillAppear:(BOOL)animated {
4830 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4831 [super viewWillAppear:animated];
4835 UpdateExternalStatus(0);
4842 [delegate_ terminateWithSuccess];
4843 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4844 [delegate_ suspendWithAnimation:YES];
4846 [delegate_ suspend];*/
4858 system("/usr/bin/sbreload");
4864 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4865 SBReboot(SBSSpringBoardServerPort());
4867 reboot2(RB_AUTOBOOT);
4874 - (void) setTitle:(NSString *)title {
4875 [progress_ setTitle:title];
4876 [self updateProgress];
4879 - (UIBarButtonItem *) rightButton {
4880 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4881 initWithTitle:UCLocalize("CLOSE")
4882 style:UIBarButtonItemStylePlain
4884 action:@selector(close)
4888 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4889 UpdateExternalStatus(1);
4891 [progress_ setRunning:true];
4892 [self setTitle:title];
4893 // implicit updateProgress
4895 SHA1SumValue notifyconf; {
4897 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4900 MMap mmap(file, MMap::ReadOnly);
4902 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4903 notifyconf = sha1.Result();
4907 SHA1SumValue springlist; {
4909 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4912 MMap mmap(file, MMap::ReadOnly);
4914 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4915 springlist = sha1.Result();
4919 if (invocation != nil) {
4920 [invocation yieldToSelector:@selector(invoke)];
4921 [self setTitle:@"COMPLETE"];
4926 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4929 MMap mmap(file, MMap::ReadOnly);
4931 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4932 if (!(notifyconf == sha1.Result()))
4939 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4942 MMap mmap(file, MMap::ReadOnly);
4944 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4945 if (!(springlist == sha1.Result()))
4951 if (RestartSubstrate_)
4955 RestartSubstrate_ = false;
4958 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4959 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
4960 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
4961 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4962 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
4966 system("su -c /usr/bin/uicache mobile");
4969 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
4971 [progress_ setRunning:false];
4972 [self updateProgress];
4974 [self applyRightButton];
4977 - (void) addProgressEvent:(CydiaProgressEvent *)event {
4978 [progress_ addEvent:event];
4979 [self updateProgress];
4982 - (bool) isProgressCancelled {
4983 return cancel_ == 2;
4988 [self updateCancel];
4991 - (void) setCancellable:(bool)cancellable {
4992 unsigned cancel(cancel_);
4996 else if (cancel_ == 0)
4999 if (cancel != cancel_)
5000 [self updateCancel];
5003 - (void) setProgressCancellable:(NSNumber *)cancellable {
5004 [self setCancellable:[cancellable boolValue]];
5007 - (void) setProgressPercent:(NSNumber *)percent {
5008 [progress_ setPercent:[percent floatValue]];
5009 [self updateProgress];
5012 - (void) setProgressStatus:(NSDictionary *)status {
5013 if (status == nil) {
5014 [progress_ setCurrent:0];
5015 [progress_ setTotal:0];
5016 [progress_ setSpeed:0];
5018 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5020 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5021 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5022 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5025 [self updateProgress];
5031 /* Package Cell {{{ */
5032 @interface PackageCell : CyteTableViewCell <
5033 CyteTableViewCellDelegate
5037 _H<NSString> description_;
5039 _H<NSString> source_;
5041 _H<Package> package_;
5042 _H<UIImage> placard_;
5046 - (PackageCell *) init;
5047 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5049 - (void) drawContentRect:(CGRect)rect;
5053 @implementation PackageCell
5055 - (PackageCell *) init {
5056 CGRect frame(CGRectMake(0, 0, 320, 74));
5057 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5058 UIView *content([self contentView]);
5059 CGRect bounds([content bounds]);
5061 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5062 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5063 [content addSubview:content_];
5065 [content_ setDelegate:self];
5066 [content_ setOpaque:YES];
5070 - (NSString *) accessibilityLabel {
5071 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5074 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5075 summarized_ = summary;
5087 Source *source = [package source];
5089 icon_ = [package icon];
5090 name_ = [package name];
5093 description_ = [package longDescription];
5094 if (description_ == nil)
5095 description_ = [package shortDescription];
5097 commercial_ = [package isCommercial];
5101 NSString *label = nil;
5102 bool trusted = false;
5104 if (source != nil) {
5105 label = [source label];
5106 trusted = [source trusted];
5107 } else if ([[package id] isEqualToString:@"firmware"])
5108 label = UCLocalize("APPLE");
5110 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5112 NSString *from(label);
5114 NSString *section = [package simpleSection];
5115 if (section != nil && ![section isEqualToString:label]) {
5116 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5117 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5120 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5122 if (NSString *purpose = [package primaryPurpose])
5123 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5128 if (NSString *mode = [package_ mode]) {
5129 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5130 color = RemovingColor_;
5131 //placard = @"removing";
5133 color = InstallingColor_;
5134 //placard = @"installing";
5137 // XXX: the removing/installing placards are not @2x
5140 color = [UIColor whiteColor];
5142 if ([package installed] != nil)
5143 placard = @"installed";
5148 [content_ setBackgroundColor:color];
5151 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5153 [self setNeedsDisplay];
5154 [content_ setNeedsDisplay];
5157 - (void) drawSummaryContentRect:(CGRect)rect {
5158 bool highlighted(highlighted_);
5159 float width([self bounds].size.width);
5163 rect.size = [(UIImage *) icon_ size];
5165 rect.size.width /= 4;
5166 rect.size.height /= 4;
5168 rect.origin.x = 14 - rect.size.width / 4;
5169 rect.origin.y = 14 - rect.size.height / 4;
5171 [icon_ drawInRect:rect];
5174 if (badge_ != nil) {
5176 rect.size = [(UIImage *) badge_ size];
5178 rect.size.width /= 4;
5179 rect.size.height /= 4;
5181 rect.origin.x = 20 - rect.size.width / 4;
5182 rect.origin.y = 20 - rect.size.height / 4;
5184 [badge_ drawInRect:rect];
5191 UISetColor(commercial_ ? Purple_ : Black_);
5192 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5194 if (placard_ != nil)
5195 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5198 - (void) drawNormalContentRect:(CGRect)rect {
5199 bool highlighted(highlighted_);
5200 float width([self bounds].size.width);
5204 rect.size = [(UIImage *) icon_ size];
5206 rect.size.width /= 2;
5207 rect.size.height /= 2;
5209 rect.origin.x = 25 - rect.size.width / 2;
5210 rect.origin.y = 25 - rect.size.height / 2;
5212 [icon_ drawInRect:rect];
5215 if (badge_ != nil) {
5217 rect.size = [(UIImage *) badge_ size];
5219 rect.size.width /= 2;
5220 rect.size.height /= 2;
5222 rect.origin.x = 36 - rect.size.width / 2;
5223 rect.origin.y = 36 - rect.size.height / 2;
5225 [badge_ drawInRect:rect];
5232 UISetColor(commercial_ ? Purple_ : Black_);
5233 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5234 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5237 UISetColor(commercial_ ? Purplish_ : Gray_);
5238 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5240 if (placard_ != nil)
5241 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5244 - (void) drawContentRect:(CGRect)rect {
5246 [self drawSummaryContentRect:rect];
5248 [self drawNormalContentRect:rect];
5253 /* Section Cell {{{ */
5254 @interface SectionCell : CyteTableViewCell <
5255 CyteTableViewCellDelegate
5257 _H<NSString> basic_;
5258 _H<NSString> section_;
5260 _H<NSString> count_;
5262 _H<UISwitch> switch_;
5266 - (void) setSection:(Section *)section editing:(BOOL)editing;
5270 @implementation SectionCell
5272 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5273 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5274 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5275 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5276 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5278 UIView *content([self contentView]);
5279 CGRect bounds([content bounds]);
5281 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5282 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5283 [content addSubview:content_];
5284 [content_ setBackgroundColor:[UIColor whiteColor]];
5286 [content_ setDelegate:self];
5290 - (void) onSwitch:(id)sender {
5291 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5292 if (metadata == nil) {
5293 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5294 [Sections_ setObject:metadata forKey:basic_];
5297 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5301 - (void) setSection:(Section *)section editing:(BOOL)editing {
5302 if (editing != editing_) {
5304 [switch_ removeFromSuperview];
5306 [self addSubview:switch_];
5315 if (section == nil) {
5316 name_ = UCLocalize("ALL_PACKAGES");
5319 basic_ = [section name];
5320 section_ = [section localized];
5322 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5323 count_ = [NSString stringWithFormat:@"%d", [section count]];
5326 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5329 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5330 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5332 [content_ setNeedsDisplay];
5335 - (void) setFrame:(CGRect)frame {
5336 [super setFrame:frame];
5338 CGRect rect([switch_ frame]);
5339 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5342 - (NSString *) accessibilityLabel {
5346 - (void) drawContentRect:(CGRect)rect {
5347 bool highlighted(highlighted_ && !editing_);
5349 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5354 float width(rect.size.width);
5360 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5362 CGSize size = [count_ sizeWithFont:Font14_];
5366 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5372 /* File Table {{{ */
5373 @interface FileTable : CyteViewController <
5374 UITableViewDataSource,
5377 _transient Database *database_;
5378 _H<Package> package_;
5380 _H<NSMutableArray> files_;
5381 _H<UITableView, 2> list_;
5384 - (id) initWithDatabase:(Database *)database;
5385 - (void) setPackage:(Package *)package;
5389 @implementation FileTable
5391 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5392 return files_ == nil ? 0 : [files_ count];
5395 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5399 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5400 static NSString *reuseIdentifier = @"Cell";
5402 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5404 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5405 [cell setFont:[UIFont systemFontOfSize:16]];
5407 [cell setText:[files_ objectAtIndex:indexPath.row]];
5408 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5413 - (NSURL *) navigationURL {
5414 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5418 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5420 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5421 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5422 [list_ setRowHeight:24.0f];
5423 [(UITableView *) list_ setDataSource:self];
5424 [list_ setDelegate:self];
5425 [[self view] addSubview:list_];
5428 - (void) viewDidLoad {
5429 [super viewDidLoad];
5431 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5434 - (void) releaseSubviews {
5438 - (id) initWithDatabase:(Database *)database {
5439 if ((self = [super init]) != nil) {
5440 database_ = database;
5442 files_ = [NSMutableArray arrayWithCapacity:32];
5446 - (void) setPackage:(Package *)package {
5450 [files_ removeAllObjects];
5452 if (package != nil) {
5454 name_ = [package id];
5456 if (NSArray *files = [package files])
5457 [files_ addObjectsFromArray:files];
5459 if ([files_ count] != 0) {
5460 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5461 [files_ removeObjectAtIndex:0];
5462 [files_ sortUsingSelector:@selector(compareByPath:)];
5464 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5465 [stack addObject:@"/"];
5467 for (int i(0), e([files_ count]); i != e; ++i) {
5468 NSString *file = [files_ objectAtIndex:i];
5469 while (![file hasPrefix:[stack lastObject]])
5470 [stack removeLastObject];
5471 NSString *directory = [stack lastObject];
5472 [stack addObject:[file stringByAppendingString:@"/"]];
5473 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5474 ([stack count] - 2) * 3, "",
5475 [file substringFromIndex:[directory length]]
5484 - (void) reloadData {
5487 [self setPackage:[database_ packageWithName:name_]];
5492 /* Package Controller {{{ */
5493 @interface CYPackageController : CydiaWebViewController <
5494 UIActionSheetDelegate
5496 _transient Database *database_;
5497 _H<Package> package_;
5500 _H<NSMutableArray> buttons_;
5501 _H<UIBarButtonItem> button_;
5504 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5508 @implementation CYPackageController
5510 - (NSURL *) navigationURL {
5511 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5514 /* XXX: this is not safe at all... localization of /fail/ */
5515 - (void) _clickButtonWithName:(NSString *)name {
5516 if ([name isEqualToString:UCLocalize("CLEAR")])
5517 [delegate_ clearPackage:package_];
5518 else if ([name isEqualToString:UCLocalize("INSTALL")])
5519 [delegate_ installPackage:package_];
5520 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5521 [delegate_ installPackage:package_];
5522 else if ([name isEqualToString:UCLocalize("REMOVE")])
5523 [delegate_ removePackage:package_];
5524 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5525 [delegate_ installPackage:package_];
5526 else _assert(false);
5529 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5530 NSString *context([sheet context]);
5532 if ([context isEqualToString:@"modify"]) {
5533 if (button != [sheet cancelButtonIndex]) {
5534 NSString *buttonName = [buttons_ objectAtIndex:button];
5535 [self _clickButtonWithName:buttonName];
5538 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5542 - (bool) _allowJavaScriptPanel {
5547 - (void) _customButtonClicked {
5548 int count([buttons_ count]);
5553 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5555 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5556 [buttons addObjectsFromArray:buttons_];
5558 UIActionSheet *sheet = [[[UIActionSheet alloc]
5561 cancelButtonTitle:nil
5562 destructiveButtonTitle:nil
5563 otherButtonTitles:nil
5566 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5568 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5569 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5571 [sheet setContext:@"modify"];
5573 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5577 // We don't want to allow non-commercial packages to do custom things to the install button,
5578 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5579 - (void) customButtonClicked {
5581 [super customButtonClicked];
5583 [self _customButtonClicked];
5586 - (void) reloadButtonClicked {
5587 // Don't reload a commerical package by tapping the loading button,
5588 // but if it's not an Install button, we should forward it on.
5589 if (![package_ uninstalled])
5590 [self _customButtonClicked];
5593 - (void) applyLoadingTitle {
5594 // Don't show "Loading" as the title. Ever.
5597 - (UIBarButtonItem *) rightButton {
5602 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5603 if ((self = [super init]) != nil) {
5604 database_ = database;
5605 buttons_ = [NSMutableArray arrayWithCapacity:4];
5606 name_ = [NSString stringWithString:name];
5607 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5611 - (void) reloadData {
5614 package_ = [database_ packageWithName:name_];
5616 [buttons_ removeAllObjects];
5618 if (package_ != nil) {
5619 [(Package *) package_ parse];
5621 commercial_ = [package_ isCommercial];
5623 if ([package_ mode] != nil)
5624 [buttons_ addObject:UCLocalize("CLEAR")];
5625 if ([package_ source] == nil);
5626 else if ([package_ upgradableAndEssential:NO])
5627 [buttons_ addObject:UCLocalize("UPGRADE")];
5628 else if ([package_ uninstalled])
5629 [buttons_ addObject:UCLocalize("INSTALL")];
5631 [buttons_ addObject:UCLocalize("REINSTALL")];
5632 if (![package_ uninstalled])
5633 [buttons_ addObject:UCLocalize("REMOVE")];
5637 switch ([buttons_ count]) {
5638 case 0: title = nil; break;
5639 case 1: title = [buttons_ objectAtIndex:0]; break;
5640 default: title = UCLocalize("MODIFY"); break;
5643 button_ = [[[UIBarButtonItem alloc]
5645 style:UIBarButtonItemStylePlain
5647 action:@selector(customButtonClicked)
5651 - (bool) isLoading {
5652 return commercial_ ? [super isLoading] : false;
5658 /* Package List Controller {{{ */
5659 @interface PackageListController : CyteViewController <
5660 UITableViewDataSource,
5663 _transient Database *database_;
5665 _H<NSArray> packages_;
5666 _H<NSMutableArray> sections_;
5667 _H<UITableView, 2> list_;
5668 _H<NSMutableArray> index_;
5669 _H<NSMutableDictionary> indices_;
5670 _H<NSString> title_;
5671 unsigned reloading_;
5674 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5675 - (void) setDelegate:(id)delegate;
5676 - (void) resetCursor;
5681 @implementation PackageListController
5683 - (bool) isSummarized {
5687 - (bool) showsSections {
5691 - (void) deselectWithAnimation:(BOOL)animated {
5692 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5695 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5696 CGRect base = [[self view] bounds];
5697 base.size.height -= bounds.size.height;
5698 base.origin = [list_ frame].origin;
5700 [UIView beginAnimations:nil context:NULL];
5701 [UIView setAnimationBeginsFromCurrentState:YES];
5702 [UIView setAnimationCurve:curve];
5703 [UIView setAnimationDuration:duration];
5704 [list_ setFrame:base];
5705 [UIView commitAnimations];
5708 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5709 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5712 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5713 [self resizeForKeyboardBounds:bounds duration:0];
5716 - (void) keyboardWillShow:(NSNotification *)notification {
5719 NSTimeInterval duration;
5720 UIViewAnimationCurve curve;
5721 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5722 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5723 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5724 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5726 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);
5727 UIViewController *base = self;
5728 while ([base parentViewController] != nil)
5729 base = [base parentViewController];
5730 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5731 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5733 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5736 - (void) keyboardWillHide:(NSNotification *)notification {
5737 NSTimeInterval duration;
5738 UIViewAnimationCurve curve;
5739 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5740 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5742 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5745 - (void) viewWillAppear:(BOOL)animated {
5746 [super viewWillAppear:animated];
5748 [self resizeForKeyboardBounds:CGRectZero];
5749 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5750 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5753 - (void) viewWillDisappear:(BOOL)animated {
5754 [super viewWillDisappear:animated];
5756 [self resizeForKeyboardBounds:CGRectZero];
5757 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5758 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5761 - (void) viewDidAppear:(BOOL)animated {
5762 [super viewDidAppear:animated];
5763 [self deselectWithAnimation:animated];
5766 - (void) didSelectPackage:(Package *)package {
5767 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5768 [view setDelegate:delegate_];
5769 [[self navigationController] pushViewController:view animated:YES];
5772 #if TryIndexedCollation
5773 + (BOOL) hasIndexedCollation {
5774 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5778 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5779 NSInteger count([sections_ count]);
5780 return count == 0 ? 1 : count;
5783 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5784 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5786 return [[sections_ objectAtIndex:section] name];
5789 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5790 if ([sections_ count] == 0)
5792 return [[sections_ objectAtIndex:section] count];
5795 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5796 @synchronized (database_) {
5797 if ([database_ era] != era_)
5800 Section *section([sections_ objectAtIndex:[path section]]);
5801 NSInteger row([path row]);
5802 Package *package([packages_ objectAtIndex:([section row] + row)]);
5803 return [[package retain] autorelease];
5806 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5807 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5809 cell = [[[PackageCell alloc] init] autorelease];
5810 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5814 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5815 Package *package([self packageAtIndexPath:path]);
5816 package = [database_ packageWithName:[package id]];
5817 [self didSelectPackage:package];
5820 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5821 if ([self showsSections])
5827 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5828 #if TryIndexedCollation
5829 if ([[self class] hasIndexedCollation]) {
5830 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5837 - (void) updateHeight {
5838 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5841 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5842 if ((self = [super init]) != nil) {
5843 database_ = database;
5844 title_ = [title copy];
5845 [[self navigationItem] setTitle:title_];
5847 #if TryIndexedCollation
5848 if ([[self class] hasIndexedCollation])
5849 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5852 index_ = [NSMutableArray arrayWithCapacity:32];
5854 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5856 packages_ = [NSArray array];
5857 sections_ = [NSMutableArray arrayWithCapacity:16];
5859 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5860 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5861 [[self view] addSubview:list_];
5863 // XXX: is 20 the most optimal number here?
5864 [list_ setSectionIndexMinimumDisplayRowCount:20];
5866 [(UITableView *) list_ setDataSource:self];
5867 [list_ setDelegate:self];
5869 [self updateHeight];
5873 - (void) setDelegate:(id)delegate {
5874 delegate_ = delegate;
5877 - (bool) shouldYield {
5881 - (bool) shouldBlock {
5885 - (NSMutableArray *) _reloadPackages {
5886 @synchronized (database_) {
5887 era_ = [database_ era];
5888 NSArray *packages([database_ packages]);
5890 return [NSMutableArray arrayWithArray:packages];
5893 - (void) _reloadData {
5894 if (reloading_ != 0) {
5901 if ([self shouldYield]) {
5905 if (![self shouldBlock])
5908 hud = [delegate_ addProgressHUD];
5909 [hud setText:UCLocalize("LOADING")];
5913 packages = [self yieldToSelector:@selector(_reloadPackages)];
5916 [delegate_ removeProgressHUD:hud];
5917 } while (reloading_ == 2);
5921 packages = [self _reloadPackages];
5924 packages_ = packages;
5926 [indices_ removeAllObjects];
5927 [sections_ removeAllObjects];
5929 Section *section = nil;
5931 #if TryIndexedCollation
5932 if ([[self class] hasIndexedCollation]) {
5933 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5934 NSArray *titles = [collation sectionIndexTitles];
5937 _profile(PackageTable$reloadData$Section)
5938 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5942 _profile(PackageTable$reloadData$Section$Package)
5943 package = [packages_ objectAtIndex:offset];
5944 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5947 while (secidx < index) {
5950 _profile(PackageTable$reloadData$Section$Allocate)
5951 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5954 _profile(PackageTable$reloadData$Section$Add)
5955 [sections_ addObject:section];
5959 [section addToCount];
5965 [index_ removeAllObjects];
5967 bool sectioned([self showsSections]);
5969 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
5970 [sections_ addObject:section];
5973 _profile(PackageTable$reloadData$Section)
5974 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5978 _profile(PackageTable$reloadData$Section$Package)
5979 package = [packages_ objectAtIndex:offset];
5980 index = [package index];
5983 if (sectioned && (section == nil || [section index] != index)) {
5984 _profile(PackageTable$reloadData$Section$Allocate)
5985 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5988 [index_ addObject:[section name]];
5989 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5991 _profile(PackageTable$reloadData$Section$Add)
5992 [sections_ addObject:section];
5996 [section addToCount];
6001 [self updateHeight];
6003 _profile(PackageTable$reloadData$List)
6004 [(UITableView *) list_ setDataSource:self];
6009 - (void) reloadData {
6011 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6014 - (void) resetCursor {
6015 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6018 - (void) clearData {
6019 [self updateHeight];
6021 [list_ setDataSource:nil];
6029 /* Filtered Package List Controller {{{ */
6030 @interface FilteredPackageListController : PackageListController {
6033 _H<NSObject> object_;
6036 - (void) setObject:(id)object;
6037 - (void) setObject:(id)object forFilter:(SEL)filter;
6040 - (void) setFilter:(SEL)filter;
6042 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6046 @implementation FilteredPackageListController
6052 - (void) setFilter:(SEL)filter {
6053 @synchronized (self) {
6056 /* XXX: this is an unsafe optimization of doomy hell */
6057 Method method(class_getInstanceMethod([Package class], filter));
6058 _assert(method != NULL);
6059 imp_ = method_getImplementation(method);
6060 _assert(imp_ != NULL);
6063 - (void) setObject:(id)object {
6064 @synchronized (self) {
6068 - (void) setObject:(id)object forFilter:(SEL)filter {
6069 @synchronized (self) {
6070 [self setFilter:filter];
6071 [self setObject:object];
6074 - (NSMutableArray *) _reloadPackages {
6075 @synchronized (database_) {
6076 era_ = [database_ era];
6077 NSArray *packages([database_ packages]);
6079 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6083 _H<NSObject> object;
6085 @synchronized (self) {
6091 _profile(PackageTable$reloadData$Filter)
6092 for (Package *package in packages)
6093 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6094 [filtered addObject:package];
6100 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6101 if ((self = [super initWithDatabase:database title:title]) != nil) {
6102 [self setFilter:filter];
6103 [self setObject:object];
6110 /* Home Controller {{{ */
6111 @interface HomeController : CydiaWebViewController {
6116 @implementation HomeController
6119 if ((self = [super init]) != nil) {
6120 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6125 - (NSURL *) navigationURL {
6126 return [NSURL URLWithString:@"cydia://home"];
6129 - (void) aboutButtonClicked {
6130 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6132 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6133 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6134 [alert setCancelButtonIndex:0];
6137 @"Copyright \u00a9 2008-2011\n"
6140 "Jay Freeman (saurik)\n"
6141 "saurik@saurik.com\n"
6142 "http://www.saurik.com/"
6148 - (UIBarButtonItem *) leftButton {
6149 return [[[UIBarButtonItem alloc]
6150 initWithTitle:UCLocalize("ABOUT")
6151 style:UIBarButtonItemStylePlain
6153 action:@selector(aboutButtonClicked)
6159 /* Manage Controller {{{ */
6160 @interface ManageController : CydiaWebViewController {
6163 - (void) queueStatusDidChange;
6167 @implementation ManageController
6170 if ((self = [super init]) != nil) {
6171 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6175 - (NSURL *) navigationURL {
6176 return [NSURL URLWithString:@"cydia://manage"];
6179 - (UIBarButtonItem *) leftButton {
6180 return [[[UIBarButtonItem alloc]
6181 initWithTitle:UCLocalize("SETTINGS")
6182 style:UIBarButtonItemStylePlain
6184 action:@selector(settingsButtonClicked)
6188 - (void) settingsButtonClicked {
6189 [delegate_ showSettings];
6192 - (void) queueButtonClicked {
6196 - (UIBarButtonItem *) customButton {
6197 return Queuing_ ? [[[UIBarButtonItem alloc]
6198 initWithTitle:UCLocalize("QUEUE")
6199 style:UIBarButtonItemStyleDone
6201 action:@selector(queueButtonClicked)
6202 ] autorelease] : [super customButton];
6205 - (void) queueStatusDidChange {
6206 [self applyRightButton];
6209 - (bool) isLoading {
6210 return !Queuing_ && [super isLoading];
6216 /* Refresh Bar {{{ */
6217 @interface RefreshBar : UINavigationBar {
6218 _H<UIProgressIndicator> indicator_;
6219 _H<UITextLabel> prompt_;
6220 _H<UIProgressBar> progress_;
6221 _H<UINavigationButton> cancel_;
6226 @implementation RefreshBar
6228 - (void) positionViews {
6229 CGRect frame = [cancel_ frame];
6230 frame.size = [cancel_ sizeThatFits:frame.size];
6231 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6232 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6233 [cancel_ setFrame:frame];
6235 CGSize prgsize = {75, 100};
6237 [self frame].size.width - prgsize.width - 10,
6238 ([self frame].size.height - prgsize.height) / 2
6240 [progress_ setFrame:prgrect];
6242 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6243 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6244 CGRect indrect = {{indoffset, indoffset}, indsize};
6245 [indicator_ setFrame:indrect];
6247 CGSize prmsize = {215, indsize.height + 4};
6249 indoffset * 2 + indsize.width,
6250 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6252 [prompt_ setFrame:prmrect];
6255 - (void) setFrame:(CGRect)frame {
6256 [super setFrame:frame];
6257 [self positionViews];
6260 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6261 if ((self = [super initWithFrame:frame]) != nil) {
6262 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6264 [self setBarStyle:UIBarStyleBlack];
6266 UIBarStyle barstyle([self _barStyle:NO]);
6267 bool ugly(barstyle == UIBarStyleDefault);
6269 UIProgressIndicatorStyle style = ugly ?
6270 UIProgressIndicatorStyleMediumBrown :
6271 UIProgressIndicatorStyleMediumWhite;
6273 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6274 [(UIProgressIndicator *) indicator_ setStyle:style];
6275 [indicator_ startAnimation];
6276 [self addSubview:indicator_];
6278 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6279 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6280 [prompt_ setBackgroundColor:[UIColor clearColor]];
6281 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6282 [self addSubview:prompt_];
6284 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6285 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6286 [(UIProgressBar *) progress_ setStyle:0];
6287 [self addSubview:progress_];
6289 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6290 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6291 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6292 [cancel_ setBarStyle:barstyle];
6294 [self positionViews];
6298 - (void) setCancellable:(bool)cancellable {
6300 [self addSubview:cancel_];
6302 [cancel_ removeFromSuperview];
6306 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6307 [progress_ setProgress:0];
6311 [self setCancellable:NO];
6314 - (void) setPrompt:(NSString *)prompt {
6315 [prompt_ setText:prompt];
6318 - (void) setProgress:(float)progress {
6319 [progress_ setProgress:progress];
6325 /* Cydia Navigation Controller Interface {{{ */
6326 @interface UINavigationController (Cydia)
6328 - (NSArray *) navigationURLCollection;
6329 - (void) unloadData;
6334 /* Cydia Tab Bar Controller {{{ */
6335 @interface CYTabBarController : UITabBarController <
6336 UITabBarControllerDelegate,
6339 _transient Database *database_;
6340 _H<RefreshBar, 1> refreshbar_;
6344 // XXX: ok, "updatedelegate_"?...
6345 _transient NSObject<CydiaDelegate> *updatedelegate_;
6347 _H<UIViewController> remembered_;
6348 _transient UIViewController *transient_;
6351 - (NSArray *) navigationURLCollection;
6352 - (void) dropBar:(BOOL)animated;
6353 - (void) beginUpdate;
6354 - (void) raiseBar:(BOOL)animated;
6356 - (void) unloadData;
6360 @implementation CYTabBarController
6362 - (void) setUnselectedViewController:(UIViewController *)transient {
6363 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6364 if (transient != nil) {
6365 if (transient_ == nil)
6366 remembered_ = [controllers objectAtIndex:0];
6367 transient_ = transient;
6368 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6369 [controllers replaceObjectAtIndex:0 withObject:transient_];
6370 [self setSelectedIndex:0];
6371 [self setViewControllers:controllers];
6372 [self concealTabBarSelection];
6373 } else if (remembered_ != nil) {
6374 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6375 transient_ = transient;
6376 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6378 [self setViewControllers:controllers];
6379 [self revealTabBarSelection];
6383 - (UIViewController *) unselectedViewController {
6387 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6388 if ([self unselectedViewController])
6389 [self setUnselectedViewController:nil];
6392 - (NSArray *) navigationURLCollection {
6393 NSMutableArray *items([NSMutableArray array]);
6395 // XXX: Should this deal with transient view controllers?
6396 for (id navigation in [self viewControllers]) {
6397 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6399 [items addObject:stack];
6405 - (void) unloadData {
6408 for (UINavigationController *controller in [self viewControllers])
6409 [controller unloadData];
6411 if (UIViewController *selected = [self selectedViewController])
6412 [selected reloadData];
6414 if (UIViewController *unselected = [self unselectedViewController]) {
6415 [unselected unloadData];
6416 [unselected reloadData];
6421 [[NSNotificationCenter defaultCenter] removeObserver:self];
6426 - (id) initWithDatabase:(Database *)database {
6427 if ((self = [super init]) != nil) {
6428 database_ = database;
6429 [self setDelegate:self];
6431 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6432 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6434 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6438 - (void) setUpdate:(NSDate *)date {
6442 - (void) beginUpdate {
6443 [(RefreshBar *) refreshbar_ start];
6446 [updatedelegate_ retainNetworkActivityIndicator];
6450 detachNewThreadSelector:@selector(performUpdate)
6456 - (void) performUpdate {
6457 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6460 status.setDelegate(self);
6461 [database_ updateWithStatus:status];
6464 performSelectorOnMainThread:@selector(completeUpdate)
6472 - (void) stopUpdateWithSelector:(SEL)selector {
6474 [updatedelegate_ releaseNetworkActivityIndicator];
6476 [self raiseBar:YES];
6479 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6482 - (void) completeUpdate {
6485 [self stopUpdateWithSelector:@selector(reloadData)];
6488 - (void) cancelUpdate {
6489 [self stopUpdateWithSelector:@selector(updateData)];
6492 - (void) cancelPressed {
6493 [self cancelUpdate];
6500 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6501 [refreshbar_ setPrompt:[event compoundMessage]];
6504 - (bool) isProgressCancelled {
6508 - (void) setProgressCancellable:(NSNumber *)cancellable {
6509 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6512 - (void) setProgressPercent:(NSNumber *)percent {
6513 [refreshbar_ setProgress:[percent floatValue]];
6516 - (void) setProgressStatus:(NSDictionary *)status {
6518 [self setProgressPercent:[status objectForKey:@"Percent"]];
6521 - (void) setUpdateDelegate:(id)delegate {
6522 updatedelegate_ = delegate;
6525 - (CGFloat) statusBarHeight {
6526 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6527 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6529 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6533 - (UIView *) transitionView {
6534 if ([self respondsToSelector:@selector(_transitionView)])
6535 return [self _transitionView];
6537 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6540 - (void) dropBar:(BOOL)animated {
6545 UIView *transition([self transitionView]);
6546 [[self view] addSubview:refreshbar_];
6548 CGRect barframe([refreshbar_ frame]);
6550 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6551 barframe.origin.y = [self statusBarHeight];
6553 barframe.origin.y = 0;
6555 [refreshbar_ setFrame:barframe];
6558 [UIView beginAnimations:nil context:NULL];
6560 CGRect viewframe = [transition frame];
6561 viewframe.origin.y += barframe.size.height;
6562 viewframe.size.height -= barframe.size.height;
6563 [transition setFrame:viewframe];
6566 [UIView commitAnimations];
6568 // Ensure bar has the proper width for our view, it might have changed
6569 barframe.size.width = viewframe.size.width;
6570 [refreshbar_ setFrame:barframe];
6573 - (void) raiseBar:(BOOL)animated {
6578 UIView *transition([self transitionView]);
6579 [refreshbar_ removeFromSuperview];
6581 CGRect barframe([refreshbar_ frame]);
6584 [UIView beginAnimations:nil context:NULL];
6586 CGRect viewframe = [transition frame];
6587 viewframe.origin.y -= barframe.size.height;
6588 viewframe.size.height += barframe.size.height;
6589 [transition setFrame:viewframe];
6592 [UIView commitAnimations];
6595 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6596 bool dropped(dropped_);
6601 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6607 - (void) statusBarFrameChanged:(NSNotification *)notification {
6617 /* Cydia Navigation Controller Implementation {{{ */
6618 @implementation UINavigationController (Cydia)
6620 - (NSArray *) navigationURLCollection {
6621 NSMutableArray *stack([NSMutableArray array]);
6623 for (CyteViewController *controller in [self viewControllers]) {
6624 NSString *url = [[controller navigationURL] absoluteString];
6626 [stack addObject:url];
6632 - (void) reloadData {
6635 if (UIViewController *visible = [self visibleViewController])
6636 [visible reloadData];
6639 - (void) unloadData {
6640 for (CyteViewController *page in [self viewControllers])
6649 /* Cydia:// Protocol {{{ */
6650 @interface CydiaURLProtocol : NSURLProtocol {
6655 @implementation CydiaURLProtocol
6657 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6658 NSURL *url([request URL]);
6662 NSString *scheme([[url scheme] lowercaseString]);
6663 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6665 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6671 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6675 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6676 id<NSURLProtocolClient> client([self client]);
6678 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6680 NSData *data(UIImagePNGRepresentation(icon));
6682 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6683 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6684 [client URLProtocol:self didLoadData:data];
6685 [client URLProtocolDidFinishLoading:self];
6689 - (void) startLoading {
6690 id<NSURLProtocolClient> client([self client]);
6691 NSURLRequest *request([self request]);
6693 NSURL *url([request URL]);
6694 NSString *href([url absoluteString]);
6695 NSString *scheme([[url scheme] lowercaseString]);
6699 if ([scheme isEqualToString:@"cydia"])
6700 path = [href substringFromIndex:8];
6701 else if ([scheme isEqualToString:@"about"])
6702 path = [href substringFromIndex:12];
6703 else _assert(false);
6705 NSRange slash([path rangeOfString:@"/"]);
6708 if (slash.location == NSNotFound) {
6712 command = [path substringToIndex:slash.location];
6713 path = [path substringFromIndex:(slash.location + 1)];
6716 Database *database([Database sharedInstance]);
6718 if ([command isEqualToString:@"package-icon"]) {
6721 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6722 Package *package([database packageWithName:path]);
6726 UIImage *icon([package icon]);
6727 [self _returnPNGWithImage:icon forRequest:request];
6728 } else if ([command isEqualToString:@"source-icon"]) {
6731 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6732 NSString *source(Simplify(path));
6733 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6735 icon = [UIImage applicationImageNamed:@"unknown.png"];
6736 [self _returnPNGWithImage:icon forRequest:request];
6737 } else if ([command isEqualToString:@"uikit-image"]) {
6740 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6741 UIImage *icon(_UIImageWithName(path));
6742 [self _returnPNGWithImage:icon forRequest:request];
6743 } else if ([command isEqualToString:@"section-icon"]) {
6746 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6747 NSString *section(Simplify(path));
6748 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6750 icon = [UIImage applicationImageNamed:@"unknown.png"];
6751 [self _returnPNGWithImage:icon forRequest:request];
6753 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6757 - (void) stopLoading {
6763 /* Section Controller {{{ */
6764 @interface SectionController : FilteredPackageListController {
6765 _H<NSString> section_;
6768 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6772 @implementation SectionController
6774 - (NSURL *) navigationURL {
6775 NSString *name = section_;
6779 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6782 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6785 title = UCLocalize("ALL_PACKAGES");
6786 else if (![name isEqual:@""])
6787 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6789 title = UCLocalize("NO_SECTION");
6791 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6798 /* Sections Controller {{{ */
6799 @interface SectionsController : CyteViewController <
6800 UITableViewDataSource,
6803 _transient Database *database_;
6804 _H<NSMutableArray> sections_;
6805 _H<NSMutableArray> filtered_;
6806 _H<UITableView, 2> list_;
6809 - (id) initWithDatabase:(Database *)database;
6810 - (void) editButtonClicked;
6814 @implementation SectionsController
6816 - (NSURL *) navigationURL {
6817 return [NSURL URLWithString:@"cydia://sections"];
6820 - (void) updateNavigationItem {
6821 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6822 if ([sections_ count] == 0) {
6823 [[self navigationItem] setRightBarButtonItem:nil];
6825 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6826 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6828 action:@selector(editButtonClicked)
6829 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6833 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6834 [super setEditing:editing animated:animated];
6839 [delegate_ updateData];
6841 [self updateNavigationItem];
6844 - (void) viewDidAppear:(BOOL)animated {
6845 [super viewDidAppear:animated];
6846 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6849 - (void) viewWillDisappear:(BOOL)animated {
6850 [super viewWillDisappear:animated];
6851 if ([self isEditing]) [self setEditing:NO];
6854 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6855 Section *section = nil;
6856 int index = [indexPath row];
6857 if (![self isEditing]) {
6860 section = [filtered_ objectAtIndex:index];
6862 section = [sections_ objectAtIndex:index];
6867 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6868 if ([self isEditing])
6869 return [sections_ count];
6871 return [filtered_ count] + 1;
6874 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6878 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6879 static NSString *reuseIdentifier = @"SectionCell";
6881 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6883 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6885 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6890 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6891 if ([self isEditing])
6894 Section *section = [self sectionAtIndexPath:indexPath];
6896 SectionController *controller = [[[SectionController alloc]
6897 initWithDatabase:database_
6898 section:[section name]
6900 [controller setDelegate:delegate_];
6902 [[self navigationController] pushViewController:controller animated:YES];
6906 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6908 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6909 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6910 [list_ setRowHeight:45.0f];
6911 [(UITableView *) list_ setDataSource:self];
6912 [list_ setDelegate:self];
6913 [[self view] addSubview:list_];
6916 - (void) viewDidLoad {
6917 [super viewDidLoad];
6919 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6922 - (void) releaseSubviews {
6926 - (id) initWithDatabase:(Database *)database {
6927 if ((self = [super init]) != nil) {
6928 database_ = database;
6930 sections_ = [NSMutableArray arrayWithCapacity:16];
6931 filtered_ = [NSMutableArray arrayWithCapacity:16];
6935 - (void) reloadData {
6938 NSArray *packages = [database_ packages];
6940 [sections_ removeAllObjects];
6941 [filtered_ removeAllObjects];
6943 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6946 for (Package *package in packages) {
6947 NSString *name([package section]);
6948 NSString *key(name == nil ? @"" : name);
6952 _profile(SectionsView$reloadData$Section)
6953 section = [sections objectForKey:key];
6954 if (section == nil) {
6955 _profile(SectionsView$reloadData$Section$Allocate)
6956 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6957 [sections setObject:section forKey:key];
6962 [section addToCount];
6964 _profile(SectionsView$reloadData$Filter)
6965 if (![package valid] || ![package visible])
6973 [sections_ addObjectsFromArray:[sections allValues]];
6975 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6977 for (Section *section in (id) sections_) {
6978 size_t count([section row]);
6982 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6983 [section setCount:count];
6984 [filtered_ addObject:section];
6987 [self updateNavigationItem];
6992 - (void) editButtonClicked {
6993 [self setEditing:![self isEditing] animated:YES];
6999 /* Changes Controller {{{ */
7000 @interface ChangesController : CyteViewController <
7001 UITableViewDataSource,
7004 _transient Database *database_;
7006 _H<NSArray> packages_;
7007 _H<NSMutableArray> sections_;
7008 _H<UITableView, 2> list_;
7012 - (id) initWithDatabase:(Database *)database;
7016 @implementation ChangesController
7018 - (NSURL *) navigationURL {
7019 return [NSURL URLWithString:@"cydia://changes"];
7022 - (void) viewDidAppear:(BOOL)animated {
7023 [super viewDidAppear:animated];
7024 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7027 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7028 NSInteger count([sections_ count]);
7029 return count == 0 ? 1 : count;
7032 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7033 if ([sections_ count] == 0)
7035 return [[sections_ objectAtIndex:section] name];
7038 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7039 if ([sections_ count] == 0)
7041 return [[sections_ objectAtIndex:section] count];
7044 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7045 @synchronized (database_) {
7046 if ([database_ era] != era_)
7049 NSUInteger sectionIndex([path section]);
7050 if (sectionIndex >= [sections_ count])
7052 Section *section([sections_ objectAtIndex:sectionIndex]);
7053 NSInteger row([path row]);
7054 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7057 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7058 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7060 cell = [[[PackageCell alloc] init] autorelease];
7061 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7065 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7066 Package *package([self packageAtIndexPath:path]);
7067 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7068 [view setDelegate:delegate_];
7069 [[self navigationController] pushViewController:view animated:YES];
7073 - (void) refreshButtonClicked {
7074 [delegate_ beginUpdate];
7075 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7078 - (void) upgradeButtonClicked {
7079 [delegate_ distUpgrade];
7083 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7085 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7086 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7087 [list_ setRowHeight:73];
7088 [(UITableView *) list_ setDataSource:self];
7089 [list_ setDelegate:self];
7090 [[self view] addSubview:list_];
7093 - (void) viewDidLoad {
7094 [super viewDidLoad];
7096 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7099 - (void) releaseSubviews {
7103 - (id) initWithDatabase:(Database *)database {
7104 if ((self = [super init]) != nil) {
7105 database_ = database;
7107 packages_ = [NSArray array];
7108 sections_ = [NSMutableArray arrayWithCapacity:16];
7112 - (NSMutableArray *) _reloadPackages {
7113 @synchronized (database_) {
7114 era_ = [database_ era];
7115 NSArray *packages([database_ packages]);
7117 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7120 _profile(ChangesController$_reloadPackages$Filter)
7121 for (Package *package in packages)
7122 if ([package upgradableAndEssential:YES] || [package visible])
7123 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7126 _profile(ChangesController$_reloadPackages$radixSort)
7127 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7134 - (void) _reloadData {
7139 UIProgressHUD *hud([delegate_ addProgressHUD]);
7140 [hud setText:UCLocalize("LOADING")];
7141 //NSLog(@"HUD:%@::%@", delegate_, hud);
7142 packages = [self yieldToSelector:@selector(_reloadPackages)];
7143 [delegate_ removeProgressHUD:hud];
7145 packages = [self _reloadPackages];
7148 @synchronized (database_) {
7149 if (era_ != [database_ era])
7152 packages_ = packages;
7153 [sections_ removeAllObjects];
7155 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7156 Section *ignored = nil;
7157 Section *section = nil;
7161 bool unseens = false;
7163 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7165 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7166 Package *package = [packages_ objectAtIndex:offset];
7168 BOOL uae = [package upgradableAndEssential:YES];
7172 time_t seen([package seen]);
7174 if (section == nil || last != seen) {
7178 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7181 _profile(ChangesController$reloadData$Allocate)
7182 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7183 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7184 [sections_ addObject:section];
7188 [section addToCount];
7189 } else if ([package ignored]) {
7190 if (ignored == nil) {
7191 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7193 [ignored addToCount];
7196 [upgradable addToCount];
7201 CFRelease(formatter);
7204 Section *last = [sections_ lastObject];
7205 size_t count = [last count];
7206 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7207 [sections_ removeLastObject];
7210 if ([ignored count] != 0)
7211 [sections_ insertObject:ignored atIndex:0];
7213 [sections_ insertObject:upgradable atIndex:0];
7218 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7219 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7220 style:UIBarButtonItemStylePlain
7222 action:@selector(upgradeButtonClicked)
7225 if (![delegate_ updating])
7226 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7227 initWithTitle:UCLocalize("REFRESH")
7228 style:UIBarButtonItemStylePlain
7230 action:@selector(refreshButtonClicked)
7236 - (void) reloadData {
7238 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7243 /* Search Controller {{{ */
7244 @interface SearchController : FilteredPackageListController <
7247 _H<UISearchBar, 1> search_;
7251 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7252 - (void) reloadData;
7256 @implementation SearchController
7258 - (NSURL *) navigationURL {
7259 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7260 return [NSURL URLWithString:@"cydia://search"];
7262 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7265 - (void) useSearch {
7266 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7271 - (void) viewWillAppear:(BOOL)animated {
7272 [super viewWillAppear:animated];
7274 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7278 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7279 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7284 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7285 [search_ resignFirstResponder];
7289 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7290 [search_ setText:@""];
7291 [self searchBarButtonClicked:searchBar];
7294 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7295 [self searchBarButtonClicked:searchBar];
7298 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7299 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7303 - (bool) shouldYield {
7307 - (bool) shouldBlock {
7308 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7311 - (bool) isSummarized {
7312 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7315 - (bool) showsSections {
7319 - (NSMutableArray *) _reloadPackages {
7320 NSMutableArray *packages([super _reloadPackages]);
7321 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7322 [packages radixSortUsingSelector:@selector(rank)];
7326 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7327 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7328 search_ = [[[UISearchBar alloc] init] autorelease];
7329 [search_ setDelegate:self];
7332 [search_ setText:query];
7336 - (void) viewDidAppear:(BOOL)animated {
7337 [super viewDidAppear:animated];
7339 if (!searchloaded_) {
7340 searchloaded_ = YES;
7341 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7342 [search_ layoutSubviews];
7343 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7345 UITextField *textField;
7346 if ([search_ respondsToSelector:@selector(searchField)])
7347 textField = [search_ searchField];
7349 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7351 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7352 [textField setEnablesReturnKeyAutomatically:NO];
7353 [[self navigationItem] setTitleView:textField];
7357 - (void) reloadData {
7358 id object([search_ text]);
7359 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7360 object = [object componentsSeparatedByString:@" "];
7362 [self setObject:object];
7368 - (void) didSelectPackage:(Package *)package {
7369 [search_ resignFirstResponder];
7370 [super didSelectPackage:package];
7375 /* Package Settings Controller {{{ */
7376 @interface PackageSettingsController : CyteViewController <
7377 UITableViewDataSource,
7380 _transient Database *database_;
7382 _H<Package> package_;
7383 _H<UITableView, 2> table_;
7384 _H<UISwitch> subscribedSwitch_;
7385 _H<UISwitch> ignoredSwitch_;
7386 _H<UITableViewCell> subscribedCell_;
7387 _H<UITableViewCell> ignoredCell_;
7390 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7394 @implementation PackageSettingsController
7396 - (NSURL *) navigationURL {
7397 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7400 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7401 if (package_ == nil)
7404 if ([package_ installed] == nil)
7410 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7411 if (package_ == nil)
7414 // both sections contain just one item right now.
7418 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7422 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7424 return UCLocalize("SHOW_ALL_CHANGES_EX");
7426 return UCLocalize("IGNORE_UPGRADES_EX");
7429 - (void) onSubscribed:(id)control {
7430 bool value([control isOn]);
7431 if (package_ == nil)
7433 if ([package_ setSubscribed:value])
7434 [delegate_ updateData];
7437 - (void) _updateIgnored {
7438 const char *package([name_ UTF8String]);
7439 bool on([ignoredSwitch_ isOn]);
7441 pid_t pid(ExecFork());
7443 FILE *dpkg(popen("dpkg --set-selections", "w"));
7444 fwrite(package, strlen(package), 1, dpkg);
7447 fwrite(" hold\n", 6, 1, dpkg);
7449 fwrite(" install\n", 9, 1, dpkg);
7459 int result(waitpid(pid, &status, 0));
7462 _assert(result == pid);
7468 - (void) onIgnored:(id)control {
7469 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7470 [invocation setTarget:self];
7471 [invocation setSelector:@selector(_updateIgnored)];
7473 [delegate_ reloadDataWithInvocation:invocation];
7476 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7477 if (package_ == nil)
7480 switch ([indexPath section]) {
7481 case 0: return subscribedCell_;
7482 case 1: return ignoredCell_;
7491 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7493 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7494 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7495 [(UITableView *) table_ setDataSource:self];
7496 [table_ setDelegate:self];
7497 [[self view] addSubview:table_];
7499 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7500 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7501 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7503 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7504 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7505 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7507 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7508 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7509 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7510 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7512 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7513 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7514 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7515 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7518 - (void) viewDidLoad {
7519 [super viewDidLoad];
7521 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7524 - (void) releaseSubviews {
7526 subscribedCell_ = nil;
7528 ignoredSwitch_ = nil;
7529 subscribedSwitch_ = nil;
7532 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7533 if ((self = [super init]) != nil) {
7534 database_ = database;
7539 - (void) reloadData {
7542 package_ = [database_ packageWithName:name_];
7544 if (package_ != nil) {
7545 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7546 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7547 } // XXX: what now, G?
7549 [table_ reloadData];
7555 /* Installed Controller {{{ */
7556 @interface InstalledController : FilteredPackageListController {
7560 - (id) initWithDatabase:(Database *)database;
7562 - (void) updateRoleButton;
7563 - (void) queueStatusDidChange;
7567 @implementation InstalledController
7569 - (NSURL *) navigationURL {
7570 return [NSURL URLWithString:@"cydia://installed"];
7573 - (id) initWithDatabase:(Database *)database {
7574 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7575 [self updateRoleButton];
7576 [self queueStatusDidChange];
7581 - (void) queueButtonClicked {
7586 - (void) queueStatusDidChange {
7590 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7591 initWithTitle:UCLocalize("QUEUE")
7592 style:UIBarButtonItemStyleDone
7594 action:@selector(queueButtonClicked)
7597 [[self navigationItem] setLeftBarButtonItem:nil];
7603 - (void) updateRoleButton {
7604 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7605 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7606 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7607 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7609 action:@selector(roleButtonClicked)
7613 - (void) roleButtonClicked {
7614 [self setObject:[NSNumber numberWithBool:expert_]];
7618 [self updateRoleButton];
7624 /* Source Cell {{{ */
7625 @interface SourceCell : CyteTableViewCell <
7626 CyteTableViewCellDelegate
7629 _H<NSString> origin_;
7630 _H<NSString> label_;
7633 - (void) setSource:(Source *)source;
7637 @implementation SourceCell
7639 - (void) _setImage:(UIImage *)image {
7641 [content_ setNeedsDisplay];
7644 - (void) _setSource:(Source *)source {
7645 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7647 if (NSString *base = [source base])
7648 if ([base length] != 0) {
7649 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7651 if (NSData *data = [NSURLConnection
7652 sendSynchronousRequest:[NSURLRequest
7654 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7658 returningResponse:NULL
7661 if (UIImage *image = [UIImage imageWithData:data])
7662 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7668 - (void) setSource:(Source *)source {
7669 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7671 origin_ = [source name];
7672 label_ = [source uri];
7674 [content_ setNeedsDisplay];
7676 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7679 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7680 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7681 UIView *content([self contentView]);
7682 CGRect bounds([content bounds]);
7684 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7685 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7686 [content_ setBackgroundColor:[UIColor whiteColor]];
7687 [content addSubview:content_];
7689 [content_ setDelegate:self];
7690 [content_ setOpaque:YES];
7694 - (NSString *) accessibilityLabel {
7698 - (void) drawContentRect:(CGRect)rect {
7699 bool highlighted(highlighted_);
7700 float width(rect.size.width);
7703 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7710 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7714 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7719 /* Source Controller {{{ */
7720 @interface SourceController : FilteredPackageListController {
7721 _transient Source *source_;
7725 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7729 @implementation SourceController
7731 - (NSURL *) navigationURL {
7732 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7735 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7736 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7738 key_ = [source key];
7742 - (void) reloadData {
7743 source_ = [database_ sourceWithKey:key_];
7744 key_ = [source_ key];
7745 [self setObject:source_];
7747 [[self navigationItem] setTitle:[source_ label]];
7754 /* Sources Controller {{{ */
7755 @interface SourcesController : CyteViewController <
7756 UITableViewDataSource,
7759 _transient Database *database_;
7760 _H<UITableView, 2> list_;
7761 _H<NSMutableArray> sources_;
7765 _H<UIProgressHUD> hud_;
7768 //NSURLConnection *installer_;
7769 NSURLConnection *trivial_;
7770 NSURLConnection *trivial_bz2_;
7771 NSURLConnection *trivial_gz_;
7772 //NSURLConnection *automatic_;
7777 - (id) initWithDatabase:(Database *)database;
7778 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7782 @implementation SourcesController
7784 - (void) _releaseConnection:(NSURLConnection *)connection {
7785 if (connection != nil) {
7786 [connection cancel];
7787 //[connection setDelegate:nil];
7788 [connection release];
7793 //[self _releaseConnection:installer_];
7794 [self _releaseConnection:trivial_];
7795 [self _releaseConnection:trivial_gz_];
7796 [self _releaseConnection:trivial_bz2_];
7797 //[self _releaseConnection:automatic_];
7802 - (NSURL *) navigationURL {
7803 return [NSURL URLWithString:@"cydia://sources"];
7806 - (void) viewDidAppear:(BOOL)animated {
7807 [super viewDidAppear:animated];
7808 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7811 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7812 return offset_ == 0 ? 1 : 2;
7815 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7816 switch (section + (offset_ == 0 ? 1 : 0)) {
7817 case 0: return UCLocalize("ENTERED_BY_USER");
7818 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7824 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7825 int count = [sources_ count];
7827 case 0: return (offset_ == 0 ? count : offset_);
7828 case 1: return count - offset_;
7834 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7836 switch (indexPath.section) {
7837 case 0: idx = indexPath.row; break;
7838 case 1: idx = indexPath.row + offset_; break;
7842 return [sources_ objectAtIndex:idx];
7845 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7846 static NSString *cellIdentifier = @"SourceCell";
7848 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7849 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7850 [cell setSource:[self sourceAtIndexPath:indexPath]];
7851 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7856 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7857 Source *source = [self sourceAtIndexPath:indexPath];
7859 SourceController *controller = [[[SourceController alloc]
7860 initWithDatabase:database_
7864 [controller setDelegate:delegate_];
7866 [[self navigationController] pushViewController:controller animated:YES];
7869 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7870 Source *source = [self sourceAtIndexPath:indexPath];
7871 return [source record] != nil;
7874 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7875 if (editingStyle == UITableViewCellEditingStyleDelete) {
7876 Source *source = [self sourceAtIndexPath:indexPath];
7877 [Sources_ removeObjectForKey:[source key]];
7878 [delegate_ syncData];
7883 [delegate_ addTrivialSource:href_];
7884 [delegate_ syncData];
7887 - (NSString *) getWarning {
7888 NSString *href(href_);
7889 NSRange colon([href rangeOfString:@"://"]);
7890 if (colon.location != NSNotFound)
7891 href = [href substringFromIndex:(colon.location + 3)];
7892 href = [href stringByAddingPercentEscapes];
7893 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7894 href = [href stringByCachingURLWithCurrentCDN];
7896 NSURL *url([NSURL URLWithString:href]);
7898 NSStringEncoding encoding;
7899 NSError *error(nil);
7901 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7902 return [warning length] == 0 ? nil : warning;
7906 - (void) _endConnection:(NSURLConnection *)connection {
7907 // XXX: the memory management in this method is horribly awkward
7909 NSURLConnection **field = NULL;
7910 if (connection == trivial_)
7912 else if (connection == trivial_bz2_)
7913 field = &trivial_bz2_;
7914 else if (connection == trivial_gz_)
7915 field = &trivial_gz_;
7916 _assert(field != NULL);
7917 [connection release];
7922 trivial_bz2_ == nil &&
7925 [delegate_ releaseNetworkActivityIndicator];
7927 [delegate_ removeProgressHUD:hud_];
7933 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7936 UIAlertView *alert = [[[UIAlertView alloc]
7937 initWithTitle:UCLocalize("SOURCE_WARNING")
7940 cancelButtonTitle:UCLocalize("CANCEL")
7942 UCLocalize("ADD_ANYWAY"),
7946 [alert setContext:@"warning"];
7947 [alert setNumberOfRows:1];
7951 } else if (error_ != nil) {
7952 UIAlertView *alert = [[[UIAlertView alloc]
7953 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7954 message:[error_ localizedDescription]
7956 cancelButtonTitle:UCLocalize("OK")
7957 otherButtonTitles:nil
7960 [alert setContext:@"urlerror"];
7963 UIAlertView *alert = [[[UIAlertView alloc]
7964 initWithTitle:UCLocalize("NOT_REPOSITORY")
7965 message:UCLocalize("NOT_REPOSITORY_EX")
7967 cancelButtonTitle:UCLocalize("OK")
7968 otherButtonTitles:nil
7971 [alert setContext:@"trivial"];
7980 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7981 switch ([response statusCode]) {
7987 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7988 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7990 [self _endConnection:connection];
7993 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7994 [self _endConnection:connection];
7997 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7998 NSMutableURLRequest *request = [NSMutableURLRequest
7999 requestWithURL:[NSURL URLWithString:href]
8000 cachePolicy:NSURLRequestUseProtocolCachePolicy
8001 timeoutInterval:120.0
8004 [request setHTTPMethod:method];
8006 if (Machine_ != NULL)
8007 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8008 if (UniqueID_ != nil)
8009 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8011 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8014 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8015 NSString *context([alert context]);
8017 if ([context isEqualToString:@"source"]) {
8020 NSString *href = [[alert textField] text];
8022 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8024 if (![href hasSuffix:@"/"])
8025 href_ = [href stringByAppendingString:@"/"];
8029 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8030 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8031 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8032 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8036 // XXX: this is stupid
8037 hud_ = [delegate_ addProgressHUD];
8038 [hud_ setText:UCLocalize("VERIFYING_URL")];
8039 [delegate_ retainNetworkActivityIndicator];
8048 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8049 } else if ([context isEqualToString:@"trivial"])
8050 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8051 else if ([context isEqualToString:@"urlerror"])
8052 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8053 else if ([context isEqualToString:@"warning"]) {
8067 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8072 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8074 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8075 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8076 [list_ setRowHeight:56];
8077 [(UITableView *) list_ setDataSource:self];
8078 [list_ setDelegate:self];
8079 [[self view] addSubview:list_];
8082 - (void) viewDidLoad {
8083 [super viewDidLoad];
8085 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8086 [self updateButtonsForEditingStatus:NO animated:NO];
8089 - (void) releaseSubviews {
8093 - (id) initWithDatabase:(Database *)database {
8094 if ((self = [super init]) != nil) {
8095 database_ = database;
8096 sources_ = [NSMutableArray arrayWithCapacity:16];
8100 - (void) reloadData {
8104 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8107 [sources_ removeAllObjects];
8108 [sources_ addObjectsFromArray:[database_ sources]];
8110 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8113 int count([sources_ count]);
8115 for (int i = 0; i != count; i++) {
8116 if ([[sources_ objectAtIndex:i] record] == nil)
8121 [list_ setEditing:NO];
8122 [self updateButtonsForEditingStatus:NO animated:NO];
8126 - (void) showAddSourcePrompt {
8127 UIAlertView *alert = [[[UIAlertView alloc]
8128 initWithTitle:UCLocalize("ENTER_APT_URL")
8131 cancelButtonTitle:UCLocalize("CANCEL")
8133 UCLocalize("ADD_SOURCE"),
8137 [alert setContext:@"source"];
8139 [alert setNumberOfRows:1];
8140 [alert addTextFieldWithValue:@"http://" label:@""];
8142 UITextInputTraits *traits = [[alert textField] textInputTraits];
8143 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8144 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8145 [traits setKeyboardType:UIKeyboardTypeURL];
8146 // XXX: UIReturnKeyDone
8147 [traits setReturnKeyType:UIReturnKeyNext];
8152 - (void) addButtonClicked {
8153 [self showAddSourcePrompt];
8156 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8157 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8158 initWithTitle:UCLocalize("ADD")
8159 style:UIBarButtonItemStylePlain
8161 action:@selector(addButtonClicked)
8162 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8164 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8165 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8166 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8168 action:@selector(editButtonClicked)
8169 ] autorelease] animated:animated];
8171 if (IsWildcat_ && !editing)
8172 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8173 initWithTitle:UCLocalize("SETTINGS")
8174 style:UIBarButtonItemStylePlain
8176 action:@selector(settingsButtonClicked)
8180 - (void) settingsButtonClicked {
8181 [delegate_ showSettings];
8184 - (void) editButtonClicked {
8185 [list_ setEditing:![list_ isEditing] animated:YES];
8187 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8193 /* Settings Controller {{{ */
8194 @interface SettingsController : CyteViewController <
8195 UITableViewDataSource,
8198 _transient Database *database_;
8199 // XXX: ok, "roledelegate_"?...
8200 _transient id roledelegate_;
8201 _H<UITableView, 2> table_;
8202 _H<UISegmentedControl> segment_;
8203 _H<UIView> container_;
8206 - (void) showDoneButton;
8207 - (void) resizeSegmentedControl;
8211 @implementation SettingsController
8214 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8216 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8217 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8218 [table_ setDelegate:self];
8219 [(UITableView *) table_ setDataSource:self];
8220 [[self view] addSubview:table_];
8222 NSArray *items = [NSArray arrayWithObjects:
8224 UCLocalize("HACKER"),
8225 UCLocalize("DEVELOPER"),
8227 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8228 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8229 [container_ addSubview:segment_];
8232 - (void) viewDidLoad {
8233 [super viewDidLoad];
8235 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8238 if ([Role_ isEqualToString:@"User"]) index = 0;
8239 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8240 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8242 [segment_ setSelectedSegmentIndex:index];
8243 [self showDoneButton];
8246 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8247 [self resizeSegmentedControl];
8250 - (void) releaseSubviews {
8256 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8257 if ((self = [super init]) != nil) {
8258 database_ = database;
8259 roledelegate_ = delegate;
8263 - (void) resizeSegmentedControl {
8264 CGFloat width = [[self view] frame].size.width;
8265 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8268 - (void) viewWillAppear:(BOOL)animated {
8269 [super viewWillAppear:animated];
8271 [self resizeSegmentedControl];
8274 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8275 [self resizeSegmentedControl];
8278 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8279 [self resizeSegmentedControl];
8283 NSString *role(nil);
8285 switch ([segment_ selectedSegmentIndex]) {
8286 case 0: role = @"User"; break;
8287 case 1: role = @"Hacker"; break;
8288 case 2: role = @"Developer"; break;
8293 if (![role isEqualToString:Role_]) {
8294 bool rolling(Role_ == nil);
8297 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8301 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8305 [roledelegate_ loadData];
8307 [roledelegate_ updateData];
8311 - (void) segmentChanged:(UISegmentedControl *)control {
8312 [self showDoneButton];
8315 - (void) saveAndClose {
8318 [[self navigationItem] setRightBarButtonItem:nil];
8319 [[self navigationController] dismissModalViewControllerAnimated:YES];
8322 - (void) doneButtonClicked {
8323 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8324 [spinner startAnimating];
8325 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8326 [[self navigationItem] setRightBarButtonItem:spinItem];
8328 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8331 - (void) showDoneButton {
8332 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8333 initWithTitle:UCLocalize("DONE")
8334 style:UIBarButtonItemStyleDone
8336 action:@selector(doneButtonClicked)
8337 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8340 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8341 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8345 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8349 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8350 return nil; // This method is required by the protocol.
8353 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8355 return UCLocalize("ROLE_EX");
8357 return [NSString stringWithFormat:
8358 @"%@: %@\n%@: %@\n%@: %@",
8359 UCLocalize("USER"), UCLocalize("USER_EX"),
8360 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8361 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8366 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8367 return section == 3 ? 44.0f : 0;
8370 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8371 return section == 3 ? container_ : nil;
8374 - (void) reloadData {
8377 [table_ reloadData];
8382 /* Stash Controller {{{ */
8383 @interface StashController : CyteViewController {
8384 _H<UIActivityIndicatorView> spinner_;
8385 _H<UILabel> status_;
8386 _H<UILabel> caption_;
8391 @implementation StashController
8394 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8395 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8397 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8398 CGRect spinrect = [spinner_ frame];
8399 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8400 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8401 [spinner_ setFrame:spinrect];
8402 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8403 [[self view] addSubview:spinner_];
8404 [spinner_ startAnimating];
8407 captrect.size.width = [[self view] frame].size.width;
8408 captrect.size.height = 40.0f;
8409 captrect.origin.x = 0;
8410 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8411 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8412 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8413 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8414 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8415 [caption_ setTextColor:[UIColor whiteColor]];
8416 [caption_ setBackgroundColor:[UIColor clearColor]];
8417 [caption_ setShadowColor:[UIColor blackColor]];
8418 [caption_ setTextAlignment:UITextAlignmentCenter];
8419 [[self view] addSubview:caption_];
8422 statusrect.size.width = [[self view] frame].size.width;
8423 statusrect.size.height = 30.0f;
8424 statusrect.origin.x = 0;
8425 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8426 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8427 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8428 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8429 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8430 [status_ setTextColor:[UIColor whiteColor]];
8431 [status_ setBackgroundColor:[UIColor clearColor]];
8432 [status_ setShadowColor:[UIColor blackColor]];
8433 [status_ setTextAlignment:UITextAlignmentCenter];
8434 [[self view] addSubview:status_];
8440 @interface CYURLCache : SDURLCache {
8445 @implementation CYURLCache
8447 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8450 else if ([event isEqualToString:@"no-cache"])
8452 else if ([event isEqualToString:@"store"])
8454 else if ([event isEqualToString:@"invalid"])
8456 else if ([event isEqualToString:@"memory"])
8458 else if ([event isEqualToString:@"disk"])
8460 else if ([event isEqualToString:@"miss"])
8463 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8467 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8468 if (NSURLResponse *response = [cached response])
8469 if (NSString *mime = [response MIMEType])
8470 if ([mime isEqualToString:@"text/cache-manifest"]) {
8471 NSURL *url([response URL]);
8474 NSLog(@"###: %@", [url absoluteString]);
8477 @synchronized (HostConfig_) {
8478 [CachedURLs_ addObject:url];
8482 [super storeCachedResponse:cached forRequest:request];
8487 @interface Cydia : UIApplication <
8488 ConfirmationControllerDelegate,
8491 UINavigationControllerDelegate,
8492 UITabBarControllerDelegate
8494 _H<UIWindow> window_;
8495 _H<CYTabBarController> tabbar_;
8496 _H<CydiaLoadingViewController> emulated_;
8498 _H<NSMutableArray> essential_;
8499 _H<NSMutableArray> broken_;
8501 Database *database_;
8503 _H<NSURL> starturl_;
8508 _H<StashController> stash_;
8517 @implementation Cydia
8519 - (void) beginUpdate {
8520 [tabbar_ beginUpdate];
8524 return [tabbar_ updating];
8528 if ([broken_ count] != 0) {
8529 int count = [broken_ count];
8531 UIAlertView *alert = [[[UIAlertView alloc]
8532 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8533 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8535 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8537 UCLocalize("TEMPORARY_IGNORE"),
8541 [alert setContext:@"fixhalf"];
8542 [alert setNumberOfRows:2];
8544 } else if (!Ignored_ && [essential_ count] != 0) {
8545 int count = [essential_ count];
8547 UIAlertView *alert = [[[UIAlertView alloc]
8548 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8549 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8551 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8553 UCLocalize("UPGRADE_ESSENTIAL"),
8554 UCLocalize("COMPLETE_UPGRADE"),
8558 [alert setContext:@"upgrade"];
8563 - (void) _saveConfig {
8569 NSString *error(nil);
8571 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8573 NSError *error(nil);
8574 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8575 NSLog(@"failure to save metadata data: %@", error);
8580 NSLog(@"failure to serialize metadata: %@", error);
8585 // Navigation controller for the queuing badge.
8586 - (UINavigationController *) queueNavigationController {
8587 NSArray *controllers = [tabbar_ viewControllers];
8588 return [controllers objectAtIndex:3];
8591 - (void) unloadData {
8592 [tabbar_ unloadData];
8595 - (void) _updateData {
8600 UINavigationController *navigation = [self queueNavigationController];
8602 id queuedelegate = nil;
8603 if ([[navigation viewControllers] count] > 0)
8604 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8606 [queuedelegate queueStatusDidChange];
8607 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8610 - (void) _refreshIfPossible:(NSDate *)update {
8611 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8613 bool recently = false;
8614 if (update != nil) {
8615 NSTimeInterval interval([update timeIntervalSinceNow]);
8616 if (interval <= 0 && interval > -(15*60))
8620 // Don't automatic refresh if:
8621 // - We already refreshed recently.
8622 // - We already auto-refreshed this launch.
8623 // - Auto-refresh is disabled.
8624 if (recently || loaded_ || ManualRefresh) {
8625 // If we are cancelling, we need to make sure it knows it's already loaded.
8628 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8630 // We are going to load, so remember that.
8633 SCNetworkReachabilityFlags flags; {
8634 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8635 SCNetworkReachabilityGetFlags(reachability, &flags);
8636 CFRelease(reachability);
8639 // XXX: this elaborate mess is what Apple is using to determine this? :(
8640 // XXX: do we care if the user has to intervene? maybe that's ok?
8642 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8643 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8644 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8645 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8646 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8647 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8651 // If we can reach the server, auto-refresh!
8653 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8659 - (void) refreshIfPossible {
8660 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8663 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8664 @synchronized (self) {
8665 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8666 [hud setText:UCLocalize("RELOADING_DATA")];
8668 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8671 [self removeProgressHUD:hud];
8675 [essential_ removeAllObjects];
8676 [broken_ removeAllObjects];
8678 NSArray *packages([database_ packages]);
8679 for (Package *package in packages) {
8681 [broken_ addObject:package];
8682 if ([package upgradableAndEssential:NO]) {
8683 if ([package essential])
8684 [essential_ addObject:package];
8689 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8692 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8693 [changesItem setBadgeValue:badge];
8694 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8695 [self setApplicationIconBadgeNumber:changes];
8698 [changesItem setBadgeValue:nil];
8699 [changesItem setAnimatedBadge:NO];
8700 [self setApplicationIconBadgeNumber:0];
8705 [self refreshIfPossible];
8708 - (void) updateData {
8714 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8717 - (void) disemulate {
8718 if (emulated_ == nil)
8721 [window_ addSubview:[tabbar_ view]];
8722 [[emulated_ view] removeFromSuperview];
8724 [window_ setUserInteractionEnabled:YES];
8727 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8728 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8730 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8732 UIViewController *parent;
8733 if (emulated_ == nil)
8742 [parent presentModalViewController:navigation animated:YES];
8745 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8746 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8748 if (navigation != nil)
8749 [navigation pushViewController:progress animated:YES];
8751 [self presentModalViewController:progress force:YES];
8753 [progress invoke:invocation withTitle:title];
8757 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8758 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8761 - (void) repairWithInvocation:(NSInvocation *)invocation {
8763 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8767 - (void) repairWithSelector:(SEL)selector {
8768 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8771 - (void) reloadData {
8772 [self reloadDataWithInvocation:nil];
8778 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8779 _assert(file != NULL);
8781 for (NSString *key in [Sources_ allKeys]) {
8782 NSDictionary *source([Sources_ objectForKey:key]);
8784 fprintf(file, "%s %s %s\n",
8785 [[source objectForKey:@"Type"] UTF8String],
8786 [[source objectForKey:@"URI"] UTF8String],
8787 [[source objectForKey:@"Distribution"] UTF8String]
8793 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8796 - (void) addTrivialSource:(NSString *)href {
8797 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8800 @"./", @"Distribution",
8801 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8807 pkgProblemResolver *resolver = [database_ resolver];
8809 resolver->InstallProtect();
8810 if (!resolver->Resolve(true))
8815 // XXX: this is a really crappy way of doing this.
8816 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8817 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8818 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8819 if ([tabbar_ updating])
8820 [tabbar_ cancelUpdate];
8822 if (![database_ prepare])
8825 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8826 [page setDelegate:self];
8827 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8830 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8831 [tabbar_ presentModalViewController:confirm_ animated:YES];
8837 @synchronized (self) {
8842 - (void) clearPackage:(Package *)package {
8843 @synchronized (self) {
8850 - (void) installPackages:(NSArray *)packages {
8851 @synchronized (self) {
8852 for (Package *package in packages)
8859 - (void) installPackage:(Package *)package {
8860 @synchronized (self) {
8867 - (void) removePackage:(Package *)package {
8868 @synchronized (self) {
8875 - (void) distUpgrade {
8876 @synchronized (self) {
8877 if (![database_ upgrade])
8884 [database_ perform];
8885 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8888 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8891 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8895 - (void) showSettings {
8896 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8899 - (void) retainNetworkActivityIndicator {
8900 if (activity_++ == 0)
8901 [self setNetworkActivityIndicatorVisible:YES];
8904 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8908 - (void) releaseNetworkActivityIndicator {
8909 if (--activity_ == 0)
8910 [self setNetworkActivityIndicatorVisible:NO];
8913 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8918 - (void) cancelAndClear:(bool)clear {
8919 @synchronized (self) {
8931 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8932 NSString *context([alert context]);
8934 if ([context isEqualToString:@"conffile"]) {
8935 FILE *input = [database_ input];
8936 if (button == [alert cancelButtonIndex])
8937 fprintf(input, "N\n");
8938 else if (button == [alert firstOtherButtonIndex])
8939 fprintf(input, "Y\n");
8942 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8943 } else if ([context isEqualToString:@"fixhalf"]) {
8944 if (button == [alert cancelButtonIndex]) {
8945 @synchronized (self) {
8946 for (Package *broken in (id) broken_) {
8949 NSString *id = [broken id];
8950 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8951 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8952 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8953 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8959 } else if (button == [alert firstOtherButtonIndex]) {
8960 [broken_ removeAllObjects];
8964 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8965 } else if ([context isEqualToString:@"upgrade"]) {
8966 if (button == [alert firstOtherButtonIndex]) {
8967 @synchronized (self) {
8968 for (Package *essential in (id) essential_)
8969 [essential install];
8974 } else if (button == [alert firstOtherButtonIndex] + 1) {
8976 } else if (button == [alert cancelButtonIndex]) {
8980 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8984 - (void) system:(NSString *)command {
8985 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8988 system([command UTF8String]);
8994 - (void) applicationWillSuspend {
8996 [super applicationWillSuspend];
8999 - (BOOL) isSafeToSuspend {
9002 NSLog(@"isSafeToSuspend: locked_ != 0");
9007 // Use external process status API internally.
9008 // This is probably a really bad idea.
9009 // XXX: what is the point of this? does this solve anything at all?
9010 uint64_t status = 0;
9012 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9013 notify_get_state(notify_token, &status);
9014 notify_cancel(notify_token);
9019 NSLog(@"isSafeToSuspend: status != 0");
9025 NSLog(@"isSafeToSuspend: -> true");
9030 - (void) applicationSuspend:(__GSEvent *)event {
9031 if ([self isSafeToSuspend])
9032 [super applicationSuspend:event];
9035 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9036 if ([self isSafeToSuspend])
9037 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9040 - (void) _setSuspended:(BOOL)value {
9041 if ([self isSafeToSuspend])
9042 [super _setSuspended:value];
9045 - (UIProgressHUD *) addProgressHUD {
9046 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9047 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9049 [window_ setUserInteractionEnabled:NO];
9051 UIViewController *target(tabbar_);
9052 if (UIViewController *modal = [target modalViewController])
9055 UIView *view([target view]);
9056 [view addSubview:hud];
9064 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9067 [hud removeFromSuperview];
9068 [window_ setUserInteractionEnabled:YES];
9071 - (CyteViewController *) pageForPackage:(NSString *)name {
9072 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9075 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9076 NSString *scheme([[url scheme] lowercaseString]);
9077 if ([[url absoluteString] length] <= [scheme length] + 3)
9079 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9080 NSArray *components([path pathComponents]);
9082 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9083 return [self pageForPackage:[components objectAtIndex:1]];
9085 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9088 NSString *base([components objectAtIndex:0]);
9090 CyteViewController *controller = nil;
9092 if ([base isEqualToString:@"url"]) {
9093 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9094 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9095 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9096 } else if (!external && [components count] == 1) {
9097 if ([base isEqualToString:@"manage"]) {
9098 controller = [[[ManageController alloc] init] autorelease];
9101 if ([base isEqualToString:@"sources"]) {
9102 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9105 if ([base isEqualToString:@"home"]) {
9106 controller = [[[HomeController alloc] init] autorelease];
9109 if ([base isEqualToString:@"sections"]) {
9110 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9113 if ([base isEqualToString:@"search"]) {
9114 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9117 if ([base isEqualToString:@"changes"]) {
9118 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9121 if ([base isEqualToString:@"installed"]) {
9122 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9124 } else if ([components count] == 2) {
9125 NSString *argument = [components objectAtIndex:1];
9127 if ([base isEqualToString:@"package"]) {
9128 controller = [self pageForPackage:argument];
9131 if (!external && [base isEqualToString:@"search"]) {
9132 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9135 if (!external && [base isEqualToString:@"sections"]) {
9136 if ([argument isEqualToString:@"all"])
9138 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9141 if (!external && [base isEqualToString:@"sources"]) {
9142 if ([argument isEqualToString:@"add"]) {
9143 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9144 [(SourcesController *)controller showAddSourcePrompt];
9146 Source *source = [database_ sourceWithKey:argument];
9147 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9151 if (!external && [base isEqualToString:@"launch"]) {
9152 [self launchApplicationWithIdentifier:argument suspended:NO];
9155 } else if (!external && [components count] == 3) {
9156 NSString *arg1 = [components objectAtIndex:1];
9157 NSString *arg2 = [components objectAtIndex:2];
9159 if ([base isEqualToString:@"package"]) {
9160 if ([arg2 isEqualToString:@"settings"]) {
9161 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9162 } else if ([arg2 isEqualToString:@"files"]) {
9163 if (Package *package = [database_ packageWithName:arg1]) {
9164 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9165 [(FileTable *)controller setPackage:package];
9171 [controller setDelegate:self];
9175 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9176 CyteViewController *page([self pageForURL:url forExternal:external]);
9179 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9180 [nav setViewControllers:[NSArray arrayWithObject:page]];
9181 [tabbar_ setUnselectedViewController:nav];
9187 - (void) applicationOpenURL:(NSURL *)url {
9188 [super applicationOpenURL:url];
9193 [self openCydiaURL:url forExternal:YES];
9196 - (void) applicationWillResignActive:(UIApplication *)application {
9197 // Stop refreshing if you get a phone call or lock the device.
9198 if ([tabbar_ updating])
9199 [tabbar_ cancelUpdate];
9201 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9202 [super applicationWillResignActive:application];
9205 - (void) applicationWillTerminate:(UIApplication *)application {
9207 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9208 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9209 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9214 - (void) setConfigurationData:(NSString *)data {
9215 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9217 if (!conffile_r(data)) {
9218 lprintf("E:invalid conffile\n");
9222 NSString *ofile = conffile_r[1];
9223 //NSString *nfile = conffile_r[2];
9225 UIAlertView *alert = [[[UIAlertView alloc]
9226 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9227 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9229 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9231 UCLocalize("ACCEPT_NEW_COPY"),
9232 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9236 [alert setContext:@"conffile"];
9237 [alert setNumberOfRows:2];
9241 - (void) addStashController {
9243 stash_ = [[[StashController alloc] init] autorelease];
9244 [window_ addSubview:[stash_ view]];
9247 - (void) removeStashController {
9248 [[stash_ view] removeFromSuperview];
9254 [self setIdleTimerDisabled:YES];
9256 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9257 UpdateExternalStatus(1);
9258 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9259 UpdateExternalStatus(0);
9261 [self removeStashController];
9263 if (ExecFork() == 0) {
9264 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9265 perror("launchctl stop");
9269 - (void) setupViewControllers {
9270 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9272 NSMutableArray *items([NSMutableArray arrayWithObjects:
9273 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9274 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9275 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9276 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9280 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9281 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9283 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9286 NSMutableArray *controllers([NSMutableArray array]);
9287 for (UITabBarItem *item in items) {
9288 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9289 [controller setTabBarItem:item];
9290 [controllers addObject:controller];
9292 [tabbar_ setViewControllers:controllers];
9294 [tabbar_ setUpdateDelegate:self];
9297 - (void) applicationDidFinishLaunching:(id)unused {
9299 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9300 [self setApplicationSupportsShakeToEdit:NO];
9302 @synchronized (HostConfig_) {
9303 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9306 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9307 initWithMemoryCapacity:524288
9308 diskCapacity:10485760
9309 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9312 [CydiaWebViewController _initialize];
9314 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9316 // this would disallow http{,s} URLs from accessing this data
9317 //[WebView registerURLSchemeAsLocal:@"cydia"];
9319 Font12_ = [UIFont systemFontOfSize:12];
9320 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9321 Font14_ = [UIFont systemFontOfSize:14];
9322 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9323 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9325 essential_ = [NSMutableArray arrayWithCapacity:4];
9326 broken_ = [NSMutableArray arrayWithCapacity:4];
9328 // XXX: I really need this thing... like, seriously... I'm sorry
9329 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9331 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9332 [window_ orderFront:self];
9333 [window_ makeKey:self];
9334 [window_ setHidden:NO];
9337 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9338 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9339 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9340 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9341 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9342 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9343 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9344 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9345 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9348 [self addStashController];
9349 // XXX: this would be much cleaner as a yieldToSelector:
9350 // that way the removeStashController could happen right here inline
9351 // we also could no longer require the useless stash_ field anymore
9352 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9356 database_ = [Database sharedInstance];
9357 [database_ setDelegate:self];
9359 [window_ setUserInteractionEnabled:NO];
9360 [self setupViewControllers];
9362 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9363 [window_ addSubview:[emulated_ view]];
9365 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9369 - (NSArray *) defaultStartPages {
9370 NSMutableArray *standard = [NSMutableArray array];
9371 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9372 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9373 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9375 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9377 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9378 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9380 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9387 [window_ setUserInteractionEnabled:YES];
9388 [self showSettings];
9391 if ([emulated_ modalViewController] != nil)
9392 [emulated_ dismissModalViewControllerAnimated:YES];
9393 [window_ setUserInteractionEnabled:NO];
9401 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9402 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9403 int standardIndex = 0;
9404 NSArray *standard = [self defaultStartPages];
9411 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9412 if (valid && closed != nil) {
9413 NSTimeInterval interval([closed timeIntervalSinceNow]);
9414 // XXX: Is 15 minutes the optimal time here?
9415 if (interval > 0 && interval <= -(15*60))
9419 if (valid && [saved count] != [standard count])
9423 for (unsigned int i = 0; i < [standard count]; i++) {
9424 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9425 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9426 // but it's good enough for now.
9427 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9434 NSArray *items = nil;
9436 [tabbar_ setSelectedIndex:savedIndex];
9439 [tabbar_ setSelectedIndex:standardIndex];
9443 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9444 NSArray *stack = [items objectAtIndex:tab];
9445 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9446 NSMutableArray *current = [NSMutableArray array];
9448 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9449 NSString *addr = [stack objectAtIndex:nav];
9450 NSURL *url = [NSURL URLWithString:addr];
9451 CyteViewController *page = [self pageForURL:url forExternal:NO];
9453 [current addObject:page];
9456 [navigation setViewControllers:current];
9459 // (Try to) show the startup URL.
9460 if (starturl_ != nil) {
9461 [self openCydiaURL:starturl_ forExternal:NO];
9466 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9467 if (item != nil && IsWildcat_) {
9468 [sheet showFromBarButtonItem:item animated:YES];
9470 [sheet showInView:window_];
9474 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9475 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9476 [progress setTitle:task];
9477 [progress addProgressEvent:event];
9480 - (void) addProgressEventForTask:(NSArray *)data {
9481 CydiaProgressEvent *event([data objectAtIndex:0]);
9482 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9483 [self addProgressEvent:event forTask:task];
9486 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9487 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9493 id Alloc_(id self, SEL selector) {
9494 id object = alloc_(self, selector);
9495 lprintf("[%s]A-%p\n", self->isa->name, object);
9500 id Dealloc_(id self, SEL selector) {
9501 id object = dealloc_(self, selector);
9502 lprintf("[%s]D-%p\n", self->isa->name, object);
9506 Class $WebDefaultUIKitDelegate;
9508 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9509 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9510 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9511 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9514 static NSSet *MobilizedFiles_;
9516 static NSURL *MobilizeURL(NSURL *url) {
9517 NSString *path([url path]);
9518 if ([path hasPrefix:@"/var/root/"]) {
9519 NSString *file([path substringFromIndex:10]);
9520 if ([MobilizedFiles_ containsObject:file])
9521 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9527 Class $CFXPreferencesPropertyListSource;
9528 @class CFXPreferencesPropertyListSource;
9530 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9531 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9532 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9533 url = MobilizeURL(url);
9534 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9535 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9541 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9542 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9543 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9544 url = MobilizeURL(url);
9545 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9546 //NSLog(@"%@ %@", [url absoluteString], value);
9552 Class $NSURLConnection;
9554 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9555 NSMutableURLRequest *copy([request mutableCopy]);
9557 NSURL *url([copy URL]);
9559 NSString *href([url absoluteString]);
9560 NSString *host([url host]);
9561 NSString *scheme([[url scheme] lowercaseString]);
9563 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9565 @synchronized (HostConfig_) {
9566 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9567 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9568 [copy setHTTPShouldUsePipelining:YES];
9570 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9571 if ([control isEqualToString:@"max-age=0"])
9572 if ([CachedURLs_ containsObject:href]) {
9574 NSLog(@"~~~: %@", href);
9577 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9579 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9580 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9581 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9585 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9589 int main(int argc, char *argv[]) {
9590 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9594 UpdateExternalStatus(0);
9596 if (Class $UIDevice = objc_getClass("UIDevice")) {
9597 UIDevice *device([$UIDevice currentDevice]);
9598 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9602 UIScreen *screen([UIScreen mainScreen]);
9603 if ([screen respondsToSelector:@selector(scale)])
9604 ScreenScale_ = [screen scale];
9608 UIDevice *device([UIDevice currentDevice]);
9609 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9612 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9613 if (idiom == UIUserInterfaceIdiomPhone)
9615 else if (idiom == UIUserInterfaceIdiomPad)
9618 NSLog(@"unknown UIUserInterfaceIdiom!");
9621 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9623 HostConfig_ = [[[NSObject alloc] init] autorelease];
9624 @synchronized (HostConfig_) {
9625 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9626 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9627 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9630 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9632 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9634 MobilizedFiles_ = [NSMutableSet setWithObjects:
9635 @"Library/Preferences/com.apple.Accessibility.plist",
9636 @"Library/Preferences/com.apple.preferences.sounds.plist",
9639 /* Library Hacks {{{ */
9640 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9642 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9644 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9645 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9646 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9647 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9650 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9651 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9652 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9653 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9656 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9657 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9658 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9659 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9660 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9663 $NSURLConnection = objc_getClass("NSURLConnection");
9664 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9665 if (NSURLConnection$init$ != NULL) {
9666 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9667 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9670 /* Set Locale {{{ */
9671 Locale_ = CFLocaleCopyCurrent();
9672 Languages_ = [NSLocale preferredLanguages];
9674 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9675 //NSLog(@"%@", [Languages_ description]);
9678 if (Locale_ != NULL)
9679 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9680 else if (Languages_ != nil && [Languages_ count] != 0)
9681 lang = [[Languages_ objectAtIndex:0] UTF8String];
9683 // XXX: consider just setting to C and then falling through?
9687 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9688 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9691 NSLog(@"Setting Language: %s", lang);
9694 setenv("LANG", lang, true);
9695 std::setlocale(LC_ALL, lang);
9699 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9701 /* Parse Arguments {{{ */
9702 bool substrate(false);
9708 for (int argi(1); argi != argc; ++argi)
9709 if (strcmp(argv[argi], "--") == 0) {
9711 argv[argi] = argv[0];
9717 for (int argi(1); argi != arge; ++argi)
9718 if (strcmp(args[argi], "--substrate") == 0)
9721 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9725 App_ = [[NSBundle mainBundle] bundlePath];
9731 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9732 alloc_ = alloc->method_imp;
9733 alloc->method_imp = (IMP) &Alloc_;*/
9735 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9736 dealloc_ = dealloc->method_imp;
9737 dealloc->method_imp = (IMP) &Dealloc_;*/
9739 /* System Information {{{ */
9743 size = sizeof(maxproc);
9744 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9745 perror("sysctlbyname(\"kern.maxproc\", ?)");
9746 else if (maxproc < 64) {
9748 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9749 perror("sysctlbyname(\"kern.maxproc\", #)");
9752 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9753 char *osversion = new char[size];
9754 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9755 perror("sysctlbyname(\"kern.osversion\", ?)");
9757 System_ = [NSString stringWithUTF8String:osversion];
9759 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9760 char *machine = new char[size];
9761 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9762 perror("sysctlbyname(\"hw.machine\", ?)");
9766 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9767 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9768 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9770 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9772 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9773 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9774 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9776 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9777 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9778 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9780 if (mcc != NULL && mnc != NULL)
9781 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9788 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9789 Build_ = [system objectForKey:@"ProductBuildVersion"];
9790 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9791 Product_ = [info objectForKey:@"SafariProductVersion"];
9792 Safari_ = [info objectForKey:@"CFBundleVersion"];
9795 /* Load Database {{{ */
9797 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9799 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9801 if (Metadata_ == NULL)
9802 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9804 Settings_ = [Metadata_ objectForKey:@"Settings"];
9806 Packages_ = [Metadata_ objectForKey:@"Packages"];
9807 Sections_ = [Metadata_ objectForKey:@"Sections"];
9808 Sources_ = [Metadata_ objectForKey:@"Sources"];
9810 Token_ = [Metadata_ objectForKey:@"Token"];
9813 if (Settings_ != nil)
9814 Role_ = [Settings_ objectForKey:@"Role"];
9816 if (Sections_ == nil) {
9817 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9818 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9821 if (Sources_ == nil) {
9822 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9823 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9828 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9831 if (Packages_ != nil) {
9833 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9837 [Metadata_ removeObjectForKey:@"Packages"];
9843 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9845 #define MobileSubstrate_(name) \
9846 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9847 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9848 if (handle == NULL) \
9849 NSLog(@"%s", dlerror()); \
9852 MobileSubstrate_(Activator)
9853 MobileSubstrate_(libstatusbar)
9854 MobileSubstrate_(SimulatedKeyEvents)
9855 MobileSubstrate_(WinterBoard)
9857 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9858 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9860 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9862 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9863 unlink("/tmp/.cydia.fw");
9865 } else if (access("/User", F_OK) != 0 || version < 4) {
9868 system("/usr/libexec/cydia/firmware.sh");
9872 _assert([[NSFileManager defaultManager]
9873 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9874 withIntermediateDirectories:YES
9879 if (access("/tmp/cydia.chk", F_OK) == 0) {
9880 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9881 _assert(errno == ENOENT);
9882 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9883 _assert(errno == ENOENT);
9886 /* APT Initialization {{{ */
9887 _assert(pkgInitConfig(*_config));
9888 _assert(pkgInitSystem(*_config, _system));
9891 _config->Set("APT::Acquire::Translation", lang);
9893 // XXX: this timeout might be important :(
9894 //_config->Set("Acquire::http::Timeout", 15);
9896 _config->Set("Acquire::http::MaxParallel", 3);
9898 /* Color Choices {{{ */
9899 space_ = CGColorSpaceCreateDeviceRGB();
9901 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9902 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9903 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9904 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9905 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9906 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9907 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9908 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9909 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9911 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9912 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9914 /* UIKit Configuration {{{ */
9915 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9916 if ($GSFontSetUseLegacyFontMetrics != NULL)
9917 $GSFontSetUseLegacyFontMetrics(YES);
9919 // XXX: I have a feeling this was important
9920 //UIKeyboardDisableAutomaticAppearance();
9923 Colon_ = UCLocalize("COLON_DELIMITED");
9924 Elision_ = UCLocalize("ELISION");
9925 Error_ = UCLocalize("ERROR");
9926 Warning_ = UCLocalize("WARNING");
9929 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9931 CGColorSpaceRelease(space_);