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_;
1268 _H<NSString> authority_;
1270 CYString defaultIcon_;
1272 _H<NSDictionary> record_;
1276 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1278 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1280 - (NSString *) depictionForPackage:(NSString *)package;
1281 - (NSString *) supportForPackage:(NSString *)package;
1283 - (NSDictionary *) record;
1287 - (NSString *) distribution;
1288 - (NSString *) type;
1290 - (NSString *) base;
1293 - (NSString *) host;
1295 - (NSString *) name;
1296 - (NSString *) shortDescription;
1297 - (NSString *) label;
1298 - (NSString *) origin;
1299 - (NSString *) version;
1301 - (NSString *) defaultIcon;
1305 @implementation Source
1309 distribution_.clear();
1314 description_.clear();
1320 defaultIcon_.clear();
1327 + (NSArray *) _attributeKeys {
1328 return [NSArray arrayWithObjects:
1335 @"shortDescription",
1343 - (NSArray *) attributeKeys {
1344 return [[self class] _attributeKeys];
1347 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1348 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1351 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1354 trusted_ = index->IsTrusted();
1356 uri_.set(pool, index->GetURI());
1357 distribution_.set(pool, index->GetDist());
1358 type_.set(pool, index->GetType());
1360 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1361 if (dindex != NULL) {
1362 base_.set(pool, dindex->MetaIndexURI(""));
1365 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1368 pkgTagFile tags(&fd);
1370 pkgTagSection section;
1377 {"default-icon", &defaultIcon_},
1378 {"depiction", &depiction_},
1379 {"description", &description_},
1381 {"origin", &origin_},
1382 {"support", &support_},
1383 {"version", &version_},
1386 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1387 const char *start, *end;
1389 if (section.Find(names[i].name_, start, end)) {
1390 CYString &value(*names[i].value_);
1391 value.set(pool, start, end - start);
1397 record_ = [Sources_ objectForKey:[self key]];
1399 NSURL *url([NSURL URLWithString:uri_]);
1403 host_ = [host_ lowercaseString];
1408 authority_ = [url path];
1411 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1412 if ((self = [super init]) != nil) {
1413 [self setMetaIndex:index inPool:pool];
1417 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1418 NSDictionary *lhr = [self record];
1419 NSDictionary *rhr = [source record];
1422 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1424 NSString *lhs = [self name];
1425 NSString *rhs = [source name];
1427 if ([lhs length] != 0 && [rhs length] != 0) {
1428 unichar lhc = [lhs characterAtIndex:0];
1429 unichar rhc = [rhs characterAtIndex:0];
1431 if (isalpha(lhc) && !isalpha(rhc))
1432 return NSOrderedAscending;
1433 else if (!isalpha(lhc) && isalpha(rhc))
1434 return NSOrderedDescending;
1437 return [lhs compare:rhs options:LaxCompareOptions_];
1440 - (NSString *) depictionForPackage:(NSString *)package {
1441 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1444 - (NSString *) supportForPackage:(NSString *)package {
1445 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1448 - (NSDictionary *) record {
1456 - (NSString *) uri {
1460 - (NSString *) distribution {
1461 return distribution_;
1464 - (NSString *) type {
1468 - (NSString *) base {
1472 - (NSString *) key {
1473 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1476 - (NSString *) host {
1480 - (NSString *) name {
1481 return origin_.empty() ? (id) authority_ : origin_;
1484 - (NSString *) shortDescription {
1485 return description_;
1488 - (NSString *) label {
1489 return label_.empty() ? (id) authority_ : label_;
1492 - (NSString *) origin {
1496 - (NSString *) version {
1500 - (NSString *) defaultIcon {
1501 return defaultIcon_;
1506 /* CydiaOperation Class {{{ */
1507 @interface CydiaOperation : NSObject {
1508 _H<NSString> operator_;
1509 _H<NSString> value_;
1512 - (NSString *) operator;
1513 - (NSString *) value;
1517 @implementation CydiaOperation
1519 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1520 if ((self = [super init]) != nil) {
1521 operator_ = [NSString stringWithUTF8String:_operator];
1522 value_ = [NSString stringWithUTF8String:value];
1526 + (NSArray *) _attributeKeys {
1527 return [NSArray arrayWithObjects:
1533 - (NSArray *) attributeKeys {
1534 return [[self class] _attributeKeys];
1537 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1538 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1541 - (NSString *) operator {
1545 - (NSString *) value {
1551 /* CydiaClause Class {{{ */
1552 @interface CydiaClause : NSObject {
1553 _H<NSString> package_;
1554 _H<CydiaOperation> version_;
1557 - (NSString *) package;
1558 - (CydiaOperation *) version;
1562 @implementation CydiaClause
1564 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1565 if ((self = [super init]) != nil) {
1566 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1568 if (const char *version = dep.TargetVer())
1569 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1571 version_ = (id) [NSNull null];
1575 + (NSArray *) _attributeKeys {
1576 return [NSArray arrayWithObjects:
1582 - (NSArray *) attributeKeys {
1583 return [[self class] _attributeKeys];
1586 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1587 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1590 - (NSString *) package {
1594 - (CydiaOperation *) version {
1600 /* CydiaRelation Class {{{ */
1601 @interface CydiaRelation : NSObject {
1602 _H<NSString> relationship_;
1603 _H<NSMutableArray> clauses_;
1606 - (NSString *) relationship;
1607 - (NSArray *) clauses;
1611 @implementation CydiaRelation
1613 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1614 if ((self = [super init]) != nil) {
1615 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1616 clauses_ = [NSMutableArray arrayWithCapacity:8];
1618 pkgCache::DepIterator start;
1619 pkgCache::DepIterator end;
1620 dep.GlobOr(start, end); // ++dep
1623 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1625 // yes, seriously. (wtf?)
1633 + (NSArray *) _attributeKeys {
1634 return [NSArray arrayWithObjects:
1640 - (NSArray *) attributeKeys {
1641 return [[self class] _attributeKeys];
1644 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1645 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1648 - (NSString *) relationship {
1649 return relationship_;
1652 - (NSArray *) clauses {
1656 - (void) addClause:(CydiaClause *)clause {
1657 [clauses_ addObject:clause];
1662 /* Package Class {{{ */
1663 struct ParsedPackage {
1668 CYString depiction_;
1678 @interface Package : NSObject {
1681 uint32_t essential_ : 1;
1682 uint32_t obsolete_ : 1;
1683 uint32_t ignored_ : 1;
1687 _transient Database *database_;
1689 pkgCache::VerIterator version_;
1690 pkgCache::PkgIterator iterator_;
1691 pkgCache::VerFileIterator file_;
1697 CYString installed_;
1699 const char *section_;
1700 _transient NSString *section$_;
1704 PackageValue *metadata_;
1705 ParsedPackage *parsed_;
1707 _H<NSMutableArray> tags_;
1710 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1711 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1713 - (pkgCache::PkgIterator) iterator;
1716 - (NSString *) section;
1717 - (NSString *) simpleSection;
1719 - (NSString *) longSection;
1720 - (NSString *) shortSection;
1724 - (MIMEAddress *) maintainer;
1726 - (NSString *) longDescription;
1727 - (NSString *) shortDescription;
1730 - (PackageValue *) metadata;
1733 - (bool) subscribed;
1734 - (bool) setSubscribed:(bool)subscribed;
1738 - (NSString *) latest;
1739 - (NSString *) installed;
1740 - (BOOL) uninstalled;
1743 - (BOOL) upgradableAndEssential:(BOOL)essential;
1746 - (BOOL) unfiltered;
1750 - (BOOL) halfConfigured;
1751 - (BOOL) halfInstalled;
1753 - (NSString *) mode;
1756 - (NSString *) name;
1758 - (NSString *) homepage;
1759 - (NSString *) depiction;
1760 - (MIMEAddress *) author;
1762 - (NSString *) support;
1764 - (NSArray *) files;
1765 - (NSArray *) warnings;
1766 - (NSArray *) applications;
1768 - (Source *) source;
1770 - (BOOL) matches:(NSString *)text;
1772 - (bool) hasSupportingRole;
1773 - (BOOL) hasTag:(NSString *)tag;
1774 - (NSString *) primaryPurpose;
1775 - (NSArray *) purposes;
1776 - (bool) isCommercial;
1778 - (void) setIndex:(size_t)index;
1780 - (CYString &) cyname;
1782 - (uint32_t) compareBySection:(NSArray *)sections;
1787 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1788 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1789 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1790 - (bool) isVisibleInSection:(NSString *)section;
1791 - (bool) isVisibleInSource:(Source *)source;
1795 uint32_t PackageChangesRadix(Package *self, void *) {
1800 uint32_t timestamp : 30;
1801 uint32_t ignored : 1;
1802 uint32_t upgradable : 1;
1806 bool upgradable([self upgradableAndEssential:YES]);
1807 value.bits.upgradable = upgradable ? 1 : 0;
1810 value.bits.timestamp = 0;
1811 value.bits.ignored = [self ignored] ? 0 : 1;
1812 value.bits.upgradable = 1;
1814 value.bits.timestamp = [self seen] >> 2;
1815 value.bits.ignored = 0;
1816 value.bits.upgradable = 0;
1819 return _not(uint32_t) - value.key;
1822 uint32_t PackagePrefixRadix(Package *self, void *context) {
1823 size_t offset(reinterpret_cast<size_t>(context));
1824 CYString &name([self cyname]);
1826 size_t size(name.size());
1829 char *text(name.data());
1832 if (!isdigit(text[0]))
1836 while (size != digits && isdigit(text[digits]))
1844 if (offset == 0 && zeros != 0) {
1845 memset(data, '0', zeros);
1846 memcpy(data + zeros, text, 4 - zeros);
1848 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1849 if (size <= offset - zeros)
1852 text += offset - zeros;
1853 size -= offset - zeros;
1856 memcpy(data, text, 4);
1858 memcpy(data, text, size);
1859 memset(data + size, 0, 4 - size);
1862 for (size_t i(0); i != 4; ++i)
1863 if (isalpha(data[i]))
1871 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1873 /* XXX: ntohl may be more honest */
1874 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1877 CYString &(*PackageName)(Package *self, SEL sel);
1879 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1880 _profile(PackageNameCompare)
1881 CYString &lhi(PackageName(lhs, @selector(cyname)));
1882 CYString &rhi(PackageName(rhs, @selector(cyname)));
1883 CFStringRef lhn(lhi), rhn(rhi);
1886 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1887 else if (rhn == NULL)
1888 return NSOrderedDescending;
1890 _profile(PackageNameCompare$NumbersLast)
1891 if (!lhi.empty() && !rhi.empty()) {
1892 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1893 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1894 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1895 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1896 return lha ? NSOrderedAscending : NSOrderedDescending;
1900 CFIndex length = CFStringGetLength(lhn);
1902 _profile(PackageNameCompare$Compare)
1903 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1908 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1909 return PackageNameCompare(*lhs, *rhs, context);
1912 struct PackageNameOrdering :
1913 std::binary_function<Package *, Package *, bool>
1915 _finline bool operator ()(Package *lhs, Package *rhs) const {
1916 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1920 @implementation Package
1922 - (NSString *) description {
1923 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1927 if (parsed_ != NULL)
1932 + (NSString *) webScriptNameForSelector:(SEL)selector {
1934 else if (selector == @selector(clear))
1936 else if (selector == @selector(getField:))
1938 else if (selector == @selector(hasTag:))
1940 else if (selector == @selector(install))
1942 else if (selector == @selector(remove))
1948 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1949 return [self webScriptNameForSelector:selector] == nil;
1952 + (NSArray *) _attributeKeys {
1953 return [NSArray arrayWithObjects:
1972 @"shortDescription",
1985 - (NSArray *) attributeKeys {
1986 return [[self class] _attributeKeys];
1989 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1990 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1993 - (NSArray *) relations {
1994 @synchronized (database_) {
1995 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
1996 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
1997 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2001 - (NSString *) getField:(NSString *)name {
2002 @synchronized (database_) {
2003 if ([database_ era] != era_ || file_.end())
2006 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2008 const char *start, *end;
2009 if (!parser.Find([name UTF8String], start, end))
2010 return (NSString *) [NSNull null];
2012 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2016 if (parsed_ != NULL)
2018 @synchronized (database_) {
2019 if ([database_ era] != era_ || file_.end())
2022 ParsedPackage *parsed(new ParsedPackage);
2025 _profile(Package$parse)
2026 pkgRecords::Parser *parser;
2028 _profile(Package$parse$Lookup)
2029 parser = &[database_ records]->Lookup(file_);
2034 _profile(Package$parse$Find)
2039 {"icon", &parsed->icon_},
2040 {"depiction", &parsed->depiction_},
2041 {"homepage", &parsed->homepage_},
2042 {"website", &website},
2043 {"bugs", &parsed->bugs_},
2044 {"support", &parsed->support_},
2045 {"sponsor", &parsed->sponsor_},
2046 {"author", &parsed->author_},
2049 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2050 const char *start, *end;
2052 if (parser->Find(names[i].name_, start, end)) {
2053 CYString &value(*names[i].value_);
2054 _profile(Package$parse$Value)
2055 value.set(pool_, start, end - start);
2061 _profile(Package$parse$Tagline)
2062 const char *start, *end;
2063 if (parser->ShortDesc(start, end)) {
2064 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2067 while (stop != start && stop[-1] == '\r')
2069 parsed->tagline_.set(pool_, start, stop - start);
2073 _profile(Package$parse$Retain)
2074 if (parsed->homepage_.empty())
2075 parsed->homepage_ = website;
2076 if (parsed->homepage_ == parsed->depiction_)
2077 parsed->homepage_.clear();
2082 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2083 if ((self = [super init]) != nil) {
2084 _profile(Package$initWithVersion)
2087 database_ = database;
2088 era_ = [database era];
2092 pkgCache::PkgIterator iterator(version.ParentPkg());
2093 iterator_ = iterator;
2095 _profile(Package$initWithVersion$Version)
2096 if (!version_.end())
2097 file_ = version_.FileList();
2099 pkgCache &cache([database_ cache]);
2100 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2104 _profile(Package$initWithVersion$Cache)
2105 name_.set(NULL, iterator.Display());
2107 latest_.set(NULL, StripVersion_(version_.VerStr()));
2109 pkgCache::VerIterator current(iterator.CurrentVer());
2111 installed_.set(NULL, StripVersion_(current.VerStr()));
2114 _profile(Package$initWithVersion$Tags)
2115 pkgCache::TagIterator tag(iterator.TagList());
2117 tags_ = [NSMutableArray arrayWithCapacity:8];
2119 const char *name(tag.Name());
2120 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2122 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2123 if (strcmp(name + 6, "enduser") == 0)
2125 else if (strcmp(name + 6, "hacker") == 0)
2127 else if (strcmp(name + 6, "developer") == 0)
2129 else if (strcmp(name + 6, "cydia") == 0)
2135 if (strncmp(name, "cydia::", 7) == 0) {
2136 if (strcmp(name + 7, "essential") == 0)
2138 else if (strcmp(name + 7, "obsolete") == 0)
2143 } while (!tag.end());
2147 _profile(Package$initWithVersion$Metadata)
2148 const char *mixed(iterator.Name());
2149 size_t size(strlen(mixed));
2150 char lower[size + 1];
2152 for (size_t i(0); i != size; ++i)
2153 lower[i] = mixed[i] | 0x20;
2156 PackageValue *metadata(PackageFind(lower, size));
2157 metadata_ = metadata;
2159 id_.set(NULL, metadata->name_, size);
2161 const char *latest(version_.VerStr());
2162 size_t length(strlen(latest));
2164 uint16_t vhash(hashlittle(latest, length));
2166 size_t capped(std::min<size_t>(8, length));
2167 latest = latest + length - capped;
2169 if (metadata->first_ == 0)
2170 metadata->first_ = now_;
2172 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2173 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2174 metadata->vhash_ = vhash;
2175 metadata->last_ = now_;
2176 } else if (metadata->last_ == 0)
2177 metadata->last_ = metadata->first_;
2180 _profile(Package$initWithVersion$Section)
2181 section_ = iterator.Section();
2184 _profile(Package$initWithVersion$Flags)
2185 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2186 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2191 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2192 pkgCache::VerIterator version;
2194 _profile(Package$packageWithIterator$GetCandidateVer)
2195 version = [database policy]->GetCandidateVer(iterator);
2203 _profile(Package$packageWithIterator$Allocate)
2204 package = [Package allocWithZone:zone];
2207 _profile(Package$packageWithIterator$Initialize)
2209 initWithVersion:version
2216 _profile(Package$packageWithIterator$Autorelease)
2217 package = [package autorelease];
2223 - (pkgCache::PkgIterator) iterator {
2227 - (NSString *) section {
2228 if (section$_ == nil) {
2229 if (section_ == NULL)
2232 _profile(Package$section$mappedSectionForPointer)
2233 section$_ = [database_ mappedSectionForPointer:section_];
2238 - (NSString *) simpleSection {
2239 if (NSString *section = [self section])
2240 return Simplify(section);
2245 - (NSString *) longSection {
2246 return LocalizeSection([self section]);
2249 - (NSString *) shortSection {
2250 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2253 - (NSString *) uri {
2256 pkgIndexFile *index;
2257 pkgCache::PkgFileIterator file(file_.File());
2258 if (![database_ list].FindIndex(file, index))
2260 return [NSString stringWithUTF8String:iterator_->Path];
2261 //return [NSString stringWithUTF8String:file.Site()];
2262 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2266 - (MIMEAddress *) maintainer {
2267 @synchronized (database_) {
2268 if ([database_ era] != era_ || file_.end())
2271 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2272 const std::string &maintainer(parser->Maintainer());
2273 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2277 @synchronized (database_) {
2278 if ([database_ era] != era_ || version_.end())
2281 return version_->InstalledSize;
2284 - (NSString *) longDescription {
2285 @synchronized (database_) {
2286 if ([database_ era] != era_ || file_.end())
2289 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2290 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2292 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2293 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2294 if ([lines count] < 2)
2297 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2298 for (size_t i(1), e([lines count]); i != e; ++i) {
2299 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2300 [trimmed addObject:trim];
2303 return [trimmed componentsJoinedByString:@"\n"];
2306 - (NSString *) shortDescription {
2307 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2311 _profile(Package$index)
2312 CFStringRef name((CFStringRef) [self name]);
2313 if (CFStringGetLength(name) == 0)
2315 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2316 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2318 return toupper(character);
2322 - (PackageValue *) metadata {
2327 PackageValue *metadata([self metadata]);
2328 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2331 - (bool) subscribed {
2332 return [self metadata]->subscribed_;
2335 - (bool) setSubscribed:(bool)subscribed {
2336 PackageValue *metadata([self metadata]);
2337 if (metadata->subscribed_ == subscribed)
2339 metadata->subscribed_ = subscribed;
2347 - (NSString *) latest {
2351 - (NSString *) installed {
2355 - (BOOL) uninstalled {
2356 return installed_.empty();
2360 return !version_.end();
2363 - (BOOL) upgradableAndEssential:(BOOL)essential {
2364 _profile(Package$upgradableAndEssential)
2365 pkgCache::VerIterator current(iterator_.CurrentVer());
2367 return essential && essential_;
2369 return !version_.end() && version_ != current;
2373 - (BOOL) essential {
2378 return [database_ cache][iterator_].InstBroken();
2381 - (BOOL) unfiltered {
2382 _profile(Package$unfiltered$obsolete)
2383 if (_unlikely(obsolete_))
2387 _profile(Package$unfiltered$hasSupportingRole)
2388 if (_unlikely(![self hasSupportingRole]))
2396 if (![self unfiltered])
2401 _profile(Package$visible$section)
2402 section = [self section];
2405 _profile(Package$visible$isSectionVisible)
2406 if (!isSectionVisible(section))
2414 unsigned char current(iterator_->CurrentState);
2415 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2418 - (BOOL) halfConfigured {
2419 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2422 - (BOOL) halfInstalled {
2423 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2427 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2428 return state.Mode != pkgDepCache::ModeKeep;
2431 - (NSString *) mode {
2432 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2434 switch (state.Mode) {
2435 case pkgDepCache::ModeDelete:
2436 if ((state.iFlags & pkgDepCache::Purge) != 0)
2440 case pkgDepCache::ModeKeep:
2441 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2442 return @"REINSTALL";
2443 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2447 case pkgDepCache::ModeInstall:
2448 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2449 return @"REINSTALL";
2450 else*/ switch (state.Status) {
2452 return @"DOWNGRADE";
2458 return @"NEW_INSTALL";
2469 - (NSString *) name {
2470 return name_.empty() ? id_ : name_;
2473 - (UIImage *) icon {
2474 NSString *section = [self simpleSection];
2477 if (parsed_ != NULL)
2478 if (NSString *href = parsed_->icon_)
2479 if ([href hasPrefix:@"file:///"])
2480 // XXX: correct escaping
2481 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2482 if (icon == nil) if (section != nil)
2483 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2484 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2485 if ([dicon hasPrefix:@"file:///"])
2486 // XXX: correct escaping
2487 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2489 icon = [UIImage applicationImageNamed:@"unknown.png"];
2493 - (NSString *) homepage {
2494 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2497 - (NSString *) depiction {
2498 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2501 - (MIMEAddress *) sponsor {
2502 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2505 - (MIMEAddress *) author {
2506 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2509 - (NSString *) support {
2510 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2513 - (NSArray *) files {
2514 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2515 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2518 fin.open([path UTF8String]);
2523 while (std::getline(fin, line))
2524 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2529 - (NSString *) state {
2530 @synchronized (database_) {
2531 if ([database_ era] != era_ || file_.end())
2534 switch (iterator_->CurrentState) {
2535 case pkgCache::State::NotInstalled:
2536 return @"NotInstalled";
2537 case pkgCache::State::UnPacked:
2539 case pkgCache::State::HalfConfigured:
2540 return @"HalfConfigured";
2541 case pkgCache::State::HalfInstalled:
2542 return @"HalfInstalled";
2543 case pkgCache::State::ConfigFiles:
2544 return @"ConfigFiles";
2545 case pkgCache::State::Installed:
2546 return @"Installed";
2547 case pkgCache::State::TriggersAwaited:
2548 return @"TriggersAwaited";
2549 case pkgCache::State::TriggersPending:
2550 return @"TriggersPending";
2553 return (NSString *) [NSNull null];
2556 - (NSString *) selection {
2557 @synchronized (database_) {
2558 if ([database_ era] != era_ || file_.end())
2561 switch (iterator_->SelectedState) {
2562 case pkgCache::State::Unknown:
2564 case pkgCache::State::Install:
2566 case pkgCache::State::Hold:
2568 case pkgCache::State::DeInstall:
2569 return @"DeInstall";
2570 case pkgCache::State::Purge:
2574 return (NSString *) [NSNull null];
2577 - (NSArray *) warnings {
2578 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2579 const char *name(iterator_.Name());
2581 size_t length(strlen(name));
2582 if (length < 2) invalid:
2583 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2584 else for (size_t i(0); i != length; ++i)
2586 /* XXX: technically this is not allowed */
2587 (name[i] < 'A' || name[i] > 'Z') &&
2588 (name[i] < 'a' || name[i] > 'z') &&
2589 (name[i] < '0' || name[i] > '9') &&
2590 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2593 if (strcmp(name, "cydia") != 0) {
2596 bool _private = false;
2599 bool repository = [[self section] isEqualToString:@"Repositories"];
2601 if (NSArray *files = [self files])
2602 for (NSString *file in files)
2603 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2605 else if (!user && [file isEqualToString:@"/User"])
2607 else if (!_private && [file isEqualToString:@"/private"])
2609 else if (!stash && [file isEqualToString:@"/var/stash"])
2612 /* XXX: this is not sensitive enough. only some folders are valid. */
2613 if (cydia && !repository)
2614 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2616 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2618 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2620 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2623 return [warnings count] == 0 ? nil : warnings;
2626 - (NSArray *) applications {
2627 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2629 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2631 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2632 if (NSArray *files = [self files])
2633 for (NSString *file in files)
2634 if (application_r(file)) {
2635 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2636 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2637 if ([id isEqualToString:me])
2640 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2642 display = application_r[1];
2644 NSString *bundle([file stringByDeletingLastPathComponent]);
2645 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2646 if (icon == nil || [icon length] == 0)
2648 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2650 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2651 [applications addObject:application];
2653 [application addObject:id];
2654 [application addObject:display];
2655 [application addObject:url];
2658 return [applications count] == 0 ? nil : applications;
2661 - (Source *) source {
2662 if (source_ == nil) {
2663 @synchronized (database_) {
2664 if ([database_ era] != era_ || file_.end())
2665 source_ = (Source *) [NSNull null];
2667 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2671 return source_ == (Source *) [NSNull null] ? nil : source_;
2674 - (BOOL) matches:(NSString *)text {
2680 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2681 if (range.location != NSNotFound)
2684 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2685 if (range.location != NSNotFound)
2690 NSString *description([self shortDescription]);
2691 NSUInteger length([description length]);
2693 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2694 if (range.location != NSNotFound)
2700 - (bool) hasSupportingRole {
2705 if ([Role_ isEqualToString:@"User"])
2709 if ([Role_ isEqualToString:@"Hacker"])
2713 if ([Role_ isEqualToString:@"Developer"])
2718 - (NSArray *) tags {
2722 - (BOOL) hasTag:(NSString *)tag {
2723 return tags_ == nil ? NO : [tags_ containsObject:tag];
2726 - (NSString *) primaryPurpose {
2727 for (NSString *tag in (NSArray *) tags_)
2728 if ([tag hasPrefix:@"purpose::"])
2729 return [tag substringFromIndex:9];
2733 - (NSArray *) purposes {
2734 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2735 for (NSString *tag in (NSArray *) tags_)
2736 if ([tag hasPrefix:@"purpose::"])
2737 [purposes addObject:[tag substringFromIndex:9]];
2738 return [purposes count] == 0 ? nil : purposes;
2741 - (bool) isCommercial {
2742 return [self hasTag:@"cydia::commercial"];
2745 - (void) setIndex:(size_t)index {
2746 if (metadata_->index_ != index)
2747 metadata_->index_ = index;
2750 - (CYString &) cyname {
2751 return name_.empty() ? id_ : name_;
2754 - (uint32_t) compareBySection:(NSArray *)sections {
2755 NSString *section([self section]);
2756 for (size_t i(0), e([sections count]); i != e; ++i) {
2757 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2761 return _not(uint32_t);
2765 @synchronized (database_) {
2766 pkgProblemResolver *resolver = [database_ resolver];
2767 resolver->Clear(iterator_);
2769 pkgCacheFile &cache([database_ cache]);
2770 cache->SetReInstall(iterator_, false);
2771 cache->MarkKeep(iterator_, false);
2775 @synchronized (database_) {
2776 pkgProblemResolver *resolver = [database_ resolver];
2777 resolver->Clear(iterator_);
2778 resolver->Protect(iterator_);
2780 pkgCacheFile &cache([database_ cache]);
2781 cache->SetReInstall(iterator_, false);
2782 cache->MarkInstall(iterator_, false);
2784 pkgDepCache::StateCache &state((*cache)[iterator_]);
2785 if (!state.Install())
2786 cache->SetReInstall(iterator_, true);
2790 @synchronized (database_) {
2791 pkgProblemResolver *resolver = [database_ resolver];
2792 resolver->Clear(iterator_);
2793 resolver->Remove(iterator_);
2794 resolver->Protect(iterator_);
2796 pkgCacheFile &cache([database_ cache]);
2797 cache->SetReInstall(iterator_, false);
2798 cache->MarkDelete(iterator_, true);
2801 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2802 _profile(Package$isUnfilteredAndSearchedForBy)
2805 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2806 value &= [self unfiltered];
2809 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2810 value &= [self matches:search];
2817 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2818 if ([search length] == 0)
2821 _profile(Package$isUnfilteredAndSelectedForBy)
2824 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2825 value &= [self unfiltered];
2828 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2829 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2836 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2837 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2840 - (bool) isVisibleInSection:(NSString *)name {
2841 NSString *section([self section]);
2845 section == nil && [name length] == 0 ||
2846 [name isEqualToString:section]
2847 ) && [self visible];
2850 - (bool) isVisibleInSource:(Source *)source {
2851 return [self source] == source && [self visible];
2856 /* Section Class {{{ */
2857 @interface Section : NSObject {
2862 _H<NSString> localized_;
2865 - (NSComparisonResult) compareByLocalized:(Section *)section;
2866 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2867 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2868 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2869 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2870 - (NSString *) name;
2877 - (void) addToCount;
2879 - (void) setCount:(size_t)count;
2880 - (NSString *) localized;
2884 @implementation Section
2886 - (NSComparisonResult) compareByLocalized:(Section *)section {
2887 NSString *lhs(localized_);
2888 NSString *rhs([section localized]);
2890 /*if ([lhs length] != 0 && [rhs length] != 0) {
2891 unichar lhc = [lhs characterAtIndex:0];
2892 unichar rhc = [rhs characterAtIndex:0];
2894 if (isalpha(lhc) && !isalpha(rhc))
2895 return NSOrderedAscending;
2896 else if (!isalpha(lhc) && isalpha(rhc))
2897 return NSOrderedDescending;
2900 return [lhs compare:rhs options:LaxCompareOptions_];
2903 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2904 if ((self = [self initWithName:name localize:NO]) != nil) {
2905 if (localized != nil)
2906 localized_ = localized;
2910 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2911 return [self initWithName:name row:0 localize:localize];
2914 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2915 if ((self = [super init]) != nil) {
2920 localized_ = LocalizeSection(name_);
2924 /* XXX: localize the index thingees */
2925 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2926 if ((self = [super init]) != nil) {
2927 name_ = [NSString stringWithCharacters:&index length:1];
2933 - (NSString *) name {
2953 - (void) addToCount {
2957 - (void) setCount:(size_t)count {
2961 - (NSString *) localized {
2968 static NSString *Colon_;
2969 static NSString *Elision_;
2970 static NSString *Error_;
2971 static NSString *Warning_;
2973 class CydiaLogCleaner :
2974 public pkgArchiveCleaner
2977 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
2982 /* Database Implementation {{{ */
2983 @implementation Database
2985 + (Database *) sharedInstance {
2986 static _H<Database> instance;
2987 if (instance == nil)
2988 instance = [[[Database alloc] init] autorelease];
2996 - (void) releasePackages {
2997 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
2998 CFArrayRemoveAllValues(packages_);
3002 // XXX: actually implement this thing
3004 [self releasePackages];
3005 apr_pool_destroy(pool_);
3006 NSRecycleZone(zone_);
3010 - (void) _readCydia:(NSNumber *)fd {
3011 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3012 std::istream is(&ib);
3015 static Pcre finish_r("^finish:([^:]*)$");
3017 while (std::getline(is, line)) {
3018 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3020 const char *data(line.c_str());
3021 size_t size = line.size();
3022 lprintf("C:%s\n", data);
3024 if (finish_r(data, size)) {
3025 NSString *finish = finish_r[1];
3026 int index = [Finishes_ indexOfObject:finish];
3027 if (index != INT_MAX && index > Finish_)
3037 - (void) _readStatus:(NSNumber *)fd {
3038 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3039 std::istream is(&ib);
3042 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3043 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3045 while (std::getline(is, line)) {
3046 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3048 const char *data(line.c_str());
3049 size_t size(line.size());
3050 lprintf("S:%s\n", data);
3052 if (conffile_r(data, size)) {
3053 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3054 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3055 } else if (strncmp(data, "status: ", 8) == 0) {
3056 // status: <package>: {unpacked,half-configured,installed}
3057 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3058 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3059 } else if (strncmp(data, "processing: ", 12) == 0) {
3060 // processing: configure: config-test
3061 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3062 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3063 } else if (pmstatus_r(data, size)) {
3064 std::string type([pmstatus_r[1] UTF8String]);
3066 NSString *package = pmstatus_r[2];
3067 if ([package isEqualToString:@"dpkg-exec"])
3070 float percent([pmstatus_r[3] floatValue]);
3071 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3073 NSString *string = pmstatus_r[4];
3075 if (type == "pmerror") {
3076 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3077 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3078 } else if (type == "pmstatus") {
3079 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3080 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3081 } else if (type == "pmconffile")
3082 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3084 lprintf("E:unknown pmstatus\n");
3086 lprintf("E:unknown status\n");
3094 - (void) _readOutput:(NSNumber *)fd {
3095 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3096 std::istream is(&ib);
3099 while (std::getline(is, line)) {
3100 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3102 lprintf("O:%s\n", line.c_str());
3104 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3105 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3117 - (Package *) packageWithName:(NSString *)name {
3118 @synchronized (self) {
3119 if (static_cast<pkgDepCache *>(cache_) == NULL)
3121 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3122 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3126 if ((self = [super init]) != nil) {
3133 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3134 apr_pool_create(&pool_, NULL);
3136 size_t capacity(MetaFile_->active_);
3142 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3143 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3147 _assert(pipe(fds) != -1);
3150 _config->Set("APT::Keep-Fds::", cydiafd_);
3151 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3154 detachNewThreadSelector:@selector(_readCydia:)
3156 withObject:[NSNumber numberWithInt:fds[0]]
3159 _assert(pipe(fds) != -1);
3163 detachNewThreadSelector:@selector(_readStatus:)
3165 withObject:[NSNumber numberWithInt:fds[0]]
3168 _assert(pipe(fds) != -1);
3169 _assert(dup2(fds[0], 0) != -1);
3170 _assert(close(fds[0]) != -1);
3172 input_ = fdopen(fds[1], "a");
3174 _assert(pipe(fds) != -1);
3175 _assert(dup2(fds[1], 1) != -1);
3176 _assert(close(fds[1]) != -1);
3179 detachNewThreadSelector:@selector(_readOutput:)
3181 withObject:[NSNumber numberWithInt:fds[0]]
3186 - (pkgCacheFile &) cache {
3190 - (pkgDepCache::Policy *) policy {
3194 - (pkgRecords *) records {
3198 - (pkgProblemResolver *) resolver {
3202 - (pkgAcquire &) fetcher {
3206 - (pkgSourceList &) list {
3210 - (NSArray *) packages {
3211 return (NSArray *) packages_;
3214 - (NSArray *) sources {
3218 - (Source *) sourceWithKey:(NSString *)key {
3219 for (Source *source in [self sources]) {
3220 if ([[source key] isEqualToString:key])
3225 - (bool) popErrorWithTitle:(NSString *)title {
3228 while (!_error->empty()) {
3230 bool warning(!_error->PopMessage(error));
3235 size_t size(error.size());
3236 if (size == 0 || error[size - 1] != '\n')
3238 error.resize(size - 1);
3241 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3243 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3249 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3250 return [self popErrorWithTitle:title] || !success;
3253 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3254 @synchronized (self) {
3257 [self releasePackages];
3260 [sourceList_ removeAllObjects];
3280 apr_pool_clear(pool_);
3282 NSRecycleZone(zone_);
3283 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3285 int chk(creat("/tmp/cydia.chk", 0644));
3289 if (invocation != nil)
3290 [invocation invoke];
3292 NSString *title(UCLocalize("DATABASE"));
3295 OpProgress progress;
3296 while (!cache_.Open(progress, true)) { pop:
3298 bool warning(!_error->PopMessage(error));
3299 lprintf("cache_.Open():[%s]\n", error.c_str());
3301 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3302 [delegate_ repairWithSelector:@selector(configure)];
3303 else if (error == "The package lists or status file could not be parsed or opened.")
3304 [delegate_ repairWithSelector:@selector(update)];
3305 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3306 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3307 // else if (error == "Malformed Status line")
3308 // else if (error == "The list of sources could not be read.")
3310 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3320 unlink("/tmp/cydia.chk");
3322 now_ = [[NSDate date] timeIntervalSince1970];
3324 policy_ = new pkgDepCache::Policy();
3325 records_ = new pkgRecords(cache_);
3326 resolver_ = new pkgProblemResolver(cache_);
3327 fetcher_ = new pkgAcquire(&status_);
3330 list_ = new pkgSourceList();
3331 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3334 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3335 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3339 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3342 if (cache_->BrokenCount() != 0) {
3343 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3346 if (cache_->BrokenCount() != 0) {
3347 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3351 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3355 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3356 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3357 [sourceList_ addObject:object];
3359 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3360 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3361 // XXX: this could be more intelligent
3362 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3363 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3365 sourceMap_[cached->ID] = object;
3370 /*std::vector<Package *> packages;
3371 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3376 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3377 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3378 //packages.push_back(package);
3379 CFArrayAppendValue(packages_, CFRetain(package));
3383 /*if (packages.empty())
3384 packages_ = [[NSArray alloc] init];
3386 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3389 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3390 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3391 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3399 /*if (!packages.empty())
3400 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3401 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3403 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3405 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3407 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3411 size_t count(CFArrayGetCount(packages_));
3412 MetaFile_->active_ = count;
3414 for (size_t index(0); index != count; ++index)
3415 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3422 @synchronized (self) {
3424 resolver_ = new pkgProblemResolver(cache_);
3426 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3427 if (!cache_[iterator].Keep())
3428 cache_->MarkKeep(iterator, false);
3429 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3430 cache_->SetReInstall(iterator, false);
3433 - (void) configure {
3434 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3436 system([dpkg UTF8String]);
3441 // XXX: I don't remember this condition
3446 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3448 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3450 if ([self popErrorWithTitle:title])
3454 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3456 CydiaLogCleaner cleaner;
3457 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3464 fetcher_->Shutdown();
3466 pkgRecords records(cache_);
3468 lock_ = new FileFd();
3469 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3471 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3473 if ([self popErrorWithTitle:title])
3477 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3480 manager_ = (_system->CreatePM(cache_));
3481 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3488 bool substrate(RestartSubstrate_);
3489 RestartSubstrate_ = false;
3491 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3493 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3495 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3497 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3498 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3501 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3503 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3505 [self popErrorWithTitle:title];
3509 bool failed = false;
3510 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3511 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3513 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3519 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3527 RestartSubstrate_ = true;
3530 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3532 if (_error->PendingError()) {
3537 if (result == pkgPackageManager::Failed) {
3542 if (result != pkgPackageManager::Completed) {
3547 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3549 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3551 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3552 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3555 if (![before isEqualToArray:after])
3560 NSString *title(UCLocalize("UPGRADE"));
3561 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3567 [self updateWithStatus:status_];
3570 - (void) updateWithStatus:(Status &)status {
3571 NSString *title(UCLocalize("REFRESHING_DATA"));
3574 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3578 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3579 if ([self popErrorWithTitle:title])
3582 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3584 bool success(ListUpdate(status, list, PulseInterval_));
3585 if (status.WasCancelled())
3588 [self popErrorWithTitle:title forOperation:success];
3589 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3593 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3596 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3597 delegate_ = delegate;
3600 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3601 progress_ = delegate;
3602 status_.setDelegate(delegate);
3605 - (NSObject<ProgressDelegate> *) progressDelegate {
3609 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3610 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3611 return i == sourceMap_.end() ? nil : i->second;
3614 - (NSString *) mappedSectionForPointer:(const char *)section {
3615 _H<NSString> *mapped;
3617 _profile(Database$mappedSectionForPointer$Cache)
3618 mapped = §ions_[section];
3621 if (*mapped == NULL) {
3622 size_t length(strlen(section));
3623 char spaced[length + 1];
3625 _profile(Database$mappedSectionForPointer$Replace)
3626 for (size_t index(0); index != length; ++index)
3627 spaced[index] = section[index] == '_' ? ' ' : section[index];
3628 spaced[length] = '\0';
3633 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3634 string = [NSString stringWithUTF8String:spaced];
3637 _profile(Database$mappedSectionForPointer$Map)
3638 string = [SectionMap_ objectForKey:string] ?: string;
3648 static _H<NSMutableSet> Diversions_;
3650 @interface Diversion : NSObject {
3653 _H<NSString> format_;
3658 @implementation Diversion
3660 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3661 if ((self = [super init]) != nil) {
3662 pattern_ = [from UTF8String];
3668 - (NSString *) divert:(NSString *)url {
3669 return !pattern_(url) ? nil : pattern_->*format_;
3672 + (NSURL *) divertURL:(NSURL *)url {
3674 NSString *href([url absoluteString]);
3676 for (Diversion *diversion in (id) Diversions_)
3677 if (NSString *diverted = [diversion divert:href]) {
3679 NSLog(@"div: %@", diverted);
3681 url = [NSURL URLWithString:diverted];
3688 - (NSString *) key {
3692 - (NSUInteger) hash {
3696 - (BOOL) isEqual:(Diversion *)object {
3697 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3702 @interface CydiaObject : NSObject {
3703 _H<IndirectDelegate> indirect_;
3704 _transient id delegate_;
3707 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3711 @interface CydiaWebViewController : CyteWebViewController {
3712 _H<CydiaObject> cydia_;
3715 + (void) addDiversion:(Diversion *)diversion;
3719 /* Web Scripting {{{ */
3720 @implementation CydiaObject
3722 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3723 if ((self = [super init]) != nil) {
3724 indirect_ = indirect;
3728 - (void) setDelegate:(id)delegate {
3729 delegate_ = delegate;
3732 + (NSArray *) _attributeKeys {
3733 return [NSArray arrayWithObjects:
3749 - (NSArray *) attributeKeys {
3750 return [[self class] _attributeKeys];
3753 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3754 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3757 - (NSString *) version {
3761 - (NSString *) device {
3762 return [[UIDevice currentDevice] uniqueIdentifier];
3765 - (NSString *) firmware {
3766 return [[UIDevice currentDevice] systemVersion];
3769 - (NSString *) hostname {
3770 return [[UIDevice currentDevice] name];
3773 - (NSString *) idiom {
3774 return (id) Idiom_ ?: [NSNull null];
3777 - (NSString *) plmn {
3778 return (id) PLMN_ ?: [NSNull null];
3781 - (NSString *) bbsnum {
3782 return (id) BBSNum_ ?: [NSNull null];
3785 - (NSString *) ecid {
3786 return (id) ChipID_ ?: [NSNull null];
3789 - (NSString *) serial {
3790 return SerialNumber_;
3793 - (NSString *) role {
3794 return (id) Role_ ?: [NSNull null];
3797 - (NSString *) model {
3798 return [NSString stringWithUTF8String:Machine_];
3801 - (NSString *) token {
3802 return (id) Token_ ?: [NSNull null];
3805 + (NSString *) webScriptNameForSelector:(SEL)selector {
3807 else if (selector == @selector(addBridgedHost:))
3808 return @"addBridgedHost";
3809 else if (selector == @selector(addInternalRedirect::))
3810 return @"addInternalRedirect";
3811 else if (selector == @selector(addPipelinedHost:scheme:))
3812 return @"addPipelinedHost";
3813 else if (selector == @selector(addTrivialSource:))
3814 return @"addTrivialSource";
3815 else if (selector == @selector(close))
3817 else if (selector == @selector(du:))
3819 else if (selector == @selector(stringWithFormat:arguments:))
3821 else if (selector == @selector(getAllSources))
3822 return @"getAllSourcs";
3823 else if (selector == @selector(getKernelNumber:))
3824 return @"getKernelNumber";
3825 else if (selector == @selector(getKernelString:))
3826 return @"getKernelString";
3827 else if (selector == @selector(getInstalledPackages))
3828 return @"getInstalledPackages";
3829 else if (selector == @selector(getIORegistryEntry::))
3830 return @"getIORegistryEntry";
3831 else if (selector == @selector(getLocaleIdentifier))
3832 return @"getLocaleIdentifier";
3833 else if (selector == @selector(getPreferredLanguages))
3834 return @"getPreferredLanguages";
3835 else if (selector == @selector(getPackageById:))
3836 return @"getPackageById";
3837 else if (selector == @selector(getSessionValue:))
3838 return @"getSessionValue";
3839 else if (selector == @selector(installPackages:))
3840 return @"installPackages";
3841 else if (selector == @selector(localizedStringForKey:value:table:))
3843 else if (selector == @selector(popViewController:))
3844 return @"popViewController";
3845 else if (selector == @selector(refreshSources))
3846 return @"refreshSources";
3847 else if (selector == @selector(removeButton))
3848 return @"removeButton";
3849 else if (selector == @selector(setSessionValue::))
3850 return @"setSessionValue";
3851 else if (selector == @selector(substitutePackageNames:))
3852 return @"substitutePackageNames";
3853 else if (selector == @selector(scrollToBottom:))
3854 return @"scrollToBottom";
3855 else if (selector == @selector(setAllowsNavigationAction:))
3856 return @"setAllowsNavigationAction";
3857 else if (selector == @selector(setBadgeValue:))
3858 return @"setBadgeValue";
3859 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3860 return @"setButtonImage";
3861 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3862 return @"setButtonTitle";
3863 else if (selector == @selector(setHidesBackButton:))
3864 return @"setHidesBackButton";
3865 else if (selector == @selector(setHidesNavigationBar:))
3866 return @"setHidesNavigationBar";
3867 else if (selector == @selector(setNavigationBarStyle:))
3868 return @"setNavigationBarStyle";
3869 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3870 return @"setNavigationBarTintColor";
3871 else if (selector == @selector(setPasteboardString:))
3872 return @"setPasteboardString";
3873 else if (selector == @selector(setPasteboardURL:))
3874 return @"setPasteboardURL";
3875 else if (selector == @selector(setToken:))
3877 else if (selector == @selector(setViewportWidth:))
3878 return @"setViewportWidth";
3879 else if (selector == @selector(statfs:))
3881 else if (selector == @selector(supports:))
3887 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3888 return [self webScriptNameForSelector:selector] == nil;
3891 - (BOOL) supports:(NSString *)feature {
3892 return [feature isEqualToString:@"window.open"];
3895 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3896 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3899 - (NSNumber *) getKernelNumber:(NSString *)name {
3900 const char *string([name UTF8String]);
3903 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3904 return (id) [NSNull null];
3906 if (size != sizeof(int))
3907 return (id) [NSNull null];
3910 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3911 return (id) [NSNull null];
3913 return [NSNumber numberWithInt:value];
3916 - (NSString *) getKernelString:(NSString *)name {
3917 const char *string([name UTF8String]);
3920 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3921 return (id) [NSNull null];
3923 char value[size + 1];
3924 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3925 return (id) [NSNull null];
3927 // XXX: just in case you request something ludicrous
3930 return [NSString stringWithCString:value];
3933 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3934 NSObject *value(CYIOGetValue([path UTF8String], entry));
3937 if ([value isKindOfClass:[NSData class]])
3938 value = CYHex((NSData *) value);
3943 - (id) getSessionValue:(NSString *)key {
3944 @synchronized (SessionData_) {
3945 return [SessionData_ objectForKey:key];
3948 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3949 @synchronized (SessionData_) {
3950 if (value == (id) [WebUndefined undefined])
3951 [SessionData_ removeObjectForKey:key];
3953 [SessionData_ setObject:value forKey:key];
3956 - (void) addBridgedHost:(NSString *)host {
3957 @synchronized (HostConfig_) {
3958 [BridgedHosts_ addObject:host];
3961 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
3962 @synchronized (HostConfig_) {
3963 if (scheme != (id) [WebUndefined undefined])
3964 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
3966 [PipelinedHosts_ addObject:host];
3969 - (void) popViewController:(NSNumber *)value {
3970 if (value == (id) [WebUndefined undefined])
3971 value = [NSNumber numberWithBool:YES];
3972 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
3975 - (void) addTrivialSource:(NSString *)href {
3976 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
3979 - (void) refreshSources {
3980 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
3983 - (NSArray *) getAllSources {
3984 return [[Database sharedInstance] sources];
3987 - (NSArray *) getInstalledPackages {
3988 Database *database([Database sharedInstance]);
3989 @synchronized (database) {
3990 NSArray *packages([database packages]);
3991 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3992 for (Package *package in packages)
3993 if (![package uninstalled])
3994 [installed addObject:package];
3998 - (Package *) getPackageById:(NSString *)id {
3999 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4003 return (Package *) [NSNull null];
4006 - (NSString *) getLocaleIdentifier {
4007 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4010 - (NSArray *) getPreferredLanguages {
4014 - (NSArray *) statfs:(NSString *)path {
4017 if (path == nil || statfs([path UTF8String], &stat) == -1)
4020 return [NSArray arrayWithObjects:
4021 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4022 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4023 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4027 - (NSNumber *) du:(NSString *)path {
4028 NSNumber *value(nil);
4031 _assert(pipe(fds) != -1);
4033 pid_t pid(ExecFork());
4035 _assert(dup2(fds[1], 1) != -1);
4036 _assert(close(fds[0]) != -1);
4037 _assert(close(fds[1]) != -1);
4038 /* XXX: this should probably not use du */
4039 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4044 _assert(close(fds[1]) != -1);
4046 if (FILE *du = fdopen(fds[0], "r")) {
4048 while (fgets(line, sizeof(line), du) != NULL) {
4049 size_t length(strlen(line));
4050 while (length != 0 && line[length - 1] == '\n')
4051 line[--length] = '\0';
4052 if (char *tab = strchr(line, '\t')) {
4054 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4059 } else _assert(close(fds[0]));
4063 if (waitpid(pid, &status, 0) == -1)
4066 else _assert(false);
4072 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4075 - (void) installPackages:(NSArray *)packages {
4076 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4079 - (NSString *) substitutePackageNames:(NSString *)message {
4080 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4081 for (size_t i(0), e([words count]); i != e; ++i) {
4082 NSString *word([words objectAtIndex:i]);
4083 if (Package *package = [[Database sharedInstance] packageWithName:word])
4084 [words replaceObjectAtIndex:i withObject:[package name]];
4087 return [words componentsJoinedByString:@" "];
4090 - (void) removeButton {
4091 [indirect_ removeButton];
4094 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4095 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4098 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4099 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4102 - (void) setBadgeValue:(id)value {
4103 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4106 - (void) setAllowsNavigationAction:(NSString *)value {
4107 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4110 - (void) setHidesBackButton:(NSString *)value {
4111 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4114 - (void) setHidesNavigationBar:(NSString *)value {
4115 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4118 - (void) setNavigationBarStyle:(NSString *)value {
4119 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4122 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4123 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4124 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4125 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4128 - (void) setPasteboardString:(NSString *)value {
4129 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4132 - (void) setPasteboardURL:(NSString *)value {
4133 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4136 - (void) _setToken:(NSString *)token {
4140 [Metadata_ removeObjectForKey:@"Token"];
4142 [Metadata_ setObject:Token_ forKey:@"Token"];
4147 - (void) setToken:(NSString *)token {
4148 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4151 - (void) scrollToBottom:(NSNumber *)animated {
4152 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4155 - (void) setViewportWidth:(float)width {
4156 [indirect_ setViewportWidthOnMainThread:width];
4159 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4160 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4161 unsigned count([arguments count]);
4163 for (unsigned i(0); i != count; ++i)
4164 values[i] = [arguments objectAtIndex:i];
4165 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4168 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4169 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4171 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4173 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4179 /* @ Loading... Indicator {{{ */
4180 @interface CYLoadingIndicator : UIView {
4181 _H<UIActivityIndicatorView> spinner_;
4183 _H<UIView> container_;
4188 @implementation CYLoadingIndicator
4190 - (id) initWithFrame:(CGRect)frame {
4191 if ((self = [super initWithFrame:frame]) != nil) {
4192 container_ = [[[UIView alloc] init] autorelease];
4193 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4195 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4196 [spinner_ startAnimating];
4197 [container_ addSubview:spinner_];
4199 label_ = [[[UILabel alloc] init] autorelease];
4200 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4201 [label_ setBackgroundColor:[UIColor clearColor]];
4202 [label_ setTextColor:[UIColor blackColor]];
4203 [label_ setShadowColor:[UIColor whiteColor]];
4204 [label_ setShadowOffset:CGSizeMake(0, 1)];
4205 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4206 [container_ addSubview:label_];
4208 CGSize viewsize = frame.size;
4209 CGSize spinnersize = [spinner_ bounds].size;
4210 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4211 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4213 CGRect containrect = {
4214 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4215 CGSizeMake(bothwidth, spinnersize.height)
4218 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4226 [container_ setFrame:containrect];
4227 [spinner_ setFrame:spinrect];
4228 [label_ setFrame:textrect];
4229 [self addSubview:container_];
4235 /* Emulated Loading Controller {{{ */
4236 @interface CYEmulatedLoadingController : CyteViewController {
4237 _H<CYLoadingIndicator> indicator_;
4238 _H<UITabBar> tabbar_;
4239 _H<UINavigationBar> navbar_;
4244 @implementation CYEmulatedLoadingController
4247 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4249 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4250 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4251 [[self view] addSubview:table];
4253 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4254 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4255 [[self view] addSubview:indicator_];
4257 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4258 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4259 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4260 [[self view] addSubview:tabbar_];
4262 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4263 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4264 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4265 [[self view] addSubview:navbar_];
4268 - (void) releaseSubviews {
4277 /* Cydia Browser Controller {{{ */
4278 @implementation CydiaWebViewController
4280 - (NSURL *) navigationURL {
4281 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4284 + (void) initialize {
4285 Diversions_ = [NSMutableSet setWithCapacity:0];
4288 + (void) addDiversion:(Diversion *)diversion {
4289 [Diversions_ addObject:diversion];
4292 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4293 [super webView:view didClearWindowObject:window forFrame:frame];
4295 WebDataSource *source([frame dataSource]);
4296 NSURLResponse *response([source response]);
4297 NSURL *url([response URL]);
4298 NSString *scheme([[url scheme] lowercaseString]);
4300 bool bridged(false);
4302 @synchronized (HostConfig_) {
4303 if ([scheme isEqualToString:@"file"])
4305 else if ([scheme isEqualToString:@"https"])
4306 if ([BridgedHosts_ containsObject:[url host]])
4311 [window setValue:cydia_ forKey:@"cydia"];
4314 - (NSURL *) URLWithURL:(NSURL *)url {
4315 return [Diversion divertURL:url];
4318 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4319 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4321 if (System_ != NULL)
4322 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4323 if (Machine_ != NULL)
4324 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4326 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4331 - (void) setDelegate:(id)delegate {
4332 [super setDelegate:delegate];
4333 [cydia_ setDelegate:delegate];
4337 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4338 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4340 WebView *webview([[webview_ _documentView] webView]);
4342 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4345 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4347 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4348 if (Product_ != nil)
4349 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4351 [webview setApplicationNameForUserAgent:application];
4359 @interface NSObject (CydiaScript)
4360 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4363 @implementation NSObject (CydiaScript)
4365 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4371 @implementation NSArray (CydiaScript)
4373 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4374 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4375 for (size_t i(0), e([self count]); i != e; ++i)
4376 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4382 @implementation NSDictionary (CydiaScript)
4384 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4385 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4387 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4394 /* Confirmation Controller {{{ */
4395 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4396 if (!iterator.end())
4397 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4398 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4400 pkgCache::PkgIterator package(dep.TargetPkg());
4403 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4410 @protocol ConfirmationControllerDelegate
4411 - (void) cancelAndClear:(bool)clear;
4412 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4416 @interface ConfirmationController : CydiaWebViewController {
4417 _transient Database *database_;
4419 _H<UIAlertView> essential_;
4421 _H<NSDictionary> changes_;
4422 _H<NSMutableArray> issues_;
4423 _H<NSDictionary> sizes_;
4428 - (id) initWithDatabase:(Database *)database;
4432 @implementation ConfirmationController
4436 RestartSubstrate_ = true;
4437 [delegate_ confirmWithNavigationController:[self navigationController]];
4440 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4441 NSString *context([alert context]);
4443 if ([context isEqualToString:@"remove"]) {
4444 if (button == [alert cancelButtonIndex])
4445 [self dismissModalViewControllerAnimated:YES];
4446 else if (button == [alert firstOtherButtonIndex]) {
4450 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4451 } else if ([context isEqualToString:@"unable"]) {
4452 [self dismissModalViewControllerAnimated:YES];
4453 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4455 [super alertView:alert clickedButtonAtIndex:button];
4459 - (void) _doContinue {
4460 [self dismissModalViewControllerAnimated:YES];
4461 [delegate_ cancelAndClear:NO];
4464 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4465 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4469 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4470 [super webView:view didClearWindowObject:window forFrame:frame];
4472 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4473 (id) changes_, @"changes",
4474 (id) issues_, @"issues",
4475 (id) sizes_, @"sizes",
4477 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4480 - (id) initWithDatabase:(Database *)database {
4481 if ((self = [super init]) != nil) {
4482 database_ = database;
4484 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4485 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4486 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4487 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4488 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4492 pkgCacheFile &cache([database_ cache]);
4493 NSArray *packages([database_ packages]);
4494 pkgDepCache::Policy *policy([database_ policy]);
4496 issues_ = [NSMutableArray arrayWithCapacity:4];
4498 for (Package *package in packages) {
4499 pkgCache::PkgIterator iterator([package iterator]);
4500 NSString *name([package id]);
4502 if ([package broken]) {
4503 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4505 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4507 reasons, @"reasons",
4510 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4514 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4515 pkgCache::DepIterator start;
4516 pkgCache::DepIterator end;
4517 dep.GlobOr(start, end); // ++dep
4519 if (!cache->IsImportantDep(end))
4521 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4524 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4526 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4527 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4528 clauses, @"clauses",
4532 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4534 pkgCache::PkgIterator target(start.TargetPkg());
4535 if (target->ProvidesList != 0)
4536 reason = @"missing";
4538 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4540 reason = @"installed";
4541 installed = [NSString stringWithUTF8String:ver.VerStr()];
4542 } else if (!cache[target].CandidateVerIter(cache).end())
4543 reason = @"uninstalled";
4544 else if (target->ProvidesList == 0)
4545 reason = @"uninstallable";
4547 reason = @"virtual";
4550 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4551 [NSString stringWithUTF8String:start.CompType()], @"operator",
4552 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4555 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4556 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4557 version, @"version",
4559 installed, @"installed",
4562 // yes, seriously. (wtf?)
4570 pkgDepCache::StateCache &state(cache[iterator]);
4572 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4574 if (state.NewInstall())
4575 [installs addObject:name];
4576 // XXX: else if (state.Install())
4577 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4578 [reinstalls addObject:name];
4579 // XXX: move before previous if
4580 else if (state.Upgrade())
4581 [upgrades addObject:name];
4582 else if (state.Downgrade())
4583 [downgrades addObject:name];
4584 else if (!state.Delete())
4585 // XXX: _assert(state.Keep());
4587 else if (special_r(name))
4588 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4589 [NSNull null], @"package",
4590 [NSArray arrayWithObjects:
4591 [NSDictionary dictionaryWithObjectsAndKeys:
4592 @"Conflicts", @"relationship",
4593 [NSArray arrayWithObjects:
4594 [NSDictionary dictionaryWithObjectsAndKeys:
4596 [NSNull null], @"version",
4597 @"installed", @"reason",
4604 if ([package essential])
4606 [removes addObject:name];
4609 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4610 substrate_ |= DepSubstrate(iterator.CurrentVer());
4615 else if (Advanced_) {
4616 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4618 essential_ = [[[UIAlertView alloc]
4619 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4620 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4622 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4624 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4628 [essential_ setContext:@"remove"];
4630 essential_ = [[[UIAlertView alloc]
4631 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4632 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4634 cancelButtonTitle:UCLocalize("OKAY")
4635 otherButtonTitles:nil
4638 [essential_ setContext:@"unable"];
4641 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4642 installs, @"installs",
4643 reinstalls, @"reinstalls",
4644 upgrades, @"upgrades",
4645 downgrades, @"downgrades",
4646 removes, @"removes",
4649 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4650 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4651 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4654 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4658 - (UIBarButtonItem *) leftButton {
4659 return [[[UIBarButtonItem alloc]
4660 initWithTitle:UCLocalize("CANCEL")
4661 style:UIBarButtonItemStylePlain
4663 action:@selector(cancelButtonClicked)
4668 - (void) applyRightButton {
4669 if ([issues_ count] == 0 && ![self isLoading])
4670 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4671 initWithTitle:UCLocalize("CONFIRM")
4672 style:UIBarButtonItemStyleDone
4674 action:@selector(confirmButtonClicked)
4677 [[self navigationItem] setRightBarButtonItem:nil];
4681 - (void) cancelButtonClicked {
4682 [self dismissModalViewControllerAnimated:YES];
4683 [delegate_ cancelAndClear:YES];
4687 - (void) confirmButtonClicked {
4688 if (essential_ != nil)
4698 /* Progress Data {{{ */
4699 @interface CydiaProgressData : NSObject {
4700 _transient id delegate_;
4709 _H<NSMutableArray> events_;
4710 _H<NSString> title_;
4712 _H<NSString> status_;
4713 _H<NSString> finish_;
4718 @implementation CydiaProgressData
4720 + (NSArray *) _attributeKeys {
4721 return [NSArray arrayWithObjects:
4733 - (NSArray *) attributeKeys {
4734 return [[self class] _attributeKeys];
4737 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4738 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4742 if ((self = [super init]) != nil) {
4743 events_ = [NSMutableArray arrayWithCapacity:32];
4747 - (void) setDelegate:(id)delegate {
4748 delegate_ = delegate;
4751 - (void) setPercent:(float)value {
4755 - (NSNumber *) percent {
4756 return [NSNumber numberWithFloat:percent_];
4759 - (void) setCurrent:(float)value {
4763 - (NSNumber *) current {
4764 return [NSNumber numberWithFloat:current_];
4767 - (void) setTotal:(float)value {
4771 - (NSNumber *) total {
4772 return [NSNumber numberWithFloat:total_];
4775 - (void) setSpeed:(float)value {
4779 - (NSNumber *) speed {
4780 return [NSNumber numberWithFloat:speed_];
4783 - (NSArray *) events {
4787 - (void) removeAllEvents {
4788 [events_ removeAllObjects];
4791 - (void) addEvent:(CydiaProgressEvent *)event {
4792 [events_ addObject:event];
4795 - (void) setTitle:(NSString *)text {
4799 - (NSString *) title {
4803 - (void) setFinish:(NSString *)text {
4807 - (NSString *) finish {
4808 return (id) finish_ ?: [NSNull null];
4811 - (void) setRunning:(bool)running {
4815 - (NSNumber *) running {
4816 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4821 /* Progress Controller {{{ */
4822 @interface ProgressController : CydiaWebViewController <
4825 _transient Database *database_;
4826 _H<CydiaProgressData, 1> progress_;
4830 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4832 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4834 - (void) setTitle:(NSString *)title;
4835 - (void) setCancellable:(bool)cancellable;
4839 @implementation ProgressController
4842 [database_ setProgressDelegate:nil];
4846 - (UIBarButtonItem *) leftButton {
4847 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4848 initWithTitle:UCLocalize("CANCEL")
4849 style:UIBarButtonItemStylePlain
4851 action:@selector(cancel)
4852 ] autorelease] : nil;
4855 - (void) updateCancel {
4856 [super applyLeftButton];
4859 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4860 if ((self = [super init]) != nil) {
4861 database_ = database;
4862 delegate_ = delegate;
4864 [database_ setProgressDelegate:self];
4866 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4867 [progress_ setDelegate:self];
4869 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4871 [scroller_ setBackgroundColor:[UIColor blackColor]];
4873 [[self navigationItem] setHidesBackButton:YES];
4875 [self updateCancel];
4879 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4880 [super webView:view didClearWindowObject:window forFrame:frame];
4881 [window setValue:progress_ forKey:@"cydiaProgress"];
4884 - (void) updateProgress {
4885 [self dispatchEvent:@"CydiaProgressUpdate"];
4888 - (void) viewWillAppear:(BOOL)animated {
4889 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4890 [super viewWillAppear:animated];
4894 UpdateExternalStatus(0);
4901 [delegate_ terminateWithSuccess];
4902 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4903 [delegate_ suspendWithAnimation:YES];
4905 [delegate_ suspend];*/
4917 system("/usr/bin/sbreload");
4923 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4924 SBReboot(SBSSpringBoardServerPort());
4926 reboot2(RB_AUTOBOOT);
4933 - (void) setTitle:(NSString *)title {
4934 [progress_ setTitle:title];
4935 [self updateProgress];
4938 - (UIBarButtonItem *) rightButton {
4939 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4940 initWithTitle:UCLocalize("CLOSE")
4941 style:UIBarButtonItemStylePlain
4943 action:@selector(close)
4947 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4948 UpdateExternalStatus(1);
4950 [progress_ setRunning:true];
4951 [self setTitle:title];
4952 // implicit updateProgress
4954 SHA1SumValue notifyconf; {
4956 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4959 MMap mmap(file, MMap::ReadOnly);
4961 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4962 notifyconf = sha1.Result();
4966 SHA1SumValue springlist; {
4968 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4971 MMap mmap(file, MMap::ReadOnly);
4973 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4974 springlist = sha1.Result();
4978 if (invocation != nil) {
4979 [invocation yieldToSelector:@selector(invoke)];
4980 [self setTitle:@"COMPLETE"];
4985 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4988 MMap mmap(file, MMap::ReadOnly);
4990 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4991 if (!(notifyconf == sha1.Result()))
4998 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5001 MMap mmap(file, MMap::ReadOnly);
5003 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5004 if (!(springlist == sha1.Result()))
5010 if (RestartSubstrate_)
5014 RestartSubstrate_ = false;
5017 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5018 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5019 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5020 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5021 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5025 system("su -c /usr/bin/uicache mobile");
5028 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5030 [progress_ setRunning:false];
5031 [self updateProgress];
5033 [self applyRightButton];
5036 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5037 [progress_ addEvent:event];
5038 [self updateProgress];
5041 - (bool) isProgressCancelled {
5042 return cancel_ == 2;
5047 [self updateCancel];
5050 - (void) setCancellable:(bool)cancellable {
5051 unsigned cancel(cancel_);
5055 else if (cancel_ == 0)
5058 if (cancel != cancel_)
5059 [self updateCancel];
5062 - (void) setProgressCancellable:(NSNumber *)cancellable {
5063 [self setCancellable:[cancellable boolValue]];
5066 - (void) setProgressPercent:(NSNumber *)percent {
5067 [progress_ setPercent:[percent floatValue]];
5068 [self updateProgress];
5071 - (void) setProgressStatus:(NSDictionary *)status {
5072 if (status == nil) {
5073 [progress_ setCurrent:0];
5074 [progress_ setTotal:0];
5075 [progress_ setSpeed:0];
5077 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5079 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5080 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5081 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5084 [self updateProgress];
5090 /* Package Cell {{{ */
5091 @interface PackageCell : CyteTableViewCell <
5092 CyteTableViewCellDelegate
5096 _H<NSString> description_;
5098 _H<NSString> source_;
5100 _H<Package> package_;
5101 _H<UIImage> placard_;
5105 - (PackageCell *) init;
5106 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5108 - (void) drawContentRect:(CGRect)rect;
5112 @implementation PackageCell
5114 - (PackageCell *) init {
5115 CGRect frame(CGRectMake(0, 0, 320, 74));
5116 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5117 UIView *content([self contentView]);
5118 CGRect bounds([content bounds]);
5120 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5121 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5122 [content addSubview:content_];
5124 [content_ setDelegate:self];
5125 [content_ setOpaque:YES];
5129 - (NSString *) accessibilityLabel {
5130 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5133 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5134 summarized_ = summary;
5146 Source *source = [package source];
5148 icon_ = [package icon];
5149 name_ = [package name];
5152 description_ = [package longDescription];
5153 if (description_ == nil)
5154 description_ = [package shortDescription];
5156 commercial_ = [package isCommercial];
5160 NSString *label = nil;
5161 bool trusted = false;
5163 if (source != nil) {
5164 label = [source label];
5165 trusted = [source trusted];
5166 } else if ([[package id] isEqualToString:@"firmware"])
5167 label = UCLocalize("APPLE");
5169 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5171 NSString *from(label);
5173 NSString *section = [package simpleSection];
5174 if (section != nil && ![section isEqualToString:label]) {
5175 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5176 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5179 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5181 if (NSString *purpose = [package primaryPurpose])
5182 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5187 if (NSString *mode = [package_ mode]) {
5188 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5189 color = RemovingColor_;
5190 //placard = @"removing";
5192 color = InstallingColor_;
5193 //placard = @"installing";
5196 // XXX: the removing/installing placards are not @2x
5199 color = [UIColor whiteColor];
5201 if ([package installed] != nil)
5202 placard = @"installed";
5207 [content_ setBackgroundColor:color];
5210 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5212 [self setNeedsDisplay];
5213 [content_ setNeedsDisplay];
5216 - (void) drawSummaryContentRect:(CGRect)rect {
5217 bool highlighted(highlighted_);
5218 float width([self bounds].size.width);
5222 rect.size = [(UIImage *) icon_ size];
5224 rect.size.width /= 4;
5225 rect.size.height /= 4;
5227 rect.origin.x = 14 - rect.size.width / 4;
5228 rect.origin.y = 14 - rect.size.height / 4;
5230 [icon_ drawInRect:rect];
5233 if (badge_ != nil) {
5235 rect.size = [(UIImage *) badge_ size];
5237 rect.size.width /= 4;
5238 rect.size.height /= 4;
5240 rect.origin.x = 20 - rect.size.width / 4;
5241 rect.origin.y = 20 - rect.size.height / 4;
5243 [badge_ drawInRect:rect];
5250 UISetColor(commercial_ ? Purple_ : Black_);
5251 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5253 if (placard_ != nil)
5254 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5257 - (void) drawNormalContentRect:(CGRect)rect {
5258 bool highlighted(highlighted_);
5259 float width([self bounds].size.width);
5263 rect.size = [(UIImage *) icon_ size];
5265 rect.size.width /= 2;
5266 rect.size.height /= 2;
5268 rect.origin.x = 25 - rect.size.width / 2;
5269 rect.origin.y = 25 - rect.size.height / 2;
5271 [icon_ drawInRect:rect];
5274 if (badge_ != nil) {
5276 rect.size = [(UIImage *) badge_ size];
5278 rect.size.width /= 2;
5279 rect.size.height /= 2;
5281 rect.origin.x = 36 - rect.size.width / 2;
5282 rect.origin.y = 36 - rect.size.height / 2;
5284 [badge_ drawInRect:rect];
5291 UISetColor(commercial_ ? Purple_ : Black_);
5292 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5293 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5296 UISetColor(commercial_ ? Purplish_ : Gray_);
5297 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5299 if (placard_ != nil)
5300 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5303 - (void) drawContentRect:(CGRect)rect {
5305 [self drawSummaryContentRect:rect];
5307 [self drawNormalContentRect:rect];
5312 /* Section Cell {{{ */
5313 @interface SectionCell : CyteTableViewCell <
5314 CyteTableViewCellDelegate
5316 _H<NSString> basic_;
5317 _H<NSString> section_;
5319 _H<NSString> count_;
5321 _H<UISwitch> switch_;
5325 - (void) setSection:(Section *)section editing:(BOOL)editing;
5329 @implementation SectionCell
5331 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5332 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5333 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5334 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5335 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5337 UIView *content([self contentView]);
5338 CGRect bounds([content bounds]);
5340 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5341 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5342 [content addSubview:content_];
5343 [content_ setBackgroundColor:[UIColor whiteColor]];
5345 [content_ setDelegate:self];
5349 - (void) onSwitch:(id)sender {
5350 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5351 if (metadata == nil) {
5352 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5353 [Sections_ setObject:metadata forKey:basic_];
5356 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5360 - (void) setSection:(Section *)section editing:(BOOL)editing {
5361 if (editing != editing_) {
5363 [switch_ removeFromSuperview];
5365 [self addSubview:switch_];
5374 if (section == nil) {
5375 name_ = UCLocalize("ALL_PACKAGES");
5378 basic_ = [section name];
5379 section_ = [section localized];
5381 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5382 count_ = [NSString stringWithFormat:@"%d", [section count]];
5385 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5388 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5389 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5391 [content_ setNeedsDisplay];
5394 - (void) setFrame:(CGRect)frame {
5395 [super setFrame:frame];
5397 CGRect rect([switch_ frame]);
5398 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5401 - (NSString *) accessibilityLabel {
5405 - (void) drawContentRect:(CGRect)rect {
5406 bool highlighted(highlighted_ && !editing_);
5408 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5413 float width(rect.size.width);
5419 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5421 CGSize size = [count_ sizeWithFont:Font14_];
5425 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5431 /* File Table {{{ */
5432 @interface FileTable : CyteViewController <
5433 UITableViewDataSource,
5436 _transient Database *database_;
5437 _H<Package> package_;
5439 _H<NSMutableArray> files_;
5440 _H<UITableView, 2> list_;
5443 - (id) initWithDatabase:(Database *)database;
5444 - (void) setPackage:(Package *)package;
5448 @implementation FileTable
5450 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5451 return files_ == nil ? 0 : [files_ count];
5454 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5458 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5459 static NSString *reuseIdentifier = @"Cell";
5461 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5463 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5464 [cell setFont:[UIFont systemFontOfSize:16]];
5466 [cell setText:[files_ objectAtIndex:indexPath.row]];
5467 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5472 - (NSURL *) navigationURL {
5473 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5477 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5479 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5480 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5481 [list_ setRowHeight:24.0f];
5482 [(UITableView *) list_ setDataSource:self];
5483 [list_ setDelegate:self];
5484 [[self view] addSubview:list_];
5487 - (void) viewDidLoad {
5488 [super viewDidLoad];
5490 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5493 - (void) releaseSubviews {
5497 - (id) initWithDatabase:(Database *)database {
5498 if ((self = [super init]) != nil) {
5499 database_ = database;
5501 files_ = [NSMutableArray arrayWithCapacity:32];
5505 - (void) setPackage:(Package *)package {
5509 [files_ removeAllObjects];
5511 if (package != nil) {
5513 name_ = [package id];
5515 if (NSArray *files = [package files])
5516 [files_ addObjectsFromArray:files];
5518 if ([files_ count] != 0) {
5519 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5520 [files_ removeObjectAtIndex:0];
5521 [files_ sortUsingSelector:@selector(compareByPath:)];
5523 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5524 [stack addObject:@"/"];
5526 for (int i(0), e([files_ count]); i != e; ++i) {
5527 NSString *file = [files_ objectAtIndex:i];
5528 while (![file hasPrefix:[stack lastObject]])
5529 [stack removeLastObject];
5530 NSString *directory = [stack lastObject];
5531 [stack addObject:[file stringByAppendingString:@"/"]];
5532 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5533 ([stack count] - 2) * 3, "",
5534 [file substringFromIndex:[directory length]]
5543 - (void) reloadData {
5546 [self setPackage:[database_ packageWithName:name_]];
5551 /* Package Controller {{{ */
5552 @interface CYPackageController : CydiaWebViewController <
5553 UIActionSheetDelegate
5555 _transient Database *database_;
5556 _H<Package> package_;
5559 _H<NSMutableArray> buttons_;
5560 _H<UIBarButtonItem> button_;
5563 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5567 @implementation CYPackageController
5569 - (NSURL *) navigationURL {
5570 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5573 /* XXX: this is not safe at all... localization of /fail/ */
5574 - (void) _clickButtonWithName:(NSString *)name {
5575 if ([name isEqualToString:UCLocalize("CLEAR")])
5576 [delegate_ clearPackage:package_];
5577 else if ([name isEqualToString:UCLocalize("INSTALL")])
5578 [delegate_ installPackage:package_];
5579 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5580 [delegate_ installPackage:package_];
5581 else if ([name isEqualToString:UCLocalize("REMOVE")])
5582 [delegate_ removePackage:package_];
5583 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5584 [delegate_ installPackage:package_];
5585 else _assert(false);
5588 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5589 NSString *context([sheet context]);
5591 if ([context isEqualToString:@"modify"]) {
5592 if (button != [sheet cancelButtonIndex]) {
5593 NSString *buttonName = [buttons_ objectAtIndex:button];
5594 [self _clickButtonWithName:buttonName];
5597 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5601 - (bool) _allowJavaScriptPanel {
5606 - (void) _customButtonClicked {
5607 int count([buttons_ count]);
5612 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5614 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5615 [buttons addObjectsFromArray:buttons_];
5617 UIActionSheet *sheet = [[[UIActionSheet alloc]
5620 cancelButtonTitle:nil
5621 destructiveButtonTitle:nil
5622 otherButtonTitles:nil
5625 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5627 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5628 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5630 [sheet setContext:@"modify"];
5632 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5636 // We don't want to allow non-commercial packages to do custom things to the install button,
5637 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5638 - (void) customButtonClicked {
5640 [super customButtonClicked];
5642 [self _customButtonClicked];
5645 - (void) reloadButtonClicked {
5646 // Don't reload a commerical package by tapping the loading button,
5647 // but if it's not an Install button, we should forward it on.
5648 if (![package_ uninstalled])
5649 [self _customButtonClicked];
5652 - (void) applyLoadingTitle {
5653 // Don't show "Loading" as the title. Ever.
5656 - (UIBarButtonItem *) rightButton {
5661 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5662 if ((self = [super init]) != nil) {
5663 database_ = database;
5664 buttons_ = [NSMutableArray arrayWithCapacity:4];
5665 name_ = [NSString stringWithString:name];
5666 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5670 - (void) reloadData {
5673 package_ = [database_ packageWithName:name_];
5675 [buttons_ removeAllObjects];
5677 if (package_ != nil) {
5678 [(Package *) package_ parse];
5680 commercial_ = [package_ isCommercial];
5682 if ([package_ mode] != nil)
5683 [buttons_ addObject:UCLocalize("CLEAR")];
5684 if ([package_ source] == nil);
5685 else if ([package_ upgradableAndEssential:NO])
5686 [buttons_ addObject:UCLocalize("UPGRADE")];
5687 else if ([package_ uninstalled])
5688 [buttons_ addObject:UCLocalize("INSTALL")];
5690 [buttons_ addObject:UCLocalize("REINSTALL")];
5691 if (![package_ uninstalled])
5692 [buttons_ addObject:UCLocalize("REMOVE")];
5696 switch ([buttons_ count]) {
5697 case 0: title = nil; break;
5698 case 1: title = [buttons_ objectAtIndex:0]; break;
5699 default: title = UCLocalize("MODIFY"); break;
5702 button_ = [[[UIBarButtonItem alloc]
5704 style:UIBarButtonItemStylePlain
5706 action:@selector(customButtonClicked)
5710 - (bool) isLoading {
5711 return commercial_ ? [super isLoading] : false;
5717 /* Package List Controller {{{ */
5718 @interface PackageListController : CyteViewController <
5719 UITableViewDataSource,
5722 _transient Database *database_;
5724 _H<NSArray> packages_;
5725 _H<NSMutableArray> sections_;
5726 _H<UITableView, 2> list_;
5727 _H<NSMutableArray> index_;
5728 _H<NSMutableDictionary> indices_;
5729 _H<NSString> title_;
5730 unsigned reloading_;
5733 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5734 - (void) setDelegate:(id)delegate;
5735 - (void) resetCursor;
5740 @implementation PackageListController
5742 - (bool) isSummarized {
5746 - (void) deselectWithAnimation:(BOOL)animated {
5747 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5750 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5751 CGRect base = [[self view] bounds];
5752 base.size.height -= bounds.size.height;
5753 base.origin = [list_ frame].origin;
5755 [UIView beginAnimations:nil context:NULL];
5756 [UIView setAnimationBeginsFromCurrentState:YES];
5757 [UIView setAnimationCurve:curve];
5758 [UIView setAnimationDuration:duration];
5759 [list_ setFrame:base];
5760 [UIView commitAnimations];
5763 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5764 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5767 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5768 [self resizeForKeyboardBounds:bounds duration:0];
5771 - (void) keyboardWillShow:(NSNotification *)notification {
5774 NSTimeInterval duration;
5775 UIViewAnimationCurve curve;
5776 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5777 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5778 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5779 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5781 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);
5782 UIViewController *base = self;
5783 while ([base parentViewController] != nil)
5784 base = [base parentViewController];
5785 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5786 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5788 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5791 - (void) keyboardWillHide:(NSNotification *)notification {
5792 NSTimeInterval duration;
5793 UIViewAnimationCurve curve;
5794 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5795 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5797 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5800 - (void) viewWillAppear:(BOOL)animated {
5801 [super viewWillAppear:animated];
5803 [self resizeForKeyboardBounds:CGRectZero];
5804 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5805 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5808 - (void) viewWillDisappear:(BOOL)animated {
5809 [super viewWillDisappear:animated];
5811 [self resizeForKeyboardBounds:CGRectZero];
5812 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5813 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5816 - (void) viewDidAppear:(BOOL)animated {
5817 [super viewDidAppear:animated];
5818 [self deselectWithAnimation:animated];
5821 - (void) didSelectPackage:(Package *)package {
5822 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5823 [view setDelegate:delegate_];
5824 [[self navigationController] pushViewController:view animated:YES];
5827 #if TryIndexedCollation
5828 + (BOOL) hasIndexedCollation {
5829 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5833 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5834 NSInteger count([sections_ count]);
5835 return count == 0 ? 1 : count;
5838 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5839 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5841 return [[sections_ objectAtIndex:section] name];
5844 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5845 if ([sections_ count] == 0)
5847 return [[sections_ objectAtIndex:section] count];
5850 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5851 @synchronized (database_) {
5852 if ([database_ era] != era_)
5855 Section *section([sections_ objectAtIndex:[path section]]);
5856 NSInteger row([path row]);
5857 Package *package([packages_ objectAtIndex:([section row] + row)]);
5858 return [[package retain] autorelease];
5861 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5862 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5864 cell = [[[PackageCell alloc] init] autorelease];
5865 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5869 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5870 Package *package([self packageAtIndexPath:path]);
5871 package = [database_ packageWithName:[package id]];
5872 [self didSelectPackage:package];
5875 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5876 if ([self isSummarized])
5882 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5883 #if TryIndexedCollation
5884 if ([[self class] hasIndexedCollation]) {
5885 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5892 - (void) updateHeight {
5893 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5896 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5897 if ((self = [super init]) != nil) {
5898 database_ = database;
5899 title_ = [title copy];
5900 [[self navigationItem] setTitle:title_];
5902 #if TryIndexedCollation
5903 if ([[self class] hasIndexedCollation])
5904 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5907 index_ = [NSMutableArray arrayWithCapacity:32];
5909 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5911 packages_ = [NSArray array];
5912 sections_ = [NSMutableArray arrayWithCapacity:16];
5914 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5915 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5916 [[self view] addSubview:list_];
5918 // XXX: is 20 the most optimal number here?
5919 [list_ setSectionIndexMinimumDisplayRowCount:20];
5921 [(UITableView *) list_ setDataSource:self];
5922 [list_ setDelegate:self];
5924 [self updateHeight];
5928 - (void) setDelegate:(id)delegate {
5929 delegate_ = delegate;
5932 - (bool) hasPackage:(Package *)package {
5936 - (bool) shouldYield {
5940 - (bool) shouldBlock {
5944 - (NSArray *) _reloadPackages:(NSArray *)packages {
5945 // XXX: maybe move @synchronized() to _reloadData?
5946 @synchronized (database_) {
5947 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
5949 _profile(PackageTable$reloadData$Filter)
5950 for (Package *package in packages)
5951 if ([self hasPackage:package])
5952 [filtered addObject:package];
5958 - (void) _reloadData {
5959 if (reloading_ != 0) {
5964 era_ = [database_ era];
5965 NSArray *packages = [database_ packages];
5967 if ([self shouldYield]) {
5970 if (![self shouldBlock])
5973 hud = [delegate_ addProgressHUD];
5974 [hud setText:UCLocalize("LOADING")];
5979 packages_ = [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
5980 } while (reloading_ == 2);
5985 [delegate_ removeProgressHUD:hud];
5987 packages_ = [self _reloadPackages:packages];
5990 [indices_ removeAllObjects];
5991 [sections_ removeAllObjects];
5993 Section *section = nil;
5995 #if TryIndexedCollation
5996 if ([[self class] hasIndexedCollation]) {
5997 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5998 NSArray *titles = [collation sectionIndexTitles];
6001 _profile(PackageTable$reloadData$Section)
6002 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6006 _profile(PackageTable$reloadData$Section$Package)
6007 package = [packages_ objectAtIndex:offset];
6008 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6011 while (secidx < index) {
6014 _profile(PackageTable$reloadData$Section$Allocate)
6015 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6018 _profile(PackageTable$reloadData$Section$Add)
6019 [sections_ addObject:section];
6023 [section addToCount];
6029 [index_ removeAllObjects];
6031 bool summary([self isSummarized]);
6033 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6034 [sections_ addObject:section];
6037 _profile(PackageTable$reloadData$Section)
6038 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6042 _profile(PackageTable$reloadData$Section$Package)
6043 package = [packages_ objectAtIndex:offset];
6044 index = [package index];
6047 if (!summary && (section == nil || [section index] != index)) {
6048 _profile(PackageTable$reloadData$Section$Allocate)
6049 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6052 [index_ addObject:[section name]];
6053 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6055 _profile(PackageTable$reloadData$Section$Add)
6056 [sections_ addObject:section];
6060 [section addToCount];
6065 [self updateHeight];
6067 _profile(PackageTable$reloadData$List)
6068 [(UITableView *) list_ setDataSource:self];
6073 - (void) reloadData {
6075 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6078 - (void) resetCursor {
6079 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6082 - (void) clearData {
6083 [self updateHeight];
6085 [list_ setDataSource:nil];
6093 /* Filtered Package List Controller {{{ */
6094 @interface FilteredPackageListController : PackageListController {
6097 _H<NSObject> object_;
6100 - (void) setObject:(id)object;
6101 - (void) setObject:(id)object forFilter:(SEL)filter;
6104 - (void) setFilter:(SEL)filter;
6106 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6110 @implementation FilteredPackageListController
6116 - (void) setFilter:(SEL)filter {
6119 /* XXX: this is an unsafe optimization of doomy hell */
6120 Method method(class_getInstanceMethod([Package class], filter));
6121 _assert(method != NULL);
6122 imp_ = method_getImplementation(method);
6123 _assert(imp_ != NULL);
6126 - (void) setObject:(id)object {
6130 - (void) setObject:(id)object forFilter:(SEL)filter {
6131 [self setFilter:filter];
6132 [self setObject:object];
6135 - (bool) hasPackage:(Package *)package {
6136 _profile(FilteredPackageTable$hasPackage)
6137 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6141 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6142 if ((self = [super initWithDatabase:database title:title]) != nil) {
6143 [self setFilter:filter];
6144 [self setObject:object];
6151 /* Home Controller {{{ */
6152 @interface HomeController : CydiaWebViewController {
6157 @implementation HomeController
6160 if ((self = [super init]) != nil) {
6161 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6166 - (NSURL *) navigationURL {
6167 return [NSURL URLWithString:@"cydia://home"];
6170 - (void) aboutButtonClicked {
6171 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6173 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6174 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6175 [alert setCancelButtonIndex:0];
6178 @"Copyright \u00a9 2008-2011\n"
6181 "Jay Freeman (saurik)\n"
6182 "saurik@saurik.com\n"
6183 "http://www.saurik.com/"
6189 - (UIBarButtonItem *) leftButton {
6190 return [[[UIBarButtonItem alloc]
6191 initWithTitle:UCLocalize("ABOUT")
6192 style:UIBarButtonItemStylePlain
6194 action:@selector(aboutButtonClicked)
6198 - (void) unloadData {
6205 /* Manage Controller {{{ */
6206 @interface ManageController : CydiaWebViewController {
6209 - (void) queueStatusDidChange;
6213 @implementation ManageController
6216 if ((self = [super init]) != nil) {
6217 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6221 - (NSURL *) navigationURL {
6222 return [NSURL URLWithString:@"cydia://manage"];
6225 - (UIBarButtonItem *) leftButton {
6226 return [[[UIBarButtonItem alloc]
6227 initWithTitle:UCLocalize("SETTINGS")
6228 style:UIBarButtonItemStylePlain
6230 action:@selector(settingsButtonClicked)
6234 - (void) settingsButtonClicked {
6235 [delegate_ showSettings];
6238 - (void) queueButtonClicked {
6242 - (UIBarButtonItem *) customButton {
6243 return Queuing_ ? [[[UIBarButtonItem alloc]
6244 initWithTitle:UCLocalize("QUEUE")
6245 style:UIBarButtonItemStyleDone
6247 action:@selector(queueButtonClicked)
6248 ] autorelease] : [super customButton];
6251 - (void) queueStatusDidChange {
6252 [self applyRightButton];
6255 - (bool) isLoading {
6256 return !Queuing_ && [super isLoading];
6262 /* Refresh Bar {{{ */
6263 @interface RefreshBar : UINavigationBar {
6264 _H<UIProgressIndicator> indicator_;
6265 _H<UITextLabel> prompt_;
6266 _H<UIProgressBar> progress_;
6267 _H<UINavigationButton> cancel_;
6272 @implementation RefreshBar
6274 - (void) positionViews {
6275 CGRect frame = [cancel_ frame];
6276 frame.size = [cancel_ sizeThatFits:frame.size];
6277 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6278 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6279 [cancel_ setFrame:frame];
6281 CGSize prgsize = {75, 100};
6283 [self frame].size.width - prgsize.width - 10,
6284 ([self frame].size.height - prgsize.height) / 2
6286 [progress_ setFrame:prgrect];
6288 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6289 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6290 CGRect indrect = {{indoffset, indoffset}, indsize};
6291 [indicator_ setFrame:indrect];
6293 CGSize prmsize = {215, indsize.height + 4};
6295 indoffset * 2 + indsize.width,
6296 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6298 [prompt_ setFrame:prmrect];
6301 - (void) setFrame:(CGRect)frame {
6302 [super setFrame:frame];
6303 [self positionViews];
6306 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6307 if ((self = [super initWithFrame:frame]) != nil) {
6308 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6310 [self setBarStyle:UIBarStyleBlack];
6312 UIBarStyle barstyle([self _barStyle:NO]);
6313 bool ugly(barstyle == UIBarStyleDefault);
6315 UIProgressIndicatorStyle style = ugly ?
6316 UIProgressIndicatorStyleMediumBrown :
6317 UIProgressIndicatorStyleMediumWhite;
6319 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6320 [(UIProgressIndicator *) indicator_ setStyle:style];
6321 [indicator_ startAnimation];
6322 [self addSubview:indicator_];
6324 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6325 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6326 [prompt_ setBackgroundColor:[UIColor clearColor]];
6327 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6328 [self addSubview:prompt_];
6330 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6331 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6332 [(UIProgressBar *) progress_ setStyle:0];
6333 [self addSubview:progress_];
6335 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6336 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6337 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6338 [cancel_ setBarStyle:barstyle];
6340 [self positionViews];
6344 - (void) setCancellable:(bool)cancellable {
6346 [self addSubview:cancel_];
6348 [cancel_ removeFromSuperview];
6352 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6353 [progress_ setProgress:0];
6357 [self setCancellable:NO];
6360 - (void) setPrompt:(NSString *)prompt {
6361 [prompt_ setText:prompt];
6364 - (void) setProgress:(float)progress {
6365 [progress_ setProgress:progress];
6371 /* Cydia Navigation Controller Interface {{{ */
6372 @interface UINavigationController (Cydia)
6374 - (NSArray *) navigationURLCollection;
6375 - (void) unloadData;
6380 /* Cydia Tab Bar Controller {{{ */
6381 @interface CYTabBarController : UITabBarController <
6382 UITabBarControllerDelegate,
6385 _transient Database *database_;
6386 _H<RefreshBar, 1> refreshbar_;
6390 // XXX: ok, "updatedelegate_"?...
6391 _transient NSObject<CydiaDelegate> *updatedelegate_;
6393 _H<UIViewController> remembered_;
6394 _transient UIViewController *transient_;
6397 - (NSArray *) navigationURLCollection;
6398 - (void) dropBar:(BOOL)animated;
6399 - (void) beginUpdate;
6400 - (void) raiseBar:(BOOL)animated;
6402 - (void) unloadData;
6406 @implementation CYTabBarController
6408 - (void) setUnselectedViewController:(UIViewController *)transient {
6409 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6410 if (transient != nil) {
6411 if (transient_ == nil)
6412 remembered_ = [controllers objectAtIndex:0];
6413 transient_ = transient;
6414 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6415 [controllers replaceObjectAtIndex:0 withObject:transient_];
6416 [self setSelectedIndex:0];
6417 [self setViewControllers:controllers];
6418 [self concealTabBarSelection];
6419 } else if (remembered_ != nil) {
6420 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6421 transient_ = transient;
6422 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6424 [self setViewControllers:controllers];
6425 [self revealTabBarSelection];
6429 - (UIViewController *) unselectedViewController {
6433 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6434 if ([self unselectedViewController])
6435 [self setUnselectedViewController:nil];
6438 - (NSArray *) navigationURLCollection {
6439 NSMutableArray *items([NSMutableArray array]);
6441 // XXX: Should this deal with transient view controllers?
6442 for (id navigation in [self viewControllers]) {
6443 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6445 [items addObject:stack];
6451 - (void) unloadData {
6452 UIViewController *selected([self selectedViewController]);
6453 for (UINavigationController *controller in [self viewControllers])
6454 [controller unloadData];
6456 [selected reloadData];
6458 if (UIViewController *unselected = [self unselectedViewController])
6459 [unselected reloadData];
6465 [[NSNotificationCenter defaultCenter] removeObserver:self];
6470 - (id) initWithDatabase:(Database *)database {
6471 if ((self = [super init]) != nil) {
6472 database_ = database;
6473 [self setDelegate:self];
6475 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6476 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6478 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6482 - (void) setUpdate:(NSDate *)date {
6486 - (void) beginUpdate {
6487 [(RefreshBar *) refreshbar_ start];
6490 [updatedelegate_ retainNetworkActivityIndicator];
6494 detachNewThreadSelector:@selector(performUpdate)
6500 - (void) performUpdate {
6501 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6504 status.setDelegate(self);
6505 [database_ updateWithStatus:status];
6508 performSelectorOnMainThread:@selector(completeUpdate)
6516 - (void) stopUpdateWithSelector:(SEL)selector {
6518 [updatedelegate_ releaseNetworkActivityIndicator];
6520 [self raiseBar:YES];
6523 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6526 - (void) completeUpdate {
6529 [self stopUpdateWithSelector:@selector(reloadData)];
6532 - (void) cancelUpdate {
6533 [self stopUpdateWithSelector:@selector(updateData)];
6536 - (void) cancelPressed {
6537 [self cancelUpdate];
6544 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6545 [refreshbar_ setPrompt:[event compoundMessage]];
6548 - (bool) isProgressCancelled {
6552 - (void) setProgressCancellable:(NSNumber *)cancellable {
6553 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6556 - (void) setProgressPercent:(NSNumber *)percent {
6557 [refreshbar_ setProgress:[percent floatValue]];
6560 - (void) setProgressStatus:(NSDictionary *)status {
6562 [self setProgressPercent:[status objectForKey:@"Percent"]];
6565 - (void) setUpdateDelegate:(id)delegate {
6566 updatedelegate_ = delegate;
6569 - (CGFloat) statusBarHeight {
6570 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6571 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6573 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6577 - (UIView *) transitionView {
6578 if ([self respondsToSelector:@selector(_transitionView)])
6579 return [self _transitionView];
6581 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6584 - (void) dropBar:(BOOL)animated {
6589 UIView *transition([self transitionView]);
6590 [[self view] addSubview:refreshbar_];
6592 CGRect barframe([refreshbar_ frame]);
6594 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6595 barframe.origin.y = [self statusBarHeight];
6597 barframe.origin.y = 0;
6599 [refreshbar_ setFrame:barframe];
6602 [UIView beginAnimations:nil context:NULL];
6604 CGRect viewframe = [transition frame];
6605 viewframe.origin.y += barframe.size.height;
6606 viewframe.size.height -= barframe.size.height;
6607 [transition setFrame:viewframe];
6610 [UIView commitAnimations];
6612 // Ensure bar has the proper width for our view, it might have changed
6613 barframe.size.width = viewframe.size.width;
6614 [refreshbar_ setFrame:barframe];
6617 - (void) raiseBar:(BOOL)animated {
6622 UIView *transition([self transitionView]);
6623 [refreshbar_ removeFromSuperview];
6625 CGRect barframe([refreshbar_ frame]);
6628 [UIView beginAnimations:nil context:NULL];
6630 CGRect viewframe = [transition frame];
6631 viewframe.origin.y -= barframe.size.height;
6632 viewframe.size.height += barframe.size.height;
6633 [transition setFrame:viewframe];
6636 [UIView commitAnimations];
6639 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6640 bool dropped(dropped_);
6645 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6651 - (void) statusBarFrameChanged:(NSNotification *)notification {
6661 /* Cydia Navigation Controller Implementation {{{ */
6662 @implementation UINavigationController (Cydia)
6664 - (NSArray *) navigationURLCollection {
6665 NSMutableArray *stack([NSMutableArray array]);
6667 for (CyteViewController *controller in [self viewControllers]) {
6668 NSString *url = [[controller navigationURL] absoluteString];
6670 [stack addObject:url];
6676 - (void) reloadData {
6679 if (UIViewController *visible = [self visibleViewController])
6680 [visible reloadData];
6683 - (void) unloadData {
6684 for (CyteViewController *page in [self viewControllers])
6693 /* Cydia:// Protocol {{{ */
6694 @interface CydiaURLProtocol : NSURLProtocol {
6699 @implementation CydiaURLProtocol
6701 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6702 NSURL *url([request URL]);
6706 NSString *scheme([[url scheme] lowercaseString]);
6707 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6709 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6715 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6719 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6720 id<NSURLProtocolClient> client([self client]);
6722 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6724 NSData *data(UIImagePNGRepresentation(icon));
6726 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6727 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6728 [client URLProtocol:self didLoadData:data];
6729 [client URLProtocolDidFinishLoading:self];
6733 - (void) startLoading {
6734 id<NSURLProtocolClient> client([self client]);
6735 NSURLRequest *request([self request]);
6737 NSURL *url([request URL]);
6738 NSString *href([url absoluteString]);
6739 NSString *scheme([[url scheme] lowercaseString]);
6743 if ([scheme isEqualToString:@"cydia"])
6744 path = [href substringFromIndex:8];
6745 else if ([scheme isEqualToString:@"about"])
6746 path = [href substringFromIndex:12];
6747 else _assert(false);
6749 NSRange slash([path rangeOfString:@"/"]);
6752 if (slash.location == NSNotFound) {
6756 command = [path substringToIndex:slash.location];
6757 path = [path substringFromIndex:(slash.location + 1)];
6760 Database *database([Database sharedInstance]);
6762 if ([command isEqualToString:@"package-icon"]) {
6765 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6766 Package *package([database packageWithName:path]);
6770 UIImage *icon([package icon]);
6771 [self _returnPNGWithImage:icon forRequest:request];
6772 } else if ([command isEqualToString:@"source-icon"]) {
6775 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6776 NSString *source(Simplify(path));
6777 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6779 icon = [UIImage applicationImageNamed:@"unknown.png"];
6780 [self _returnPNGWithImage:icon forRequest:request];
6781 } else if ([command isEqualToString:@"uikit-image"]) {
6784 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6785 UIImage *icon(_UIImageWithName(path));
6786 [self _returnPNGWithImage:icon forRequest:request];
6787 } else if ([command isEqualToString:@"section-icon"]) {
6790 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6791 NSString *section(Simplify(path));
6792 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6794 icon = [UIImage applicationImageNamed:@"unknown.png"];
6795 [self _returnPNGWithImage:icon forRequest:request];
6797 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6801 - (void) stopLoading {
6807 /* Section Controller {{{ */
6808 @interface SectionController : FilteredPackageListController {
6809 _H<NSString> section_;
6812 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6816 @implementation SectionController
6818 - (NSURL *) navigationURL {
6819 NSString *name = section_;
6823 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6826 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6829 title = UCLocalize("ALL_PACKAGES");
6830 else if (![name isEqual:@""])
6831 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6833 title = UCLocalize("NO_SECTION");
6835 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6842 /* Sections Controller {{{ */
6843 @interface SectionsController : CyteViewController <
6844 UITableViewDataSource,
6847 _transient Database *database_;
6848 _H<NSMutableArray> sections_;
6849 _H<NSMutableArray> filtered_;
6850 _H<UITableView, 2> list_;
6853 - (id) initWithDatabase:(Database *)database;
6854 - (void) editButtonClicked;
6858 @implementation SectionsController
6860 - (NSURL *) navigationURL {
6861 return [NSURL URLWithString:@"cydia://sections"];
6864 - (void) updateNavigationItem {
6865 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6866 if ([sections_ count] == 0) {
6867 [[self navigationItem] setRightBarButtonItem:nil];
6869 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6870 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6872 action:@selector(editButtonClicked)
6873 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6877 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6878 [super setEditing:editing animated:animated];
6883 [delegate_ updateData];
6885 [self updateNavigationItem];
6888 - (void) viewDidAppear:(BOOL)animated {
6889 [super viewDidAppear:animated];
6890 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6893 - (void) viewWillDisappear:(BOOL)animated {
6894 [super viewWillDisappear:animated];
6895 if ([self isEditing]) [self setEditing:NO];
6898 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6899 Section *section = nil;
6900 int index = [indexPath row];
6901 if (![self isEditing]) {
6904 section = [filtered_ objectAtIndex:index];
6906 section = [sections_ objectAtIndex:index];
6911 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6912 if ([self isEditing])
6913 return [sections_ count];
6915 return [filtered_ count] + 1;
6918 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6922 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6923 static NSString *reuseIdentifier = @"SectionCell";
6925 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6927 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6929 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6934 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6935 if ([self isEditing])
6938 Section *section = [self sectionAtIndexPath:indexPath];
6940 SectionController *controller = [[[SectionController alloc]
6941 initWithDatabase:database_
6942 section:[section name]
6944 [controller setDelegate:delegate_];
6946 [[self navigationController] pushViewController:controller animated:YES];
6950 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6952 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6953 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6954 [list_ setRowHeight:45.0f];
6955 [(UITableView *) list_ setDataSource:self];
6956 [list_ setDelegate:self];
6957 [[self view] addSubview:list_];
6960 - (void) viewDidLoad {
6961 [super viewDidLoad];
6963 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6966 - (void) releaseSubviews {
6970 - (id) initWithDatabase:(Database *)database {
6971 if ((self = [super init]) != nil) {
6972 database_ = database;
6974 sections_ = [NSMutableArray arrayWithCapacity:16];
6975 filtered_ = [NSMutableArray arrayWithCapacity:16];
6979 - (void) reloadData {
6982 NSArray *packages = [database_ packages];
6984 [sections_ removeAllObjects];
6985 [filtered_ removeAllObjects];
6987 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6990 for (Package *package in packages) {
6991 NSString *name([package section]);
6992 NSString *key(name == nil ? @"" : name);
6996 _profile(SectionsView$reloadData$Section)
6997 section = [sections objectForKey:key];
6998 if (section == nil) {
6999 _profile(SectionsView$reloadData$Section$Allocate)
7000 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7001 [sections setObject:section forKey:key];
7006 [section addToCount];
7008 _profile(SectionsView$reloadData$Filter)
7009 if (![package valid] || ![package visible])
7017 [sections_ addObjectsFromArray:[sections allValues]];
7019 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7021 for (Section *section in (id) sections_) {
7022 size_t count([section row]);
7026 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7027 [section setCount:count];
7028 [filtered_ addObject:section];
7031 [self updateNavigationItem];
7036 - (void) editButtonClicked {
7037 [self setEditing:![self isEditing] animated:YES];
7043 /* Changes Controller {{{ */
7044 @interface ChangesController : CyteViewController <
7045 UITableViewDataSource,
7048 _transient Database *database_;
7050 _H<NSArray> packages_;
7051 _H<NSMutableArray> sections_;
7052 _H<UITableView, 2> list_;
7056 - (id) initWithDatabase:(Database *)database;
7060 @implementation ChangesController
7062 - (NSURL *) navigationURL {
7063 return [NSURL URLWithString:@"cydia://changes"];
7066 - (void) viewDidAppear:(BOOL)animated {
7067 [super viewDidAppear:animated];
7068 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7071 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7072 NSInteger count([sections_ count]);
7073 return count == 0 ? 1 : count;
7076 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7077 if ([sections_ count] == 0)
7079 return [[sections_ objectAtIndex:section] name];
7082 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7083 if ([sections_ count] == 0)
7085 return [[sections_ objectAtIndex:section] count];
7088 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7089 @synchronized (database_) {
7090 if ([database_ era] != era_)
7093 NSUInteger sectionIndex([path section]);
7094 if (sectionIndex >= [sections_ count])
7096 Section *section([sections_ objectAtIndex:sectionIndex]);
7097 NSInteger row([path row]);
7098 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7101 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7102 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7104 cell = [[[PackageCell alloc] init] autorelease];
7105 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7109 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7110 Package *package([self packageAtIndexPath:path]);
7111 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7112 [view setDelegate:delegate_];
7113 [[self navigationController] pushViewController:view animated:YES];
7117 - (void) refreshButtonClicked {
7118 [delegate_ beginUpdate];
7119 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7122 - (void) upgradeButtonClicked {
7123 [delegate_ distUpgrade];
7127 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7129 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7130 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7131 [list_ setRowHeight:73];
7132 [(UITableView *) list_ setDataSource:self];
7133 [list_ setDelegate:self];
7134 [[self view] addSubview:list_];
7137 - (void) viewDidLoad {
7138 [super viewDidLoad];
7140 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7143 - (void) releaseSubviews {
7147 - (id) initWithDatabase:(Database *)database {
7148 if ((self = [super init]) != nil) {
7149 database_ = database;
7151 packages_ = [NSArray array];
7152 sections_ = [NSMutableArray arrayWithCapacity:16];
7156 - (NSArray *) _reloadPackages:(NSArray *)packages {
7157 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7160 _profile(ChangesController$_reloadPackages$Filter)
7161 for (Package *package in packages)
7162 if ([package upgradableAndEssential:YES] || [package visible])
7163 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7166 _profile(ChangesController$_reloadPackages$radixSort)
7167 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7174 - (void) _reloadData {
7175 @synchronized (database_) {
7176 era_ = [database_ era];
7177 NSArray *packages = [database_ packages];
7180 UIProgressHUD *hud([delegate_ addProgressHUD]);
7181 [hud setText:UCLocalize("LOADING")];
7182 //NSLog(@"HUD:%@::%@", delegate_, hud);
7183 packages_ = [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7184 [delegate_ removeProgressHUD:hud];
7186 packages_ = [self _reloadPackages:packages];
7189 [sections_ removeAllObjects];
7191 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7192 Section *ignored = nil;
7193 Section *section = nil;
7197 bool unseens = false;
7199 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7201 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7202 Package *package = [packages_ objectAtIndex:offset];
7204 BOOL uae = [package upgradableAndEssential:YES];
7208 time_t seen([package seen]);
7210 if (section == nil || last != seen) {
7214 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7217 _profile(ChangesController$reloadData$Allocate)
7218 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7219 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7220 [sections_ addObject:section];
7224 [section addToCount];
7225 } else if ([package ignored]) {
7226 if (ignored == nil) {
7227 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7229 [ignored addToCount];
7232 [upgradable addToCount];
7237 CFRelease(formatter);
7240 Section *last = [sections_ lastObject];
7241 size_t count = [last count];
7242 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7243 [sections_ removeLastObject];
7246 if ([ignored count] != 0)
7247 [sections_ insertObject:ignored atIndex:0];
7249 [sections_ insertObject:upgradable atIndex:0];
7254 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7255 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7256 style:UIBarButtonItemStylePlain
7258 action:@selector(upgradeButtonClicked)
7261 if (![delegate_ updating])
7262 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7263 initWithTitle:UCLocalize("REFRESH")
7264 style:UIBarButtonItemStylePlain
7266 action:@selector(refreshButtonClicked)
7272 - (void) reloadData {
7274 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7279 /* Search Controller {{{ */
7280 @interface SearchController : FilteredPackageListController <
7283 _H<UISearchBar, 1> search_;
7287 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7288 - (void) reloadData;
7292 @implementation SearchController
7294 - (NSURL *) navigationURL {
7295 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7296 return [NSURL URLWithString:@"cydia://search"];
7298 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7301 - (void) useSearch {
7302 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7307 - (void) viewWillAppear:(BOOL)animated {
7308 [super viewWillAppear:animated];
7310 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7314 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7315 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7320 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7321 [search_ resignFirstResponder];
7325 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7326 [search_ setText:@""];
7327 [self searchBarButtonClicked:searchBar];
7330 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7331 [self searchBarButtonClicked:searchBar];
7334 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7335 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7339 - (bool) shouldYield {
7343 - (bool) shouldBlock {
7344 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7347 - (bool) isSummarized {
7348 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7351 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7352 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7353 search_ = [[[UISearchBar alloc] init] autorelease];
7354 [search_ setDelegate:self];
7357 [search_ setText:query];
7361 - (void) viewDidAppear:(BOOL)animated {
7362 [super viewDidAppear:animated];
7364 if (!searchloaded_) {
7365 searchloaded_ = YES;
7366 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7367 [search_ layoutSubviews];
7368 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7370 UITextField *textField;
7371 if ([search_ respondsToSelector:@selector(searchField)])
7372 textField = [search_ searchField];
7374 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7376 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7377 [textField setEnablesReturnKeyAutomatically:NO];
7378 [[self navigationItem] setTitleView:textField];
7382 - (void) reloadData {
7383 [self setObject:[search_ text]];
7389 - (void) didSelectPackage:(Package *)package {
7390 [search_ resignFirstResponder];
7391 [super didSelectPackage:package];
7396 /* Package Settings Controller {{{ */
7397 @interface PackageSettingsController : CyteViewController <
7398 UITableViewDataSource,
7401 _transient Database *database_;
7403 _H<Package> package_;
7404 _H<UITableView, 2> table_;
7405 _H<UISwitch> subscribedSwitch_;
7406 _H<UISwitch> ignoredSwitch_;
7407 _H<UITableViewCell> subscribedCell_;
7408 _H<UITableViewCell> ignoredCell_;
7411 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7415 @implementation PackageSettingsController
7417 - (NSURL *) navigationURL {
7418 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7421 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7422 if (package_ == nil)
7425 if ([package_ installed] == nil)
7431 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7432 if (package_ == nil)
7435 // both sections contain just one item right now.
7439 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7443 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7445 return UCLocalize("SHOW_ALL_CHANGES_EX");
7447 return UCLocalize("IGNORE_UPGRADES_EX");
7450 - (void) onSubscribed:(id)control {
7451 bool value([control isOn]);
7452 if (package_ == nil)
7454 if ([package_ setSubscribed:value])
7455 [delegate_ updateData];
7458 - (void) _updateIgnored {
7459 const char *package([name_ UTF8String]);
7460 bool on([ignoredSwitch_ isOn]);
7462 pid_t pid(ExecFork());
7464 FILE *dpkg(popen("dpkg --set-selections", "w"));
7465 fwrite(package, strlen(package), 1, dpkg);
7468 fwrite(" hold\n", 6, 1, dpkg);
7470 fwrite(" install\n", 9, 1, dpkg);
7480 int result(waitpid(pid, &status, 0));
7483 _assert(result == pid);
7489 - (void) onIgnored:(id)control {
7490 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7491 [invocation setTarget:self];
7492 [invocation setSelector:@selector(_updateIgnored)];
7494 [delegate_ reloadDataWithInvocation:invocation];
7497 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7498 if (package_ == nil)
7501 switch ([indexPath section]) {
7502 case 0: return subscribedCell_;
7503 case 1: return ignoredCell_;
7512 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7514 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7515 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7516 [(UITableView *) table_ setDataSource:self];
7517 [table_ setDelegate:self];
7518 [[self view] addSubview:table_];
7520 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7521 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7522 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7524 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7525 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7526 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7528 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7529 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7530 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7531 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7533 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7534 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7535 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7536 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7539 - (void) viewDidLoad {
7540 [super viewDidLoad];
7542 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7545 - (void) releaseSubviews {
7547 subscribedCell_ = nil;
7549 ignoredSwitch_ = nil;
7550 subscribedSwitch_ = nil;
7553 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7554 if ((self = [super init]) != nil) {
7555 database_ = database;
7560 - (void) reloadData {
7563 package_ = [database_ packageWithName:name_];
7565 if (package_ != nil) {
7566 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7567 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7568 } // XXX: what now, G?
7570 [table_ reloadData];
7576 /* Installed Controller {{{ */
7577 @interface InstalledController : FilteredPackageListController {
7581 - (id) initWithDatabase:(Database *)database;
7583 - (void) updateRoleButton;
7584 - (void) queueStatusDidChange;
7588 @implementation InstalledController
7590 - (NSURL *) navigationURL {
7591 return [NSURL URLWithString:@"cydia://installed"];
7594 - (id) initWithDatabase:(Database *)database {
7595 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7596 [self updateRoleButton];
7597 [self queueStatusDidChange];
7602 - (void) queueButtonClicked {
7607 - (void) queueStatusDidChange {
7611 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7612 initWithTitle:UCLocalize("QUEUE")
7613 style:UIBarButtonItemStyleDone
7615 action:@selector(queueButtonClicked)
7618 [[self navigationItem] setLeftBarButtonItem:nil];
7624 - (void) updateRoleButton {
7625 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7626 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7627 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7628 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7630 action:@selector(roleButtonClicked)
7634 - (void) roleButtonClicked {
7635 [self setObject:[NSNumber numberWithBool:expert_]];
7639 [self updateRoleButton];
7645 /* Source Cell {{{ */
7646 @interface SourceCell : CyteTableViewCell <
7647 CyteTableViewCellDelegate
7650 _H<NSString> origin_;
7651 _H<NSString> label_;
7654 - (void) setSource:(Source *)source;
7658 @implementation SourceCell
7660 - (void) _setImage:(UIImage *)image {
7662 [content_ setNeedsDisplay];
7665 - (void) _setSource:(Source *)source {
7666 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7668 if (NSString *base = [source base])
7669 if ([base length] != 0) {
7670 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7672 if (NSData *data = [NSURLConnection
7673 sendSynchronousRequest:[NSURLRequest
7675 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7679 returningResponse:NULL
7682 if (UIImage *image = [UIImage imageWithData:data])
7683 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7689 - (void) setSource:(Source *)source {
7690 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7692 origin_ = [source name];
7693 label_ = [source uri];
7695 [content_ setNeedsDisplay];
7697 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7700 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7701 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7702 UIView *content([self contentView]);
7703 CGRect bounds([content bounds]);
7705 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7706 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7707 [content_ setBackgroundColor:[UIColor whiteColor]];
7708 [content addSubview:content_];
7710 [content_ setDelegate:self];
7711 [content_ setOpaque:YES];
7715 - (NSString *) accessibilityLabel {
7719 - (void) drawContentRect:(CGRect)rect {
7720 bool highlighted(highlighted_);
7721 float width(rect.size.width);
7724 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7731 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7735 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7740 /* Source Controller {{{ */
7741 @interface SourceController : FilteredPackageListController {
7742 _transient Source *source_;
7746 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7750 @implementation SourceController
7752 - (NSURL *) navigationURL {
7753 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7756 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7757 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7759 key_ = [source key];
7763 - (void) reloadData {
7764 source_ = [database_ sourceWithKey:key_];
7765 key_ = [source_ key];
7766 [self setObject:source_];
7768 [[self navigationItem] setTitle:[source_ label]];
7775 /* Sources Controller {{{ */
7776 @interface SourcesController : CyteViewController <
7777 UITableViewDataSource,
7780 _transient Database *database_;
7781 _H<UITableView, 2> list_;
7782 _H<NSMutableArray> sources_;
7786 _H<UIProgressHUD> hud_;
7789 //NSURLConnection *installer_;
7790 NSURLConnection *trivial_;
7791 NSURLConnection *trivial_bz2_;
7792 NSURLConnection *trivial_gz_;
7793 //NSURLConnection *automatic_;
7798 - (id) initWithDatabase:(Database *)database;
7799 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7803 @implementation SourcesController
7805 - (void) _releaseConnection:(NSURLConnection *)connection {
7806 if (connection != nil) {
7807 [connection cancel];
7808 //[connection setDelegate:nil];
7809 [connection release];
7814 //[self _releaseConnection:installer_];
7815 [self _releaseConnection:trivial_];
7816 [self _releaseConnection:trivial_gz_];
7817 [self _releaseConnection:trivial_bz2_];
7818 //[self _releaseConnection:automatic_];
7823 - (NSURL *) navigationURL {
7824 return [NSURL URLWithString:@"cydia://sources"];
7827 - (void) viewDidAppear:(BOOL)animated {
7828 [super viewDidAppear:animated];
7829 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7832 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7833 return offset_ == 0 ? 1 : 2;
7836 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7837 switch (section + (offset_ == 0 ? 1 : 0)) {
7838 case 0: return UCLocalize("ENTERED_BY_USER");
7839 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7845 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7846 int count = [sources_ count];
7848 case 0: return (offset_ == 0 ? count : offset_);
7849 case 1: return count - offset_;
7855 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7857 switch (indexPath.section) {
7858 case 0: idx = indexPath.row; break;
7859 case 1: idx = indexPath.row + offset_; break;
7863 return [sources_ objectAtIndex:idx];
7866 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7867 static NSString *cellIdentifier = @"SourceCell";
7869 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7870 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7871 [cell setSource:[self sourceAtIndexPath:indexPath]];
7872 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7877 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7878 Source *source = [self sourceAtIndexPath:indexPath];
7880 SourceController *controller = [[[SourceController alloc]
7881 initWithDatabase:database_
7885 [controller setDelegate:delegate_];
7887 [[self navigationController] pushViewController:controller animated:YES];
7890 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7891 Source *source = [self sourceAtIndexPath:indexPath];
7892 return [source record] != nil;
7895 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7896 if (editingStyle == UITableViewCellEditingStyleDelete) {
7897 Source *source = [self sourceAtIndexPath:indexPath];
7898 [Sources_ removeObjectForKey:[source key]];
7899 [delegate_ syncData];
7904 [delegate_ addTrivialSource:href_];
7905 [delegate_ syncData];
7908 - (NSString *) getWarning {
7909 NSString *href(href_);
7910 NSRange colon([href rangeOfString:@"://"]);
7911 if (colon.location != NSNotFound)
7912 href = [href substringFromIndex:(colon.location + 3)];
7913 href = [href stringByAddingPercentEscapes];
7914 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7915 href = [href stringByCachingURLWithCurrentCDN];
7917 NSURL *url([NSURL URLWithString:href]);
7919 NSStringEncoding encoding;
7920 NSError *error(nil);
7922 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7923 return [warning length] == 0 ? nil : warning;
7927 - (void) _endConnection:(NSURLConnection *)connection {
7928 // XXX: the memory management in this method is horribly awkward
7930 NSURLConnection **field = NULL;
7931 if (connection == trivial_)
7933 else if (connection == trivial_bz2_)
7934 field = &trivial_bz2_;
7935 else if (connection == trivial_gz_)
7936 field = &trivial_gz_;
7937 _assert(field != NULL);
7938 [connection release];
7943 trivial_bz2_ == nil &&
7946 [delegate_ releaseNetworkActivityIndicator];
7948 [delegate_ removeProgressHUD:hud_];
7954 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7957 UIAlertView *alert = [[[UIAlertView alloc]
7958 initWithTitle:UCLocalize("SOURCE_WARNING")
7961 cancelButtonTitle:UCLocalize("CANCEL")
7963 UCLocalize("ADD_ANYWAY"),
7967 [alert setContext:@"warning"];
7968 [alert setNumberOfRows:1];
7972 } else if (error_ != nil) {
7973 UIAlertView *alert = [[[UIAlertView alloc]
7974 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7975 message:[error_ localizedDescription]
7977 cancelButtonTitle:UCLocalize("OK")
7978 otherButtonTitles:nil
7981 [alert setContext:@"urlerror"];
7984 UIAlertView *alert = [[[UIAlertView alloc]
7985 initWithTitle:UCLocalize("NOT_REPOSITORY")
7986 message:UCLocalize("NOT_REPOSITORY_EX")
7988 cancelButtonTitle:UCLocalize("OK")
7989 otherButtonTitles:nil
7992 [alert setContext:@"trivial"];
8001 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8002 switch ([response statusCode]) {
8008 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8009 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8011 [self _endConnection:connection];
8014 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8015 [self _endConnection:connection];
8018 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8019 NSMutableURLRequest *request = [NSMutableURLRequest
8020 requestWithURL:[NSURL URLWithString:href]
8021 cachePolicy:NSURLRequestUseProtocolCachePolicy
8022 timeoutInterval:120.0
8025 [request setHTTPMethod:method];
8027 if (Machine_ != NULL)
8028 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8029 if (UniqueID_ != nil)
8030 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8032 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8035 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8036 NSString *context([alert context]);
8038 if ([context isEqualToString:@"source"]) {
8041 NSString *href = [[alert textField] text];
8043 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8045 if (![href hasSuffix:@"/"])
8046 href_ = [href stringByAppendingString:@"/"];
8050 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8051 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8052 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8053 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8057 // XXX: this is stupid
8058 hud_ = [delegate_ addProgressHUD];
8059 [hud_ setText:UCLocalize("VERIFYING_URL")];
8060 [delegate_ retainNetworkActivityIndicator];
8069 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8070 } else if ([context isEqualToString:@"trivial"])
8071 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8072 else if ([context isEqualToString:@"urlerror"])
8073 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8074 else if ([context isEqualToString:@"warning"]) {
8088 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8093 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8095 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8096 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8097 [list_ setRowHeight:56];
8098 [(UITableView *) list_ setDataSource:self];
8099 [list_ setDelegate:self];
8100 [[self view] addSubview:list_];
8103 - (void) viewDidLoad {
8104 [super viewDidLoad];
8106 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8107 [self updateButtonsForEditingStatus:NO animated:NO];
8110 - (void) releaseSubviews {
8114 - (id) initWithDatabase:(Database *)database {
8115 if ((self = [super init]) != nil) {
8116 database_ = database;
8117 sources_ = [NSMutableArray arrayWithCapacity:16];
8121 - (void) reloadData {
8125 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8128 [sources_ removeAllObjects];
8129 [sources_ addObjectsFromArray:[database_ sources]];
8131 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8134 int count([sources_ count]);
8136 for (int i = 0; i != count; i++) {
8137 if ([[sources_ objectAtIndex:i] record] == nil)
8142 [list_ setEditing:NO];
8143 [self updateButtonsForEditingStatus:NO animated:NO];
8147 - (void) showAddSourcePrompt {
8148 UIAlertView *alert = [[[UIAlertView alloc]
8149 initWithTitle:UCLocalize("ENTER_APT_URL")
8152 cancelButtonTitle:UCLocalize("CANCEL")
8154 UCLocalize("ADD_SOURCE"),
8158 [alert setContext:@"source"];
8160 [alert setNumberOfRows:1];
8161 [alert addTextFieldWithValue:@"http://" label:@""];
8163 UITextInputTraits *traits = [[alert textField] textInputTraits];
8164 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8165 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8166 [traits setKeyboardType:UIKeyboardTypeURL];
8167 // XXX: UIReturnKeyDone
8168 [traits setReturnKeyType:UIReturnKeyNext];
8173 - (void) addButtonClicked {
8174 [self showAddSourcePrompt];
8177 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8178 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8179 initWithTitle:UCLocalize("ADD")
8180 style:UIBarButtonItemStylePlain
8182 action:@selector(addButtonClicked)
8183 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8185 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8186 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8187 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8189 action:@selector(editButtonClicked)
8190 ] autorelease] animated:animated];
8192 if (IsWildcat_ && !editing)
8193 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8194 initWithTitle:UCLocalize("SETTINGS")
8195 style:UIBarButtonItemStylePlain
8197 action:@selector(settingsButtonClicked)
8201 - (void) settingsButtonClicked {
8202 [delegate_ showSettings];
8205 - (void) editButtonClicked {
8206 [list_ setEditing:![list_ isEditing] animated:YES];
8208 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8214 /* Settings Controller {{{ */
8215 @interface SettingsController : CyteViewController <
8216 UITableViewDataSource,
8219 _transient Database *database_;
8220 // XXX: ok, "roledelegate_"?...
8221 _transient id roledelegate_;
8222 _H<UITableView, 2> table_;
8223 _H<UISegmentedControl> segment_;
8224 _H<UIView> container_;
8227 - (void) showDoneButton;
8228 - (void) resizeSegmentedControl;
8232 @implementation SettingsController
8235 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8237 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8238 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8239 [table_ setDelegate:self];
8240 [(UITableView *) table_ setDataSource:self];
8241 [[self view] addSubview:table_];
8243 NSArray *items = [NSArray arrayWithObjects:
8245 UCLocalize("HACKER"),
8246 UCLocalize("DEVELOPER"),
8248 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8249 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8250 [container_ addSubview:segment_];
8253 - (void) viewDidLoad {
8254 [super viewDidLoad];
8256 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8259 if ([Role_ isEqualToString:@"User"]) index = 0;
8260 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8261 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8263 [segment_ setSelectedSegmentIndex:index];
8264 [self showDoneButton];
8267 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8268 [self resizeSegmentedControl];
8271 - (void) releaseSubviews {
8277 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8278 if ((self = [super init]) != nil) {
8279 database_ = database;
8280 roledelegate_ = delegate;
8284 - (void) resizeSegmentedControl {
8285 CGFloat width = [[self view] frame].size.width;
8286 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8289 - (void) viewWillAppear:(BOOL)animated {
8290 [super viewWillAppear:animated];
8292 [self resizeSegmentedControl];
8295 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8296 [self resizeSegmentedControl];
8299 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8300 [self resizeSegmentedControl];
8304 NSString *role(nil);
8306 switch ([segment_ selectedSegmentIndex]) {
8307 case 0: role = @"User"; break;
8308 case 1: role = @"Hacker"; break;
8309 case 2: role = @"Developer"; break;
8314 if (![role isEqualToString:Role_]) {
8315 bool rolling(Role_ == nil);
8318 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8322 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8326 [roledelegate_ loadData];
8328 [roledelegate_ updateData];
8332 - (void) segmentChanged:(UISegmentedControl *)control {
8333 [self showDoneButton];
8336 - (void) saveAndClose {
8339 [[self navigationItem] setRightBarButtonItem:nil];
8340 [[self navigationController] dismissModalViewControllerAnimated:YES];
8343 - (void) doneButtonClicked {
8344 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8345 [spinner startAnimating];
8346 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8347 [[self navigationItem] setRightBarButtonItem:spinItem];
8349 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8352 - (void) showDoneButton {
8353 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8354 initWithTitle:UCLocalize("DONE")
8355 style:UIBarButtonItemStyleDone
8357 action:@selector(doneButtonClicked)
8358 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8361 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8362 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8366 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8370 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8371 return nil; // This method is required by the protocol.
8374 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8376 return UCLocalize("ROLE_EX");
8378 return [NSString stringWithFormat:
8379 @"%@: %@\n%@: %@\n%@: %@",
8380 UCLocalize("USER"), UCLocalize("USER_EX"),
8381 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8382 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8387 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8388 return section == 3 ? 44.0f : 0;
8391 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8392 return section == 3 ? container_ : nil;
8395 - (void) reloadData {
8398 [table_ reloadData];
8403 /* Stash Controller {{{ */
8404 @interface StashController : CyteViewController {
8405 _H<UIActivityIndicatorView> spinner_;
8406 _H<UILabel> status_;
8407 _H<UILabel> caption_;
8412 @implementation StashController
8415 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8416 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8418 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8419 CGRect spinrect = [spinner_ frame];
8420 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8421 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8422 [spinner_ setFrame:spinrect];
8423 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8424 [[self view] addSubview:spinner_];
8425 [spinner_ startAnimating];
8428 captrect.size.width = [[self view] frame].size.width;
8429 captrect.size.height = 40.0f;
8430 captrect.origin.x = 0;
8431 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8432 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8433 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8434 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8435 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8436 [caption_ setTextColor:[UIColor whiteColor]];
8437 [caption_ setBackgroundColor:[UIColor clearColor]];
8438 [caption_ setShadowColor:[UIColor blackColor]];
8439 [caption_ setTextAlignment:UITextAlignmentCenter];
8440 [[self view] addSubview:caption_];
8443 statusrect.size.width = [[self view] frame].size.width;
8444 statusrect.size.height = 30.0f;
8445 statusrect.origin.x = 0;
8446 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8447 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8448 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8449 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8450 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8451 [status_ setTextColor:[UIColor whiteColor]];
8452 [status_ setBackgroundColor:[UIColor clearColor]];
8453 [status_ setShadowColor:[UIColor blackColor]];
8454 [status_ setTextAlignment:UITextAlignmentCenter];
8455 [[self view] addSubview:status_];
8461 @interface CYURLCache : SDURLCache {
8466 @implementation CYURLCache
8468 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8471 else if ([event isEqualToString:@"no-cache"])
8473 else if ([event isEqualToString:@"store"])
8475 else if ([event isEqualToString:@"invalid"])
8477 else if ([event isEqualToString:@"memory"])
8479 else if ([event isEqualToString:@"disk"])
8481 else if ([event isEqualToString:@"miss"])
8484 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8490 @interface Cydia : UIApplication <
8491 ConfirmationControllerDelegate,
8494 UINavigationControllerDelegate,
8495 UITabBarControllerDelegate
8497 _H<UIWindow> window_;
8498 _H<CYTabBarController> tabbar_;
8499 _H<CYEmulatedLoadingController> emulated_;
8501 _H<NSMutableArray> essential_;
8502 _H<NSMutableArray> broken_;
8504 Database *database_;
8506 _H<NSURL> starturl_;
8511 _H<StashController> stash_;
8520 @implementation Cydia
8522 - (void) beginUpdate {
8523 [tabbar_ beginUpdate];
8527 return [tabbar_ updating];
8531 if ([broken_ count] != 0) {
8532 int count = [broken_ count];
8534 UIAlertView *alert = [[[UIAlertView alloc]
8535 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8536 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8538 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8540 UCLocalize("TEMPORARY_IGNORE"),
8544 [alert setContext:@"fixhalf"];
8545 [alert setNumberOfRows:2];
8547 } else if (!Ignored_ && [essential_ count] != 0) {
8548 int count = [essential_ count];
8550 UIAlertView *alert = [[[UIAlertView alloc]
8551 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8552 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8554 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8556 UCLocalize("UPGRADE_ESSENTIAL"),
8557 UCLocalize("COMPLETE_UPGRADE"),
8561 [alert setContext:@"upgrade"];
8566 - (void) _saveConfig {
8572 NSString *error(nil);
8574 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8576 NSError *error(nil);
8577 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8578 NSLog(@"failure to save metadata data: %@", error);
8583 NSLog(@"failure to serialize metadata: %@", error);
8588 // Navigation controller for the queuing badge.
8589 - (UINavigationController *) queueNavigationController {
8590 NSArray *controllers = [tabbar_ viewControllers];
8591 return [controllers objectAtIndex:3];
8594 - (void) unloadData {
8595 [tabbar_ unloadData];
8598 - (void) _updateData {
8603 UINavigationController *navigation = [self queueNavigationController];
8605 id queuedelegate = nil;
8606 if ([[navigation viewControllers] count] > 0)
8607 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8609 [queuedelegate queueStatusDidChange];
8610 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8613 - (void) _refreshIfPossible:(NSDate *)update {
8614 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8616 bool recently = false;
8617 if (update != nil) {
8618 NSTimeInterval interval([update timeIntervalSinceNow]);
8619 if (interval <= 0 && interval > -(15*60))
8623 // Don't automatic refresh if:
8624 // - We already refreshed recently.
8625 // - We already auto-refreshed this launch.
8626 // - Auto-refresh is disabled.
8627 if (recently || loaded_ || ManualRefresh) {
8628 // If we are cancelling, we need to make sure it knows it's already loaded.
8631 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8633 // We are going to load, so remember that.
8636 SCNetworkReachabilityFlags flags; {
8637 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8638 SCNetworkReachabilityGetFlags(reachability, &flags);
8639 CFRelease(reachability);
8642 // XXX: this elaborate mess is what Apple is using to determine this? :(
8643 // XXX: do we care if the user has to intervene? maybe that's ok?
8645 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8646 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8647 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8648 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8649 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8650 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8654 // If we can reach the server, auto-refresh!
8656 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8662 - (void) refreshIfPossible {
8663 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8666 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8667 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8668 [hud setText:UCLocalize("RELOADING_DATA")];
8670 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8673 [self removeProgressHUD:hud];
8677 [essential_ removeAllObjects];
8678 [broken_ removeAllObjects];
8680 NSArray *packages([database_ packages]);
8681 for (Package *package in packages) {
8683 [broken_ addObject:package];
8684 if ([package upgradableAndEssential:NO]) {
8685 if ([package essential])
8686 [essential_ addObject:package];
8691 NSLog(@"changes:#%u", changes);
8693 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8696 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8697 [changesItem setBadgeValue:badge];
8698 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8699 [self setApplicationIconBadgeNumber:changes];
8702 [changesItem setBadgeValue:nil];
8703 [changesItem setAnimatedBadge:NO];
8704 [self setApplicationIconBadgeNumber:0];
8709 [self refreshIfPossible];
8712 - (void) updateData {
8721 @synchronized (self) {
8722 [self _reloadDataWithInvocation:nil];
8726 - (void) disemulate {
8727 if (emulated_ == nil)
8730 [window_ addSubview:[tabbar_ view]];
8731 [[emulated_ view] removeFromSuperview];
8733 [window_ setUserInteractionEnabled:YES];
8736 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8737 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8739 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8741 UIViewController *parent;
8742 if (emulated_ == nil)
8751 [parent presentModalViewController:navigation animated:YES];
8754 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8755 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8757 if (navigation != nil)
8758 [navigation pushViewController:progress animated:YES];
8760 [self presentModalViewController:progress force:YES];
8762 [progress invoke:invocation withTitle:title];
8766 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8767 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8770 - (void) repairWithInvocation:(NSInvocation *)invocation {
8772 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8776 - (void) repairWithSelector:(SEL)selector {
8777 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8783 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8784 _assert(file != NULL);
8786 for (NSString *key in [Sources_ allKeys]) {
8787 NSDictionary *source([Sources_ objectForKey:key]);
8789 fprintf(file, "%s %s %s\n",
8790 [[source objectForKey:@"Type"] UTF8String],
8791 [[source objectForKey:@"URI"] UTF8String],
8792 [[source objectForKey:@"Distribution"] UTF8String]
8798 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8803 - (void) addTrivialSource:(NSString *)href {
8804 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8807 @"./", @"Distribution",
8808 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8813 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8814 @synchronized (self) {
8815 [self _reloadDataWithInvocation:invocation];
8819 - (void) reloadData {
8820 [self reloadDataWithInvocation:nil];
8824 pkgProblemResolver *resolver = [database_ resolver];
8826 resolver->InstallProtect();
8827 if (!resolver->Resolve(true))
8832 // XXX: this is a really crappy way of doing this.
8833 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8834 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8835 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8836 if ([tabbar_ updating])
8837 [tabbar_ cancelUpdate];
8839 if (![database_ prepare])
8842 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8843 [page setDelegate:self];
8844 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8847 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8848 [tabbar_ presentModalViewController:confirm_ animated:YES];
8854 @synchronized (self) {
8859 - (void) clearPackage:(Package *)package {
8860 @synchronized (self) {
8867 - (void) installPackages:(NSArray *)packages {
8868 @synchronized (self) {
8869 for (Package *package in packages)
8876 - (void) installPackage:(Package *)package {
8877 @synchronized (self) {
8884 - (void) removePackage:(Package *)package {
8885 @synchronized (self) {
8892 - (void) distUpgrade {
8893 @synchronized (self) {
8894 if (![database_ upgrade])
8900 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8903 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8908 - (void) showSettings {
8909 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8912 - (void) retainNetworkActivityIndicator {
8913 if (activity_++ == 0)
8914 [self setNetworkActivityIndicatorVisible:YES];
8917 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8921 - (void) releaseNetworkActivityIndicator {
8922 if (--activity_ == 0)
8923 [self setNetworkActivityIndicatorVisible:NO];
8926 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8931 - (void) cancelAndClear:(bool)clear {
8932 @synchronized (self) {
8944 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8945 NSString *context([alert context]);
8947 if ([context isEqualToString:@"conffile"]) {
8948 FILE *input = [database_ input];
8949 if (button == [alert cancelButtonIndex])
8950 fprintf(input, "N\n");
8951 else if (button == [alert firstOtherButtonIndex])
8952 fprintf(input, "Y\n");
8955 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8956 } else if ([context isEqualToString:@"fixhalf"]) {
8957 if (button == [alert cancelButtonIndex]) {
8958 @synchronized (self) {
8959 for (Package *broken in (id) broken_) {
8962 NSString *id = [broken id];
8963 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8964 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8965 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8966 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8972 } else if (button == [alert firstOtherButtonIndex]) {
8973 [broken_ removeAllObjects];
8977 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8978 } else if ([context isEqualToString:@"upgrade"]) {
8979 if (button == [alert firstOtherButtonIndex]) {
8980 @synchronized (self) {
8981 for (Package *essential in (id) essential_)
8982 [essential install];
8987 } else if (button == [alert firstOtherButtonIndex] + 1) {
8989 } else if (button == [alert cancelButtonIndex]) {
8993 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8997 - (void) system:(NSString *)command {
8998 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9001 system([command UTF8String]);
9007 - (void) applicationWillSuspend {
9009 [super applicationWillSuspend];
9012 - (BOOL) isSafeToSuspend {
9015 NSLog(@"isSafeToSuspend: locked_ != 0");
9020 // Use external process status API internally.
9021 // This is probably a really bad idea.
9022 // XXX: what is the point of this? does this solve anything at all?
9023 uint64_t status = 0;
9025 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9026 notify_get_state(notify_token, &status);
9027 notify_cancel(notify_token);
9032 NSLog(@"isSafeToSuspend: status != 0");
9038 NSLog(@"isSafeToSuspend: -> true");
9043 - (void) applicationSuspend:(__GSEvent *)event {
9044 if ([self isSafeToSuspend])
9045 [super applicationSuspend:event];
9048 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9049 if ([self isSafeToSuspend])
9050 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9053 - (void) _setSuspended:(BOOL)value {
9054 if ([self isSafeToSuspend])
9055 [super _setSuspended:value];
9058 - (UIProgressHUD *) addProgressHUD {
9059 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9060 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9062 [window_ setUserInteractionEnabled:NO];
9064 UIViewController *target(tabbar_);
9065 if (UIViewController *modal = [target modalViewController])
9068 UIView *view([target view]);
9069 [view addSubview:hud];
9077 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9080 [hud removeFromSuperview];
9081 [window_ setUserInteractionEnabled:YES];
9084 - (CyteViewController *) pageForPackage:(NSString *)name {
9085 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9088 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9089 NSString *scheme([[url scheme] lowercaseString]);
9090 if ([[url absoluteString] length] <= [scheme length] + 3)
9092 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9093 NSArray *components([path pathComponents]);
9095 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9096 return [self pageForPackage:[components objectAtIndex:1]];
9098 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9101 NSString *base([components objectAtIndex:0]);
9103 CyteViewController *controller = nil;
9105 if ([base isEqualToString:@"url"]) {
9106 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9107 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9108 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9109 } else if (!external && [components count] == 1) {
9110 if ([base isEqualToString:@"manage"]) {
9111 controller = [[[ManageController alloc] init] autorelease];
9114 if ([base isEqualToString:@"sources"]) {
9115 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9118 if ([base isEqualToString:@"home"]) {
9119 controller = [[[HomeController alloc] init] autorelease];
9122 if ([base isEqualToString:@"sections"]) {
9123 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9126 if ([base isEqualToString:@"search"]) {
9127 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9130 if ([base isEqualToString:@"changes"]) {
9131 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9134 if ([base isEqualToString:@"installed"]) {
9135 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9137 } else if ([components count] == 2) {
9138 NSString *argument = [components objectAtIndex:1];
9140 if ([base isEqualToString:@"package"]) {
9141 controller = [self pageForPackage:argument];
9144 if (!external && [base isEqualToString:@"search"]) {
9145 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9148 if (!external && [base isEqualToString:@"sections"]) {
9149 if ([argument isEqualToString:@"all"])
9151 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9154 if (!external && [base isEqualToString:@"sources"]) {
9155 if ([argument isEqualToString:@"add"]) {
9156 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9157 [(SourcesController *)controller showAddSourcePrompt];
9159 Source *source = [database_ sourceWithKey:argument];
9160 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9164 if (!external && [base isEqualToString:@"launch"]) {
9165 [self launchApplicationWithIdentifier:argument suspended:NO];
9168 } else if (!external && [components count] == 3) {
9169 NSString *arg1 = [components objectAtIndex:1];
9170 NSString *arg2 = [components objectAtIndex:2];
9172 if ([base isEqualToString:@"package"]) {
9173 if ([arg2 isEqualToString:@"settings"]) {
9174 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9175 } else if ([arg2 isEqualToString:@"files"]) {
9176 if (Package *package = [database_ packageWithName:arg1]) {
9177 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9178 [(FileTable *)controller setPackage:package];
9184 [controller setDelegate:self];
9188 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9189 CyteViewController *page([self pageForURL:url forExternal:external]);
9192 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9193 [nav setViewControllers:[NSArray arrayWithObject:page]];
9194 [tabbar_ setUnselectedViewController:nav];
9200 - (void) applicationOpenURL:(NSURL *)url {
9201 [super applicationOpenURL:url];
9206 [self openCydiaURL:url forExternal:YES];
9209 - (void) applicationWillResignActive:(UIApplication *)application {
9210 // Stop refreshing if you get a phone call or lock the device.
9211 if ([tabbar_ updating])
9212 [tabbar_ cancelUpdate];
9214 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9215 [super applicationWillResignActive:application];
9218 - (void) applicationWillTerminate:(UIApplication *)application {
9220 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9221 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9222 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9227 - (void) setConfigurationData:(NSString *)data {
9228 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9230 if (!conffile_r(data)) {
9231 lprintf("E:invalid conffile\n");
9235 NSString *ofile = conffile_r[1];
9236 //NSString *nfile = conffile_r[2];
9238 UIAlertView *alert = [[[UIAlertView alloc]
9239 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9240 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9242 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9244 UCLocalize("ACCEPT_NEW_COPY"),
9245 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9249 [alert setContext:@"conffile"];
9250 [alert setNumberOfRows:2];
9254 - (void) addStashController {
9256 stash_ = [[[StashController alloc] init] autorelease];
9257 [window_ addSubview:[stash_ view]];
9260 - (void) removeStashController {
9261 [[stash_ view] removeFromSuperview];
9267 [self setIdleTimerDisabled:YES];
9269 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9270 UpdateExternalStatus(1);
9271 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9272 UpdateExternalStatus(0);
9274 [self removeStashController];
9276 if (ExecFork() == 0) {
9277 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9278 perror("launchctl stop");
9282 - (void) setupViewControllers {
9283 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9285 NSMutableArray *items([NSMutableArray arrayWithObjects:
9286 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9287 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9288 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9289 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9293 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9294 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9296 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9299 NSMutableArray *controllers([NSMutableArray array]);
9300 for (UITabBarItem *item in items) {
9301 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9302 [controller setTabBarItem:item];
9303 [controllers addObject:controller];
9305 [tabbar_ setViewControllers:controllers];
9307 [tabbar_ setUpdateDelegate:self];
9310 - (void) applicationDidFinishLaunching:(id)unused {
9312 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9313 [self setApplicationSupportsShakeToEdit:NO];
9315 @synchronized (HostConfig_) {
9316 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9319 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9320 initWithMemoryCapacity:524288
9321 diskCapacity:10485760
9322 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9325 [CydiaWebViewController _initialize];
9327 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9329 // this would disallow http{,s} URLs from accessing this data
9330 //[WebView registerURLSchemeAsLocal:@"cydia"];
9332 Font12_ = [UIFont systemFontOfSize:12];
9333 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9334 Font14_ = [UIFont systemFontOfSize:14];
9335 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9336 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9338 essential_ = [NSMutableArray arrayWithCapacity:4];
9339 broken_ = [NSMutableArray arrayWithCapacity:4];
9341 // XXX: I really need this thing... like, seriously... I'm sorry
9342 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9344 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9345 [window_ orderFront:self];
9346 [window_ makeKey:self];
9347 [window_ setHidden:NO];
9350 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9351 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9352 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9353 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9354 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9355 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9356 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9357 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9358 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9361 [self addStashController];
9362 // XXX: this would be much cleaner as a yieldToSelector:
9363 // that way the removeStashController could happen right here inline
9364 // we also could no longer require the useless stash_ field anymore
9365 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9369 database_ = [Database sharedInstance];
9370 [database_ setDelegate:self];
9372 [window_ setUserInteractionEnabled:NO];
9373 [self setupViewControllers];
9375 emulated_ = [[[CYEmulatedLoadingController alloc] init] autorelease];
9376 [window_ addSubview:[emulated_ view]];
9378 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9382 - (NSArray *) defaultStartPages {
9383 NSMutableArray *standard = [NSMutableArray array];
9384 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9385 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9386 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9388 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9390 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9391 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9393 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9400 [window_ setUserInteractionEnabled:YES];
9401 [self showSettings];
9404 if ([emulated_ modalViewController] != nil)
9405 [emulated_ dismissModalViewControllerAnimated:YES];
9406 [window_ setUserInteractionEnabled:NO];
9414 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9415 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9416 int standardIndex = 0;
9417 NSArray *standard = [self defaultStartPages];
9424 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9425 if (valid && closed != nil) {
9426 NSTimeInterval interval([closed timeIntervalSinceNow]);
9427 // XXX: Is 15 minutes the optimal time here?
9428 if (interval > 0 && interval <= -(15*60))
9432 if (valid && [saved count] != [standard count])
9436 for (unsigned int i = 0; i < [standard count]; i++) {
9437 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9438 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9439 // but it's good enough for now.
9440 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9447 NSArray *items = nil;
9449 [tabbar_ setSelectedIndex:savedIndex];
9452 [tabbar_ setSelectedIndex:standardIndex];
9456 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9457 NSArray *stack = [items objectAtIndex:tab];
9458 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9459 NSMutableArray *current = [NSMutableArray array];
9461 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9462 NSString *addr = [stack objectAtIndex:nav];
9463 NSURL *url = [NSURL URLWithString:addr];
9464 CyteViewController *page = [self pageForURL:url forExternal:NO];
9466 [current addObject:page];
9469 [navigation setViewControllers:current];
9472 // (Try to) show the startup URL.
9473 if (starturl_ != nil) {
9474 [self openCydiaURL:starturl_ forExternal:NO];
9479 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9480 if (item != nil && IsWildcat_) {
9481 [sheet showFromBarButtonItem:item animated:YES];
9483 [sheet showInView:window_];
9487 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9488 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9489 [progress setTitle:task];
9490 [progress addProgressEvent:event];
9493 - (void) addProgressEventForTask:(NSArray *)data {
9494 CydiaProgressEvent *event([data objectAtIndex:0]);
9495 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9496 [self addProgressEvent:event forTask:task];
9499 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9500 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9506 id Alloc_(id self, SEL selector) {
9507 id object = alloc_(self, selector);
9508 lprintf("[%s]A-%p\n", self->isa->name, object);
9513 id Dealloc_(id self, SEL selector) {
9514 id object = dealloc_(self, selector);
9515 lprintf("[%s]D-%p\n", self->isa->name, object);
9519 Class $WebDefaultUIKitDelegate;
9521 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9522 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9523 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9524 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9527 static NSSet *MobilizedFiles_;
9529 static NSURL *MobilizeURL(NSURL *url) {
9530 NSString *path([url path]);
9531 if ([path hasPrefix:@"/var/root/"]) {
9532 NSString *file([path substringFromIndex:10]);
9533 if ([MobilizedFiles_ containsObject:file])
9534 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9540 Class $CFXPreferencesPropertyListSource;
9541 @class CFXPreferencesPropertyListSource;
9543 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9544 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9545 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9546 url = MobilizeURL(url);
9547 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9548 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9554 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9555 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9556 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9557 url = MobilizeURL(url);
9558 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9559 //NSLog(@"%@ %@", [url absoluteString], value);
9565 Class $NSURLConnection;
9567 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9568 NSMutableURLRequest *copy([request mutableCopy]);
9570 NSURL *url([copy URL]);
9571 NSString *host([url host]);
9572 NSString *scheme([[url scheme] lowercaseString]);
9574 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9576 @synchronized (HostConfig_) {
9577 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9578 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9579 [copy setHTTPShouldUsePipelining:YES];
9582 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9586 int main(int argc, char *argv[]) {
9587 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9591 UpdateExternalStatus(0);
9593 if (Class $UIDevice = objc_getClass("UIDevice")) {
9594 UIDevice *device([$UIDevice currentDevice]);
9595 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9599 UIScreen *screen([UIScreen mainScreen]);
9600 if ([screen respondsToSelector:@selector(scale)])
9601 ScreenScale_ = [screen scale];
9605 UIDevice *device([UIDevice currentDevice]);
9606 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9609 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9610 if (idiom == UIUserInterfaceIdiomPhone)
9612 else if (idiom == UIUserInterfaceIdiomPad)
9615 NSLog(@"unknown UIUserInterfaceIdiom!");
9618 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9620 HostConfig_ = [[[NSObject alloc] init] autorelease];
9621 @synchronized (HostConfig_) {
9622 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9623 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9626 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9628 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9630 MobilizedFiles_ = [NSMutableSet setWithObjects:
9631 @"Library/Preferences/com.apple.Accessibility.plist",
9632 @"Library/Preferences/com.apple.preferences.sounds.plist",
9635 /* Library Hacks {{{ */
9636 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9638 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9640 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9641 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9642 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9643 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9646 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9647 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9648 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9649 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9652 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9653 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9654 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9655 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9656 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9659 $NSURLConnection = objc_getClass("NSURLConnection");
9660 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9661 if (NSURLConnection$init$ != NULL) {
9662 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9663 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9666 /* Set Locale {{{ */
9667 Locale_ = CFLocaleCopyCurrent();
9668 Languages_ = [NSLocale preferredLanguages];
9670 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9671 //NSLog(@"%@", [Languages_ description]);
9674 if (Locale_ != NULL)
9675 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9676 else if (Languages_ != nil && [Languages_ count] != 0)
9677 lang = [[Languages_ objectAtIndex:0] UTF8String];
9679 // XXX: consider just setting to C and then falling through?
9683 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9684 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9687 NSLog(@"Setting Language: %s", lang);
9690 setenv("LANG", lang, true);
9691 std::setlocale(LC_ALL, lang);
9695 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9697 /* Parse Arguments {{{ */
9698 bool substrate(false);
9704 for (int argi(1); argi != argc; ++argi)
9705 if (strcmp(argv[argi], "--") == 0) {
9707 argv[argi] = argv[0];
9713 for (int argi(1); argi != arge; ++argi)
9714 if (strcmp(args[argi], "--substrate") == 0)
9717 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9721 App_ = [[NSBundle mainBundle] bundlePath];
9727 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9728 alloc_ = alloc->method_imp;
9729 alloc->method_imp = (IMP) &Alloc_;*/
9731 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9732 dealloc_ = dealloc->method_imp;
9733 dealloc->method_imp = (IMP) &Dealloc_;*/
9735 /* System Information {{{ */
9739 size = sizeof(maxproc);
9740 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9741 perror("sysctlbyname(\"kern.maxproc\", ?)");
9742 else if (maxproc < 64) {
9744 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9745 perror("sysctlbyname(\"kern.maxproc\", #)");
9748 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9749 char *osversion = new char[size];
9750 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9751 perror("sysctlbyname(\"kern.osversion\", ?)");
9753 System_ = [NSString stringWithUTF8String:osversion];
9755 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9756 char *machine = new char[size];
9757 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9758 perror("sysctlbyname(\"hw.machine\", ?)");
9762 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9763 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9764 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9766 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9768 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9769 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9770 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9772 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9773 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9774 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9776 if (mcc != NULL && mnc != NULL)
9777 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9784 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9785 Build_ = [system objectForKey:@"ProductBuildVersion"];
9786 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9787 Product_ = [info objectForKey:@"SafariProductVersion"];
9788 Safari_ = [info objectForKey:@"CFBundleVersion"];
9791 /* Load Database {{{ */
9793 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9795 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9797 if (Metadata_ == NULL)
9798 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9800 Settings_ = [Metadata_ objectForKey:@"Settings"];
9802 Packages_ = [Metadata_ objectForKey:@"Packages"];
9803 Sections_ = [Metadata_ objectForKey:@"Sections"];
9804 Sources_ = [Metadata_ objectForKey:@"Sources"];
9806 Token_ = [Metadata_ objectForKey:@"Token"];
9809 if (Settings_ != nil)
9810 Role_ = [Settings_ objectForKey:@"Role"];
9812 if (Sections_ == nil) {
9813 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9814 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9817 if (Sources_ == nil) {
9818 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9819 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9824 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9827 if (Packages_ != nil) {
9829 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9833 [Metadata_ removeObjectForKey:@"Packages"];
9839 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9841 #define MobileSubstrate_(name) \
9842 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9843 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9844 if (handle == NULL) \
9845 NSLog(@"%s", dlerror()); \
9848 MobileSubstrate_(Activator)
9849 MobileSubstrate_(libstatusbar)
9850 MobileSubstrate_(SimulatedKeyEvents)
9851 MobileSubstrate_(WinterBoard)
9853 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9854 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9856 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9858 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9859 unlink("/tmp/.cydia.fw");
9861 } else if (access("/User", F_OK) != 0 || version < 4) {
9864 system("/usr/libexec/cydia/firmware.sh");
9868 _assert([[NSFileManager defaultManager]
9869 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9870 withIntermediateDirectories:YES
9875 if (access("/tmp/cydia.chk", F_OK) == 0) {
9876 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9877 _assert(errno == ENOENT);
9878 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9879 _assert(errno == ENOENT);
9882 /* APT Initialization {{{ */
9883 _assert(pkgInitConfig(*_config));
9884 _assert(pkgInitSystem(*_config, _system));
9887 _config->Set("APT::Acquire::Translation", lang);
9889 // XXX: this timeout might be important :(
9890 //_config->Set("Acquire::http::Timeout", 15);
9892 _config->Set("Acquire::http::MaxParallel", 3);
9894 /* Color Choices {{{ */
9895 space_ = CGColorSpaceCreateDeviceRGB();
9897 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9898 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9899 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9900 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9901 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9902 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9903 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9904 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9905 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9907 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9908 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9910 /* UIKit Configuration {{{ */
9911 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9912 if ($GSFontSetUseLegacyFontMetrics != NULL)
9913 $GSFontSetUseLegacyFontMetrics(YES);
9915 // XXX: I have a feeling this was important
9916 //UIKeyboardDisableAutomaticAppearance();
9919 Colon_ = UCLocalize("COLON_DELIMITED");
9920 Elision_ = UCLocalize("ELISION");
9921 Error_ = UCLocalize("ERROR");
9922 Warning_ = UCLocalize("WARNING");
9925 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9927 CGColorSpaceRelease(space_);