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/ProgressEvent.h"
135 #include "SDURLCache/SDURLCache.h"
142 #define _timestamp ({ \
144 gettimeofday(&tv, NULL); \
145 tv.tv_sec * 1000000 + tv.tv_usec; \
148 typedef std::vector<class ProfileTime *> TimeList;
158 ProfileTime(const char *name) :
162 times_.push_back(this);
165 void AddTime(uint64_t time) {
172 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
184 ProfileTimer(ProfileTime &time) :
191 time_.AddTime(_timestamp - start_);
196 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
198 std::cerr << "========" << std::endl;
201 #define _profile(name) { \
202 static ProfileTime name(#name); \
203 ProfileTimer _ ## name(name);
208 #define Cydia_ CYDIA_VERSION
210 #define lprintf(args...) fprintf(stderr, args)
213 #define TraceLogging (1 && !ForRelease)
214 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
215 #define ProfileTimes (0 && !ForRelease)
216 #define ForSaurik (0 && !ForRelease)
217 #define LogBrowser (0 && !ForRelease)
218 #define TrackResize (0 && !ForRelease)
219 #define ManualRefresh (1 && !ForRelease)
220 #define ShowInternals (0 && !ForRelease)
221 #define AlwaysReload (0 && !ForRelease)
222 #define TryIndexedCollation (0 && !ForRelease)
226 #define _trace(args...)
231 #define _profile(name) {
234 #define PrintTimes() do {} while (false)
237 // Hash Functions/Structures {{{
238 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
246 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
248 static _finline NSString *CydiaURL(NSString *path) {
250 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
251 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
252 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
253 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
254 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
256 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
259 static _finline void UpdateExternalStatus(uint64_t newStatus) {
261 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
262 notify_set_state(notify_token, newStatus);
263 notify_cancel(notify_token);
265 notify_post("com.saurik.Cydia.status");
268 /* NSForcedOrderingSearch doesn't work on the iPhone */
269 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
270 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
271 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
273 /* Insertion Sort {{{ */
275 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
276 const char *ptr = (const char *)list;
278 CFIndex half = count / 2;
279 const char *probe = ptr + elementSize * half;
280 CFComparisonResult cr = comparator(element, probe, context);
281 if (0 == cr) return (probe - (const char *)list) / elementSize;
282 ptr = (cr < 0) ? ptr : probe + elementSize;
283 count = (cr < 0) ? half : (half + (count & 1) - 1);
285 return (ptr - (const char *)list) / elementSize;
288 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
289 const char *ptr = (const char *)list;
291 CFIndex half = count / 2;
292 const char *probe = ptr + elementSize * half;
293 CFComparisonResult cr = comparator(element, probe, context);
294 if (0 == cr) return (probe - (const char *)list) / elementSize;
295 ptr = (cr < 0) ? ptr : probe + elementSize;
296 count = (cr < 0) ? half : (half + (count & 1) - 1);
298 return (ptr - (const char *)list) / elementSize;
301 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
302 if (range.length == 0)
304 const void **values(new const void *[range.length]);
305 CFArrayGetValues(array, range, values);
307 #if HistogramInsertionSort > 0
308 uint32_t total(0), *offsets(new uint32_t[range.length]);
311 for (CFIndex index(1); index != range.length; ++index) {
312 const void *value(values[index]);
313 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
314 CFIndex correct(index);
315 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
316 #if HistogramInsertionSort > 1
317 NSLog(@"%@ < %@", value, values[correct - 1]);
322 if (correct != index) {
323 size_t offset(index - correct);
324 #if HistogramInsertionSort
328 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
330 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
331 values[correct] = value;
335 CFArrayReplaceValues(array, range, values, range.length);
338 #if HistogramInsertionSort > 0
339 for (CFIndex index(0); index != range.length; ++index)
340 if (offsets[index] != 0)
341 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
342 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
349 /* Apple Bug Fixes {{{ */
350 @implementation UIWebDocumentView (Cydia)
352 - (void) _setScrollerOffset:(CGPoint)offset {
353 UIScroller *scroller([self _scroller]);
355 CGSize size([scroller contentSize]);
356 CGSize bounds([scroller bounds].size);
359 max.x = size.width - bounds.width;
360 max.y = size.height - bounds.height;
368 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
369 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
371 [scroller setOffset:offset];
377 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
378 size_t length([self length] - state->state);
381 else if (length > count)
383 for (size_t i(0); i != length; ++i)
384 objects[i] = [self item:state->state++];
385 state->itemsPtr = objects;
386 state->mutationsPtr = (unsigned long *) self;
390 /* Cydia NSString Additions {{{ */
391 @interface NSString (Cydia)
392 - (NSComparisonResult) compareByPath:(NSString *)other;
393 - (NSString *) stringByCachingURLWithCurrentCDN;
394 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
397 @implementation NSString (Cydia)
399 - (NSComparisonResult) compareByPath:(NSString *)other {
400 NSString *prefix = [self commonPrefixWithString:other options:0];
401 size_t length = [prefix length];
403 NSRange lrange = NSMakeRange(length, [self length] - length);
404 NSRange rrange = NSMakeRange(length, [other length] - length);
406 lrange = [self rangeOfString:@"/" options:0 range:lrange];
407 rrange = [other rangeOfString:@"/" options:0 range:rrange];
409 NSComparisonResult value;
411 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
412 value = NSOrderedSame;
413 else if (lrange.location == NSNotFound)
414 value = NSOrderedAscending;
415 else if (rrange.location == NSNotFound)
416 value = NSOrderedDescending;
418 value = NSOrderedSame;
420 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
421 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
422 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
423 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
425 NSComparisonResult result = [lpath compare:rpath];
426 return result == NSOrderedSame ? value : result;
429 - (NSString *) stringByCachingURLWithCurrentCDN {
431 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
432 withString:@"://cache.cydia.saurik.com/"
436 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
437 return [(id)CFURLCreateStringByAddingPercentEscapes(
442 kCFStringEncodingUTF8
449 /* C++ NSString Wrapper Cache {{{ */
450 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
451 return size == 0 ? NULL :
452 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
453 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
456 static _finline CFStringRef CYStringCreate(const char *data) {
457 return CYStringCreate(data, strlen(data));
466 _finline void clear_() {
467 if (cache_ != NULL) {
474 _finline bool empty() const {
478 _finline size_t size() const {
482 _finline char *data() const {
486 _finline void clear() {
491 _finline CYString() :
498 _finline ~CYString() {
502 void operator =(const CYString &rhs) {
506 if (rhs.cache_ == nil)
509 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
512 void copy(apr_pool_t *pool) {
513 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
514 memcpy(temp, data_, size_);
519 void set(apr_pool_t *pool, const char *data, size_t size) {
525 data_ = const_cast<char *>(data);
533 _finline void set(apr_pool_t *pool, const char *data) {
534 set(pool, data, data == NULL ? 0 : strlen(data));
537 _finline void set(apr_pool_t *pool, const std::string &rhs) {
538 set(pool, rhs.data(), rhs.size());
541 bool operator ==(const CYString &rhs) const {
542 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
545 _finline operator CFStringRef() {
547 cache_ = CYStringCreate(data_, size_);
551 _finline operator id() {
552 return (NSString *) static_cast<CFStringRef>(*this);
555 _finline operator const char *() {
556 return reinterpret_cast<const char *>(data_);
560 /* C++ NSString Algorithm Adapters {{{ */
562 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
565 struct NSStringMapHash :
566 std::unary_function<NSString *, size_t>
568 _finline size_t operator ()(NSString *value) const {
569 return CFStringHashNSString((CFStringRef) value);
573 struct NSStringMapLess :
574 std::binary_function<NSString *, NSString *, bool>
576 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
577 return [lhs compare:rhs] == NSOrderedAscending;
581 struct NSStringMapEqual :
582 std::binary_function<NSString *, NSString *, bool>
584 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
585 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
586 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
587 //[lhs isEqualToString:rhs];
592 /* CoreGraphics Primitives {{{ */
597 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
598 CGFloat color[] = {red, green, blue, alpha};
599 return CGColorCreate(space, color);
608 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
609 color_(Create_(space, red, green, blue, alpha))
611 Set(space, red, green, blue, alpha);
616 CGColorRelease(color_);
623 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
625 color_ = Create_(space, red, green, blue, alpha);
628 operator CGColorRef() {
634 /* Random Global Variables {{{ */
635 static const int PulseInterval_ = 50000;
637 static const NSString *UI_;
640 static bool RestartSubstrate_;
641 static NSArray *Finishes_;
643 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
644 #define NotifyConfig_ "/etc/notify.conf"
646 static bool Queuing_;
648 static CYColor Blue_;
649 static CYColor Blueish_;
650 static CYColor Black_;
652 static CYColor White_;
653 static CYColor Gray_;
654 static CYColor Green_;
655 static CYColor Purple_;
656 static CYColor Purplish_;
658 static UIColor *InstallingColor_;
659 static UIColor *RemovingColor_;
661 static NSString *App_;
663 static BOOL Advanced_;
664 static BOOL Ignored_;
666 static _H<UIFont> Font12_;
667 static _H<UIFont> Font12Bold_;
668 static _H<UIFont> Font14_;
669 static _H<UIFont> Font18Bold_;
670 static _H<UIFont> Font22Bold_;
672 static const char *Machine_ = NULL;
673 static NSString *System_ = nil;
674 static NSString *SerialNumber_ = nil;
675 static NSString *ChipID_ = nil;
676 static NSString *BBSNum_ = nil;
677 static _H<NSString> Token_;
678 static NSString *UniqueID_ = nil;
679 static NSString *PLMN_ = nil;
680 static NSString *Build_ = nil;
681 static NSString *Product_ = nil;
682 static NSString *Safari_ = nil;
684 static CFLocaleRef Locale_;
685 static NSArray *Languages_;
686 static CGColorSpaceRef space_;
688 static NSDictionary *SectionMap_;
689 static NSMutableDictionary *Metadata_;
690 static _transient NSMutableDictionary *Settings_;
691 static _transient NSString *Role_;
692 static _transient NSMutableDictionary *Packages_;
693 static _transient NSMutableDictionary *Sections_;
694 static _transient NSMutableDictionary *Sources_;
695 static bool Changed_;
699 static CGFloat ScreenScale_;
700 static NSString *Idiom_;
702 static _H<NSMutableDictionary> SessionData_;
703 static _H<NSObject> HostConfig_;
704 static _H<NSMutableSet> BridgedHosts_;
705 static _H<NSMutableSet> PipelinedHosts_;
707 static NSString *kCydiaProgressEventTypeError = @"Error";
708 static NSString *kCydiaProgressEventTypeInformation = @"Information";
709 static NSString *kCydiaProgressEventTypeStatus = @"Status";
710 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
713 /* Display Helpers {{{ */
714 inline float Interpolate(float begin, float end, float fraction) {
715 return (end - begin) * fraction + begin;
718 static _finline const char *StripVersion_(const char *version) {
719 const char *colon(strchr(version, ':'));
720 return colon == NULL ? version : colon + 1;
723 NSString *LocalizeSection(NSString *section) {
724 static Pcre title_r("^(.*?) \\((.*)\\)$");
725 if (title_r(section)) {
726 NSString *parent(title_r[1]);
727 NSString *child(title_r[2]);
729 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
730 LocalizeSection(parent),
731 LocalizeSection(child)
735 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
738 NSString *Simplify(NSString *title) {
739 const char *data = [title UTF8String];
740 size_t size = [title length];
742 static Pcre square_r("^\\[(.*)\\]$");
743 if (square_r(data, size))
744 return Simplify(square_r[1]);
746 static Pcre paren_r("^\\((.*)\\)$");
747 if (paren_r(data, size))
748 return Simplify(paren_r[1]);
750 static Pcre title_r("^(.*?) \\((.*)\\)$");
751 if (title_r(data, size))
752 return Simplify(title_r[1]);
758 NSString *GetLastUpdate() {
759 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
762 return UCLocalize("NEVER_OR_UNKNOWN");
764 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
765 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
767 CFRelease(formatter);
769 return [(NSString *) formatted autorelease];
772 bool isSectionVisible(NSString *section) {
773 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
774 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
775 return hidden == nil || ![hidden boolValue];
778 static NSObject *CYIOGetValue(const char *path, NSString *property) {
779 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
780 if (entry == MACH_PORT_NULL)
783 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
784 IOObjectRelease(entry);
788 return [(id) value autorelease];
791 static NSString *CYHex(NSData *data, bool reverse = false) {
795 size_t length([data length]);
796 uint8_t bytes[length];
797 [data getBytes:bytes];
799 char string[length * 2 + 1];
800 for (size_t i(0); i != length; ++i)
801 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
803 return [NSString stringWithUTF8String:string];
808 /* Delegate Prototypes {{{ */
811 @class CydiaProgressEvent;
813 @protocol DatabaseDelegate
814 - (void) repairWithSelector:(SEL)selector;
815 - (void) setConfigurationData:(NSString *)data;
816 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
819 @class CYPackageController;
821 @protocol CydiaDelegate
822 - (void) retainNetworkActivityIndicator;
823 - (void) releaseNetworkActivityIndicator;
824 - (void) clearPackage:(Package *)package;
825 - (void) installPackage:(Package *)package;
826 - (void) installPackages:(NSArray *)packages;
827 - (void) removePackage:(Package *)package;
828 - (void) beginUpdate;
830 - (void) distUpgrade;
834 - (void) addTrivialSource:(NSString *)href;
835 - (void) showSettings;
836 - (UIProgressHUD *) addProgressHUD;
837 - (void) removeProgressHUD:(UIProgressHUD *)hud;
838 - (CyteViewController *) pageForPackage:(NSString *)name;
839 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
840 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
844 /* Status Delegation {{{ */
846 public pkgAcquireStatus
849 _transient NSObject<ProgressDelegate> *delegate_;
859 void setDelegate(NSObject<ProgressDelegate> *delegate) {
860 delegate_ = delegate;
863 NSObject<ProgressDelegate> *getDelegate() const {
867 virtual bool MediaChange(std::string media, std::string drive) {
871 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
874 virtual void Fetch(pkgAcquire::ItemDesc &item) {
875 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
876 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
877 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
880 virtual void Done(pkgAcquire::ItemDesc &item) {
883 virtual void Fail(pkgAcquire::ItemDesc &item) {
885 item.Owner->Status == pkgAcquire::Item::StatIdle ||
886 item.Owner->Status == pkgAcquire::Item::StatDone
890 std::string &error(item.Owner->ErrorText);
894 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
895 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
898 virtual bool Pulse(pkgAcquire *Owner) {
899 bool value = pkgAcquireStatus::Pulse(Owner);
902 double(CurrentBytes + CurrentItems) /
903 double(TotalBytes + TotalItems)
906 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
907 [NSNumber numberWithDouble:percent], @"Percent",
909 [NSNumber numberWithDouble:CurrentBytes], @"Current",
910 [NSNumber numberWithDouble:TotalBytes], @"Total",
911 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
912 nil] waitUntilDone:YES];
914 if (value && ![delegate_ isProgressCancelled])
922 _finline bool WasCancelled() const {
926 virtual void Start() {
927 pkgAcquireStatus::Start();
928 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
931 virtual void Stop() {
932 pkgAcquireStatus::Stop();
933 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
934 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
938 /* Database Interface {{{ */
939 typedef std::map< unsigned long, _H<Source> > SourceMap;
941 @interface Database : NSObject {
948 pkgDepCache::Policy *policy_;
949 pkgRecords *records_;
950 pkgProblemResolver *resolver_;
951 pkgAcquire *fetcher_;
953 SPtr<pkgPackageManager> manager_;
954 pkgSourceList *list_;
956 SourceMap sourceMap_;
957 _H<NSMutableArray> sourceList_;
959 CFMutableArrayRef packages_;
961 _transient NSObject<DatabaseDelegate> *delegate_;
962 _transient NSObject<ProgressDelegate> *progress_;
970 std::map<const char *, _H<NSString> > sections_;
973 + (Database *) sharedInstance;
976 - (void) _readCydia:(NSNumber *)fd;
977 - (void) _readStatus:(NSNumber *)fd;
978 - (void) _readOutput:(NSNumber *)fd;
982 - (Package *) packageWithName:(NSString *)name;
984 - (pkgCacheFile &) cache;
985 - (pkgDepCache::Policy *) policy;
986 - (pkgRecords *) records;
987 - (pkgProblemResolver *) resolver;
988 - (pkgAcquire &) fetcher;
989 - (pkgSourceList &) list;
990 - (NSArray *) packages;
991 - (NSArray *) sources;
992 - (Source *) sourceWithKey:(NSString *)key;
993 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1001 - (void) updateWithStatus:(Status &)status;
1003 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1005 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1006 - (NSObject<ProgressDelegate> *) progressDelegate;
1008 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1010 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1014 /* ProgressEvent Implementation {{{ */
1015 @implementation CydiaProgressEvent
1017 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1018 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1021 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1022 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1023 [event setPackage:package];
1027 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1028 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1030 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1031 NSArray *fields([description componentsSeparatedByString:@" "]);
1032 [event setItem:fields];
1034 if ([fields count] > 3) {
1035 [event setPackage:[fields objectAtIndex:2]];
1036 [event setVersion:[fields objectAtIndex:3]];
1039 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1044 + (NSArray *) _attributeKeys {
1045 return [NSArray arrayWithObjects:
1055 - (NSArray *) attributeKeys {
1056 return [[self class] _attributeKeys];
1059 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1060 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1063 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1064 if ((self = [super init]) != nil) {
1070 - (NSString *) message {
1074 - (NSString *) type {
1078 - (NSArray *) item {
1079 return (id) item_ ?: [NSNull null];
1082 - (void) setItem:(NSArray *)item {
1086 - (NSString *) package {
1087 return (id) package_ ?: [NSNull null];
1090 - (void) setPackage:(NSString *)package {
1094 - (NSString *) url {
1095 return (id) url_ ?: [NSNull null];
1098 - (void) setURL:(NSString *)url {
1102 - (void) setVersion:(NSString *)version {
1106 - (NSString *) version {
1107 return (id) version_ ?: [NSNull null];
1110 - (NSString *) compound:(NSString *)value {
1112 NSString *mode(nil); {
1113 NSString *type([self type]);
1114 if ([type isEqualToString:kCydiaProgressEventTypeError])
1115 mode = UCLocalize("ERROR");
1116 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1117 mode = UCLocalize("WARNING");
1121 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1127 - (NSString *) compoundMessage {
1128 return [self compound:[self message]];
1131 - (NSString *) compoundTitle {
1134 if (package_ == nil)
1136 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1137 title = [package name];
1141 return [self compound:title];
1147 // Cytore Definitions {{{
1148 struct PackageValue :
1151 Cytore::Offset<PackageValue> next_;
1153 uint32_t index_ : 23;
1154 uint32_t subscribed_ : 1;
1171 Cytore::Offset<PackageValue> packages_[1 << 16];
1174 static Cytore::File<MetaValue> MetaFile_;
1176 // Cytore Helper Functions {{{
1177 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1178 SplitHash nhash = { hashlittle(name, length) };
1180 PackageValue *metadata;
1182 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1183 offset: if (offset->IsNull()) {
1184 *offset = MetaFile_.New<PackageValue>(length + 1);
1185 metadata = &MetaFile_.Get(*offset);
1187 if (metadata == NULL) {
1191 metadata = new PackageValue();
1192 memset(metadata, 0, sizeof(*metadata));
1195 memcpy(metadata->name_, name, length + 1);
1196 metadata->nhash_ = nhash.u16[1];
1198 metadata = &MetaFile_.Get(*offset);
1200 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1201 offset = &metadata->next_;
1209 static void PackageImport(const void *key, const void *value, void *context) {
1210 bool &fail(*reinterpret_cast<bool *>(context));
1213 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1214 NSLog(@"failed to import package %@", key);
1218 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1219 NSDictionary *package((NSDictionary *) value);
1221 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1222 if ([subscribed boolValue] && !metadata->subscribed_)
1223 metadata->subscribed_ = true;
1225 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1226 time_t time([date timeIntervalSince1970]);
1227 if (metadata->first_ > time || metadata->first_ == 0)
1228 metadata->first_ = time;
1231 NSDate *date([package objectForKey:@"LastSeen"]);
1232 NSString *version([package objectForKey:@"LastVersion"]);
1234 if (date != nil && version != nil) {
1235 time_t time([date timeIntervalSince1970]);
1236 if (metadata->last_ < time || metadata->last_ == 0)
1237 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1238 size_t length(strlen(buffer));
1239 uint16_t vhash(hashlittle(buffer, length));
1241 size_t capped(std::min<size_t>(8, length));
1242 char *latest(buffer + length - capped);
1244 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1245 metadata->vhash_ = vhash;
1247 metadata->last_ = time;
1253 /* Source Class {{{ */
1254 @interface Source : NSObject {
1255 CYString depiction_;
1256 CYString description_;
1262 CYString distribution_;
1267 _H<NSString> authority_;
1269 CYString defaultIcon_;
1271 _H<NSDictionary> record_;
1275 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1277 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1279 - (NSString *) depictionForPackage:(NSString *)package;
1280 - (NSString *) supportForPackage:(NSString *)package;
1282 - (NSDictionary *) record;
1286 - (NSString *) distribution;
1287 - (NSString *) type;
1289 - (NSString *) host;
1291 - (NSString *) name;
1292 - (NSString *) shortDescription;
1293 - (NSString *) label;
1294 - (NSString *) origin;
1295 - (NSString *) version;
1297 - (NSString *) defaultIcon;
1301 @implementation Source
1305 distribution_.clear();
1308 description_.clear();
1314 defaultIcon_.clear();
1321 + (NSArray *) _attributeKeys {
1322 return [NSArray arrayWithObjects:
1329 @"shortDescription",
1337 - (NSArray *) attributeKeys {
1338 return [[self class] _attributeKeys];
1341 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1342 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1345 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1348 trusted_ = index->IsTrusted();
1350 uri_.set(pool, index->GetURI());
1351 distribution_.set(pool, index->GetDist());
1352 type_.set(pool, index->GetType());
1354 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1355 if (dindex != NULL) {
1357 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1360 pkgTagFile tags(&fd);
1362 pkgTagSection section;
1369 {"default-icon", &defaultIcon_},
1370 {"depiction", &depiction_},
1371 {"description", &description_},
1373 {"origin", &origin_},
1374 {"support", &support_},
1375 {"version", &version_},
1378 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1379 const char *start, *end;
1381 if (section.Find(names[i].name_, start, end)) {
1382 CYString &value(*names[i].value_);
1383 value.set(pool, start, end - start);
1389 record_ = [Sources_ objectForKey:[self key]];
1391 NSURL *url([NSURL URLWithString:uri_]);
1395 host_ = [host_ lowercaseString];
1400 authority_ = [url path];
1403 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1404 if ((self = [super init]) != nil) {
1405 [self setMetaIndex:index inPool:pool];
1409 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1410 NSDictionary *lhr = [self record];
1411 NSDictionary *rhr = [source record];
1414 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1416 NSString *lhs = [self name];
1417 NSString *rhs = [source name];
1419 if ([lhs length] != 0 && [rhs length] != 0) {
1420 unichar lhc = [lhs characterAtIndex:0];
1421 unichar rhc = [rhs characterAtIndex:0];
1423 if (isalpha(lhc) && !isalpha(rhc))
1424 return NSOrderedAscending;
1425 else if (!isalpha(lhc) && isalpha(rhc))
1426 return NSOrderedDescending;
1429 return [lhs compare:rhs options:LaxCompareOptions_];
1432 - (NSString *) depictionForPackage:(NSString *)package {
1433 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1436 - (NSString *) supportForPackage:(NSString *)package {
1437 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1440 - (NSDictionary *) record {
1448 - (NSString *) uri {
1452 - (NSString *) distribution {
1453 return distribution_;
1456 - (NSString *) type {
1460 - (NSString *) key {
1461 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1464 - (NSString *) host {
1468 - (NSString *) name {
1469 return origin_.empty() ? (id) authority_ : origin_;
1472 - (NSString *) shortDescription {
1473 return description_;
1476 - (NSString *) label {
1477 return label_.empty() ? (id) authority_ : label_;
1480 - (NSString *) origin {
1484 - (NSString *) version {
1488 - (NSString *) defaultIcon {
1489 return defaultIcon_;
1494 /* CydiaOperation Class {{{ */
1495 @interface CydiaOperation : NSObject {
1496 _H<NSString> operator_;
1497 _H<NSString> value_;
1500 - (NSString *) operator;
1501 - (NSString *) value;
1505 @implementation CydiaOperation
1507 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1508 if ((self = [super init]) != nil) {
1509 operator_ = [NSString stringWithUTF8String:_operator];
1510 value_ = [NSString stringWithUTF8String:value];
1514 + (NSArray *) _attributeKeys {
1515 return [NSArray arrayWithObjects:
1521 - (NSArray *) attributeKeys {
1522 return [[self class] _attributeKeys];
1525 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1526 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1529 - (NSString *) operator {
1533 - (NSString *) value {
1539 /* CydiaClause Class {{{ */
1540 @interface CydiaClause : NSObject {
1541 _H<NSString> package_;
1542 _H<CydiaOperation> version_;
1545 - (NSString *) package;
1546 - (CydiaOperation *) version;
1550 @implementation CydiaClause
1552 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1553 if ((self = [super init]) != nil) {
1554 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1556 if (const char *version = dep.TargetVer())
1557 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1559 version_ = (id) [NSNull null];
1563 + (NSArray *) _attributeKeys {
1564 return [NSArray arrayWithObjects:
1570 - (NSArray *) attributeKeys {
1571 return [[self class] _attributeKeys];
1574 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1575 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1578 - (NSString *) package {
1582 - (CydiaOperation *) version {
1588 /* CydiaRelation Class {{{ */
1589 @interface CydiaRelation : NSObject {
1590 _H<NSString> relationship_;
1591 _H<NSMutableArray> clauses_;
1594 - (NSString *) relationship;
1595 - (NSArray *) clauses;
1599 @implementation CydiaRelation
1601 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1602 if ((self = [super init]) != nil) {
1603 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1604 clauses_ = [NSMutableArray arrayWithCapacity:8];
1606 pkgCache::DepIterator start;
1607 pkgCache::DepIterator end;
1608 dep.GlobOr(start, end); // ++dep
1611 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1613 // yes, seriously. (wtf?)
1621 + (NSArray *) _attributeKeys {
1622 return [NSArray arrayWithObjects:
1628 - (NSArray *) attributeKeys {
1629 return [[self class] _attributeKeys];
1632 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1633 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1636 - (NSString *) relationship {
1637 return relationship_;
1640 - (NSArray *) clauses {
1644 - (void) addClause:(CydiaClause *)clause {
1645 [clauses_ addObject:clause];
1650 /* Package Class {{{ */
1651 struct ParsedPackage {
1656 CYString depiction_;
1666 @interface Package : NSObject {
1669 uint32_t essential_ : 1;
1670 uint32_t obsolete_ : 1;
1671 uint32_t ignored_ : 1;
1675 _transient Database *database_;
1677 pkgCache::VerIterator version_;
1678 pkgCache::PkgIterator iterator_;
1679 pkgCache::VerFileIterator file_;
1685 CYString installed_;
1687 const char *section_;
1688 _transient NSString *section$_;
1692 PackageValue *metadata_;
1693 ParsedPackage *parsed_;
1695 _H<NSMutableArray> tags_;
1698 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1699 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1701 - (pkgCache::PkgIterator) iterator;
1704 - (NSString *) section;
1705 - (NSString *) simpleSection;
1707 - (NSString *) longSection;
1708 - (NSString *) shortSection;
1712 - (MIMEAddress *) maintainer;
1714 - (NSString *) longDescription;
1715 - (NSString *) shortDescription;
1718 - (PackageValue *) metadata;
1721 - (bool) subscribed;
1722 - (bool) setSubscribed:(bool)subscribed;
1726 - (NSString *) latest;
1727 - (NSString *) installed;
1728 - (BOOL) uninstalled;
1731 - (BOOL) upgradableAndEssential:(BOOL)essential;
1734 - (BOOL) unfiltered;
1738 - (BOOL) halfConfigured;
1739 - (BOOL) halfInstalled;
1741 - (NSString *) mode;
1744 - (NSString *) name;
1746 - (NSString *) homepage;
1747 - (NSString *) depiction;
1748 - (MIMEAddress *) author;
1750 - (NSString *) support;
1752 - (NSArray *) files;
1753 - (NSArray *) warnings;
1754 - (NSArray *) applications;
1756 - (Source *) source;
1758 - (BOOL) matches:(NSString *)text;
1760 - (bool) hasSupportingRole;
1761 - (BOOL) hasTag:(NSString *)tag;
1762 - (NSString *) primaryPurpose;
1763 - (NSArray *) purposes;
1764 - (bool) isCommercial;
1766 - (void) setIndex:(size_t)index;
1768 - (CYString &) cyname;
1770 - (uint32_t) compareBySection:(NSArray *)sections;
1775 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1776 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1777 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1778 - (bool) isVisibleInSection:(NSString *)section;
1779 - (bool) isVisibleInSource:(Source *)source;
1783 uint32_t PackageChangesRadix(Package *self, void *) {
1788 uint32_t timestamp : 30;
1789 uint32_t ignored : 1;
1790 uint32_t upgradable : 1;
1794 bool upgradable([self upgradableAndEssential:YES]);
1795 value.bits.upgradable = upgradable ? 1 : 0;
1798 value.bits.timestamp = 0;
1799 value.bits.ignored = [self ignored] ? 0 : 1;
1800 value.bits.upgradable = 1;
1802 value.bits.timestamp = [self seen] >> 2;
1803 value.bits.ignored = 0;
1804 value.bits.upgradable = 0;
1807 return _not(uint32_t) - value.key;
1810 uint32_t PackagePrefixRadix(Package *self, void *context) {
1811 size_t offset(reinterpret_cast<size_t>(context));
1812 CYString &name([self cyname]);
1814 size_t size(name.size());
1817 char *text(name.data());
1820 if (!isdigit(text[0]))
1824 while (size != digits && isdigit(text[digits]))
1832 if (offset == 0 && zeros != 0) {
1833 memset(data, '0', zeros);
1834 memcpy(data + zeros, text, 4 - zeros);
1836 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1837 if (size <= offset - zeros)
1840 text += offset - zeros;
1841 size -= offset - zeros;
1844 memcpy(data, text, 4);
1846 memcpy(data, text, size);
1847 memset(data + size, 0, 4 - size);
1850 for (size_t i(0); i != 4; ++i)
1851 if (isalpha(data[i]))
1859 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1861 /* XXX: ntohl may be more honest */
1862 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1865 CYString &(*PackageName)(Package *self, SEL sel);
1867 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1868 _profile(PackageNameCompare)
1869 CYString &lhi(PackageName(lhs, @selector(cyname)));
1870 CYString &rhi(PackageName(rhs, @selector(cyname)));
1871 CFStringRef lhn(lhi), rhn(rhi);
1874 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1875 else if (rhn == NULL)
1876 return NSOrderedDescending;
1878 _profile(PackageNameCompare$NumbersLast)
1879 if (!lhi.empty() && !rhi.empty()) {
1880 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1881 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1882 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1883 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1884 return lha ? NSOrderedAscending : NSOrderedDescending;
1888 CFIndex length = CFStringGetLength(lhn);
1890 _profile(PackageNameCompare$Compare)
1891 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1896 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1897 return PackageNameCompare(*lhs, *rhs, context);
1900 struct PackageNameOrdering :
1901 std::binary_function<Package *, Package *, bool>
1903 _finline bool operator ()(Package *lhs, Package *rhs) const {
1904 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1908 @implementation Package
1910 - (NSString *) description {
1911 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1915 if (parsed_ != NULL)
1920 + (NSString *) webScriptNameForSelector:(SEL)selector {
1922 else if (selector == @selector(clear))
1924 else if (selector == @selector(getField:))
1926 else if (selector == @selector(hasTag:))
1928 else if (selector == @selector(install))
1930 else if (selector == @selector(remove))
1936 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1937 return [self webScriptNameForSelector:selector] == nil;
1940 + (NSArray *) _attributeKeys {
1941 return [NSArray arrayWithObjects:
1960 @"shortDescription",
1973 - (NSArray *) attributeKeys {
1974 return [[self class] _attributeKeys];
1977 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1978 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1981 - (NSArray *) relations {
1982 @synchronized (database_) {
1983 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
1984 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
1985 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
1989 - (NSString *) getField:(NSString *)name {
1990 @synchronized (database_) {
1991 if ([database_ era] != era_ || file_.end())
1994 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
1996 const char *start, *end;
1997 if (!parser.Find([name UTF8String], start, end))
1998 return (NSString *) [NSNull null];
2000 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2004 if (parsed_ != NULL)
2006 @synchronized (database_) {
2007 if ([database_ era] != era_ || file_.end())
2010 ParsedPackage *parsed(new ParsedPackage);
2013 _profile(Package$parse)
2014 pkgRecords::Parser *parser;
2016 _profile(Package$parse$Lookup)
2017 parser = &[database_ records]->Lookup(file_);
2022 _profile(Package$parse$Find)
2027 {"icon", &parsed->icon_},
2028 {"depiction", &parsed->depiction_},
2029 {"homepage", &parsed->homepage_},
2030 {"website", &website},
2031 {"bugs", &parsed->bugs_},
2032 {"support", &parsed->support_},
2033 {"sponsor", &parsed->sponsor_},
2034 {"author", &parsed->author_},
2037 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2038 const char *start, *end;
2040 if (parser->Find(names[i].name_, start, end)) {
2041 CYString &value(*names[i].value_);
2042 _profile(Package$parse$Value)
2043 value.set(pool_, start, end - start);
2049 _profile(Package$parse$Tagline)
2050 const char *start, *end;
2051 if (parser->ShortDesc(start, end)) {
2052 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2055 while (stop != start && stop[-1] == '\r')
2057 parsed->tagline_.set(pool_, start, stop - start);
2061 _profile(Package$parse$Retain)
2062 if (parsed->homepage_.empty())
2063 parsed->homepage_ = website;
2064 if (parsed->homepage_ == parsed->depiction_)
2065 parsed->homepage_.clear();
2070 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2071 if ((self = [super init]) != nil) {
2072 _profile(Package$initWithVersion)
2075 database_ = database;
2076 era_ = [database era];
2080 pkgCache::PkgIterator iterator(version.ParentPkg());
2081 iterator_ = iterator;
2083 _profile(Package$initWithVersion$Version)
2084 if (!version_.end())
2085 file_ = version_.FileList();
2087 pkgCache &cache([database_ cache]);
2088 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2092 _profile(Package$initWithVersion$Cache)
2093 name_.set(NULL, iterator.Display());
2095 latest_.set(NULL, StripVersion_(version_.VerStr()));
2097 pkgCache::VerIterator current(iterator.CurrentVer());
2099 installed_.set(NULL, StripVersion_(current.VerStr()));
2102 _profile(Package$initWithVersion$Tags)
2103 pkgCache::TagIterator tag(iterator.TagList());
2105 tags_ = [NSMutableArray arrayWithCapacity:8];
2107 const char *name(tag.Name());
2108 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2110 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2111 if (strcmp(name + 6, "enduser") == 0)
2113 else if (strcmp(name + 6, "hacker") == 0)
2115 else if (strcmp(name + 6, "developer") == 0)
2117 else if (strcmp(name + 6, "cydia") == 0)
2123 if (strncmp(name, "cydia::", 7) == 0) {
2124 if (strcmp(name + 7, "essential") == 0)
2126 else if (strcmp(name + 7, "obsolete") == 0)
2131 } while (!tag.end());
2135 _profile(Package$initWithVersion$Metadata)
2136 const char *mixed(iterator.Name());
2137 size_t size(strlen(mixed));
2138 char lower[size + 1];
2140 for (size_t i(0); i != size; ++i)
2141 lower[i] = mixed[i] | 0x20;
2144 PackageValue *metadata(PackageFind(lower, size));
2145 metadata_ = metadata;
2147 id_.set(NULL, metadata->name_, size);
2149 const char *latest(version_.VerStr());
2150 size_t length(strlen(latest));
2152 uint16_t vhash(hashlittle(latest, length));
2154 size_t capped(std::min<size_t>(8, length));
2155 latest = latest + length - capped;
2157 if (metadata->first_ == 0)
2158 metadata->first_ = now_;
2160 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2161 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2162 metadata->vhash_ = vhash;
2163 metadata->last_ = now_;
2164 } else if (metadata->last_ == 0)
2165 metadata->last_ = metadata->first_;
2168 _profile(Package$initWithVersion$Section)
2169 section_ = iterator.Section();
2172 _profile(Package$initWithVersion$Flags)
2173 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2174 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2179 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2180 pkgCache::VerIterator version;
2182 _profile(Package$packageWithIterator$GetCandidateVer)
2183 version = [database policy]->GetCandidateVer(iterator);
2191 _profile(Package$packageWithIterator$Allocate)
2192 package = [Package allocWithZone:zone];
2195 _profile(Package$packageWithIterator$Initialize)
2197 initWithVersion:version
2204 _profile(Package$packageWithIterator$Autorelease)
2205 package = [package autorelease];
2211 - (pkgCache::PkgIterator) iterator {
2215 - (NSString *) section {
2216 if (section$_ == nil) {
2217 if (section_ == NULL)
2220 _profile(Package$section$mappedSectionForPointer)
2221 section$_ = [database_ mappedSectionForPointer:section_];
2226 - (NSString *) simpleSection {
2227 if (NSString *section = [self section])
2228 return Simplify(section);
2233 - (NSString *) longSection {
2234 return LocalizeSection([self section]);
2237 - (NSString *) shortSection {
2238 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2241 - (NSString *) uri {
2244 pkgIndexFile *index;
2245 pkgCache::PkgFileIterator file(file_.File());
2246 if (![database_ list].FindIndex(file, index))
2248 return [NSString stringWithUTF8String:iterator_->Path];
2249 //return [NSString stringWithUTF8String:file.Site()];
2250 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2254 - (MIMEAddress *) maintainer {
2255 @synchronized (database_) {
2256 if ([database_ era] != era_ || file_.end())
2259 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2260 const std::string &maintainer(parser->Maintainer());
2261 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2265 @synchronized (database_) {
2266 if ([database_ era] != era_ || version_.end())
2269 return version_->InstalledSize;
2272 - (NSString *) longDescription {
2273 @synchronized (database_) {
2274 if ([database_ era] != era_ || file_.end())
2277 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2278 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2280 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2281 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2282 if ([lines count] < 2)
2285 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2286 for (size_t i(1), e([lines count]); i != e; ++i) {
2287 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2288 [trimmed addObject:trim];
2291 return [trimmed componentsJoinedByString:@"\n"];
2294 - (NSString *) shortDescription {
2295 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2299 _profile(Package$index)
2300 CFStringRef name((CFStringRef) [self name]);
2301 if (CFStringGetLength(name) == 0)
2303 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2304 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2306 return toupper(character);
2310 - (PackageValue *) metadata {
2315 PackageValue *metadata([self metadata]);
2316 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2319 - (bool) subscribed {
2320 return [self metadata]->subscribed_;
2323 - (bool) setSubscribed:(bool)subscribed {
2324 PackageValue *metadata([self metadata]);
2325 if (metadata->subscribed_ == subscribed)
2327 metadata->subscribed_ = subscribed;
2335 - (NSString *) latest {
2339 - (NSString *) installed {
2343 - (BOOL) uninstalled {
2344 return installed_.empty();
2348 return !version_.end();
2351 - (BOOL) upgradableAndEssential:(BOOL)essential {
2352 _profile(Package$upgradableAndEssential)
2353 pkgCache::VerIterator current(iterator_.CurrentVer());
2355 return essential && essential_;
2357 return !version_.end() && version_ != current;
2361 - (BOOL) essential {
2366 return [database_ cache][iterator_].InstBroken();
2369 - (BOOL) unfiltered {
2370 _profile(Package$unfiltered$obsolete)
2371 if (_unlikely(obsolete_))
2375 _profile(Package$unfiltered$hasSupportingRole)
2376 if (_unlikely(![self hasSupportingRole]))
2384 if (![self unfiltered])
2389 _profile(Package$visible$section)
2390 section = [self section];
2393 _profile(Package$visible$isSectionVisible)
2394 if (!isSectionVisible(section))
2402 unsigned char current(iterator_->CurrentState);
2403 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2406 - (BOOL) halfConfigured {
2407 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2410 - (BOOL) halfInstalled {
2411 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2415 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2416 return state.Mode != pkgDepCache::ModeKeep;
2419 - (NSString *) mode {
2420 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2422 switch (state.Mode) {
2423 case pkgDepCache::ModeDelete:
2424 if ((state.iFlags & pkgDepCache::Purge) != 0)
2428 case pkgDepCache::ModeKeep:
2429 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2430 return @"REINSTALL";
2431 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2435 case pkgDepCache::ModeInstall:
2436 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2437 return @"REINSTALL";
2438 else*/ switch (state.Status) {
2440 return @"DOWNGRADE";
2446 return @"NEW_INSTALL";
2457 - (NSString *) name {
2458 return name_.empty() ? id_ : name_;
2461 - (UIImage *) icon {
2462 NSString *section = [self simpleSection];
2465 if (parsed_ != NULL)
2466 if (NSString *href = parsed_->icon_)
2467 if ([href hasPrefix:@"file:///"])
2468 // XXX: correct escaping
2469 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2470 if (icon == nil) if (section != nil)
2471 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2472 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2473 if ([dicon hasPrefix:@"file:///"])
2474 // XXX: correct escaping
2475 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2477 icon = [UIImage applicationImageNamed:@"unknown.png"];
2481 - (NSString *) homepage {
2482 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2485 - (NSString *) depiction {
2486 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2489 - (MIMEAddress *) sponsor {
2490 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2493 - (MIMEAddress *) author {
2494 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2497 - (NSString *) support {
2498 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2501 - (NSArray *) files {
2502 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2503 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2506 fin.open([path UTF8String]);
2511 while (std::getline(fin, line))
2512 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2517 - (NSString *) state {
2518 @synchronized (database_) {
2519 if ([database_ era] != era_ || file_.end())
2522 switch (iterator_->CurrentState) {
2523 case pkgCache::State::NotInstalled:
2524 return @"NotInstalled";
2525 case pkgCache::State::UnPacked:
2527 case pkgCache::State::HalfConfigured:
2528 return @"HalfConfigured";
2529 case pkgCache::State::HalfInstalled:
2530 return @"HalfInstalled";
2531 case pkgCache::State::ConfigFiles:
2532 return @"ConfigFiles";
2533 case pkgCache::State::Installed:
2534 return @"Installed";
2535 case pkgCache::State::TriggersAwaited:
2536 return @"TriggersAwaited";
2537 case pkgCache::State::TriggersPending:
2538 return @"TriggersPending";
2541 return (NSString *) [NSNull null];
2544 - (NSString *) selection {
2545 @synchronized (database_) {
2546 if ([database_ era] != era_ || file_.end())
2549 switch (iterator_->SelectedState) {
2550 case pkgCache::State::Unknown:
2552 case pkgCache::State::Install:
2554 case pkgCache::State::Hold:
2556 case pkgCache::State::DeInstall:
2557 return @"DeInstall";
2558 case pkgCache::State::Purge:
2562 return (NSString *) [NSNull null];
2565 - (NSArray *) warnings {
2566 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2567 const char *name(iterator_.Name());
2569 size_t length(strlen(name));
2570 if (length < 2) invalid:
2571 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2572 else for (size_t i(0); i != length; ++i)
2574 /* XXX: technically this is not allowed */
2575 (name[i] < 'A' || name[i] > 'Z') &&
2576 (name[i] < 'a' || name[i] > 'z') &&
2577 (name[i] < '0' || name[i] > '9') &&
2578 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2581 if (strcmp(name, "cydia") != 0) {
2584 bool _private = false;
2587 bool repository = [[self section] isEqualToString:@"Repositories"];
2589 if (NSArray *files = [self files])
2590 for (NSString *file in files)
2591 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2593 else if (!user && [file isEqualToString:@"/User"])
2595 else if (!_private && [file isEqualToString:@"/private"])
2597 else if (!stash && [file isEqualToString:@"/var/stash"])
2600 /* XXX: this is not sensitive enough. only some folders are valid. */
2601 if (cydia && !repository)
2602 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2604 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2606 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2608 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2611 return [warnings count] == 0 ? nil : warnings;
2614 - (NSArray *) applications {
2615 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2617 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2619 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2620 if (NSArray *files = [self files])
2621 for (NSString *file in files)
2622 if (application_r(file)) {
2623 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2624 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2625 if ([id isEqualToString:me])
2628 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2630 display = application_r[1];
2632 NSString *bundle([file stringByDeletingLastPathComponent]);
2633 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2634 if (icon == nil || [icon length] == 0)
2636 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2638 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2639 [applications addObject:application];
2641 [application addObject:id];
2642 [application addObject:display];
2643 [application addObject:url];
2646 return [applications count] == 0 ? nil : applications;
2649 - (Source *) source {
2650 if (source_ == nil) {
2651 @synchronized (database_) {
2652 if ([database_ era] != era_ || file_.end())
2653 source_ = (Source *) [NSNull null];
2655 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2659 return source_ == (Source *) [NSNull null] ? nil : source_;
2662 - (BOOL) matches:(NSString *)text {
2668 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2669 if (range.location != NSNotFound)
2672 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2673 if (range.location != NSNotFound)
2678 NSString *description([self shortDescription]);
2679 NSUInteger length([description length]);
2681 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2682 if (range.location != NSNotFound)
2688 - (bool) hasSupportingRole {
2693 if ([Role_ isEqualToString:@"User"])
2697 if ([Role_ isEqualToString:@"Hacker"])
2701 if ([Role_ isEqualToString:@"Developer"])
2706 - (NSArray *) tags {
2710 - (BOOL) hasTag:(NSString *)tag {
2711 return tags_ == nil ? NO : [tags_ containsObject:tag];
2714 - (NSString *) primaryPurpose {
2715 for (NSString *tag in (NSArray *) tags_)
2716 if ([tag hasPrefix:@"purpose::"])
2717 return [tag substringFromIndex:9];
2721 - (NSArray *) purposes {
2722 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2723 for (NSString *tag in (NSArray *) tags_)
2724 if ([tag hasPrefix:@"purpose::"])
2725 [purposes addObject:[tag substringFromIndex:9]];
2726 return [purposes count] == 0 ? nil : purposes;
2729 - (bool) isCommercial {
2730 return [self hasTag:@"cydia::commercial"];
2733 - (void) setIndex:(size_t)index {
2734 if (metadata_->index_ != index)
2735 metadata_->index_ = index;
2738 - (CYString &) cyname {
2739 return name_.empty() ? id_ : name_;
2742 - (uint32_t) compareBySection:(NSArray *)sections {
2743 NSString *section([self section]);
2744 for (size_t i(0), e([sections count]); i != e; ++i) {
2745 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2749 return _not(uint32_t);
2753 @synchronized (database_) {
2754 pkgProblemResolver *resolver = [database_ resolver];
2755 resolver->Clear(iterator_);
2757 pkgCacheFile &cache([database_ cache]);
2758 cache->SetReInstall(iterator_, false);
2759 cache->MarkKeep(iterator_, false);
2763 @synchronized (database_) {
2764 pkgProblemResolver *resolver = [database_ resolver];
2765 resolver->Clear(iterator_);
2766 resolver->Protect(iterator_);
2768 pkgCacheFile &cache([database_ cache]);
2769 cache->SetReInstall(iterator_, false);
2770 cache->MarkInstall(iterator_, false);
2772 pkgDepCache::StateCache &state((*cache)[iterator_]);
2773 if (!state.Install())
2774 cache->SetReInstall(iterator_, true);
2778 @synchronized (database_) {
2779 pkgProblemResolver *resolver = [database_ resolver];
2780 resolver->Clear(iterator_);
2781 resolver->Remove(iterator_);
2782 resolver->Protect(iterator_);
2784 pkgCacheFile &cache([database_ cache]);
2785 cache->SetReInstall(iterator_, false);
2786 cache->MarkDelete(iterator_, true);
2789 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2790 _profile(Package$isUnfilteredAndSearchedForBy)
2793 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2794 value &= [self unfiltered];
2797 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2798 value &= [self matches:search];
2805 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2806 if ([search length] == 0)
2809 _profile(Package$isUnfilteredAndSelectedForBy)
2812 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2813 value &= [self unfiltered];
2816 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2817 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2824 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2825 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2828 - (bool) isVisibleInSection:(NSString *)name {
2829 NSString *section([self section]);
2833 section == nil && [name length] == 0 ||
2834 [name isEqualToString:section]
2835 ) && [self visible];
2838 - (bool) isVisibleInSource:(Source *)source {
2839 return [self source] == source && [self visible];
2844 /* Section Class {{{ */
2845 @interface Section : NSObject {
2850 _H<NSString> localized_;
2853 - (NSComparisonResult) compareByLocalized:(Section *)section;
2854 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2855 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2856 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2857 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2858 - (NSString *) name;
2865 - (void) addToCount;
2867 - (void) setCount:(size_t)count;
2868 - (NSString *) localized;
2872 @implementation Section
2874 - (NSComparisonResult) compareByLocalized:(Section *)section {
2875 NSString *lhs(localized_);
2876 NSString *rhs([section localized]);
2878 /*if ([lhs length] != 0 && [rhs length] != 0) {
2879 unichar lhc = [lhs characterAtIndex:0];
2880 unichar rhc = [rhs characterAtIndex:0];
2882 if (isalpha(lhc) && !isalpha(rhc))
2883 return NSOrderedAscending;
2884 else if (!isalpha(lhc) && isalpha(rhc))
2885 return NSOrderedDescending;
2888 return [lhs compare:rhs options:LaxCompareOptions_];
2891 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2892 if ((self = [self initWithName:name localize:NO]) != nil) {
2893 if (localized != nil)
2894 localized_ = localized;
2898 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2899 return [self initWithName:name row:0 localize:localize];
2902 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2903 if ((self = [super init]) != nil) {
2908 localized_ = LocalizeSection(name_);
2912 /* XXX: localize the index thingees */
2913 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2914 if ((self = [super init]) != nil) {
2915 name_ = [NSString stringWithCharacters:&index length:1];
2921 - (NSString *) name {
2941 - (void) addToCount {
2945 - (void) setCount:(size_t)count {
2949 - (NSString *) localized {
2956 static NSString *Colon_;
2957 static NSString *Elision_;
2958 static NSString *Error_;
2959 static NSString *Warning_;
2961 class CydiaLogCleaner :
2962 public pkgArchiveCleaner
2965 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
2970 /* Database Implementation {{{ */
2971 @implementation Database
2973 + (Database *) sharedInstance {
2974 static _H<Database> instance;
2975 if (instance == nil)
2976 instance = [[[Database alloc] init] autorelease];
2984 - (void) releasePackages {
2985 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
2986 CFArrayRemoveAllValues(packages_);
2990 // XXX: actually implement this thing
2992 [self releasePackages];
2993 apr_pool_destroy(pool_);
2994 NSRecycleZone(zone_);
2998 - (void) _readCydia:(NSNumber *)fd {
2999 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3000 std::istream is(&ib);
3003 static Pcre finish_r("^finish:([^:]*)$");
3005 while (std::getline(is, line)) {
3006 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3008 const char *data(line.c_str());
3009 size_t size = line.size();
3010 lprintf("C:%s\n", data);
3012 if (finish_r(data, size)) {
3013 NSString *finish = finish_r[1];
3014 int index = [Finishes_ indexOfObject:finish];
3015 if (index != INT_MAX && index > Finish_)
3025 - (void) _readStatus:(NSNumber *)fd {
3026 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3027 std::istream is(&ib);
3030 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3031 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3033 while (std::getline(is, line)) {
3034 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3036 const char *data(line.c_str());
3037 size_t size(line.size());
3038 lprintf("S:%s\n", data);
3040 if (conffile_r(data, size)) {
3041 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3042 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3043 } else if (strncmp(data, "status: ", 8) == 0) {
3044 // status: <package>: {unpacked,half-configured,installed}
3045 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3046 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3047 } else if (strncmp(data, "processing: ", 12) == 0) {
3048 // processing: configure: config-test
3049 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3050 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3051 } else if (pmstatus_r(data, size)) {
3052 std::string type([pmstatus_r[1] UTF8String]);
3054 NSString *package = pmstatus_r[2];
3055 if ([package isEqualToString:@"dpkg-exec"])
3058 float percent([pmstatus_r[3] floatValue]);
3059 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3061 NSString *string = pmstatus_r[4];
3063 if (type == "pmerror") {
3064 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3065 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3066 } else if (type == "pmstatus") {
3067 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3068 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3069 } else if (type == "pmconffile")
3070 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3072 lprintf("E:unknown pmstatus\n");
3074 lprintf("E:unknown status\n");
3082 - (void) _readOutput:(NSNumber *)fd {
3083 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3084 std::istream is(&ib);
3087 while (std::getline(is, line)) {
3088 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3090 lprintf("O:%s\n", line.c_str());
3092 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3093 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3105 - (Package *) packageWithName:(NSString *)name {
3106 @synchronized (self) {
3107 if (static_cast<pkgDepCache *>(cache_) == NULL)
3109 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3110 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3114 if ((self = [super init]) != nil) {
3121 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3122 apr_pool_create(&pool_, NULL);
3124 size_t capacity(MetaFile_->active_);
3130 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3131 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3135 _assert(pipe(fds) != -1);
3138 _config->Set("APT::Keep-Fds::", cydiafd_);
3139 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3142 detachNewThreadSelector:@selector(_readCydia:)
3144 withObject:[NSNumber numberWithInt:fds[0]]
3147 _assert(pipe(fds) != -1);
3151 detachNewThreadSelector:@selector(_readStatus:)
3153 withObject:[NSNumber numberWithInt:fds[0]]
3156 _assert(pipe(fds) != -1);
3157 _assert(dup2(fds[0], 0) != -1);
3158 _assert(close(fds[0]) != -1);
3160 input_ = fdopen(fds[1], "a");
3162 _assert(pipe(fds) != -1);
3163 _assert(dup2(fds[1], 1) != -1);
3164 _assert(close(fds[1]) != -1);
3167 detachNewThreadSelector:@selector(_readOutput:)
3169 withObject:[NSNumber numberWithInt:fds[0]]
3174 - (pkgCacheFile &) cache {
3178 - (pkgDepCache::Policy *) policy {
3182 - (pkgRecords *) records {
3186 - (pkgProblemResolver *) resolver {
3190 - (pkgAcquire &) fetcher {
3194 - (pkgSourceList &) list {
3198 - (NSArray *) packages {
3199 return (NSArray *) packages_;
3202 - (NSArray *) sources {
3206 - (Source *) sourceWithKey:(NSString *)key {
3207 for (Source *source in [self sources]) {
3208 if ([[source key] isEqualToString:key])
3213 - (bool) popErrorWithTitle:(NSString *)title {
3216 while (!_error->empty()) {
3218 bool warning(!_error->PopMessage(error));
3223 size_t size(error.size());
3224 if (size == 0 || error[size - 1] != '\n')
3226 error.resize(size - 1);
3229 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3231 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3237 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3238 return [self popErrorWithTitle:title] || !success;
3241 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3242 @synchronized (self) {
3245 [self releasePackages];
3248 [sourceList_ removeAllObjects];
3268 apr_pool_clear(pool_);
3270 NSRecycleZone(zone_);
3271 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3273 int chk(creat("/tmp/cydia.chk", 0644));
3277 if (invocation != nil)
3278 [invocation invoke];
3280 NSString *title(UCLocalize("DATABASE"));
3283 OpProgress progress;
3284 while (!cache_.Open(progress, true)) { pop:
3286 bool warning(!_error->PopMessage(error));
3287 lprintf("cache_.Open():[%s]\n", error.c_str());
3289 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3290 [delegate_ repairWithSelector:@selector(configure)];
3291 else if (error == "The package lists or status file could not be parsed or opened.")
3292 [delegate_ repairWithSelector:@selector(update)];
3293 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3294 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3295 // else if (error == "Malformed Status line")
3296 // else if (error == "The list of sources could not be read.")
3298 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3308 unlink("/tmp/cydia.chk");
3310 now_ = [[NSDate date] timeIntervalSince1970];
3312 policy_ = new pkgDepCache::Policy();
3313 records_ = new pkgRecords(cache_);
3314 resolver_ = new pkgProblemResolver(cache_);
3315 fetcher_ = new pkgAcquire(&status_);
3318 list_ = new pkgSourceList();
3319 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3322 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3323 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3327 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3330 if (cache_->BrokenCount() != 0) {
3331 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3334 if (cache_->BrokenCount() != 0) {
3335 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3339 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3343 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3344 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3345 [sourceList_ addObject:object];
3347 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3348 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3349 // XXX: this could be more intelligent
3350 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3351 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3353 sourceMap_[cached->ID] = object;
3358 /*std::vector<Package *> packages;
3359 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3364 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3365 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3366 //packages.push_back(package);
3367 CFArrayAppendValue(packages_, CFRetain(package));
3371 /*if (packages.empty())
3372 packages_ = [[NSArray alloc] init];
3374 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3377 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3378 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3379 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3387 /*if (!packages.empty())
3388 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3389 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3391 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3393 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3395 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3399 size_t count(CFArrayGetCount(packages_));
3400 MetaFile_->active_ = count;
3402 for (size_t index(0); index != count; ++index)
3403 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3410 @synchronized (self) {
3412 resolver_ = new pkgProblemResolver(cache_);
3414 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3415 if (!cache_[iterator].Keep())
3416 cache_->MarkKeep(iterator, false);
3417 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3418 cache_->SetReInstall(iterator, false);
3421 - (void) configure {
3422 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3424 system([dpkg UTF8String]);
3429 // XXX: I don't remember this condition
3434 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3436 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3438 if ([self popErrorWithTitle:title])
3442 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3444 CydiaLogCleaner cleaner;
3445 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3452 fetcher_->Shutdown();
3454 pkgRecords records(cache_);
3456 lock_ = new FileFd();
3457 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3459 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3461 if ([self popErrorWithTitle:title])
3465 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3468 manager_ = (_system->CreatePM(cache_));
3469 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3476 bool substrate(RestartSubstrate_);
3477 RestartSubstrate_ = false;
3479 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3481 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3483 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3485 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3486 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3489 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3491 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3493 [self popErrorWithTitle:title];
3497 bool failed = false;
3498 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3499 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3501 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3507 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3515 RestartSubstrate_ = true;
3518 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3520 if (_error->PendingError()) {
3525 if (result == pkgPackageManager::Failed) {
3530 if (result != pkgPackageManager::Completed) {
3535 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3537 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3539 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3540 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3543 if (![before isEqualToArray:after])
3548 NSString *title(UCLocalize("UPGRADE"));
3549 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3555 [self updateWithStatus:status_];
3558 - (void) updateWithStatus:(Status &)status {
3559 NSString *title(UCLocalize("REFRESHING_DATA"));
3562 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3566 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3567 if ([self popErrorWithTitle:title])
3570 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3572 bool success(ListUpdate(status, list, PulseInterval_));
3573 if (status.WasCancelled())
3576 [self popErrorWithTitle:title forOperation:success];
3577 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3581 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3584 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3585 delegate_ = delegate;
3588 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3589 progress_ = delegate;
3590 status_.setDelegate(delegate);
3593 - (NSObject<ProgressDelegate> *) progressDelegate {
3597 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3598 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3599 return i == sourceMap_.end() ? nil : i->second;
3602 - (NSString *) mappedSectionForPointer:(const char *)section {
3603 _H<NSString> *mapped;
3605 _profile(Database$mappedSectionForPointer$Cache)
3606 mapped = §ions_[section];
3609 if (*mapped == NULL) {
3610 size_t length(strlen(section));
3611 char spaced[length + 1];
3613 _profile(Database$mappedSectionForPointer$Replace)
3614 for (size_t index(0); index != length; ++index)
3615 spaced[index] = section[index] == '_' ? ' ' : section[index];
3616 spaced[length] = '\0';
3621 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3622 string = [NSString stringWithUTF8String:spaced];
3625 _profile(Database$mappedSectionForPointer$Map)
3626 string = [SectionMap_ objectForKey:string] ?: string;
3636 static _H<NSMutableSet> Diversions_;
3638 @interface Diversion : NSObject {
3641 _H<NSString> format_;
3646 @implementation Diversion
3648 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3649 if ((self = [super init]) != nil) {
3650 pattern_ = [from UTF8String];
3656 - (NSString *) divert:(NSString *)url {
3657 return !pattern_(url) ? nil : pattern_->*format_;
3660 + (NSURL *) divertURL:(NSURL *)url {
3662 NSString *href([url absoluteString]);
3664 for (Diversion *diversion in (id) Diversions_)
3665 if (NSString *diverted = [diversion divert:href]) {
3667 NSLog(@"div: %@", diverted);
3669 url = [NSURL URLWithString:diverted];
3676 - (NSString *) key {
3680 - (NSUInteger) hash {
3684 - (BOOL) isEqual:(Diversion *)object {
3685 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3690 @interface CydiaObject : NSObject {
3691 _H<IndirectDelegate> indirect_;
3692 _transient id delegate_;
3695 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3699 @interface CydiaWebViewController : CyteWebViewController {
3700 _H<CydiaObject> cydia_;
3703 + (void) addDiversion:(Diversion *)diversion;
3707 /* Web Scripting {{{ */
3708 @implementation CydiaObject
3710 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3711 if ((self = [super init]) != nil) {
3712 indirect_ = indirect;
3716 - (void) setDelegate:(id)delegate {
3717 delegate_ = delegate;
3720 + (NSArray *) _attributeKeys {
3721 return [NSArray arrayWithObjects:
3737 - (NSArray *) attributeKeys {
3738 return [[self class] _attributeKeys];
3741 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3742 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3745 - (NSString *) version {
3749 - (NSString *) device {
3750 return [[UIDevice currentDevice] uniqueIdentifier];
3753 - (NSString *) firmware {
3754 return [[UIDevice currentDevice] systemVersion];
3757 - (NSString *) hostname {
3758 return [[UIDevice currentDevice] name];
3761 - (NSString *) idiom {
3762 return (id) Idiom_ ?: [NSNull null];
3765 - (NSString *) plmn {
3766 return (id) PLMN_ ?: [NSNull null];
3769 - (NSString *) bbsnum {
3770 return (id) BBSNum_ ?: [NSNull null];
3773 - (NSString *) ecid {
3774 return (id) ChipID_ ?: [NSNull null];
3777 - (NSString *) serial {
3778 return SerialNumber_;
3781 - (NSString *) role {
3782 return (id) Role_ ?: [NSNull null];
3785 - (NSString *) model {
3786 return [NSString stringWithUTF8String:Machine_];
3789 - (NSString *) token {
3790 return (id) Token_ ?: [NSNull null];
3793 + (NSString *) webScriptNameForSelector:(SEL)selector {
3795 else if (selector == @selector(addBridgedHost:))
3796 return @"addBridgedHost";
3797 else if (selector == @selector(addInternalRedirect::))
3798 return @"addInternalRedirect";
3799 else if (selector == @selector(addPipelinedHost:scheme:))
3800 return @"addPipelinedHost";
3801 else if (selector == @selector(addTrivialSource:))
3802 return @"addTrivialSource";
3803 else if (selector == @selector(close))
3805 else if (selector == @selector(du:))
3807 else if (selector == @selector(stringWithFormat:arguments:))
3809 else if (selector == @selector(getAllSources))
3810 return @"getAllSourcs";
3811 else if (selector == @selector(getKernelNumber:))
3812 return @"getKernelNumber";
3813 else if (selector == @selector(getKernelString:))
3814 return @"getKernelString";
3815 else if (selector == @selector(getInstalledPackages))
3816 return @"getInstalledPackages";
3817 else if (selector == @selector(getIORegistryEntry::))
3818 return @"getIORegistryEntry";
3819 else if (selector == @selector(getLocaleIdentifier))
3820 return @"getLocaleIdentifier";
3821 else if (selector == @selector(getPreferredLanguages))
3822 return @"getPreferredLanguages";
3823 else if (selector == @selector(getPackageById:))
3824 return @"getPackageById";
3825 else if (selector == @selector(getSessionValue:))
3826 return @"getSessionValue";
3827 else if (selector == @selector(installPackages:))
3828 return @"installPackages";
3829 else if (selector == @selector(localizedStringForKey:value:table:))
3831 else if (selector == @selector(popViewController:))
3832 return @"popViewController";
3833 else if (selector == @selector(refreshSources))
3834 return @"refreshSources";
3835 else if (selector == @selector(removeButton))
3836 return @"removeButton";
3837 else if (selector == @selector(setSessionValue::))
3838 return @"setSessionValue";
3839 else if (selector == @selector(substitutePackageNames:))
3840 return @"substitutePackageNames";
3841 else if (selector == @selector(scrollToBottom:))
3842 return @"scrollToBottom";
3843 else if (selector == @selector(setAllowsNavigationAction:))
3844 return @"setAllowsNavigationAction";
3845 else if (selector == @selector(setBadgeValue:))
3846 return @"setBadgeValue";
3847 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3848 return @"setButtonImage";
3849 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3850 return @"setButtonTitle";
3851 else if (selector == @selector(setHidesBackButton:))
3852 return @"setHidesBackButton";
3853 else if (selector == @selector(setHidesNavigationBar:))
3854 return @"setHidesNavigationBar";
3855 else if (selector == @selector(setNavigationBarStyle:))
3856 return @"setNavigationBarStyle";
3857 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3858 return @"setNavigationBarTintColor";
3859 else if (selector == @selector(setPasteboardString:))
3860 return @"setPasteboardString";
3861 else if (selector == @selector(setPasteboardURL:))
3862 return @"setPasteboardURL";
3863 else if (selector == @selector(setToken:))
3865 else if (selector == @selector(setViewportWidth:))
3866 return @"setViewportWidth";
3867 else if (selector == @selector(statfs:))
3869 else if (selector == @selector(supports:))
3875 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3876 return [self webScriptNameForSelector:selector] == nil;
3879 - (BOOL) supports:(NSString *)feature {
3880 return [feature isEqualToString:@"window.open"];
3883 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3884 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3887 - (NSNumber *) getKernelNumber:(NSString *)name {
3888 const char *string([name UTF8String]);
3891 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3892 return (id) [NSNull null];
3894 if (size != sizeof(int))
3895 return (id) [NSNull null];
3898 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3899 return (id) [NSNull null];
3901 return [NSNumber numberWithInt:value];
3904 - (NSString *) getKernelString:(NSString *)name {
3905 const char *string([name UTF8String]);
3908 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3909 return (id) [NSNull null];
3911 char value[size + 1];
3912 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3913 return (id) [NSNull null];
3915 // XXX: just in case you request something ludicrous
3918 return [NSString stringWithCString:value];
3921 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3922 NSObject *value(CYIOGetValue([path UTF8String], entry));
3925 if ([value isKindOfClass:[NSData class]])
3926 value = CYHex((NSData *) value);
3931 - (id) getSessionValue:(NSString *)key {
3932 @synchronized (SessionData_) {
3933 return [SessionData_ objectForKey:key];
3936 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3937 @synchronized (SessionData_) {
3938 if (value == (id) [WebUndefined undefined])
3939 [SessionData_ removeObjectForKey:key];
3941 [SessionData_ setObject:value forKey:key];
3944 - (void) addBridgedHost:(NSString *)host {
3945 @synchronized (HostConfig_) {
3946 [BridgedHosts_ addObject:host];
3949 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
3950 @synchronized (HostConfig_) {
3951 if (scheme != (id) [WebUndefined undefined])
3952 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
3954 [PipelinedHosts_ addObject:host];
3957 - (void) popViewController:(NSNumber *)value {
3958 if (value == (id) [WebUndefined undefined])
3959 value = [NSNumber numberWithBool:YES];
3960 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
3963 - (void) addTrivialSource:(NSString *)href {
3964 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3967 - (void) refreshSources {
3968 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3971 - (NSArray *) getAllSources {
3972 return [[Database sharedInstance] sources];
3975 - (NSArray *) getInstalledPackages {
3976 Database *database([Database sharedInstance]);
3977 @synchronized (database) {
3978 NSArray *packages([database packages]);
3979 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3980 for (Package *package in packages)
3981 if (![package uninstalled])
3982 [installed addObject:package];
3986 - (Package *) getPackageById:(NSString *)id {
3987 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
3991 return (Package *) [NSNull null];
3994 - (NSString *) getLocaleIdentifier {
3995 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
3998 - (NSArray *) getPreferredLanguages {
4002 - (NSArray *) statfs:(NSString *)path {
4005 if (path == nil || statfs([path UTF8String], &stat) == -1)
4008 return [NSArray arrayWithObjects:
4009 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4010 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4011 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4015 - (NSNumber *) du:(NSString *)path {
4016 NSNumber *value(nil);
4019 _assert(pipe(fds) != -1);
4021 pid_t pid(ExecFork());
4023 _assert(dup2(fds[1], 1) != -1);
4024 _assert(close(fds[0]) != -1);
4025 _assert(close(fds[1]) != -1);
4026 /* XXX: this should probably not use du */
4027 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4032 _assert(close(fds[1]) != -1);
4034 if (FILE *du = fdopen(fds[0], "r")) {
4036 while (fgets(line, sizeof(line), du) != NULL) {
4037 size_t length(strlen(line));
4038 while (length != 0 && line[length - 1] == '\n')
4039 line[--length] = '\0';
4040 if (char *tab = strchr(line, '\t')) {
4042 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4047 } else _assert(close(fds[0]));
4051 if (waitpid(pid, &status, 0) == -1)
4054 else _assert(false);
4060 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4063 - (void) installPackages:(NSArray *)packages {
4064 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4067 - (NSString *) substitutePackageNames:(NSString *)message {
4068 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4069 for (size_t i(0), e([words count]); i != e; ++i) {
4070 NSString *word([words objectAtIndex:i]);
4071 if (Package *package = [[Database sharedInstance] packageWithName:word])
4072 [words replaceObjectAtIndex:i withObject:[package name]];
4075 return [words componentsJoinedByString:@" "];
4078 - (void) removeButton {
4079 [indirect_ removeButton];
4082 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4083 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4086 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4087 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4090 - (void) setBadgeValue:(id)value {
4091 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4094 - (void) setAllowsNavigationAction:(NSString *)value {
4095 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4098 - (void) setHidesBackButton:(NSString *)value {
4099 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4102 - (void) setHidesNavigationBar:(NSString *)value {
4103 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4106 - (void) setNavigationBarStyle:(NSString *)value {
4107 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4110 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4111 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4112 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4113 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4116 - (void) setPasteboardString:(NSString *)value {
4117 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4120 - (void) setPasteboardURL:(NSString *)value {
4121 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4124 - (void) _setToken:(NSString *)token {
4128 [Metadata_ removeObjectForKey:@"Token"];
4130 [Metadata_ setObject:Token_ forKey:@"Token"];
4135 - (void) setToken:(NSString *)token {
4136 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4139 - (void) scrollToBottom:(NSNumber *)animated {
4140 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4143 - (void) setViewportWidth:(float)width {
4144 [indirect_ setViewportWidthOnMainThread:width];
4147 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4148 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4149 unsigned count([arguments count]);
4151 for (unsigned i(0); i != count; ++i)
4152 values[i] = [arguments objectAtIndex:i];
4153 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4156 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4157 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4159 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4161 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4167 /* @ Loading... Indicator {{{ */
4168 @interface CYLoadingIndicator : UIView {
4169 _H<UIActivityIndicatorView> spinner_;
4171 _H<UIView> container_;
4174 @property (readonly, nonatomic) UILabel *label;
4175 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4179 @implementation CYLoadingIndicator
4181 - (id) initWithFrame:(CGRect)frame {
4182 if ((self = [super initWithFrame:frame]) != nil) {
4183 container_ = [[[UIView alloc] init] autorelease];
4184 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4186 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4187 [spinner_ startAnimating];
4188 [container_ addSubview:spinner_];
4190 label_ = [[[UILabel alloc] init] autorelease];
4191 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4192 [label_ setBackgroundColor:[UIColor clearColor]];
4193 [label_ setTextColor:[UIColor blackColor]];
4194 [label_ setShadowColor:[UIColor whiteColor]];
4195 [label_ setShadowOffset:CGSizeMake(0, 1)];
4196 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4197 [container_ addSubview:label_];
4199 CGSize viewsize = frame.size;
4200 CGSize spinnersize = [spinner_ bounds].size;
4201 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4202 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4204 CGRect containrect = {
4205 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4206 CGSizeMake(bothwidth, spinnersize.height)
4209 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4217 [container_ setFrame:containrect];
4218 [spinner_ setFrame:spinrect];
4219 [label_ setFrame:textrect];
4220 [self addSubview:container_];
4224 - (UILabel *) label {
4228 - (UIActivityIndicatorView *) activityIndicatorView {
4234 /* Emulated Loading Controller {{{ */
4235 @interface CYEmulatedLoadingController : CyteViewController {
4236 _transient Database *database_;
4237 _H<CYLoadingIndicator> indicator_;
4238 _H<UITabBar> tabbar_;
4239 _H<UINavigationBar> navbar_;
4244 @implementation CYEmulatedLoadingController
4246 - (id) initWithDatabase:(Database *)database {
4247 if ((self = [super init]) != nil) {
4248 database_ = database;
4253 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4255 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4256 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4257 [[self view] addSubview:table];
4259 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4260 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4261 [[self view] addSubview:indicator_];
4263 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4264 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4265 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4266 [[self view] addSubview:tabbar_];
4268 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4269 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4270 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4271 [[self view] addSubview:navbar_];
4274 - (void) releaseSubviews {
4283 /* Cydia Browser Controller {{{ */
4284 @implementation CydiaWebViewController
4286 - (NSURL *) navigationURL {
4287 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4290 + (void) initialize {
4291 Diversions_ = [NSMutableSet setWithCapacity:0];
4294 + (void) addDiversion:(Diversion *)diversion {
4295 [Diversions_ addObject:diversion];
4298 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4299 [super webView:view didClearWindowObject:window forFrame:frame];
4301 WebDataSource *source([frame dataSource]);
4302 NSURLResponse *response([source response]);
4303 NSURL *url([response URL]);
4304 NSString *scheme([[url scheme] lowercaseString]);
4306 bool bridged(false);
4308 @synchronized (HostConfig_) {
4309 if ([scheme isEqualToString:@"file"])
4311 else if ([scheme isEqualToString:@"https"])
4312 if ([BridgedHosts_ containsObject:[url host]])
4317 [window setValue:cydia_ forKey:@"cydia"];
4320 - (NSURL *) URLWithURL:(NSURL *)url {
4321 return [Diversion divertURL:url];
4324 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4325 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4327 if (System_ != NULL)
4328 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4329 if (Machine_ != NULL)
4330 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4332 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4337 - (void) setDelegate:(id)delegate {
4338 [super setDelegate:delegate];
4339 [cydia_ setDelegate:delegate];
4343 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4344 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4346 WebView *webview([[webview_ _documentView] webView]);
4348 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4351 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4353 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4354 if (Product_ != nil)
4355 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4357 [webview setApplicationNameForUserAgent:application];
4365 @interface NSObject (CydiaScript)
4366 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4369 @implementation NSObject (CydiaScript)
4371 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4377 @implementation NSArray (CydiaScript)
4379 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4380 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4381 for (size_t i(0), e([self count]); i != e; ++i)
4382 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4388 @implementation NSDictionary (CydiaScript)
4390 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4391 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4393 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4400 /* Confirmation Controller {{{ */
4401 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4402 if (!iterator.end())
4403 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4404 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4406 pkgCache::PkgIterator package(dep.TargetPkg());
4409 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4416 @protocol ConfirmationControllerDelegate
4417 - (void) cancelAndClear:(bool)clear;
4418 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4422 @interface ConfirmationController : CydiaWebViewController {
4423 _transient Database *database_;
4425 _H<UIAlertView> essential_;
4427 _H<NSDictionary> changes_;
4428 _H<NSMutableArray> issues_;
4429 _H<NSDictionary> sizes_;
4434 - (id) initWithDatabase:(Database *)database;
4438 @implementation ConfirmationController
4442 RestartSubstrate_ = true;
4443 [delegate_ confirmWithNavigationController:[self navigationController]];
4446 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4447 NSString *context([alert context]);
4449 if ([context isEqualToString:@"remove"]) {
4450 if (button == [alert cancelButtonIndex])
4451 [self dismissModalViewControllerAnimated:YES];
4452 else if (button == [alert firstOtherButtonIndex]) {
4456 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4457 } else if ([context isEqualToString:@"unable"]) {
4458 [self dismissModalViewControllerAnimated:YES];
4459 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4461 [super alertView:alert clickedButtonAtIndex:button];
4465 - (void) _doContinue {
4466 [self dismissModalViewControllerAnimated:YES];
4467 [delegate_ cancelAndClear:NO];
4470 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4471 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4475 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4476 [super webView:view didClearWindowObject:window forFrame:frame];
4478 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4479 (id) changes_, @"changes",
4480 (id) issues_, @"issues",
4481 (id) sizes_, @"sizes",
4483 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4486 - (id) initWithDatabase:(Database *)database {
4487 if ((self = [super init]) != nil) {
4488 database_ = database;
4490 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4491 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4492 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4493 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4494 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4498 pkgCacheFile &cache([database_ cache]);
4499 NSArray *packages([database_ packages]);
4500 pkgDepCache::Policy *policy([database_ policy]);
4502 issues_ = [NSMutableArray arrayWithCapacity:4];
4504 for (Package *package in packages) {
4505 pkgCache::PkgIterator iterator([package iterator]);
4506 NSString *name([package id]);
4508 if ([package broken]) {
4509 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4511 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4513 reasons, @"reasons",
4516 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4520 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4521 pkgCache::DepIterator start;
4522 pkgCache::DepIterator end;
4523 dep.GlobOr(start, end); // ++dep
4525 if (!cache->IsImportantDep(end))
4527 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4530 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4532 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4533 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4534 clauses, @"clauses",
4538 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4540 pkgCache::PkgIterator target(start.TargetPkg());
4541 if (target->ProvidesList != 0)
4542 reason = @"missing";
4544 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4546 reason = @"installed";
4547 installed = [NSString stringWithUTF8String:ver.VerStr()];
4548 } else if (!cache[target].CandidateVerIter(cache).end())
4549 reason = @"uninstalled";
4550 else if (target->ProvidesList == 0)
4551 reason = @"uninstallable";
4553 reason = @"virtual";
4556 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4557 [NSString stringWithUTF8String:start.CompType()], @"operator",
4558 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4561 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4562 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4563 version, @"version",
4565 installed, @"installed",
4568 // yes, seriously. (wtf?)
4576 pkgDepCache::StateCache &state(cache[iterator]);
4578 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4580 if (state.NewInstall())
4581 [installs addObject:name];
4582 // XXX: else if (state.Install())
4583 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4584 [reinstalls addObject:name];
4585 // XXX: move before previous if
4586 else if (state.Upgrade())
4587 [upgrades addObject:name];
4588 else if (state.Downgrade())
4589 [downgrades addObject:name];
4590 else if (!state.Delete())
4591 // XXX: _assert(state.Keep());
4593 else if (special_r(name))
4594 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4595 [NSNull null], @"package",
4596 [NSArray arrayWithObjects:
4597 [NSDictionary dictionaryWithObjectsAndKeys:
4598 @"Conflicts", @"relationship",
4599 [NSArray arrayWithObjects:
4600 [NSDictionary dictionaryWithObjectsAndKeys:
4602 [NSNull null], @"version",
4603 @"installed", @"reason",
4610 if ([package essential])
4612 [removes addObject:name];
4615 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4616 substrate_ |= DepSubstrate(iterator.CurrentVer());
4621 else if (Advanced_) {
4622 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4624 essential_ = [[[UIAlertView alloc]
4625 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4626 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4628 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4630 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4634 [essential_ setContext:@"remove"];
4636 essential_ = [[[UIAlertView alloc]
4637 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4638 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4640 cancelButtonTitle:UCLocalize("OKAY")
4641 otherButtonTitles:nil
4644 [essential_ setContext:@"unable"];
4647 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4648 installs, @"installs",
4649 reinstalls, @"reinstalls",
4650 upgrades, @"upgrades",
4651 downgrades, @"downgrades",
4652 removes, @"removes",
4655 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4656 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4657 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4660 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4664 - (UIBarButtonItem *) leftButton {
4665 return [[[UIBarButtonItem alloc]
4666 initWithTitle:UCLocalize("CANCEL")
4667 style:UIBarButtonItemStylePlain
4669 action:@selector(cancelButtonClicked)
4674 - (void) applyRightButton {
4675 if ([issues_ count] == 0 && ![self isLoading])
4676 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4677 initWithTitle:UCLocalize("CONFIRM")
4678 style:UIBarButtonItemStyleDone
4680 action:@selector(confirmButtonClicked)
4683 [[self navigationItem] setRightBarButtonItem:nil];
4687 - (void) cancelButtonClicked {
4688 [self dismissModalViewControllerAnimated:YES];
4689 [delegate_ cancelAndClear:YES];
4693 - (void) confirmButtonClicked {
4694 if (essential_ != nil)
4704 /* Progress Data {{{ */
4705 @interface CydiaProgressData : NSObject {
4706 _transient id delegate_;
4715 _H<NSMutableArray> events_;
4716 _H<NSString> title_;
4718 _H<NSString> status_;
4719 _H<NSString> finish_;
4724 @implementation CydiaProgressData
4726 + (NSArray *) _attributeKeys {
4727 return [NSArray arrayWithObjects:
4739 - (NSArray *) attributeKeys {
4740 return [[self class] _attributeKeys];
4743 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4744 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4748 if ((self = [super init]) != nil) {
4749 events_ = [NSMutableArray arrayWithCapacity:32];
4753 - (void) setDelegate:(id)delegate {
4754 delegate_ = delegate;
4757 - (void) setPercent:(float)value {
4761 - (NSNumber *) percent {
4762 return [NSNumber numberWithFloat:percent_];
4765 - (void) setCurrent:(float)value {
4769 - (NSNumber *) current {
4770 return [NSNumber numberWithFloat:current_];
4773 - (void) setTotal:(float)value {
4777 - (NSNumber *) total {
4778 return [NSNumber numberWithFloat:total_];
4781 - (void) setSpeed:(float)value {
4785 - (NSNumber *) speed {
4786 return [NSNumber numberWithFloat:speed_];
4789 - (NSArray *) events {
4793 - (void) removeAllEvents {
4794 [events_ removeAllObjects];
4797 - (void) addEvent:(CydiaProgressEvent *)event {
4798 [events_ addObject:event];
4801 - (void) setTitle:(NSString *)text {
4805 - (NSString *) title {
4809 - (void) setFinish:(NSString *)text {
4813 - (NSString *) finish {
4814 return (id) finish_ ?: [NSNull null];
4817 - (void) setRunning:(bool)running {
4821 - (NSNumber *) running {
4822 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4827 /* Progress Controller {{{ */
4828 @interface ProgressController : CydiaWebViewController <
4831 _transient Database *database_;
4832 _H<CydiaProgressData, 1> progress_;
4836 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4838 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4840 - (void) setTitle:(NSString *)title;
4841 - (void) setCancellable:(bool)cancellable;
4845 @implementation ProgressController
4848 [database_ setProgressDelegate:nil];
4852 - (UIBarButtonItem *) leftButton {
4853 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4854 initWithTitle:UCLocalize("CANCEL")
4855 style:UIBarButtonItemStylePlain
4857 action:@selector(cancel)
4858 ] autorelease] : nil;
4861 - (void) updateCancel {
4862 [super applyLeftButton];
4865 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4866 if ((self = [super init]) != nil) {
4867 database_ = database;
4868 delegate_ = delegate;
4870 [database_ setProgressDelegate:self];
4872 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4873 [progress_ setDelegate:self];
4875 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4877 [scroller_ setBackgroundColor:[UIColor blackColor]];
4879 [[self navigationItem] setHidesBackButton:YES];
4881 [self updateCancel];
4885 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4886 [super webView:view didClearWindowObject:window forFrame:frame];
4887 [window setValue:progress_ forKey:@"cydiaProgress"];
4890 - (void) updateProgress {
4891 [self dispatchEvent:@"CydiaProgressUpdate"];
4894 - (void) viewWillAppear:(BOOL)animated {
4895 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4896 [super viewWillAppear:animated];
4900 UpdateExternalStatus(0);
4907 [delegate_ terminateWithSuccess];
4908 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4909 [delegate_ suspendWithAnimation:YES];
4911 [delegate_ suspend];*/
4923 system("/usr/bin/sbreload");
4929 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4930 SBReboot(SBSSpringBoardServerPort());
4932 reboot2(RB_AUTOBOOT);
4939 - (void) setTitle:(NSString *)title {
4940 [progress_ setTitle:title];
4941 [self updateProgress];
4944 - (UIBarButtonItem *) rightButton {
4945 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4946 initWithTitle:UCLocalize("CLOSE")
4947 style:UIBarButtonItemStylePlain
4949 action:@selector(close)
4953 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4954 UpdateExternalStatus(1);
4956 [progress_ setRunning:true];
4957 [self setTitle:title];
4958 // implicit updateProgress
4960 SHA1SumValue notifyconf; {
4962 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4965 MMap mmap(file, MMap::ReadOnly);
4967 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4968 notifyconf = sha1.Result();
4972 SHA1SumValue springlist; {
4974 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4977 MMap mmap(file, MMap::ReadOnly);
4979 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4980 springlist = sha1.Result();
4984 if (invocation != nil) {
4985 [invocation yieldToSelector:@selector(invoke)];
4986 [self setTitle:@"COMPLETE"];
4991 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4994 MMap mmap(file, MMap::ReadOnly);
4996 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4997 if (!(notifyconf == sha1.Result()))
5004 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5007 MMap mmap(file, MMap::ReadOnly);
5009 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5010 if (!(springlist == sha1.Result()))
5016 if (RestartSubstrate_)
5020 RestartSubstrate_ = false;
5023 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5024 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5025 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5026 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5027 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5031 system("su -c /usr/bin/uicache mobile");
5034 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5036 [progress_ setRunning:false];
5037 [self updateProgress];
5039 [self applyRightButton];
5042 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5043 [progress_ addEvent:event];
5044 [self updateProgress];
5047 - (bool) isProgressCancelled {
5048 return cancel_ == 2;
5053 [self updateCancel];
5056 - (void) setCancellable:(bool)cancellable {
5057 unsigned cancel(cancel_);
5061 else if (cancel_ == 0)
5064 if (cancel != cancel_)
5065 [self updateCancel];
5068 - (void) setProgressCancellable:(NSNumber *)cancellable {
5069 [self setCancellable:[cancellable boolValue]];
5072 - (void) setProgressPercent:(NSNumber *)percent {
5073 [progress_ setPercent:[percent floatValue]];
5074 [self updateProgress];
5077 - (void) setProgressStatus:(NSDictionary *)status {
5078 if (status == nil) {
5079 [progress_ setCurrent:0];
5080 [progress_ setTotal:0];
5081 [progress_ setSpeed:0];
5083 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5085 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5086 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5087 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5090 [self updateProgress];
5096 /* Package Cell {{{ */
5097 @interface PackageCell : CyteTableViewCell <
5098 CyteTableViewCellDelegate
5102 _H<NSString> description_;
5104 _H<NSString> source_;
5106 _H<Package> package_;
5107 _H<UIImage> placard_;
5111 - (PackageCell *) init;
5112 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5114 - (void) drawContentRect:(CGRect)rect;
5118 @implementation PackageCell
5120 - (PackageCell *) init {
5121 CGRect frame(CGRectMake(0, 0, 320, 74));
5122 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5123 UIView *content([self contentView]);
5124 CGRect bounds([content bounds]);
5126 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5127 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5128 [content addSubview:content_];
5130 [content_ setDelegate:self];
5131 [content_ setOpaque:YES];
5135 - (NSString *) accessibilityLabel {
5136 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5139 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5140 summarized_ = summary;
5152 Source *source = [package source];
5154 icon_ = [package icon];
5155 name_ = [package name];
5158 description_ = [package longDescription];
5159 if (description_ == nil)
5160 description_ = [package shortDescription];
5162 commercial_ = [package isCommercial];
5166 NSString *label = nil;
5167 bool trusted = false;
5169 if (source != nil) {
5170 label = [source label];
5171 trusted = [source trusted];
5172 } else if ([[package id] isEqualToString:@"firmware"])
5173 label = UCLocalize("APPLE");
5175 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5177 NSString *from(label);
5179 NSString *section = [package simpleSection];
5180 if (section != nil && ![section isEqualToString:label]) {
5181 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5182 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5185 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5187 if (NSString *purpose = [package primaryPurpose])
5188 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5193 if (NSString *mode = [package_ mode]) {
5194 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5195 color = RemovingColor_;
5196 //placard = @"removing";
5198 color = InstallingColor_;
5199 //placard = @"installing";
5202 // XXX: the removing/installing placards are not @2x
5205 color = [UIColor whiteColor];
5207 if ([package installed] != nil)
5208 placard = @"installed";
5213 [content_ setBackgroundColor:color];
5216 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5218 [self setNeedsDisplay];
5219 [content_ setNeedsDisplay];
5222 - (void) drawSummaryContentRect:(CGRect)rect {
5223 bool highlighted(highlighted_);
5224 float width([self bounds].size.width);
5228 rect.size = [(UIImage *) icon_ size];
5230 rect.size.width /= 4;
5231 rect.size.height /= 4;
5233 rect.origin.x = 14 - rect.size.width / 4;
5234 rect.origin.y = 14 - rect.size.height / 4;
5236 [icon_ drawInRect:rect];
5239 if (badge_ != nil) {
5241 rect.size = [(UIImage *) badge_ size];
5243 rect.size.width /= 4;
5244 rect.size.height /= 4;
5246 rect.origin.x = 20 - rect.size.width / 4;
5247 rect.origin.y = 20 - rect.size.height / 4;
5249 [badge_ drawInRect:rect];
5256 UISetColor(commercial_ ? Purple_ : Black_);
5257 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5259 if (placard_ != nil)
5260 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5263 - (void) drawNormalContentRect:(CGRect)rect {
5264 bool highlighted(highlighted_);
5265 float width([self bounds].size.width);
5269 rect.size = [(UIImage *) icon_ size];
5271 rect.size.width /= 2;
5272 rect.size.height /= 2;
5274 rect.origin.x = 25 - rect.size.width / 2;
5275 rect.origin.y = 25 - rect.size.height / 2;
5277 [icon_ drawInRect:rect];
5280 if (badge_ != nil) {
5282 rect.size = [(UIImage *) badge_ size];
5284 rect.size.width /= 2;
5285 rect.size.height /= 2;
5287 rect.origin.x = 36 - rect.size.width / 2;
5288 rect.origin.y = 36 - rect.size.height / 2;
5290 [badge_ drawInRect:rect];
5297 UISetColor(commercial_ ? Purple_ : Black_);
5298 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5299 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5302 UISetColor(commercial_ ? Purplish_ : Gray_);
5303 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5305 if (placard_ != nil)
5306 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5309 - (void) drawContentRect:(CGRect)rect {
5311 [self drawSummaryContentRect:rect];
5313 [self drawNormalContentRect:rect];
5318 /* Section Cell {{{ */
5319 @interface SectionCell : CyteTableViewCell <
5320 CyteTableViewCellDelegate
5322 _H<NSString> basic_;
5323 _H<NSString> section_;
5325 _H<NSString> count_;
5327 _H<UISwitch> switch_;
5331 - (void) setSection:(Section *)section editing:(BOOL)editing;
5335 @implementation SectionCell
5337 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5338 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5339 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5340 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5341 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5343 UIView *content([self contentView]);
5344 CGRect bounds([content bounds]);
5346 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5347 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5348 [content addSubview:content_];
5349 [content_ setBackgroundColor:[UIColor whiteColor]];
5351 [content_ setDelegate:self];
5355 - (void) onSwitch:(id)sender {
5356 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5357 if (metadata == nil) {
5358 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5359 [Sections_ setObject:metadata forKey:basic_];
5362 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5366 - (void) setSection:(Section *)section editing:(BOOL)editing {
5367 if (editing != editing_) {
5369 [switch_ removeFromSuperview];
5371 [self addSubview:switch_];
5380 if (section == nil) {
5381 name_ = UCLocalize("ALL_PACKAGES");
5384 basic_ = [section name];
5385 section_ = [section localized];
5387 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5388 count_ = [NSString stringWithFormat:@"%d", [section count]];
5391 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5394 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5395 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5397 [content_ setNeedsDisplay];
5400 - (void) setFrame:(CGRect)frame {
5401 [super setFrame:frame];
5403 CGRect rect([switch_ frame]);
5404 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5407 - (NSString *) accessibilityLabel {
5411 - (void) drawContentRect:(CGRect)rect {
5412 bool highlighted(highlighted_ && !editing_);
5414 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5419 float width(rect.size.width);
5425 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5427 CGSize size = [count_ sizeWithFont:Font14_];
5431 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5437 /* File Table {{{ */
5438 @interface FileTable : CyteViewController <
5439 UITableViewDataSource,
5442 _transient Database *database_;
5443 _H<Package> package_;
5445 _H<NSMutableArray> files_;
5446 _H<UITableView, 2> list_;
5449 - (id) initWithDatabase:(Database *)database;
5450 - (void) setPackage:(Package *)package;
5454 @implementation FileTable
5456 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5457 return files_ == nil ? 0 : [files_ count];
5460 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5464 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5465 static NSString *reuseIdentifier = @"Cell";
5467 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5469 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5470 [cell setFont:[UIFont systemFontOfSize:16]];
5472 [cell setText:[files_ objectAtIndex:indexPath.row]];
5473 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5478 - (NSURL *) navigationURL {
5479 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5483 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5485 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5486 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5487 [list_ setRowHeight:24.0f];
5488 [(UITableView *) list_ setDataSource:self];
5489 [list_ setDelegate:self];
5490 [[self view] addSubview:list_];
5493 - (void) viewDidLoad {
5494 [super viewDidLoad];
5496 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5499 - (void) releaseSubviews {
5503 - (id) initWithDatabase:(Database *)database {
5504 if ((self = [super init]) != nil) {
5505 database_ = database;
5507 files_ = [NSMutableArray arrayWithCapacity:32];
5511 - (void) setPackage:(Package *)package {
5515 [files_ removeAllObjects];
5517 if (package != nil) {
5519 name_ = [package id];
5521 if (NSArray *files = [package files])
5522 [files_ addObjectsFromArray:files];
5524 if ([files_ count] != 0) {
5525 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5526 [files_ removeObjectAtIndex:0];
5527 [files_ sortUsingSelector:@selector(compareByPath:)];
5529 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5530 [stack addObject:@"/"];
5532 for (int i(0), e([files_ count]); i != e; ++i) {
5533 NSString *file = [files_ objectAtIndex:i];
5534 while (![file hasPrefix:[stack lastObject]])
5535 [stack removeLastObject];
5536 NSString *directory = [stack lastObject];
5537 [stack addObject:[file stringByAppendingString:@"/"]];
5538 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5539 ([stack count] - 2) * 3, "",
5540 [file substringFromIndex:[directory length]]
5549 - (void) reloadData {
5552 [self setPackage:[database_ packageWithName:name_]];
5557 /* Package Controller {{{ */
5558 @interface CYPackageController : CydiaWebViewController <
5559 UIActionSheetDelegate
5561 _transient Database *database_;
5562 _H<Package> package_;
5565 _H<NSMutableArray> buttons_;
5566 _H<UIBarButtonItem> button_;
5569 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5573 @implementation CYPackageController
5575 - (NSURL *) navigationURL {
5576 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5579 /* XXX: this is not safe at all... localization of /fail/ */
5580 - (void) _clickButtonWithName:(NSString *)name {
5581 if ([name isEqualToString:UCLocalize("CLEAR")])
5582 [delegate_ clearPackage:package_];
5583 else if ([name isEqualToString:UCLocalize("INSTALL")])
5584 [delegate_ installPackage:package_];
5585 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5586 [delegate_ installPackage:package_];
5587 else if ([name isEqualToString:UCLocalize("REMOVE")])
5588 [delegate_ removePackage:package_];
5589 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5590 [delegate_ installPackage:package_];
5591 else _assert(false);
5594 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5595 NSString *context([sheet context]);
5597 if ([context isEqualToString:@"modify"]) {
5598 if (button != [sheet cancelButtonIndex]) {
5599 NSString *buttonName = [buttons_ objectAtIndex:button];
5600 [self _clickButtonWithName:buttonName];
5603 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5607 - (bool) _allowJavaScriptPanel {
5612 - (void) _customButtonClicked {
5613 int count([buttons_ count]);
5618 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5620 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5621 [buttons addObjectsFromArray:buttons_];
5623 UIActionSheet *sheet = [[[UIActionSheet alloc]
5626 cancelButtonTitle:nil
5627 destructiveButtonTitle:nil
5628 otherButtonTitles:nil
5631 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5633 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5634 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5636 [sheet setContext:@"modify"];
5638 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5642 // We don't want to allow non-commercial packages to do custom things to the install button,
5643 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5644 - (void) customButtonClicked {
5646 [super customButtonClicked];
5648 [self _customButtonClicked];
5651 - (void) reloadButtonClicked {
5652 // Don't reload a commerical package by tapping the loading button,
5653 // but if it's not an Install button, we should forward it on.
5654 if (![package_ uninstalled])
5655 [self _customButtonClicked];
5658 - (void) applyLoadingTitle {
5659 // Don't show "Loading" as the title. Ever.
5662 - (UIBarButtonItem *) rightButton {
5667 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5668 if ((self = [super init]) != nil) {
5669 database_ = database;
5670 buttons_ = [NSMutableArray arrayWithCapacity:4];
5671 name_ = [NSString stringWithString:name];
5672 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5676 - (void) reloadData {
5679 package_ = [database_ packageWithName:name_];
5681 [buttons_ removeAllObjects];
5683 if (package_ != nil) {
5684 [(Package *) package_ parse];
5686 commercial_ = [package_ isCommercial];
5688 if ([package_ mode] != nil)
5689 [buttons_ addObject:UCLocalize("CLEAR")];
5690 if ([package_ source] == nil);
5691 else if ([package_ upgradableAndEssential:NO])
5692 [buttons_ addObject:UCLocalize("UPGRADE")];
5693 else if ([package_ uninstalled])
5694 [buttons_ addObject:UCLocalize("INSTALL")];
5696 [buttons_ addObject:UCLocalize("REINSTALL")];
5697 if (![package_ uninstalled])
5698 [buttons_ addObject:UCLocalize("REMOVE")];
5702 switch ([buttons_ count]) {
5703 case 0: title = nil; break;
5704 case 1: title = [buttons_ objectAtIndex:0]; break;
5705 default: title = UCLocalize("MODIFY"); break;
5708 button_ = [[[UIBarButtonItem alloc]
5710 style:UIBarButtonItemStylePlain
5712 action:@selector(customButtonClicked)
5716 - (bool) isLoading {
5717 return commercial_ ? [super isLoading] : false;
5723 /* Package List Controller {{{ */
5724 @interface PackageListController : CyteViewController <
5725 UITableViewDataSource,
5728 _transient Database *database_;
5730 _H<NSArray> packages_;
5731 _H<NSMutableArray> sections_;
5732 _H<UITableView, 2> list_;
5733 _H<NSMutableArray> index_;
5734 _H<NSMutableDictionary> indices_;
5735 _H<NSString> title_;
5736 unsigned reloading_;
5739 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5740 - (void) setDelegate:(id)delegate;
5741 - (void) resetCursor;
5746 @implementation PackageListController
5748 - (bool) isSummarized {
5752 - (void) deselectWithAnimation:(BOOL)animated {
5753 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5756 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5757 CGRect base = [[self view] bounds];
5758 base.size.height -= bounds.size.height;
5759 base.origin = [list_ frame].origin;
5761 [UIView beginAnimations:nil context:NULL];
5762 [UIView setAnimationBeginsFromCurrentState:YES];
5763 [UIView setAnimationCurve:curve];
5764 [UIView setAnimationDuration:duration];
5765 [list_ setFrame:base];
5766 [UIView commitAnimations];
5769 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5770 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5773 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5774 [self resizeForKeyboardBounds:bounds duration:0];
5777 - (void) keyboardWillShow:(NSNotification *)notification {
5780 NSTimeInterval duration;
5781 UIViewAnimationCurve curve;
5782 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5783 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5784 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5785 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5787 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);
5788 UIViewController *base = self;
5789 while ([base parentViewController] != nil)
5790 base = [base parentViewController];
5791 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5792 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5794 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5797 - (void) keyboardWillHide:(NSNotification *)notification {
5798 NSTimeInterval duration;
5799 UIViewAnimationCurve curve;
5800 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5801 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5803 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5806 - (void) viewWillAppear:(BOOL)animated {
5807 [super viewWillAppear:animated];
5809 [self resizeForKeyboardBounds:CGRectZero];
5810 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5811 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5814 - (void) viewWillDisappear:(BOOL)animated {
5815 [super viewWillDisappear:animated];
5817 [self resizeForKeyboardBounds:CGRectZero];
5818 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5819 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5822 - (void) viewDidAppear:(BOOL)animated {
5823 [super viewDidAppear:animated];
5824 [self deselectWithAnimation:animated];
5827 - (void) didSelectPackage:(Package *)package {
5828 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5829 [view setDelegate:delegate_];
5830 [[self navigationController] pushViewController:view animated:YES];
5833 #if TryIndexedCollation
5834 + (BOOL) hasIndexedCollation {
5835 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5839 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5840 NSInteger count([sections_ count]);
5841 return count == 0 ? 1 : count;
5844 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5845 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5847 return [[sections_ objectAtIndex:section] name];
5850 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5851 if ([sections_ count] == 0)
5853 return [[sections_ objectAtIndex:section] count];
5856 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5857 @synchronized (database_) {
5858 if ([database_ era] != era_)
5861 Section *section([sections_ objectAtIndex:[path section]]);
5862 NSInteger row([path row]);
5863 Package *package([packages_ objectAtIndex:([section row] + row)]);
5864 return [[package retain] autorelease];
5867 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5868 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5870 cell = [[[PackageCell alloc] init] autorelease];
5871 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5875 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5876 Package *package([self packageAtIndexPath:path]);
5877 package = [database_ packageWithName:[package id]];
5878 [self didSelectPackage:package];
5881 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5882 if ([self isSummarized])
5888 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5889 #if TryIndexedCollation
5890 if ([[self class] hasIndexedCollation]) {
5891 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5898 - (void) updateHeight {
5899 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5902 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5903 if ((self = [super init]) != nil) {
5904 database_ = database;
5905 title_ = [title copy];
5906 [[self navigationItem] setTitle:title_];
5908 #if TryIndexedCollation
5909 if ([[self class] hasIndexedCollation])
5910 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5913 index_ = [NSMutableArray arrayWithCapacity:32];
5915 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5917 packages_ = [NSArray array];
5918 sections_ = [NSMutableArray arrayWithCapacity:16];
5920 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5921 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5922 [[self view] addSubview:list_];
5924 // XXX: is 20 the most optimal number here?
5925 [list_ setSectionIndexMinimumDisplayRowCount:20];
5927 [(UITableView *) list_ setDataSource:self];
5928 [list_ setDelegate:self];
5930 [self updateHeight];
5934 - (void) setDelegate:(id)delegate {
5935 delegate_ = delegate;
5938 - (bool) hasPackage:(Package *)package {
5942 - (bool) shouldYield {
5946 - (bool) shouldBlock {
5950 - (NSArray *) _reloadPackages:(NSArray *)packages {
5951 // XXX: maybe move @synchronized() to _reloadData?
5952 @synchronized (database_) {
5953 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
5955 _profile(PackageTable$reloadData$Filter)
5956 for (Package *package in packages)
5957 if ([self hasPackage:package])
5958 [filtered addObject:package];
5964 - (void) _reloadData {
5965 if (reloading_ != 0) {
5970 era_ = [database_ era];
5971 NSArray *packages = [database_ packages];
5973 if ([self shouldYield]) {
5976 if (![self shouldBlock])
5979 hud = [delegate_ addProgressHUD];
5980 [hud setText:UCLocalize("LOADING")];
5985 packages_ = [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
5986 } while (reloading_ == 2);
5991 [delegate_ removeProgressHUD:hud];
5993 packages_ = [self _reloadPackages:packages];
5996 [indices_ removeAllObjects];
5997 [sections_ removeAllObjects];
5999 Section *section = nil;
6001 #if TryIndexedCollation
6002 if ([[self class] hasIndexedCollation]) {
6003 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6004 NSArray *titles = [collation sectionIndexTitles];
6007 _profile(PackageTable$reloadData$Section)
6008 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6012 _profile(PackageTable$reloadData$Section$Package)
6013 package = [packages_ objectAtIndex:offset];
6014 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6017 while (secidx < index) {
6020 _profile(PackageTable$reloadData$Section$Allocate)
6021 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6024 _profile(PackageTable$reloadData$Section$Add)
6025 [sections_ addObject:section];
6029 [section addToCount];
6035 [index_ removeAllObjects];
6037 bool summary([self isSummarized]);
6039 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6040 [sections_ addObject:section];
6043 _profile(PackageTable$reloadData$Section)
6044 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6048 _profile(PackageTable$reloadData$Section$Package)
6049 package = [packages_ objectAtIndex:offset];
6050 index = [package index];
6053 if (!summary && (section == nil || [section index] != index)) {
6054 _profile(PackageTable$reloadData$Section$Allocate)
6055 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6058 [index_ addObject:[section name]];
6059 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6061 _profile(PackageTable$reloadData$Section$Add)
6062 [sections_ addObject:section];
6066 [section addToCount];
6071 [self updateHeight];
6073 _profile(PackageTable$reloadData$List)
6074 [(UITableView *) list_ setDataSource:self];
6079 - (void) reloadData {
6081 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6084 - (void) resetCursor {
6085 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6088 - (void) clearData {
6089 [self updateHeight];
6091 [list_ setDataSource:nil];
6099 /* Filtered Package List Controller {{{ */
6100 @interface FilteredPackageListController : PackageListController {
6103 _H<NSObject> object_;
6106 - (void) setObject:(id)object;
6107 - (void) setObject:(id)object forFilter:(SEL)filter;
6110 - (void) setFilter:(SEL)filter;
6112 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6116 @implementation FilteredPackageListController
6122 - (void) setFilter:(SEL)filter {
6125 /* XXX: this is an unsafe optimization of doomy hell */
6126 Method method(class_getInstanceMethod([Package class], filter));
6127 _assert(method != NULL);
6128 imp_ = method_getImplementation(method);
6129 _assert(imp_ != NULL);
6132 - (void) setObject:(id)object {
6136 - (void) setObject:(id)object forFilter:(SEL)filter {
6137 [self setFilter:filter];
6138 [self setObject:object];
6141 - (bool) hasPackage:(Package *)package {
6142 _profile(FilteredPackageTable$hasPackage)
6143 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6147 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6148 if ((self = [super initWithDatabase:database title:title]) != nil) {
6149 [self setFilter:filter];
6150 [self setObject:object];
6157 /* Home Controller {{{ */
6158 @interface HomeController : CydiaWebViewController {
6163 @implementation HomeController
6166 if ((self = [super init]) != nil) {
6167 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6172 - (NSURL *) navigationURL {
6173 return [NSURL URLWithString:@"cydia://home"];
6176 - (void) aboutButtonClicked {
6177 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6179 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6180 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6181 [alert setCancelButtonIndex:0];
6184 @"Copyright \u00a9 2008-2011\n"
6187 "Jay Freeman (saurik)\n"
6188 "saurik@saurik.com\n"
6189 "http://www.saurik.com/"
6195 - (UIBarButtonItem *) leftButton {
6196 return [[[UIBarButtonItem alloc]
6197 initWithTitle:UCLocalize("ABOUT")
6198 style:UIBarButtonItemStylePlain
6200 action:@selector(aboutButtonClicked)
6204 - (void) unloadData {
6211 /* Manage Controller {{{ */
6212 @interface ManageController : CydiaWebViewController {
6215 - (void) queueStatusDidChange;
6219 @implementation ManageController
6222 if ((self = [super init]) != nil) {
6223 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6227 - (NSURL *) navigationURL {
6228 return [NSURL URLWithString:@"cydia://manage"];
6231 - (UIBarButtonItem *) leftButton {
6232 return [[[UIBarButtonItem alloc]
6233 initWithTitle:UCLocalize("SETTINGS")
6234 style:UIBarButtonItemStylePlain
6236 action:@selector(settingsButtonClicked)
6240 - (void) settingsButtonClicked {
6241 [delegate_ showSettings];
6244 - (void) queueButtonClicked {
6248 - (UIBarButtonItem *) customButton {
6249 return Queuing_ ? [[[UIBarButtonItem alloc]
6250 initWithTitle:UCLocalize("QUEUE")
6251 style:UIBarButtonItemStyleDone
6253 action:@selector(queueButtonClicked)
6254 ] autorelease] : [super customButton];
6257 - (void) queueStatusDidChange {
6258 [self applyRightButton];
6261 - (bool) isLoading {
6262 return !Queuing_ && [super isLoading];
6268 /* Refresh Bar {{{ */
6269 @interface RefreshBar : UINavigationBar {
6270 _H<UIProgressIndicator> indicator_;
6271 _H<UITextLabel> prompt_;
6272 _H<UIProgressBar> progress_;
6273 _H<UINavigationButton> cancel_;
6278 @implementation RefreshBar
6280 - (void) positionViews {
6281 CGRect frame = [cancel_ frame];
6282 frame.size = [cancel_ sizeThatFits:frame.size];
6283 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6284 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6285 [cancel_ setFrame:frame];
6287 CGSize prgsize = {75, 100};
6289 [self frame].size.width - prgsize.width - 10,
6290 ([self frame].size.height - prgsize.height) / 2
6292 [progress_ setFrame:prgrect];
6294 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6295 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6296 CGRect indrect = {{indoffset, indoffset}, indsize};
6297 [indicator_ setFrame:indrect];
6299 CGSize prmsize = {215, indsize.height + 4};
6301 indoffset * 2 + indsize.width,
6302 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6304 [prompt_ setFrame:prmrect];
6307 - (void) setFrame:(CGRect)frame {
6308 [super setFrame:frame];
6309 [self positionViews];
6312 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6313 if ((self = [super initWithFrame:frame]) != nil) {
6314 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6316 [self setBarStyle:UIBarStyleBlack];
6318 UIBarStyle barstyle([self _barStyle:NO]);
6319 bool ugly(barstyle == UIBarStyleDefault);
6321 UIProgressIndicatorStyle style = ugly ?
6322 UIProgressIndicatorStyleMediumBrown :
6323 UIProgressIndicatorStyleMediumWhite;
6325 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6326 [(UIProgressIndicator *) indicator_ setStyle:style];
6327 [indicator_ startAnimation];
6328 [self addSubview:indicator_];
6330 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6331 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6332 [prompt_ setBackgroundColor:[UIColor clearColor]];
6333 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6334 [self addSubview:prompt_];
6336 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6337 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6338 [(UIProgressBar *) progress_ setStyle:0];
6339 [self addSubview:progress_];
6341 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6342 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6343 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6344 [cancel_ setBarStyle:barstyle];
6346 [self positionViews];
6350 - (void) setCancellable:(bool)cancellable {
6352 [self addSubview:cancel_];
6354 [cancel_ removeFromSuperview];
6358 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6359 [progress_ setProgress:0];
6363 [self setCancellable:NO];
6366 - (void) setPrompt:(NSString *)prompt {
6367 [prompt_ setText:prompt];
6370 - (void) setProgress:(float)progress {
6371 [progress_ setProgress:progress];
6377 /* Cydia Navigation Controller Interface {{{ */
6378 @interface UINavigationController (Cydia)
6380 - (NSArray *) navigationURLCollection;
6381 - (void) unloadData;
6386 /* Cydia Tab Bar Controller {{{ */
6387 @interface CYTabBarController : UITabBarController <
6388 UITabBarControllerDelegate,
6391 _transient Database *database_;
6392 _H<RefreshBar, 1> refreshbar_;
6396 // XXX: ok, "updatedelegate_"?...
6397 _transient NSObject<CydiaDelegate> *updatedelegate_;
6399 _H<UIViewController> remembered_;
6400 _transient UIViewController *transient_;
6403 - (NSArray *) navigationURLCollection;
6404 - (void) dropBar:(BOOL)animated;
6405 - (void) beginUpdate;
6406 - (void) raiseBar:(BOOL)animated;
6408 - (void) unloadData;
6412 @implementation CYTabBarController
6414 - (void) setUnselectedViewController:(UIViewController *)transient {
6415 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6416 if (transient != nil) {
6417 if (transient_ == nil)
6418 remembered_ = [controllers objectAtIndex:0];
6419 transient_ = transient;
6420 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6421 [controllers replaceObjectAtIndex:0 withObject:transient_];
6422 [self setSelectedIndex:0];
6423 [self setViewControllers:controllers];
6424 [self concealTabBarSelection];
6425 } else if (remembered_ != nil) {
6426 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6427 transient_ = transient;
6428 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6430 [self setViewControllers:controllers];
6431 [self revealTabBarSelection];
6435 - (UIViewController *) unselectedViewController {
6439 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6440 if ([self unselectedViewController])
6441 [self setUnselectedViewController:nil];
6444 - (NSArray *) navigationURLCollection {
6445 NSMutableArray *items([NSMutableArray array]);
6447 // XXX: Should this deal with transient view controllers?
6448 for (id navigation in [self viewControllers]) {
6449 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6451 [items addObject:stack];
6457 - (void) unloadData {
6458 UIViewController *selected([self selectedViewController]);
6459 for (UINavigationController *controller in [self viewControllers])
6460 [controller unloadData];
6462 [selected reloadData];
6464 if (UIViewController *unselected = [self unselectedViewController])
6465 [unselected reloadData];
6471 [[NSNotificationCenter defaultCenter] removeObserver:self];
6476 - (id) initWithDatabase:(Database *)database {
6477 if ((self = [super init]) != nil) {
6478 database_ = database;
6479 [self setDelegate:self];
6481 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6482 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6484 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6488 - (void) setUpdate:(NSDate *)date {
6492 - (void) beginUpdate {
6493 [(RefreshBar *) refreshbar_ start];
6496 [updatedelegate_ retainNetworkActivityIndicator];
6500 detachNewThreadSelector:@selector(performUpdate)
6506 - (void) performUpdate {
6507 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6510 status.setDelegate(self);
6511 [database_ updateWithStatus:status];
6514 performSelectorOnMainThread:@selector(completeUpdate)
6522 - (void) stopUpdateWithSelector:(SEL)selector {
6524 [updatedelegate_ releaseNetworkActivityIndicator];
6526 [self raiseBar:YES];
6529 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6532 - (void) completeUpdate {
6535 [self stopUpdateWithSelector:@selector(reloadData)];
6538 - (void) cancelUpdate {
6539 [self stopUpdateWithSelector:@selector(updateData)];
6542 - (void) cancelPressed {
6543 [self cancelUpdate];
6550 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6551 [refreshbar_ setPrompt:[event compoundMessage]];
6554 - (bool) isProgressCancelled {
6558 - (void) setProgressCancellable:(NSNumber *)cancellable {
6559 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6562 - (void) setProgressPercent:(NSNumber *)percent {
6563 [refreshbar_ setProgress:[percent floatValue]];
6566 - (void) setProgressStatus:(NSDictionary *)status {
6568 [self setProgressPercent:[status objectForKey:@"Percent"]];
6571 - (void) setUpdateDelegate:(id)delegate {
6572 updatedelegate_ = delegate;
6575 - (CGFloat) statusBarHeight {
6576 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6577 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6579 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6583 - (UIView *) transitionView {
6584 if ([self respondsToSelector:@selector(_transitionView)])
6585 return [self _transitionView];
6587 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6590 - (void) dropBar:(BOOL)animated {
6595 UIView *transition([self transitionView]);
6596 [[self view] addSubview:refreshbar_];
6598 CGRect barframe([refreshbar_ frame]);
6600 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6601 barframe.origin.y = [self statusBarHeight];
6603 barframe.origin.y = 0;
6605 [refreshbar_ setFrame:barframe];
6608 [UIView beginAnimations:nil context:NULL];
6610 CGRect viewframe = [transition frame];
6611 viewframe.origin.y += barframe.size.height;
6612 viewframe.size.height -= barframe.size.height;
6613 [transition setFrame:viewframe];
6616 [UIView commitAnimations];
6618 // Ensure bar has the proper width for our view, it might have changed
6619 barframe.size.width = viewframe.size.width;
6620 [refreshbar_ setFrame:barframe];
6623 - (void) raiseBar:(BOOL)animated {
6628 UIView *transition([self transitionView]);
6629 [refreshbar_ removeFromSuperview];
6631 CGRect barframe([refreshbar_ frame]);
6634 [UIView beginAnimations:nil context:NULL];
6636 CGRect viewframe = [transition frame];
6637 viewframe.origin.y -= barframe.size.height;
6638 viewframe.size.height += barframe.size.height;
6639 [transition setFrame:viewframe];
6642 [UIView commitAnimations];
6645 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6646 bool dropped(dropped_);
6651 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6657 - (void) statusBarFrameChanged:(NSNotification *)notification {
6667 /* Cydia Navigation Controller Implementation {{{ */
6668 @implementation UINavigationController (Cydia)
6670 - (NSArray *) navigationURLCollection {
6671 NSMutableArray *stack([NSMutableArray array]);
6673 for (CyteViewController *controller in [self viewControllers]) {
6674 NSString *url = [[controller navigationURL] absoluteString];
6676 [stack addObject:url];
6682 - (void) reloadData {
6685 if (UIViewController *visible = [self visibleViewController])
6686 [visible reloadData];
6689 - (void) unloadData {
6690 for (CyteViewController *page in [self viewControllers])
6699 /* Cydia:// Protocol {{{ */
6700 @interface CydiaURLProtocol : NSURLProtocol {
6705 @implementation CydiaURLProtocol
6707 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6708 NSURL *url([request URL]);
6712 NSString *scheme([[url scheme] lowercaseString]);
6713 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6715 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6721 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6725 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6726 id<NSURLProtocolClient> client([self client]);
6728 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6730 NSData *data(UIImagePNGRepresentation(icon));
6732 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6733 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6734 [client URLProtocol:self didLoadData:data];
6735 [client URLProtocolDidFinishLoading:self];
6739 - (void) startLoading {
6740 id<NSURLProtocolClient> client([self client]);
6741 NSURLRequest *request([self request]);
6743 NSURL *url([request URL]);
6744 NSString *href([url absoluteString]);
6745 NSString *scheme([[url scheme] lowercaseString]);
6749 if ([scheme isEqualToString:@"cydia"])
6750 path = [href substringFromIndex:8];
6751 else if ([scheme isEqualToString:@"about"])
6752 path = [href substringFromIndex:12];
6753 else _assert(false);
6755 NSRange slash([path rangeOfString:@"/"]);
6758 if (slash.location == NSNotFound) {
6762 command = [path substringToIndex:slash.location];
6763 path = [path substringFromIndex:(slash.location + 1)];
6766 Database *database([Database sharedInstance]);
6768 if ([command isEqualToString:@"package-icon"]) {
6771 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6772 Package *package([database packageWithName:path]);
6776 UIImage *icon([package icon]);
6777 [self _returnPNGWithImage:icon forRequest:request];
6778 } else if ([command isEqualToString:@"source-icon"]) {
6781 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6782 NSString *source(Simplify(path));
6783 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6785 icon = [UIImage applicationImageNamed:@"unknown.png"];
6786 [self _returnPNGWithImage:icon forRequest:request];
6787 } else if ([command isEqualToString:@"uikit-image"]) {
6790 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6791 UIImage *icon(_UIImageWithName(path));
6792 [self _returnPNGWithImage:icon forRequest:request];
6793 } else if ([command isEqualToString:@"section-icon"]) {
6796 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6797 NSString *section(Simplify(path));
6798 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6800 icon = [UIImage applicationImageNamed:@"unknown.png"];
6801 [self _returnPNGWithImage:icon forRequest:request];
6803 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6807 - (void) stopLoading {
6813 /* Section Controller {{{ */
6814 @interface SectionController : FilteredPackageListController {
6815 _H<NSString> section_;
6818 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6822 @implementation SectionController
6824 - (NSURL *) navigationURL {
6825 NSString *name = section_;
6829 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6832 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6835 title = UCLocalize("ALL_PACKAGES");
6836 else if (![name isEqual:@""])
6837 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6839 title = UCLocalize("NO_SECTION");
6841 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6848 /* Sections Controller {{{ */
6849 @interface SectionsController : CyteViewController <
6850 UITableViewDataSource,
6853 _transient Database *database_;
6854 _H<NSMutableArray> sections_;
6855 _H<NSMutableArray> filtered_;
6856 _H<UITableView, 2> list_;
6859 - (id) initWithDatabase:(Database *)database;
6860 - (void) editButtonClicked;
6864 @implementation SectionsController
6866 - (NSURL *) navigationURL {
6867 return [NSURL URLWithString:@"cydia://sections"];
6870 - (void) updateNavigationItem {
6871 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6872 if ([sections_ count] == 0) {
6873 [[self navigationItem] setRightBarButtonItem:nil];
6875 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6876 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6878 action:@selector(editButtonClicked)
6879 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6883 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6884 [super setEditing:editing animated:animated];
6889 [delegate_ updateData];
6891 [self updateNavigationItem];
6894 - (void) viewDidAppear:(BOOL)animated {
6895 [super viewDidAppear:animated];
6896 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6899 - (void) viewWillDisappear:(BOOL)animated {
6900 [super viewWillDisappear:animated];
6901 if ([self isEditing]) [self setEditing:NO];
6904 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6905 Section *section = nil;
6906 int index = [indexPath row];
6907 if (![self isEditing]) {
6910 section = [filtered_ objectAtIndex:index];
6912 section = [sections_ objectAtIndex:index];
6917 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6918 if ([self isEditing])
6919 return [sections_ count];
6921 return [filtered_ count] + 1;
6924 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6928 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6929 static NSString *reuseIdentifier = @"SectionCell";
6931 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6933 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6935 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6940 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6941 if ([self isEditing])
6944 Section *section = [self sectionAtIndexPath:indexPath];
6946 SectionController *controller = [[[SectionController alloc]
6947 initWithDatabase:database_
6948 section:[section name]
6950 [controller setDelegate:delegate_];
6952 [[self navigationController] pushViewController:controller animated:YES];
6956 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6958 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6959 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6960 [list_ setRowHeight:45.0f];
6961 [(UITableView *) list_ setDataSource:self];
6962 [list_ setDelegate:self];
6963 [[self view] addSubview:list_];
6966 - (void) viewDidLoad {
6967 [super viewDidLoad];
6969 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6972 - (void) releaseSubviews {
6976 - (id) initWithDatabase:(Database *)database {
6977 if ((self = [super init]) != nil) {
6978 database_ = database;
6980 sections_ = [NSMutableArray arrayWithCapacity:16];
6981 filtered_ = [NSMutableArray arrayWithCapacity:16];
6985 - (void) reloadData {
6988 NSArray *packages = [database_ packages];
6990 [sections_ removeAllObjects];
6991 [filtered_ removeAllObjects];
6993 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6996 for (Package *package in packages) {
6997 NSString *name([package section]);
6998 NSString *key(name == nil ? @"" : name);
7002 _profile(SectionsView$reloadData$Section)
7003 section = [sections objectForKey:key];
7004 if (section == nil) {
7005 _profile(SectionsView$reloadData$Section$Allocate)
7006 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7007 [sections setObject:section forKey:key];
7012 [section addToCount];
7014 _profile(SectionsView$reloadData$Filter)
7015 if (![package valid] || ![package visible])
7023 [sections_ addObjectsFromArray:[sections allValues]];
7025 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7027 for (Section *section in (id) sections_) {
7028 size_t count([section row]);
7032 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7033 [section setCount:count];
7034 [filtered_ addObject:section];
7037 [self updateNavigationItem];
7042 - (void) editButtonClicked {
7043 [self setEditing:![self isEditing] animated:YES];
7049 /* Changes Controller {{{ */
7050 @interface ChangesController : CyteViewController <
7051 UITableViewDataSource,
7054 _transient Database *database_;
7056 _H<NSArray> packages_;
7057 _H<NSMutableArray> sections_;
7058 _H<UITableView, 2> list_;
7062 - (id) initWithDatabase:(Database *)database;
7066 @implementation ChangesController
7068 - (NSURL *) navigationURL {
7069 return [NSURL URLWithString:@"cydia://changes"];
7072 - (void) viewDidAppear:(BOOL)animated {
7073 [super viewDidAppear:animated];
7074 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7077 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7078 NSInteger count([sections_ count]);
7079 return count == 0 ? 1 : count;
7082 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7083 if ([sections_ count] == 0)
7085 return [[sections_ objectAtIndex:section] name];
7088 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7089 if ([sections_ count] == 0)
7091 return [[sections_ objectAtIndex:section] count];
7094 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7095 @synchronized (database_) {
7096 if ([database_ era] != era_)
7099 NSUInteger sectionIndex([path section]);
7100 if (sectionIndex >= [sections_ count])
7102 Section *section([sections_ objectAtIndex:sectionIndex]);
7103 NSInteger row([path row]);
7104 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7107 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7108 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7110 cell = [[[PackageCell alloc] init] autorelease];
7111 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7115 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7116 Package *package([self packageAtIndexPath:path]);
7117 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7118 [view setDelegate:delegate_];
7119 [[self navigationController] pushViewController:view animated:YES];
7123 - (void) refreshButtonClicked {
7124 [delegate_ beginUpdate];
7125 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7128 - (void) upgradeButtonClicked {
7129 [delegate_ distUpgrade];
7133 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7135 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7136 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7137 [list_ setRowHeight:73];
7138 [(UITableView *) list_ setDataSource:self];
7139 [list_ setDelegate:self];
7140 [[self view] addSubview:list_];
7143 - (void) viewDidLoad {
7144 [super viewDidLoad];
7146 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7149 - (void) releaseSubviews {
7153 - (id) initWithDatabase:(Database *)database {
7154 if ((self = [super init]) != nil) {
7155 database_ = database;
7157 packages_ = [NSArray array];
7158 sections_ = [NSMutableArray arrayWithCapacity:16];
7162 - (NSArray *) _reloadPackages:(NSArray *)packages {
7163 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7166 _profile(ChangesController$_reloadPackages$Filter)
7167 for (Package *package in packages)
7168 if ([package upgradableAndEssential:YES] || [package visible])
7169 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7172 _profile(ChangesController$_reloadPackages$radixSort)
7173 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7180 - (void) _reloadData {
7181 @synchronized (database_) {
7182 era_ = [database_ era];
7183 NSArray *packages = [database_ packages];
7186 UIProgressHUD *hud([delegate_ addProgressHUD]);
7187 [hud setText:UCLocalize("LOADING")];
7188 //NSLog(@"HUD:%@::%@", delegate_, hud);
7189 packages_ = [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7190 [delegate_ removeProgressHUD:hud];
7192 packages_ = [self _reloadPackages:packages];
7195 [sections_ removeAllObjects];
7197 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7198 Section *ignored = nil;
7199 Section *section = nil;
7203 bool unseens = false;
7205 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7207 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7208 Package *package = [packages_ objectAtIndex:offset];
7210 BOOL uae = [package upgradableAndEssential:YES];
7214 time_t seen([package seen]);
7216 if (section == nil || last != seen) {
7220 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7223 _profile(ChangesController$reloadData$Allocate)
7224 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7225 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7226 [sections_ addObject:section];
7230 [section addToCount];
7231 } else if ([package ignored]) {
7232 if (ignored == nil) {
7233 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7235 [ignored addToCount];
7238 [upgradable addToCount];
7243 CFRelease(formatter);
7246 Section *last = [sections_ lastObject];
7247 size_t count = [last count];
7248 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7249 [sections_ removeLastObject];
7252 if ([ignored count] != 0)
7253 [sections_ insertObject:ignored atIndex:0];
7255 [sections_ insertObject:upgradable atIndex:0];
7260 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7261 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7262 style:UIBarButtonItemStylePlain
7264 action:@selector(upgradeButtonClicked)
7267 if (![delegate_ updating])
7268 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7269 initWithTitle:UCLocalize("REFRESH")
7270 style:UIBarButtonItemStylePlain
7272 action:@selector(refreshButtonClicked)
7278 - (void) reloadData {
7280 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7285 /* Search Controller {{{ */
7286 @interface SearchController : FilteredPackageListController <
7289 _H<UISearchBar, 1> search_;
7293 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7294 - (void) reloadData;
7298 @implementation SearchController
7300 - (NSURL *) navigationURL {
7301 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7302 return [NSURL URLWithString:@"cydia://search"];
7304 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7307 - (void) useSearch {
7308 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7313 - (void) viewWillAppear:(BOOL)animated {
7314 [super viewWillAppear:animated];
7316 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7320 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7321 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7326 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7327 [search_ resignFirstResponder];
7331 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7332 [search_ setText:@""];
7333 [self searchBarButtonClicked:searchBar];
7336 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7337 [self searchBarButtonClicked:searchBar];
7340 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7341 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7345 - (bool) shouldYield {
7349 - (bool) shouldBlock {
7350 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7353 - (bool) isSummarized {
7354 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7357 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7358 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7359 search_ = [[[UISearchBar alloc] init] autorelease];
7360 [search_ setDelegate:self];
7363 [search_ setText:query];
7367 - (void) viewDidAppear:(BOOL)animated {
7368 [super viewDidAppear:animated];
7370 if (!searchloaded_) {
7371 searchloaded_ = YES;
7372 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7373 [search_ layoutSubviews];
7374 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7376 UITextField *textField;
7377 if ([search_ respondsToSelector:@selector(searchField)])
7378 textField = [search_ searchField];
7380 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7382 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7383 [textField setEnablesReturnKeyAutomatically:NO];
7384 [[self navigationItem] setTitleView:textField];
7388 - (void) reloadData {
7389 [self setObject:[search_ text]];
7395 - (void) didSelectPackage:(Package *)package {
7396 [search_ resignFirstResponder];
7397 [super didSelectPackage:package];
7402 /* Package Settings Controller {{{ */
7403 @interface PackageSettingsController : CyteViewController <
7404 UITableViewDataSource,
7407 _transient Database *database_;
7409 _H<Package> package_;
7410 _H<UITableView, 2> table_;
7411 _H<UISwitch> subscribedSwitch_;
7412 _H<UISwitch> ignoredSwitch_;
7413 _H<UITableViewCell> subscribedCell_;
7414 _H<UITableViewCell> ignoredCell_;
7417 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7421 @implementation PackageSettingsController
7423 - (NSURL *) navigationURL {
7424 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7427 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7428 if (package_ == nil)
7431 if ([package_ installed] == nil)
7437 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7438 if (package_ == nil)
7441 // both sections contain just one item right now.
7445 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7449 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7451 return UCLocalize("SHOW_ALL_CHANGES_EX");
7453 return UCLocalize("IGNORE_UPGRADES_EX");
7456 - (void) onSubscribed:(id)control {
7457 bool value([control isOn]);
7458 if (package_ == nil)
7460 if ([package_ setSubscribed:value])
7461 [delegate_ updateData];
7464 - (void) _updateIgnored {
7465 const char *package([name_ UTF8String]);
7466 bool on([ignoredSwitch_ isOn]);
7468 pid_t pid(ExecFork());
7470 FILE *dpkg(popen("dpkg --set-selections", "w"));
7471 fwrite(package, strlen(package), 1, dpkg);
7474 fwrite(" hold\n", 6, 1, dpkg);
7476 fwrite(" install\n", 9, 1, dpkg);
7486 int result(waitpid(pid, &status, 0));
7489 _assert(result == pid);
7495 - (void) onIgnored:(id)control {
7496 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7497 [invocation setTarget:self];
7498 [invocation setSelector:@selector(_updateIgnored)];
7500 [delegate_ reloadDataWithInvocation:invocation];
7503 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7504 if (package_ == nil)
7507 switch ([indexPath section]) {
7508 case 0: return subscribedCell_;
7509 case 1: return ignoredCell_;
7518 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7520 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7521 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7522 [(UITableView *) table_ setDataSource:self];
7523 [table_ setDelegate:self];
7524 [[self view] addSubview:table_];
7526 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7527 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7528 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7530 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7531 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7532 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7534 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7535 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7536 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7537 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7539 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7540 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7541 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7542 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7545 - (void) viewDidLoad {
7546 [super viewDidLoad];
7548 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7551 - (void) releaseSubviews {
7553 subscribedCell_ = nil;
7555 ignoredSwitch_ = nil;
7556 subscribedSwitch_ = nil;
7559 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7560 if ((self = [super init]) != nil) {
7561 database_ = database;
7566 - (void) reloadData {
7569 package_ = [database_ packageWithName:name_];
7571 if (package_ != nil) {
7572 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7573 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7574 } // XXX: what now, G?
7576 [table_ reloadData];
7582 /* Installed Controller {{{ */
7583 @interface InstalledController : FilteredPackageListController {
7587 - (id) initWithDatabase:(Database *)database;
7589 - (void) updateRoleButton;
7590 - (void) queueStatusDidChange;
7594 @implementation InstalledController
7596 - (NSURL *) navigationURL {
7597 return [NSURL URLWithString:@"cydia://installed"];
7600 - (id) initWithDatabase:(Database *)database {
7601 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7602 [self updateRoleButton];
7603 [self queueStatusDidChange];
7608 - (void) queueButtonClicked {
7613 - (void) queueStatusDidChange {
7617 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7618 initWithTitle:UCLocalize("QUEUE")
7619 style:UIBarButtonItemStyleDone
7621 action:@selector(queueButtonClicked)
7624 [[self navigationItem] setLeftBarButtonItem:nil];
7630 - (void) updateRoleButton {
7631 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7632 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7633 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7634 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7636 action:@selector(roleButtonClicked)
7640 - (void) roleButtonClicked {
7641 [self setObject:[NSNumber numberWithBool:expert_]];
7645 [self updateRoleButton];
7651 /* Source Cell {{{ */
7652 @interface SourceCell : CyteTableViewCell <
7653 CyteTableViewCellDelegate
7656 _H<NSString> origin_;
7657 _H<NSString> label_;
7660 - (void) setSource:(Source *)source;
7664 @implementation SourceCell
7666 - (void) setSource:(Source *)source {
7669 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7671 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7673 origin_ = [source name];
7674 label_ = [source uri];
7676 [content_ setNeedsDisplay];
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]);
8469 @interface Cydia : UIApplication <
8470 ConfirmationControllerDelegate,
8473 UINavigationControllerDelegate,
8474 UITabBarControllerDelegate
8476 _H<UIWindow> window_;
8477 _H<CYTabBarController> tabbar_;
8478 _H<CYEmulatedLoadingController> emulated_;
8480 _H<NSMutableArray> essential_;
8481 _H<NSMutableArray> broken_;
8483 Database *database_;
8485 _H<NSURL> starturl_;
8490 _H<StashController> stash_;
8499 @implementation Cydia
8501 - (void) beginUpdate {
8502 [tabbar_ beginUpdate];
8506 return [tabbar_ updating];
8510 if ([broken_ count] != 0) {
8511 int count = [broken_ count];
8513 UIAlertView *alert = [[[UIAlertView alloc]
8514 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8515 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8517 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8519 UCLocalize("TEMPORARY_IGNORE"),
8523 [alert setContext:@"fixhalf"];
8524 [alert setNumberOfRows:2];
8526 } else if (!Ignored_ && [essential_ count] != 0) {
8527 int count = [essential_ count];
8529 UIAlertView *alert = [[[UIAlertView alloc]
8530 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8531 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8533 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8535 UCLocalize("UPGRADE_ESSENTIAL"),
8536 UCLocalize("COMPLETE_UPGRADE"),
8540 [alert setContext:@"upgrade"];
8545 - (void) _saveConfig {
8551 NSString *error(nil);
8553 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8555 NSError *error(nil);
8556 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8557 NSLog(@"failure to save metadata data: %@", error);
8562 NSLog(@"failure to serialize metadata: %@", error);
8567 // Navigation controller for the queuing badge.
8568 - (UINavigationController *) queueNavigationController {
8569 NSArray *controllers = [tabbar_ viewControllers];
8570 return [controllers objectAtIndex:3];
8573 - (void) unloadData {
8574 [tabbar_ unloadData];
8577 - (void) _updateData {
8582 UINavigationController *navigation = [self queueNavigationController];
8584 id queuedelegate = nil;
8585 if ([[navigation viewControllers] count] > 0)
8586 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8588 [queuedelegate queueStatusDidChange];
8589 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8592 - (void) _refreshIfPossible:(NSDate *)update {
8593 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8595 bool recently = false;
8596 if (update != nil) {
8597 NSTimeInterval interval([update timeIntervalSinceNow]);
8598 if (interval <= 0 && interval > -(15*60))
8602 // Don't automatic refresh if:
8603 // - We already refreshed recently.
8604 // - We already auto-refreshed this launch.
8605 // - Auto-refresh is disabled.
8606 if (recently || loaded_ || ManualRefresh) {
8607 // If we are cancelling, we need to make sure it knows it's already loaded.
8610 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8612 // We are going to load, so remember that.
8615 SCNetworkReachabilityFlags flags; {
8616 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8617 SCNetworkReachabilityGetFlags(reachability, &flags);
8618 CFRelease(reachability);
8621 // XXX: this elaborate mess is what Apple is using to determine this? :(
8622 // XXX: do we care if the user has to intervene? maybe that's ok?
8624 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8625 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8626 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8627 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8628 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8629 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8633 // If we can reach the server, auto-refresh!
8635 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8641 - (void) refreshIfPossible {
8642 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8645 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8646 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8647 [hud setText:UCLocalize("RELOADING_DATA")];
8649 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8652 [self removeProgressHUD:hud];
8656 [essential_ removeAllObjects];
8657 [broken_ removeAllObjects];
8659 NSArray *packages([database_ packages]);
8660 for (Package *package in packages) {
8662 [broken_ addObject:package];
8663 if ([package upgradableAndEssential:NO]) {
8664 if ([package essential])
8665 [essential_ addObject:package];
8670 NSLog(@"changes:#%u", changes);
8672 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8675 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8676 [changesItem setBadgeValue:badge];
8677 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8678 [self setApplicationIconBadgeNumber:changes];
8681 [changesItem setBadgeValue:nil];
8682 [changesItem setAnimatedBadge:NO];
8683 [self setApplicationIconBadgeNumber:0];
8688 [self refreshIfPossible];
8691 - (void) updateData {
8700 @synchronized (self) {
8701 [self _reloadDataWithInvocation:nil];
8705 - (void) disemulate {
8706 if (emulated_ == nil)
8709 [window_ addSubview:[tabbar_ view]];
8710 [[emulated_ view] removeFromSuperview];
8712 [window_ setUserInteractionEnabled:YES];
8715 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8716 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8718 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8720 UIViewController *parent;
8721 if (emulated_ == nil)
8730 [parent presentModalViewController:navigation animated:YES];
8733 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8734 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8736 if (navigation != nil)
8737 [navigation pushViewController:progress animated:YES];
8739 [self presentModalViewController:progress force:YES];
8741 [progress invoke:invocation withTitle:title];
8745 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8746 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8749 - (void) repairWithInvocation:(NSInvocation *)invocation {
8751 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8755 - (void) repairWithSelector:(SEL)selector {
8756 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8762 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8763 _assert(file != NULL);
8765 for (NSString *key in [Sources_ allKeys]) {
8766 NSDictionary *source([Sources_ objectForKey:key]);
8768 fprintf(file, "%s %s %s\n",
8769 [[source objectForKey:@"Type"] UTF8String],
8770 [[source objectForKey:@"URI"] UTF8String],
8771 [[source objectForKey:@"Distribution"] UTF8String]
8777 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8782 - (void) addTrivialSource:(NSString *)href {
8783 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8786 @"./", @"Distribution",
8787 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8792 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8793 @synchronized (self) {
8794 [self _reloadDataWithInvocation:invocation];
8798 - (void) reloadData {
8799 [self reloadDataWithInvocation:nil];
8803 pkgProblemResolver *resolver = [database_ resolver];
8805 resolver->InstallProtect();
8806 if (!resolver->Resolve(true))
8811 // XXX: this is a really crappy way of doing this.
8812 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8813 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8814 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8815 if ([tabbar_ updating])
8816 [tabbar_ cancelUpdate];
8818 if (![database_ prepare])
8821 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8822 [page setDelegate:self];
8823 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8826 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8827 [tabbar_ presentModalViewController:confirm_ animated:YES];
8833 @synchronized (self) {
8838 - (void) clearPackage:(Package *)package {
8839 @synchronized (self) {
8846 - (void) installPackages:(NSArray *)packages {
8847 @synchronized (self) {
8848 for (Package *package in packages)
8855 - (void) installPackage:(Package *)package {
8856 @synchronized (self) {
8863 - (void) removePackage:(Package *)package {
8864 @synchronized (self) {
8871 - (void) distUpgrade {
8872 @synchronized (self) {
8873 if (![database_ upgrade])
8879 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8882 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8887 - (void) showSettings {
8888 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8891 - (void) retainNetworkActivityIndicator {
8892 if (activity_++ == 0)
8893 [self setNetworkActivityIndicatorVisible:YES];
8896 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8900 - (void) releaseNetworkActivityIndicator {
8901 if (--activity_ == 0)
8902 [self setNetworkActivityIndicatorVisible:NO];
8905 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8910 - (void) cancelAndClear:(bool)clear {
8911 @synchronized (self) {
8923 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8924 NSString *context([alert context]);
8926 if ([context isEqualToString:@"conffile"]) {
8927 FILE *input = [database_ input];
8928 if (button == [alert cancelButtonIndex])
8929 fprintf(input, "N\n");
8930 else if (button == [alert firstOtherButtonIndex])
8931 fprintf(input, "Y\n");
8934 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8935 } else if ([context isEqualToString:@"fixhalf"]) {
8936 if (button == [alert cancelButtonIndex]) {
8937 @synchronized (self) {
8938 for (Package *broken in (id) broken_) {
8941 NSString *id = [broken id];
8942 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8943 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8944 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8945 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8951 } else if (button == [alert firstOtherButtonIndex]) {
8952 [broken_ removeAllObjects];
8956 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8957 } else if ([context isEqualToString:@"upgrade"]) {
8958 if (button == [alert firstOtherButtonIndex]) {
8959 @synchronized (self) {
8960 for (Package *essential in (id) essential_)
8961 [essential install];
8966 } else if (button == [alert firstOtherButtonIndex] + 1) {
8968 } else if (button == [alert cancelButtonIndex]) {
8972 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8976 - (void) system:(NSString *)command {
8977 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8980 system([command UTF8String]);
8986 - (void) applicationWillSuspend {
8988 [super applicationWillSuspend];
8991 - (BOOL) isSafeToSuspend {
8994 NSLog(@"isSafeToSuspend: locked_ != 0");
8999 // Use external process status API internally.
9000 // This is probably a really bad idea.
9001 // XXX: what is the point of this? does this solve anything at all?
9002 uint64_t status = 0;
9004 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9005 notify_get_state(notify_token, &status);
9006 notify_cancel(notify_token);
9011 NSLog(@"isSafeToSuspend: status != 0");
9017 NSLog(@"isSafeToSuspend: -> true");
9022 - (void) applicationSuspend:(__GSEvent *)event {
9023 if ([self isSafeToSuspend])
9024 [super applicationSuspend:event];
9027 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9028 if ([self isSafeToSuspend])
9029 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9032 - (void) _setSuspended:(BOOL)value {
9033 if ([self isSafeToSuspend])
9034 [super _setSuspended:value];
9037 - (UIProgressHUD *) addProgressHUD {
9038 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9039 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9041 [window_ setUserInteractionEnabled:NO];
9043 UIViewController *target(tabbar_);
9044 if (UIViewController *modal = [target modalViewController])
9047 UIView *view([target view]);
9048 [view addSubview:hud];
9056 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9059 [hud removeFromSuperview];
9060 [window_ setUserInteractionEnabled:YES];
9063 - (CyteViewController *) pageForPackage:(NSString *)name {
9064 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9067 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9068 NSString *scheme([[url scheme] lowercaseString]);
9069 if ([[url absoluteString] length] <= [scheme length] + 3)
9071 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9072 NSArray *components([path pathComponents]);
9074 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9075 return [self pageForPackage:[components objectAtIndex:1]];
9077 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9080 NSString *base([components objectAtIndex:0]);
9082 CyteViewController *controller = nil;
9084 if ([base isEqualToString:@"url"]) {
9085 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9086 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9087 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9088 } else if (!external && [components count] == 1) {
9089 if ([base isEqualToString:@"manage"]) {
9090 controller = [[[ManageController alloc] init] autorelease];
9093 if ([base isEqualToString:@"sources"]) {
9094 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9097 if ([base isEqualToString:@"home"]) {
9098 controller = [[[HomeController alloc] init] autorelease];
9101 if ([base isEqualToString:@"sections"]) {
9102 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9105 if ([base isEqualToString:@"search"]) {
9106 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9109 if ([base isEqualToString:@"changes"]) {
9110 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9113 if ([base isEqualToString:@"installed"]) {
9114 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9116 } else if ([components count] == 2) {
9117 NSString *argument = [components objectAtIndex:1];
9119 if ([base isEqualToString:@"package"]) {
9120 controller = [self pageForPackage:argument];
9123 if (!external && [base isEqualToString:@"search"]) {
9124 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9127 if (!external && [base isEqualToString:@"sections"]) {
9128 if ([argument isEqualToString:@"all"])
9130 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9133 if (!external && [base isEqualToString:@"sources"]) {
9134 if ([argument isEqualToString:@"add"]) {
9135 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9136 [(SourcesController *)controller showAddSourcePrompt];
9138 Source *source = [database_ sourceWithKey:argument];
9139 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9143 if (!external && [base isEqualToString:@"launch"]) {
9144 [self launchApplicationWithIdentifier:argument suspended:NO];
9147 } else if (!external && [components count] == 3) {
9148 NSString *arg1 = [components objectAtIndex:1];
9149 NSString *arg2 = [components objectAtIndex:2];
9151 if ([base isEqualToString:@"package"]) {
9152 if ([arg2 isEqualToString:@"settings"]) {
9153 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9154 } else if ([arg2 isEqualToString:@"files"]) {
9155 if (Package *package = [database_ packageWithName:arg1]) {
9156 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9157 [(FileTable *)controller setPackage:package];
9163 [controller setDelegate:self];
9167 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9168 CyteViewController *page([self pageForURL:url forExternal:external]);
9171 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9172 [nav setViewControllers:[NSArray arrayWithObject:page]];
9173 [tabbar_ setUnselectedViewController:nav];
9179 - (void) applicationOpenURL:(NSURL *)url {
9180 [super applicationOpenURL:url];
9185 [self openCydiaURL:url forExternal:YES];
9188 - (void) applicationWillResignActive:(UIApplication *)application {
9189 // Stop refreshing if you get a phone call or lock the device.
9190 if ([tabbar_ updating])
9191 [tabbar_ cancelUpdate];
9193 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9194 [super applicationWillResignActive:application];
9197 - (void) applicationWillTerminate:(UIApplication *)application {
9199 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9200 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9201 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9206 - (void) setConfigurationData:(NSString *)data {
9207 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9209 if (!conffile_r(data)) {
9210 lprintf("E:invalid conffile\n");
9214 NSString *ofile = conffile_r[1];
9215 //NSString *nfile = conffile_r[2];
9217 UIAlertView *alert = [[[UIAlertView alloc]
9218 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9219 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9221 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9223 UCLocalize("ACCEPT_NEW_COPY"),
9224 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9228 [alert setContext:@"conffile"];
9229 [alert setNumberOfRows:2];
9233 - (void) addStashController {
9235 stash_ = [[[StashController alloc] init] autorelease];
9236 [window_ addSubview:[stash_ view]];
9239 - (void) removeStashController {
9240 [[stash_ view] removeFromSuperview];
9246 [self setIdleTimerDisabled:YES];
9248 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9249 UpdateExternalStatus(1);
9250 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9251 UpdateExternalStatus(0);
9253 [self removeStashController];
9255 if (ExecFork() == 0) {
9256 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9257 perror("launchctl stop");
9261 - (void) setupViewControllers {
9262 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9264 NSMutableArray *items([NSMutableArray arrayWithObjects:
9265 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9266 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9267 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9268 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9272 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9273 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9275 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9278 NSMutableArray *controllers([NSMutableArray array]);
9279 for (UITabBarItem *item in items) {
9280 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9281 [controller setTabBarItem:item];
9282 [controllers addObject:controller];
9284 [tabbar_ setViewControllers:controllers];
9286 [tabbar_ setUpdateDelegate:self];
9289 - (void) applicationDidFinishLaunching:(id)unused {
9291 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9292 [self setApplicationSupportsShakeToEdit:NO];
9294 @synchronized (HostConfig_) {
9295 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9298 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9299 initWithMemoryCapacity:524288
9300 diskCapacity:10485760
9301 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9304 [CydiaWebViewController _initialize];
9306 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9308 // this would disallow http{,s} URLs from accessing this data
9309 //[WebView registerURLSchemeAsLocal:@"cydia"];
9311 Font12_ = [UIFont systemFontOfSize:12];
9312 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9313 Font14_ = [UIFont systemFontOfSize:14];
9314 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9315 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9317 essential_ = [NSMutableArray arrayWithCapacity:4];
9318 broken_ = [NSMutableArray arrayWithCapacity:4];
9320 // XXX: I really need this thing... like, seriously... I'm sorry
9321 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9323 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9324 [window_ orderFront:self];
9325 [window_ makeKey:self];
9326 [window_ setHidden:NO];
9329 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9330 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9331 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9332 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9333 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9334 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9335 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9336 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9337 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9340 [self addStashController];
9341 // XXX: this would be much cleaner as a yieldToSelector:
9342 // that way the removeStashController could happen right here inline
9343 // we also could no longer require the useless stash_ field anymore
9344 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9348 database_ = [Database sharedInstance];
9349 [database_ setDelegate:self];
9351 [window_ setUserInteractionEnabled:NO];
9352 [self setupViewControllers];
9354 emulated_ = [[[CYEmulatedLoadingController alloc] initWithDatabase:database_] autorelease];
9355 [window_ addSubview:[emulated_ view]];
9357 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9361 - (NSArray *) defaultStartPages {
9362 NSMutableArray *standard = [NSMutableArray array];
9363 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9364 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9365 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9367 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9369 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9370 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9372 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9379 [window_ setUserInteractionEnabled:YES];
9380 [self showSettings];
9383 if ([emulated_ modalViewController] != nil)
9384 [emulated_ dismissModalViewControllerAnimated:YES];
9385 [window_ setUserInteractionEnabled:NO];
9393 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9394 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9395 int standardIndex = 0;
9396 NSArray *standard = [self defaultStartPages];
9403 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9404 if (valid && closed != nil) {
9405 NSTimeInterval interval([closed timeIntervalSinceNow]);
9406 // XXX: Is 15 minutes the optimal time here?
9407 if (interval > 0 && interval <= -(15*60))
9411 if (valid && [saved count] != [standard count])
9415 for (unsigned int i = 0; i < [standard count]; i++) {
9416 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9417 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9418 // but it's good enough for now.
9419 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9426 NSArray *items = nil;
9428 [tabbar_ setSelectedIndex:savedIndex];
9431 [tabbar_ setSelectedIndex:standardIndex];
9435 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9436 NSArray *stack = [items objectAtIndex:tab];
9437 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9438 NSMutableArray *current = [NSMutableArray array];
9440 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9441 NSString *addr = [stack objectAtIndex:nav];
9442 NSURL *url = [NSURL URLWithString:addr];
9443 CyteViewController *page = [self pageForURL:url forExternal:NO];
9445 [current addObject:page];
9448 [navigation setViewControllers:current];
9451 // (Try to) show the startup URL.
9452 if (starturl_ != nil) {
9453 [self openCydiaURL:starturl_ forExternal:NO];
9458 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9459 if (item != nil && IsWildcat_) {
9460 [sheet showFromBarButtonItem:item animated:YES];
9462 [sheet showInView:window_];
9466 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9467 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9468 [progress setTitle:task];
9469 [progress addProgressEvent:event];
9472 - (void) addProgressEventForTask:(NSArray *)data {
9473 CydiaProgressEvent *event([data objectAtIndex:0]);
9474 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9475 [self addProgressEvent:event forTask:task];
9478 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9479 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9485 id Alloc_(id self, SEL selector) {
9486 id object = alloc_(self, selector);
9487 lprintf("[%s]A-%p\n", self->isa->name, object);
9492 id Dealloc_(id self, SEL selector) {
9493 id object = dealloc_(self, selector);
9494 lprintf("[%s]D-%p\n", self->isa->name, object);
9498 Class $WebDefaultUIKitDelegate;
9500 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9501 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9502 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9503 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9506 static NSSet *MobilizedFiles_;
9508 static NSURL *MobilizeURL(NSURL *url) {
9509 NSString *path([url path]);
9510 if ([path hasPrefix:@"/var/root/"]) {
9511 NSString *file([path substringFromIndex:10]);
9512 if ([MobilizedFiles_ containsObject:file])
9513 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9519 Class $CFXPreferencesPropertyListSource;
9520 @class CFXPreferencesPropertyListSource;
9522 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9523 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9524 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9525 url = MobilizeURL(url);
9526 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9527 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9533 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9534 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9535 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9536 url = MobilizeURL(url);
9537 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9538 //NSLog(@"%@ %@", [url absoluteString], value);
9544 Class $NSURLConnection;
9546 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9547 NSMutableURLRequest *copy([request mutableCopy]);
9549 NSURL *url([copy URL]);
9550 NSString *host([url host]);
9551 NSString *scheme([[url scheme] lowercaseString]);
9553 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9555 @synchronized (HostConfig_) {
9556 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9557 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9558 [copy setHTTPShouldUsePipelining:YES];
9561 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9565 int main(int argc, char *argv[]) {
9566 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9570 UpdateExternalStatus(0);
9572 if (Class $UIDevice = objc_getClass("UIDevice")) {
9573 UIDevice *device([$UIDevice currentDevice]);
9574 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9578 UIScreen *screen([UIScreen mainScreen]);
9579 if ([screen respondsToSelector:@selector(scale)])
9580 ScreenScale_ = [screen scale];
9584 UIDevice *device([UIDevice currentDevice]);
9585 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9588 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9589 if (idiom == UIUserInterfaceIdiomPhone)
9591 else if (idiom == UIUserInterfaceIdiomPad)
9594 NSLog(@"unknown UIUserInterfaceIdiom!");
9597 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9599 HostConfig_ = [[[NSObject alloc] init] autorelease];
9600 @synchronized (HostConfig_) {
9601 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9602 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9605 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9607 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9609 MobilizedFiles_ = [NSMutableSet setWithObjects:
9610 @"Library/Preferences/com.apple.Accessibility.plist",
9611 @"Library/Preferences/com.apple.preferences.sounds.plist",
9614 /* Library Hacks {{{ */
9615 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9617 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9619 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9620 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9621 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9622 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9625 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9626 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9627 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9628 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9631 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9632 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9633 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9634 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9635 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9638 $NSURLConnection = objc_getClass("NSURLConnection");
9639 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9640 if (NSURLConnection$init$ != NULL) {
9641 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9642 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9645 /* Set Locale {{{ */
9646 Locale_ = CFLocaleCopyCurrent();
9647 Languages_ = [NSLocale preferredLanguages];
9649 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9650 //NSLog(@"%@", [Languages_ description]);
9653 if (Locale_ != NULL)
9654 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9655 else if (Languages_ != nil && [Languages_ count] != 0)
9656 lang = [[Languages_ objectAtIndex:0] UTF8String];
9658 // XXX: consider just setting to C and then falling through?
9662 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9663 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9666 NSLog(@"Setting Language: %s", lang);
9669 setenv("LANG", lang, true);
9670 std::setlocale(LC_ALL, lang);
9674 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9676 /* Parse Arguments {{{ */
9677 bool substrate(false);
9683 for (int argi(1); argi != argc; ++argi)
9684 if (strcmp(argv[argi], "--") == 0) {
9686 argv[argi] = argv[0];
9692 for (int argi(1); argi != arge; ++argi)
9693 if (strcmp(args[argi], "--substrate") == 0)
9696 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9700 App_ = [[NSBundle mainBundle] bundlePath];
9706 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9707 alloc_ = alloc->method_imp;
9708 alloc->method_imp = (IMP) &Alloc_;*/
9710 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9711 dealloc_ = dealloc->method_imp;
9712 dealloc->method_imp = (IMP) &Dealloc_;*/
9714 /* System Information {{{ */
9718 size = sizeof(maxproc);
9719 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9720 perror("sysctlbyname(\"kern.maxproc\", ?)");
9721 else if (maxproc < 64) {
9723 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9724 perror("sysctlbyname(\"kern.maxproc\", #)");
9727 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9728 char *osversion = new char[size];
9729 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9730 perror("sysctlbyname(\"kern.osversion\", ?)");
9732 System_ = [NSString stringWithUTF8String:osversion];
9734 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9735 char *machine = new char[size];
9736 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9737 perror("sysctlbyname(\"hw.machine\", ?)");
9741 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9742 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9743 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9745 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9747 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9748 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9749 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9751 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9752 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9753 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9755 if (mcc != NULL && mnc != NULL)
9756 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9763 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9764 Build_ = [system objectForKey:@"ProductBuildVersion"];
9765 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9766 Product_ = [info objectForKey:@"SafariProductVersion"];
9767 Safari_ = [info objectForKey:@"CFBundleVersion"];
9770 /* Load Database {{{ */
9772 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9774 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9776 if (Metadata_ == NULL)
9777 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9779 Settings_ = [Metadata_ objectForKey:@"Settings"];
9781 Packages_ = [Metadata_ objectForKey:@"Packages"];
9782 Sections_ = [Metadata_ objectForKey:@"Sections"];
9783 Sources_ = [Metadata_ objectForKey:@"Sources"];
9785 Token_ = [Metadata_ objectForKey:@"Token"];
9788 if (Settings_ != nil)
9789 Role_ = [Settings_ objectForKey:@"Role"];
9791 if (Sections_ == nil) {
9792 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9793 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9796 if (Sources_ == nil) {
9797 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9798 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9803 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9806 if (Packages_ != nil) {
9808 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9812 [Metadata_ removeObjectForKey:@"Packages"];
9818 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9820 #define MobileSubstrate_(name) \
9821 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9822 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9823 if (handle == NULL) \
9824 NSLog(@"%s", dlerror()); \
9827 MobileSubstrate_(Activator)
9828 MobileSubstrate_(libstatusbar)
9829 MobileSubstrate_(SimulatedKeyEvents)
9830 MobileSubstrate_(WinterBoard)
9832 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9833 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9835 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9837 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9838 unlink("/tmp/.cydia.fw");
9840 } else if (access("/User", F_OK) != 0 || version < 4) {
9843 system("/usr/libexec/cydia/firmware.sh");
9847 _assert([[NSFileManager defaultManager]
9848 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9849 withIntermediateDirectories:YES
9854 if (access("/tmp/cydia.chk", F_OK) == 0) {
9855 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9856 _assert(errno == ENOENT);
9857 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9858 _assert(errno == ENOENT);
9861 /* APT Initialization {{{ */
9862 _assert(pkgInitConfig(*_config));
9863 _assert(pkgInitSystem(*_config, _system));
9866 _config->Set("APT::Acquire::Translation", lang);
9868 // XXX: this timeout might be important :(
9869 //_config->Set("Acquire::http::Timeout", 15);
9871 _config->Set("Acquire::http::MaxParallel", 3);
9873 /* Color Choices {{{ */
9874 space_ = CGColorSpaceCreateDeviceRGB();
9876 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9877 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9878 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9879 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9880 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9881 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9882 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9883 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9884 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9886 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9887 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9889 /* UIKit Configuration {{{ */
9890 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9891 if ($GSFontSetUseLegacyFontMetrics != NULL)
9892 $GSFontSetUseLegacyFontMetrics(YES);
9894 // XXX: I have a feeling this was important
9895 //UIKeyboardDisableAutomaticAppearance();
9898 Colon_ = UCLocalize("COLON_DELIMITED");
9899 Elision_ = UCLocalize("ELISION");
9900 Error_ = UCLocalize("ERROR");
9901 Warning_ = UCLocalize("WARNING");
9904 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9906 CGColorSpaceRelease(space_);