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 <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
126 #include <CydiaSubstrate/CydiaSubstrate.h>
127 #include "Menes/Menes.h"
129 #include "CyteKit/PerlCompatibleRegEx.hpp"
130 #include "CyteKit/TableViewCell.h"
131 #include "CyteKit/WebScriptObject-Cyte.h"
132 #include "CyteKit/WebViewController.h"
133 #include "CyteKit/stringWithUTF8Bytes.h"
135 #include "Cydia/MIMEAddress.h"
136 #include "Cydia/LoadingViewController.h"
137 #include "Cydia/ProgressEvent.h"
139 #include "SDURLCache/SDURLCache.h"
146 #define _timestamp ({ \
148 gettimeofday(&tv, NULL); \
149 tv.tv_sec * 1000000 + tv.tv_usec; \
152 typedef std::vector<class ProfileTime *> TimeList;
162 ProfileTime(const char *name) :
166 times_.push_back(this);
169 void AddTime(uint64_t time) {
176 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
188 ProfileTimer(ProfileTime &time) :
195 time_.AddTime(_timestamp - start_);
200 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
202 std::cerr << "========" << std::endl;
205 #define _profile(name) { \
206 static ProfileTime name(#name); \
207 ProfileTimer _ ## name(name);
212 extern NSString *Cydia_;
214 #define lprintf(args...) fprintf(stderr, args)
217 #define TraceLogging (1 && !ForRelease)
218 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
219 #define ProfileTimes (0 && !ForRelease)
220 #define ForSaurik (0 && !ForRelease)
221 #define LogBrowser (0 && !ForRelease)
222 #define TrackResize (0 && !ForRelease)
223 #define ManualRefresh (1 && !ForRelease)
224 #define ShowInternals (0 && !ForRelease)
225 #define AlwaysReload (0 && !ForRelease)
226 #define TryIndexedCollation (0 && !ForRelease)
230 #define _trace(args...)
235 #define _profile(name) {
238 #define PrintTimes() do {} while (false)
241 // Hash Functions/Structures {{{
242 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
250 static NSString *Colon_;
252 static NSString *Error_;
253 static NSString *Warning_;
255 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
257 static _finline NSString *CydiaURL(NSString *path) {
259 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
260 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
261 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
262 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
263 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
265 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
268 static _finline void UpdateExternalStatus(uint64_t newStatus) {
270 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
271 notify_set_state(notify_token, newStatus);
272 notify_cancel(notify_token);
274 notify_post("com.saurik.Cydia.status");
277 static CGFloat CYStatusBarHeight() {
278 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
279 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
282 /* NSForcedOrderingSearch doesn't work on the iPhone */
283 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
284 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
285 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
287 /* Insertion Sort {{{ */
289 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
290 const char *ptr = (const char *)list;
292 CFIndex half = count / 2;
293 const char *probe = ptr + elementSize * half;
294 CFComparisonResult cr = comparator(element, probe, context);
295 if (0 == cr) return (probe - (const char *)list) / elementSize;
296 ptr = (cr < 0) ? ptr : probe + elementSize;
297 count = (cr < 0) ? half : (half + (count & 1) - 1);
299 return (ptr - (const char *)list) / elementSize;
302 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
303 const char *ptr = (const char *)list;
305 CFIndex half = count / 2;
306 const char *probe = ptr + elementSize * half;
307 CFComparisonResult cr = comparator(element, probe, context);
308 if (0 == cr) return (probe - (const char *)list) / elementSize;
309 ptr = (cr < 0) ? ptr : probe + elementSize;
310 count = (cr < 0) ? half : (half + (count & 1) - 1);
312 return (ptr - (const char *)list) / elementSize;
315 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
316 if (range.length == 0)
318 const void **values(new const void *[range.length]);
319 CFArrayGetValues(array, range, values);
321 #if HistogramInsertionSort > 0
322 uint32_t total(0), *offsets(new uint32_t[range.length]);
325 for (CFIndex index(1); index != range.length; ++index) {
326 const void *value(values[index]);
327 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
328 CFIndex correct(index);
329 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
330 #if HistogramInsertionSort > 1
331 NSLog(@"%@ < %@", value, values[correct - 1]);
336 if (correct != index) {
337 size_t offset(index - correct);
338 #if HistogramInsertionSort
342 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
344 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
345 values[correct] = value;
349 CFArrayReplaceValues(array, range, values, range.length);
352 #if HistogramInsertionSort > 0
353 for (CFIndex index(0); index != range.length; ++index)
354 if (offsets[index] != 0)
355 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
356 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
363 /* Apple Bug Fixes {{{ */
364 @implementation UIWebDocumentView (Cydia)
366 - (void) _setScrollerOffset:(CGPoint)offset {
367 UIScroller *scroller([self _scroller]);
369 CGSize size([scroller contentSize]);
370 CGSize bounds([scroller bounds].size);
373 max.x = size.width - bounds.width;
374 max.y = size.height - bounds.height;
382 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
383 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
385 [scroller setOffset:offset];
391 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
392 size_t length([self length] - state->state);
395 else if (length > count)
397 for (size_t i(0); i != length; ++i)
398 objects[i] = [self item:state->state++];
399 state->itemsPtr = objects;
400 state->mutationsPtr = (unsigned long *) self;
404 /* Cydia NSString Additions {{{ */
405 @interface NSString (Cydia)
406 - (NSComparisonResult) compareByPath:(NSString *)other;
407 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
410 @implementation NSString (Cydia)
412 - (NSComparisonResult) compareByPath:(NSString *)other {
413 NSString *prefix = [self commonPrefixWithString:other options:0];
414 size_t length = [prefix length];
416 NSRange lrange = NSMakeRange(length, [self length] - length);
417 NSRange rrange = NSMakeRange(length, [other length] - length);
419 lrange = [self rangeOfString:@"/" options:0 range:lrange];
420 rrange = [other rangeOfString:@"/" options:0 range:rrange];
422 NSComparisonResult value;
424 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
425 value = NSOrderedSame;
426 else if (lrange.location == NSNotFound)
427 value = NSOrderedAscending;
428 else if (rrange.location == NSNotFound)
429 value = NSOrderedDescending;
431 value = NSOrderedSame;
433 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
434 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
435 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
436 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
438 NSComparisonResult result = [lpath compare:rpath];
439 return result == NSOrderedSame ? value : result;
442 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
443 return [(id)CFURLCreateStringByAddingPercentEscapes(
448 kCFStringEncodingUTF8
455 /* C++ NSString Wrapper Cache {{{ */
456 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
457 return size == 0 ? NULL :
458 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
459 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
462 static _finline CFStringRef CYStringCreate(const char *data) {
463 return CYStringCreate(data, strlen(data));
472 _finline void clear_() {
473 if (cache_ != NULL) {
480 _finline bool empty() const {
484 _finline size_t size() const {
488 _finline char *data() const {
492 _finline void clear() {
497 _finline CYString() :
504 _finline ~CYString() {
508 void operator =(const CYString &rhs) {
512 if (rhs.cache_ == nil)
515 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
518 void copy(apr_pool_t *pool) {
519 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
520 memcpy(temp, data_, size_);
525 void set(apr_pool_t *pool, const char *data, size_t size) {
531 data_ = const_cast<char *>(data);
539 _finline void set(apr_pool_t *pool, const char *data) {
540 set(pool, data, data == NULL ? 0 : strlen(data));
543 _finline void set(apr_pool_t *pool, const std::string &rhs) {
544 set(pool, rhs.data(), rhs.size());
547 bool operator ==(const CYString &rhs) const {
548 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
551 _finline operator CFStringRef() {
553 cache_ = CYStringCreate(data_, size_);
557 _finline operator id() {
558 return (NSString *) static_cast<CFStringRef>(*this);
561 _finline operator const char *() {
562 return reinterpret_cast<const char *>(data_);
566 /* C++ NSString Algorithm Adapters {{{ */
568 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
571 struct NSStringMapHash :
572 std::unary_function<NSString *, size_t>
574 _finline size_t operator ()(NSString *value) const {
575 return CFStringHashNSString((CFStringRef) value);
579 struct NSStringMapLess :
580 std::binary_function<NSString *, NSString *, bool>
582 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
583 return [lhs compare:rhs] == NSOrderedAscending;
587 struct NSStringMapEqual :
588 std::binary_function<NSString *, NSString *, bool>
590 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
591 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
592 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
593 //[lhs isEqualToString:rhs];
598 /* CoreGraphics Primitives {{{ */
603 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
604 CGFloat color[] = {red, green, blue, alpha};
605 return CGColorCreate(space, color);
614 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
615 color_(Create_(space, red, green, blue, alpha))
617 Set(space, red, green, blue, alpha);
622 CGColorRelease(color_);
629 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
631 color_ = Create_(space, red, green, blue, alpha);
634 operator CGColorRef() {
640 /* Random Global Variables {{{ */
641 static const int PulseInterval_ = 50000;
643 static const NSString *UI_;
646 static bool RestartSubstrate_;
647 static NSArray *Finishes_;
649 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
650 #define NotifyConfig_ "/etc/notify.conf"
652 static bool Queuing_;
654 static CYColor Blue_;
655 static CYColor Blueish_;
656 static CYColor Black_;
658 static CYColor White_;
659 static CYColor Gray_;
660 static CYColor Green_;
661 static CYColor Purple_;
662 static CYColor Purplish_;
664 static UIColor *InstallingColor_;
665 static UIColor *RemovingColor_;
667 static NSString *App_;
669 static BOOL Advanced_;
670 static BOOL Ignored_;
672 static _H<UIFont> Font12_;
673 static _H<UIFont> Font12Bold_;
674 static _H<UIFont> Font14_;
675 static _H<UIFont> Font18Bold_;
676 static _H<UIFont> Font22Bold_;
678 static const char *Machine_ = NULL;
679 static NSString *System_ = nil;
680 static NSString *SerialNumber_ = nil;
681 static NSString *ChipID_ = nil;
682 static NSString *BBSNum_ = nil;
683 static _H<NSString> Token_;
684 static NSString *UniqueID_ = nil;
685 static NSString *PLMN_ = nil;
686 static NSString *Build_ = nil;
687 static NSString *Product_ = nil;
688 static NSString *Safari_ = nil;
690 static CFLocaleRef Locale_;
691 static NSArray *Languages_;
692 static CGColorSpaceRef space_;
694 static NSDictionary *SectionMap_;
695 static NSMutableDictionary *Metadata_;
696 static _transient NSMutableDictionary *Settings_;
697 static _transient NSString *Role_;
698 static _transient NSMutableDictionary *Packages_;
699 static _transient NSMutableDictionary *Values_;
700 static _transient NSMutableDictionary *Sections_;
701 _H<NSMutableDictionary> Sources_;
702 static _transient NSNumber *Version_;
703 _H<NSString> CydiaSource_;
708 static CGFloat ScreenScale_;
709 static NSString *Idiom_;
710 _H<NSString> Firmware_;
711 static NSString *Major_;
713 static _H<NSMutableDictionary> SessionData_;
714 static _H<NSObject> HostConfig_;
715 static _H<NSMutableSet> BridgedHosts_;
716 static _H<NSMutableSet> TokenHosts_;
717 static _H<NSMutableSet> InsecureHosts_;
718 static _H<NSMutableSet> PipelinedHosts_;
719 static _H<NSMutableSet> CachedURLs_;
721 static NSString *kCydiaProgressEventTypeError = @"Error";
722 static NSString *kCydiaProgressEventTypeInformation = @"Information";
723 static NSString *kCydiaProgressEventTypeStatus = @"Status";
724 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
727 /* Display Helpers {{{ */
728 inline float Interpolate(float begin, float end, float fraction) {
729 return (end - begin) * fraction + begin;
732 static _finline const char *StripVersion_(const char *version) {
733 const char *colon(strchr(version, ':'));
734 return colon == NULL ? version : colon + 1;
737 NSString *LocalizeSection(NSString *section) {
738 static Pcre title_r("^(.*?) \\((.*)\\)$");
739 if (title_r(section)) {
740 NSString *parent(title_r[1]);
741 NSString *child(title_r[2]);
743 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
744 LocalizeSection(parent),
745 LocalizeSection(child)
749 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
752 NSString *Simplify(NSString *title) {
753 const char *data = [title UTF8String];
754 size_t size = [title length];
756 static Pcre square_r("^\\[(.*)\\]$");
757 if (square_r(data, size))
758 return Simplify(square_r[1]);
760 static Pcre paren_r("^\\((.*)\\)$");
761 if (paren_r(data, size))
762 return Simplify(paren_r[1]);
764 static Pcre title_r("^(.*?) \\((.*)\\)$");
765 if (title_r(data, size))
766 return Simplify(title_r[1]);
772 NSString *GetLastUpdate() {
773 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
776 return UCLocalize("NEVER_OR_UNKNOWN");
778 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
779 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
781 CFRelease(formatter);
783 return [(NSString *) formatted autorelease];
786 bool isSectionVisible(NSString *section) {
787 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
788 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
789 return hidden == nil || ![hidden boolValue];
792 static NSObject *CYIOGetValue(const char *path, NSString *property) {
793 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
794 if (entry == MACH_PORT_NULL)
797 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
798 IOObjectRelease(entry);
802 return [(id) value autorelease];
805 static NSString *CYHex(NSData *data, bool reverse = false) {
809 size_t length([data length]);
810 uint8_t bytes[length];
811 [data getBytes:bytes];
813 char string[length * 2 + 1];
814 for (size_t i(0); i != length; ++i)
815 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
817 return [NSString stringWithUTF8String:string];
822 /* Delegate Prototypes {{{ */
825 @class CydiaProgressEvent;
827 @protocol DatabaseDelegate
828 - (void) repairWithSelector:(SEL)selector;
829 - (void) setConfigurationData:(NSString *)data;
830 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
833 @class CYPackageController;
835 @protocol CydiaDelegate
836 - (void) returnToCydia;
838 - (void) retainNetworkActivityIndicator;
839 - (void) releaseNetworkActivityIndicator;
840 - (void) clearPackage:(Package *)package;
841 - (void) installPackage:(Package *)package;
842 - (void) installPackages:(NSArray *)packages;
843 - (void) removePackage:(Package *)package;
844 - (void) beginUpdate;
846 - (void) distUpgrade;
850 - (void) addSource:(NSDictionary *)source;
851 - (void) addTrivialSource:(NSString *)href;
852 - (void) showSettings;
853 - (UIProgressHUD *) addProgressHUD;
854 - (void) removeProgressHUD:(UIProgressHUD *)hud;
855 - (CyteViewController *) pageForPackage:(NSString *)name;
856 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
857 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
861 /* Status Delegation {{{ */
863 public pkgAcquireStatus
866 _transient NSObject<ProgressDelegate> *delegate_;
876 void setDelegate(NSObject<ProgressDelegate> *delegate) {
877 delegate_ = delegate;
880 NSObject<ProgressDelegate> *getDelegate() const {
884 virtual bool MediaChange(std::string media, std::string drive) {
888 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
892 virtual void Fetch(pkgAcquire::ItemDesc &item) {
893 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
894 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
895 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
898 virtual void Done(pkgAcquire::ItemDesc &item) {
899 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
900 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
901 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
904 virtual void Fail(pkgAcquire::ItemDesc &item) {
906 item.Owner->Status == pkgAcquire::Item::StatIdle ||
907 item.Owner->Status == pkgAcquire::Item::StatDone
911 std::string &error(item.Owner->ErrorText);
915 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
916 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
919 virtual bool Pulse(pkgAcquire *Owner) {
920 bool value = pkgAcquireStatus::Pulse(Owner);
923 double(CurrentBytes + CurrentItems) /
924 double(TotalBytes + TotalItems)
927 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
928 [NSNumber numberWithDouble:percent], @"Percent",
930 [NSNumber numberWithDouble:CurrentBytes], @"Current",
931 [NSNumber numberWithDouble:TotalBytes], @"Total",
932 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
933 nil] waitUntilDone:YES];
935 if (value && ![delegate_ isProgressCancelled])
943 _finline bool WasCancelled() const {
947 virtual void Start() {
948 pkgAcquireStatus::Start();
949 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
952 virtual void Stop() {
953 pkgAcquireStatus::Stop();
954 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
955 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
959 /* Database Interface {{{ */
960 typedef std::map< unsigned long, _H<Source> > SourceMap;
962 @interface Database : NSObject {
969 pkgDepCache::Policy *policy_;
970 pkgRecords *records_;
971 pkgProblemResolver *resolver_;
972 pkgAcquire *fetcher_;
974 SPtr<pkgPackageManager> manager_;
975 pkgSourceList *list_;
977 SourceMap sourceMap_;
978 _H<NSMutableArray> sourceList_;
980 CFMutableArrayRef packages_;
982 _transient NSObject<DatabaseDelegate> *delegate_;
983 _transient NSObject<ProgressDelegate> *progress_;
991 std::map<const char *, _H<NSString> > sections_;
994 + (Database *) sharedInstance;
997 - (void) _readCydia:(NSNumber *)fd;
998 - (void) _readStatus:(NSNumber *)fd;
999 - (void) _readOutput:(NSNumber *)fd;
1003 - (Package *) packageWithName:(NSString *)name;
1005 - (pkgCacheFile &) cache;
1006 - (pkgDepCache::Policy *) policy;
1007 - (pkgRecords *) records;
1008 - (pkgProblemResolver *) resolver;
1009 - (pkgAcquire &) fetcher;
1010 - (pkgSourceList &) list;
1011 - (NSArray *) packages;
1012 - (NSArray *) sources;
1013 - (Source *) sourceWithKey:(NSString *)key;
1014 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1022 - (void) updateWithStatus:(Status &)status;
1024 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1026 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1027 - (NSObject<ProgressDelegate> *) progressDelegate;
1029 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1031 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1035 /* ProgressEvent Implementation {{{ */
1036 @implementation CydiaProgressEvent
1038 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1039 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1042 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1043 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1044 [event setPackage:package];
1048 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1049 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1051 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1052 NSArray *fields([description componentsSeparatedByString:@" "]);
1053 [event setItem:fields];
1055 if ([fields count] > 3) {
1056 [event setPackage:[fields objectAtIndex:2]];
1057 [event setVersion:[fields objectAtIndex:3]];
1060 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1065 + (NSArray *) _attributeKeys {
1066 return [NSArray arrayWithObjects:
1076 - (NSArray *) attributeKeys {
1077 return [[self class] _attributeKeys];
1080 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1081 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1084 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1085 if ((self = [super init]) != nil) {
1091 - (NSString *) message {
1095 - (NSString *) type {
1099 - (NSArray *) item {
1100 return (id) item_ ?: [NSNull null];
1103 - (void) setItem:(NSArray *)item {
1107 - (NSString *) package {
1108 return (id) package_ ?: [NSNull null];
1111 - (void) setPackage:(NSString *)package {
1115 - (NSString *) url {
1116 return (id) url_ ?: [NSNull null];
1119 - (void) setURL:(NSString *)url {
1123 - (void) setVersion:(NSString *)version {
1127 - (NSString *) version {
1128 return (id) version_ ?: [NSNull null];
1131 - (NSString *) compound:(NSString *)value {
1133 NSString *mode(nil); {
1134 NSString *type([self type]);
1135 if ([type isEqualToString:kCydiaProgressEventTypeError])
1136 mode = UCLocalize("ERROR");
1137 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1138 mode = UCLocalize("WARNING");
1142 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1148 - (NSString *) compoundMessage {
1149 return [self compound:[self message]];
1152 - (NSString *) compoundTitle {
1155 if (package_ == nil)
1157 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1158 title = [package name];
1162 return [self compound:title];
1168 // Cytore Definitions {{{
1169 struct PackageValue :
1172 Cytore::Offset<PackageValue> next_;
1174 uint32_t index_ : 23;
1175 uint32_t subscribed_ : 1;
1192 Cytore::Offset<PackageValue> packages_[1 << 16];
1195 static Cytore::File<MetaValue> MetaFile_;
1197 // Cytore Helper Functions {{{
1198 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1199 SplitHash nhash = { hashlittle(name, length) };
1201 PackageValue *metadata;
1203 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1204 offset: if (offset->IsNull()) {
1205 *offset = MetaFile_.New<PackageValue>(length + 1);
1206 metadata = &MetaFile_.Get(*offset);
1208 if (metadata == NULL) {
1212 metadata = new PackageValue();
1213 memset(metadata, 0, sizeof(*metadata));
1216 memcpy(metadata->name_, name, length + 1);
1217 metadata->nhash_ = nhash.u16[1];
1219 metadata = &MetaFile_.Get(*offset);
1221 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1222 offset = &metadata->next_;
1230 static void PackageImport(const void *key, const void *value, void *context) {
1231 bool &fail(*reinterpret_cast<bool *>(context));
1234 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1235 NSLog(@"failed to import package %@", key);
1239 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1240 NSDictionary *package((NSDictionary *) value);
1242 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1243 if ([subscribed boolValue] && !metadata->subscribed_)
1244 metadata->subscribed_ = true;
1246 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1247 time_t time([date timeIntervalSince1970]);
1248 if (metadata->first_ > time || metadata->first_ == 0)
1249 metadata->first_ = time;
1252 NSDate *date([package objectForKey:@"LastSeen"]);
1253 NSString *version([package objectForKey:@"LastVersion"]);
1255 if (date != nil && version != nil) {
1256 time_t time([date timeIntervalSince1970]);
1257 if (metadata->last_ < time || metadata->last_ == 0)
1258 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1259 size_t length(strlen(buffer));
1260 uint16_t vhash(hashlittle(buffer, length));
1262 size_t capped(std::min<size_t>(8, length));
1263 char *latest(buffer + length - capped);
1265 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1266 metadata->vhash_ = vhash;
1268 metadata->last_ = time;
1274 /* Source Class {{{ */
1275 @interface Source : NSObject {
1277 Database *database_;
1280 CYString depiction_;
1281 CYString description_;
1287 CYString distribution_;
1293 _H<NSString> authority_;
1295 CYString defaultIcon_;
1297 _H<NSDictionary> record_;
1301 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1303 - (NSComparisonResult) compareByName:(Source *)source;
1305 - (NSString *) depictionForPackage:(NSString *)package;
1306 - (NSString *) supportForPackage:(NSString *)package;
1308 - (NSDictionary *) record;
1311 - (NSString *) rooturi;
1312 - (NSString *) distribution;
1313 - (NSString *) type;
1316 - (NSString *) host;
1318 - (NSString *) name;
1319 - (NSString *) shortDescription;
1320 - (NSString *) label;
1321 - (NSString *) origin;
1322 - (NSString *) version;
1324 - (NSString *) defaultIcon;
1325 - (NSURL *) iconURL;
1329 @implementation Source
1333 distribution_.clear();
1338 description_.clear();
1344 defaultIcon_.clear();
1351 + (NSString *) webScriptNameForSelector:(SEL)selector {
1353 else if (selector == @selector(addSection:))
1354 return @"addSection";
1355 else if (selector == @selector(getField:))
1357 else if (selector == @selector(removeSection:))
1358 return @"removeSection";
1359 else if (selector == @selector(remove))
1365 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1366 return [self webScriptNameForSelector:selector] == nil;
1369 + (NSArray *) _attributeKeys {
1370 return [NSArray arrayWithObjects:
1381 @"shortDescription",
1388 - (NSArray *) attributeKeys {
1389 return [[self class] _attributeKeys];
1392 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1393 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1396 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1399 trusted_ = index->IsTrusted();
1401 uri_.set(pool, index->GetURI());
1402 distribution_.set(pool, index->GetDist());
1403 type_.set(pool, index->GetType());
1405 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1406 if (dindex != NULL) {
1407 base_.set(pool, dindex->MetaIndexURI(""));
1410 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1413 pkgTagFile tags(&fd);
1415 pkgTagSection section;
1422 {"default-icon", &defaultIcon_},
1423 {"depiction", &depiction_},
1424 {"description", &description_},
1426 {"origin", &origin_},
1427 {"support", &support_},
1428 {"version", &version_},
1431 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1432 const char *start, *end;
1434 if (section.Find(names[i].name_, start, end)) {
1435 CYString &value(*names[i].value_);
1436 value.set(pool, start, end - start);
1442 record_ = [Sources_ objectForKey:[self key]];
1444 NSURL *url([NSURL URLWithString:uri_]);
1448 host_ = [host_ lowercaseString];
1453 authority_ = [url path];
1456 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1457 if ((self = [super init]) != nil) {
1458 era_ = [database era];
1459 database_ = database;
1462 [self setMetaIndex:index inPool:pool];
1466 - (NSString *) getField:(NSString *)name {
1467 @synchronized (database_) {
1468 if ([database_ era] != era_ || index_ == NULL)
1471 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1476 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1481 pkgTagFile tags(&fd);
1483 pkgTagSection section;
1486 const char *start, *end;
1487 if (!section.Find([name UTF8String], start, end))
1488 return (NSString *) [NSNull null];
1490 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1493 - (NSComparisonResult) compareByName:(Source *)source {
1494 NSString *lhs = [self name];
1495 NSString *rhs = [source name];
1497 if ([lhs length] != 0 && [rhs length] != 0) {
1498 unichar lhc = [lhs characterAtIndex:0];
1499 unichar rhc = [rhs characterAtIndex:0];
1501 if (isalpha(lhc) && !isalpha(rhc))
1502 return NSOrderedAscending;
1503 else if (!isalpha(lhc) && isalpha(rhc))
1504 return NSOrderedDescending;
1507 return [lhs compare:rhs options:LaxCompareOptions_];
1510 - (NSString *) depictionForPackage:(NSString *)package {
1511 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1514 - (NSString *) supportForPackage:(NSString *)package {
1515 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1518 - (NSArray *) sections {
1519 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1522 - (void) _addSection:(NSString *)section {
1525 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1526 if (![sections containsObject:section]) {
1527 [sections addObject:section];
1531 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1536 - (bool) addSection:(NSString *)section {
1540 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1544 - (void) _removeSection:(NSString *)section {
1548 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1549 if ([sections containsObject:section]) {
1550 [sections removeObject:section];
1555 - (bool) removeSection:(NSString *)section {
1559 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1564 [Sources_ removeObjectForKey:[self key]];
1569 bool value(record_ != nil);
1570 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1574 - (NSDictionary *) record {
1582 - (NSString *) rooturi {
1586 - (NSString *) distribution {
1587 return distribution_;
1590 - (NSString *) type {
1594 - (NSString *) baseuri {
1595 return base_.empty() ? nil : (id) base_;
1598 - (NSString *) iconuri {
1599 if (NSString *base = [self baseuri])
1600 return [base stringByAppendingString:@"CydiaIcon.png"];
1605 - (NSURL *) iconURL {
1606 if (NSString *uri = [self iconuri])
1607 return [NSURL URLWithString:uri];
1611 - (NSString *) key {
1612 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1615 - (NSString *) host {
1619 - (NSString *) name {
1620 return origin_.empty() ? (id) authority_ : origin_;
1623 - (NSString *) shortDescription {
1624 return description_;
1627 - (NSString *) label {
1628 return label_.empty() ? (id) authority_ : label_;
1631 - (NSString *) origin {
1635 - (NSString *) version {
1639 - (NSString *) defaultIcon {
1640 return defaultIcon_;
1645 /* CydiaOperation Class {{{ */
1646 @interface CydiaOperation : NSObject {
1647 _H<NSString> operator_;
1648 _H<NSString> value_;
1651 - (NSString *) operator;
1652 - (NSString *) value;
1656 @implementation CydiaOperation
1658 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1659 if ((self = [super init]) != nil) {
1660 operator_ = [NSString stringWithUTF8String:_operator];
1661 value_ = [NSString stringWithUTF8String:value];
1665 + (NSArray *) _attributeKeys {
1666 return [NSArray arrayWithObjects:
1672 - (NSArray *) attributeKeys {
1673 return [[self class] _attributeKeys];
1676 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1677 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1680 - (NSString *) operator {
1684 - (NSString *) value {
1690 /* CydiaClause Class {{{ */
1691 @interface CydiaClause : NSObject {
1692 _H<NSString> package_;
1693 _H<CydiaOperation> version_;
1696 - (NSString *) package;
1697 - (CydiaOperation *) version;
1701 @implementation CydiaClause
1703 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1704 if ((self = [super init]) != nil) {
1705 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1707 if (const char *version = dep.TargetVer())
1708 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1710 version_ = (id) [NSNull null];
1714 + (NSArray *) _attributeKeys {
1715 return [NSArray arrayWithObjects:
1721 - (NSArray *) attributeKeys {
1722 return [[self class] _attributeKeys];
1725 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1726 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1729 - (NSString *) package {
1733 - (CydiaOperation *) version {
1739 /* CydiaRelation Class {{{ */
1740 @interface CydiaRelation : NSObject {
1741 _H<NSString> relationship_;
1742 _H<NSMutableArray> clauses_;
1745 - (NSString *) relationship;
1746 - (NSArray *) clauses;
1750 @implementation CydiaRelation
1752 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1753 if ((self = [super init]) != nil) {
1754 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1755 clauses_ = [NSMutableArray arrayWithCapacity:8];
1757 pkgCache::DepIterator start;
1758 pkgCache::DepIterator end;
1759 dep.GlobOr(start, end); // ++dep
1762 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1764 // yes, seriously. (wtf?)
1772 + (NSArray *) _attributeKeys {
1773 return [NSArray arrayWithObjects:
1779 - (NSArray *) attributeKeys {
1780 return [[self class] _attributeKeys];
1783 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1784 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1787 - (NSString *) relationship {
1788 return relationship_;
1791 - (NSArray *) clauses {
1795 - (void) addClause:(CydiaClause *)clause {
1796 [clauses_ addObject:clause];
1801 /* Package Class {{{ */
1802 struct ParsedPackage {
1806 CYString architecture_;
1809 CYString depiction_;
1819 @interface Package : NSObject {
1822 uint32_t essential_ : 1;
1823 uint32_t obsolete_ : 1;
1824 uint32_t ignored_ : 1;
1825 uint32_t pooled_ : 1;
1831 _transient Database *database_;
1833 pkgCache::VerIterator version_;
1834 pkgCache::PkgIterator iterator_;
1835 pkgCache::VerFileIterator file_;
1841 CYString installed_;
1843 const char *section_;
1844 _transient NSString *section$_;
1848 PackageValue *metadata_;
1849 ParsedPackage *parsed_;
1851 _H<NSMutableArray> tags_;
1854 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1855 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1857 - (pkgCache::PkgIterator) iterator;
1860 - (NSString *) section;
1861 - (NSString *) simpleSection;
1863 - (NSString *) longSection;
1864 - (NSString *) shortSection;
1868 - (MIMEAddress *) maintainer;
1870 - (NSString *) longDescription;
1871 - (NSString *) shortDescription;
1874 - (PackageValue *) metadata;
1877 - (bool) subscribed;
1878 - (bool) setSubscribed:(bool)subscribed;
1882 - (NSString *) latest;
1883 - (NSString *) installed;
1884 - (BOOL) uninstalled;
1887 - (BOOL) upgradableAndEssential:(BOOL)essential;
1890 - (BOOL) unfiltered;
1894 - (BOOL) halfConfigured;
1895 - (BOOL) halfInstalled;
1897 - (NSString *) mode;
1900 - (NSString *) name;
1902 - (NSString *) homepage;
1903 - (NSString *) depiction;
1904 - (MIMEAddress *) author;
1906 - (NSString *) support;
1908 - (NSArray *) files;
1909 - (NSArray *) warnings;
1910 - (NSArray *) applications;
1912 - (Source *) source;
1915 - (BOOL) matches:(NSArray *)query;
1917 - (bool) hasSupportingRole;
1918 - (BOOL) hasTag:(NSString *)tag;
1919 - (NSString *) primaryPurpose;
1920 - (NSArray *) purposes;
1921 - (bool) isCommercial;
1923 - (void) setIndex:(size_t)index;
1925 - (CYString &) cyname;
1927 - (uint32_t) compareBySection:(NSArray *)sections;
1932 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1933 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1934 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1935 - (bool) isVisibleInSection:(NSString *)section;
1936 - (bool) isVisibleInSource:(Source *)source;
1940 uint32_t PackageChangesRadix(Package *self, void *) {
1945 uint32_t timestamp : 30;
1946 uint32_t ignored : 1;
1947 uint32_t upgradable : 1;
1951 bool upgradable([self upgradableAndEssential:YES]);
1952 value.bits.upgradable = upgradable ? 1 : 0;
1955 value.bits.timestamp = 0;
1956 value.bits.ignored = [self ignored] ? 0 : 1;
1957 value.bits.upgradable = 1;
1959 value.bits.timestamp = [self seen] >> 2;
1960 value.bits.ignored = 0;
1961 value.bits.upgradable = 0;
1964 return _not(uint32_t) - value.key;
1967 uint32_t PackagePrefixRadix(Package *self, void *context) {
1968 size_t offset(reinterpret_cast<size_t>(context));
1969 CYString &name([self cyname]);
1971 size_t size(name.size());
1974 char *text(name.data());
1977 if (!isdigit(text[0]))
1981 while (size != digits && isdigit(text[digits]))
1989 if (offset == 0 && zeros != 0) {
1990 memset(data, '0', zeros);
1991 memcpy(data + zeros, text, 4 - zeros);
1993 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1994 if (size <= offset - zeros)
1997 text += offset - zeros;
1998 size -= offset - zeros;
2001 memcpy(data, text, 4);
2003 memcpy(data, text, size);
2004 memset(data + size, 0, 4 - size);
2007 for (size_t i(0); i != 4; ++i)
2008 if (isalpha(data[i]))
2016 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2018 /* XXX: ntohl may be more honest */
2019 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2022 CYString &(*PackageName)(Package *self, SEL sel);
2024 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2025 _profile(PackageNameCompare)
2026 CYString &lhi(PackageName(lhs, @selector(cyname)));
2027 CYString &rhi(PackageName(rhs, @selector(cyname)));
2028 CFStringRef lhn(lhi), rhn(rhi);
2031 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2032 else if (rhn == NULL)
2033 return NSOrderedDescending;
2035 _profile(PackageNameCompare$NumbersLast)
2036 if (!lhi.empty() && !rhi.empty()) {
2037 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2038 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2039 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2040 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2041 return lha ? NSOrderedAscending : NSOrderedDescending;
2045 CFIndex length = CFStringGetLength(lhn);
2047 _profile(PackageNameCompare$Compare)
2048 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2053 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2054 return PackageNameCompare(*lhs, *rhs, context);
2057 struct PackageNameOrdering :
2058 std::binary_function<Package *, Package *, bool>
2060 _finline bool operator ()(Package *lhs, Package *rhs) const {
2061 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2065 @implementation Package
2067 - (NSString *) description {
2068 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2073 apr_pool_destroy(pool_);
2074 if (parsed_ != NULL)
2079 + (NSString *) webScriptNameForSelector:(SEL)selector {
2081 else if (selector == @selector(clear))
2083 else if (selector == @selector(getField:))
2085 else if (selector == @selector(hasTag:))
2087 else if (selector == @selector(install))
2089 else if (selector == @selector(remove))
2095 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2096 return [self webScriptNameForSelector:selector] == nil;
2099 + (NSArray *) _attributeKeys {
2100 return [NSArray arrayWithObjects:
2121 @"shortDescription",
2134 - (NSArray *) attributeKeys {
2135 return [[self class] _attributeKeys];
2138 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2139 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2142 - (NSArray *) relations {
2143 @synchronized (database_) {
2144 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2145 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2146 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2150 - (NSString *) architecture {
2152 @synchronized (database_) {
2153 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2156 - (NSString *) getField:(NSString *)name {
2157 @synchronized (database_) {
2158 if ([database_ era] != era_ || file_.end())
2161 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2163 const char *start, *end;
2164 if (!parser.Find([name UTF8String], start, end))
2165 return (NSString *) [NSNull null];
2167 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2171 if (parsed_ != NULL)
2173 @synchronized (database_) {
2174 if ([database_ era] != era_ || file_.end())
2177 ParsedPackage *parsed(new ParsedPackage);
2180 _profile(Package$parse)
2181 pkgRecords::Parser *parser;
2183 _profile(Package$parse$Lookup)
2184 parser = &[database_ records]->Lookup(file_);
2189 _profile(Package$parse$Find)
2194 {"architecture", &parsed->architecture_},
2195 {"icon", &parsed->icon_},
2196 {"depiction", &parsed->depiction_},
2197 {"homepage", &parsed->homepage_},
2198 {"website", &website},
2199 {"bugs", &parsed->bugs_},
2200 {"support", &parsed->support_},
2201 {"sponsor", &parsed->sponsor_},
2202 {"author", &parsed->author_},
2203 {"md5sum", &parsed->md5sum_},
2206 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2207 const char *start, *end;
2209 if (parser->Find(names[i].name_, start, end)) {
2210 CYString &value(*names[i].value_);
2211 _profile(Package$parse$Value)
2212 value.set(pool_, start, end - start);
2218 _profile(Package$parse$Tagline)
2219 const char *start, *end;
2220 if (parser->ShortDesc(start, end)) {
2221 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2224 while (stop != start && stop[-1] == '\r')
2226 parsed->tagline_.set(pool_, start, stop - start);
2230 _profile(Package$parse$Retain)
2231 if (parsed->homepage_.empty())
2232 parsed->homepage_ = website;
2233 if (parsed->homepage_ == parsed->depiction_)
2234 parsed->homepage_.clear();
2239 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2240 if ((self = [super init]) != nil) {
2241 _profile(Package$initWithVersion)
2243 apr_pool_create(&pool_, NULL);
2249 database_ = database;
2250 era_ = [database era];
2254 pkgCache::PkgIterator iterator(version.ParentPkg());
2255 iterator_ = iterator;
2257 _profile(Package$initWithVersion$Version)
2258 if (!version_.end())
2259 file_ = version_.FileList();
2261 pkgCache &cache([database_ cache]);
2262 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2266 _profile(Package$initWithVersion$Cache)
2267 name_.set(NULL, iterator.Display());
2269 latest_.set(NULL, StripVersion_(version_.VerStr()));
2271 pkgCache::VerIterator current(iterator.CurrentVer());
2273 installed_.set(NULL, StripVersion_(current.VerStr()));
2276 _profile(Package$initWithVersion$Tags)
2277 pkgCache::TagIterator tag(iterator.TagList());
2279 tags_ = [NSMutableArray arrayWithCapacity:8];
2281 const char *name(tag.Name());
2282 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2284 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2285 if (strcmp(name + 6, "enduser") == 0)
2287 else if (strcmp(name + 6, "hacker") == 0)
2289 else if (strcmp(name + 6, "developer") == 0)
2291 else if (strcmp(name + 6, "cydia") == 0)
2297 if (strncmp(name, "cydia::", 7) == 0) {
2298 if (strcmp(name + 7, "essential") == 0)
2300 else if (strcmp(name + 7, "obsolete") == 0)
2305 } while (!tag.end());
2309 _profile(Package$initWithVersion$Metadata)
2310 const char *mixed(iterator.Name());
2311 size_t size(strlen(mixed));
2312 char lower[size + 1];
2314 for (size_t i(0); i != size; ++i)
2315 lower[i] = mixed[i] | 0x20;
2318 PackageValue *metadata(PackageFind(lower, size));
2319 metadata_ = metadata;
2321 id_.set(NULL, metadata->name_, size);
2323 const char *latest(version_.VerStr());
2324 size_t length(strlen(latest));
2326 uint16_t vhash(hashlittle(latest, length));
2328 size_t capped(std::min<size_t>(8, length));
2329 latest = latest + length - capped;
2331 if (metadata->first_ == 0)
2332 metadata->first_ = now_;
2334 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2335 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2336 metadata->vhash_ = vhash;
2337 metadata->last_ = now_;
2338 } else if (metadata->last_ == 0)
2339 metadata->last_ = metadata->first_;
2342 _profile(Package$initWithVersion$Section)
2343 section_ = iterator.Section();
2346 _profile(Package$initWithVersion$Flags)
2347 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2348 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2353 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2354 pkgCache::VerIterator version;
2356 _profile(Package$packageWithIterator$GetCandidateVer)
2357 version = [database policy]->GetCandidateVer(iterator);
2365 _profile(Package$packageWithIterator$Allocate)
2366 package = [Package allocWithZone:zone];
2369 _profile(Package$packageWithIterator$Initialize)
2371 initWithVersion:version
2378 _profile(Package$packageWithIterator$Autorelease)
2379 package = [package autorelease];
2385 - (pkgCache::PkgIterator) iterator {
2389 - (NSString *) section {
2390 if (section$_ == nil) {
2391 if (section_ == NULL)
2394 _profile(Package$section$mappedSectionForPointer)
2395 section$_ = [database_ mappedSectionForPointer:section_];
2400 - (NSString *) simpleSection {
2401 if (NSString *section = [self section])
2402 return Simplify(section);
2407 - (NSString *) longSection {
2408 return LocalizeSection([self section]);
2411 - (NSString *) shortSection {
2412 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2415 - (NSString *) uri {
2418 pkgIndexFile *index;
2419 pkgCache::PkgFileIterator file(file_.File());
2420 if (![database_ list].FindIndex(file, index))
2422 return [NSString stringWithUTF8String:iterator_->Path];
2423 //return [NSString stringWithUTF8String:file.Site()];
2424 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2428 - (MIMEAddress *) maintainer {
2429 @synchronized (database_) {
2430 if ([database_ era] != era_ || file_.end())
2433 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2434 const std::string &maintainer(parser->Maintainer());
2435 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2438 - (NSString *) md5sum {
2439 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2443 @synchronized (database_) {
2444 if ([database_ era] != era_ || version_.end())
2447 return version_->InstalledSize;
2450 - (NSString *) longDescription {
2451 @synchronized (database_) {
2452 if ([database_ era] != era_ || file_.end())
2455 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2456 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2458 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2459 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2460 if ([lines count] < 2)
2463 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2464 for (size_t i(1), e([lines count]); i != e; ++i) {
2465 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2466 [trimmed addObject:trim];
2469 return [trimmed componentsJoinedByString:@"\n"];
2472 - (NSString *) shortDescription {
2473 if (parsed_ != NULL)
2474 return static_cast<NSString *>(parsed_->tagline_);
2476 @synchronized (database_) {
2477 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2479 const char *start, *end;
2480 if (!parser.ShortDesc(start, end))
2483 if (end - start > 200)
2487 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2490 while (end != start && end[-1] == '\r')
2494 return [(id) CYStringCreate(start, end - start) autorelease];
2498 _profile(Package$index)
2499 CFStringRef name((CFStringRef) [self name]);
2500 if (CFStringGetLength(name) == 0)
2502 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2503 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2505 return toupper(character);
2509 - (PackageValue *) metadata {
2514 PackageValue *metadata([self metadata]);
2515 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2518 - (bool) subscribed {
2519 return [self metadata]->subscribed_;
2522 - (bool) setSubscribed:(bool)subscribed {
2523 PackageValue *metadata([self metadata]);
2524 if (metadata->subscribed_ == subscribed)
2526 metadata->subscribed_ = subscribed;
2534 - (NSString *) latest {
2538 - (NSString *) installed {
2542 - (BOOL) uninstalled {
2543 return installed_.empty();
2547 return !version_.end();
2550 - (BOOL) upgradableAndEssential:(BOOL)essential {
2551 _profile(Package$upgradableAndEssential)
2552 pkgCache::VerIterator current(iterator_.CurrentVer());
2554 return essential && essential_;
2556 return !version_.end() && version_ != current;
2560 - (BOOL) essential {
2565 return [database_ cache][iterator_].InstBroken();
2568 - (BOOL) unfiltered {
2569 _profile(Package$unfiltered$obsolete)
2570 if (_unlikely(obsolete_))
2574 _profile(Package$unfiltered$hasSupportingRole)
2575 if (_unlikely(![self hasSupportingRole]))
2583 if (![self unfiltered])
2588 _profile(Package$visible$section)
2589 section = [self section];
2592 _profile(Package$visible$isSectionVisible)
2593 if (!isSectionVisible(section))
2601 unsigned char current(iterator_->CurrentState);
2602 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2605 - (BOOL) halfConfigured {
2606 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2609 - (BOOL) halfInstalled {
2610 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2614 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2615 return state.Mode != pkgDepCache::ModeKeep;
2618 - (NSString *) mode {
2619 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2621 switch (state.Mode) {
2622 case pkgDepCache::ModeDelete:
2623 if ((state.iFlags & pkgDepCache::Purge) != 0)
2627 case pkgDepCache::ModeKeep:
2628 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2629 return @"REINSTALL";
2630 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2634 case pkgDepCache::ModeInstall:
2635 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2636 return @"REINSTALL";
2637 else*/ switch (state.Status) {
2639 return @"DOWNGRADE";
2645 return @"NEW_INSTALL";
2656 - (NSString *) name {
2657 return name_.empty() ? id_ : name_;
2660 - (UIImage *) icon {
2661 NSString *section = [self simpleSection];
2664 if (parsed_ != NULL)
2665 if (NSString *href = parsed_->icon_)
2666 if ([href hasPrefix:@"file:///"])
2667 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2668 if (icon == nil) if (section != nil)
2669 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2670 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2671 if ([dicon hasPrefix:@"file:///"])
2672 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2674 icon = [UIImage applicationImageNamed:@"unknown.png"];
2678 - (NSString *) homepage {
2679 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2682 - (NSString *) depiction {
2683 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2686 - (MIMEAddress *) sponsor {
2687 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2690 - (MIMEAddress *) author {
2691 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2694 - (NSString *) support {
2695 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2698 - (NSArray *) files {
2699 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2700 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2703 fin.open([path UTF8String]);
2708 while (std::getline(fin, line))
2709 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2714 - (NSString *) state {
2715 @synchronized (database_) {
2716 if ([database_ era] != era_ || file_.end())
2719 switch (iterator_->CurrentState) {
2720 case pkgCache::State::NotInstalled:
2721 return @"NotInstalled";
2722 case pkgCache::State::UnPacked:
2724 case pkgCache::State::HalfConfigured:
2725 return @"HalfConfigured";
2726 case pkgCache::State::HalfInstalled:
2727 return @"HalfInstalled";
2728 case pkgCache::State::ConfigFiles:
2729 return @"ConfigFiles";
2730 case pkgCache::State::Installed:
2731 return @"Installed";
2732 case pkgCache::State::TriggersAwaited:
2733 return @"TriggersAwaited";
2734 case pkgCache::State::TriggersPending:
2735 return @"TriggersPending";
2738 return (NSString *) [NSNull null];
2741 - (NSString *) selection {
2742 @synchronized (database_) {
2743 if ([database_ era] != era_ || file_.end())
2746 switch (iterator_->SelectedState) {
2747 case pkgCache::State::Unknown:
2749 case pkgCache::State::Install:
2751 case pkgCache::State::Hold:
2753 case pkgCache::State::DeInstall:
2754 return @"DeInstall";
2755 case pkgCache::State::Purge:
2759 return (NSString *) [NSNull null];
2762 - (NSArray *) warnings {
2763 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2764 const char *name(iterator_.Name());
2766 size_t length(strlen(name));
2767 if (length < 2) invalid:
2768 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2769 else for (size_t i(0); i != length; ++i)
2771 /* XXX: technically this is not allowed */
2772 (name[i] < 'A' || name[i] > 'Z') &&
2773 (name[i] < 'a' || name[i] > 'z') &&
2774 (name[i] < '0' || name[i] > '9') &&
2775 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2778 if (strcmp(name, "cydia") != 0) {
2781 bool _private = false;
2784 bool repository = [[self section] isEqualToString:@"Repositories"];
2786 if (NSArray *files = [self files])
2787 for (NSString *file in files)
2788 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2790 else if (!user && [file isEqualToString:@"/User"])
2792 else if (!_private && [file isEqualToString:@"/private"])
2794 else if (!stash && [file isEqualToString:@"/var/stash"])
2797 /* XXX: this is not sensitive enough. only some folders are valid. */
2798 if (cydia && !repository)
2799 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2801 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2803 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2805 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2808 return [warnings count] == 0 ? nil : warnings;
2811 - (NSArray *) applications {
2812 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2814 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2816 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2817 if (NSArray *files = [self files])
2818 for (NSString *file in files)
2819 if (application_r(file)) {
2820 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2821 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2822 if ([id isEqualToString:me])
2825 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2827 display = application_r[1];
2829 NSString *bundle([file stringByDeletingLastPathComponent]);
2830 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2831 if (icon == nil || [icon length] == 0)
2833 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2835 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2836 [applications addObject:application];
2838 [application addObject:id];
2839 [application addObject:display];
2840 [application addObject:url];
2843 return [applications count] == 0 ? nil : applications;
2846 - (Source *) source {
2847 if (source_ == nil) {
2848 @synchronized (database_) {
2849 if ([database_ era] != era_ || file_.end())
2850 source_ = (Source *) [NSNull null];
2852 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2856 return source_ == (Source *) [NSNull null] ? nil : source_;
2863 - (BOOL) matches:(NSArray *)query {
2864 if (query == nil || [query count] == 0)
2873 string = [self name];
2874 length = [string length];
2876 for (NSString *term in query) {
2877 range = [string rangeOfString:term options:MatchCompareOptions_];
2878 if (range.location != NSNotFound)
2879 rank_ -= 6 * 1000000 / length;
2884 length = [string length];
2886 for (NSString *term in query) {
2887 range = [string rangeOfString:term options:MatchCompareOptions_];
2888 if (range.location != NSNotFound)
2889 rank_ -= 6 * 1000000 / length;
2893 string = [self shortDescription];
2894 length = [string length];
2895 NSUInteger stop(std::min<NSUInteger>(length, 200));
2897 for (NSString *term in query) {
2898 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2899 if (range.location != NSNotFound)
2900 rank_ -= 2 * 100000;
2906 - (bool) hasSupportingRole {
2911 if ([Role_ isEqualToString:@"User"])
2915 if ([Role_ isEqualToString:@"Hacker"])
2919 if ([Role_ isEqualToString:@"Developer"])
2924 - (NSArray *) tags {
2928 - (BOOL) hasTag:(NSString *)tag {
2929 return tags_ == nil ? NO : [tags_ containsObject:tag];
2932 - (NSString *) primaryPurpose {
2933 for (NSString *tag in (NSArray *) tags_)
2934 if ([tag hasPrefix:@"purpose::"])
2935 return [tag substringFromIndex:9];
2939 - (NSArray *) purposes {
2940 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2941 for (NSString *tag in (NSArray *) tags_)
2942 if ([tag hasPrefix:@"purpose::"])
2943 [purposes addObject:[tag substringFromIndex:9]];
2944 return [purposes count] == 0 ? nil : purposes;
2947 - (bool) isCommercial {
2948 return [self hasTag:@"cydia::commercial"];
2951 - (void) setIndex:(size_t)index {
2952 if (metadata_->index_ != index)
2953 metadata_->index_ = index;
2956 - (CYString &) cyname {
2957 return name_.empty() ? id_ : name_;
2960 - (uint32_t) compareBySection:(NSArray *)sections {
2961 NSString *section([self section]);
2962 for (size_t i(0), e([sections count]); i != e; ++i) {
2963 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2967 return _not(uint32_t);
2971 @synchronized (database_) {
2972 pkgProblemResolver *resolver = [database_ resolver];
2973 resolver->Clear(iterator_);
2975 pkgCacheFile &cache([database_ cache]);
2976 cache->SetReInstall(iterator_, false);
2977 cache->MarkKeep(iterator_, false);
2981 @synchronized (database_) {
2982 pkgProblemResolver *resolver = [database_ resolver];
2983 resolver->Clear(iterator_);
2984 resolver->Protect(iterator_);
2986 pkgCacheFile &cache([database_ cache]);
2987 cache->SetReInstall(iterator_, false);
2988 cache->MarkInstall(iterator_, false);
2990 pkgDepCache::StateCache &state((*cache)[iterator_]);
2991 if (!state.Install())
2992 cache->SetReInstall(iterator_, true);
2996 @synchronized (database_) {
2997 pkgProblemResolver *resolver = [database_ resolver];
2998 resolver->Clear(iterator_);
2999 resolver->Remove(iterator_);
3000 resolver->Protect(iterator_);
3002 pkgCacheFile &cache([database_ cache]);
3003 cache->SetReInstall(iterator_, false);
3004 cache->MarkDelete(iterator_, true);
3007 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3008 _profile(Package$isUnfilteredAndSearchedForBy)
3011 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3012 value &= [self unfiltered];
3015 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3016 value &= [self matches:query];
3023 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3024 if ([search length] == 0)
3027 _profile(Package$isUnfilteredAndSelectedForBy)
3030 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3031 value &= [self unfiltered];
3034 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3035 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3042 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3043 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3046 - (bool) isVisibleInSection:(NSString *)name {
3047 NSString *section([self section]);
3051 section == nil && [name length] == 0 ||
3052 [name isEqualToString:section]
3053 ) && [self visible];
3056 - (bool) isVisibleInSource:(Source *)source {
3057 return [self source] == source && [self visible];
3062 /* Section Class {{{ */
3063 @interface Section : NSObject {
3068 _H<NSString> localized_;
3071 - (NSComparisonResult) compareByLocalized:(Section *)section;
3072 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3073 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3074 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3075 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3076 - (NSString *) name;
3083 - (void) addToCount;
3085 - (void) setCount:(size_t)count;
3086 - (NSString *) localized;
3090 @implementation Section
3092 - (NSComparisonResult) compareByLocalized:(Section *)section {
3093 NSString *lhs(localized_);
3094 NSString *rhs([section localized]);
3096 /*if ([lhs length] != 0 && [rhs length] != 0) {
3097 unichar lhc = [lhs characterAtIndex:0];
3098 unichar rhc = [rhs characterAtIndex:0];
3100 if (isalpha(lhc) && !isalpha(rhc))
3101 return NSOrderedAscending;
3102 else if (!isalpha(lhc) && isalpha(rhc))
3103 return NSOrderedDescending;
3106 return [lhs compare:rhs options:LaxCompareOptions_];
3109 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3110 if ((self = [self initWithName:name localize:NO]) != nil) {
3111 if (localized != nil)
3112 localized_ = localized;
3116 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3117 return [self initWithName:name row:0 localize:localize];
3120 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3121 if ((self = [super init]) != nil) {
3126 localized_ = LocalizeSection(name_);
3130 /* XXX: localize the index thingees */
3131 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3132 if ((self = [super init]) != nil) {
3133 name_ = [NSString stringWithCharacters:&index length:1];
3139 - (NSString *) name {
3159 - (void) addToCount {
3163 - (void) setCount:(size_t)count {
3167 - (NSString *) localized {
3174 class CydiaLogCleaner :
3175 public pkgArchiveCleaner
3178 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3183 /* Database Implementation {{{ */
3184 @implementation Database
3186 + (Database *) sharedInstance {
3187 static _H<Database> instance;
3188 if (instance == nil)
3189 instance = [[[Database alloc] init] autorelease];
3197 - (void) releasePackages {
3198 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3199 CFArrayRemoveAllValues(packages_);
3203 // XXX: actually implement this thing
3205 [self releasePackages];
3206 apr_pool_destroy(pool_);
3207 NSRecycleZone(zone_);
3211 - (void) _readCydia:(NSNumber *)fd {
3212 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3213 std::istream is(&ib);
3216 static Pcre finish_r("^finish:([^:]*)$");
3218 while (std::getline(is, line)) {
3219 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3221 const char *data(line.c_str());
3222 size_t size = line.size();
3223 lprintf("C:%s\n", data);
3225 if (finish_r(data, size)) {
3226 NSString *finish = finish_r[1];
3227 int index = [Finishes_ indexOfObject:finish];
3228 if (index != INT_MAX && index > Finish_)
3238 - (void) _readStatus:(NSNumber *)fd {
3239 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3240 std::istream is(&ib);
3243 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3244 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3246 while (std::getline(is, line)) {
3247 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3249 const char *data(line.c_str());
3250 size_t size(line.size());
3251 lprintf("S:%s\n", data);
3253 if (conffile_r(data, size)) {
3254 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3255 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3256 } else if (strncmp(data, "status: ", 8) == 0) {
3257 // status: <package>: {unpacked,half-configured,installed}
3258 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3259 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3260 } else if (strncmp(data, "processing: ", 12) == 0) {
3261 // processing: configure: config-test
3262 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3263 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3264 } else if (pmstatus_r(data, size)) {
3265 std::string type([pmstatus_r[1] UTF8String]);
3267 NSString *package = pmstatus_r[2];
3268 if ([package isEqualToString:@"dpkg-exec"])
3271 float percent([pmstatus_r[3] floatValue]);
3272 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3274 NSString *string = pmstatus_r[4];
3276 if (type == "pmerror") {
3277 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3278 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3279 } else if (type == "pmstatus") {
3280 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3281 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3282 } else if (type == "pmconffile")
3283 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3285 lprintf("E:unknown pmstatus\n");
3287 lprintf("E:unknown status\n");
3295 - (void) _readOutput:(NSNumber *)fd {
3296 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3297 std::istream is(&ib);
3300 while (std::getline(is, line)) {
3301 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3303 lprintf("O:%s\n", line.c_str());
3305 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3306 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3318 - (Package *) packageWithName:(NSString *)name {
3321 @synchronized (self) {
3322 if (static_cast<pkgDepCache *>(cache_) == NULL)
3324 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3325 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3329 if ((self = [super init]) != nil) {
3336 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3337 apr_pool_create(&pool_, NULL);
3339 size_t capacity(MetaFile_->active_);
3345 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3346 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3350 _assert(pipe(fds) != -1);
3353 _config->Set("APT::Keep-Fds::", cydiafd_);
3354 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3357 detachNewThreadSelector:@selector(_readCydia:)
3359 withObject:[NSNumber numberWithInt:fds[0]]
3362 _assert(pipe(fds) != -1);
3366 detachNewThreadSelector:@selector(_readStatus:)
3368 withObject:[NSNumber numberWithInt:fds[0]]
3371 _assert(pipe(fds) != -1);
3372 _assert(dup2(fds[0], 0) != -1);
3373 _assert(close(fds[0]) != -1);
3375 input_ = fdopen(fds[1], "a");
3377 _assert(pipe(fds) != -1);
3378 _assert(dup2(fds[1], 1) != -1);
3379 _assert(close(fds[1]) != -1);
3382 detachNewThreadSelector:@selector(_readOutput:)
3384 withObject:[NSNumber numberWithInt:fds[0]]
3389 - (pkgCacheFile &) cache {
3393 - (pkgDepCache::Policy *) policy {
3397 - (pkgRecords *) records {
3401 - (pkgProblemResolver *) resolver {
3405 - (pkgAcquire &) fetcher {
3409 - (pkgSourceList &) list {
3413 - (NSArray *) packages {
3414 return (NSArray *) packages_;
3417 - (NSArray *) sources {
3421 - (Source *) sourceWithKey:(NSString *)key {
3422 for (Source *source in [self sources]) {
3423 if ([[source key] isEqualToString:key])
3428 - (bool) popErrorWithTitle:(NSString *)title {
3431 while (!_error->empty()) {
3433 bool warning(!_error->PopMessage(error));
3438 size_t size(error.size());
3439 if (size == 0 || error[size - 1] != '\n')
3441 error.resize(size - 1);
3444 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3446 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3447 if (warning && no_pubkey(error.c_str()))
3450 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3456 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3457 return [self popErrorWithTitle:title] || !success;
3460 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3461 @synchronized (self) {
3464 [self releasePackages];
3467 [sourceList_ removeAllObjects];
3487 apr_pool_clear(pool_);
3489 NSRecycleZone(zone_);
3490 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3492 int chk(creat("/tmp/cydia.chk", 0644));
3496 if (invocation != nil)
3497 [invocation invoke];
3499 NSString *title(UCLocalize("DATABASE"));
3502 OpProgress progress;
3503 while (!cache_.Open(progress, true)) { pop:
3505 bool warning(!_error->PopMessage(error));
3506 lprintf("cache_.Open():[%s]\n", error.c_str());
3508 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3509 [delegate_ repairWithSelector:@selector(configure)];
3510 else if (error == "The package lists or status file could not be parsed or opened.")
3511 [delegate_ repairWithSelector:@selector(update)];
3512 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3513 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3514 // else if (error == "Malformed Status line")
3515 // else if (error == "The list of sources could not be read.")
3517 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3527 unlink("/tmp/cydia.chk");
3529 now_ = [[NSDate date] timeIntervalSince1970];
3531 policy_ = new pkgDepCache::Policy();
3532 records_ = new pkgRecords(cache_);
3533 resolver_ = new pkgProblemResolver(cache_);
3534 fetcher_ = new pkgAcquire(&status_);
3537 list_ = new pkgSourceList();
3538 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3541 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3542 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3546 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3549 if (cache_->BrokenCount() != 0) {
3550 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3553 if (cache_->BrokenCount() != 0) {
3554 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3558 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3562 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3563 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3564 [sourceList_ addObject:object];
3566 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3567 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3568 // XXX: this could be more intelligent
3569 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3570 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3572 sourceMap_[cached->ID] = object;
3577 /*std::vector<Package *> packages;
3578 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3583 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3584 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3585 //packages.push_back(package);
3586 CFArrayAppendValue(packages_, CFRetain(package));
3590 /*if (packages.empty())
3591 packages_ = [[NSArray alloc] init];
3593 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3596 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3597 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3598 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3606 /*if (!packages.empty())
3607 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3608 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3610 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3612 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3614 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3618 size_t count(CFArrayGetCount(packages_));
3619 MetaFile_->active_ = count;
3621 for (size_t index(0); index != count; ++index)
3622 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3629 @synchronized (self) {
3631 resolver_ = new pkgProblemResolver(cache_);
3633 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3634 if (!cache_[iterator].Keep())
3635 cache_->MarkKeep(iterator, false);
3636 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3637 cache_->SetReInstall(iterator, false);
3640 - (void) configure {
3641 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3643 system([dpkg UTF8String]);
3648 // XXX: I don't remember this condition
3653 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3655 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3657 if ([self popErrorWithTitle:title])
3661 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3663 CydiaLogCleaner cleaner;
3664 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3671 fetcher_->Shutdown();
3673 pkgRecords records(cache_);
3675 lock_ = new FileFd();
3676 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3678 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3680 if ([self popErrorWithTitle:title])
3684 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3687 manager_ = (_system->CreatePM(cache_));
3688 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3695 bool substrate(RestartSubstrate_);
3696 RestartSubstrate_ = false;
3698 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3700 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3702 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3704 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3705 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3708 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3710 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3712 [self popErrorWithTitle:title];
3716 bool failed = false;
3717 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3718 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3720 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3726 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3734 RestartSubstrate_ = true;
3737 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3739 if (_error->PendingError()) {
3744 if (result == pkgPackageManager::Failed) {
3749 if (result != pkgPackageManager::Completed) {
3754 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3756 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3758 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3759 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3762 if (![before isEqualToArray:after])
3767 NSString *title(UCLocalize("UPGRADE"));
3768 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3774 [self updateWithStatus:status_];
3777 - (void) updateWithStatus:(Status &)status {
3778 NSString *title(UCLocalize("REFRESHING_DATA"));
3781 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3785 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3786 if ([self popErrorWithTitle:title])
3789 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3791 bool success(ListUpdate(status, list, PulseInterval_));
3792 if (status.WasCancelled())
3795 [self popErrorWithTitle:title forOperation:success];
3796 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3800 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3803 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3804 delegate_ = delegate;
3807 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3808 progress_ = delegate;
3809 status_.setDelegate(delegate);
3812 - (NSObject<ProgressDelegate> *) progressDelegate {
3816 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3817 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3818 return i == sourceMap_.end() ? nil : i->second;
3821 - (NSString *) mappedSectionForPointer:(const char *)section {
3822 _H<NSString> *mapped;
3824 _profile(Database$mappedSectionForPointer$Cache)
3825 mapped = §ions_[section];
3828 if (*mapped == NULL) {
3829 size_t length(strlen(section));
3830 char spaced[length + 1];
3832 _profile(Database$mappedSectionForPointer$Replace)
3833 for (size_t index(0); index != length; ++index)
3834 spaced[index] = section[index] == '_' ? ' ' : section[index];
3835 spaced[length] = '\0';
3840 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3841 string = [NSString stringWithUTF8String:spaced];
3844 _profile(Database$mappedSectionForPointer$Map)
3845 string = [SectionMap_ objectForKey:string] ?: string;
3855 static _H<NSMutableSet> Diversions_;
3857 @interface Diversion : NSObject {
3860 _H<NSString> format_;
3865 @implementation Diversion
3867 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3868 if ((self = [super init]) != nil) {
3869 pattern_ = [from UTF8String];
3875 - (NSString *) divert:(NSString *)url {
3876 return !pattern_(url) ? nil : pattern_->*format_;
3879 + (NSURL *) divertURL:(NSURL *)url {
3881 NSString *href([url absoluteString]);
3883 for (Diversion *diversion in (id) Diversions_)
3884 if (NSString *diverted = [diversion divert:href]) {
3886 NSLog(@"div: %@", diverted);
3888 url = [NSURL URLWithString:diverted];
3895 - (NSString *) key {
3899 - (NSUInteger) hash {
3903 - (BOOL) isEqual:(Diversion *)object {
3904 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3909 @interface CydiaObject : NSObject {
3910 _H<IndirectDelegate> indirect_;
3911 _transient id delegate_;
3914 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3918 @interface CydiaWebViewController : CyteWebViewController {
3919 _H<CydiaObject> cydia_;
3922 + (void) addDiversion:(Diversion *)diversion;
3926 /* Web Scripting {{{ */
3927 @implementation CydiaObject
3929 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3930 if ((self = [super init]) != nil) {
3931 indirect_ = indirect;
3935 - (void) setDelegate:(id)delegate {
3936 delegate_ = delegate;
3939 + (NSArray *) _attributeKeys {
3940 return [NSArray arrayWithObjects:
3957 - (NSArray *) attributeKeys {
3958 return [[self class] _attributeKeys];
3961 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3962 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3965 - (NSString *) version {
3969 - (NSString *) device {
3970 return [[UIDevice currentDevice] uniqueIdentifier];
3973 - (NSString *) firmware {
3974 return [[UIDevice currentDevice] systemVersion];
3977 - (NSString *) hostname {
3978 return [[UIDevice currentDevice] name];
3981 - (NSString *) idiom {
3982 return (id) Idiom_ ?: [NSNull null];
3985 - (NSString *) plmn {
3986 return (id) PLMN_ ?: [NSNull null];
3989 - (NSString *) bbsnum {
3990 return (id) BBSNum_ ?: [NSNull null];
3993 - (NSString *) ecid {
3994 return (id) ChipID_ ?: [NSNull null];
3997 - (NSString *) serial {
3998 return SerialNumber_;
4001 - (NSString *) role {
4002 return (id) Role_ ?: [NSNull null];
4005 - (NSString *) model {
4006 return [NSString stringWithUTF8String:Machine_];
4009 - (NSString *) token {
4010 return (id) Token_ ?: [NSNull null];
4013 + (NSString *) webScriptNameForSelector:(SEL)selector {
4015 else if (selector == @selector(addBridgedHost:))
4016 return @"addBridgedHost";
4017 else if (selector == @selector(addInsecureHost:))
4018 return @"addInsecureHost";
4019 else if (selector == @selector(addInternalRedirect::))
4020 return @"addInternalRedirect";
4021 else if (selector == @selector(addPipelinedHost:scheme:))
4022 return @"addPipelinedHost";
4023 else if (selector == @selector(addSource:::))
4024 return @"addSource";
4025 else if (selector == @selector(addTokenHost:))
4026 return @"addTokenHost";
4027 else if (selector == @selector(addTrivialSource:))
4028 return @"addTrivialSource";
4029 else if (selector == @selector(close))
4031 else if (selector == @selector(du:))
4033 else if (selector == @selector(stringWithFormat:arguments:))
4035 else if (selector == @selector(getAllSources))
4036 return @"getAllSourcs";
4037 else if (selector == @selector(getKernelNumber:))
4038 return @"getKernelNumber";
4039 else if (selector == @selector(getKernelString:))
4040 return @"getKernelString";
4041 else if (selector == @selector(getInstalledPackages))
4042 return @"getInstalledPackages";
4043 else if (selector == @selector(getIORegistryEntry::))
4044 return @"getIORegistryEntry";
4045 else if (selector == @selector(getLocaleIdentifier))
4046 return @"getLocaleIdentifier";
4047 else if (selector == @selector(getPreferredLanguages))
4048 return @"getPreferredLanguages";
4049 else if (selector == @selector(getPackageById:))
4050 return @"getPackageById";
4051 else if (selector == @selector(getMetadataKeys))
4052 return @"getMetadataKeys";
4053 else if (selector == @selector(getMetadataValue:))
4054 return @"getMetadataValue";
4055 else if (selector == @selector(getSessionValue:))
4056 return @"getSessionValue";
4057 else if (selector == @selector(installPackages:))
4058 return @"installPackages";
4059 else if (selector == @selector(localizedStringForKey:value:table:))
4061 else if (selector == @selector(popViewController:))
4062 return @"popViewController";
4063 else if (selector == @selector(refreshSources))
4064 return @"refreshSources";
4065 else if (selector == @selector(removeButton))
4066 return @"removeButton";
4067 else if (selector == @selector(saveConfig))
4068 return @"saveConfig";
4069 else if (selector == @selector(setCydiaSource:))
4070 return @"setCydiaSource";
4071 else if (selector == @selector(setMetadataValue::))
4072 return @"setMetadataValue";
4073 else if (selector == @selector(setSessionValue::))
4074 return @"setSessionValue";
4075 else if (selector == @selector(substitutePackageNames:))
4076 return @"substitutePackageNames";
4077 else if (selector == @selector(scrollToBottom:))
4078 return @"scrollToBottom";
4079 else if (selector == @selector(setAllowsNavigationAction:))
4080 return @"setAllowsNavigationAction";
4081 else if (selector == @selector(setBadgeValue:))
4082 return @"setBadgeValue";
4083 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4084 return @"setButtonImage";
4085 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4086 return @"setButtonTitle";
4087 else if (selector == @selector(setHidesBackButton:))
4088 return @"setHidesBackButton";
4089 else if (selector == @selector(setHidesNavigationBar:))
4090 return @"setHidesNavigationBar";
4091 else if (selector == @selector(setNavigationBarStyle:))
4092 return @"setNavigationBarStyle";
4093 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4094 return @"setNavigationBarTintColor";
4095 else if (selector == @selector(setPasteboardString:))
4096 return @"setPasteboardString";
4097 else if (selector == @selector(setPasteboardURL:))
4098 return @"setPasteboardURL";
4099 else if (selector == @selector(setToken:))
4101 else if (selector == @selector(setViewportWidth:))
4102 return @"setViewportWidth";
4103 else if (selector == @selector(statfs:))
4105 else if (selector == @selector(supports:))
4107 else if (selector == @selector(unload))
4113 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4114 return [self webScriptNameForSelector:selector] == nil;
4117 - (BOOL) supports:(NSString *)feature {
4118 return [feature isEqualToString:@"window.open"];
4122 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4125 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4126 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4129 - (NSNumber *) getKernelNumber:(NSString *)name {
4130 const char *string([name UTF8String]);
4133 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4134 return (id) [NSNull null];
4136 if (size != sizeof(int))
4137 return (id) [NSNull null];
4140 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4141 return (id) [NSNull null];
4143 return [NSNumber numberWithInt:value];
4146 - (NSString *) getKernelString:(NSString *)name {
4147 const char *string([name UTF8String]);
4150 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4151 return (id) [NSNull null];
4153 char value[size + 1];
4154 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4155 return (id) [NSNull null];
4157 // XXX: just in case you request something ludicrous
4160 return [NSString stringWithCString:value];
4163 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4164 NSObject *value(CYIOGetValue([path UTF8String], entry));
4167 if ([value isKindOfClass:[NSData class]])
4168 value = CYHex((NSData *) value);
4173 - (void) _setCydiaSource:(NSString *)source {
4174 @synchronized (HostConfig_) {
4175 CydiaSource_ = source;
4176 [Metadata_ setObject:source forKey:@"CydiaSource"];
4182 - (void) setCydiaSource:(NSString *)source {
4183 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4186 - (NSString *) cydiaSource {
4187 @synchronized (HostConfig_) {
4188 return (id) CydiaSource_ ?: [NSNull null];
4192 - (NSArray *) getMetadataKeys {
4193 @synchronized (Values_) {
4194 return [Values_ allKeys];
4197 - (id) getMetadataValue:(NSString *)key {
4198 @synchronized (Values_) {
4199 return [Values_ objectForKey:key];
4202 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4203 @synchronized (Values_) {
4204 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4205 [Values_ removeObjectForKey:key];
4207 [Values_ setObject:value forKey:key];
4209 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4212 - (id) getSessionValue:(NSString *)key {
4213 @synchronized (SessionData_) {
4214 return [SessionData_ objectForKey:key];
4217 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4218 @synchronized (SessionData_) {
4219 if (value == (id) [WebUndefined undefined])
4220 [SessionData_ removeObjectForKey:key];
4222 [SessionData_ setObject:value forKey:key];
4225 - (void) addBridgedHost:(NSString *)host {
4226 @synchronized (HostConfig_) {
4227 [BridgedHosts_ addObject:host];
4230 - (void) addInsecureHost:(NSString *)host {
4231 @synchronized (HostConfig_) {
4232 [InsecureHosts_ addObject:host];
4235 - (void) addTokenHost:(NSString *)host {
4236 @synchronized (HostConfig_) {
4237 [TokenHosts_ addObject:host];
4240 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4241 @synchronized (HostConfig_) {
4242 if (scheme != (id) [WebUndefined undefined])
4243 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4245 [PipelinedHosts_ addObject:host];
4248 - (void) popViewController:(NSNumber *)value {
4249 if (value == (id) [WebUndefined undefined])
4250 value = [NSNumber numberWithBool:YES];
4251 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4254 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4255 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4257 for (NSString *section in sections)
4258 [array addObject:section];
4260 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4263 distribution, @"Distribution",
4265 nil] waitUntilDone:NO];
4268 - (void) addTrivialSource:(NSString *)href {
4269 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4272 - (void) refreshSources {
4273 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4276 - (void) saveConfig {
4277 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4280 - (NSArray *) getAllSources {
4281 return [[Database sharedInstance] sources];
4284 - (NSArray *) getInstalledPackages {
4285 Database *database([Database sharedInstance]);
4286 @synchronized (database) {
4287 NSArray *packages([database packages]);
4288 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4289 for (Package *package in packages)
4290 if (![package uninstalled])
4291 [installed addObject:package];
4295 - (Package *) getPackageById:(NSString *)id {
4296 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4300 return (Package *) [NSNull null];
4303 - (NSString *) getLocaleIdentifier {
4304 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4307 - (NSArray *) getPreferredLanguages {
4311 - (NSArray *) statfs:(NSString *)path {
4314 if (path == nil || statfs([path UTF8String], &stat) == -1)
4317 return [NSArray arrayWithObjects:
4318 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4319 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4320 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4324 - (NSNumber *) du:(NSString *)path {
4325 NSNumber *value(nil);
4328 _assert(pipe(fds) != -1);
4330 pid_t pid(ExecFork());
4332 _assert(dup2(fds[1], 1) != -1);
4333 _assert(close(fds[0]) != -1);
4334 _assert(close(fds[1]) != -1);
4335 /* XXX: this should probably not use du */
4336 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4341 _assert(close(fds[1]) != -1);
4343 if (FILE *du = fdopen(fds[0], "r")) {
4345 while (fgets(line, sizeof(line), du) != NULL) {
4346 size_t length(strlen(line));
4347 while (length != 0 && line[length - 1] == '\n')
4348 line[--length] = '\0';
4349 if (char *tab = strchr(line, '\t')) {
4351 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4356 } else _assert(close(fds[0]));
4360 if (waitpid(pid, &status, 0) == -1)
4363 else _assert(false);
4369 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4372 - (void) installPackages:(NSArray *)packages {
4373 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4376 - (NSString *) substitutePackageNames:(NSString *)message {
4377 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4378 for (size_t i(0), e([words count]); i != e; ++i) {
4379 NSString *word([words objectAtIndex:i]);
4380 if (Package *package = [[Database sharedInstance] packageWithName:word])
4381 [words replaceObjectAtIndex:i withObject:[package name]];
4384 return [words componentsJoinedByString:@" "];
4387 - (void) removeButton {
4388 [indirect_ removeButton];
4391 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4392 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4395 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4396 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4399 - (void) setBadgeValue:(id)value {
4400 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4403 - (void) setAllowsNavigationAction:(NSString *)value {
4404 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4407 - (void) setHidesBackButton:(NSString *)value {
4408 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4411 - (void) setHidesNavigationBar:(NSString *)value {
4412 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4415 - (void) setNavigationBarStyle:(NSString *)value {
4416 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4419 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4420 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4421 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4422 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4425 - (void) setPasteboardString:(NSString *)value {
4426 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4429 - (void) setPasteboardURL:(NSString *)value {
4430 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4433 - (void) _setToken:(NSString *)token {
4437 [Metadata_ removeObjectForKey:@"Token"];
4439 [Metadata_ setObject:Token_ forKey:@"Token"];
4444 - (void) setToken:(NSString *)token {
4445 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4448 - (void) scrollToBottom:(NSNumber *)animated {
4449 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4452 - (void) setViewportWidth:(float)width {
4453 [indirect_ setViewportWidthOnMainThread:width];
4456 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4457 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4458 unsigned count([arguments count]);
4460 for (unsigned i(0); i != count; ++i)
4461 values[i] = [arguments objectAtIndex:i];
4462 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4465 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4466 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4468 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4470 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4476 @interface NSURL (CydiaSecure)
4479 @implementation NSURL (CydiaSecure)
4481 - (bool) isCydiaSecure {
4482 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4485 @synchronized (HostConfig_) {
4486 if ([InsecureHosts_ containsObject:[self host]])
4495 /* Cydia Browser Controller {{{ */
4496 @implementation CydiaWebViewController
4498 - (NSURL *) navigationURL {
4499 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4502 + (void) _initialize {
4503 [super _initialize];
4505 Diversions_ = [NSMutableSet setWithCapacity:0];
4508 + (void) addDiversion:(Diversion *)diversion {
4509 [Diversions_ addObject:diversion];
4512 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4513 [super webView:view didClearWindowObject:window forFrame:frame];
4515 WebDataSource *source([frame dataSource]);
4516 NSURLResponse *response([source response]);
4517 NSURL *url([response URL]);
4518 NSString *scheme([[url scheme] lowercaseString]);
4520 bool bridged(false);
4522 @synchronized (HostConfig_) {
4523 if ([scheme isEqualToString:@"file"])
4525 else if ([scheme isEqualToString:@"https"])
4526 if ([BridgedHosts_ containsObject:[url host]])
4531 [window setValue:cydia_ forKey:@"cydia"];
4534 - (void) _setupMail:(MFMailComposeViewController *)controller {
4535 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4537 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4538 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4541 - (NSURL *) URLWithURL:(NSURL *)url {
4542 return [Diversion divertURL:url];
4545 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4546 NSURL *url([request URL]);
4547 NSString *host([url host]);
4549 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4551 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4552 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4553 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4554 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4559 @synchronized (HostConfig_) {
4560 bridged = [BridgedHosts_ containsObject:host];
4561 token = [TokenHosts_ containsObject:host];
4564 if ([url isCydiaSecure]) {
4566 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4567 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4569 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4570 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4577 - (void) setDelegate:(id)delegate {
4578 [super setDelegate:delegate];
4579 [cydia_ setDelegate:delegate];
4582 - (NSString *) applicationNameForUserAgent {
4583 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4586 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4588 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4589 if (Product_ != nil)
4590 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4596 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4597 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4603 @interface AppCacheController : CydiaWebViewController {
4608 @implementation AppCacheController
4610 - (void) didReceiveMemoryWarning {
4617 @interface NSObject (CydiaScript)
4618 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4621 @implementation NSObject (CydiaScript)
4623 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4629 @implementation NSArray (CydiaScript)
4631 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4632 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4633 for (size_t i(0), e([self count]); i != e; ++i)
4634 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4640 @implementation NSDictionary (CydiaScript)
4642 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4643 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4645 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4652 /* Confirmation Controller {{{ */
4653 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4654 if (!iterator.end())
4655 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4656 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4658 pkgCache::PkgIterator package(dep.TargetPkg());
4661 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4668 @protocol ConfirmationControllerDelegate
4669 - (void) cancelAndClear:(bool)clear;
4670 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4674 @interface ConfirmationController : CydiaWebViewController {
4675 _transient Database *database_;
4677 _H<UIAlertView> essential_;
4679 _H<NSDictionary> changes_;
4680 _H<NSMutableArray> issues_;
4681 _H<NSDictionary> sizes_;
4686 - (id) initWithDatabase:(Database *)database;
4690 @implementation ConfirmationController
4694 RestartSubstrate_ = true;
4695 [delegate_ confirmWithNavigationController:[self navigationController]];
4698 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4699 NSString *context([alert context]);
4701 if ([context isEqualToString:@"remove"]) {
4702 if (button == [alert cancelButtonIndex])
4703 [self dismissModalViewControllerAnimated:YES];
4704 else if (button == [alert firstOtherButtonIndex]) {
4708 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4709 } else if ([context isEqualToString:@"unable"]) {
4710 [self dismissModalViewControllerAnimated:YES];
4711 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4713 [super alertView:alert clickedButtonAtIndex:button];
4717 - (void) _doContinue {
4718 [delegate_ cancelAndClear:NO];
4719 [self dismissModalViewControllerAnimated:YES];
4722 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4723 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4727 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4728 [super webView:view didClearWindowObject:window forFrame:frame];
4730 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4731 (id) changes_, @"changes",
4732 (id) issues_, @"issues",
4733 (id) sizes_, @"sizes",
4735 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4738 - (id) initWithDatabase:(Database *)database {
4739 if ((self = [super init]) != nil) {
4740 database_ = database;
4742 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4743 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4744 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4745 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4746 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4750 pkgCacheFile &cache([database_ cache]);
4751 NSArray *packages([database_ packages]);
4752 pkgDepCache::Policy *policy([database_ policy]);
4754 issues_ = [NSMutableArray arrayWithCapacity:4];
4756 for (Package *package in packages) {
4757 pkgCache::PkgIterator iterator([package iterator]);
4758 NSString *name([package id]);
4760 if ([package broken]) {
4761 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4763 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4765 reasons, @"reasons",
4768 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4772 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4773 pkgCache::DepIterator start;
4774 pkgCache::DepIterator end;
4775 dep.GlobOr(start, end); // ++dep
4777 if (!cache->IsImportantDep(end))
4779 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4782 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4784 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4785 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4786 clauses, @"clauses",
4790 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4792 pkgCache::PkgIterator target(start.TargetPkg());
4793 if (target->ProvidesList != 0)
4794 reason = @"missing";
4796 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4798 reason = @"installed";
4799 installed = [NSString stringWithUTF8String:ver.VerStr()];
4800 } else if (!cache[target].CandidateVerIter(cache).end())
4801 reason = @"uninstalled";
4802 else if (target->ProvidesList == 0)
4803 reason = @"uninstallable";
4805 reason = @"virtual";
4808 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4809 [NSString stringWithUTF8String:start.CompType()], @"operator",
4810 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4813 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4814 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4815 version, @"version",
4817 installed, @"installed",
4820 // yes, seriously. (wtf?)
4828 pkgDepCache::StateCache &state(cache[iterator]);
4830 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4832 if (state.NewInstall())
4833 [installs addObject:name];
4834 // XXX: else if (state.Install())
4835 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4836 [reinstalls addObject:name];
4837 // XXX: move before previous if
4838 else if (state.Upgrade())
4839 [upgrades addObject:name];
4840 else if (state.Downgrade())
4841 [downgrades addObject:name];
4842 else if (!state.Delete())
4843 // XXX: _assert(state.Keep());
4845 else if (special_r(name))
4846 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4847 [NSNull null], @"package",
4848 [NSArray arrayWithObjects:
4849 [NSDictionary dictionaryWithObjectsAndKeys:
4850 @"Conflicts", @"relationship",
4851 [NSArray arrayWithObjects:
4852 [NSDictionary dictionaryWithObjectsAndKeys:
4854 [NSNull null], @"version",
4855 @"installed", @"reason",
4862 if ([package essential])
4864 [removes addObject:name];
4867 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4868 substrate_ |= DepSubstrate(iterator.CurrentVer());
4873 else if (Advanced_) {
4874 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4876 essential_ = [[[UIAlertView alloc]
4877 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4878 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4880 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4882 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4886 [essential_ setContext:@"remove"];
4888 essential_ = [[[UIAlertView alloc]
4889 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4890 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4892 cancelButtonTitle:UCLocalize("OKAY")
4893 otherButtonTitles:nil
4896 [essential_ setContext:@"unable"];
4899 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4900 installs, @"installs",
4901 reinstalls, @"reinstalls",
4902 upgrades, @"upgrades",
4903 downgrades, @"downgrades",
4904 removes, @"removes",
4907 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4908 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4909 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4912 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4916 - (UIBarButtonItem *) leftButton {
4917 return [[[UIBarButtonItem alloc]
4918 initWithTitle:UCLocalize("CANCEL")
4919 style:UIBarButtonItemStylePlain
4921 action:@selector(cancelButtonClicked)
4926 - (void) applyRightButton {
4927 if ([issues_ count] == 0 && ![self isLoading])
4928 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4929 initWithTitle:UCLocalize("CONFIRM")
4930 style:UIBarButtonItemStyleDone
4932 action:@selector(confirmButtonClicked)
4935 [[self navigationItem] setRightBarButtonItem:nil];
4939 - (void) cancelButtonClicked {
4940 [self dismissModalViewControllerAnimated:YES];
4941 [delegate_ cancelAndClear:YES];
4945 - (void) confirmButtonClicked {
4946 if (essential_ != nil)
4956 /* Progress Data {{{ */
4957 @interface CydiaProgressData : NSObject {
4958 _transient id delegate_;
4967 _H<NSMutableArray> events_;
4968 _H<NSString> title_;
4970 _H<NSString> status_;
4971 _H<NSString> finish_;
4976 @implementation CydiaProgressData
4978 + (NSArray *) _attributeKeys {
4979 return [NSArray arrayWithObjects:
4991 - (NSArray *) attributeKeys {
4992 return [[self class] _attributeKeys];
4995 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4996 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5000 if ((self = [super init]) != nil) {
5001 events_ = [NSMutableArray arrayWithCapacity:32];
5005 - (void) setDelegate:(id)delegate {
5006 delegate_ = delegate;
5009 - (void) setPercent:(float)value {
5013 - (NSNumber *) percent {
5014 return [NSNumber numberWithFloat:percent_];
5017 - (void) setCurrent:(float)value {
5021 - (NSNumber *) current {
5022 return [NSNumber numberWithFloat:current_];
5025 - (void) setTotal:(float)value {
5029 - (NSNumber *) total {
5030 return [NSNumber numberWithFloat:total_];
5033 - (void) setSpeed:(float)value {
5037 - (NSNumber *) speed {
5038 return [NSNumber numberWithFloat:speed_];
5041 - (NSArray *) events {
5045 - (void) removeAllEvents {
5046 [events_ removeAllObjects];
5049 - (void) addEvent:(CydiaProgressEvent *)event {
5050 [events_ addObject:event];
5053 - (void) setTitle:(NSString *)text {
5057 - (NSString *) title {
5061 - (void) setFinish:(NSString *)text {
5065 - (NSString *) finish {
5066 return (id) finish_ ?: [NSNull null];
5069 - (void) setRunning:(bool)running {
5073 - (NSNumber *) running {
5074 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5079 /* Progress Controller {{{ */
5080 @interface ProgressController : CydiaWebViewController <
5083 _transient Database *database_;
5084 _H<CydiaProgressData, 1> progress_;
5088 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5090 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5092 - (void) setTitle:(NSString *)title;
5093 - (void) setCancellable:(bool)cancellable;
5097 @implementation ProgressController
5100 [database_ setProgressDelegate:nil];
5104 - (UIBarButtonItem *) leftButton {
5105 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5106 initWithTitle:UCLocalize("CANCEL")
5107 style:UIBarButtonItemStylePlain
5109 action:@selector(cancel)
5110 ] autorelease] : nil;
5113 - (void) updateCancel {
5114 [super applyLeftButton];
5117 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5118 if ((self = [super init]) != nil) {
5119 database_ = database;
5120 delegate_ = delegate;
5122 [database_ setProgressDelegate:self];
5124 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5125 [progress_ setDelegate:self];
5127 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5129 [scroller_ setBackgroundColor:[UIColor blackColor]];
5131 [[self navigationItem] setHidesBackButton:YES];
5133 [self updateCancel];
5137 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5138 [super webView:view didClearWindowObject:window forFrame:frame];
5139 [window setValue:progress_ forKey:@"cydiaProgress"];
5142 - (void) updateProgress {
5143 [self dispatchEvent:@"CydiaProgressUpdate"];
5146 - (void) viewWillAppear:(BOOL)animated {
5147 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5148 [super viewWillAppear:animated];
5152 UpdateExternalStatus(0);
5155 [delegate_ saveState];
5159 [delegate_ returnToCydia];
5163 [delegate_ terminateWithSuccess];
5164 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5165 [delegate_ suspendWithAnimation:YES];
5167 [delegate_ suspend];*/
5179 system("/usr/bin/sbreload");
5185 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5186 SBReboot(SBSSpringBoardServerPort());
5188 reboot2(RB_AUTOBOOT);
5195 - (void) setTitle:(NSString *)title {
5196 [progress_ setTitle:title];
5197 [self updateProgress];
5200 - (UIBarButtonItem *) rightButton {
5201 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5202 initWithTitle:UCLocalize("CLOSE")
5203 style:UIBarButtonItemStylePlain
5205 action:@selector(close)
5211 system("su -c /usr/bin/uicache mobile");
5215 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5216 UpdateExternalStatus(1);
5218 [progress_ setRunning:true];
5219 [self setTitle:title];
5220 // implicit updateProgress
5222 SHA1SumValue notifyconf; {
5224 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5227 MMap mmap(file, MMap::ReadOnly);
5229 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5230 notifyconf = sha1.Result();
5234 SHA1SumValue springlist; {
5236 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5239 MMap mmap(file, MMap::ReadOnly);
5241 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5242 springlist = sha1.Result();
5246 if (invocation != nil) {
5247 [invocation yieldToSelector:@selector(invoke)];
5248 [self setTitle:@"COMPLETE"];
5253 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5256 MMap mmap(file, MMap::ReadOnly);
5258 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5259 if (!(notifyconf == sha1.Result()))
5266 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5269 MMap mmap(file, MMap::ReadOnly);
5271 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5272 if (!(springlist == sha1.Result()))
5278 if (RestartSubstrate_)
5282 RestartSubstrate_ = false;
5285 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5286 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5287 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5288 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5289 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5292 UIProgressHUD *hud([delegate_ addProgressHUD]);
5293 [hud setText:UCLocalize("LOADING")];
5294 [self yieldToSelector:@selector(uicache)];
5295 [delegate_ removeProgressHUD:hud];
5297 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5299 [progress_ setRunning:false];
5300 [self updateProgress];
5302 [self applyRightButton];
5305 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5306 [progress_ addEvent:event];
5307 [self updateProgress];
5310 - (bool) isProgressCancelled {
5311 return cancel_ == 2;
5316 [self updateCancel];
5319 - (void) setCancellable:(bool)cancellable {
5320 unsigned cancel(cancel_);
5324 else if (cancel_ == 0)
5327 if (cancel != cancel_)
5328 [self updateCancel];
5331 - (void) setProgressCancellable:(NSNumber *)cancellable {
5332 [self setCancellable:[cancellable boolValue]];
5335 - (void) setProgressPercent:(NSNumber *)percent {
5336 [progress_ setPercent:[percent floatValue]];
5337 [self updateProgress];
5340 - (void) setProgressStatus:(NSDictionary *)status {
5341 if (status == nil) {
5342 [progress_ setCurrent:0];
5343 [progress_ setTotal:0];
5344 [progress_ setSpeed:0];
5346 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5348 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5349 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5350 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5353 [self updateProgress];
5359 /* Package Cell {{{ */
5360 @interface PackageCell : CyteTableViewCell <
5361 CyteTableViewCellDelegate
5365 _H<NSString> description_;
5367 _H<NSString> source_;
5369 _H<UIImage> placard_;
5373 - (PackageCell *) init;
5374 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5376 - (void) drawContentRect:(CGRect)rect;
5380 @implementation PackageCell
5382 - (PackageCell *) init {
5383 CGRect frame(CGRectMake(0, 0, 320, 74));
5384 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5385 UIView *content([self contentView]);
5386 CGRect bounds([content bounds]);
5388 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5389 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5390 [content addSubview:content_];
5392 [content_ setDelegate:self];
5393 [content_ setOpaque:YES];
5397 - (NSString *) accessibilityLabel {
5398 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5401 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5402 summarized_ = summary;
5412 [content_ setBackgroundColor:[UIColor whiteColor]];
5416 Source *source = [package source];
5418 icon_ = [package icon];
5420 if (NSString *name = [package name])
5421 name_ = [NSString stringWithString:name];
5423 NSString *description(nil);
5425 if (description == nil && IsWildcat_)
5426 description = [package longDescription];
5427 if (description == nil)
5428 description = [package shortDescription];
5430 if (description != nil)
5431 description_ = [NSString stringWithString:description];
5433 commercial_ = [package isCommercial];
5435 NSString *label = nil;
5436 bool trusted = false;
5438 if (source != nil) {
5439 label = [source label];
5440 trusted = [source trusted];
5441 } else if ([[package id] isEqualToString:@"firmware"])
5442 label = UCLocalize("APPLE");
5444 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5446 NSString *from(label);
5448 NSString *section = [package simpleSection];
5449 if (section != nil && ![section isEqualToString:label]) {
5450 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5451 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5454 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5456 if (NSString *purpose = [package primaryPurpose])
5457 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5462 if (NSString *mode = [package mode]) {
5463 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5464 color = RemovingColor_;
5465 //placard = @"removing";
5467 color = InstallingColor_;
5468 //placard = @"installing";
5471 // XXX: the removing/installing placards are not @2x
5474 color = [UIColor whiteColor];
5476 if ([package installed] != nil)
5477 placard = @"installed";
5482 [content_ setBackgroundColor:color];
5485 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5488 [self setNeedsDisplay];
5489 [content_ setNeedsDisplay];
5492 - (void) drawSummaryContentRect:(CGRect)rect {
5493 bool highlighted(highlighted_);
5494 float width([self bounds].size.width);
5498 rect.size = [(UIImage *) icon_ size];
5500 while (rect.size.width > 16 || rect.size.height > 16) {
5501 rect.size.width /= 2;
5502 rect.size.height /= 2;
5505 rect.origin.x = 18 - rect.size.width / 2;
5506 rect.origin.y = 18 - rect.size.height / 2;
5508 [icon_ drawInRect:rect];
5511 if (badge_ != nil) {
5513 rect.size = [(UIImage *) badge_ size];
5515 rect.size.width /= 4;
5516 rect.size.height /= 4;
5518 rect.origin.x = 23 - rect.size.width / 2;
5519 rect.origin.y = 23 - rect.size.height / 2;
5521 [badge_ drawInRect:rect];
5528 UISetColor(commercial_ ? Purple_ : Black_);
5529 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5531 if (placard_ != nil)
5532 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5535 - (void) drawNormalContentRect:(CGRect)rect {
5536 bool highlighted(highlighted_);
5537 float width([self bounds].size.width);
5541 rect.size = [(UIImage *) icon_ size];
5543 while (rect.size.width > 32 || rect.size.height > 32) {
5544 rect.size.width /= 2;
5545 rect.size.height /= 2;
5548 rect.origin.x = 25 - rect.size.width / 2;
5549 rect.origin.y = 25 - rect.size.height / 2;
5551 [icon_ drawInRect:rect];
5554 if (badge_ != nil) {
5556 rect.size = [(UIImage *) badge_ size];
5558 rect.size.width /= 2;
5559 rect.size.height /= 2;
5561 rect.origin.x = 36 - rect.size.width / 2;
5562 rect.origin.y = 36 - rect.size.height / 2;
5564 [badge_ drawInRect:rect];
5571 UISetColor(commercial_ ? Purple_ : Black_);
5572 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5573 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5576 UISetColor(commercial_ ? Purplish_ : Gray_);
5577 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5579 if (placard_ != nil)
5580 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5583 - (void) drawContentRect:(CGRect)rect {
5585 [self drawSummaryContentRect:rect];
5587 [self drawNormalContentRect:rect];
5592 /* Section Cell {{{ */
5593 @interface SectionCell : CyteTableViewCell <
5594 CyteTableViewCellDelegate
5596 _H<NSString> basic_;
5597 _H<NSString> section_;
5599 _H<NSString> count_;
5601 _H<UISwitch> switch_;
5605 - (void) setSection:(Section *)section editing:(BOOL)editing;
5609 @implementation SectionCell
5611 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5612 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5613 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5614 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5615 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5617 UIView *content([self contentView]);
5618 CGRect bounds([content bounds]);
5620 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5621 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5622 [content addSubview:content_];
5623 [content_ setBackgroundColor:[UIColor whiteColor]];
5625 [content_ setDelegate:self];
5629 - (void) onSwitch:(id)sender {
5630 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5631 if (metadata == nil) {
5632 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5633 [Sections_ setObject:metadata forKey:basic_];
5636 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5640 - (void) setSection:(Section *)section editing:(BOOL)editing {
5641 if (editing != editing_) {
5643 [switch_ removeFromSuperview];
5645 [self addSubview:switch_];
5654 if (section == nil) {
5655 name_ = UCLocalize("ALL_PACKAGES");
5658 basic_ = [section name];
5659 section_ = [section localized];
5661 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5662 count_ = [NSString stringWithFormat:@"%d", [section count]];
5665 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5668 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5669 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5671 [content_ setNeedsDisplay];
5674 - (void) setFrame:(CGRect)frame {
5675 [super setFrame:frame];
5677 CGRect rect([switch_ frame]);
5678 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5681 - (NSString *) accessibilityLabel {
5685 - (void) drawContentRect:(CGRect)rect {
5686 bool highlighted(highlighted_ && !editing_);
5688 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5693 float width(rect.size.width);
5699 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5701 CGSize size = [count_ sizeWithFont:Font14_];
5705 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5711 /* File Table {{{ */
5712 @interface FileTable : CyteViewController <
5713 UITableViewDataSource,
5716 _transient Database *database_;
5717 _H<Package> package_;
5719 _H<NSMutableArray> files_;
5720 _H<UITableView, 2> list_;
5723 - (id) initWithDatabase:(Database *)database;
5724 - (void) setPackage:(Package *)package;
5728 @implementation FileTable
5730 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5731 return files_ == nil ? 0 : [files_ count];
5734 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5738 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5739 static NSString *reuseIdentifier = @"Cell";
5741 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5743 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5744 [cell setFont:[UIFont systemFontOfSize:16]];
5746 [cell setText:[files_ objectAtIndex:indexPath.row]];
5747 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5752 - (NSURL *) navigationURL {
5753 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5757 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5759 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5760 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5761 [list_ setRowHeight:24.0f];
5762 [(UITableView *) list_ setDataSource:self];
5763 [list_ setDelegate:self];
5764 [[self view] addSubview:list_];
5767 - (void) viewDidLoad {
5768 [super viewDidLoad];
5770 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5773 - (void) releaseSubviews {
5779 [super releaseSubviews];
5782 - (id) initWithDatabase:(Database *)database {
5783 if ((self = [super init]) != nil) {
5784 database_ = database;
5788 - (void) setPackage:(Package *)package {
5792 files_ = [NSMutableArray arrayWithCapacity:32];
5794 if (package != nil) {
5796 name_ = [package id];
5798 if (NSArray *files = [package files])
5799 [files_ addObjectsFromArray:files];
5801 if ([files_ count] != 0) {
5802 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5803 [files_ removeObjectAtIndex:0];
5804 [files_ sortUsingSelector:@selector(compareByPath:)];
5806 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5807 [stack addObject:@"/"];
5809 for (int i(0), e([files_ count]); i != e; ++i) {
5810 NSString *file = [files_ objectAtIndex:i];
5811 while (![file hasPrefix:[stack lastObject]])
5812 [stack removeLastObject];
5813 NSString *directory = [stack lastObject];
5814 [stack addObject:[file stringByAppendingString:@"/"]];
5815 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5816 ([stack count] - 2) * 3, "",
5817 [file substringFromIndex:[directory length]]
5826 - (void) reloadData {
5829 [self setPackage:[database_ packageWithName:name_]];
5834 /* Package Controller {{{ */
5835 @interface CYPackageController : CydiaWebViewController <
5836 UIActionSheetDelegate
5838 _transient Database *database_;
5839 _H<Package> package_;
5842 _H<NSMutableArray> buttons_;
5843 _H<UIBarButtonItem> button_;
5846 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5850 @implementation CYPackageController
5852 - (NSURL *) navigationURL {
5853 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5856 /* XXX: this is not safe at all... localization of /fail/ */
5857 - (void) _clickButtonWithName:(NSString *)name {
5858 if ([name isEqualToString:UCLocalize("CLEAR")])
5859 [delegate_ clearPackage:package_];
5860 else if ([name isEqualToString:UCLocalize("INSTALL")])
5861 [delegate_ installPackage:package_];
5862 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5863 [delegate_ installPackage:package_];
5864 else if ([name isEqualToString:UCLocalize("REMOVE")])
5865 [delegate_ removePackage:package_];
5866 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5867 [delegate_ installPackage:package_];
5868 else _assert(false);
5871 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5872 NSString *context([sheet context]);
5874 if ([context isEqualToString:@"modify"]) {
5875 if (button != [sheet cancelButtonIndex]) {
5876 NSString *buttonName = [buttons_ objectAtIndex:button];
5877 [self _clickButtonWithName:buttonName];
5880 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5884 - (bool) _allowJavaScriptPanel {
5889 - (void) _customButtonClicked {
5890 int count([buttons_ count]);
5895 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5897 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5898 [buttons addObjectsFromArray:buttons_];
5900 UIActionSheet *sheet = [[[UIActionSheet alloc]
5903 cancelButtonTitle:nil
5904 destructiveButtonTitle:nil
5905 otherButtonTitles:nil
5908 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5910 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5911 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5913 [sheet setContext:@"modify"];
5915 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5919 // We don't want to allow non-commercial packages to do custom things to the install button,
5920 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5921 - (void) customButtonClicked {
5923 [super customButtonClicked];
5925 [self _customButtonClicked];
5928 - (void) reloadButtonClicked {
5929 // Don't reload a commerical package by tapping the loading button,
5930 // but if it's not an Install button, we should forward it on.
5931 if (![package_ uninstalled])
5932 [self _customButtonClicked];
5935 - (void) applyLoadingTitle {
5936 // Don't show "Loading" as the title. Ever.
5939 - (UIBarButtonItem *) rightButton {
5944 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5945 if ((self = [super init]) != nil) {
5946 database_ = database;
5947 buttons_ = [NSMutableArray arrayWithCapacity:4];
5948 name_ = name == nil ? @"" : [NSString stringWithString:name];
5949 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5953 - (void) reloadData {
5956 package_ = [database_ packageWithName:name_];
5958 [buttons_ removeAllObjects];
5960 if (package_ != nil) {
5961 [(Package *) package_ parse];
5963 commercial_ = [package_ isCommercial];
5965 if ([package_ mode] != nil)
5966 [buttons_ addObject:UCLocalize("CLEAR")];
5967 if ([package_ source] == nil);
5968 else if ([package_ upgradableAndEssential:NO])
5969 [buttons_ addObject:UCLocalize("UPGRADE")];
5970 else if ([package_ uninstalled])
5971 [buttons_ addObject:UCLocalize("INSTALL")];
5973 [buttons_ addObject:UCLocalize("REINSTALL")];
5974 if (![package_ uninstalled])
5975 [buttons_ addObject:UCLocalize("REMOVE")];
5979 switch ([buttons_ count]) {
5980 case 0: title = nil; break;
5981 case 1: title = [buttons_ objectAtIndex:0]; break;
5982 default: title = UCLocalize("MODIFY"); break;
5985 button_ = [[[UIBarButtonItem alloc]
5987 style:UIBarButtonItemStylePlain
5989 action:@selector(customButtonClicked)
5993 - (bool) isLoading {
5994 return commercial_ ? [super isLoading] : false;
6000 /* Package List Controller {{{ */
6001 @interface PackageListController : CyteViewController <
6002 UITableViewDataSource,
6005 _transient Database *database_;
6007 _H<NSArray> packages_;
6008 _H<NSMutableArray> sections_;
6009 _H<UITableView, 2> list_;
6010 _H<NSMutableArray> index_;
6011 _H<NSMutableDictionary> indices_;
6012 _H<NSString> title_;
6013 unsigned reloading_;
6016 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6017 - (void) setDelegate:(id)delegate;
6018 - (void) resetCursor;
6023 @implementation PackageListController
6025 - (bool) isSummarized {
6029 - (bool) showsSections {
6033 - (void) deselectWithAnimation:(BOOL)animated {
6034 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6037 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6038 CGRect base = [[self view] bounds];
6039 base.size.height -= bounds.size.height;
6040 base.origin = [list_ frame].origin;
6042 [UIView beginAnimations:nil context:NULL];
6043 [UIView setAnimationBeginsFromCurrentState:YES];
6044 [UIView setAnimationCurve:curve];
6045 [UIView setAnimationDuration:duration];
6046 [list_ setFrame:base];
6047 [UIView commitAnimations];
6050 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6051 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6054 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6055 [self resizeForKeyboardBounds:bounds duration:0];
6058 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6059 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6060 *curve = UIViewAnimationCurveEaseInOut;
6062 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6064 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6067 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6070 - (void) keyboardWillShow:(NSNotification *)notification {
6073 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6074 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6076 NSTimeInterval duration;
6077 UIViewAnimationCurve curve;
6078 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6080 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);
6081 UIViewController *base = self;
6082 while ([base parentViewController] != nil)
6083 base = [base parentViewController];
6084 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6085 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6087 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6088 intersection.size.height += CYStatusBarHeight();
6090 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6093 - (void) keyboardWillHide:(NSNotification *)notification {
6094 NSTimeInterval duration;
6095 UIViewAnimationCurve curve;
6096 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6098 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6101 - (void) viewWillAppear:(BOOL)animated {
6102 [super viewWillAppear:animated];
6104 [self resizeForKeyboardBounds:CGRectZero];
6105 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6106 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6109 - (void) viewWillDisappear:(BOOL)animated {
6110 [super viewWillDisappear:animated];
6112 [self resizeForKeyboardBounds:CGRectZero];
6113 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6114 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6117 - (void) viewDidAppear:(BOOL)animated {
6118 [super viewDidAppear:animated];
6119 [self deselectWithAnimation:animated];
6122 - (void) didSelectPackage:(Package *)package {
6123 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6124 [view setDelegate:delegate_];
6125 [[self navigationController] pushViewController:view animated:YES];
6128 #if TryIndexedCollation
6129 + (BOOL) hasIndexedCollation {
6130 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6134 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6135 NSInteger count([sections_ count]);
6136 return count == 0 ? 1 : count;
6139 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6140 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6142 return [[sections_ objectAtIndex:section] name];
6145 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6146 if ([sections_ count] == 0)
6148 return [[sections_ objectAtIndex:section] count];
6151 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6152 @synchronized (database_) {
6153 if ([database_ era] != era_)
6156 Section *section([sections_ objectAtIndex:[path section]]);
6157 NSInteger row([path row]);
6158 Package *package([packages_ objectAtIndex:([section row] + row)]);
6159 return [[package retain] autorelease];
6162 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6163 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6165 cell = [[[PackageCell alloc] init] autorelease];
6167 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6168 [cell setPackage:package asSummary:[self isSummarized]];
6172 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6173 Package *package([self packageAtIndexPath:path]);
6174 package = [database_ packageWithName:[package id]];
6175 [self didSelectPackage:package];
6178 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6179 if (![self showsSections])
6185 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6186 #if TryIndexedCollation
6187 if ([[self class] hasIndexedCollation]) {
6188 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6195 - (void) updateHeight {
6196 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6199 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6200 if ((self = [super init]) != nil) {
6201 database_ = database;
6202 title_ = [title copy];
6203 [[self navigationItem] setTitle:title_];
6208 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6210 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6211 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6212 [[self view] addSubview:list_];
6214 // XXX: is 20 the most optimal number here?
6215 [list_ setSectionIndexMinimumDisplayRowCount:20];
6217 [(UITableView *) list_ setDataSource:self];
6218 [list_ setDelegate:self];
6220 [self updateHeight];
6223 - (void) releaseSubviews {
6231 [super releaseSubviews];
6234 - (void) setDelegate:(id)delegate {
6235 delegate_ = delegate;
6238 - (bool) shouldYield {
6242 - (bool) shouldBlock {
6246 - (NSMutableArray *) _reloadPackages {
6247 @synchronized (database_) {
6248 era_ = [database_ era];
6249 NSArray *packages([database_ packages]);
6251 return [NSMutableArray arrayWithArray:packages];
6254 - (void) _reloadData {
6255 if (reloading_ != 0) {
6262 if ([self shouldYield]) {
6266 if (![self shouldBlock])
6269 hud = [delegate_ addProgressHUD];
6270 [hud setText:UCLocalize("LOADING")];
6274 packages = [self yieldToSelector:@selector(_reloadPackages)];
6277 [delegate_ removeProgressHUD:hud];
6278 } while (reloading_ == 2);
6282 packages = [self _reloadPackages];
6285 packages_ = packages;
6287 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6288 sections_ = [NSMutableArray arrayWithCapacity:16];
6290 Section *section = nil;
6292 #if TryIndexedCollation
6293 if ([[self class] hasIndexedCollation]) {
6294 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6296 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6297 NSArray *titles = [collation sectionIndexTitles];
6300 _profile(PackageTable$reloadData$Section)
6301 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6305 _profile(PackageTable$reloadData$Section$Package)
6306 package = [packages_ objectAtIndex:offset];
6307 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6310 while (secidx < index) {
6313 _profile(PackageTable$reloadData$Section$Allocate)
6314 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6317 _profile(PackageTable$reloadData$Section$Add)
6318 [sections_ addObject:section];
6322 [section addToCount];
6328 index_ = [NSMutableArray arrayWithCapacity:32];
6330 bool sectioned([self showsSections]);
6332 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6333 [sections_ addObject:section];
6336 _profile(PackageTable$reloadData$Section)
6337 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6341 _profile(PackageTable$reloadData$Section$Package)
6342 package = [packages_ objectAtIndex:offset];
6343 index = [package index];
6346 if (sectioned && (section == nil || [section index] != index)) {
6347 _profile(PackageTable$reloadData$Section$Allocate)
6348 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6351 [index_ addObject:[section name]];
6352 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6354 _profile(PackageTable$reloadData$Section$Add)
6355 [sections_ addObject:section];
6359 [section addToCount];
6364 [self updateHeight];
6366 _profile(PackageTable$reloadData$List)
6367 [(UITableView *) list_ setDataSource:self];
6372 - (void) reloadData {
6375 if ([self shouldYield])
6376 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6381 - (void) resetCursor {
6382 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6385 - (void) clearData {
6386 [self updateHeight];
6388 [list_ setDataSource:nil];
6396 /* Filtered Package List Controller {{{ */
6397 @interface FilteredPackageListController : PackageListController {
6400 _H<NSObject> object_;
6403 - (void) setObject:(id)object;
6404 - (void) setObject:(id)object forFilter:(SEL)filter;
6407 - (void) setFilter:(SEL)filter;
6409 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6413 @implementation FilteredPackageListController
6419 - (void) setFilter:(SEL)filter {
6420 @synchronized (self) {
6423 /* XXX: this is an unsafe optimization of doomy hell */
6424 Method method(class_getInstanceMethod([Package class], filter));
6425 _assert(method != NULL);
6426 imp_ = method_getImplementation(method);
6427 _assert(imp_ != NULL);
6430 - (void) setObject:(id)object {
6431 @synchronized (self) {
6435 - (void) setObject:(id)object forFilter:(SEL)filter {
6436 @synchronized (self) {
6437 [self setFilter:filter];
6438 [self setObject:object];
6441 - (NSMutableArray *) _reloadPackages {
6442 @synchronized (database_) {
6443 era_ = [database_ era];
6444 NSArray *packages([database_ packages]);
6446 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6450 _H<NSObject> object;
6452 @synchronized (self) {
6458 _profile(PackageTable$reloadData$Filter)
6459 for (Package *package in packages)
6460 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6461 [filtered addObject:package];
6467 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6468 if ((self = [super initWithDatabase:database title:title]) != nil) {
6469 [self setFilter:filter];
6470 [self setObject:object];
6477 /* Home Controller {{{ */
6478 @interface HomeController : CydiaWebViewController {
6483 @implementation HomeController
6486 if ((self = [super init]) != nil) {
6487 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6492 - (NSURL *) navigationURL {
6493 return [NSURL URLWithString:@"cydia://home"];
6496 - (void) didReceiveMemoryWarning {
6499 - (void) aboutButtonClicked {
6500 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6502 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6503 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6504 [alert setCancelButtonIndex:0];
6507 @"Copyright \u00a9 2008-2011\n"
6510 "Jay Freeman (saurik)\n"
6511 "saurik@saurik.com\n"
6512 "http://www.saurik.com/"
6518 - (UIBarButtonItem *) leftButton {
6519 return [[[UIBarButtonItem alloc]
6520 initWithTitle:UCLocalize("ABOUT")
6521 style:UIBarButtonItemStylePlain
6523 action:@selector(aboutButtonClicked)
6529 /* Manage Controller {{{ */
6530 @interface ManageController : CydiaWebViewController {
6533 - (void) queueStatusDidChange;
6537 @implementation ManageController
6540 if ((self = [super init]) != nil) {
6541 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6545 - (NSURL *) navigationURL {
6546 return [NSURL URLWithString:@"cydia://manage"];
6549 - (UIBarButtonItem *) leftButton {
6550 return [[[UIBarButtonItem alloc]
6551 initWithTitle:UCLocalize("SETTINGS")
6552 style:UIBarButtonItemStylePlain
6554 action:@selector(settingsButtonClicked)
6558 - (void) settingsButtonClicked {
6559 [delegate_ showSettings];
6562 - (void) queueButtonClicked {
6566 - (UIBarButtonItem *) rightButton {
6567 return Queuing_ ? [[[UIBarButtonItem alloc]
6568 initWithTitle:UCLocalize("QUEUE")
6569 style:UIBarButtonItemStyleDone
6571 action:@selector(queueButtonClicked)
6572 ] autorelease] : nil;
6575 - (void) queueStatusDidChange {
6576 [self applyRightButton];
6579 - (bool) isLoading {
6580 return !Queuing_ && [super isLoading];
6586 /* Refresh Bar {{{ */
6587 @interface RefreshBar : UINavigationBar {
6588 _H<UIProgressIndicator> indicator_;
6589 _H<UITextLabel> prompt_;
6590 _H<UIProgressBar> progress_;
6591 _H<UINavigationButton> cancel_;
6596 @implementation RefreshBar
6598 - (void) positionViews {
6599 CGRect frame = [cancel_ frame];
6600 frame.size = [cancel_ sizeThatFits:frame.size];
6601 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6602 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6603 [cancel_ setFrame:frame];
6605 CGSize prgsize = {75, 100};
6607 [self frame].size.width - prgsize.width - 10,
6608 ([self frame].size.height - prgsize.height) / 2
6610 [progress_ setFrame:prgrect];
6612 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6613 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6614 CGRect indrect = {{indoffset, indoffset}, indsize};
6615 [indicator_ setFrame:indrect];
6617 CGSize prmsize = {215, indsize.height + 4};
6619 indoffset * 2 + indsize.width,
6620 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6622 [prompt_ setFrame:prmrect];
6625 - (void) setFrame:(CGRect)frame {
6626 [super setFrame:frame];
6627 [self positionViews];
6630 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6631 if ((self = [super initWithFrame:frame]) != nil) {
6632 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6634 [self setBarStyle:UIBarStyleBlack];
6636 UIBarStyle barstyle([self _barStyle:NO]);
6637 bool ugly(barstyle == UIBarStyleDefault);
6639 UIProgressIndicatorStyle style = ugly ?
6640 UIProgressIndicatorStyleMediumBrown :
6641 UIProgressIndicatorStyleMediumWhite;
6643 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6644 [(UIProgressIndicator *) indicator_ setStyle:style];
6645 [indicator_ startAnimation];
6646 [self addSubview:indicator_];
6648 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6649 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6650 [prompt_ setBackgroundColor:[UIColor clearColor]];
6651 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6652 [self addSubview:prompt_];
6654 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6655 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6656 [(UIProgressBar *) progress_ setStyle:0];
6657 [self addSubview:progress_];
6659 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6660 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6661 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6662 [cancel_ setBarStyle:barstyle];
6664 [self positionViews];
6668 - (void) setCancellable:(bool)cancellable {
6670 [self addSubview:cancel_];
6672 [cancel_ removeFromSuperview];
6676 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6677 [progress_ setProgress:0];
6681 [self setCancellable:NO];
6684 - (void) setPrompt:(NSString *)prompt {
6685 [prompt_ setText:prompt];
6688 - (void) setProgress:(float)progress {
6689 [progress_ setProgress:progress];
6695 /* Cydia Navigation Controller Interface {{{ */
6696 @interface UINavigationController (Cydia)
6698 - (NSArray *) navigationURLCollection;
6699 - (void) unloadData;
6704 /* Cydia Tab Bar Controller {{{ */
6705 @interface CYTabBarController : UITabBarController <
6706 UITabBarControllerDelegate,
6709 _transient Database *database_;
6710 _H<RefreshBar, 1> refreshbar_;
6714 // XXX: ok, "updatedelegate_"?...
6715 _transient NSObject<CydiaDelegate> *updatedelegate_;
6717 _H<UIViewController> remembered_;
6718 _transient UIViewController *transient_;
6721 - (NSArray *) navigationURLCollection;
6722 - (void) dropBar:(BOOL)animated;
6723 - (void) beginUpdate;
6724 - (void) raiseBar:(BOOL)animated;
6726 - (void) unloadData;
6730 @implementation CYTabBarController
6732 - (void) setUnselectedViewController:(UIViewController *)transient {
6733 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6734 if (transient != nil) {
6735 if (transient_ == nil)
6736 remembered_ = [controllers objectAtIndex:0];
6737 transient_ = transient;
6738 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6739 [controllers replaceObjectAtIndex:0 withObject:transient_];
6740 [self setSelectedIndex:0];
6741 [self setViewControllers:controllers];
6742 [self concealTabBarSelection];
6743 } else if (remembered_ != nil) {
6744 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6745 transient_ = transient;
6746 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6748 [self setViewControllers:controllers];
6749 [self revealTabBarSelection];
6753 - (UIViewController *) unselectedViewController {
6757 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6758 if ([self unselectedViewController])
6759 [self setUnselectedViewController:nil];
6762 - (NSArray *) navigationURLCollection {
6763 NSMutableArray *items([NSMutableArray array]);
6765 // XXX: Should this deal with transient view controllers?
6766 for (id navigation in [self viewControllers]) {
6767 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6769 [items addObject:stack];
6775 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6776 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6777 [self setUnselectedViewController:nil];
6779 [super dismissModalViewControllerAnimated:YES];
6782 - (void) unloadData {
6785 for (UINavigationController *controller in [self viewControllers])
6786 [controller unloadData];
6788 if (UIViewController *selected = [self selectedViewController])
6789 [selected reloadData];
6791 if (UIViewController *unselected = [self unselectedViewController]) {
6792 [unselected unloadData];
6793 [unselected reloadData];
6798 [[NSNotificationCenter defaultCenter] removeObserver:self];
6803 - (id) initWithDatabase:(Database *)database {
6804 if ((self = [super init]) != nil) {
6805 database_ = database;
6806 [self setDelegate:self];
6808 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6809 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6811 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6815 - (void) setUpdate:(NSDate *)date {
6819 - (void) beginUpdate {
6820 [(RefreshBar *) refreshbar_ start];
6823 [updatedelegate_ retainNetworkActivityIndicator];
6827 detachNewThreadSelector:@selector(performUpdate)
6833 - (void) performUpdate {
6834 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6837 status.setDelegate(self);
6838 [database_ updateWithStatus:status];
6841 performSelectorOnMainThread:@selector(completeUpdate)
6849 - (void) stopUpdateWithSelector:(SEL)selector {
6851 [updatedelegate_ releaseNetworkActivityIndicator];
6853 [self raiseBar:YES];
6856 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6859 - (void) completeUpdate {
6862 [self stopUpdateWithSelector:@selector(reloadData)];
6865 - (void) cancelUpdate {
6866 [self stopUpdateWithSelector:@selector(updateData)];
6869 - (void) cancelPressed {
6870 [self cancelUpdate];
6877 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6878 [refreshbar_ setPrompt:[event compoundMessage]];
6881 - (bool) isProgressCancelled {
6885 - (void) setProgressCancellable:(NSNumber *)cancellable {
6886 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6889 - (void) setProgressPercent:(NSNumber *)percent {
6890 [refreshbar_ setProgress:[percent floatValue]];
6893 - (void) setProgressStatus:(NSDictionary *)status {
6895 [self setProgressPercent:[status objectForKey:@"Percent"]];
6898 - (void) setUpdateDelegate:(id)delegate {
6899 updatedelegate_ = delegate;
6902 - (UIView *) transitionView {
6903 if ([self respondsToSelector:@selector(_transitionView)])
6904 return [self _transitionView];
6906 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6909 - (void) dropBar:(BOOL)animated {
6914 UIView *transition([self transitionView]);
6915 [[self view] addSubview:refreshbar_];
6917 CGRect barframe([refreshbar_ frame]);
6919 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6920 barframe.origin.y = CYStatusBarHeight();
6922 barframe.origin.y = 0;
6924 [refreshbar_ setFrame:barframe];
6927 [UIView beginAnimations:nil context:NULL];
6929 CGRect viewframe = [transition frame];
6930 viewframe.origin.y += barframe.size.height;
6931 viewframe.size.height -= barframe.size.height;
6932 [transition setFrame:viewframe];
6935 [UIView commitAnimations];
6937 // Ensure bar has the proper width for our view, it might have changed
6938 barframe.size.width = viewframe.size.width;
6939 [refreshbar_ setFrame:barframe];
6942 - (void) raiseBar:(BOOL)animated {
6947 UIView *transition([self transitionView]);
6948 [refreshbar_ removeFromSuperview];
6950 CGRect barframe([refreshbar_ frame]);
6953 [UIView beginAnimations:nil context:NULL];
6955 CGRect viewframe = [transition frame];
6956 viewframe.origin.y -= barframe.size.height;
6957 viewframe.size.height += barframe.size.height;
6958 [transition setFrame:viewframe];
6961 [UIView commitAnimations];
6964 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6965 bool dropped(dropped_);
6970 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6976 - (void) statusBarFrameChanged:(NSNotification *)notification {
6986 /* Cydia Navigation Controller Implementation {{{ */
6987 @implementation UINavigationController (Cydia)
6989 - (NSArray *) navigationURLCollection {
6990 NSMutableArray *stack([NSMutableArray array]);
6992 for (CyteViewController *controller in [self viewControllers]) {
6993 NSString *url = [[controller navigationURL] absoluteString];
6995 [stack addObject:url];
7001 - (void) reloadData {
7004 UIViewController *visible([self visibleViewController]);
7006 [visible reloadData];
7008 // on the iPad, this view controller is ALSO visible. :(
7010 if (UIViewController *top = [self topViewController])
7015 - (void) unloadData {
7016 for (CyteViewController *page in [self viewControllers])
7025 /* Cydia:// Protocol {{{ */
7026 @interface CydiaURLProtocol : NSURLProtocol {
7031 @implementation CydiaURLProtocol
7033 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7034 NSURL *url([request URL]);
7038 NSString *scheme([[url scheme] lowercaseString]);
7039 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7041 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7047 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7051 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7052 id<NSURLProtocolClient> client([self client]);
7054 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7056 NSData *data(UIImagePNGRepresentation(icon));
7058 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7059 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7060 [client URLProtocol:self didLoadData:data];
7061 [client URLProtocolDidFinishLoading:self];
7065 - (void) startLoading {
7066 id<NSURLProtocolClient> client([self client]);
7067 NSURLRequest *request([self request]);
7069 NSURL *url([request URL]);
7070 NSString *href([url absoluteString]);
7071 NSString *scheme([[url scheme] lowercaseString]);
7075 if ([scheme isEqualToString:@"cydia"])
7076 path = [href substringFromIndex:8];
7077 else if ([scheme isEqualToString:@"about"])
7078 path = [href substringFromIndex:12];
7079 else _assert(false);
7081 NSRange slash([path rangeOfString:@"/"]);
7084 if (slash.location == NSNotFound) {
7088 command = [path substringToIndex:slash.location];
7089 path = [path substringFromIndex:(slash.location + 1)];
7092 Database *database([Database sharedInstance]);
7094 if ([command isEqualToString:@"package-icon"]) {
7097 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7098 Package *package([database packageWithName:path]);
7102 UIImage *icon([package icon]);
7103 [self _returnPNGWithImage:icon forRequest:request];
7104 } else if ([command isEqualToString:@"uikit-image"]) {
7107 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7108 UIImage *icon(_UIImageWithName(path));
7109 [self _returnPNGWithImage:icon forRequest:request];
7110 } else if ([command isEqualToString:@"section-icon"]) {
7113 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7114 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7116 icon = [UIImage applicationImageNamed:@"unknown.png"];
7117 [self _returnPNGWithImage:icon forRequest:request];
7119 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7123 - (void) stopLoading {
7129 /* Section Controller {{{ */
7130 @interface SectionController : FilteredPackageListController {
7131 _H<NSString> section_;
7134 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7138 @implementation SectionController
7140 - (NSURL *) navigationURL {
7141 NSString *name = section_;
7145 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7148 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7151 title = UCLocalize("ALL_PACKAGES");
7152 else if (![name isEqual:@""])
7153 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7155 title = UCLocalize("NO_SECTION");
7157 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7164 /* Sections Controller {{{ */
7165 @interface SectionsController : CyteViewController <
7166 UITableViewDataSource,
7169 _transient Database *database_;
7170 _H<NSMutableArray> sections_;
7171 _H<NSMutableArray> filtered_;
7172 _H<UITableView, 2> list_;
7175 - (id) initWithDatabase:(Database *)database;
7176 - (void) editButtonClicked;
7180 @implementation SectionsController
7182 - (NSURL *) navigationURL {
7183 return [NSURL URLWithString:@"cydia://sections"];
7186 - (void) updateNavigationItem {
7187 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7188 if ([sections_ count] == 0) {
7189 [[self navigationItem] setRightBarButtonItem:nil];
7191 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7192 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7194 action:@selector(editButtonClicked)
7195 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7199 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7200 [super setEditing:editing animated:animated];
7205 [delegate_ updateData];
7207 [self updateNavigationItem];
7210 - (void) viewDidAppear:(BOOL)animated {
7211 [super viewDidAppear:animated];
7212 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7215 - (void) viewWillDisappear:(BOOL)animated {
7216 [super viewWillDisappear:animated];
7217 if ([self isEditing]) [self setEditing:NO];
7220 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7221 Section *section = nil;
7222 int index = [indexPath row];
7223 if (![self isEditing]) {
7226 section = [filtered_ objectAtIndex:index];
7228 section = [sections_ objectAtIndex:index];
7233 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7234 if ([self isEditing])
7235 return [sections_ count];
7237 return [filtered_ count] + 1;
7240 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7244 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7245 static NSString *reuseIdentifier = @"SectionCell";
7247 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7249 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7251 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7256 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7257 if ([self isEditing])
7260 Section *section = [self sectionAtIndexPath:indexPath];
7262 SectionController *controller = [[[SectionController alloc]
7263 initWithDatabase:database_
7264 section:[section name]
7266 [controller setDelegate:delegate_];
7268 [[self navigationController] pushViewController:controller animated:YES];
7272 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7274 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7275 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7276 [list_ setRowHeight:45.0f];
7277 [(UITableView *) list_ setDataSource:self];
7278 [list_ setDelegate:self];
7279 [[self view] addSubview:list_];
7282 - (void) viewDidLoad {
7283 [super viewDidLoad];
7285 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7288 - (void) releaseSubviews {
7294 [super releaseSubviews];
7297 - (id) initWithDatabase:(Database *)database {
7298 if ((self = [super init]) != nil) {
7299 database_ = database;
7303 - (void) reloadData {
7306 NSArray *packages = [database_ packages];
7308 sections_ = [NSMutableArray arrayWithCapacity:16];
7309 filtered_ = [NSMutableArray arrayWithCapacity:16];
7311 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7314 for (Package *package in packages) {
7315 NSString *name([package section]);
7316 NSString *key(name == nil ? @"" : name);
7320 _profile(SectionsView$reloadData$Section)
7321 section = [sections objectForKey:key];
7322 if (section == nil) {
7323 _profile(SectionsView$reloadData$Section$Allocate)
7324 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7325 [sections setObject:section forKey:key];
7330 [section addToCount];
7332 _profile(SectionsView$reloadData$Filter)
7333 if (![package valid] || ![package visible])
7341 [sections_ addObjectsFromArray:[sections allValues]];
7343 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7345 for (Section *section in (id) sections_) {
7346 size_t count([section row]);
7350 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7351 [section setCount:count];
7352 [filtered_ addObject:section];
7355 [self updateNavigationItem];
7360 - (void) editButtonClicked {
7361 [self setEditing:![self isEditing] animated:YES];
7367 /* Changes Controller {{{ */
7368 @interface ChangesController : CyteViewController <
7369 UITableViewDataSource,
7372 _transient Database *database_;
7374 _H<NSArray> packages_;
7375 _H<NSMutableArray> sections_;
7376 _H<UITableView, 2> list_;
7380 - (id) initWithDatabase:(Database *)database;
7384 @implementation ChangesController
7386 - (NSURL *) navigationURL {
7387 return [NSURL URLWithString:@"cydia://changes"];
7390 - (void) viewDidAppear:(BOOL)animated {
7391 [super viewDidAppear:animated];
7392 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7395 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7396 NSInteger count([sections_ count]);
7397 return count == 0 ? 1 : count;
7400 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7401 if ([sections_ count] == 0)
7403 return [[sections_ objectAtIndex:section] name];
7406 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7407 if ([sections_ count] == 0)
7409 return [[sections_ objectAtIndex:section] count];
7412 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7413 @synchronized (database_) {
7414 if ([database_ era] != era_)
7417 NSUInteger sectionIndex([path section]);
7418 if (sectionIndex >= [sections_ count])
7420 Section *section([sections_ objectAtIndex:sectionIndex]);
7421 NSInteger row([path row]);
7422 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7425 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7426 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7428 cell = [[[PackageCell alloc] init] autorelease];
7430 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7431 [cell setPackage:package asSummary:false];
7435 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7436 Package *package([self packageAtIndexPath:path]);
7437 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7438 [view setDelegate:delegate_];
7439 [[self navigationController] pushViewController:view animated:YES];
7443 - (void) refreshButtonClicked {
7444 [delegate_ beginUpdate];
7445 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7448 - (void) upgradeButtonClicked {
7449 [delegate_ distUpgrade];
7450 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7454 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7456 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7457 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7458 [list_ setRowHeight:73];
7459 [(UITableView *) list_ setDataSource:self];
7460 [list_ setDelegate:self];
7461 [[self view] addSubview:list_];
7464 - (void) viewDidLoad {
7465 [super viewDidLoad];
7467 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7470 - (void) releaseSubviews {
7476 [super releaseSubviews];
7479 - (id) initWithDatabase:(Database *)database {
7480 if ((self = [super init]) != nil) {
7481 database_ = database;
7485 - (NSMutableArray *) _reloadPackages {
7486 @synchronized (database_) {
7487 era_ = [database_ era];
7488 NSArray *packages([database_ packages]);
7490 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7493 _profile(ChangesController$_reloadPackages$Filter)
7494 for (Package *package in packages)
7495 if ([package upgradableAndEssential:YES] || [package visible])
7496 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7499 _profile(ChangesController$_reloadPackages$radixSort)
7500 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7507 - (void) _reloadData {
7512 UIProgressHUD *hud([delegate_ addProgressHUD]);
7513 [hud setText:UCLocalize("LOADING")];
7514 //NSLog(@"HUD:%@::%@", delegate_, hud);
7515 packages = [self yieldToSelector:@selector(_reloadPackages)];
7516 [delegate_ removeProgressHUD:hud];
7518 packages = [self _reloadPackages];
7521 @synchronized (database_) {
7522 if (era_ != [database_ era])
7525 packages_ = packages;
7526 sections_ = [NSMutableArray arrayWithCapacity:16];
7528 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7529 Section *ignored = nil;
7530 Section *section = nil;
7534 bool unseens = false;
7536 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7538 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7539 Package *package = [packages_ objectAtIndex:offset];
7541 BOOL uae = [package upgradableAndEssential:YES];
7545 time_t seen([package seen]);
7547 if (section == nil || last != seen) {
7551 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7554 _profile(ChangesController$reloadData$Allocate)
7555 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7556 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7557 [sections_ addObject:section];
7561 [section addToCount];
7562 } else if ([package ignored]) {
7563 if (ignored == nil) {
7564 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7566 [ignored addToCount];
7569 [upgradable addToCount];
7574 CFRelease(formatter);
7577 Section *last = [sections_ lastObject];
7578 size_t count = [last count];
7579 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7580 [sections_ removeLastObject];
7583 if ([ignored count] != 0)
7584 [sections_ insertObject:ignored atIndex:0];
7586 [sections_ insertObject:upgradable atIndex:0];
7590 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7591 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7592 style:UIBarButtonItemStylePlain
7594 action:@selector(upgradeButtonClicked)
7595 ] autorelease]) animated:YES];
7597 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7598 initWithTitle:UCLocalize("REFRESH")
7599 style:UIBarButtonItemStylePlain
7601 action:@selector(refreshButtonClicked)
7602 ] autorelease]) animated:YES];
7607 - (void) reloadData {
7609 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7614 /* Search Controller {{{ */
7615 @interface SearchController : FilteredPackageListController <
7618 _H<UISearchBar, 1> search_;
7622 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7623 - (void) reloadData;
7627 @implementation SearchController
7629 - (NSURL *) navigationURL {
7630 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7631 return [NSURL URLWithString:@"cydia://search"];
7633 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7636 - (void) useSearch {
7637 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7642 - (void) viewWillAppear:(BOOL)animated {
7643 [super viewWillAppear:animated];
7645 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7649 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7650 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7655 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7656 [search_ resignFirstResponder];
7660 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7661 [search_ setText:@""];
7662 [self searchBarButtonClicked:searchBar];
7665 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7666 [self searchBarButtonClicked:searchBar];
7669 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7670 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7674 - (bool) shouldYield {
7678 - (bool) shouldBlock {
7679 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7682 - (bool) isSummarized {
7683 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7686 - (bool) showsSections {
7690 - (NSMutableArray *) _reloadPackages {
7691 NSMutableArray *packages([super _reloadPackages]);
7692 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7693 [packages radixSortUsingSelector:@selector(rank)];
7697 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7698 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7699 search_ = [[[UISearchBar alloc] init] autorelease];
7700 [search_ setDelegate:self];
7703 [search_ setText:query];
7707 - (void) viewDidAppear:(BOOL)animated {
7708 [super viewDidAppear:animated];
7710 if (!searchloaded_) {
7711 searchloaded_ = YES;
7712 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7713 [search_ layoutSubviews];
7714 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7716 UITextField *textField;
7717 if ([search_ respondsToSelector:@selector(searchField)])
7718 textField = [search_ searchField];
7720 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7722 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7723 [textField setEnablesReturnKeyAutomatically:NO];
7724 [[self navigationItem] setTitleView:textField];
7728 - (void) reloadData {
7729 id object([search_ text]);
7730 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7731 object = [object componentsSeparatedByString:@" "];
7733 [self setObject:object];
7739 - (void) didSelectPackage:(Package *)package {
7740 [search_ resignFirstResponder];
7741 [super didSelectPackage:package];
7746 /* Package Settings Controller {{{ */
7747 @interface PackageSettingsController : CyteViewController <
7748 UITableViewDataSource,
7751 _transient Database *database_;
7753 _H<Package> package_;
7754 _H<UITableView, 2> table_;
7755 _H<UISwitch> subscribedSwitch_;
7756 _H<UISwitch> ignoredSwitch_;
7757 _H<UITableViewCell> subscribedCell_;
7758 _H<UITableViewCell> ignoredCell_;
7761 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7765 @implementation PackageSettingsController
7767 - (NSURL *) navigationURL {
7768 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7771 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7772 if (package_ == nil)
7775 if ([package_ installed] == nil)
7781 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7782 if (package_ == nil)
7785 // both sections contain just one item right now.
7789 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7793 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7795 return UCLocalize("SHOW_ALL_CHANGES_EX");
7797 return UCLocalize("IGNORE_UPGRADES_EX");
7800 - (void) onSubscribed:(id)control {
7801 bool value([control isOn]);
7802 if (package_ == nil)
7804 if ([package_ setSubscribed:value])
7805 [delegate_ updateData];
7808 - (void) _updateIgnored {
7809 const char *package([name_ UTF8String]);
7810 bool on([ignoredSwitch_ isOn]);
7812 pid_t pid(ExecFork());
7814 FILE *dpkg(popen("dpkg --set-selections", "w"));
7815 fwrite(package, strlen(package), 1, dpkg);
7818 fwrite(" hold\n", 6, 1, dpkg);
7820 fwrite(" install\n", 9, 1, dpkg);
7830 int result(waitpid(pid, &status, 0));
7833 _assert(result == pid);
7839 - (void) onIgnored:(id)control {
7840 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7841 [invocation setTarget:self];
7842 [invocation setSelector:@selector(_updateIgnored)];
7844 [delegate_ reloadDataWithInvocation:invocation];
7847 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7848 if (package_ == nil)
7851 switch ([indexPath section]) {
7852 case 0: return subscribedCell_;
7853 case 1: return ignoredCell_;
7862 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7864 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7865 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7866 [(UITableView *) table_ setDataSource:self];
7867 [table_ setDelegate:self];
7868 [[self view] addSubview:table_];
7870 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7871 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7872 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7874 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7875 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7876 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7878 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7879 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7880 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7881 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7883 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7884 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7885 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7886 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7889 - (void) viewDidLoad {
7890 [super viewDidLoad];
7892 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7895 - (void) releaseSubviews {
7897 subscribedCell_ = nil;
7899 ignoredSwitch_ = nil;
7900 subscribedSwitch_ = nil;
7902 [super releaseSubviews];
7905 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7906 if ((self = [super init]) != nil) {
7907 database_ = database;
7912 - (void) reloadData {
7915 package_ = [database_ packageWithName:name_];
7917 if (package_ != nil) {
7918 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7919 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7920 } // XXX: what now, G?
7922 [table_ reloadData];
7928 /* Installed Controller {{{ */
7929 @interface InstalledController : FilteredPackageListController {
7933 - (id) initWithDatabase:(Database *)database;
7935 - (void) updateRoleButton;
7936 - (void) queueStatusDidChange;
7940 @implementation InstalledController
7942 - (NSURL *) navigationURL {
7943 return [NSURL URLWithString:@"cydia://installed"];
7946 - (id) initWithDatabase:(Database *)database {
7947 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7948 [self updateRoleButton];
7949 [self queueStatusDidChange];
7954 - (void) queueButtonClicked {
7959 - (void) queueStatusDidChange {
7963 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7964 initWithTitle:UCLocalize("QUEUE")
7965 style:UIBarButtonItemStyleDone
7967 action:@selector(queueButtonClicked)
7970 [[self navigationItem] setLeftBarButtonItem:nil];
7976 - (void) updateRoleButton {
7977 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7978 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7979 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7980 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7982 action:@selector(roleButtonClicked)
7986 - (void) roleButtonClicked {
7987 [self setObject:[NSNumber numberWithBool:expert_]];
7991 [self updateRoleButton];
7997 /* Source Cell {{{ */
7998 @interface SourceCell : CyteTableViewCell <
7999 CyteTableViewCellDelegate
8003 _H<NSString> origin_;
8004 _H<NSString> label_;
8007 - (void) setSource:(Source *)source;
8011 @implementation SourceCell
8013 - (void) _setImage:(NSArray *)data {
8014 if ([url_ isEqual:[data objectAtIndex:0]]) {
8015 icon_ = [data objectAtIndex:1];
8016 [content_ setNeedsDisplay];
8020 - (void) _setSource:(NSURL *) url {
8021 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8023 if (NSData *data = [NSURLConnection
8024 sendSynchronousRequest:[NSURLRequest
8026 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8030 returningResponse:NULL
8033 if (UIImage *image = [UIImage imageWithData:data])
8034 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8039 - (void) setSource:(Source *)source {
8040 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8042 origin_ = [source name];
8043 label_ = [source rooturi];
8045 [content_ setNeedsDisplay];
8047 url_ = [source iconURL];
8048 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8051 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8052 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8053 UIView *content([self contentView]);
8054 CGRect bounds([content bounds]);
8056 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8057 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8058 [content_ setBackgroundColor:[UIColor whiteColor]];
8059 [content addSubview:content_];
8061 [content_ setDelegate:self];
8062 [content_ setOpaque:YES];
8064 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8068 - (NSString *) accessibilityLabel {
8072 - (void) drawContentRect:(CGRect)rect {
8073 bool highlighted(highlighted_);
8074 float width(rect.size.width);
8078 rect.size = [(UIImage *) icon_ size];
8080 while (rect.size.width > 32 || rect.size.height > 32) {
8081 rect.size.width /= 2;
8082 rect.size.height /= 2;
8085 rect.origin.x = 25 - rect.size.width / 2;
8086 rect.origin.y = 25 - rect.size.height / 2;
8088 [icon_ drawInRect:rect];
8096 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 60) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8100 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 75) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8105 /* Source Controller {{{ */
8106 @interface SourceController : FilteredPackageListController {
8107 _transient Source *source_;
8111 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8115 @implementation SourceController
8117 - (NSURL *) navigationURL {
8118 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8121 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8122 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8124 key_ = [source key];
8128 - (void) reloadData {
8129 source_ = [database_ sourceWithKey:key_];
8130 key_ = [source_ key];
8131 [self setObject:source_];
8133 [[self navigationItem] setTitle:[source_ label]];
8140 /* Sources Controller {{{ */
8141 @interface SourcesController : CyteViewController <
8142 UITableViewDataSource,
8145 _transient Database *database_;
8148 _H<UITableView, 2> list_;
8149 _H<NSMutableArray> sources_;
8153 _H<UIProgressHUD> hud_;
8156 //NSURLConnection *installer_;
8157 NSURLConnection *trivial_;
8158 NSURLConnection *trivial_bz2_;
8159 NSURLConnection *trivial_gz_;
8160 //NSURLConnection *automatic_;
8165 - (id) initWithDatabase:(Database *)database;
8166 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8170 @implementation SourcesController
8172 - (void) _releaseConnection:(NSURLConnection *)connection {
8173 if (connection != nil) {
8174 [connection cancel];
8175 //[connection setDelegate:nil];
8176 [connection release];
8181 //[self _releaseConnection:installer_];
8182 [self _releaseConnection:trivial_];
8183 [self _releaseConnection:trivial_gz_];
8184 [self _releaseConnection:trivial_bz2_];
8185 //[self _releaseConnection:automatic_];
8190 - (NSURL *) navigationURL {
8191 return [NSURL URLWithString:@"cydia://sources"];
8194 - (void) viewDidAppear:(BOOL)animated {
8195 [super viewDidAppear:animated];
8196 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8199 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8203 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8207 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8208 return [sources_ count];
8211 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8212 @synchronized (database_) {
8213 if ([database_ era] != era_)
8216 return [sources_ objectAtIndex:[indexPath row]];
8219 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8220 static NSString *cellIdentifier = @"SourceCell";
8222 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8223 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8224 [cell setSource:[self sourceAtIndexPath:indexPath]];
8225 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8230 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8231 Source *source = [self sourceAtIndexPath:indexPath];
8233 SourceController *controller = [[[SourceController alloc]
8234 initWithDatabase:database_
8238 [controller setDelegate:delegate_];
8240 [[self navigationController] pushViewController:controller animated:YES];
8243 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8244 Source *source = [self sourceAtIndexPath:indexPath];
8245 return [source record] != nil;
8248 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8249 if (editingStyle == UITableViewCellEditingStyleDelete) {
8250 Source *source = [self sourceAtIndexPath:indexPath];
8251 [Sources_ removeObjectForKey:[source key]];
8252 [delegate_ syncData];
8257 [delegate_ addTrivialSource:href_];
8258 [delegate_ syncData];
8261 - (NSString *) getWarning {
8262 NSString *href(href_);
8263 NSRange colon([href rangeOfString:@"://"]);
8264 if (colon.location != NSNotFound)
8265 href = [href substringFromIndex:(colon.location + 3)];
8266 href = [href stringByAddingPercentEscapes];
8267 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8269 NSURL *url([NSURL URLWithString:href]);
8271 NSStringEncoding encoding;
8272 NSError *error(nil);
8274 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8275 return [warning length] == 0 ? nil : warning;
8279 - (void) _endConnection:(NSURLConnection *)connection {
8280 // XXX: the memory management in this method is horribly awkward
8282 NSURLConnection **field = NULL;
8283 if (connection == trivial_)
8285 else if (connection == trivial_bz2_)
8286 field = &trivial_bz2_;
8287 else if (connection == trivial_gz_)
8288 field = &trivial_gz_;
8289 _assert(field != NULL);
8290 [connection release];
8295 trivial_bz2_ == nil &&
8298 [delegate_ releaseNetworkActivityIndicator];
8300 [delegate_ removeProgressHUD:hud_];
8304 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8305 UIAlertView *alert = [[[UIAlertView alloc]
8306 initWithTitle:UCLocalize("SOURCE_WARNING")
8309 cancelButtonTitle:UCLocalize("CANCEL")
8311 UCLocalize("ADD_ANYWAY"),
8315 [alert setContext:@"warning"];
8316 [alert setNumberOfRows:1];
8319 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8325 } else if (error_ != nil) {
8326 UIAlertView *alert = [[[UIAlertView alloc]
8327 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8328 message:[error_ localizedDescription]
8330 cancelButtonTitle:UCLocalize("OK")
8331 otherButtonTitles:nil
8334 [alert setContext:@"urlerror"];
8337 UIAlertView *alert = [[[UIAlertView alloc]
8338 initWithTitle:UCLocalize("NOT_REPOSITORY")
8339 message:UCLocalize("NOT_REPOSITORY_EX")
8341 cancelButtonTitle:UCLocalize("OK")
8342 otherButtonTitles:nil
8345 [alert setContext:@"trivial"];
8354 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8355 switch ([response statusCode]) {
8361 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8362 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8364 [self _endConnection:connection];
8367 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8368 [self _endConnection:connection];
8371 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8372 NSURL *url([NSURL URLWithString:href]);
8374 NSMutableURLRequest *request = [NSMutableURLRequest
8376 cachePolicy:NSURLRequestUseProtocolCachePolicy
8377 timeoutInterval:120.0
8380 [request setHTTPMethod:method];
8382 if (Machine_ != NULL)
8383 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8385 if ([url isCydiaSecure]) {
8386 if (UniqueID_ != nil) {
8387 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8388 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8392 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8395 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8396 NSString *context([alert context]);
8398 if ([context isEqualToString:@"source"]) {
8401 NSString *href = [[alert textField] text];
8403 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8405 if (![href hasSuffix:@"/"])
8406 href_ = [href stringByAppendingString:@"/"];
8410 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8411 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8412 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8413 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8417 // XXX: this is stupid
8418 hud_ = [delegate_ addProgressHUD];
8419 [hud_ setText:UCLocalize("VERIFYING_URL")];
8420 [delegate_ retainNetworkActivityIndicator];
8429 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8430 } else if ([context isEqualToString:@"trivial"])
8431 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8432 else if ([context isEqualToString:@"urlerror"])
8433 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8434 else if ([context isEqualToString:@"warning"]) {
8448 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8453 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8455 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8456 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8457 [list_ setRowHeight:53];
8458 [(UITableView *) list_ setDataSource:self];
8459 [list_ setDelegate:self];
8460 [[self view] addSubview:list_];
8463 - (void) viewDidLoad {
8464 [super viewDidLoad];
8466 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8467 [self updateButtonsForEditingStatus:NO animated:NO];
8470 - (void) releaseSubviews {
8475 [super releaseSubviews];
8478 - (id) initWithDatabase:(Database *)database {
8479 if ((self = [super init]) != nil) {
8480 database_ = database;
8484 - (void) reloadData {
8487 @synchronized (database_) {
8488 era_ = [database_ era];
8491 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8494 sources_ = [NSMutableArray arrayWithCapacity:16];
8495 [sources_ addObjectsFromArray:[database_ sources]];
8497 [sources_ sortUsingSelector:@selector(compareByName:)];
8500 int count([sources_ count]);
8502 for (int i = 0; i != count; i++) {
8503 if ([[sources_ objectAtIndex:i] record] == nil)
8508 [list_ setEditing:NO];
8509 [self updateButtonsForEditingStatus:NO animated:NO];
8513 - (void) showAddSourcePrompt {
8514 UIAlertView *alert = [[[UIAlertView alloc]
8515 initWithTitle:UCLocalize("ENTER_APT_URL")
8518 cancelButtonTitle:UCLocalize("CANCEL")
8520 UCLocalize("ADD_SOURCE"),
8524 [alert setContext:@"source"];
8526 [alert setNumberOfRows:1];
8527 [alert addTextFieldWithValue:@"http://" label:@""];
8529 UITextInputTraits *traits = [[alert textField] textInputTraits];
8530 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8531 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8532 [traits setKeyboardType:UIKeyboardTypeURL];
8533 // XXX: UIReturnKeyDone
8534 [traits setReturnKeyType:UIReturnKeyNext];
8539 - (void) addButtonClicked {
8540 [self showAddSourcePrompt];
8543 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8544 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8545 initWithTitle:UCLocalize("ADD")
8546 style:UIBarButtonItemStylePlain
8548 action:@selector(addButtonClicked)
8549 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8551 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8552 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8553 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8555 action:@selector(editButtonClicked)
8556 ] autorelease] animated:animated];
8558 if (IsWildcat_ && !editing)
8559 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8560 initWithTitle:UCLocalize("SETTINGS")
8561 style:UIBarButtonItemStylePlain
8563 action:@selector(settingsButtonClicked)
8567 - (void) settingsButtonClicked {
8568 [delegate_ showSettings];
8571 - (void) editButtonClicked {
8572 [list_ setEditing:![list_ isEditing] animated:YES];
8574 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8580 /* Settings Controller {{{ */
8581 @interface SettingsController : CyteViewController <
8582 UITableViewDataSource,
8585 _transient Database *database_;
8586 // XXX: ok, "roledelegate_"?...
8587 _transient id roledelegate_;
8588 _H<UITableView, 2> table_;
8589 _H<UISegmentedControl> segment_;
8590 _H<UIView> container_;
8593 - (void) showDoneButton;
8594 - (void) resizeSegmentedControl;
8598 @implementation SettingsController
8601 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8603 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8604 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8605 [table_ setDelegate:self];
8606 [(UITableView *) table_ setDataSource:self];
8607 [[self view] addSubview:table_];
8609 NSArray *items = [NSArray arrayWithObjects:
8611 UCLocalize("HACKER"),
8612 UCLocalize("DEVELOPER"),
8614 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8615 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8616 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8617 [container_ addSubview:segment_];
8620 - (void) viewDidLoad {
8621 [super viewDidLoad];
8623 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8626 if ([Role_ isEqualToString:@"User"]) index = 0;
8627 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8628 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8630 [segment_ setSelectedSegmentIndex:index];
8631 [self showDoneButton];
8634 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8635 [self resizeSegmentedControl];
8638 - (void) releaseSubviews {
8643 [super releaseSubviews];
8646 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8647 if ((self = [super init]) != nil) {
8648 database_ = database;
8649 roledelegate_ = delegate;
8653 - (void) resizeSegmentedControl {
8654 CGFloat width = [[self view] frame].size.width;
8655 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8658 - (void) viewWillAppear:(BOOL)animated {
8659 [super viewWillAppear:animated];
8661 [self resizeSegmentedControl];
8664 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8665 [self resizeSegmentedControl];
8668 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8669 [self resizeSegmentedControl];
8673 NSString *role(nil);
8675 switch ([segment_ selectedSegmentIndex]) {
8676 case 0: role = @"User"; break;
8677 case 1: role = @"Hacker"; break;
8678 case 2: role = @"Developer"; break;
8683 if (![role isEqualToString:Role_]) {
8684 bool rolling(Role_ == nil);
8687 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8691 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8695 [roledelegate_ loadData];
8697 [roledelegate_ updateData];
8701 - (void) segmentChanged:(UISegmentedControl *)control {
8702 [self showDoneButton];
8705 - (void) saveAndClose {
8708 [[self navigationItem] setRightBarButtonItem:nil];
8709 [[self navigationController] dismissModalViewControllerAnimated:YES];
8712 - (void) doneButtonClicked {
8713 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8714 [spinner startAnimating];
8715 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8716 [[self navigationItem] setRightBarButtonItem:spinItem];
8718 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8721 - (void) showDoneButton {
8722 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8723 initWithTitle:UCLocalize("DONE")
8724 style:UIBarButtonItemStyleDone
8726 action:@selector(doneButtonClicked)
8727 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8730 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8731 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8735 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8739 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8740 return nil; // This method is required by the protocol.
8743 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8745 return UCLocalize("ROLE_EX");
8747 return [NSString stringWithFormat:
8748 @"%@: %@\n%@: %@\n%@: %@",
8749 UCLocalize("USER"), UCLocalize("USER_EX"),
8750 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8751 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8756 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8757 return section == 3 ? 44.0f : 0;
8760 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8761 return section == 3 ? container_ : nil;
8764 - (void) reloadData {
8767 [table_ reloadData];
8772 /* Stash Controller {{{ */
8773 @interface StashController : CyteViewController {
8774 _H<UIActivityIndicatorView> spinner_;
8775 _H<UILabel> status_;
8776 _H<UILabel> caption_;
8781 @implementation StashController
8784 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8785 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8787 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8788 CGRect spinrect = [spinner_ frame];
8789 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8790 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8791 [spinner_ setFrame:spinrect];
8792 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8793 [[self view] addSubview:spinner_];
8794 [spinner_ startAnimating];
8797 captrect.size.width = [[self view] frame].size.width;
8798 captrect.size.height = 40.0f;
8799 captrect.origin.x = 0;
8800 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8801 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8802 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8803 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8804 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8805 [caption_ setTextColor:[UIColor whiteColor]];
8806 [caption_ setBackgroundColor:[UIColor clearColor]];
8807 [caption_ setShadowColor:[UIColor blackColor]];
8808 [caption_ setTextAlignment:UITextAlignmentCenter];
8809 [[self view] addSubview:caption_];
8812 statusrect.size.width = [[self view] frame].size.width;
8813 statusrect.size.height = 30.0f;
8814 statusrect.origin.x = 0;
8815 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8816 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8817 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8818 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8819 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8820 [status_ setTextColor:[UIColor whiteColor]];
8821 [status_ setBackgroundColor:[UIColor clearColor]];
8822 [status_ setShadowColor:[UIColor blackColor]];
8823 [status_ setTextAlignment:UITextAlignmentCenter];
8824 [[self view] addSubview:status_];
8827 - (void) releaseSubviews {
8832 [super releaseSubviews];
8838 @interface CYURLCache : SDURLCache {
8843 @implementation CYURLCache
8845 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8848 else if ([event isEqualToString:@"no-cache"])
8850 else if ([event isEqualToString:@"store"])
8852 else if ([event isEqualToString:@"invalid"])
8854 else if ([event isEqualToString:@"memory"])
8856 else if ([event isEqualToString:@"disk"])
8858 else if ([event isEqualToString:@"miss"])
8861 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8865 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8866 if (NSURLResponse *response = [cached response])
8867 if (NSString *mime = [response MIMEType])
8868 if ([mime isEqualToString:@"text/cache-manifest"]) {
8869 NSURL *url([response URL]);
8872 NSLog(@"###: %@", [url absoluteString]);
8875 @synchronized (HostConfig_) {
8876 [CachedURLs_ addObject:url];
8880 [super storeCachedResponse:cached forRequest:request];
8885 @interface Cydia : UIApplication <
8886 ConfirmationControllerDelegate,
8889 UINavigationControllerDelegate,
8890 UITabBarControllerDelegate
8892 _H<UIWindow> window_;
8893 _H<CYTabBarController> tabbar_;
8894 _H<CydiaLoadingViewController> emulated_;
8896 _H<NSMutableArray> essential_;
8897 _H<NSMutableArray> broken_;
8899 Database *database_;
8901 _H<NSURL> starturl_;
8906 _H<StashController> stash_;
8915 @implementation Cydia
8917 - (void) beginUpdate {
8918 [tabbar_ beginUpdate];
8922 return [tabbar_ updating];
8926 if ([broken_ count] != 0) {
8927 int count = [broken_ count];
8929 UIAlertView *alert = [[[UIAlertView alloc]
8930 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8931 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8933 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8935 UCLocalize("TEMPORARY_IGNORE"),
8939 [alert setContext:@"fixhalf"];
8940 [alert setNumberOfRows:2];
8942 } else if (!Ignored_ && [essential_ count] != 0) {
8943 int count = [essential_ count];
8945 UIAlertView *alert = [[[UIAlertView alloc]
8946 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8947 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8949 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8951 UCLocalize("UPGRADE_ESSENTIAL"),
8952 UCLocalize("COMPLETE_UPGRADE"),
8956 [alert setContext:@"upgrade"];
8961 - (void) returnToCydia {
8965 - (void) _saveConfig {
8971 NSString *error(nil);
8973 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8975 NSError *error(nil);
8976 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8977 NSLog(@"failure to save metadata data: %@", error);
8982 NSLog(@"failure to serialize metadata: %@", error);
8986 CydiaWriteSources();
8989 // Navigation controller for the queuing badge.
8990 - (UINavigationController *) queueNavigationController {
8991 NSArray *controllers = [tabbar_ viewControllers];
8992 return [controllers objectAtIndex:3];
8995 - (void) unloadData {
8996 [tabbar_ unloadData];
8999 - (void) _updateData {
9003 UINavigationController *navigation = [self queueNavigationController];
9005 id queuedelegate = nil;
9006 if ([[navigation viewControllers] count] > 0)
9007 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9009 [queuedelegate queueStatusDidChange];
9010 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9013 - (void) _refreshIfPossible:(NSDate *)update {
9014 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9016 bool recently = false;
9017 if (update != nil) {
9018 NSTimeInterval interval([update timeIntervalSinceNow]);
9019 if (interval <= 0 && interval > -(15*60))
9023 // Don't automatic refresh if:
9024 // - We already refreshed recently.
9025 // - We already auto-refreshed this launch.
9026 // - Auto-refresh is disabled.
9027 if (recently || loaded_ || ManualRefresh) {
9028 // If we are cancelling, we need to make sure it knows it's already loaded.
9031 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9033 // We are going to load, so remember that.
9036 SCNetworkReachabilityFlags flags; {
9037 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9038 SCNetworkReachabilityGetFlags(reachability, &flags);
9039 CFRelease(reachability);
9042 // XXX: this elaborate mess is what Apple is using to determine this? :(
9043 // XXX: do we care if the user has to intervene? maybe that's ok?
9045 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9046 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9047 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9048 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9049 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9050 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9054 // If we can reach the server, auto-refresh!
9056 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9062 - (void) refreshIfPossible {
9063 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9066 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9067 @synchronized (self) {
9068 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9069 [hud setText:UCLocalize("RELOADING_DATA")];
9071 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9075 [essential_ removeAllObjects];
9076 [broken_ removeAllObjects];
9078 NSArray *packages([database_ packages]);
9079 for (Package *package in packages) {
9081 [broken_ addObject:package];
9082 if ([package upgradableAndEssential:NO]) {
9083 if ([package essential])
9084 [essential_ addObject:package];
9089 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9092 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9093 [changesItem setBadgeValue:badge];
9094 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9095 [self setApplicationIconBadgeNumber:changes];
9098 [changesItem setBadgeValue:nil];
9099 [changesItem setAnimatedBadge:NO];
9100 [self setApplicationIconBadgeNumber:0];
9106 [self removeProgressHUD:hud];
9109 - (void) updateData {
9115 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9118 - (void) disemulate {
9119 if (emulated_ == nil)
9122 [window_ addSubview:[tabbar_ view]];
9123 [[emulated_ view] removeFromSuperview];
9125 [window_ setUserInteractionEnabled:YES];
9128 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9129 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9131 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9133 UIViewController *parent;
9134 if (emulated_ == nil)
9143 [parent presentModalViewController:navigation animated:YES];
9146 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9147 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9149 if (navigation != nil)
9150 [navigation pushViewController:progress animated:YES];
9152 [self presentModalViewController:progress force:YES];
9154 [progress invoke:invocation withTitle:title];
9158 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9159 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9162 - (void) repairWithInvocation:(NSInvocation *)invocation {
9164 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9168 - (void) repairWithSelector:(SEL)selector {
9169 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9172 - (void) reloadData {
9173 [self reloadDataWithInvocation:nil];
9174 if ([database_ progressDelegate] == nil)
9180 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9183 - (void) addSource:(NSDictionary *) source {
9184 CydiaAddSource(source);
9187 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9188 CydiaAddSource(href, distribution, sections);
9191 - (void) addTrivialSource:(NSString *)href {
9192 CydiaAddSource(href, @"./");
9195 - (void) updateValues {
9200 pkgProblemResolver *resolver = [database_ resolver];
9202 resolver->InstallProtect();
9203 if (!resolver->Resolve(true))
9208 // XXX: this is a really crappy way of doing this.
9209 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9210 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9211 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9212 if ([tabbar_ updating])
9213 [tabbar_ cancelUpdate];
9215 if (![database_ prepare])
9218 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9219 [page setDelegate:self];
9220 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9223 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9224 [tabbar_ presentModalViewController:confirm_ animated:YES];
9230 @synchronized (self) {
9235 - (void) clearPackage:(Package *)package {
9236 @synchronized (self) {
9243 - (void) installPackages:(NSArray *)packages {
9244 @synchronized (self) {
9245 for (Package *package in packages)
9252 - (void) installPackage:(Package *)package {
9253 @synchronized (self) {
9260 - (void) removePackage:(Package *)package {
9261 @synchronized (self) {
9268 - (void) distUpgrade {
9269 @synchronized (self) {
9270 if (![database_ upgrade])
9277 [database_ perform];
9278 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9281 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9284 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9286 [self refreshIfPossible];
9289 - (void) showSettings {
9290 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9293 - (void) retainNetworkActivityIndicator {
9294 if (activity_++ == 0)
9295 [self setNetworkActivityIndicatorVisible:YES];
9298 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9302 - (void) releaseNetworkActivityIndicator {
9303 if (--activity_ == 0)
9304 [self setNetworkActivityIndicatorVisible:NO];
9307 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9312 - (void) cancelAndClear:(bool)clear {
9313 @synchronized (self) {
9325 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9326 NSString *context([alert context]);
9328 if ([context isEqualToString:@"conffile"]) {
9329 FILE *input = [database_ input];
9330 if (button == [alert cancelButtonIndex])
9331 fprintf(input, "N\n");
9332 else if (button == [alert firstOtherButtonIndex])
9333 fprintf(input, "Y\n");
9336 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9337 } else if ([context isEqualToString:@"fixhalf"]) {
9338 if (button == [alert cancelButtonIndex]) {
9339 @synchronized (self) {
9340 for (Package *broken in (id) broken_) {
9343 NSString *id = [broken id];
9344 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9345 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9346 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9347 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9353 } else if (button == [alert firstOtherButtonIndex]) {
9354 [broken_ removeAllObjects];
9358 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9359 } else if ([context isEqualToString:@"upgrade"]) {
9360 if (button == [alert firstOtherButtonIndex]) {
9361 @synchronized (self) {
9362 for (Package *essential in (id) essential_)
9363 [essential install];
9368 } else if (button == [alert firstOtherButtonIndex] + 1) {
9370 } else if (button == [alert cancelButtonIndex]) {
9374 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9378 - (void) system:(NSString *)command {
9379 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9382 system([command UTF8String]);
9388 - (void) applicationWillSuspend {
9390 [super applicationWillSuspend];
9393 - (BOOL) isSafeToSuspend {
9396 NSLog(@"isSafeToSuspend: locked_ != 0");
9401 // Use external process status API internally.
9402 // This is probably a really bad idea.
9403 // XXX: what is the point of this? does this solve anything at all?
9404 uint64_t status = 0;
9406 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9407 notify_get_state(notify_token, &status);
9408 notify_cancel(notify_token);
9413 NSLog(@"isSafeToSuspend: status != 0");
9419 NSLog(@"isSafeToSuspend: -> true");
9424 - (void) applicationSuspend:(__GSEvent *)event {
9425 if ([self isSafeToSuspend])
9426 [super applicationSuspend:event];
9429 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9430 if ([self isSafeToSuspend])
9431 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9434 - (void) _setSuspended:(BOOL)value {
9435 if ([self isSafeToSuspend])
9436 [super _setSuspended:value];
9439 - (UIProgressHUD *) addProgressHUD {
9440 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9441 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9443 [window_ setUserInteractionEnabled:NO];
9445 UIViewController *target(tabbar_);
9446 if (UIViewController *modal = [target modalViewController])
9449 [hud showInView:[target view]];
9455 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9458 [hud removeFromSuperview];
9459 [window_ setUserInteractionEnabled:YES];
9462 - (CyteViewController *) pageForPackage:(NSString *)name {
9463 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9466 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9467 NSString *scheme([[url scheme] lowercaseString]);
9468 if ([[url absoluteString] length] <= [scheme length] + 3)
9470 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9471 NSArray *components([path componentsSeparatedByString:@"/"]);
9473 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9474 return [self pageForPackage:[components objectAtIndex:1]];
9476 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9479 NSString *base([components objectAtIndex:0]);
9481 CyteViewController *controller = nil;
9483 if ([base isEqualToString:@"url"]) {
9484 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9485 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9486 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9487 } else if (!external && [components count] == 1) {
9488 if ([base isEqualToString:@"manage"]) {
9489 controller = [[[ManageController alloc] init] autorelease];
9492 if ([base isEqualToString:@"storage"]) {
9493 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9496 if ([base isEqualToString:@"sources"]) {
9497 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9500 if ([base isEqualToString:@"home"]) {
9501 controller = [[[HomeController alloc] init] autorelease];
9504 if ([base isEqualToString:@"sections"]) {
9505 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9508 if ([base isEqualToString:@"search"]) {
9509 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9512 if ([base isEqualToString:@"changes"]) {
9513 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9516 if ([base isEqualToString:@"installed"]) {
9517 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9519 } else if ([components count] == 2) {
9520 NSString *argument = [components objectAtIndex:1];
9522 if ([base isEqualToString:@"package"]) {
9523 controller = [self pageForPackage:argument];
9526 if (!external && [base isEqualToString:@"search"]) {
9527 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9530 if (!external && [base isEqualToString:@"sections"]) {
9531 if ([argument isEqualToString:@"all"])
9533 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9536 if (!external && [base isEqualToString:@"sources"]) {
9537 if ([argument isEqualToString:@"add"]) {
9538 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9539 [(SourcesController *)controller showAddSourcePrompt];
9541 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9542 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9546 if (!external && [base isEqualToString:@"launch"]) {
9547 [self launchApplicationWithIdentifier:argument suspended:NO];
9550 } else if (!external && [components count] == 3) {
9551 NSString *arg1 = [components objectAtIndex:1];
9552 NSString *arg2 = [components objectAtIndex:2];
9554 if ([base isEqualToString:@"package"]) {
9555 if ([arg2 isEqualToString:@"settings"]) {
9556 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9557 } else if ([arg2 isEqualToString:@"files"]) {
9558 if (Package *package = [database_ packageWithName:arg1]) {
9559 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9560 [(FileTable *)controller setPackage:package];
9566 [controller setDelegate:self];
9570 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9571 CyteViewController *page([self pageForURL:url forExternal:external]);
9574 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9575 [nav setViewControllers:[NSArray arrayWithObject:page]];
9576 [tabbar_ setUnselectedViewController:nav];
9582 - (void) applicationOpenURL:(NSURL *)url {
9583 [super applicationOpenURL:url];
9588 [self openCydiaURL:url forExternal:YES];
9591 - (void) applicationWillResignActive:(UIApplication *)application {
9592 // Stop refreshing if you get a phone call or lock the device.
9593 if ([tabbar_ updating])
9594 [tabbar_ cancelUpdate];
9596 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9597 [super applicationWillResignActive:application];
9600 - (void) saveState {
9601 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9602 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9603 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9609 - (void) applicationWillTerminate:(UIApplication *)application {
9613 - (void) setConfigurationData:(NSString *)data {
9614 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9616 if (!conffile_r(data)) {
9617 lprintf("E:invalid conffile\n");
9621 NSString *ofile = conffile_r[1];
9622 //NSString *nfile = conffile_r[2];
9624 UIAlertView *alert = [[[UIAlertView alloc]
9625 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9626 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9628 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9630 UCLocalize("ACCEPT_NEW_COPY"),
9631 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9635 [alert setContext:@"conffile"];
9636 [alert setNumberOfRows:2];
9640 - (void) addStashController {
9642 stash_ = [[[StashController alloc] init] autorelease];
9643 [window_ addSubview:[stash_ view]];
9646 - (void) removeStashController {
9647 [[stash_ view] removeFromSuperview];
9653 [self setIdleTimerDisabled:YES];
9655 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9656 UpdateExternalStatus(1);
9657 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9658 UpdateExternalStatus(0);
9660 [self removeStashController];
9662 if (ExecFork() == 0) {
9663 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9664 perror("launchctl stop");
9668 - (void) setupViewControllers {
9669 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9671 NSMutableArray *items([NSMutableArray arrayWithObjects:
9672 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9673 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9674 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9675 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9679 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9680 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9682 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9685 NSMutableArray *controllers([NSMutableArray array]);
9686 for (UITabBarItem *item in items) {
9687 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9688 [controller setTabBarItem:item];
9689 [controllers addObject:controller];
9691 [tabbar_ setViewControllers:controllers];
9693 [tabbar_ setUpdateDelegate:self];
9696 - (void) _sendMemoryWarningNotification {
9697 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9700 - (void) _sendMemoryWarningNotifications {
9702 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9707 - (void) applicationDidFinishLaunching:(id)unused {
9708 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9711 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9712 [self setApplicationSupportsShakeToEdit:NO];
9714 @synchronized (HostConfig_) {
9715 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9718 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9719 initWithMemoryCapacity:524288
9720 diskCapacity:10485760
9721 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9724 [CydiaWebViewController _initialize];
9726 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9728 // this would disallow http{,s} URLs from accessing this data
9729 //[WebView registerURLSchemeAsLocal:@"cydia"];
9731 Font12_ = [UIFont systemFontOfSize:12];
9732 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9733 Font14_ = [UIFont systemFontOfSize:14];
9734 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9735 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9737 essential_ = [NSMutableArray arrayWithCapacity:4];
9738 broken_ = [NSMutableArray arrayWithCapacity:4];
9740 // XXX: I really need this thing... like, seriously... I'm sorry
9741 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9743 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9744 [window_ orderFront:self];
9745 [window_ makeKey:self];
9746 [window_ setHidden:NO];
9749 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9750 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9751 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9752 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9753 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9754 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9755 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9756 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9757 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9760 [self addStashController];
9761 // XXX: this would be much cleaner as a yieldToSelector:
9762 // that way the removeStashController could happen right here inline
9763 // we also could no longer require the useless stash_ field anymore
9764 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9768 database_ = [Database sharedInstance];
9769 [database_ setDelegate:self];
9771 [window_ setUserInteractionEnabled:NO];
9772 [self setupViewControllers];
9774 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9775 [window_ addSubview:[emulated_ view]];
9777 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9781 - (NSArray *) defaultStartPages {
9782 NSMutableArray *standard = [NSMutableArray array];
9783 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9784 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9785 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9787 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9789 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9790 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9792 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9799 [window_ setUserInteractionEnabled:YES];
9800 [self showSettings];
9803 if ([emulated_ modalViewController] != nil)
9804 [emulated_ dismissModalViewControllerAnimated:YES];
9805 [window_ setUserInteractionEnabled:NO];
9808 [self reloadDataWithInvocation:nil];
9809 [self refreshIfPossible];
9814 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9815 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9816 int standardIndex = 0;
9817 NSArray *standard = [self defaultStartPages];
9824 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9825 if (valid && closed != nil) {
9826 NSTimeInterval interval([closed timeIntervalSinceNow]);
9827 // XXX: Is 15 minutes the optimal time here?
9828 if (interval > 0 && interval <= -(15*60))
9832 if (valid && [saved count] != [standard count])
9836 for (unsigned int i = 0; i < [standard count]; i++) {
9837 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9838 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9839 // but it's good enough for now.
9840 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9847 NSArray *items = nil;
9849 [tabbar_ setSelectedIndex:savedIndex];
9852 [tabbar_ setSelectedIndex:standardIndex];
9856 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9857 NSArray *stack = [items objectAtIndex:tab];
9858 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9859 NSMutableArray *current = [NSMutableArray array];
9861 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9862 NSString *addr = [stack objectAtIndex:nav];
9863 NSURL *url = [NSURL URLWithString:addr];
9864 CyteViewController *page = [self pageForURL:url forExternal:NO];
9866 [current addObject:page];
9869 [navigation setViewControllers:current];
9872 // (Try to) show the startup URL.
9873 if (starturl_ != nil) {
9874 [self openCydiaURL:starturl_ forExternal:NO];
9879 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9880 if (item != nil && IsWildcat_) {
9881 [sheet showFromBarButtonItem:item animated:YES];
9883 [sheet showInView:window_];
9887 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9888 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9889 [progress setTitle:task];
9890 [progress addProgressEvent:event];
9893 - (void) addProgressEventForTask:(NSArray *)data {
9894 CydiaProgressEvent *event([data objectAtIndex:0]);
9895 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9896 [self addProgressEvent:event forTask:task];
9899 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9900 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9906 id Alloc_(id self, SEL selector) {
9907 id object = alloc_(self, selector);
9908 lprintf("[%s]A-%p\n", self->isa->name, object);
9913 id Dealloc_(id self, SEL selector) {
9914 id object = dealloc_(self, selector);
9915 lprintf("[%s]D-%p\n", self->isa->name, object);
9919 Class $WebDefaultUIKitDelegate;
9921 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9922 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9923 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9924 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9927 static NSSet *MobilizedFiles_;
9929 static NSURL *MobilizeURL(NSURL *url) {
9930 NSString *path([url path]);
9931 if ([path hasPrefix:@"/var/root/"]) {
9932 NSString *file([path substringFromIndex:10]);
9933 if ([MobilizedFiles_ containsObject:file])
9934 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9940 Class $CFXPreferencesPropertyListSource;
9941 @class CFXPreferencesPropertyListSource;
9943 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9944 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9945 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9946 url = MobilizeURL(url);
9947 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9948 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9954 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9955 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9956 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9957 url = MobilizeURL(url);
9958 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9959 //NSLog(@"%@ %@", [url absoluteString], value);
9965 Class $NSURLConnection;
9967 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9968 NSMutableURLRequest *copy([request mutableCopy]);
9970 NSURL *url([copy URL]);
9972 NSString *href([url absoluteString]);
9973 NSString *host([url host]);
9974 NSString *scheme([[url scheme] lowercaseString]);
9976 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9978 @synchronized (HostConfig_) {
9979 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9980 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9981 [copy setHTTPShouldUsePipelining:YES];
9983 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9984 if ([control isEqualToString:@"max-age=0"])
9985 if ([CachedURLs_ containsObject:href]) {
9987 NSLog(@"~~~: %@", href);
9990 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9992 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9993 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9994 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9998 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10002 int main(int argc, char *argv[]) {
10003 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10007 UpdateExternalStatus(0);
10009 if (Class $UIDevice = objc_getClass("UIDevice")) {
10010 UIDevice *device([$UIDevice currentDevice]);
10011 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10013 IsWildcat_ = false;
10015 UIScreen *screen([UIScreen mainScreen]);
10016 if ([screen respondsToSelector:@selector(scale)])
10017 ScreenScale_ = [screen scale];
10021 UIDevice *device([UIDevice currentDevice]);
10022 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10023 Idiom_ = @"iphone";
10025 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10026 if (idiom == UIUserInterfaceIdiomPhone)
10027 Idiom_ = @"iphone";
10028 else if (idiom == UIUserInterfaceIdiomPad)
10031 NSLog(@"unknown UIUserInterfaceIdiom!");
10034 Pcre pattern("^([0-9]+\\.[0-9]+)");
10036 if (pattern([device systemVersion]))
10037 Firmware_ = pattern[1];
10038 if (pattern(Cydia_))
10039 Major_ = pattern[1];
10041 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10043 HostConfig_ = [[[NSObject alloc] init] autorelease];
10044 @synchronized (HostConfig_) {
10045 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10046 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10047 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10048 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10049 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10052 NSString *ui(@"ui/ios");
10054 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10055 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10056 UI_ = CydiaURL(ui);
10058 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10060 MobilizedFiles_ = [NSMutableSet setWithObjects:
10061 @"Library/Preferences/com.apple.Accessibility.plist",
10062 @"Library/Preferences/com.apple.preferences.sounds.plist",
10065 /* Library Hacks {{{ */
10066 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10068 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10070 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10071 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10072 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10073 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10076 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10077 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10078 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10079 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10082 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10083 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10084 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10085 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10086 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10089 $NSURLConnection = objc_getClass("NSURLConnection");
10090 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10091 if (NSURLConnection$init$ != NULL) {
10092 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10093 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10096 /* Set Locale {{{ */
10097 Locale_ = CFLocaleCopyCurrent();
10098 Languages_ = [NSLocale preferredLanguages];
10100 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10101 //NSLog(@"%@", [Languages_ description]);
10104 if (Locale_ != NULL)
10105 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10106 else if (Languages_ != nil && [Languages_ count] != 0)
10107 lang = [[Languages_ objectAtIndex:0] UTF8String];
10109 // XXX: consider just setting to C and then falling through?
10112 if (lang != NULL) {
10113 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10114 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10117 NSLog(@"Setting Language: %s", lang);
10119 if (lang != NULL) {
10120 setenv("LANG", lang, true);
10121 std::setlocale(LC_ALL, lang);
10125 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10127 /* Parse Arguments {{{ */
10128 bool substrate(false);
10134 for (int argi(1); argi != argc; ++argi)
10135 if (strcmp(argv[argi], "--") == 0) {
10137 argv[argi] = argv[0];
10143 for (int argi(1); argi != arge; ++argi)
10144 if (strcmp(args[argi], "--substrate") == 0)
10147 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10151 App_ = [[NSBundle mainBundle] bundlePath];
10157 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10158 alloc_ = alloc->method_imp;
10159 alloc->method_imp = (IMP) &Alloc_;*/
10161 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10162 dealloc_ = dealloc->method_imp;
10163 dealloc->method_imp = (IMP) &Dealloc_;*/
10165 /* System Information {{{ */
10169 size = sizeof(maxproc);
10170 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10171 perror("sysctlbyname(\"kern.maxproc\", ?)");
10172 else if (maxproc < 64) {
10174 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10175 perror("sysctlbyname(\"kern.maxproc\", #)");
10178 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10179 char *osversion = new char[size];
10180 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10181 perror("sysctlbyname(\"kern.osversion\", ?)");
10183 System_ = [NSString stringWithUTF8String:osversion];
10185 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10186 char *machine = new char[size];
10187 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10188 perror("sysctlbyname(\"hw.machine\", ?)");
10190 Machine_ = machine;
10192 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10193 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10194 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10196 UniqueID_ = [device uniqueIdentifier];
10198 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10199 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10200 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10202 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10203 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10204 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10206 if (mcc != NULL && mnc != NULL)
10207 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10214 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10215 Build_ = [system objectForKey:@"ProductBuildVersion"];
10216 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10217 Product_ = [info objectForKey:@"SafariProductVersion"];
10218 Safari_ = [info objectForKey:@"CFBundleVersion"];
10221 /* Load Database {{{ */
10223 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10225 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10227 if (Metadata_ == NULL)
10228 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10230 Settings_ = [Metadata_ objectForKey:@"Settings"];
10232 Packages_ = [Metadata_ objectForKey:@"Packages"];
10234 Values_ = [Metadata_ objectForKey:@"Values"];
10235 Sections_ = [Metadata_ objectForKey:@"Sections"];
10236 Sources_ = [Metadata_ objectForKey:@"Sources"];
10238 Token_ = [Metadata_ objectForKey:@"Token"];
10240 Version_ = [Metadata_ objectForKey:@"Version"];
10242 @synchronized (HostConfig_) {
10243 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10247 if (Settings_ != nil)
10248 Role_ = [Settings_ objectForKey:@"Role"];
10250 if (Values_ == nil) {
10251 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10252 [Metadata_ setObject:Values_ forKey:@"Values"];
10255 if (Sections_ == nil) {
10256 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10257 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10260 if (Sources_ == nil) {
10261 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10262 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10265 if (Version_ == nil) {
10266 Version_ = [NSNumber numberWithUnsignedInt:0];
10267 [Metadata_ setObject:Version_ forKey:@"Version"];
10270 @synchronized (HostConfig_) {
10271 if (CydiaSource_ == nil) {
10272 CydiaSource_ = @"apt.saurik.com";
10273 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10277 if ([Version_ unsignedIntValue] == 0) {
10278 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10279 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10280 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10281 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10283 Version_ = [NSNumber numberWithUnsignedInt:1];
10284 [Metadata_ setObject:Version_ forKey:@"Version"];
10286 [Metadata_ removeObjectForKey:@"LastUpdate"];
10292 CydiaWriteSources();
10295 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10298 if (Packages_ != nil) {
10300 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10304 [Metadata_ removeObjectForKey:@"Packages"];
10310 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10312 #define MobileSubstrate_(name) \
10313 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10314 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10315 if (handle == NULL) \
10316 NSLog(@"%s", dlerror()); \
10319 MobileSubstrate_(Activator)
10320 MobileSubstrate_(libstatusbar)
10321 MobileSubstrate_(SimulatedKeyEvents)
10322 MobileSubstrate_(WinterBoard)
10324 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10325 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10327 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10329 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10330 unlink("/tmp/.cydia.fw");
10332 } else if (access("/User", F_OK) != 0 || version < 4) {
10335 system("/usr/libexec/cydia/firmware.sh");
10339 _assert([[NSFileManager defaultManager]
10340 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10341 withIntermediateDirectories:YES
10346 if (access("/tmp/cydia.chk", F_OK) == 0) {
10347 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10348 _assert(errno == ENOENT);
10349 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10350 _assert(errno == ENOENT);
10353 /* APT Initialization {{{ */
10354 _assert(pkgInitConfig(*_config));
10355 _assert(pkgInitSystem(*_config, _system));
10358 _config->Set("APT::Acquire::Translation", lang);
10360 // XXX: this timeout might be important :(
10361 //_config->Set("Acquire::http::Timeout", 15);
10363 _config->Set("Acquire::http::MaxParallel", 3);
10365 /* Color Choices {{{ */
10366 space_ = CGColorSpaceCreateDeviceRGB();
10368 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10369 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10370 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10371 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10372 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10373 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10374 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10375 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10376 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10378 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10379 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10381 /* UIKit Configuration {{{ */
10382 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10383 if ($GSFontSetUseLegacyFontMetrics != NULL)
10384 $GSFontSetUseLegacyFontMetrics(YES);
10386 // XXX: I have a feeling this was important
10387 //UIKeyboardDisableAutomaticAppearance();
10390 Colon_ = UCLocalize("COLON_DELIMITED");
10391 Elision_ = UCLocalize("ELISION");
10392 Error_ = UCLocalize("ERROR");
10393 Warning_ = UCLocalize("WARNING");
10396 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10398 CGColorSpaceRelease(space_);
10399 CFRelease(Locale_);