1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
210 #define Cydia_ CYDIA_VERSION
212 #define lprintf(args...) fprintf(stderr, args)
215 #define TraceLogging (1 && !ForRelease)
216 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
217 #define ProfileTimes (0 && !ForRelease)
218 #define ForSaurik (0 && !ForRelease)
219 #define LogBrowser (0 && !ForRelease)
220 #define TrackResize (0 && !ForRelease)
221 #define ManualRefresh (1 && !ForRelease)
222 #define ShowInternals (0 && !ForRelease)
223 #define AlwaysReload (0 && !ForRelease)
224 #define TryIndexedCollation (0 && !ForRelease)
228 #define _trace(args...)
233 #define _profile(name) {
236 #define PrintTimes() do {} while (false)
239 // Hash Functions/Structures {{{
240 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
250 static _finline NSString *CydiaURL(NSString *path) {
252 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
253 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
254 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
255 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
256 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
258 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
261 static _finline void UpdateExternalStatus(uint64_t newStatus) {
263 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
264 notify_set_state(notify_token, newStatus);
265 notify_cancel(notify_token);
267 notify_post("com.saurik.Cydia.status");
270 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
271 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
272 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
275 /* NSForcedOrderingSearch doesn't work on the iPhone */
276 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
277 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
278 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
280 /* Insertion Sort {{{ */
282 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
283 const char *ptr = (const char *)list;
285 CFIndex half = count / 2;
286 const char *probe = ptr + elementSize * half;
287 CFComparisonResult cr = comparator(element, probe, context);
288 if (0 == cr) return (probe - (const char *)list) / elementSize;
289 ptr = (cr < 0) ? ptr : probe + elementSize;
290 count = (cr < 0) ? half : (half + (count & 1) - 1);
292 return (ptr - (const char *)list) / elementSize;
295 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
296 const char *ptr = (const char *)list;
298 CFIndex half = count / 2;
299 const char *probe = ptr + elementSize * half;
300 CFComparisonResult cr = comparator(element, probe, context);
301 if (0 == cr) return (probe - (const char *)list) / elementSize;
302 ptr = (cr < 0) ? ptr : probe + elementSize;
303 count = (cr < 0) ? half : (half + (count & 1) - 1);
305 return (ptr - (const char *)list) / elementSize;
308 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
309 if (range.length == 0)
311 const void **values(new const void *[range.length]);
312 CFArrayGetValues(array, range, values);
314 #if HistogramInsertionSort > 0
315 uint32_t total(0), *offsets(new uint32_t[range.length]);
318 for (CFIndex index(1); index != range.length; ++index) {
319 const void *value(values[index]);
320 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
321 CFIndex correct(index);
322 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
323 #if HistogramInsertionSort > 1
324 NSLog(@"%@ < %@", value, values[correct - 1]);
329 if (correct != index) {
330 size_t offset(index - correct);
331 #if HistogramInsertionSort
335 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
337 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
338 values[correct] = value;
342 CFArrayReplaceValues(array, range, values, range.length);
345 #if HistogramInsertionSort > 0
346 for (CFIndex index(0); index != range.length; ++index)
347 if (offsets[index] != 0)
348 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
349 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
356 /* Apple Bug Fixes {{{ */
357 @implementation UIWebDocumentView (Cydia)
359 - (void) _setScrollerOffset:(CGPoint)offset {
360 UIScroller *scroller([self _scroller]);
362 CGSize size([scroller contentSize]);
363 CGSize bounds([scroller bounds].size);
366 max.x = size.width - bounds.width;
367 max.y = size.height - bounds.height;
375 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
376 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
378 [scroller setOffset:offset];
384 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
385 size_t length([self length] - state->state);
388 else if (length > count)
390 for (size_t i(0); i != length; ++i)
391 objects[i] = [self item:state->state++];
392 state->itemsPtr = objects;
393 state->mutationsPtr = (unsigned long *) self;
397 /* Cydia NSString Additions {{{ */
398 @interface NSString (Cydia)
399 - (NSComparisonResult) compareByPath:(NSString *)other;
400 - (NSString *) stringByCachingURLWithCurrentCDN;
401 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
404 @implementation NSString (Cydia)
406 - (NSComparisonResult) compareByPath:(NSString *)other {
407 NSString *prefix = [self commonPrefixWithString:other options:0];
408 size_t length = [prefix length];
410 NSRange lrange = NSMakeRange(length, [self length] - length);
411 NSRange rrange = NSMakeRange(length, [other length] - length);
413 lrange = [self rangeOfString:@"/" options:0 range:lrange];
414 rrange = [other rangeOfString:@"/" options:0 range:rrange];
416 NSComparisonResult value;
418 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
419 value = NSOrderedSame;
420 else if (lrange.location == NSNotFound)
421 value = NSOrderedAscending;
422 else if (rrange.location == NSNotFound)
423 value = NSOrderedDescending;
425 value = NSOrderedSame;
427 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
428 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
429 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
430 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
432 NSComparisonResult result = [lpath compare:rpath];
433 return result == NSOrderedSame ? value : result;
436 - (NSString *) stringByCachingURLWithCurrentCDN {
438 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
439 withString:@"://cache.cydia.saurik.com/"
443 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
444 return [(id)CFURLCreateStringByAddingPercentEscapes(
449 kCFStringEncodingUTF8
456 /* C++ NSString Wrapper Cache {{{ */
457 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
458 return size == 0 ? NULL :
459 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
460 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
463 static _finline CFStringRef CYStringCreate(const char *data) {
464 return CYStringCreate(data, strlen(data));
473 _finline void clear_() {
474 if (cache_ != NULL) {
481 _finline bool empty() const {
485 _finline size_t size() const {
489 _finline char *data() const {
493 _finline void clear() {
498 _finline CYString() :
505 _finline ~CYString() {
509 void operator =(const CYString &rhs) {
513 if (rhs.cache_ == nil)
516 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
519 void copy(apr_pool_t *pool) {
520 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
521 memcpy(temp, data_, size_);
526 void set(apr_pool_t *pool, const char *data, size_t size) {
532 data_ = const_cast<char *>(data);
540 _finline void set(apr_pool_t *pool, const char *data) {
541 set(pool, data, data == NULL ? 0 : strlen(data));
544 _finline void set(apr_pool_t *pool, const std::string &rhs) {
545 set(pool, rhs.data(), rhs.size());
548 bool operator ==(const CYString &rhs) const {
549 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
552 _finline operator CFStringRef() {
554 cache_ = CYStringCreate(data_, size_);
558 _finline operator id() {
559 return (NSString *) static_cast<CFStringRef>(*this);
562 _finline operator const char *() {
563 return reinterpret_cast<const char *>(data_);
567 /* C++ NSString Algorithm Adapters {{{ */
569 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
572 struct NSStringMapHash :
573 std::unary_function<NSString *, size_t>
575 _finline size_t operator ()(NSString *value) const {
576 return CFStringHashNSString((CFStringRef) value);
580 struct NSStringMapLess :
581 std::binary_function<NSString *, NSString *, bool>
583 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
584 return [lhs compare:rhs] == NSOrderedAscending;
588 struct NSStringMapEqual :
589 std::binary_function<NSString *, NSString *, bool>
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
593 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
594 //[lhs isEqualToString:rhs];
599 /* CoreGraphics Primitives {{{ */
604 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
605 CGFloat color[] = {red, green, blue, alpha};
606 return CGColorCreate(space, color);
615 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
616 color_(Create_(space, red, green, blue, alpha))
618 Set(space, red, green, blue, alpha);
623 CGColorRelease(color_);
630 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
632 color_ = Create_(space, red, green, blue, alpha);
635 operator CGColorRef() {
641 /* Random Global Variables {{{ */
642 static const int PulseInterval_ = 50000;
644 static const NSString *UI_;
647 static bool RestartSubstrate_;
648 static NSArray *Finishes_;
650 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
651 #define NotifyConfig_ "/etc/notify.conf"
653 static bool Queuing_;
655 static CYColor Blue_;
656 static CYColor Blueish_;
657 static CYColor Black_;
659 static CYColor White_;
660 static CYColor Gray_;
661 static CYColor Green_;
662 static CYColor Purple_;
663 static CYColor Purplish_;
665 static UIColor *InstallingColor_;
666 static UIColor *RemovingColor_;
668 static NSString *App_;
670 static BOOL Advanced_;
671 static BOOL Ignored_;
673 static _H<UIFont> Font12_;
674 static _H<UIFont> Font12Bold_;
675 static _H<UIFont> Font14_;
676 static _H<UIFont> Font18Bold_;
677 static _H<UIFont> Font22Bold_;
679 static const char *Machine_ = NULL;
680 static NSString *System_ = nil;
681 static NSString *SerialNumber_ = nil;
682 static NSString *ChipID_ = nil;
683 static NSString *BBSNum_ = nil;
684 static _H<NSString> Token_;
685 static NSString *UniqueID_ = nil;
686 static NSString *PLMN_ = nil;
687 static NSString *Build_ = nil;
688 static NSString *Product_ = nil;
689 static NSString *Safari_ = nil;
691 static CFLocaleRef Locale_;
692 static NSArray *Languages_;
693 static CGColorSpaceRef space_;
695 static NSDictionary *SectionMap_;
696 static NSMutableDictionary *Metadata_;
697 static _transient NSMutableDictionary *Settings_;
698 static _transient NSString *Role_;
699 static _transient NSMutableDictionary *Packages_;
700 static _transient NSMutableDictionary *Sections_;
701 static _transient NSMutableDictionary *Sources_;
702 static bool Changed_;
706 static CGFloat ScreenScale_;
707 static NSString *Idiom_;
709 static _H<NSMutableDictionary> SessionData_;
710 static _H<NSObject> HostConfig_;
711 static _H<NSMutableSet> BridgedHosts_;
712 static _H<NSMutableSet> PipelinedHosts_;
713 static _H<NSMutableSet> CachedURLs_;
715 static NSString *kCydiaProgressEventTypeError = @"Error";
716 static NSString *kCydiaProgressEventTypeInformation = @"Information";
717 static NSString *kCydiaProgressEventTypeStatus = @"Status";
718 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
721 /* Display Helpers {{{ */
722 inline float Interpolate(float begin, float end, float fraction) {
723 return (end - begin) * fraction + begin;
726 static _finline const char *StripVersion_(const char *version) {
727 const char *colon(strchr(version, ':'));
728 return colon == NULL ? version : colon + 1;
731 NSString *LocalizeSection(NSString *section) {
732 static Pcre title_r("^(.*?) \\((.*)\\)$");
733 if (title_r(section)) {
734 NSString *parent(title_r[1]);
735 NSString *child(title_r[2]);
737 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
738 LocalizeSection(parent),
739 LocalizeSection(child)
743 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
746 NSString *Simplify(NSString *title) {
747 const char *data = [title UTF8String];
748 size_t size = [title length];
750 static Pcre square_r("^\\[(.*)\\]$");
751 if (square_r(data, size))
752 return Simplify(square_r[1]);
754 static Pcre paren_r("^\\((.*)\\)$");
755 if (paren_r(data, size))
756 return Simplify(paren_r[1]);
758 static Pcre title_r("^(.*?) \\((.*)\\)$");
759 if (title_r(data, size))
760 return Simplify(title_r[1]);
766 NSString *GetLastUpdate() {
767 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
770 return UCLocalize("NEVER_OR_UNKNOWN");
772 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
773 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
775 CFRelease(formatter);
777 return [(NSString *) formatted autorelease];
780 bool isSectionVisible(NSString *section) {
781 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
782 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
783 return hidden == nil || ![hidden boolValue];
786 static NSObject *CYIOGetValue(const char *path, NSString *property) {
787 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
788 if (entry == MACH_PORT_NULL)
791 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
792 IOObjectRelease(entry);
796 return [(id) value autorelease];
799 static NSString *CYHex(NSData *data, bool reverse = false) {
803 size_t length([data length]);
804 uint8_t bytes[length];
805 [data getBytes:bytes];
807 char string[length * 2 + 1];
808 for (size_t i(0); i != length; ++i)
809 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
811 return [NSString stringWithUTF8String:string];
816 /* Delegate Prototypes {{{ */
819 @class CydiaProgressEvent;
821 @protocol DatabaseDelegate
822 - (void) repairWithSelector:(SEL)selector;
823 - (void) setConfigurationData:(NSString *)data;
824 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
827 @class CYPackageController;
829 @protocol CydiaDelegate
830 - (void) retainNetworkActivityIndicator;
831 - (void) releaseNetworkActivityIndicator;
832 - (void) clearPackage:(Package *)package;
833 - (void) installPackage:(Package *)package;
834 - (void) installPackages:(NSArray *)packages;
835 - (void) removePackage:(Package *)package;
836 - (void) beginUpdate;
838 - (void) distUpgrade;
842 - (void) addTrivialSource:(NSString *)href;
843 - (void) showSettings;
844 - (UIProgressHUD *) addProgressHUD;
845 - (void) removeProgressHUD:(UIProgressHUD *)hud;
846 - (CyteViewController *) pageForPackage:(NSString *)name;
847 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
848 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
852 /* Status Delegation {{{ */
854 public pkgAcquireStatus
857 _transient NSObject<ProgressDelegate> *delegate_;
867 void setDelegate(NSObject<ProgressDelegate> *delegate) {
868 delegate_ = delegate;
871 NSObject<ProgressDelegate> *getDelegate() const {
875 virtual bool MediaChange(std::string media, std::string drive) {
879 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
882 virtual void Fetch(pkgAcquire::ItemDesc &item) {
883 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
884 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
885 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
888 virtual void Done(pkgAcquire::ItemDesc &item) {
891 virtual void Fail(pkgAcquire::ItemDesc &item) {
893 item.Owner->Status == pkgAcquire::Item::StatIdle ||
894 item.Owner->Status == pkgAcquire::Item::StatDone
898 std::string &error(item.Owner->ErrorText);
902 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
903 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
906 virtual bool Pulse(pkgAcquire *Owner) {
907 bool value = pkgAcquireStatus::Pulse(Owner);
910 double(CurrentBytes + CurrentItems) /
911 double(TotalBytes + TotalItems)
914 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
915 [NSNumber numberWithDouble:percent], @"Percent",
917 [NSNumber numberWithDouble:CurrentBytes], @"Current",
918 [NSNumber numberWithDouble:TotalBytes], @"Total",
919 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
920 nil] waitUntilDone:YES];
922 if (value && ![delegate_ isProgressCancelled])
930 _finline bool WasCancelled() const {
934 virtual void Start() {
935 pkgAcquireStatus::Start();
936 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
939 virtual void Stop() {
940 pkgAcquireStatus::Stop();
941 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
942 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
946 /* Database Interface {{{ */
947 typedef std::map< unsigned long, _H<Source> > SourceMap;
949 @interface Database : NSObject {
956 pkgDepCache::Policy *policy_;
957 pkgRecords *records_;
958 pkgProblemResolver *resolver_;
959 pkgAcquire *fetcher_;
961 SPtr<pkgPackageManager> manager_;
962 pkgSourceList *list_;
964 SourceMap sourceMap_;
965 _H<NSMutableArray> sourceList_;
967 CFMutableArrayRef packages_;
969 _transient NSObject<DatabaseDelegate> *delegate_;
970 _transient NSObject<ProgressDelegate> *progress_;
978 std::map<const char *, _H<NSString> > sections_;
981 + (Database *) sharedInstance;
984 - (void) _readCydia:(NSNumber *)fd;
985 - (void) _readStatus:(NSNumber *)fd;
986 - (void) _readOutput:(NSNumber *)fd;
990 - (Package *) packageWithName:(NSString *)name;
992 - (pkgCacheFile &) cache;
993 - (pkgDepCache::Policy *) policy;
994 - (pkgRecords *) records;
995 - (pkgProblemResolver *) resolver;
996 - (pkgAcquire &) fetcher;
997 - (pkgSourceList &) list;
998 - (NSArray *) packages;
999 - (NSArray *) sources;
1000 - (Source *) sourceWithKey:(NSString *)key;
1001 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1009 - (void) updateWithStatus:(Status &)status;
1011 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1013 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1014 - (NSObject<ProgressDelegate> *) progressDelegate;
1016 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1018 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1022 /* ProgressEvent Implementation {{{ */
1023 @implementation CydiaProgressEvent
1025 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1026 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1029 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1030 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1031 [event setPackage:package];
1035 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1036 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1038 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1039 NSArray *fields([description componentsSeparatedByString:@" "]);
1040 [event setItem:fields];
1042 if ([fields count] > 3) {
1043 [event setPackage:[fields objectAtIndex:2]];
1044 [event setVersion:[fields objectAtIndex:3]];
1047 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1052 + (NSArray *) _attributeKeys {
1053 return [NSArray arrayWithObjects:
1063 - (NSArray *) attributeKeys {
1064 return [[self class] _attributeKeys];
1067 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1068 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1071 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1072 if ((self = [super init]) != nil) {
1078 - (NSString *) message {
1082 - (NSString *) type {
1086 - (NSArray *) item {
1087 return (id) item_ ?: [NSNull null];
1090 - (void) setItem:(NSArray *)item {
1094 - (NSString *) package {
1095 return (id) package_ ?: [NSNull null];
1098 - (void) setPackage:(NSString *)package {
1102 - (NSString *) url {
1103 return (id) url_ ?: [NSNull null];
1106 - (void) setURL:(NSString *)url {
1110 - (void) setVersion:(NSString *)version {
1114 - (NSString *) version {
1115 return (id) version_ ?: [NSNull null];
1118 - (NSString *) compound:(NSString *)value {
1120 NSString *mode(nil); {
1121 NSString *type([self type]);
1122 if ([type isEqualToString:kCydiaProgressEventTypeError])
1123 mode = UCLocalize("ERROR");
1124 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1125 mode = UCLocalize("WARNING");
1129 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1135 - (NSString *) compoundMessage {
1136 return [self compound:[self message]];
1139 - (NSString *) compoundTitle {
1142 if (package_ == nil)
1144 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1145 title = [package name];
1149 return [self compound:title];
1155 // Cytore Definitions {{{
1156 struct PackageValue :
1159 Cytore::Offset<PackageValue> next_;
1161 uint32_t index_ : 23;
1162 uint32_t subscribed_ : 1;
1179 Cytore::Offset<PackageValue> packages_[1 << 16];
1182 static Cytore::File<MetaValue> MetaFile_;
1184 // Cytore Helper Functions {{{
1185 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1186 SplitHash nhash = { hashlittle(name, length) };
1188 PackageValue *metadata;
1190 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1191 offset: if (offset->IsNull()) {
1192 *offset = MetaFile_.New<PackageValue>(length + 1);
1193 metadata = &MetaFile_.Get(*offset);
1195 if (metadata == NULL) {
1199 metadata = new PackageValue();
1200 memset(metadata, 0, sizeof(*metadata));
1203 memcpy(metadata->name_, name, length + 1);
1204 metadata->nhash_ = nhash.u16[1];
1206 metadata = &MetaFile_.Get(*offset);
1208 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1209 offset = &metadata->next_;
1217 static void PackageImport(const void *key, const void *value, void *context) {
1218 bool &fail(*reinterpret_cast<bool *>(context));
1221 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1222 NSLog(@"failed to import package %@", key);
1226 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1227 NSDictionary *package((NSDictionary *) value);
1229 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1230 if ([subscribed boolValue] && !metadata->subscribed_)
1231 metadata->subscribed_ = true;
1233 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1234 time_t time([date timeIntervalSince1970]);
1235 if (metadata->first_ > time || metadata->first_ == 0)
1236 metadata->first_ = time;
1239 NSDate *date([package objectForKey:@"LastSeen"]);
1240 NSString *version([package objectForKey:@"LastVersion"]);
1242 if (date != nil && version != nil) {
1243 time_t time([date timeIntervalSince1970]);
1244 if (metadata->last_ < time || metadata->last_ == 0)
1245 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1246 size_t length(strlen(buffer));
1247 uint16_t vhash(hashlittle(buffer, length));
1249 size_t capped(std::min<size_t>(8, length));
1250 char *latest(buffer + length - capped);
1252 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1253 metadata->vhash_ = vhash;
1255 metadata->last_ = time;
1261 /* Source Class {{{ */
1262 @interface Source : NSObject {
1263 CYString depiction_;
1264 CYString description_;
1270 CYString distribution_;
1276 _H<NSString> authority_;
1278 CYString defaultIcon_;
1280 _H<NSDictionary> record_;
1284 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1286 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1288 - (NSString *) depictionForPackage:(NSString *)package;
1289 - (NSString *) supportForPackage:(NSString *)package;
1291 - (NSDictionary *) record;
1295 - (NSString *) distribution;
1296 - (NSString *) type;
1298 - (NSString *) base;
1301 - (NSString *) host;
1303 - (NSString *) name;
1304 - (NSString *) shortDescription;
1305 - (NSString *) label;
1306 - (NSString *) origin;
1307 - (NSString *) version;
1309 - (NSString *) defaultIcon;
1313 @implementation Source
1317 distribution_.clear();
1322 description_.clear();
1328 defaultIcon_.clear();
1335 + (NSArray *) _attributeKeys {
1336 return [NSArray arrayWithObjects:
1343 @"shortDescription",
1351 - (NSArray *) attributeKeys {
1352 return [[self class] _attributeKeys];
1355 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1356 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1359 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1362 trusted_ = index->IsTrusted();
1364 uri_.set(pool, index->GetURI());
1365 distribution_.set(pool, index->GetDist());
1366 type_.set(pool, index->GetType());
1368 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1369 if (dindex != NULL) {
1370 base_.set(pool, dindex->MetaIndexURI(""));
1373 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1376 pkgTagFile tags(&fd);
1378 pkgTagSection section;
1385 {"default-icon", &defaultIcon_},
1386 {"depiction", &depiction_},
1387 {"description", &description_},
1389 {"origin", &origin_},
1390 {"support", &support_},
1391 {"version", &version_},
1394 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1395 const char *start, *end;
1397 if (section.Find(names[i].name_, start, end)) {
1398 CYString &value(*names[i].value_);
1399 value.set(pool, start, end - start);
1405 record_ = [Sources_ objectForKey:[self key]];
1407 NSURL *url([NSURL URLWithString:uri_]);
1411 host_ = [host_ lowercaseString];
1416 authority_ = [url path];
1419 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1420 if ((self = [super init]) != nil) {
1421 [self setMetaIndex:index inPool:pool];
1425 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1426 NSDictionary *lhr = [self record];
1427 NSDictionary *rhr = [source record];
1430 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1432 NSString *lhs = [self name];
1433 NSString *rhs = [source name];
1435 if ([lhs length] != 0 && [rhs length] != 0) {
1436 unichar lhc = [lhs characterAtIndex:0];
1437 unichar rhc = [rhs characterAtIndex:0];
1439 if (isalpha(lhc) && !isalpha(rhc))
1440 return NSOrderedAscending;
1441 else if (!isalpha(lhc) && isalpha(rhc))
1442 return NSOrderedDescending;
1445 return [lhs compare:rhs options:LaxCompareOptions_];
1448 - (NSString *) depictionForPackage:(NSString *)package {
1449 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1452 - (NSString *) supportForPackage:(NSString *)package {
1453 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1456 - (NSDictionary *) record {
1464 - (NSString *) uri {
1468 - (NSString *) distribution {
1469 return distribution_;
1472 - (NSString *) type {
1476 - (NSString *) base {
1480 - (NSString *) key {
1481 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1484 - (NSString *) host {
1488 - (NSString *) name {
1489 return origin_.empty() ? (id) authority_ : origin_;
1492 - (NSString *) shortDescription {
1493 return description_;
1496 - (NSString *) label {
1497 return label_.empty() ? (id) authority_ : label_;
1500 - (NSString *) origin {
1504 - (NSString *) version {
1508 - (NSString *) defaultIcon {
1509 return defaultIcon_;
1514 /* CydiaOperation Class {{{ */
1515 @interface CydiaOperation : NSObject {
1516 _H<NSString> operator_;
1517 _H<NSString> value_;
1520 - (NSString *) operator;
1521 - (NSString *) value;
1525 @implementation CydiaOperation
1527 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1528 if ((self = [super init]) != nil) {
1529 operator_ = [NSString stringWithUTF8String:_operator];
1530 value_ = [NSString stringWithUTF8String:value];
1534 + (NSArray *) _attributeKeys {
1535 return [NSArray arrayWithObjects:
1541 - (NSArray *) attributeKeys {
1542 return [[self class] _attributeKeys];
1545 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1546 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1549 - (NSString *) operator {
1553 - (NSString *) value {
1559 /* CydiaClause Class {{{ */
1560 @interface CydiaClause : NSObject {
1561 _H<NSString> package_;
1562 _H<CydiaOperation> version_;
1565 - (NSString *) package;
1566 - (CydiaOperation *) version;
1570 @implementation CydiaClause
1572 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1573 if ((self = [super init]) != nil) {
1574 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1576 if (const char *version = dep.TargetVer())
1577 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1579 version_ = (id) [NSNull null];
1583 + (NSArray *) _attributeKeys {
1584 return [NSArray arrayWithObjects:
1590 - (NSArray *) attributeKeys {
1591 return [[self class] _attributeKeys];
1594 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1595 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1598 - (NSString *) package {
1602 - (CydiaOperation *) version {
1608 /* CydiaRelation Class {{{ */
1609 @interface CydiaRelation : NSObject {
1610 _H<NSString> relationship_;
1611 _H<NSMutableArray> clauses_;
1614 - (NSString *) relationship;
1615 - (NSArray *) clauses;
1619 @implementation CydiaRelation
1621 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1622 if ((self = [super init]) != nil) {
1623 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1624 clauses_ = [NSMutableArray arrayWithCapacity:8];
1626 pkgCache::DepIterator start;
1627 pkgCache::DepIterator end;
1628 dep.GlobOr(start, end); // ++dep
1631 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1633 // yes, seriously. (wtf?)
1641 + (NSArray *) _attributeKeys {
1642 return [NSArray arrayWithObjects:
1648 - (NSArray *) attributeKeys {
1649 return [[self class] _attributeKeys];
1652 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1653 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1656 - (NSString *) relationship {
1657 return relationship_;
1660 - (NSArray *) clauses {
1664 - (void) addClause:(CydiaClause *)clause {
1665 [clauses_ addObject:clause];
1670 /* Package Class {{{ */
1671 struct ParsedPackage {
1676 CYString depiction_;
1686 @interface Package : NSObject {
1689 uint32_t essential_ : 1;
1690 uint32_t obsolete_ : 1;
1691 uint32_t ignored_ : 1;
1697 _transient Database *database_;
1699 pkgCache::VerIterator version_;
1700 pkgCache::PkgIterator iterator_;
1701 pkgCache::VerFileIterator file_;
1707 CYString installed_;
1709 const char *section_;
1710 _transient NSString *section$_;
1714 PackageValue *metadata_;
1715 ParsedPackage *parsed_;
1717 _H<NSMutableArray> tags_;
1720 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1721 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1723 - (pkgCache::PkgIterator) iterator;
1726 - (NSString *) section;
1727 - (NSString *) simpleSection;
1729 - (NSString *) longSection;
1730 - (NSString *) shortSection;
1734 - (MIMEAddress *) maintainer;
1736 - (NSString *) longDescription;
1737 - (NSString *) shortDescription;
1740 - (PackageValue *) metadata;
1743 - (bool) subscribed;
1744 - (bool) setSubscribed:(bool)subscribed;
1748 - (NSString *) latest;
1749 - (NSString *) installed;
1750 - (BOOL) uninstalled;
1753 - (BOOL) upgradableAndEssential:(BOOL)essential;
1756 - (BOOL) unfiltered;
1760 - (BOOL) halfConfigured;
1761 - (BOOL) halfInstalled;
1763 - (NSString *) mode;
1766 - (NSString *) name;
1768 - (NSString *) homepage;
1769 - (NSString *) depiction;
1770 - (MIMEAddress *) author;
1772 - (NSString *) support;
1774 - (NSArray *) files;
1775 - (NSArray *) warnings;
1776 - (NSArray *) applications;
1778 - (Source *) source;
1781 - (BOOL) matches:(NSArray *)query;
1783 - (bool) hasSupportingRole;
1784 - (BOOL) hasTag:(NSString *)tag;
1785 - (NSString *) primaryPurpose;
1786 - (NSArray *) purposes;
1787 - (bool) isCommercial;
1789 - (void) setIndex:(size_t)index;
1791 - (CYString &) cyname;
1793 - (uint32_t) compareBySection:(NSArray *)sections;
1798 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1799 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1800 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1801 - (bool) isVisibleInSection:(NSString *)section;
1802 - (bool) isVisibleInSource:(Source *)source;
1806 uint32_t PackageChangesRadix(Package *self, void *) {
1811 uint32_t timestamp : 30;
1812 uint32_t ignored : 1;
1813 uint32_t upgradable : 1;
1817 bool upgradable([self upgradableAndEssential:YES]);
1818 value.bits.upgradable = upgradable ? 1 : 0;
1821 value.bits.timestamp = 0;
1822 value.bits.ignored = [self ignored] ? 0 : 1;
1823 value.bits.upgradable = 1;
1825 value.bits.timestamp = [self seen] >> 2;
1826 value.bits.ignored = 0;
1827 value.bits.upgradable = 0;
1830 return _not(uint32_t) - value.key;
1833 uint32_t PackagePrefixRadix(Package *self, void *context) {
1834 size_t offset(reinterpret_cast<size_t>(context));
1835 CYString &name([self cyname]);
1837 size_t size(name.size());
1840 char *text(name.data());
1843 if (!isdigit(text[0]))
1847 while (size != digits && isdigit(text[digits]))
1855 if (offset == 0 && zeros != 0) {
1856 memset(data, '0', zeros);
1857 memcpy(data + zeros, text, 4 - zeros);
1859 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1860 if (size <= offset - zeros)
1863 text += offset - zeros;
1864 size -= offset - zeros;
1867 memcpy(data, text, 4);
1869 memcpy(data, text, size);
1870 memset(data + size, 0, 4 - size);
1873 for (size_t i(0); i != 4; ++i)
1874 if (isalpha(data[i]))
1882 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1884 /* XXX: ntohl may be more honest */
1885 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1888 CYString &(*PackageName)(Package *self, SEL sel);
1890 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1891 _profile(PackageNameCompare)
1892 CYString &lhi(PackageName(lhs, @selector(cyname)));
1893 CYString &rhi(PackageName(rhs, @selector(cyname)));
1894 CFStringRef lhn(lhi), rhn(rhi);
1897 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1898 else if (rhn == NULL)
1899 return NSOrderedDescending;
1901 _profile(PackageNameCompare$NumbersLast)
1902 if (!lhi.empty() && !rhi.empty()) {
1903 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1904 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1905 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1906 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1907 return lha ? NSOrderedAscending : NSOrderedDescending;
1911 CFIndex length = CFStringGetLength(lhn);
1913 _profile(PackageNameCompare$Compare)
1914 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1919 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1920 return PackageNameCompare(*lhs, *rhs, context);
1923 struct PackageNameOrdering :
1924 std::binary_function<Package *, Package *, bool>
1926 _finline bool operator ()(Package *lhs, Package *rhs) const {
1927 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1931 @implementation Package
1933 - (NSString *) description {
1934 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1938 if (parsed_ != NULL)
1943 + (NSString *) webScriptNameForSelector:(SEL)selector {
1945 else if (selector == @selector(clear))
1947 else if (selector == @selector(getField:))
1949 else if (selector == @selector(hasTag:))
1951 else if (selector == @selector(install))
1953 else if (selector == @selector(remove))
1959 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1960 return [self webScriptNameForSelector:selector] == nil;
1963 + (NSArray *) _attributeKeys {
1964 return [NSArray arrayWithObjects:
1983 @"shortDescription",
1996 - (NSArray *) attributeKeys {
1997 return [[self class] _attributeKeys];
2000 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2001 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2004 - (NSArray *) relations {
2005 @synchronized (database_) {
2006 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2007 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2008 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2012 - (NSString *) getField:(NSString *)name {
2013 @synchronized (database_) {
2014 if ([database_ era] != era_ || file_.end())
2017 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2019 const char *start, *end;
2020 if (!parser.Find([name UTF8String], start, end))
2021 return (NSString *) [NSNull null];
2023 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2027 if (parsed_ != NULL)
2029 @synchronized (database_) {
2030 if ([database_ era] != era_ || file_.end())
2033 ParsedPackage *parsed(new ParsedPackage);
2036 _profile(Package$parse)
2037 pkgRecords::Parser *parser;
2039 _profile(Package$parse$Lookup)
2040 parser = &[database_ records]->Lookup(file_);
2045 _profile(Package$parse$Find)
2050 {"icon", &parsed->icon_},
2051 {"depiction", &parsed->depiction_},
2052 {"homepage", &parsed->homepage_},
2053 {"website", &website},
2054 {"bugs", &parsed->bugs_},
2055 {"support", &parsed->support_},
2056 {"sponsor", &parsed->sponsor_},
2057 {"author", &parsed->author_},
2060 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2061 const char *start, *end;
2063 if (parser->Find(names[i].name_, start, end)) {
2064 CYString &value(*names[i].value_);
2065 _profile(Package$parse$Value)
2066 value.set(pool_, start, end - start);
2072 _profile(Package$parse$Tagline)
2073 const char *start, *end;
2074 if (parser->ShortDesc(start, end)) {
2075 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2078 while (stop != start && stop[-1] == '\r')
2080 parsed->tagline_.set(pool_, start, stop - start);
2084 _profile(Package$parse$Retain)
2085 if (parsed->homepage_.empty())
2086 parsed->homepage_ = website;
2087 if (parsed->homepage_ == parsed->depiction_)
2088 parsed->homepage_.clear();
2093 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2094 if ((self = [super init]) != nil) {
2095 _profile(Package$initWithVersion)
2098 database_ = database;
2099 era_ = [database era];
2103 pkgCache::PkgIterator iterator(version.ParentPkg());
2104 iterator_ = iterator;
2106 _profile(Package$initWithVersion$Version)
2107 if (!version_.end())
2108 file_ = version_.FileList();
2110 pkgCache &cache([database_ cache]);
2111 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2115 _profile(Package$initWithVersion$Cache)
2116 name_.set(NULL, iterator.Display());
2118 latest_.set(NULL, StripVersion_(version_.VerStr()));
2120 pkgCache::VerIterator current(iterator.CurrentVer());
2122 installed_.set(NULL, StripVersion_(current.VerStr()));
2125 _profile(Package$initWithVersion$Tags)
2126 pkgCache::TagIterator tag(iterator.TagList());
2128 tags_ = [NSMutableArray arrayWithCapacity:8];
2130 const char *name(tag.Name());
2131 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2133 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2134 if (strcmp(name + 6, "enduser") == 0)
2136 else if (strcmp(name + 6, "hacker") == 0)
2138 else if (strcmp(name + 6, "developer") == 0)
2140 else if (strcmp(name + 6, "cydia") == 0)
2146 if (strncmp(name, "cydia::", 7) == 0) {
2147 if (strcmp(name + 7, "essential") == 0)
2149 else if (strcmp(name + 7, "obsolete") == 0)
2154 } while (!tag.end());
2158 _profile(Package$initWithVersion$Metadata)
2159 const char *mixed(iterator.Name());
2160 size_t size(strlen(mixed));
2161 char lower[size + 1];
2163 for (size_t i(0); i != size; ++i)
2164 lower[i] = mixed[i] | 0x20;
2167 PackageValue *metadata(PackageFind(lower, size));
2168 metadata_ = metadata;
2170 id_.set(NULL, metadata->name_, size);
2172 const char *latest(version_.VerStr());
2173 size_t length(strlen(latest));
2175 uint16_t vhash(hashlittle(latest, length));
2177 size_t capped(std::min<size_t>(8, length));
2178 latest = latest + length - capped;
2180 if (metadata->first_ == 0)
2181 metadata->first_ = now_;
2183 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2184 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2185 metadata->vhash_ = vhash;
2186 metadata->last_ = now_;
2187 } else if (metadata->last_ == 0)
2188 metadata->last_ = metadata->first_;
2191 _profile(Package$initWithVersion$Section)
2192 section_ = iterator.Section();
2195 _profile(Package$initWithVersion$Flags)
2196 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2197 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2202 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2203 pkgCache::VerIterator version;
2205 _profile(Package$packageWithIterator$GetCandidateVer)
2206 version = [database policy]->GetCandidateVer(iterator);
2214 _profile(Package$packageWithIterator$Allocate)
2215 package = [Package allocWithZone:zone];
2218 _profile(Package$packageWithIterator$Initialize)
2220 initWithVersion:version
2227 _profile(Package$packageWithIterator$Autorelease)
2228 package = [package autorelease];
2234 - (pkgCache::PkgIterator) iterator {
2238 - (NSString *) section {
2239 if (section$_ == nil) {
2240 if (section_ == NULL)
2243 _profile(Package$section$mappedSectionForPointer)
2244 section$_ = [database_ mappedSectionForPointer:section_];
2249 - (NSString *) simpleSection {
2250 if (NSString *section = [self section])
2251 return Simplify(section);
2256 - (NSString *) longSection {
2257 return LocalizeSection([self section]);
2260 - (NSString *) shortSection {
2261 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2264 - (NSString *) uri {
2267 pkgIndexFile *index;
2268 pkgCache::PkgFileIterator file(file_.File());
2269 if (![database_ list].FindIndex(file, index))
2271 return [NSString stringWithUTF8String:iterator_->Path];
2272 //return [NSString stringWithUTF8String:file.Site()];
2273 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2277 - (MIMEAddress *) maintainer {
2278 @synchronized (database_) {
2279 if ([database_ era] != era_ || file_.end())
2282 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2283 const std::string &maintainer(parser->Maintainer());
2284 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2288 @synchronized (database_) {
2289 if ([database_ era] != era_ || version_.end())
2292 return version_->InstalledSize;
2295 - (NSString *) longDescription {
2296 @synchronized (database_) {
2297 if ([database_ era] != era_ || file_.end())
2300 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2301 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2303 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2304 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2305 if ([lines count] < 2)
2308 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2309 for (size_t i(1), e([lines count]); i != e; ++i) {
2310 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2311 [trimmed addObject:trim];
2314 return [trimmed componentsJoinedByString:@"\n"];
2317 - (NSString *) shortDescription {
2318 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2322 _profile(Package$index)
2323 CFStringRef name((CFStringRef) [self name]);
2324 if (CFStringGetLength(name) == 0)
2326 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2327 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2329 return toupper(character);
2333 - (PackageValue *) metadata {
2338 PackageValue *metadata([self metadata]);
2339 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2342 - (bool) subscribed {
2343 return [self metadata]->subscribed_;
2346 - (bool) setSubscribed:(bool)subscribed {
2347 PackageValue *metadata([self metadata]);
2348 if (metadata->subscribed_ == subscribed)
2350 metadata->subscribed_ = subscribed;
2358 - (NSString *) latest {
2362 - (NSString *) installed {
2366 - (BOOL) uninstalled {
2367 return installed_.empty();
2371 return !version_.end();
2374 - (BOOL) upgradableAndEssential:(BOOL)essential {
2375 _profile(Package$upgradableAndEssential)
2376 pkgCache::VerIterator current(iterator_.CurrentVer());
2378 return essential && essential_;
2380 return !version_.end() && version_ != current;
2384 - (BOOL) essential {
2389 return [database_ cache][iterator_].InstBroken();
2392 - (BOOL) unfiltered {
2393 _profile(Package$unfiltered$obsolete)
2394 if (_unlikely(obsolete_))
2398 _profile(Package$unfiltered$hasSupportingRole)
2399 if (_unlikely(![self hasSupportingRole]))
2407 if (![self unfiltered])
2412 _profile(Package$visible$section)
2413 section = [self section];
2416 _profile(Package$visible$isSectionVisible)
2417 if (!isSectionVisible(section))
2425 unsigned char current(iterator_->CurrentState);
2426 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2429 - (BOOL) halfConfigured {
2430 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2433 - (BOOL) halfInstalled {
2434 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2438 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2439 return state.Mode != pkgDepCache::ModeKeep;
2442 - (NSString *) mode {
2443 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2445 switch (state.Mode) {
2446 case pkgDepCache::ModeDelete:
2447 if ((state.iFlags & pkgDepCache::Purge) != 0)
2451 case pkgDepCache::ModeKeep:
2452 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2453 return @"REINSTALL";
2454 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2458 case pkgDepCache::ModeInstall:
2459 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2460 return @"REINSTALL";
2461 else*/ switch (state.Status) {
2463 return @"DOWNGRADE";
2469 return @"NEW_INSTALL";
2480 - (NSString *) name {
2481 return name_.empty() ? id_ : name_;
2484 - (UIImage *) icon {
2485 NSString *section = [self simpleSection];
2488 if (parsed_ != NULL)
2489 if (NSString *href = parsed_->icon_)
2490 if ([href hasPrefix:@"file:///"])
2491 // XXX: correct escaping
2492 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2493 if (icon == nil) if (section != nil)
2494 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2495 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2496 if ([dicon hasPrefix:@"file:///"])
2497 // XXX: correct escaping
2498 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2500 icon = [UIImage applicationImageNamed:@"unknown.png"];
2504 - (NSString *) homepage {
2505 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2508 - (NSString *) depiction {
2509 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2512 - (MIMEAddress *) sponsor {
2513 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2516 - (MIMEAddress *) author {
2517 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2520 - (NSString *) support {
2521 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2524 - (NSArray *) files {
2525 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2526 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2529 fin.open([path UTF8String]);
2534 while (std::getline(fin, line))
2535 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2540 - (NSString *) state {
2541 @synchronized (database_) {
2542 if ([database_ era] != era_ || file_.end())
2545 switch (iterator_->CurrentState) {
2546 case pkgCache::State::NotInstalled:
2547 return @"NotInstalled";
2548 case pkgCache::State::UnPacked:
2550 case pkgCache::State::HalfConfigured:
2551 return @"HalfConfigured";
2552 case pkgCache::State::HalfInstalled:
2553 return @"HalfInstalled";
2554 case pkgCache::State::ConfigFiles:
2555 return @"ConfigFiles";
2556 case pkgCache::State::Installed:
2557 return @"Installed";
2558 case pkgCache::State::TriggersAwaited:
2559 return @"TriggersAwaited";
2560 case pkgCache::State::TriggersPending:
2561 return @"TriggersPending";
2564 return (NSString *) [NSNull null];
2567 - (NSString *) selection {
2568 @synchronized (database_) {
2569 if ([database_ era] != era_ || file_.end())
2572 switch (iterator_->SelectedState) {
2573 case pkgCache::State::Unknown:
2575 case pkgCache::State::Install:
2577 case pkgCache::State::Hold:
2579 case pkgCache::State::DeInstall:
2580 return @"DeInstall";
2581 case pkgCache::State::Purge:
2585 return (NSString *) [NSNull null];
2588 - (NSArray *) warnings {
2589 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2590 const char *name(iterator_.Name());
2592 size_t length(strlen(name));
2593 if (length < 2) invalid:
2594 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2595 else for (size_t i(0); i != length; ++i)
2597 /* XXX: technically this is not allowed */
2598 (name[i] < 'A' || name[i] > 'Z') &&
2599 (name[i] < 'a' || name[i] > 'z') &&
2600 (name[i] < '0' || name[i] > '9') &&
2601 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2604 if (strcmp(name, "cydia") != 0) {
2607 bool _private = false;
2610 bool repository = [[self section] isEqualToString:@"Repositories"];
2612 if (NSArray *files = [self files])
2613 for (NSString *file in files)
2614 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2616 else if (!user && [file isEqualToString:@"/User"])
2618 else if (!_private && [file isEqualToString:@"/private"])
2620 else if (!stash && [file isEqualToString:@"/var/stash"])
2623 /* XXX: this is not sensitive enough. only some folders are valid. */
2624 if (cydia && !repository)
2625 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2627 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2629 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2631 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2634 return [warnings count] == 0 ? nil : warnings;
2637 - (NSArray *) applications {
2638 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2640 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2642 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2643 if (NSArray *files = [self files])
2644 for (NSString *file in files)
2645 if (application_r(file)) {
2646 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2647 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2648 if ([id isEqualToString:me])
2651 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2653 display = application_r[1];
2655 NSString *bundle([file stringByDeletingLastPathComponent]);
2656 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2657 if (icon == nil || [icon length] == 0)
2659 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2661 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2662 [applications addObject:application];
2664 [application addObject:id];
2665 [application addObject:display];
2666 [application addObject:url];
2669 return [applications count] == 0 ? nil : applications;
2672 - (Source *) source {
2673 if (source_ == nil) {
2674 @synchronized (database_) {
2675 if ([database_ era] != era_ || file_.end())
2676 source_ = (Source *) [NSNull null];
2678 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2682 return source_ == (Source *) [NSNull null] ? nil : source_;
2689 - (BOOL) matches:(NSArray *)query {
2690 if (query == nil || [query count] == 0)
2702 length = [string length];
2704 for (NSString *term in query) {
2705 range = [string rangeOfString:term options:MatchCompareOptions_];
2706 if (range.location != NSNotFound)
2707 rank_ -= 10 * 100000 / length;
2710 string = [self name];
2712 for (NSString *term in query) {
2713 range = [string rangeOfString:term options:MatchCompareOptions_];
2714 if (range.location != NSNotFound)
2715 rank_ -= 6 * 100000 / length;
2718 string = [self shortDescription];
2719 length = [string length];
2720 NSUInteger stop(std::min<NSUInteger>(length, 100));
2722 for (NSString *term in query) {
2723 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2724 if (range.location != NSNotFound)
2725 rank_ -= 2 * 100000 / length;
2731 - (bool) hasSupportingRole {
2736 if ([Role_ isEqualToString:@"User"])
2740 if ([Role_ isEqualToString:@"Hacker"])
2744 if ([Role_ isEqualToString:@"Developer"])
2749 - (NSArray *) tags {
2753 - (BOOL) hasTag:(NSString *)tag {
2754 return tags_ == nil ? NO : [tags_ containsObject:tag];
2757 - (NSString *) primaryPurpose {
2758 for (NSString *tag in (NSArray *) tags_)
2759 if ([tag hasPrefix:@"purpose::"])
2760 return [tag substringFromIndex:9];
2764 - (NSArray *) purposes {
2765 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2766 for (NSString *tag in (NSArray *) tags_)
2767 if ([tag hasPrefix:@"purpose::"])
2768 [purposes addObject:[tag substringFromIndex:9]];
2769 return [purposes count] == 0 ? nil : purposes;
2772 - (bool) isCommercial {
2773 return [self hasTag:@"cydia::commercial"];
2776 - (void) setIndex:(size_t)index {
2777 if (metadata_->index_ != index)
2778 metadata_->index_ = index;
2781 - (CYString &) cyname {
2782 return name_.empty() ? id_ : name_;
2785 - (uint32_t) compareBySection:(NSArray *)sections {
2786 NSString *section([self section]);
2787 for (size_t i(0), e([sections count]); i != e; ++i) {
2788 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2792 return _not(uint32_t);
2796 @synchronized (database_) {
2797 pkgProblemResolver *resolver = [database_ resolver];
2798 resolver->Clear(iterator_);
2800 pkgCacheFile &cache([database_ cache]);
2801 cache->SetReInstall(iterator_, false);
2802 cache->MarkKeep(iterator_, false);
2806 @synchronized (database_) {
2807 pkgProblemResolver *resolver = [database_ resolver];
2808 resolver->Clear(iterator_);
2809 resolver->Protect(iterator_);
2811 pkgCacheFile &cache([database_ cache]);
2812 cache->SetReInstall(iterator_, false);
2813 cache->MarkInstall(iterator_, false);
2815 pkgDepCache::StateCache &state((*cache)[iterator_]);
2816 if (!state.Install())
2817 cache->SetReInstall(iterator_, true);
2821 @synchronized (database_) {
2822 pkgProblemResolver *resolver = [database_ resolver];
2823 resolver->Clear(iterator_);
2824 resolver->Remove(iterator_);
2825 resolver->Protect(iterator_);
2827 pkgCacheFile &cache([database_ cache]);
2828 cache->SetReInstall(iterator_, false);
2829 cache->MarkDelete(iterator_, true);
2832 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2833 _profile(Package$isUnfilteredAndSearchedForBy)
2836 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2837 value &= [self unfiltered];
2840 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2841 value &= [self matches:query];
2848 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2849 if ([search length] == 0)
2852 _profile(Package$isUnfilteredAndSelectedForBy)
2855 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2856 value &= [self unfiltered];
2859 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2860 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2867 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2868 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2871 - (bool) isVisibleInSection:(NSString *)name {
2872 NSString *section([self section]);
2876 section == nil && [name length] == 0 ||
2877 [name isEqualToString:section]
2878 ) && [self visible];
2881 - (bool) isVisibleInSource:(Source *)source {
2882 return [self source] == source && [self visible];
2887 /* Section Class {{{ */
2888 @interface Section : NSObject {
2893 _H<NSString> localized_;
2896 - (NSComparisonResult) compareByLocalized:(Section *)section;
2897 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2898 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2899 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2900 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2901 - (NSString *) name;
2908 - (void) addToCount;
2910 - (void) setCount:(size_t)count;
2911 - (NSString *) localized;
2915 @implementation Section
2917 - (NSComparisonResult) compareByLocalized:(Section *)section {
2918 NSString *lhs(localized_);
2919 NSString *rhs([section localized]);
2921 /*if ([lhs length] != 0 && [rhs length] != 0) {
2922 unichar lhc = [lhs characterAtIndex:0];
2923 unichar rhc = [rhs characterAtIndex:0];
2925 if (isalpha(lhc) && !isalpha(rhc))
2926 return NSOrderedAscending;
2927 else if (!isalpha(lhc) && isalpha(rhc))
2928 return NSOrderedDescending;
2931 return [lhs compare:rhs options:LaxCompareOptions_];
2934 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2935 if ((self = [self initWithName:name localize:NO]) != nil) {
2936 if (localized != nil)
2937 localized_ = localized;
2941 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2942 return [self initWithName:name row:0 localize:localize];
2945 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2946 if ((self = [super init]) != nil) {
2951 localized_ = LocalizeSection(name_);
2955 /* XXX: localize the index thingees */
2956 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2957 if ((self = [super init]) != nil) {
2958 name_ = [NSString stringWithCharacters:&index length:1];
2964 - (NSString *) name {
2984 - (void) addToCount {
2988 - (void) setCount:(size_t)count {
2992 - (NSString *) localized {
2999 static NSString *Colon_;
3001 static NSString *Error_;
3002 static NSString *Warning_;
3004 class CydiaLogCleaner :
3005 public pkgArchiveCleaner
3008 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3013 /* Database Implementation {{{ */
3014 @implementation Database
3016 + (Database *) sharedInstance {
3017 static _H<Database> instance;
3018 if (instance == nil)
3019 instance = [[[Database alloc] init] autorelease];
3027 - (void) releasePackages {
3028 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3029 CFArrayRemoveAllValues(packages_);
3033 // XXX: actually implement this thing
3035 [self releasePackages];
3036 apr_pool_destroy(pool_);
3037 NSRecycleZone(zone_);
3041 - (void) _readCydia:(NSNumber *)fd {
3042 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3043 std::istream is(&ib);
3046 static Pcre finish_r("^finish:([^:]*)$");
3048 while (std::getline(is, line)) {
3049 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3051 const char *data(line.c_str());
3052 size_t size = line.size();
3053 lprintf("C:%s\n", data);
3055 if (finish_r(data, size)) {
3056 NSString *finish = finish_r[1];
3057 int index = [Finishes_ indexOfObject:finish];
3058 if (index != INT_MAX && index > Finish_)
3068 - (void) _readStatus:(NSNumber *)fd {
3069 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3070 std::istream is(&ib);
3073 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3074 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3076 while (std::getline(is, line)) {
3077 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3079 const char *data(line.c_str());
3080 size_t size(line.size());
3081 lprintf("S:%s\n", data);
3083 if (conffile_r(data, size)) {
3084 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3085 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3086 } else if (strncmp(data, "status: ", 8) == 0) {
3087 // status: <package>: {unpacked,half-configured,installed}
3088 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3089 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3090 } else if (strncmp(data, "processing: ", 12) == 0) {
3091 // processing: configure: config-test
3092 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3093 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3094 } else if (pmstatus_r(data, size)) {
3095 std::string type([pmstatus_r[1] UTF8String]);
3097 NSString *package = pmstatus_r[2];
3098 if ([package isEqualToString:@"dpkg-exec"])
3101 float percent([pmstatus_r[3] floatValue]);
3102 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3104 NSString *string = pmstatus_r[4];
3106 if (type == "pmerror") {
3107 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3108 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3109 } else if (type == "pmstatus") {
3110 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3111 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3112 } else if (type == "pmconffile")
3113 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3115 lprintf("E:unknown pmstatus\n");
3117 lprintf("E:unknown status\n");
3125 - (void) _readOutput:(NSNumber *)fd {
3126 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3127 std::istream is(&ib);
3130 while (std::getline(is, line)) {
3131 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3133 lprintf("O:%s\n", line.c_str());
3135 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3136 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3148 - (Package *) packageWithName:(NSString *)name {
3149 @synchronized (self) {
3150 if (static_cast<pkgDepCache *>(cache_) == NULL)
3152 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3153 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3157 if ((self = [super init]) != nil) {
3164 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3165 apr_pool_create(&pool_, NULL);
3167 size_t capacity(MetaFile_->active_);
3173 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3174 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3178 _assert(pipe(fds) != -1);
3181 _config->Set("APT::Keep-Fds::", cydiafd_);
3182 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3185 detachNewThreadSelector:@selector(_readCydia:)
3187 withObject:[NSNumber numberWithInt:fds[0]]
3190 _assert(pipe(fds) != -1);
3194 detachNewThreadSelector:@selector(_readStatus:)
3196 withObject:[NSNumber numberWithInt:fds[0]]
3199 _assert(pipe(fds) != -1);
3200 _assert(dup2(fds[0], 0) != -1);
3201 _assert(close(fds[0]) != -1);
3203 input_ = fdopen(fds[1], "a");
3205 _assert(pipe(fds) != -1);
3206 _assert(dup2(fds[1], 1) != -1);
3207 _assert(close(fds[1]) != -1);
3210 detachNewThreadSelector:@selector(_readOutput:)
3212 withObject:[NSNumber numberWithInt:fds[0]]
3217 - (pkgCacheFile &) cache {
3221 - (pkgDepCache::Policy *) policy {
3225 - (pkgRecords *) records {
3229 - (pkgProblemResolver *) resolver {
3233 - (pkgAcquire &) fetcher {
3237 - (pkgSourceList &) list {
3241 - (NSArray *) packages {
3242 return (NSArray *) packages_;
3245 - (NSArray *) sources {
3249 - (Source *) sourceWithKey:(NSString *)key {
3250 for (Source *source in [self sources]) {
3251 if ([[source key] isEqualToString:key])
3256 - (bool) popErrorWithTitle:(NSString *)title {
3259 while (!_error->empty()) {
3261 bool warning(!_error->PopMessage(error));
3266 size_t size(error.size());
3267 if (size == 0 || error[size - 1] != '\n')
3269 error.resize(size - 1);
3272 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3274 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3280 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3281 return [self popErrorWithTitle:title] || !success;
3284 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3285 @synchronized (self) {
3288 [self releasePackages];
3291 [sourceList_ removeAllObjects];
3311 apr_pool_clear(pool_);
3313 NSRecycleZone(zone_);
3314 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3316 int chk(creat("/tmp/cydia.chk", 0644));
3320 if (invocation != nil)
3321 [invocation invoke];
3323 NSString *title(UCLocalize("DATABASE"));
3326 OpProgress progress;
3327 while (!cache_.Open(progress, true)) { pop:
3329 bool warning(!_error->PopMessage(error));
3330 lprintf("cache_.Open():[%s]\n", error.c_str());
3332 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3333 [delegate_ repairWithSelector:@selector(configure)];
3334 else if (error == "The package lists or status file could not be parsed or opened.")
3335 [delegate_ repairWithSelector:@selector(update)];
3336 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3337 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3338 // else if (error == "Malformed Status line")
3339 // else if (error == "The list of sources could not be read.")
3341 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3351 unlink("/tmp/cydia.chk");
3353 now_ = [[NSDate date] timeIntervalSince1970];
3355 policy_ = new pkgDepCache::Policy();
3356 records_ = new pkgRecords(cache_);
3357 resolver_ = new pkgProblemResolver(cache_);
3358 fetcher_ = new pkgAcquire(&status_);
3361 list_ = new pkgSourceList();
3362 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3365 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3366 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3370 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3373 if (cache_->BrokenCount() != 0) {
3374 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3377 if (cache_->BrokenCount() != 0) {
3378 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3382 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3386 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3387 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3388 [sourceList_ addObject:object];
3390 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3391 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3392 // XXX: this could be more intelligent
3393 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3394 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3396 sourceMap_[cached->ID] = object;
3401 /*std::vector<Package *> packages;
3402 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3407 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3408 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3409 //packages.push_back(package);
3410 CFArrayAppendValue(packages_, CFRetain(package));
3414 /*if (packages.empty())
3415 packages_ = [[NSArray alloc] init];
3417 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3420 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3421 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3422 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3430 /*if (!packages.empty())
3431 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3432 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3434 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3436 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3438 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3442 size_t count(CFArrayGetCount(packages_));
3443 MetaFile_->active_ = count;
3445 for (size_t index(0); index != count; ++index)
3446 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3453 @synchronized (self) {
3455 resolver_ = new pkgProblemResolver(cache_);
3457 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3458 if (!cache_[iterator].Keep())
3459 cache_->MarkKeep(iterator, false);
3460 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3461 cache_->SetReInstall(iterator, false);
3464 - (void) configure {
3465 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3467 system([dpkg UTF8String]);
3472 // XXX: I don't remember this condition
3477 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3479 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3481 if ([self popErrorWithTitle:title])
3485 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3487 CydiaLogCleaner cleaner;
3488 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3495 fetcher_->Shutdown();
3497 pkgRecords records(cache_);
3499 lock_ = new FileFd();
3500 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3502 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3504 if ([self popErrorWithTitle:title])
3508 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3511 manager_ = (_system->CreatePM(cache_));
3512 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3519 bool substrate(RestartSubstrate_);
3520 RestartSubstrate_ = false;
3522 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3524 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3526 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3528 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3529 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3532 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3534 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3536 [self popErrorWithTitle:title];
3540 bool failed = false;
3541 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3542 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3544 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3550 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3558 RestartSubstrate_ = true;
3561 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3563 if (_error->PendingError()) {
3568 if (result == pkgPackageManager::Failed) {
3573 if (result != pkgPackageManager::Completed) {
3578 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3580 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3582 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3583 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3586 if (![before isEqualToArray:after])
3591 NSString *title(UCLocalize("UPGRADE"));
3592 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3598 [self updateWithStatus:status_];
3601 - (void) updateWithStatus:(Status &)status {
3602 NSString *title(UCLocalize("REFRESHING_DATA"));
3605 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3609 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3610 if ([self popErrorWithTitle:title])
3613 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3615 bool success(ListUpdate(status, list, PulseInterval_));
3616 if (status.WasCancelled())
3619 [self popErrorWithTitle:title forOperation:success];
3620 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3624 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3627 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3628 delegate_ = delegate;
3631 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3632 progress_ = delegate;
3633 status_.setDelegate(delegate);
3636 - (NSObject<ProgressDelegate> *) progressDelegate {
3640 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3641 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3642 return i == sourceMap_.end() ? nil : i->second;
3645 - (NSString *) mappedSectionForPointer:(const char *)section {
3646 _H<NSString> *mapped;
3648 _profile(Database$mappedSectionForPointer$Cache)
3649 mapped = §ions_[section];
3652 if (*mapped == NULL) {
3653 size_t length(strlen(section));
3654 char spaced[length + 1];
3656 _profile(Database$mappedSectionForPointer$Replace)
3657 for (size_t index(0); index != length; ++index)
3658 spaced[index] = section[index] == '_' ? ' ' : section[index];
3659 spaced[length] = '\0';
3664 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3665 string = [NSString stringWithUTF8String:spaced];
3668 _profile(Database$mappedSectionForPointer$Map)
3669 string = [SectionMap_ objectForKey:string] ?: string;
3679 static _H<NSMutableSet> Diversions_;
3681 @interface Diversion : NSObject {
3684 _H<NSString> format_;
3689 @implementation Diversion
3691 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3692 if ((self = [super init]) != nil) {
3693 pattern_ = [from UTF8String];
3699 - (NSString *) divert:(NSString *)url {
3700 return !pattern_(url) ? nil : pattern_->*format_;
3703 + (NSURL *) divertURL:(NSURL *)url {
3705 NSString *href([url absoluteString]);
3707 for (Diversion *diversion in (id) Diversions_)
3708 if (NSString *diverted = [diversion divert:href]) {
3710 NSLog(@"div: %@", diverted);
3712 url = [NSURL URLWithString:diverted];
3719 - (NSString *) key {
3723 - (NSUInteger) hash {
3727 - (BOOL) isEqual:(Diversion *)object {
3728 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3733 @interface CydiaObject : NSObject {
3734 _H<IndirectDelegate> indirect_;
3735 _transient id delegate_;
3738 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3742 @interface CydiaWebViewController : CyteWebViewController {
3743 _H<CydiaObject> cydia_;
3746 + (void) addDiversion:(Diversion *)diversion;
3750 /* Web Scripting {{{ */
3751 @implementation CydiaObject
3753 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3754 if ((self = [super init]) != nil) {
3755 indirect_ = indirect;
3759 - (void) setDelegate:(id)delegate {
3760 delegate_ = delegate;
3763 + (NSArray *) _attributeKeys {
3764 return [NSArray arrayWithObjects:
3780 - (NSArray *) attributeKeys {
3781 return [[self class] _attributeKeys];
3784 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3785 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3788 - (NSString *) version {
3792 - (NSString *) device {
3793 return [[UIDevice currentDevice] uniqueIdentifier];
3796 - (NSString *) firmware {
3797 return [[UIDevice currentDevice] systemVersion];
3800 - (NSString *) hostname {
3801 return [[UIDevice currentDevice] name];
3804 - (NSString *) idiom {
3805 return (id) Idiom_ ?: [NSNull null];
3808 - (NSString *) plmn {
3809 return (id) PLMN_ ?: [NSNull null];
3812 - (NSString *) bbsnum {
3813 return (id) BBSNum_ ?: [NSNull null];
3816 - (NSString *) ecid {
3817 return (id) ChipID_ ?: [NSNull null];
3820 - (NSString *) serial {
3821 return SerialNumber_;
3824 - (NSString *) role {
3825 return (id) Role_ ?: [NSNull null];
3828 - (NSString *) model {
3829 return [NSString stringWithUTF8String:Machine_];
3832 - (NSString *) token {
3833 return (id) Token_ ?: [NSNull null];
3836 + (NSString *) webScriptNameForSelector:(SEL)selector {
3838 else if (selector == @selector(addBridgedHost:))
3839 return @"addBridgedHost";
3840 else if (selector == @selector(addInternalRedirect::))
3841 return @"addInternalRedirect";
3842 else if (selector == @selector(addPipelinedHost:scheme:))
3843 return @"addPipelinedHost";
3844 else if (selector == @selector(addTrivialSource:))
3845 return @"addTrivialSource";
3846 else if (selector == @selector(close))
3848 else if (selector == @selector(du:))
3850 else if (selector == @selector(stringWithFormat:arguments:))
3852 else if (selector == @selector(getAllSources))
3853 return @"getAllSourcs";
3854 else if (selector == @selector(getKernelNumber:))
3855 return @"getKernelNumber";
3856 else if (selector == @selector(getKernelString:))
3857 return @"getKernelString";
3858 else if (selector == @selector(getInstalledPackages))
3859 return @"getInstalledPackages";
3860 else if (selector == @selector(getIORegistryEntry::))
3861 return @"getIORegistryEntry";
3862 else if (selector == @selector(getLocaleIdentifier))
3863 return @"getLocaleIdentifier";
3864 else if (selector == @selector(getPreferredLanguages))
3865 return @"getPreferredLanguages";
3866 else if (selector == @selector(getPackageById:))
3867 return @"getPackageById";
3868 else if (selector == @selector(getSessionValue:))
3869 return @"getSessionValue";
3870 else if (selector == @selector(installPackages:))
3871 return @"installPackages";
3872 else if (selector == @selector(localizedStringForKey:value:table:))
3874 else if (selector == @selector(popViewController:))
3875 return @"popViewController";
3876 else if (selector == @selector(refreshSources))
3877 return @"refreshSources";
3878 else if (selector == @selector(removeButton))
3879 return @"removeButton";
3880 else if (selector == @selector(setSessionValue::))
3881 return @"setSessionValue";
3882 else if (selector == @selector(substitutePackageNames:))
3883 return @"substitutePackageNames";
3884 else if (selector == @selector(scrollToBottom:))
3885 return @"scrollToBottom";
3886 else if (selector == @selector(setAllowsNavigationAction:))
3887 return @"setAllowsNavigationAction";
3888 else if (selector == @selector(setBadgeValue:))
3889 return @"setBadgeValue";
3890 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3891 return @"setButtonImage";
3892 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3893 return @"setButtonTitle";
3894 else if (selector == @selector(setHidesBackButton:))
3895 return @"setHidesBackButton";
3896 else if (selector == @selector(setHidesNavigationBar:))
3897 return @"setHidesNavigationBar";
3898 else if (selector == @selector(setNavigationBarStyle:))
3899 return @"setNavigationBarStyle";
3900 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3901 return @"setNavigationBarTintColor";
3902 else if (selector == @selector(setPasteboardString:))
3903 return @"setPasteboardString";
3904 else if (selector == @selector(setPasteboardURL:))
3905 return @"setPasteboardURL";
3906 else if (selector == @selector(setToken:))
3908 else if (selector == @selector(setViewportWidth:))
3909 return @"setViewportWidth";
3910 else if (selector == @selector(statfs:))
3912 else if (selector == @selector(supports:))
3914 else if (selector == @selector(unload))
3920 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3921 return [self webScriptNameForSelector:selector] == nil;
3924 - (BOOL) supports:(NSString *)feature {
3925 return [feature isEqualToString:@"window.open"];
3929 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
3932 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3933 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3936 - (NSNumber *) getKernelNumber:(NSString *)name {
3937 const char *string([name UTF8String]);
3940 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3941 return (id) [NSNull null];
3943 if (size != sizeof(int))
3944 return (id) [NSNull null];
3947 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3948 return (id) [NSNull null];
3950 return [NSNumber numberWithInt:value];
3953 - (NSString *) getKernelString:(NSString *)name {
3954 const char *string([name UTF8String]);
3957 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3958 return (id) [NSNull null];
3960 char value[size + 1];
3961 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3962 return (id) [NSNull null];
3964 // XXX: just in case you request something ludicrous
3967 return [NSString stringWithCString:value];
3970 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3971 NSObject *value(CYIOGetValue([path UTF8String], entry));
3974 if ([value isKindOfClass:[NSData class]])
3975 value = CYHex((NSData *) value);
3980 - (id) getSessionValue:(NSString *)key {
3981 @synchronized (SessionData_) {
3982 return [SessionData_ objectForKey:key];
3985 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3986 @synchronized (SessionData_) {
3987 if (value == (id) [WebUndefined undefined])
3988 [SessionData_ removeObjectForKey:key];
3990 [SessionData_ setObject:value forKey:key];
3993 - (void) addBridgedHost:(NSString *)host {
3994 @synchronized (HostConfig_) {
3995 [BridgedHosts_ addObject:host];
3998 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
3999 @synchronized (HostConfig_) {
4000 if (scheme != (id) [WebUndefined undefined])
4001 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4003 [PipelinedHosts_ addObject:host];
4006 - (void) popViewController:(NSNumber *)value {
4007 if (value == (id) [WebUndefined undefined])
4008 value = [NSNumber numberWithBool:YES];
4009 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4012 - (void) addTrivialSource:(NSString *)href {
4013 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4016 - (void) refreshSources {
4017 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4020 - (NSArray *) getAllSources {
4021 return [[Database sharedInstance] sources];
4024 - (NSArray *) getInstalledPackages {
4025 Database *database([Database sharedInstance]);
4026 @synchronized (database) {
4027 NSArray *packages([database packages]);
4028 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4029 for (Package *package in packages)
4030 if (![package uninstalled])
4031 [installed addObject:package];
4035 - (Package *) getPackageById:(NSString *)id {
4036 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4040 return (Package *) [NSNull null];
4043 - (NSString *) getLocaleIdentifier {
4044 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4047 - (NSArray *) getPreferredLanguages {
4051 - (NSArray *) statfs:(NSString *)path {
4054 if (path == nil || statfs([path UTF8String], &stat) == -1)
4057 return [NSArray arrayWithObjects:
4058 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4059 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4060 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4064 - (NSNumber *) du:(NSString *)path {
4065 NSNumber *value(nil);
4068 _assert(pipe(fds) != -1);
4070 pid_t pid(ExecFork());
4072 _assert(dup2(fds[1], 1) != -1);
4073 _assert(close(fds[0]) != -1);
4074 _assert(close(fds[1]) != -1);
4075 /* XXX: this should probably not use du */
4076 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4081 _assert(close(fds[1]) != -1);
4083 if (FILE *du = fdopen(fds[0], "r")) {
4085 while (fgets(line, sizeof(line), du) != NULL) {
4086 size_t length(strlen(line));
4087 while (length != 0 && line[length - 1] == '\n')
4088 line[--length] = '\0';
4089 if (char *tab = strchr(line, '\t')) {
4091 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4096 } else _assert(close(fds[0]));
4100 if (waitpid(pid, &status, 0) == -1)
4103 else _assert(false);
4109 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4112 - (void) installPackages:(NSArray *)packages {
4113 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4116 - (NSString *) substitutePackageNames:(NSString *)message {
4117 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4118 for (size_t i(0), e([words count]); i != e; ++i) {
4119 NSString *word([words objectAtIndex:i]);
4120 if (Package *package = [[Database sharedInstance] packageWithName:word])
4121 [words replaceObjectAtIndex:i withObject:[package name]];
4124 return [words componentsJoinedByString:@" "];
4127 - (void) removeButton {
4128 [indirect_ removeButton];
4131 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4132 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4135 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4136 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4139 - (void) setBadgeValue:(id)value {
4140 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4143 - (void) setAllowsNavigationAction:(NSString *)value {
4144 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4147 - (void) setHidesBackButton:(NSString *)value {
4148 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4151 - (void) setHidesNavigationBar:(NSString *)value {
4152 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4155 - (void) setNavigationBarStyle:(NSString *)value {
4156 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4159 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4160 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4161 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4162 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4165 - (void) setPasteboardString:(NSString *)value {
4166 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4169 - (void) setPasteboardURL:(NSString *)value {
4170 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4173 - (void) _setToken:(NSString *)token {
4177 [Metadata_ removeObjectForKey:@"Token"];
4179 [Metadata_ setObject:Token_ forKey:@"Token"];
4184 - (void) setToken:(NSString *)token {
4185 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4188 - (void) scrollToBottom:(NSNumber *)animated {
4189 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4192 - (void) setViewportWidth:(float)width {
4193 [indirect_ setViewportWidthOnMainThread:width];
4196 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4197 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4198 unsigned count([arguments count]);
4200 for (unsigned i(0); i != count; ++i)
4201 values[i] = [arguments objectAtIndex:i];
4202 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4205 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4206 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4208 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4210 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4217 /* Cydia Browser Controller {{{ */
4218 @implementation CydiaWebViewController
4220 - (NSURL *) navigationURL {
4221 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4224 + (void) initialize {
4225 Diversions_ = [NSMutableSet setWithCapacity:0];
4228 + (void) addDiversion:(Diversion *)diversion {
4229 [Diversions_ addObject:diversion];
4232 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4233 [super webView:view didClearWindowObject:window forFrame:frame];
4235 WebDataSource *source([frame dataSource]);
4236 NSURLResponse *response([source response]);
4237 NSURL *url([response URL]);
4238 NSString *scheme([[url scheme] lowercaseString]);
4240 bool bridged(false);
4242 @synchronized (HostConfig_) {
4243 if ([scheme isEqualToString:@"file"])
4245 else if ([scheme isEqualToString:@"https"])
4246 if ([BridgedHosts_ containsObject:[url host]])
4251 [window setValue:cydia_ forKey:@"cydia"];
4254 - (void) _setupMail:(MFMailComposeViewController *)controller {
4255 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4257 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4258 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4261 - (NSURL *) URLWithURL:(NSURL *)url {
4262 return [Diversion divertURL:url];
4265 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4266 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4268 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4269 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4270 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4271 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4272 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4273 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4278 - (void) setDelegate:(id)delegate {
4279 [super setDelegate:delegate];
4280 [cydia_ setDelegate:delegate];
4283 - (NSString *) applicationNameForUserAgent {
4284 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4287 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4289 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4290 if (Product_ != nil)
4291 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4297 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4298 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4306 @interface NSObject (CydiaScript)
4307 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4310 @implementation NSObject (CydiaScript)
4312 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4318 @implementation NSArray (CydiaScript)
4320 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4321 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4322 for (size_t i(0), e([self count]); i != e; ++i)
4323 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4329 @implementation NSDictionary (CydiaScript)
4331 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4332 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4334 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4341 /* Confirmation Controller {{{ */
4342 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4343 if (!iterator.end())
4344 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4345 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4347 pkgCache::PkgIterator package(dep.TargetPkg());
4350 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4357 @protocol ConfirmationControllerDelegate
4358 - (void) cancelAndClear:(bool)clear;
4359 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4363 @interface ConfirmationController : CydiaWebViewController {
4364 _transient Database *database_;
4366 _H<UIAlertView> essential_;
4368 _H<NSDictionary> changes_;
4369 _H<NSMutableArray> issues_;
4370 _H<NSDictionary> sizes_;
4375 - (id) initWithDatabase:(Database *)database;
4379 @implementation ConfirmationController
4383 RestartSubstrate_ = true;
4384 [delegate_ confirmWithNavigationController:[self navigationController]];
4387 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4388 NSString *context([alert context]);
4390 if ([context isEqualToString:@"remove"]) {
4391 if (button == [alert cancelButtonIndex])
4392 [self dismissModalViewControllerAnimated:YES];
4393 else if (button == [alert firstOtherButtonIndex]) {
4397 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4398 } else if ([context isEqualToString:@"unable"]) {
4399 [self dismissModalViewControllerAnimated:YES];
4400 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4402 [super alertView:alert clickedButtonAtIndex:button];
4406 - (void) _doContinue {
4407 [self dismissModalViewControllerAnimated:YES];
4408 [delegate_ cancelAndClear:NO];
4411 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4412 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4416 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4417 [super webView:view didClearWindowObject:window forFrame:frame];
4419 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4420 (id) changes_, @"changes",
4421 (id) issues_, @"issues",
4422 (id) sizes_, @"sizes",
4424 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4427 - (id) initWithDatabase:(Database *)database {
4428 if ((self = [super init]) != nil) {
4429 database_ = database;
4431 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4432 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4433 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4434 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4435 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4439 pkgCacheFile &cache([database_ cache]);
4440 NSArray *packages([database_ packages]);
4441 pkgDepCache::Policy *policy([database_ policy]);
4443 issues_ = [NSMutableArray arrayWithCapacity:4];
4445 for (Package *package in packages) {
4446 pkgCache::PkgIterator iterator([package iterator]);
4447 NSString *name([package id]);
4449 if ([package broken]) {
4450 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4452 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4454 reasons, @"reasons",
4457 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4461 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4462 pkgCache::DepIterator start;
4463 pkgCache::DepIterator end;
4464 dep.GlobOr(start, end); // ++dep
4466 if (!cache->IsImportantDep(end))
4468 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4471 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4473 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4474 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4475 clauses, @"clauses",
4479 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4481 pkgCache::PkgIterator target(start.TargetPkg());
4482 if (target->ProvidesList != 0)
4483 reason = @"missing";
4485 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4487 reason = @"installed";
4488 installed = [NSString stringWithUTF8String:ver.VerStr()];
4489 } else if (!cache[target].CandidateVerIter(cache).end())
4490 reason = @"uninstalled";
4491 else if (target->ProvidesList == 0)
4492 reason = @"uninstallable";
4494 reason = @"virtual";
4497 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4498 [NSString stringWithUTF8String:start.CompType()], @"operator",
4499 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4502 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4503 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4504 version, @"version",
4506 installed, @"installed",
4509 // yes, seriously. (wtf?)
4517 pkgDepCache::StateCache &state(cache[iterator]);
4519 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4521 if (state.NewInstall())
4522 [installs addObject:name];
4523 // XXX: else if (state.Install())
4524 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4525 [reinstalls addObject:name];
4526 // XXX: move before previous if
4527 else if (state.Upgrade())
4528 [upgrades addObject:name];
4529 else if (state.Downgrade())
4530 [downgrades addObject:name];
4531 else if (!state.Delete())
4532 // XXX: _assert(state.Keep());
4534 else if (special_r(name))
4535 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4536 [NSNull null], @"package",
4537 [NSArray arrayWithObjects:
4538 [NSDictionary dictionaryWithObjectsAndKeys:
4539 @"Conflicts", @"relationship",
4540 [NSArray arrayWithObjects:
4541 [NSDictionary dictionaryWithObjectsAndKeys:
4543 [NSNull null], @"version",
4544 @"installed", @"reason",
4551 if ([package essential])
4553 [removes addObject:name];
4556 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4557 substrate_ |= DepSubstrate(iterator.CurrentVer());
4562 else if (Advanced_) {
4563 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4565 essential_ = [[[UIAlertView alloc]
4566 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4567 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4569 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4571 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4575 [essential_ setContext:@"remove"];
4577 essential_ = [[[UIAlertView alloc]
4578 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4579 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4581 cancelButtonTitle:UCLocalize("OKAY")
4582 otherButtonTitles:nil
4585 [essential_ setContext:@"unable"];
4588 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4589 installs, @"installs",
4590 reinstalls, @"reinstalls",
4591 upgrades, @"upgrades",
4592 downgrades, @"downgrades",
4593 removes, @"removes",
4596 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4597 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4598 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4601 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4605 - (UIBarButtonItem *) leftButton {
4606 return [[[UIBarButtonItem alloc]
4607 initWithTitle:UCLocalize("CANCEL")
4608 style:UIBarButtonItemStylePlain
4610 action:@selector(cancelButtonClicked)
4615 - (void) applyRightButton {
4616 if ([issues_ count] == 0 && ![self isLoading])
4617 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4618 initWithTitle:UCLocalize("CONFIRM")
4619 style:UIBarButtonItemStyleDone
4621 action:@selector(confirmButtonClicked)
4624 [[self navigationItem] setRightBarButtonItem:nil];
4628 - (void) cancelButtonClicked {
4629 [self dismissModalViewControllerAnimated:YES];
4630 [delegate_ cancelAndClear:YES];
4634 - (void) confirmButtonClicked {
4635 if (essential_ != nil)
4645 /* Progress Data {{{ */
4646 @interface CydiaProgressData : NSObject {
4647 _transient id delegate_;
4656 _H<NSMutableArray> events_;
4657 _H<NSString> title_;
4659 _H<NSString> status_;
4660 _H<NSString> finish_;
4665 @implementation CydiaProgressData
4667 + (NSArray *) _attributeKeys {
4668 return [NSArray arrayWithObjects:
4680 - (NSArray *) attributeKeys {
4681 return [[self class] _attributeKeys];
4684 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4685 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4689 if ((self = [super init]) != nil) {
4690 events_ = [NSMutableArray arrayWithCapacity:32];
4694 - (void) setDelegate:(id)delegate {
4695 delegate_ = delegate;
4698 - (void) setPercent:(float)value {
4702 - (NSNumber *) percent {
4703 return [NSNumber numberWithFloat:percent_];
4706 - (void) setCurrent:(float)value {
4710 - (NSNumber *) current {
4711 return [NSNumber numberWithFloat:current_];
4714 - (void) setTotal:(float)value {
4718 - (NSNumber *) total {
4719 return [NSNumber numberWithFloat:total_];
4722 - (void) setSpeed:(float)value {
4726 - (NSNumber *) speed {
4727 return [NSNumber numberWithFloat:speed_];
4730 - (NSArray *) events {
4734 - (void) removeAllEvents {
4735 [events_ removeAllObjects];
4738 - (void) addEvent:(CydiaProgressEvent *)event {
4739 [events_ addObject:event];
4742 - (void) setTitle:(NSString *)text {
4746 - (NSString *) title {
4750 - (void) setFinish:(NSString *)text {
4754 - (NSString *) finish {
4755 return (id) finish_ ?: [NSNull null];
4758 - (void) setRunning:(bool)running {
4762 - (NSNumber *) running {
4763 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4768 /* Progress Controller {{{ */
4769 @interface ProgressController : CydiaWebViewController <
4772 _transient Database *database_;
4773 _H<CydiaProgressData, 1> progress_;
4777 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4779 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4781 - (void) setTitle:(NSString *)title;
4782 - (void) setCancellable:(bool)cancellable;
4786 @implementation ProgressController
4789 [database_ setProgressDelegate:nil];
4793 - (UIBarButtonItem *) leftButton {
4794 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4795 initWithTitle:UCLocalize("CANCEL")
4796 style:UIBarButtonItemStylePlain
4798 action:@selector(cancel)
4799 ] autorelease] : nil;
4802 - (void) updateCancel {
4803 [super applyLeftButton];
4806 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4807 if ((self = [super init]) != nil) {
4808 database_ = database;
4809 delegate_ = delegate;
4811 [database_ setProgressDelegate:self];
4813 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4814 [progress_ setDelegate:self];
4816 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4818 [scroller_ setBackgroundColor:[UIColor blackColor]];
4820 [[self navigationItem] setHidesBackButton:YES];
4822 [self updateCancel];
4826 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4827 [super webView:view didClearWindowObject:window forFrame:frame];
4828 [window setValue:progress_ forKey:@"cydiaProgress"];
4831 - (void) updateProgress {
4832 [self dispatchEvent:@"CydiaProgressUpdate"];
4835 - (void) viewWillAppear:(BOOL)animated {
4836 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4837 [super viewWillAppear:animated];
4841 UpdateExternalStatus(0);
4848 [delegate_ terminateWithSuccess];
4849 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4850 [delegate_ suspendWithAnimation:YES];
4852 [delegate_ suspend];*/
4864 system("/usr/bin/sbreload");
4870 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4871 SBReboot(SBSSpringBoardServerPort());
4873 reboot2(RB_AUTOBOOT);
4880 - (void) setTitle:(NSString *)title {
4881 [progress_ setTitle:title];
4882 [self updateProgress];
4885 - (UIBarButtonItem *) rightButton {
4886 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4887 initWithTitle:UCLocalize("CLOSE")
4888 style:UIBarButtonItemStylePlain
4890 action:@selector(close)
4894 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4895 UpdateExternalStatus(1);
4897 [progress_ setRunning:true];
4898 [self setTitle:title];
4899 // implicit updateProgress
4901 SHA1SumValue notifyconf; {
4903 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4906 MMap mmap(file, MMap::ReadOnly);
4908 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4909 notifyconf = sha1.Result();
4913 SHA1SumValue springlist; {
4915 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4918 MMap mmap(file, MMap::ReadOnly);
4920 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4921 springlist = sha1.Result();
4925 if (invocation != nil) {
4926 [invocation yieldToSelector:@selector(invoke)];
4927 [self setTitle:@"COMPLETE"];
4932 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4935 MMap mmap(file, MMap::ReadOnly);
4937 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4938 if (!(notifyconf == sha1.Result()))
4945 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4948 MMap mmap(file, MMap::ReadOnly);
4950 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4951 if (!(springlist == sha1.Result()))
4957 if (RestartSubstrate_)
4961 RestartSubstrate_ = false;
4964 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4965 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
4966 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
4967 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4968 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
4972 system("su -c /usr/bin/uicache mobile");
4975 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
4977 [progress_ setRunning:false];
4978 [self updateProgress];
4980 [self applyRightButton];
4983 - (void) addProgressEvent:(CydiaProgressEvent *)event {
4984 [progress_ addEvent:event];
4985 [self updateProgress];
4988 - (bool) isProgressCancelled {
4989 return cancel_ == 2;
4994 [self updateCancel];
4997 - (void) setCancellable:(bool)cancellable {
4998 unsigned cancel(cancel_);
5002 else if (cancel_ == 0)
5005 if (cancel != cancel_)
5006 [self updateCancel];
5009 - (void) setProgressCancellable:(NSNumber *)cancellable {
5010 [self setCancellable:[cancellable boolValue]];
5013 - (void) setProgressPercent:(NSNumber *)percent {
5014 [progress_ setPercent:[percent floatValue]];
5015 [self updateProgress];
5018 - (void) setProgressStatus:(NSDictionary *)status {
5019 if (status == nil) {
5020 [progress_ setCurrent:0];
5021 [progress_ setTotal:0];
5022 [progress_ setSpeed:0];
5024 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5026 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5027 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5028 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5031 [self updateProgress];
5037 /* Package Cell {{{ */
5038 @interface PackageCell : CyteTableViewCell <
5039 CyteTableViewCellDelegate
5043 _H<NSString> description_;
5045 _H<NSString> source_;
5047 _H<Package> package_;
5048 _H<UIImage> placard_;
5052 - (PackageCell *) init;
5053 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5055 - (void) drawContentRect:(CGRect)rect;
5059 @implementation PackageCell
5061 - (PackageCell *) init {
5062 CGRect frame(CGRectMake(0, 0, 320, 74));
5063 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5064 UIView *content([self contentView]);
5065 CGRect bounds([content bounds]);
5067 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5068 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5069 [content addSubview:content_];
5071 [content_ setDelegate:self];
5072 [content_ setOpaque:YES];
5076 - (NSString *) accessibilityLabel {
5077 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5080 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5081 summarized_ = summary;
5093 Source *source = [package source];
5095 icon_ = [package icon];
5097 if (NSString *name = [package name])
5098 name_ = [NSString stringWithString:name];
5100 NSString *description(nil);
5102 if (description == nil && IsWildcat_)
5103 description = [package longDescription];
5104 if (description == nil)
5105 description = [package shortDescription];
5107 if (description != nil)
5108 description_ = [NSString stringWithString:description];
5110 commercial_ = [package isCommercial];
5114 NSString *label = nil;
5115 bool trusted = false;
5117 if (source != nil) {
5118 label = [source label];
5119 trusted = [source trusted];
5120 } else if ([[package id] isEqualToString:@"firmware"])
5121 label = UCLocalize("APPLE");
5123 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5125 NSString *from(label);
5127 NSString *section = [package simpleSection];
5128 if (section != nil && ![section isEqualToString:label]) {
5129 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5130 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5133 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5135 if (NSString *purpose = [package primaryPurpose])
5136 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5141 if (NSString *mode = [package_ mode]) {
5142 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5143 color = RemovingColor_;
5144 //placard = @"removing";
5146 color = InstallingColor_;
5147 //placard = @"installing";
5150 // XXX: the removing/installing placards are not @2x
5153 color = [UIColor whiteColor];
5155 if ([package installed] != nil)
5156 placard = @"installed";
5161 [content_ setBackgroundColor:color];
5164 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5166 [self setNeedsDisplay];
5167 [content_ setNeedsDisplay];
5170 - (void) drawSummaryContentRect:(CGRect)rect {
5171 bool highlighted(highlighted_);
5172 float width([self bounds].size.width);
5176 rect.size = [(UIImage *) icon_ size];
5178 rect.size.width /= 4;
5179 rect.size.height /= 4;
5181 rect.origin.x = 14 - rect.size.width / 4;
5182 rect.origin.y = 14 - rect.size.height / 4;
5184 [icon_ drawInRect:rect];
5187 if (badge_ != nil) {
5189 rect.size = [(UIImage *) badge_ size];
5191 rect.size.width /= 4;
5192 rect.size.height /= 4;
5194 rect.origin.x = 20 - rect.size.width / 4;
5195 rect.origin.y = 20 - rect.size.height / 4;
5197 [badge_ drawInRect:rect];
5204 UISetColor(commercial_ ? Purple_ : Black_);
5205 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5207 if (placard_ != nil)
5208 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5211 - (void) drawNormalContentRect:(CGRect)rect {
5212 bool highlighted(highlighted_);
5213 float width([self bounds].size.width);
5217 rect.size = [(UIImage *) icon_ size];
5219 rect.size.width /= 2;
5220 rect.size.height /= 2;
5222 rect.origin.x = 25 - rect.size.width / 2;
5223 rect.origin.y = 25 - rect.size.height / 2;
5225 [icon_ drawInRect:rect];
5228 if (badge_ != nil) {
5230 rect.size = [(UIImage *) badge_ size];
5232 rect.size.width /= 2;
5233 rect.size.height /= 2;
5235 rect.origin.x = 36 - rect.size.width / 2;
5236 rect.origin.y = 36 - rect.size.height / 2;
5238 [badge_ drawInRect:rect];
5245 UISetColor(commercial_ ? Purple_ : Black_);
5246 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5247 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5250 UISetColor(commercial_ ? Purplish_ : Gray_);
5251 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5253 if (placard_ != nil)
5254 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5257 - (void) drawContentRect:(CGRect)rect {
5259 [self drawSummaryContentRect:rect];
5261 [self drawNormalContentRect:rect];
5266 /* Section Cell {{{ */
5267 @interface SectionCell : CyteTableViewCell <
5268 CyteTableViewCellDelegate
5270 _H<NSString> basic_;
5271 _H<NSString> section_;
5273 _H<NSString> count_;
5275 _H<UISwitch> switch_;
5279 - (void) setSection:(Section *)section editing:(BOOL)editing;
5283 @implementation SectionCell
5285 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5286 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5287 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5288 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5289 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5291 UIView *content([self contentView]);
5292 CGRect bounds([content bounds]);
5294 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5295 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5296 [content addSubview:content_];
5297 [content_ setBackgroundColor:[UIColor whiteColor]];
5299 [content_ setDelegate:self];
5303 - (void) onSwitch:(id)sender {
5304 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5305 if (metadata == nil) {
5306 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5307 [Sections_ setObject:metadata forKey:basic_];
5310 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5314 - (void) setSection:(Section *)section editing:(BOOL)editing {
5315 if (editing != editing_) {
5317 [switch_ removeFromSuperview];
5319 [self addSubview:switch_];
5328 if (section == nil) {
5329 name_ = UCLocalize("ALL_PACKAGES");
5332 basic_ = [section name];
5333 section_ = [section localized];
5335 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5336 count_ = [NSString stringWithFormat:@"%d", [section count]];
5339 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5342 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5343 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5345 [content_ setNeedsDisplay];
5348 - (void) setFrame:(CGRect)frame {
5349 [super setFrame:frame];
5351 CGRect rect([switch_ frame]);
5352 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5355 - (NSString *) accessibilityLabel {
5359 - (void) drawContentRect:(CGRect)rect {
5360 bool highlighted(highlighted_ && !editing_);
5362 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5367 float width(rect.size.width);
5373 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5375 CGSize size = [count_ sizeWithFont:Font14_];
5379 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5385 /* File Table {{{ */
5386 @interface FileTable : CyteViewController <
5387 UITableViewDataSource,
5390 _transient Database *database_;
5391 _H<Package> package_;
5393 _H<NSMutableArray> files_;
5394 _H<UITableView, 2> list_;
5397 - (id) initWithDatabase:(Database *)database;
5398 - (void) setPackage:(Package *)package;
5402 @implementation FileTable
5404 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5405 return files_ == nil ? 0 : [files_ count];
5408 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5412 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5413 static NSString *reuseIdentifier = @"Cell";
5415 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5417 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5418 [cell setFont:[UIFont systemFontOfSize:16]];
5420 [cell setText:[files_ objectAtIndex:indexPath.row]];
5421 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5426 - (NSURL *) navigationURL {
5427 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5431 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5433 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5434 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5435 [list_ setRowHeight:24.0f];
5436 [(UITableView *) list_ setDataSource:self];
5437 [list_ setDelegate:self];
5438 [[self view] addSubview:list_];
5441 - (void) viewDidLoad {
5442 [super viewDidLoad];
5444 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5447 - (void) releaseSubviews {
5450 [super releaseSubviews];
5453 - (id) initWithDatabase:(Database *)database {
5454 if ((self = [super init]) != nil) {
5455 database_ = database;
5457 files_ = [NSMutableArray arrayWithCapacity:32];
5461 - (void) setPackage:(Package *)package {
5465 [files_ removeAllObjects];
5467 if (package != nil) {
5469 name_ = [package id];
5471 if (NSArray *files = [package files])
5472 [files_ addObjectsFromArray:files];
5474 if ([files_ count] != 0) {
5475 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5476 [files_ removeObjectAtIndex:0];
5477 [files_ sortUsingSelector:@selector(compareByPath:)];
5479 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5480 [stack addObject:@"/"];
5482 for (int i(0), e([files_ count]); i != e; ++i) {
5483 NSString *file = [files_ objectAtIndex:i];
5484 while (![file hasPrefix:[stack lastObject]])
5485 [stack removeLastObject];
5486 NSString *directory = [stack lastObject];
5487 [stack addObject:[file stringByAppendingString:@"/"]];
5488 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5489 ([stack count] - 2) * 3, "",
5490 [file substringFromIndex:[directory length]]
5499 - (void) reloadData {
5502 [self setPackage:[database_ packageWithName:name_]];
5507 /* Package Controller {{{ */
5508 @interface CYPackageController : CydiaWebViewController <
5509 UIActionSheetDelegate
5511 _transient Database *database_;
5512 _H<Package> package_;
5515 _H<NSMutableArray> buttons_;
5516 _H<UIBarButtonItem> button_;
5519 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5523 @implementation CYPackageController
5525 - (NSURL *) navigationURL {
5526 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5529 /* XXX: this is not safe at all... localization of /fail/ */
5530 - (void) _clickButtonWithName:(NSString *)name {
5531 if ([name isEqualToString:UCLocalize("CLEAR")])
5532 [delegate_ clearPackage:package_];
5533 else if ([name isEqualToString:UCLocalize("INSTALL")])
5534 [delegate_ installPackage:package_];
5535 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5536 [delegate_ installPackage:package_];
5537 else if ([name isEqualToString:UCLocalize("REMOVE")])
5538 [delegate_ removePackage:package_];
5539 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5540 [delegate_ installPackage:package_];
5541 else _assert(false);
5544 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5545 NSString *context([sheet context]);
5547 if ([context isEqualToString:@"modify"]) {
5548 if (button != [sheet cancelButtonIndex]) {
5549 NSString *buttonName = [buttons_ objectAtIndex:button];
5550 [self _clickButtonWithName:buttonName];
5553 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5557 - (bool) _allowJavaScriptPanel {
5562 - (void) _customButtonClicked {
5563 int count([buttons_ count]);
5568 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5570 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5571 [buttons addObjectsFromArray:buttons_];
5573 UIActionSheet *sheet = [[[UIActionSheet alloc]
5576 cancelButtonTitle:nil
5577 destructiveButtonTitle:nil
5578 otherButtonTitles:nil
5581 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5583 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5584 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5586 [sheet setContext:@"modify"];
5588 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5592 // We don't want to allow non-commercial packages to do custom things to the install button,
5593 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5594 - (void) customButtonClicked {
5596 [super customButtonClicked];
5598 [self _customButtonClicked];
5601 - (void) reloadButtonClicked {
5602 // Don't reload a commerical package by tapping the loading button,
5603 // but if it's not an Install button, we should forward it on.
5604 if (![package_ uninstalled])
5605 [self _customButtonClicked];
5608 - (void) applyLoadingTitle {
5609 // Don't show "Loading" as the title. Ever.
5612 - (UIBarButtonItem *) rightButton {
5617 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5618 if ((self = [super init]) != nil) {
5619 database_ = database;
5620 buttons_ = [NSMutableArray arrayWithCapacity:4];
5621 name_ = [NSString stringWithString:name];
5622 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5626 - (void) reloadData {
5629 package_ = [database_ packageWithName:name_];
5631 [buttons_ removeAllObjects];
5633 if (package_ != nil) {
5634 [(Package *) package_ parse];
5636 commercial_ = [package_ isCommercial];
5638 if ([package_ mode] != nil)
5639 [buttons_ addObject:UCLocalize("CLEAR")];
5640 if ([package_ source] == nil);
5641 else if ([package_ upgradableAndEssential:NO])
5642 [buttons_ addObject:UCLocalize("UPGRADE")];
5643 else if ([package_ uninstalled])
5644 [buttons_ addObject:UCLocalize("INSTALL")];
5646 [buttons_ addObject:UCLocalize("REINSTALL")];
5647 if (![package_ uninstalled])
5648 [buttons_ addObject:UCLocalize("REMOVE")];
5652 switch ([buttons_ count]) {
5653 case 0: title = nil; break;
5654 case 1: title = [buttons_ objectAtIndex:0]; break;
5655 default: title = UCLocalize("MODIFY"); break;
5658 button_ = [[[UIBarButtonItem alloc]
5660 style:UIBarButtonItemStylePlain
5662 action:@selector(customButtonClicked)
5666 - (bool) isLoading {
5667 return commercial_ ? [super isLoading] : false;
5673 /* Package List Controller {{{ */
5674 @interface PackageListController : CyteViewController <
5675 UITableViewDataSource,
5678 _transient Database *database_;
5680 _H<NSArray> packages_;
5681 _H<NSMutableArray> sections_;
5682 _H<UITableView, 2> list_;
5683 _H<NSMutableArray> index_;
5684 _H<NSMutableDictionary> indices_;
5685 _H<NSString> title_;
5686 unsigned reloading_;
5689 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5690 - (void) setDelegate:(id)delegate;
5691 - (void) resetCursor;
5696 @implementation PackageListController
5698 - (bool) isSummarized {
5702 - (bool) showsSections {
5706 - (void) deselectWithAnimation:(BOOL)animated {
5707 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5710 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5711 CGRect base = [[self view] bounds];
5712 base.size.height -= bounds.size.height;
5713 base.origin = [list_ frame].origin;
5715 [UIView beginAnimations:nil context:NULL];
5716 [UIView setAnimationBeginsFromCurrentState:YES];
5717 [UIView setAnimationCurve:curve];
5718 [UIView setAnimationDuration:duration];
5719 [list_ setFrame:base];
5720 [UIView commitAnimations];
5723 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5724 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5727 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5728 [self resizeForKeyboardBounds:bounds duration:0];
5731 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5732 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5733 *curve = UIViewAnimationCurveEaseInOut;
5735 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5737 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5740 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5743 - (void) keyboardWillShow:(NSNotification *)notification {
5746 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5747 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5749 NSTimeInterval duration;
5750 UIViewAnimationCurve curve;
5751 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5753 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);
5754 UIViewController *base = self;
5755 while ([base parentViewController] != nil)
5756 base = [base parentViewController];
5757 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5758 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5760 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5761 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5763 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5766 - (void) keyboardWillHide:(NSNotification *)notification {
5767 NSTimeInterval duration;
5768 UIViewAnimationCurve curve;
5769 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5771 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5774 - (void) viewWillAppear:(BOOL)animated {
5775 [super viewWillAppear:animated];
5777 [self resizeForKeyboardBounds:CGRectZero];
5778 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5779 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5782 - (void) viewWillDisappear:(BOOL)animated {
5783 [super viewWillDisappear:animated];
5785 [self resizeForKeyboardBounds:CGRectZero];
5786 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5787 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5790 - (void) viewDidAppear:(BOOL)animated {
5791 [super viewDidAppear:animated];
5792 [self deselectWithAnimation:animated];
5795 - (void) didSelectPackage:(Package *)package {
5796 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5797 [view setDelegate:delegate_];
5798 [[self navigationController] pushViewController:view animated:YES];
5801 #if TryIndexedCollation
5802 + (BOOL) hasIndexedCollation {
5803 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5807 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5808 NSInteger count([sections_ count]);
5809 return count == 0 ? 1 : count;
5812 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5813 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5815 return [[sections_ objectAtIndex:section] name];
5818 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5819 if ([sections_ count] == 0)
5821 return [[sections_ objectAtIndex:section] count];
5824 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5825 @synchronized (database_) {
5826 if ([database_ era] != era_)
5829 Section *section([sections_ objectAtIndex:[path section]]);
5830 NSInteger row([path row]);
5831 Package *package([packages_ objectAtIndex:([section row] + row)]);
5832 return [[package retain] autorelease];
5835 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5836 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5838 cell = [[[PackageCell alloc] init] autorelease];
5839 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5843 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5844 Package *package([self packageAtIndexPath:path]);
5845 package = [database_ packageWithName:[package id]];
5846 [self didSelectPackage:package];
5849 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5850 if ([self showsSections])
5856 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5857 #if TryIndexedCollation
5858 if ([[self class] hasIndexedCollation]) {
5859 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5866 - (void) updateHeight {
5867 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5870 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5871 if ((self = [super init]) != nil) {
5872 database_ = database;
5873 title_ = [title copy];
5874 [[self navigationItem] setTitle:title_];
5876 #if TryIndexedCollation
5877 if ([[self class] hasIndexedCollation])
5878 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5881 index_ = [NSMutableArray arrayWithCapacity:32];
5883 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5885 packages_ = [NSArray array];
5886 sections_ = [NSMutableArray arrayWithCapacity:16];
5891 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5893 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5894 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5895 [[self view] addSubview:list_];
5897 // XXX: is 20 the most optimal number here?
5898 [list_ setSectionIndexMinimumDisplayRowCount:20];
5900 [(UITableView *) list_ setDataSource:self];
5901 [list_ setDelegate:self];
5903 [self updateHeight];
5906 - (void) releaseSubviews {
5909 [super releaseSubviews];
5912 - (void) setDelegate:(id)delegate {
5913 delegate_ = delegate;
5916 - (bool) shouldYield {
5920 - (bool) shouldBlock {
5924 - (NSMutableArray *) _reloadPackages {
5925 @synchronized (database_) {
5926 era_ = [database_ era];
5927 NSArray *packages([database_ packages]);
5929 return [NSMutableArray arrayWithArray:packages];
5932 - (void) _reloadData {
5933 if (reloading_ != 0) {
5940 if ([self shouldYield]) {
5944 if (![self shouldBlock])
5947 hud = [delegate_ addProgressHUD];
5948 [hud setText:UCLocalize("LOADING")];
5952 packages = [self yieldToSelector:@selector(_reloadPackages)];
5955 [delegate_ removeProgressHUD:hud];
5956 } while (reloading_ == 2);
5960 packages = [self _reloadPackages];
5963 packages_ = packages;
5965 [indices_ removeAllObjects];
5966 [sections_ removeAllObjects];
5968 Section *section = nil;
5970 #if TryIndexedCollation
5971 if ([[self class] hasIndexedCollation]) {
5972 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5973 NSArray *titles = [collation sectionIndexTitles];
5976 _profile(PackageTable$reloadData$Section)
5977 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5981 _profile(PackageTable$reloadData$Section$Package)
5982 package = [packages_ objectAtIndex:offset];
5983 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5986 while (secidx < index) {
5989 _profile(PackageTable$reloadData$Section$Allocate)
5990 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5993 _profile(PackageTable$reloadData$Section$Add)
5994 [sections_ addObject:section];
5998 [section addToCount];
6004 [index_ removeAllObjects];
6006 bool sectioned([self showsSections]);
6008 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6009 [sections_ addObject:section];
6012 _profile(PackageTable$reloadData$Section)
6013 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6017 _profile(PackageTable$reloadData$Section$Package)
6018 package = [packages_ objectAtIndex:offset];
6019 index = [package index];
6022 if (sectioned && (section == nil || [section index] != index)) {
6023 _profile(PackageTable$reloadData$Section$Allocate)
6024 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6027 [index_ addObject:[section name]];
6028 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6030 _profile(PackageTable$reloadData$Section$Add)
6031 [sections_ addObject:section];
6035 [section addToCount];
6040 [self updateHeight];
6042 _profile(PackageTable$reloadData$List)
6043 [(UITableView *) list_ setDataSource:self];
6048 - (void) reloadData {
6050 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6053 - (void) resetCursor {
6054 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6057 - (void) clearData {
6058 [self updateHeight];
6060 [list_ setDataSource:nil];
6068 /* Filtered Package List Controller {{{ */
6069 @interface FilteredPackageListController : PackageListController {
6072 _H<NSObject> object_;
6075 - (void) setObject:(id)object;
6076 - (void) setObject:(id)object forFilter:(SEL)filter;
6079 - (void) setFilter:(SEL)filter;
6081 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6085 @implementation FilteredPackageListController
6091 - (void) setFilter:(SEL)filter {
6092 @synchronized (self) {
6095 /* XXX: this is an unsafe optimization of doomy hell */
6096 Method method(class_getInstanceMethod([Package class], filter));
6097 _assert(method != NULL);
6098 imp_ = method_getImplementation(method);
6099 _assert(imp_ != NULL);
6102 - (void) setObject:(id)object {
6103 @synchronized (self) {
6107 - (void) setObject:(id)object forFilter:(SEL)filter {
6108 @synchronized (self) {
6109 [self setFilter:filter];
6110 [self setObject:object];
6113 - (NSMutableArray *) _reloadPackages {
6114 @synchronized (database_) {
6115 era_ = [database_ era];
6116 NSArray *packages([database_ packages]);
6118 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6122 _H<NSObject> object;
6124 @synchronized (self) {
6130 _profile(PackageTable$reloadData$Filter)
6131 for (Package *package in packages)
6132 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6133 [filtered addObject:package];
6139 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6140 if ((self = [super initWithDatabase:database title:title]) != nil) {
6141 [self setFilter:filter];
6142 [self setObject:object];
6149 /* Home Controller {{{ */
6150 @interface HomeController : CydiaWebViewController {
6155 @implementation HomeController
6158 if ((self = [super init]) != nil) {
6159 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6164 - (NSURL *) navigationURL {
6165 return [NSURL URLWithString:@"cydia://home"];
6168 - (void) aboutButtonClicked {
6169 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6171 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6172 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6173 [alert setCancelButtonIndex:0];
6176 @"Copyright \u00a9 2008-2011\n"
6179 "Jay Freeman (saurik)\n"
6180 "saurik@saurik.com\n"
6181 "http://www.saurik.com/"
6187 - (UIBarButtonItem *) leftButton {
6188 return [[[UIBarButtonItem alloc]
6189 initWithTitle:UCLocalize("ABOUT")
6190 style:UIBarButtonItemStylePlain
6192 action:@selector(aboutButtonClicked)
6198 /* Manage Controller {{{ */
6199 @interface ManageController : CydiaWebViewController {
6202 - (void) queueStatusDidChange;
6206 @implementation ManageController
6209 if ((self = [super init]) != nil) {
6210 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6214 - (NSURL *) navigationURL {
6215 return [NSURL URLWithString:@"cydia://manage"];
6218 - (UIBarButtonItem *) leftButton {
6219 return [[[UIBarButtonItem alloc]
6220 initWithTitle:UCLocalize("SETTINGS")
6221 style:UIBarButtonItemStylePlain
6223 action:@selector(settingsButtonClicked)
6227 - (void) settingsButtonClicked {
6228 [delegate_ showSettings];
6231 - (void) queueButtonClicked {
6235 - (UIBarButtonItem *) customButton {
6236 return Queuing_ ? [[[UIBarButtonItem alloc]
6237 initWithTitle:UCLocalize("QUEUE")
6238 style:UIBarButtonItemStyleDone
6240 action:@selector(queueButtonClicked)
6241 ] autorelease] : [super customButton];
6244 - (void) queueStatusDidChange {
6245 [self applyRightButton];
6248 - (bool) isLoading {
6249 return !Queuing_ && [super isLoading];
6255 /* Refresh Bar {{{ */
6256 @interface RefreshBar : UINavigationBar {
6257 _H<UIProgressIndicator> indicator_;
6258 _H<UITextLabel> prompt_;
6259 _H<UIProgressBar> progress_;
6260 _H<UINavigationButton> cancel_;
6265 @implementation RefreshBar
6267 - (void) positionViews {
6268 CGRect frame = [cancel_ frame];
6269 frame.size = [cancel_ sizeThatFits:frame.size];
6270 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6271 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6272 [cancel_ setFrame:frame];
6274 CGSize prgsize = {75, 100};
6276 [self frame].size.width - prgsize.width - 10,
6277 ([self frame].size.height - prgsize.height) / 2
6279 [progress_ setFrame:prgrect];
6281 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6282 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6283 CGRect indrect = {{indoffset, indoffset}, indsize};
6284 [indicator_ setFrame:indrect];
6286 CGSize prmsize = {215, indsize.height + 4};
6288 indoffset * 2 + indsize.width,
6289 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6291 [prompt_ setFrame:prmrect];
6294 - (void) setFrame:(CGRect)frame {
6295 [super setFrame:frame];
6296 [self positionViews];
6299 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6300 if ((self = [super initWithFrame:frame]) != nil) {
6301 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6303 [self setBarStyle:UIBarStyleBlack];
6305 UIBarStyle barstyle([self _barStyle:NO]);
6306 bool ugly(barstyle == UIBarStyleDefault);
6308 UIProgressIndicatorStyle style = ugly ?
6309 UIProgressIndicatorStyleMediumBrown :
6310 UIProgressIndicatorStyleMediumWhite;
6312 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6313 [(UIProgressIndicator *) indicator_ setStyle:style];
6314 [indicator_ startAnimation];
6315 [self addSubview:indicator_];
6317 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6318 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6319 [prompt_ setBackgroundColor:[UIColor clearColor]];
6320 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6321 [self addSubview:prompt_];
6323 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6324 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6325 [(UIProgressBar *) progress_ setStyle:0];
6326 [self addSubview:progress_];
6328 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6329 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6330 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6331 [cancel_ setBarStyle:barstyle];
6333 [self positionViews];
6337 - (void) setCancellable:(bool)cancellable {
6339 [self addSubview:cancel_];
6341 [cancel_ removeFromSuperview];
6345 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6346 [progress_ setProgress:0];
6350 [self setCancellable:NO];
6353 - (void) setPrompt:(NSString *)prompt {
6354 [prompt_ setText:prompt];
6357 - (void) setProgress:(float)progress {
6358 [progress_ setProgress:progress];
6364 /* Cydia Navigation Controller Interface {{{ */
6365 @interface UINavigationController (Cydia)
6367 - (NSArray *) navigationURLCollection;
6368 - (void) unloadData;
6373 /* Cydia Tab Bar Controller {{{ */
6374 @interface CYTabBarController : UITabBarController <
6375 UITabBarControllerDelegate,
6378 _transient Database *database_;
6379 _H<RefreshBar, 1> refreshbar_;
6383 // XXX: ok, "updatedelegate_"?...
6384 _transient NSObject<CydiaDelegate> *updatedelegate_;
6386 _H<UIViewController> remembered_;
6387 _transient UIViewController *transient_;
6390 - (NSArray *) navigationURLCollection;
6391 - (void) dropBar:(BOOL)animated;
6392 - (void) beginUpdate;
6393 - (void) raiseBar:(BOOL)animated;
6395 - (void) unloadData;
6399 @implementation CYTabBarController
6401 - (void) setUnselectedViewController:(UIViewController *)transient {
6402 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6403 if (transient != nil) {
6404 if (transient_ == nil)
6405 remembered_ = [controllers objectAtIndex:0];
6406 transient_ = transient;
6407 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6408 [controllers replaceObjectAtIndex:0 withObject:transient_];
6409 [self setSelectedIndex:0];
6410 [self setViewControllers:controllers];
6411 [self concealTabBarSelection];
6412 } else if (remembered_ != nil) {
6413 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6414 transient_ = transient;
6415 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6417 [self setViewControllers:controllers];
6418 [self revealTabBarSelection];
6422 - (UIViewController *) unselectedViewController {
6426 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6427 if ([self unselectedViewController])
6428 [self setUnselectedViewController:nil];
6431 - (NSArray *) navigationURLCollection {
6432 NSMutableArray *items([NSMutableArray array]);
6434 // XXX: Should this deal with transient view controllers?
6435 for (id navigation in [self viewControllers]) {
6436 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6438 [items addObject:stack];
6444 - (void) unloadData {
6447 for (UINavigationController *controller in [self viewControllers])
6448 [controller unloadData];
6450 if (UIViewController *selected = [self selectedViewController])
6451 [selected reloadData];
6453 if (UIViewController *unselected = [self unselectedViewController]) {
6454 [unselected unloadData];
6455 [unselected reloadData];
6460 [[NSNotificationCenter defaultCenter] removeObserver:self];
6465 - (id) initWithDatabase:(Database *)database {
6466 if ((self = [super init]) != nil) {
6467 database_ = database;
6468 [self setDelegate:self];
6470 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6471 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6473 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6477 - (void) setUpdate:(NSDate *)date {
6481 - (void) beginUpdate {
6482 [(RefreshBar *) refreshbar_ start];
6485 [updatedelegate_ retainNetworkActivityIndicator];
6489 detachNewThreadSelector:@selector(performUpdate)
6495 - (void) performUpdate {
6496 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6499 status.setDelegate(self);
6500 [database_ updateWithStatus:status];
6503 performSelectorOnMainThread:@selector(completeUpdate)
6511 - (void) stopUpdateWithSelector:(SEL)selector {
6513 [updatedelegate_ releaseNetworkActivityIndicator];
6515 [self raiseBar:YES];
6518 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6521 - (void) completeUpdate {
6524 [self stopUpdateWithSelector:@selector(reloadData)];
6527 - (void) cancelUpdate {
6528 [self stopUpdateWithSelector:@selector(updateData)];
6531 - (void) cancelPressed {
6532 [self cancelUpdate];
6539 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6540 [refreshbar_ setPrompt:[event compoundMessage]];
6543 - (bool) isProgressCancelled {
6547 - (void) setProgressCancellable:(NSNumber *)cancellable {
6548 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6551 - (void) setProgressPercent:(NSNumber *)percent {
6552 [refreshbar_ setProgress:[percent floatValue]];
6555 - (void) setProgressStatus:(NSDictionary *)status {
6557 [self setProgressPercent:[status objectForKey:@"Percent"]];
6560 - (void) setUpdateDelegate:(id)delegate {
6561 updatedelegate_ = delegate;
6564 - (UIView *) transitionView {
6565 if ([self respondsToSelector:@selector(_transitionView)])
6566 return [self _transitionView];
6568 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6571 - (void) dropBar:(BOOL)animated {
6576 UIView *transition([self transitionView]);
6577 [[self view] addSubview:refreshbar_];
6579 CGRect barframe([refreshbar_ frame]);
6581 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6582 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6584 barframe.origin.y = 0;
6586 [refreshbar_ setFrame:barframe];
6589 [UIView beginAnimations:nil context:NULL];
6591 CGRect viewframe = [transition frame];
6592 viewframe.origin.y += barframe.size.height;
6593 viewframe.size.height -= barframe.size.height;
6594 [transition setFrame:viewframe];
6597 [UIView commitAnimations];
6599 // Ensure bar has the proper width for our view, it might have changed
6600 barframe.size.width = viewframe.size.width;
6601 [refreshbar_ setFrame:barframe];
6604 - (void) raiseBar:(BOOL)animated {
6609 UIView *transition([self transitionView]);
6610 [refreshbar_ removeFromSuperview];
6612 CGRect barframe([refreshbar_ frame]);
6615 [UIView beginAnimations:nil context:NULL];
6617 CGRect viewframe = [transition frame];
6618 viewframe.origin.y -= barframe.size.height;
6619 viewframe.size.height += barframe.size.height;
6620 [transition setFrame:viewframe];
6623 [UIView commitAnimations];
6626 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6627 bool dropped(dropped_);
6632 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6638 - (void) statusBarFrameChanged:(NSNotification *)notification {
6648 /* Cydia Navigation Controller Implementation {{{ */
6649 @implementation UINavigationController (Cydia)
6651 - (NSArray *) navigationURLCollection {
6652 NSMutableArray *stack([NSMutableArray array]);
6654 for (CyteViewController *controller in [self viewControllers]) {
6655 NSString *url = [[controller navigationURL] absoluteString];
6657 [stack addObject:url];
6663 - (void) reloadData {
6666 if (UIViewController *visible = [self visibleViewController])
6667 [visible reloadData];
6670 - (void) unloadData {
6671 for (CyteViewController *page in [self viewControllers])
6680 /* Cydia:// Protocol {{{ */
6681 @interface CydiaURLProtocol : NSURLProtocol {
6686 @implementation CydiaURLProtocol
6688 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6689 NSURL *url([request URL]);
6693 NSString *scheme([[url scheme] lowercaseString]);
6694 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6696 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6702 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6706 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6707 id<NSURLProtocolClient> client([self client]);
6709 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6711 NSData *data(UIImagePNGRepresentation(icon));
6713 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6714 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6715 [client URLProtocol:self didLoadData:data];
6716 [client URLProtocolDidFinishLoading:self];
6720 - (void) startLoading {
6721 id<NSURLProtocolClient> client([self client]);
6722 NSURLRequest *request([self request]);
6724 NSURL *url([request URL]);
6725 NSString *href([url absoluteString]);
6726 NSString *scheme([[url scheme] lowercaseString]);
6730 if ([scheme isEqualToString:@"cydia"])
6731 path = [href substringFromIndex:8];
6732 else if ([scheme isEqualToString:@"about"])
6733 path = [href substringFromIndex:12];
6734 else _assert(false);
6736 NSRange slash([path rangeOfString:@"/"]);
6739 if (slash.location == NSNotFound) {
6743 command = [path substringToIndex:slash.location];
6744 path = [path substringFromIndex:(slash.location + 1)];
6747 Database *database([Database sharedInstance]);
6749 if ([command isEqualToString:@"package-icon"]) {
6752 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6753 Package *package([database packageWithName:path]);
6757 UIImage *icon([package icon]);
6758 [self _returnPNGWithImage:icon forRequest:request];
6759 } else if ([command isEqualToString:@"source-icon"]) {
6762 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6763 NSString *source(Simplify(path));
6764 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6766 icon = [UIImage applicationImageNamed:@"unknown.png"];
6767 [self _returnPNGWithImage:icon forRequest:request];
6768 } else if ([command isEqualToString:@"uikit-image"]) {
6771 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6772 UIImage *icon(_UIImageWithName(path));
6773 [self _returnPNGWithImage:icon forRequest:request];
6774 } else if ([command isEqualToString:@"section-icon"]) {
6777 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6778 NSString *section(Simplify(path));
6779 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6781 icon = [UIImage applicationImageNamed:@"unknown.png"];
6782 [self _returnPNGWithImage:icon forRequest:request];
6784 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6788 - (void) stopLoading {
6794 /* Section Controller {{{ */
6795 @interface SectionController : FilteredPackageListController {
6796 _H<NSString> section_;
6799 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6803 @implementation SectionController
6805 - (NSURL *) navigationURL {
6806 NSString *name = section_;
6810 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6813 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6816 title = UCLocalize("ALL_PACKAGES");
6817 else if (![name isEqual:@""])
6818 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6820 title = UCLocalize("NO_SECTION");
6822 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6829 /* Sections Controller {{{ */
6830 @interface SectionsController : CyteViewController <
6831 UITableViewDataSource,
6834 _transient Database *database_;
6835 _H<NSMutableArray> sections_;
6836 _H<NSMutableArray> filtered_;
6837 _H<UITableView, 2> list_;
6840 - (id) initWithDatabase:(Database *)database;
6841 - (void) editButtonClicked;
6845 @implementation SectionsController
6847 - (NSURL *) navigationURL {
6848 return [NSURL URLWithString:@"cydia://sections"];
6851 - (void) updateNavigationItem {
6852 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6853 if ([sections_ count] == 0) {
6854 [[self navigationItem] setRightBarButtonItem:nil];
6856 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6857 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6859 action:@selector(editButtonClicked)
6860 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6864 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6865 [super setEditing:editing animated:animated];
6870 [delegate_ updateData];
6872 [self updateNavigationItem];
6875 - (void) viewDidAppear:(BOOL)animated {
6876 [super viewDidAppear:animated];
6877 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6880 - (void) viewWillDisappear:(BOOL)animated {
6881 [super viewWillDisappear:animated];
6882 if ([self isEditing]) [self setEditing:NO];
6885 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6886 Section *section = nil;
6887 int index = [indexPath row];
6888 if (![self isEditing]) {
6891 section = [filtered_ objectAtIndex:index];
6893 section = [sections_ objectAtIndex:index];
6898 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6899 if ([self isEditing])
6900 return [sections_ count];
6902 return [filtered_ count] + 1;
6905 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6909 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6910 static NSString *reuseIdentifier = @"SectionCell";
6912 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6914 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6916 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6921 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6922 if ([self isEditing])
6925 Section *section = [self sectionAtIndexPath:indexPath];
6927 SectionController *controller = [[[SectionController alloc]
6928 initWithDatabase:database_
6929 section:[section name]
6931 [controller setDelegate:delegate_];
6933 [[self navigationController] pushViewController:controller animated:YES];
6937 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6939 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6940 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6941 [list_ setRowHeight:45.0f];
6942 [(UITableView *) list_ setDataSource:self];
6943 [list_ setDelegate:self];
6944 [[self view] addSubview:list_];
6947 - (void) viewDidLoad {
6948 [super viewDidLoad];
6950 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6953 - (void) releaseSubviews {
6956 [super releaseSubviews];
6959 - (id) initWithDatabase:(Database *)database {
6960 if ((self = [super init]) != nil) {
6961 database_ = database;
6963 sections_ = [NSMutableArray arrayWithCapacity:16];
6964 filtered_ = [NSMutableArray arrayWithCapacity:16];
6968 - (void) reloadData {
6971 NSArray *packages = [database_ packages];
6973 [sections_ removeAllObjects];
6974 [filtered_ removeAllObjects];
6976 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6979 for (Package *package in packages) {
6980 NSString *name([package section]);
6981 NSString *key(name == nil ? @"" : name);
6985 _profile(SectionsView$reloadData$Section)
6986 section = [sections objectForKey:key];
6987 if (section == nil) {
6988 _profile(SectionsView$reloadData$Section$Allocate)
6989 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6990 [sections setObject:section forKey:key];
6995 [section addToCount];
6997 _profile(SectionsView$reloadData$Filter)
6998 if (![package valid] || ![package visible])
7006 [sections_ addObjectsFromArray:[sections allValues]];
7008 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7010 for (Section *section in (id) sections_) {
7011 size_t count([section row]);
7015 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7016 [section setCount:count];
7017 [filtered_ addObject:section];
7020 [self updateNavigationItem];
7025 - (void) editButtonClicked {
7026 [self setEditing:![self isEditing] animated:YES];
7032 /* Changes Controller {{{ */
7033 @interface ChangesController : CyteViewController <
7034 UITableViewDataSource,
7037 _transient Database *database_;
7039 _H<NSArray> packages_;
7040 _H<NSMutableArray> sections_;
7041 _H<UITableView, 2> list_;
7045 - (id) initWithDatabase:(Database *)database;
7049 @implementation ChangesController
7051 - (NSURL *) navigationURL {
7052 return [NSURL URLWithString:@"cydia://changes"];
7055 - (void) viewDidAppear:(BOOL)animated {
7056 [super viewDidAppear:animated];
7057 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7060 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7061 NSInteger count([sections_ count]);
7062 return count == 0 ? 1 : count;
7065 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7066 if ([sections_ count] == 0)
7068 return [[sections_ objectAtIndex:section] name];
7071 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7072 if ([sections_ count] == 0)
7074 return [[sections_ objectAtIndex:section] count];
7077 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7078 @synchronized (database_) {
7079 if ([database_ era] != era_)
7082 NSUInteger sectionIndex([path section]);
7083 if (sectionIndex >= [sections_ count])
7085 Section *section([sections_ objectAtIndex:sectionIndex]);
7086 NSInteger row([path row]);
7087 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7090 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7091 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7093 cell = [[[PackageCell alloc] init] autorelease];
7094 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7098 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7099 Package *package([self packageAtIndexPath:path]);
7100 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7101 [view setDelegate:delegate_];
7102 [[self navigationController] pushViewController:view animated:YES];
7106 - (void) refreshButtonClicked {
7107 [delegate_ beginUpdate];
7108 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7111 - (void) upgradeButtonClicked {
7112 [delegate_ distUpgrade];
7116 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7118 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7119 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7120 [list_ setRowHeight:73];
7121 [(UITableView *) list_ setDataSource:self];
7122 [list_ setDelegate:self];
7123 [[self view] addSubview:list_];
7126 - (void) viewDidLoad {
7127 [super viewDidLoad];
7129 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7132 - (void) releaseSubviews {
7135 [super releaseSubviews];
7138 - (id) initWithDatabase:(Database *)database {
7139 if ((self = [super init]) != nil) {
7140 database_ = database;
7142 packages_ = [NSArray array];
7143 sections_ = [NSMutableArray arrayWithCapacity:16];
7147 - (NSMutableArray *) _reloadPackages {
7148 @synchronized (database_) {
7149 era_ = [database_ era];
7150 NSArray *packages([database_ packages]);
7152 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7155 _profile(ChangesController$_reloadPackages$Filter)
7156 for (Package *package in packages)
7157 if ([package upgradableAndEssential:YES] || [package visible])
7158 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7161 _profile(ChangesController$_reloadPackages$radixSort)
7162 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7169 - (void) _reloadData {
7174 UIProgressHUD *hud([delegate_ addProgressHUD]);
7175 [hud setText:UCLocalize("LOADING")];
7176 //NSLog(@"HUD:%@::%@", delegate_, hud);
7177 packages = [self yieldToSelector:@selector(_reloadPackages)];
7178 [delegate_ removeProgressHUD:hud];
7180 packages = [self _reloadPackages];
7183 @synchronized (database_) {
7184 if (era_ != [database_ era])
7187 packages_ = packages;
7188 [sections_ removeAllObjects];
7190 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7191 Section *ignored = nil;
7192 Section *section = nil;
7196 bool unseens = false;
7198 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7200 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7201 Package *package = [packages_ objectAtIndex:offset];
7203 BOOL uae = [package upgradableAndEssential:YES];
7207 time_t seen([package seen]);
7209 if (section == nil || last != seen) {
7213 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7216 _profile(ChangesController$reloadData$Allocate)
7217 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7218 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7219 [sections_ addObject:section];
7223 [section addToCount];
7224 } else if ([package ignored]) {
7225 if (ignored == nil) {
7226 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7228 [ignored addToCount];
7231 [upgradable addToCount];
7236 CFRelease(formatter);
7239 Section *last = [sections_ lastObject];
7240 size_t count = [last count];
7241 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7242 [sections_ removeLastObject];
7245 if ([ignored count] != 0)
7246 [sections_ insertObject:ignored atIndex:0];
7248 [sections_ insertObject:upgradable atIndex:0];
7253 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7254 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7255 style:UIBarButtonItemStylePlain
7257 action:@selector(upgradeButtonClicked)
7260 if (![delegate_ updating])
7261 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7262 initWithTitle:UCLocalize("REFRESH")
7263 style:UIBarButtonItemStylePlain
7265 action:@selector(refreshButtonClicked)
7271 - (void) reloadData {
7273 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7278 /* Search Controller {{{ */
7279 @interface SearchController : FilteredPackageListController <
7282 _H<UISearchBar, 1> search_;
7286 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7287 - (void) reloadData;
7291 @implementation SearchController
7293 - (NSURL *) navigationURL {
7294 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7295 return [NSURL URLWithString:@"cydia://search"];
7297 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7300 - (void) useSearch {
7301 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7306 - (void) viewWillAppear:(BOOL)animated {
7307 [super viewWillAppear:animated];
7309 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7313 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7314 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7319 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7320 [search_ resignFirstResponder];
7324 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7325 [search_ setText:@""];
7326 [self searchBarButtonClicked:searchBar];
7329 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7330 [self searchBarButtonClicked:searchBar];
7333 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7334 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7338 - (bool) shouldYield {
7342 - (bool) shouldBlock {
7343 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7346 - (bool) isSummarized {
7347 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7350 - (bool) showsSections {
7354 - (NSMutableArray *) _reloadPackages {
7355 NSMutableArray *packages([super _reloadPackages]);
7356 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7357 [packages radixSortUsingSelector:@selector(rank)];
7361 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7362 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7363 search_ = [[[UISearchBar alloc] init] autorelease];
7364 [search_ setDelegate:self];
7367 [search_ setText:query];
7371 - (void) viewDidAppear:(BOOL)animated {
7372 [super viewDidAppear:animated];
7374 if (!searchloaded_) {
7375 searchloaded_ = YES;
7376 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7377 [search_ layoutSubviews];
7378 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7380 UITextField *textField;
7381 if ([search_ respondsToSelector:@selector(searchField)])
7382 textField = [search_ searchField];
7384 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7386 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7387 [textField setEnablesReturnKeyAutomatically:NO];
7388 [[self navigationItem] setTitleView:textField];
7392 - (void) reloadData {
7393 id object([search_ text]);
7394 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7395 object = [object componentsSeparatedByString:@" "];
7397 [self setObject:object];
7403 - (void) didSelectPackage:(Package *)package {
7404 [search_ resignFirstResponder];
7405 [super didSelectPackage:package];
7410 /* Package Settings Controller {{{ */
7411 @interface PackageSettingsController : CyteViewController <
7412 UITableViewDataSource,
7415 _transient Database *database_;
7417 _H<Package> package_;
7418 _H<UITableView, 2> table_;
7419 _H<UISwitch> subscribedSwitch_;
7420 _H<UISwitch> ignoredSwitch_;
7421 _H<UITableViewCell> subscribedCell_;
7422 _H<UITableViewCell> ignoredCell_;
7425 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7429 @implementation PackageSettingsController
7431 - (NSURL *) navigationURL {
7432 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7435 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7436 if (package_ == nil)
7439 if ([package_ installed] == nil)
7445 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7446 if (package_ == nil)
7449 // both sections contain just one item right now.
7453 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7457 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7459 return UCLocalize("SHOW_ALL_CHANGES_EX");
7461 return UCLocalize("IGNORE_UPGRADES_EX");
7464 - (void) onSubscribed:(id)control {
7465 bool value([control isOn]);
7466 if (package_ == nil)
7468 if ([package_ setSubscribed:value])
7469 [delegate_ updateData];
7472 - (void) _updateIgnored {
7473 const char *package([name_ UTF8String]);
7474 bool on([ignoredSwitch_ isOn]);
7476 pid_t pid(ExecFork());
7478 FILE *dpkg(popen("dpkg --set-selections", "w"));
7479 fwrite(package, strlen(package), 1, dpkg);
7482 fwrite(" hold\n", 6, 1, dpkg);
7484 fwrite(" install\n", 9, 1, dpkg);
7494 int result(waitpid(pid, &status, 0));
7497 _assert(result == pid);
7503 - (void) onIgnored:(id)control {
7504 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7505 [invocation setTarget:self];
7506 [invocation setSelector:@selector(_updateIgnored)];
7508 [delegate_ reloadDataWithInvocation:invocation];
7511 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7512 if (package_ == nil)
7515 switch ([indexPath section]) {
7516 case 0: return subscribedCell_;
7517 case 1: return ignoredCell_;
7526 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7528 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7529 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7530 [(UITableView *) table_ setDataSource:self];
7531 [table_ setDelegate:self];
7532 [[self view] addSubview:table_];
7534 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7535 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7536 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7538 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7539 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7540 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7542 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7543 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7544 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7545 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7547 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7548 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7549 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7550 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7553 - (void) viewDidLoad {
7554 [super viewDidLoad];
7556 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7559 - (void) releaseSubviews {
7561 subscribedCell_ = nil;
7563 ignoredSwitch_ = nil;
7564 subscribedSwitch_ = nil;
7566 [super releaseSubviews];
7569 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7570 if ((self = [super init]) != nil) {
7571 database_ = database;
7576 - (void) reloadData {
7579 package_ = [database_ packageWithName:name_];
7581 if (package_ != nil) {
7582 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7583 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7584 } // XXX: what now, G?
7586 [table_ reloadData];
7592 /* Installed Controller {{{ */
7593 @interface InstalledController : FilteredPackageListController {
7597 - (id) initWithDatabase:(Database *)database;
7599 - (void) updateRoleButton;
7600 - (void) queueStatusDidChange;
7604 @implementation InstalledController
7606 - (NSURL *) navigationURL {
7607 return [NSURL URLWithString:@"cydia://installed"];
7610 - (id) initWithDatabase:(Database *)database {
7611 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7612 [self updateRoleButton];
7613 [self queueStatusDidChange];
7618 - (void) queueButtonClicked {
7623 - (void) queueStatusDidChange {
7627 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7628 initWithTitle:UCLocalize("QUEUE")
7629 style:UIBarButtonItemStyleDone
7631 action:@selector(queueButtonClicked)
7634 [[self navigationItem] setLeftBarButtonItem:nil];
7640 - (void) updateRoleButton {
7641 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7642 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7643 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7644 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7646 action:@selector(roleButtonClicked)
7650 - (void) roleButtonClicked {
7651 [self setObject:[NSNumber numberWithBool:expert_]];
7655 [self updateRoleButton];
7661 /* Source Cell {{{ */
7662 @interface SourceCell : CyteTableViewCell <
7663 CyteTableViewCellDelegate
7666 _H<NSString> origin_;
7667 _H<NSString> label_;
7670 - (void) setSource:(Source *)source;
7674 @implementation SourceCell
7676 - (void) _setImage:(UIImage *)image {
7678 [content_ setNeedsDisplay];
7681 - (void) _setSource:(Source *)source {
7682 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7684 if (NSString *base = [source base])
7685 if ([base length] != 0) {
7686 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7688 if (NSData *data = [NSURLConnection
7689 sendSynchronousRequest:[NSURLRequest
7691 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7695 returningResponse:NULL
7698 if (UIImage *image = [UIImage imageWithData:data])
7699 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7705 - (void) setSource:(Source *)source {
7706 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7708 origin_ = [source name];
7709 label_ = [source uri];
7711 [content_ setNeedsDisplay];
7713 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7716 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7717 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7718 UIView *content([self contentView]);
7719 CGRect bounds([content bounds]);
7721 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7722 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7723 [content_ setBackgroundColor:[UIColor whiteColor]];
7724 [content addSubview:content_];
7726 [content_ setDelegate:self];
7727 [content_ setOpaque:YES];
7731 - (NSString *) accessibilityLabel {
7735 - (void) drawContentRect:(CGRect)rect {
7736 bool highlighted(highlighted_);
7737 float width(rect.size.width);
7740 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7747 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7751 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7756 /* Source Controller {{{ */
7757 @interface SourceController : FilteredPackageListController {
7758 _transient Source *source_;
7762 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7766 @implementation SourceController
7768 - (NSURL *) navigationURL {
7769 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7772 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7773 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7775 key_ = [source key];
7779 - (void) reloadData {
7780 source_ = [database_ sourceWithKey:key_];
7781 key_ = [source_ key];
7782 [self setObject:source_];
7784 [[self navigationItem] setTitle:[source_ label]];
7791 /* Sources Controller {{{ */
7792 @interface SourcesController : CyteViewController <
7793 UITableViewDataSource,
7796 _transient Database *database_;
7797 _H<UITableView, 2> list_;
7798 _H<NSMutableArray> sources_;
7802 _H<UIProgressHUD> hud_;
7805 //NSURLConnection *installer_;
7806 NSURLConnection *trivial_;
7807 NSURLConnection *trivial_bz2_;
7808 NSURLConnection *trivial_gz_;
7809 //NSURLConnection *automatic_;
7814 - (id) initWithDatabase:(Database *)database;
7815 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7819 @implementation SourcesController
7821 - (void) _releaseConnection:(NSURLConnection *)connection {
7822 if (connection != nil) {
7823 [connection cancel];
7824 //[connection setDelegate:nil];
7825 [connection release];
7830 //[self _releaseConnection:installer_];
7831 [self _releaseConnection:trivial_];
7832 [self _releaseConnection:trivial_gz_];
7833 [self _releaseConnection:trivial_bz2_];
7834 //[self _releaseConnection:automatic_];
7839 - (NSURL *) navigationURL {
7840 return [NSURL URLWithString:@"cydia://sources"];
7843 - (void) viewDidAppear:(BOOL)animated {
7844 [super viewDidAppear:animated];
7845 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7848 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7849 return offset_ == 0 ? 1 : 2;
7852 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7853 switch (section + (offset_ == 0 ? 1 : 0)) {
7854 case 0: return UCLocalize("ENTERED_BY_USER");
7855 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7861 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7862 int count = [sources_ count];
7864 case 0: return (offset_ == 0 ? count : offset_);
7865 case 1: return count - offset_;
7871 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7873 switch (indexPath.section) {
7874 case 0: idx = indexPath.row; break;
7875 case 1: idx = indexPath.row + offset_; break;
7879 return [sources_ objectAtIndex:idx];
7882 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7883 static NSString *cellIdentifier = @"SourceCell";
7885 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7886 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7887 [cell setSource:[self sourceAtIndexPath:indexPath]];
7888 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7893 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7894 Source *source = [self sourceAtIndexPath:indexPath];
7896 SourceController *controller = [[[SourceController alloc]
7897 initWithDatabase:database_
7901 [controller setDelegate:delegate_];
7903 [[self navigationController] pushViewController:controller animated:YES];
7906 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7907 Source *source = [self sourceAtIndexPath:indexPath];
7908 return [source record] != nil;
7911 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7912 if (editingStyle == UITableViewCellEditingStyleDelete) {
7913 Source *source = [self sourceAtIndexPath:indexPath];
7914 [Sources_ removeObjectForKey:[source key]];
7915 [delegate_ syncData];
7920 [delegate_ addTrivialSource:href_];
7921 [delegate_ syncData];
7924 - (NSString *) getWarning {
7925 NSString *href(href_);
7926 NSRange colon([href rangeOfString:@"://"]);
7927 if (colon.location != NSNotFound)
7928 href = [href substringFromIndex:(colon.location + 3)];
7929 href = [href stringByAddingPercentEscapes];
7930 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7931 href = [href stringByCachingURLWithCurrentCDN];
7933 NSURL *url([NSURL URLWithString:href]);
7935 NSStringEncoding encoding;
7936 NSError *error(nil);
7938 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7939 return [warning length] == 0 ? nil : warning;
7943 - (void) _endConnection:(NSURLConnection *)connection {
7944 // XXX: the memory management in this method is horribly awkward
7946 NSURLConnection **field = NULL;
7947 if (connection == trivial_)
7949 else if (connection == trivial_bz2_)
7950 field = &trivial_bz2_;
7951 else if (connection == trivial_gz_)
7952 field = &trivial_gz_;
7953 _assert(field != NULL);
7954 [connection release];
7959 trivial_bz2_ == nil &&
7962 [delegate_ releaseNetworkActivityIndicator];
7964 [delegate_ removeProgressHUD:hud_];
7970 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7973 UIAlertView *alert = [[[UIAlertView alloc]
7974 initWithTitle:UCLocalize("SOURCE_WARNING")
7977 cancelButtonTitle:UCLocalize("CANCEL")
7979 UCLocalize("ADD_ANYWAY"),
7983 [alert setContext:@"warning"];
7984 [alert setNumberOfRows:1];
7988 } else if (error_ != nil) {
7989 UIAlertView *alert = [[[UIAlertView alloc]
7990 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7991 message:[error_ localizedDescription]
7993 cancelButtonTitle:UCLocalize("OK")
7994 otherButtonTitles:nil
7997 [alert setContext:@"urlerror"];
8000 UIAlertView *alert = [[[UIAlertView alloc]
8001 initWithTitle:UCLocalize("NOT_REPOSITORY")
8002 message:UCLocalize("NOT_REPOSITORY_EX")
8004 cancelButtonTitle:UCLocalize("OK")
8005 otherButtonTitles:nil
8008 [alert setContext:@"trivial"];
8017 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8018 switch ([response statusCode]) {
8024 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8025 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8027 [self _endConnection:connection];
8030 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8031 [self _endConnection:connection];
8034 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8035 NSMutableURLRequest *request = [NSMutableURLRequest
8036 requestWithURL:[NSURL URLWithString:href]
8037 cachePolicy:NSURLRequestUseProtocolCachePolicy
8038 timeoutInterval:120.0
8041 [request setHTTPMethod:method];
8043 if (Machine_ != NULL)
8044 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8045 if (UniqueID_ != nil)
8046 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8048 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8051 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8052 NSString *context([alert context]);
8054 if ([context isEqualToString:@"source"]) {
8057 NSString *href = [[alert textField] text];
8059 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8061 if (![href hasSuffix:@"/"])
8062 href_ = [href stringByAppendingString:@"/"];
8066 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8067 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8068 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8069 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8073 // XXX: this is stupid
8074 hud_ = [delegate_ addProgressHUD];
8075 [hud_ setText:UCLocalize("VERIFYING_URL")];
8076 [delegate_ retainNetworkActivityIndicator];
8085 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8086 } else if ([context isEqualToString:@"trivial"])
8087 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8088 else if ([context isEqualToString:@"urlerror"])
8089 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8090 else if ([context isEqualToString:@"warning"]) {
8104 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8109 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8111 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8112 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8113 [list_ setRowHeight:56];
8114 [(UITableView *) list_ setDataSource:self];
8115 [list_ setDelegate:self];
8116 [[self view] addSubview:list_];
8119 - (void) viewDidLoad {
8120 [super viewDidLoad];
8122 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8123 [self updateButtonsForEditingStatus:NO animated:NO];
8126 - (void) releaseSubviews {
8129 [super releaseSubviews];
8132 - (id) initWithDatabase:(Database *)database {
8133 if ((self = [super init]) != nil) {
8134 database_ = database;
8135 sources_ = [NSMutableArray arrayWithCapacity:16];
8139 - (void) reloadData {
8143 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8146 [sources_ removeAllObjects];
8147 [sources_ addObjectsFromArray:[database_ sources]];
8149 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8152 int count([sources_ count]);
8154 for (int i = 0; i != count; i++) {
8155 if ([[sources_ objectAtIndex:i] record] == nil)
8160 [list_ setEditing:NO];
8161 [self updateButtonsForEditingStatus:NO animated:NO];
8165 - (void) showAddSourcePrompt {
8166 UIAlertView *alert = [[[UIAlertView alloc]
8167 initWithTitle:UCLocalize("ENTER_APT_URL")
8170 cancelButtonTitle:UCLocalize("CANCEL")
8172 UCLocalize("ADD_SOURCE"),
8176 [alert setContext:@"source"];
8178 [alert setNumberOfRows:1];
8179 [alert addTextFieldWithValue:@"http://" label:@""];
8181 UITextInputTraits *traits = [[alert textField] textInputTraits];
8182 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8183 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8184 [traits setKeyboardType:UIKeyboardTypeURL];
8185 // XXX: UIReturnKeyDone
8186 [traits setReturnKeyType:UIReturnKeyNext];
8191 - (void) addButtonClicked {
8192 [self showAddSourcePrompt];
8195 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8196 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8197 initWithTitle:UCLocalize("ADD")
8198 style:UIBarButtonItemStylePlain
8200 action:@selector(addButtonClicked)
8201 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8203 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8204 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8205 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8207 action:@selector(editButtonClicked)
8208 ] autorelease] animated:animated];
8210 if (IsWildcat_ && !editing)
8211 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8212 initWithTitle:UCLocalize("SETTINGS")
8213 style:UIBarButtonItemStylePlain
8215 action:@selector(settingsButtonClicked)
8219 - (void) settingsButtonClicked {
8220 [delegate_ showSettings];
8223 - (void) editButtonClicked {
8224 [list_ setEditing:![list_ isEditing] animated:YES];
8226 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8232 /* Settings Controller {{{ */
8233 @interface SettingsController : CyteViewController <
8234 UITableViewDataSource,
8237 _transient Database *database_;
8238 // XXX: ok, "roledelegate_"?...
8239 _transient id roledelegate_;
8240 _H<UITableView, 2> table_;
8241 _H<UISegmentedControl> segment_;
8242 _H<UIView> container_;
8245 - (void) showDoneButton;
8246 - (void) resizeSegmentedControl;
8250 @implementation SettingsController
8253 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8255 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8256 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8257 [table_ setDelegate:self];
8258 [(UITableView *) table_ setDataSource:self];
8259 [[self view] addSubview:table_];
8261 NSArray *items = [NSArray arrayWithObjects:
8263 UCLocalize("HACKER"),
8264 UCLocalize("DEVELOPER"),
8266 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8267 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8268 [container_ addSubview:segment_];
8271 - (void) viewDidLoad {
8272 [super viewDidLoad];
8274 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8277 if ([Role_ isEqualToString:@"User"]) index = 0;
8278 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8279 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8281 [segment_ setSelectedSegmentIndex:index];
8282 [self showDoneButton];
8285 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8286 [self resizeSegmentedControl];
8289 - (void) releaseSubviews {
8294 [super releaseSubviews];
8297 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8298 if ((self = [super init]) != nil) {
8299 database_ = database;
8300 roledelegate_ = delegate;
8304 - (void) resizeSegmentedControl {
8305 CGFloat width = [[self view] frame].size.width;
8306 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8309 - (void) viewWillAppear:(BOOL)animated {
8310 [super viewWillAppear:animated];
8312 [self resizeSegmentedControl];
8315 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8316 [self resizeSegmentedControl];
8319 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8320 [self resizeSegmentedControl];
8324 NSString *role(nil);
8326 switch ([segment_ selectedSegmentIndex]) {
8327 case 0: role = @"User"; break;
8328 case 1: role = @"Hacker"; break;
8329 case 2: role = @"Developer"; break;
8334 if (![role isEqualToString:Role_]) {
8335 bool rolling(Role_ == nil);
8338 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8342 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8346 [roledelegate_ loadData];
8348 [roledelegate_ updateData];
8352 - (void) segmentChanged:(UISegmentedControl *)control {
8353 [self showDoneButton];
8356 - (void) saveAndClose {
8359 [[self navigationItem] setRightBarButtonItem:nil];
8360 [[self navigationController] dismissModalViewControllerAnimated:YES];
8363 - (void) doneButtonClicked {
8364 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8365 [spinner startAnimating];
8366 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8367 [[self navigationItem] setRightBarButtonItem:spinItem];
8369 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8372 - (void) showDoneButton {
8373 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8374 initWithTitle:UCLocalize("DONE")
8375 style:UIBarButtonItemStyleDone
8377 action:@selector(doneButtonClicked)
8378 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8381 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8382 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8386 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8390 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8391 return nil; // This method is required by the protocol.
8394 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8396 return UCLocalize("ROLE_EX");
8398 return [NSString stringWithFormat:
8399 @"%@: %@\n%@: %@\n%@: %@",
8400 UCLocalize("USER"), UCLocalize("USER_EX"),
8401 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8402 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8407 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8408 return section == 3 ? 44.0f : 0;
8411 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8412 return section == 3 ? container_ : nil;
8415 - (void) reloadData {
8418 [table_ reloadData];
8423 /* Stash Controller {{{ */
8424 @interface StashController : CyteViewController {
8425 _H<UIActivityIndicatorView> spinner_;
8426 _H<UILabel> status_;
8427 _H<UILabel> caption_;
8432 @implementation StashController
8435 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8436 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8438 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8439 CGRect spinrect = [spinner_ frame];
8440 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8441 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8442 [spinner_ setFrame:spinrect];
8443 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8444 [[self view] addSubview:spinner_];
8445 [spinner_ startAnimating];
8448 captrect.size.width = [[self view] frame].size.width;
8449 captrect.size.height = 40.0f;
8450 captrect.origin.x = 0;
8451 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8452 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8453 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8454 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8455 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8456 [caption_ setTextColor:[UIColor whiteColor]];
8457 [caption_ setBackgroundColor:[UIColor clearColor]];
8458 [caption_ setShadowColor:[UIColor blackColor]];
8459 [caption_ setTextAlignment:UITextAlignmentCenter];
8460 [[self view] addSubview:caption_];
8463 statusrect.size.width = [[self view] frame].size.width;
8464 statusrect.size.height = 30.0f;
8465 statusrect.origin.x = 0;
8466 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8467 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8468 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8469 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8470 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8471 [status_ setTextColor:[UIColor whiteColor]];
8472 [status_ setBackgroundColor:[UIColor clearColor]];
8473 [status_ setShadowColor:[UIColor blackColor]];
8474 [status_ setTextAlignment:UITextAlignmentCenter];
8475 [[self view] addSubview:status_];
8478 - (void) releaseSubviews {
8483 [super releaseSubviews];
8489 @interface CYURLCache : SDURLCache {
8494 @implementation CYURLCache
8496 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8499 else if ([event isEqualToString:@"no-cache"])
8501 else if ([event isEqualToString:@"store"])
8503 else if ([event isEqualToString:@"invalid"])
8505 else if ([event isEqualToString:@"memory"])
8507 else if ([event isEqualToString:@"disk"])
8509 else if ([event isEqualToString:@"miss"])
8512 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8516 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8517 if (NSURLResponse *response = [cached response])
8518 if (NSString *mime = [response MIMEType])
8519 if ([mime isEqualToString:@"text/cache-manifest"]) {
8520 NSURL *url([response URL]);
8523 NSLog(@"###: %@", [url absoluteString]);
8526 @synchronized (HostConfig_) {
8527 [CachedURLs_ addObject:url];
8531 [super storeCachedResponse:cached forRequest:request];
8536 @interface Cydia : UIApplication <
8537 ConfirmationControllerDelegate,
8540 UINavigationControllerDelegate,
8541 UITabBarControllerDelegate
8543 _H<UIWindow> window_;
8544 _H<CYTabBarController> tabbar_;
8545 _H<CydiaLoadingViewController> emulated_;
8547 _H<NSMutableArray> essential_;
8548 _H<NSMutableArray> broken_;
8550 Database *database_;
8552 _H<NSURL> starturl_;
8557 _H<StashController> stash_;
8566 @implementation Cydia
8568 - (void) beginUpdate {
8569 [tabbar_ beginUpdate];
8573 return [tabbar_ updating];
8577 if ([broken_ count] != 0) {
8578 int count = [broken_ count];
8580 UIAlertView *alert = [[[UIAlertView alloc]
8581 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8582 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8584 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8586 UCLocalize("TEMPORARY_IGNORE"),
8590 [alert setContext:@"fixhalf"];
8591 [alert setNumberOfRows:2];
8593 } else if (!Ignored_ && [essential_ count] != 0) {
8594 int count = [essential_ count];
8596 UIAlertView *alert = [[[UIAlertView alloc]
8597 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8598 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8600 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8602 UCLocalize("UPGRADE_ESSENTIAL"),
8603 UCLocalize("COMPLETE_UPGRADE"),
8607 [alert setContext:@"upgrade"];
8612 - (void) _saveConfig {
8618 NSString *error(nil);
8620 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8622 NSError *error(nil);
8623 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8624 NSLog(@"failure to save metadata data: %@", error);
8629 NSLog(@"failure to serialize metadata: %@", error);
8634 // Navigation controller for the queuing badge.
8635 - (UINavigationController *) queueNavigationController {
8636 NSArray *controllers = [tabbar_ viewControllers];
8637 return [controllers objectAtIndex:3];
8640 - (void) unloadData {
8641 [tabbar_ unloadData];
8644 - (void) _updateData {
8649 UINavigationController *navigation = [self queueNavigationController];
8651 id queuedelegate = nil;
8652 if ([[navigation viewControllers] count] > 0)
8653 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8655 [queuedelegate queueStatusDidChange];
8656 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8659 - (void) _refreshIfPossible:(NSDate *)update {
8660 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8662 bool recently = false;
8663 if (update != nil) {
8664 NSTimeInterval interval([update timeIntervalSinceNow]);
8665 if (interval <= 0 && interval > -(15*60))
8669 // Don't automatic refresh if:
8670 // - We already refreshed recently.
8671 // - We already auto-refreshed this launch.
8672 // - Auto-refresh is disabled.
8673 if (recently || loaded_ || ManualRefresh) {
8674 // If we are cancelling, we need to make sure it knows it's already loaded.
8677 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8679 // We are going to load, so remember that.
8682 SCNetworkReachabilityFlags flags; {
8683 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8684 SCNetworkReachabilityGetFlags(reachability, &flags);
8685 CFRelease(reachability);
8688 // XXX: this elaborate mess is what Apple is using to determine this? :(
8689 // XXX: do we care if the user has to intervene? maybe that's ok?
8691 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8692 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8693 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8694 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8695 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8696 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8700 // If we can reach the server, auto-refresh!
8702 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8708 - (void) refreshIfPossible {
8709 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8712 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8713 @synchronized (self) {
8714 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8715 [hud setText:UCLocalize("RELOADING_DATA")];
8717 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8720 [self removeProgressHUD:hud];
8724 [essential_ removeAllObjects];
8725 [broken_ removeAllObjects];
8727 NSArray *packages([database_ packages]);
8728 for (Package *package in packages) {
8730 [broken_ addObject:package];
8731 if ([package upgradableAndEssential:NO]) {
8732 if ([package essential])
8733 [essential_ addObject:package];
8738 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8741 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8742 [changesItem setBadgeValue:badge];
8743 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8744 [self setApplicationIconBadgeNumber:changes];
8747 [changesItem setBadgeValue:nil];
8748 [changesItem setAnimatedBadge:NO];
8749 [self setApplicationIconBadgeNumber:0];
8754 [self refreshIfPossible];
8757 - (void) updateData {
8763 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8766 - (void) disemulate {
8767 if (emulated_ == nil)
8770 [window_ addSubview:[tabbar_ view]];
8771 [[emulated_ view] removeFromSuperview];
8773 [window_ setUserInteractionEnabled:YES];
8776 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8777 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8779 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8781 UIViewController *parent;
8782 if (emulated_ == nil)
8791 [parent presentModalViewController:navigation animated:YES];
8794 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8795 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8797 if (navigation != nil)
8798 [navigation pushViewController:progress animated:YES];
8800 [self presentModalViewController:progress force:YES];
8802 [progress invoke:invocation withTitle:title];
8806 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8807 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8810 - (void) repairWithInvocation:(NSInvocation *)invocation {
8812 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8816 - (void) repairWithSelector:(SEL)selector {
8817 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8820 - (void) reloadData {
8821 [self reloadDataWithInvocation:nil];
8827 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8828 _assert(file != NULL);
8830 for (NSString *key in [Sources_ allKeys]) {
8831 NSDictionary *source([Sources_ objectForKey:key]);
8833 fprintf(file, "%s %s %s\n",
8834 [[source objectForKey:@"Type"] UTF8String],
8835 [[source objectForKey:@"URI"] UTF8String],
8836 [[source objectForKey:@"Distribution"] UTF8String]
8842 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8845 - (void) addTrivialSource:(NSString *)href {
8846 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8849 @"./", @"Distribution",
8850 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8856 pkgProblemResolver *resolver = [database_ resolver];
8858 resolver->InstallProtect();
8859 if (!resolver->Resolve(true))
8864 // XXX: this is a really crappy way of doing this.
8865 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8866 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8867 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8868 if ([tabbar_ updating])
8869 [tabbar_ cancelUpdate];
8871 if (![database_ prepare])
8874 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8875 [page setDelegate:self];
8876 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8879 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8880 [tabbar_ presentModalViewController:confirm_ animated:YES];
8886 @synchronized (self) {
8891 - (void) clearPackage:(Package *)package {
8892 @synchronized (self) {
8899 - (void) installPackages:(NSArray *)packages {
8900 @synchronized (self) {
8901 for (Package *package in packages)
8908 - (void) installPackage:(Package *)package {
8909 @synchronized (self) {
8916 - (void) removePackage:(Package *)package {
8917 @synchronized (self) {
8924 - (void) distUpgrade {
8925 @synchronized (self) {
8926 if (![database_ upgrade])
8933 [database_ perform];
8934 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8937 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8940 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8944 - (void) showSettings {
8945 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8948 - (void) retainNetworkActivityIndicator {
8949 if (activity_++ == 0)
8950 [self setNetworkActivityIndicatorVisible:YES];
8953 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8957 - (void) releaseNetworkActivityIndicator {
8958 if (--activity_ == 0)
8959 [self setNetworkActivityIndicatorVisible:NO];
8962 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8967 - (void) cancelAndClear:(bool)clear {
8968 @synchronized (self) {
8980 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8981 NSString *context([alert context]);
8983 if ([context isEqualToString:@"conffile"]) {
8984 FILE *input = [database_ input];
8985 if (button == [alert cancelButtonIndex])
8986 fprintf(input, "N\n");
8987 else if (button == [alert firstOtherButtonIndex])
8988 fprintf(input, "Y\n");
8991 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8992 } else if ([context isEqualToString:@"fixhalf"]) {
8993 if (button == [alert cancelButtonIndex]) {
8994 @synchronized (self) {
8995 for (Package *broken in (id) broken_) {
8998 NSString *id = [broken id];
8999 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9000 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9001 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9002 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9008 } else if (button == [alert firstOtherButtonIndex]) {
9009 [broken_ removeAllObjects];
9013 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9014 } else if ([context isEqualToString:@"upgrade"]) {
9015 if (button == [alert firstOtherButtonIndex]) {
9016 @synchronized (self) {
9017 for (Package *essential in (id) essential_)
9018 [essential install];
9023 } else if (button == [alert firstOtherButtonIndex] + 1) {
9025 } else if (button == [alert cancelButtonIndex]) {
9029 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9033 - (void) system:(NSString *)command {
9034 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9037 system([command UTF8String]);
9043 - (void) applicationWillSuspend {
9045 [super applicationWillSuspend];
9048 - (BOOL) isSafeToSuspend {
9051 NSLog(@"isSafeToSuspend: locked_ != 0");
9056 // Use external process status API internally.
9057 // This is probably a really bad idea.
9058 // XXX: what is the point of this? does this solve anything at all?
9059 uint64_t status = 0;
9061 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9062 notify_get_state(notify_token, &status);
9063 notify_cancel(notify_token);
9068 NSLog(@"isSafeToSuspend: status != 0");
9074 NSLog(@"isSafeToSuspend: -> true");
9079 - (void) applicationSuspend:(__GSEvent *)event {
9080 if ([self isSafeToSuspend])
9081 [super applicationSuspend:event];
9084 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9085 if ([self isSafeToSuspend])
9086 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9089 - (void) _setSuspended:(BOOL)value {
9090 if ([self isSafeToSuspend])
9091 [super _setSuspended:value];
9094 - (UIProgressHUD *) addProgressHUD {
9095 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9096 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9098 [window_ setUserInteractionEnabled:NO];
9100 UIViewController *target(tabbar_);
9101 if (UIViewController *modal = [target modalViewController])
9104 UIView *view([target view]);
9105 [view addSubview:hud];
9113 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9116 [hud removeFromSuperview];
9117 [window_ setUserInteractionEnabled:YES];
9120 - (CyteViewController *) pageForPackage:(NSString *)name {
9121 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9124 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9125 NSString *scheme([[url scheme] lowercaseString]);
9126 if ([[url absoluteString] length] <= [scheme length] + 3)
9128 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9129 NSArray *components([path pathComponents]);
9131 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9132 return [self pageForPackage:[components objectAtIndex:1]];
9134 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9137 NSString *base([components objectAtIndex:0]);
9139 CyteViewController *controller = nil;
9141 if ([base isEqualToString:@"url"]) {
9142 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9143 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9144 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9145 } else if (!external && [components count] == 1) {
9146 if ([base isEqualToString:@"manage"]) {
9147 controller = [[[ManageController alloc] init] autorelease];
9150 if ([base isEqualToString:@"sources"]) {
9151 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9154 if ([base isEqualToString:@"home"]) {
9155 controller = [[[HomeController alloc] init] autorelease];
9158 if ([base isEqualToString:@"sections"]) {
9159 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9162 if ([base isEqualToString:@"search"]) {
9163 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9166 if ([base isEqualToString:@"changes"]) {
9167 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9170 if ([base isEqualToString:@"installed"]) {
9171 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9173 } else if ([components count] == 2) {
9174 NSString *argument = [components objectAtIndex:1];
9176 if ([base isEqualToString:@"package"]) {
9177 controller = [self pageForPackage:argument];
9180 if (!external && [base isEqualToString:@"search"]) {
9181 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9184 if (!external && [base isEqualToString:@"sections"]) {
9185 if ([argument isEqualToString:@"all"])
9187 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9190 if (!external && [base isEqualToString:@"sources"]) {
9191 if ([argument isEqualToString:@"add"]) {
9192 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9193 [(SourcesController *)controller showAddSourcePrompt];
9195 Source *source = [database_ sourceWithKey:argument];
9196 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9200 if (!external && [base isEqualToString:@"launch"]) {
9201 [self launchApplicationWithIdentifier:argument suspended:NO];
9204 } else if (!external && [components count] == 3) {
9205 NSString *arg1 = [components objectAtIndex:1];
9206 NSString *arg2 = [components objectAtIndex:2];
9208 if ([base isEqualToString:@"package"]) {
9209 if ([arg2 isEqualToString:@"settings"]) {
9210 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9211 } else if ([arg2 isEqualToString:@"files"]) {
9212 if (Package *package = [database_ packageWithName:arg1]) {
9213 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9214 [(FileTable *)controller setPackage:package];
9220 [controller setDelegate:self];
9224 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9225 CyteViewController *page([self pageForURL:url forExternal:external]);
9228 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9229 [nav setViewControllers:[NSArray arrayWithObject:page]];
9230 [tabbar_ setUnselectedViewController:nav];
9236 - (void) applicationOpenURL:(NSURL *)url {
9237 [super applicationOpenURL:url];
9242 [self openCydiaURL:url forExternal:YES];
9245 - (void) applicationWillResignActive:(UIApplication *)application {
9246 // Stop refreshing if you get a phone call or lock the device.
9247 if ([tabbar_ updating])
9248 [tabbar_ cancelUpdate];
9250 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9251 [super applicationWillResignActive:application];
9254 - (void) applicationWillTerminate:(UIApplication *)application {
9256 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9257 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9258 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9263 - (void) setConfigurationData:(NSString *)data {
9264 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9266 if (!conffile_r(data)) {
9267 lprintf("E:invalid conffile\n");
9271 NSString *ofile = conffile_r[1];
9272 //NSString *nfile = conffile_r[2];
9274 UIAlertView *alert = [[[UIAlertView alloc]
9275 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9276 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9278 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9280 UCLocalize("ACCEPT_NEW_COPY"),
9281 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9285 [alert setContext:@"conffile"];
9286 [alert setNumberOfRows:2];
9290 - (void) addStashController {
9292 stash_ = [[[StashController alloc] init] autorelease];
9293 [window_ addSubview:[stash_ view]];
9296 - (void) removeStashController {
9297 [[stash_ view] removeFromSuperview];
9303 [self setIdleTimerDisabled:YES];
9305 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9306 UpdateExternalStatus(1);
9307 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9308 UpdateExternalStatus(0);
9310 [self removeStashController];
9312 if (ExecFork() == 0) {
9313 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9314 perror("launchctl stop");
9318 - (void) setupViewControllers {
9319 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9321 NSMutableArray *items([NSMutableArray arrayWithObjects:
9322 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9323 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9324 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9325 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9329 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9330 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9332 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9335 NSMutableArray *controllers([NSMutableArray array]);
9336 for (UITabBarItem *item in items) {
9337 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9338 [controller setTabBarItem:item];
9339 [controllers addObject:controller];
9341 [tabbar_ setViewControllers:controllers];
9343 [tabbar_ setUpdateDelegate:self];
9346 - (void) applicationDidFinishLaunching:(id)unused {
9348 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9349 [self setApplicationSupportsShakeToEdit:NO];
9351 @synchronized (HostConfig_) {
9352 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9355 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9356 initWithMemoryCapacity:524288
9357 diskCapacity:10485760
9358 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9361 [CydiaWebViewController _initialize];
9363 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9365 // this would disallow http{,s} URLs from accessing this data
9366 //[WebView registerURLSchemeAsLocal:@"cydia"];
9368 Font12_ = [UIFont systemFontOfSize:12];
9369 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9370 Font14_ = [UIFont systemFontOfSize:14];
9371 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9372 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9374 essential_ = [NSMutableArray arrayWithCapacity:4];
9375 broken_ = [NSMutableArray arrayWithCapacity:4];
9377 // XXX: I really need this thing... like, seriously... I'm sorry
9378 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9380 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9381 [window_ orderFront:self];
9382 [window_ makeKey:self];
9383 [window_ setHidden:NO];
9386 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9387 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9388 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9389 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9390 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9391 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9392 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9393 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9394 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9397 [self addStashController];
9398 // XXX: this would be much cleaner as a yieldToSelector:
9399 // that way the removeStashController could happen right here inline
9400 // we also could no longer require the useless stash_ field anymore
9401 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9405 database_ = [Database sharedInstance];
9406 [database_ setDelegate:self];
9408 [window_ setUserInteractionEnabled:NO];
9409 [self setupViewControllers];
9411 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9412 [window_ addSubview:[emulated_ view]];
9414 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9418 - (NSArray *) defaultStartPages {
9419 NSMutableArray *standard = [NSMutableArray array];
9420 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9421 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9422 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9424 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9426 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9427 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9429 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9436 [window_ setUserInteractionEnabled:YES];
9437 [self showSettings];
9440 if ([emulated_ modalViewController] != nil)
9441 [emulated_ dismissModalViewControllerAnimated:YES];
9442 [window_ setUserInteractionEnabled:NO];
9450 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9451 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9452 int standardIndex = 0;
9453 NSArray *standard = [self defaultStartPages];
9460 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9461 if (valid && closed != nil) {
9462 NSTimeInterval interval([closed timeIntervalSinceNow]);
9463 // XXX: Is 15 minutes the optimal time here?
9464 if (interval > 0 && interval <= -(15*60))
9468 if (valid && [saved count] != [standard count])
9472 for (unsigned int i = 0; i < [standard count]; i++) {
9473 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9474 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9475 // but it's good enough for now.
9476 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9483 NSArray *items = nil;
9485 [tabbar_ setSelectedIndex:savedIndex];
9488 [tabbar_ setSelectedIndex:standardIndex];
9492 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9493 NSArray *stack = [items objectAtIndex:tab];
9494 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9495 NSMutableArray *current = [NSMutableArray array];
9497 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9498 NSString *addr = [stack objectAtIndex:nav];
9499 NSURL *url = [NSURL URLWithString:addr];
9500 CyteViewController *page = [self pageForURL:url forExternal:NO];
9502 [current addObject:page];
9505 [navigation setViewControllers:current];
9508 // (Try to) show the startup URL.
9509 if (starturl_ != nil) {
9510 [self openCydiaURL:starturl_ forExternal:NO];
9515 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9516 if (item != nil && IsWildcat_) {
9517 [sheet showFromBarButtonItem:item animated:YES];
9519 [sheet showInView:window_];
9523 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9524 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9525 [progress setTitle:task];
9526 [progress addProgressEvent:event];
9529 - (void) addProgressEventForTask:(NSArray *)data {
9530 CydiaProgressEvent *event([data objectAtIndex:0]);
9531 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9532 [self addProgressEvent:event forTask:task];
9535 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9536 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9542 id Alloc_(id self, SEL selector) {
9543 id object = alloc_(self, selector);
9544 lprintf("[%s]A-%p\n", self->isa->name, object);
9549 id Dealloc_(id self, SEL selector) {
9550 id object = dealloc_(self, selector);
9551 lprintf("[%s]D-%p\n", self->isa->name, object);
9555 Class $WebDefaultUIKitDelegate;
9557 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9558 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9559 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9560 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9563 static NSSet *MobilizedFiles_;
9565 static NSURL *MobilizeURL(NSURL *url) {
9566 NSString *path([url path]);
9567 if ([path hasPrefix:@"/var/root/"]) {
9568 NSString *file([path substringFromIndex:10]);
9569 if ([MobilizedFiles_ containsObject:file])
9570 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9576 Class $CFXPreferencesPropertyListSource;
9577 @class CFXPreferencesPropertyListSource;
9579 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9580 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9581 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9582 url = MobilizeURL(url);
9583 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9584 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9590 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9591 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9592 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9593 url = MobilizeURL(url);
9594 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9595 //NSLog(@"%@ %@", [url absoluteString], value);
9601 Class $NSURLConnection;
9603 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9604 NSMutableURLRequest *copy([request mutableCopy]);
9606 NSURL *url([copy URL]);
9608 NSString *href([url absoluteString]);
9609 NSString *host([url host]);
9610 NSString *scheme([[url scheme] lowercaseString]);
9612 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9614 @synchronized (HostConfig_) {
9615 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9616 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9617 [copy setHTTPShouldUsePipelining:YES];
9619 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9620 if ([control isEqualToString:@"max-age=0"])
9621 if ([CachedURLs_ containsObject:href]) {
9623 NSLog(@"~~~: %@", href);
9626 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9628 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9629 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9630 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9634 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9638 int main(int argc, char *argv[]) {
9639 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9643 UpdateExternalStatus(0);
9645 if (Class $UIDevice = objc_getClass("UIDevice")) {
9646 UIDevice *device([$UIDevice currentDevice]);
9647 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9651 UIScreen *screen([UIScreen mainScreen]);
9652 if ([screen respondsToSelector:@selector(scale)])
9653 ScreenScale_ = [screen scale];
9657 UIDevice *device([UIDevice currentDevice]);
9658 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9661 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9662 if (idiom == UIUserInterfaceIdiomPhone)
9664 else if (idiom == UIUserInterfaceIdiomPad)
9667 NSLog(@"unknown UIUserInterfaceIdiom!");
9670 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9672 HostConfig_ = [[[NSObject alloc] init] autorelease];
9673 @synchronized (HostConfig_) {
9674 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9675 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9676 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9679 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9681 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9683 MobilizedFiles_ = [NSMutableSet setWithObjects:
9684 @"Library/Preferences/com.apple.Accessibility.plist",
9685 @"Library/Preferences/com.apple.preferences.sounds.plist",
9688 /* Library Hacks {{{ */
9689 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9691 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9693 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9694 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9695 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9696 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9699 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9700 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9701 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9702 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9705 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9706 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9707 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9708 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9709 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9712 $NSURLConnection = objc_getClass("NSURLConnection");
9713 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9714 if (NSURLConnection$init$ != NULL) {
9715 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9716 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9719 /* Set Locale {{{ */
9720 Locale_ = CFLocaleCopyCurrent();
9721 Languages_ = [NSLocale preferredLanguages];
9723 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9724 //NSLog(@"%@", [Languages_ description]);
9727 if (Locale_ != NULL)
9728 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9729 else if (Languages_ != nil && [Languages_ count] != 0)
9730 lang = [[Languages_ objectAtIndex:0] UTF8String];
9732 // XXX: consider just setting to C and then falling through?
9736 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9737 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9740 NSLog(@"Setting Language: %s", lang);
9743 setenv("LANG", lang, true);
9744 std::setlocale(LC_ALL, lang);
9748 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9750 /* Parse Arguments {{{ */
9751 bool substrate(false);
9757 for (int argi(1); argi != argc; ++argi)
9758 if (strcmp(argv[argi], "--") == 0) {
9760 argv[argi] = argv[0];
9766 for (int argi(1); argi != arge; ++argi)
9767 if (strcmp(args[argi], "--substrate") == 0)
9770 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9774 App_ = [[NSBundle mainBundle] bundlePath];
9780 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9781 alloc_ = alloc->method_imp;
9782 alloc->method_imp = (IMP) &Alloc_;*/
9784 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9785 dealloc_ = dealloc->method_imp;
9786 dealloc->method_imp = (IMP) &Dealloc_;*/
9788 /* System Information {{{ */
9792 size = sizeof(maxproc);
9793 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9794 perror("sysctlbyname(\"kern.maxproc\", ?)");
9795 else if (maxproc < 64) {
9797 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9798 perror("sysctlbyname(\"kern.maxproc\", #)");
9801 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9802 char *osversion = new char[size];
9803 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9804 perror("sysctlbyname(\"kern.osversion\", ?)");
9806 System_ = [NSString stringWithUTF8String:osversion];
9808 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9809 char *machine = new char[size];
9810 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9811 perror("sysctlbyname(\"hw.machine\", ?)");
9815 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9816 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9817 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9819 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9821 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9822 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9823 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9825 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9826 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9827 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9829 if (mcc != NULL && mnc != NULL)
9830 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9837 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9838 Build_ = [system objectForKey:@"ProductBuildVersion"];
9839 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9840 Product_ = [info objectForKey:@"SafariProductVersion"];
9841 Safari_ = [info objectForKey:@"CFBundleVersion"];
9844 /* Load Database {{{ */
9846 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9848 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9850 if (Metadata_ == NULL)
9851 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9853 Settings_ = [Metadata_ objectForKey:@"Settings"];
9855 Packages_ = [Metadata_ objectForKey:@"Packages"];
9856 Sections_ = [Metadata_ objectForKey:@"Sections"];
9857 Sources_ = [Metadata_ objectForKey:@"Sources"];
9859 Token_ = [Metadata_ objectForKey:@"Token"];
9862 if (Settings_ != nil)
9863 Role_ = [Settings_ objectForKey:@"Role"];
9865 if (Sections_ == nil) {
9866 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9867 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9870 if (Sources_ == nil) {
9871 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9872 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9877 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9880 if (Packages_ != nil) {
9882 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9886 [Metadata_ removeObjectForKey:@"Packages"];
9892 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9894 #define MobileSubstrate_(name) \
9895 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9896 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9897 if (handle == NULL) \
9898 NSLog(@"%s", dlerror()); \
9901 MobileSubstrate_(Activator)
9902 MobileSubstrate_(libstatusbar)
9903 MobileSubstrate_(SimulatedKeyEvents)
9904 MobileSubstrate_(WinterBoard)
9906 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9907 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9909 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9911 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9912 unlink("/tmp/.cydia.fw");
9914 } else if (access("/User", F_OK) != 0 || version < 4) {
9917 system("/usr/libexec/cydia/firmware.sh");
9921 _assert([[NSFileManager defaultManager]
9922 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9923 withIntermediateDirectories:YES
9928 if (access("/tmp/cydia.chk", F_OK) == 0) {
9929 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9930 _assert(errno == ENOENT);
9931 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9932 _assert(errno == ENOENT);
9935 /* APT Initialization {{{ */
9936 _assert(pkgInitConfig(*_config));
9937 _assert(pkgInitSystem(*_config, _system));
9940 _config->Set("APT::Acquire::Translation", lang);
9942 // XXX: this timeout might be important :(
9943 //_config->Set("Acquire::http::Timeout", 15);
9945 _config->Set("Acquire::http::MaxParallel", 3);
9947 /* Color Choices {{{ */
9948 space_ = CGColorSpaceCreateDeviceRGB();
9950 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9951 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9952 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9953 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9954 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9955 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9956 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9957 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9958 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9960 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9961 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9963 /* UIKit Configuration {{{ */
9964 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9965 if ($GSFontSetUseLegacyFontMetrics != NULL)
9966 $GSFontSetUseLegacyFontMetrics(YES);
9968 // XXX: I have a feeling this was important
9969 //UIKeyboardDisableAutomaticAppearance();
9972 Colon_ = UCLocalize("COLON_DELIMITED");
9973 Elision_ = UCLocalize("ELISION");
9974 Error_ = UCLocalize("ERROR");
9975 Warning_ = UCLocalize("WARNING");
9978 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9980 CGColorSpaceRelease(space_);