1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
209 #define Cydia_ CYDIA_VERSION
211 #define lprintf(args...) fprintf(stderr, args)
214 #define TraceLogging (1 && !ForRelease)
215 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
216 #define ProfileTimes (0 && !ForRelease)
217 #define ForSaurik (0 && !ForRelease)
218 #define LogBrowser (0 && !ForRelease)
219 #define TrackResize (0 && !ForRelease)
220 #define ManualRefresh (1 && !ForRelease)
221 #define ShowInternals (0 && !ForRelease)
222 #define AlwaysReload (0 && !ForRelease)
223 #define TryIndexedCollation (0 && !ForRelease)
227 #define _trace(args...)
232 #define _profile(name) {
235 #define PrintTimes() do {} while (false)
238 // Hash Functions/Structures {{{
239 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
247 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
249 static _finline NSString *CydiaURL(NSString *path) {
251 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
252 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
253 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
254 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
255 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
257 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
260 static _finline void UpdateExternalStatus(uint64_t newStatus) {
262 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
263 notify_set_state(notify_token, newStatus);
264 notify_cancel(notify_token);
266 notify_post("com.saurik.Cydia.status");
269 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
270 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
271 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
274 /* NSForcedOrderingSearch doesn't work on the iPhone */
275 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
276 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
277 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
279 /* Insertion Sort {{{ */
281 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
282 const char *ptr = (const char *)list;
284 CFIndex half = count / 2;
285 const char *probe = ptr + elementSize * half;
286 CFComparisonResult cr = comparator(element, probe, context);
287 if (0 == cr) return (probe - (const char *)list) / elementSize;
288 ptr = (cr < 0) ? ptr : probe + elementSize;
289 count = (cr < 0) ? half : (half + (count & 1) - 1);
291 return (ptr - (const char *)list) / elementSize;
294 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
295 const char *ptr = (const char *)list;
297 CFIndex half = count / 2;
298 const char *probe = ptr + elementSize * half;
299 CFComparisonResult cr = comparator(element, probe, context);
300 if (0 == cr) return (probe - (const char *)list) / elementSize;
301 ptr = (cr < 0) ? ptr : probe + elementSize;
302 count = (cr < 0) ? half : (half + (count & 1) - 1);
304 return (ptr - (const char *)list) / elementSize;
307 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
308 if (range.length == 0)
310 const void **values(new const void *[range.length]);
311 CFArrayGetValues(array, range, values);
313 #if HistogramInsertionSort > 0
314 uint32_t total(0), *offsets(new uint32_t[range.length]);
317 for (CFIndex index(1); index != range.length; ++index) {
318 const void *value(values[index]);
319 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
320 CFIndex correct(index);
321 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
322 #if HistogramInsertionSort > 1
323 NSLog(@"%@ < %@", value, values[correct - 1]);
328 if (correct != index) {
329 size_t offset(index - correct);
330 #if HistogramInsertionSort
334 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
336 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
337 values[correct] = value;
341 CFArrayReplaceValues(array, range, values, range.length);
344 #if HistogramInsertionSort > 0
345 for (CFIndex index(0); index != range.length; ++index)
346 if (offsets[index] != 0)
347 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
348 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
355 /* Apple Bug Fixes {{{ */
356 @implementation UIWebDocumentView (Cydia)
358 - (void) _setScrollerOffset:(CGPoint)offset {
359 UIScroller *scroller([self _scroller]);
361 CGSize size([scroller contentSize]);
362 CGSize bounds([scroller bounds].size);
365 max.x = size.width - bounds.width;
366 max.y = size.height - bounds.height;
374 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
375 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
377 [scroller setOffset:offset];
383 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
384 size_t length([self length] - state->state);
387 else if (length > count)
389 for (size_t i(0); i != length; ++i)
390 objects[i] = [self item:state->state++];
391 state->itemsPtr = objects;
392 state->mutationsPtr = (unsigned long *) self;
396 /* Cydia NSString Additions {{{ */
397 @interface NSString (Cydia)
398 - (NSComparisonResult) compareByPath:(NSString *)other;
399 - (NSString *) stringByCachingURLWithCurrentCDN;
400 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
403 @implementation NSString (Cydia)
405 - (NSComparisonResult) compareByPath:(NSString *)other {
406 NSString *prefix = [self commonPrefixWithString:other options:0];
407 size_t length = [prefix length];
409 NSRange lrange = NSMakeRange(length, [self length] - length);
410 NSRange rrange = NSMakeRange(length, [other length] - length);
412 lrange = [self rangeOfString:@"/" options:0 range:lrange];
413 rrange = [other rangeOfString:@"/" options:0 range:rrange];
415 NSComparisonResult value;
417 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
418 value = NSOrderedSame;
419 else if (lrange.location == NSNotFound)
420 value = NSOrderedAscending;
421 else if (rrange.location == NSNotFound)
422 value = NSOrderedDescending;
424 value = NSOrderedSame;
426 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
427 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
428 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
429 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
431 NSComparisonResult result = [lpath compare:rpath];
432 return result == NSOrderedSame ? value : result;
435 - (NSString *) stringByCachingURLWithCurrentCDN {
437 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
438 withString:@"://cache.cydia.saurik.com/"
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 *Sections_;
700 static _transient NSMutableDictionary *Sources_;
701 static bool Changed_;
705 static CGFloat ScreenScale_;
706 static NSString *Idiom_;
708 static _H<NSMutableDictionary> SessionData_;
709 static _H<NSObject> HostConfig_;
710 static _H<NSMutableSet> BridgedHosts_;
711 static _H<NSMutableSet> PipelinedHosts_;
712 static _H<NSMutableSet> CachedURLs_;
714 static NSString *kCydiaProgressEventTypeError = @"Error";
715 static NSString *kCydiaProgressEventTypeInformation = @"Information";
716 static NSString *kCydiaProgressEventTypeStatus = @"Status";
717 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
720 /* Display Helpers {{{ */
721 inline float Interpolate(float begin, float end, float fraction) {
722 return (end - begin) * fraction + begin;
725 static _finline const char *StripVersion_(const char *version) {
726 const char *colon(strchr(version, ':'));
727 return colon == NULL ? version : colon + 1;
730 NSString *LocalizeSection(NSString *section) {
731 static Pcre title_r("^(.*?) \\((.*)\\)$");
732 if (title_r(section)) {
733 NSString *parent(title_r[1]);
734 NSString *child(title_r[2]);
736 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
737 LocalizeSection(parent),
738 LocalizeSection(child)
742 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
745 NSString *Simplify(NSString *title) {
746 const char *data = [title UTF8String];
747 size_t size = [title length];
749 static Pcre square_r("^\\[(.*)\\]$");
750 if (square_r(data, size))
751 return Simplify(square_r[1]);
753 static Pcre paren_r("^\\((.*)\\)$");
754 if (paren_r(data, size))
755 return Simplify(paren_r[1]);
757 static Pcre title_r("^(.*?) \\((.*)\\)$");
758 if (title_r(data, size))
759 return Simplify(title_r[1]);
765 NSString *GetLastUpdate() {
766 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
769 return UCLocalize("NEVER_OR_UNKNOWN");
771 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
772 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
774 CFRelease(formatter);
776 return [(NSString *) formatted autorelease];
779 bool isSectionVisible(NSString *section) {
780 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
781 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
782 return hidden == nil || ![hidden boolValue];
785 static NSObject *CYIOGetValue(const char *path, NSString *property) {
786 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
787 if (entry == MACH_PORT_NULL)
790 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
791 IOObjectRelease(entry);
795 return [(id) value autorelease];
798 static NSString *CYHex(NSData *data, bool reverse = false) {
802 size_t length([data length]);
803 uint8_t bytes[length];
804 [data getBytes:bytes];
806 char string[length * 2 + 1];
807 for (size_t i(0); i != length; ++i)
808 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
810 return [NSString stringWithUTF8String:string];
815 /* Delegate Prototypes {{{ */
818 @class CydiaProgressEvent;
820 @protocol DatabaseDelegate
821 - (void) repairWithSelector:(SEL)selector;
822 - (void) setConfigurationData:(NSString *)data;
823 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
826 @class CYPackageController;
828 @protocol CydiaDelegate
829 - (void) retainNetworkActivityIndicator;
830 - (void) releaseNetworkActivityIndicator;
831 - (void) clearPackage:(Package *)package;
832 - (void) installPackage:(Package *)package;
833 - (void) installPackages:(NSArray *)packages;
834 - (void) removePackage:(Package *)package;
835 - (void) beginUpdate;
837 - (void) distUpgrade;
841 - (void) addTrivialSource:(NSString *)href;
842 - (void) showSettings;
843 - (UIProgressHUD *) addProgressHUD;
844 - (void) removeProgressHUD:(UIProgressHUD *)hud;
845 - (CyteViewController *) pageForPackage:(NSString *)name;
846 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
847 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
851 /* Status Delegation {{{ */
853 public pkgAcquireStatus
856 _transient NSObject<ProgressDelegate> *delegate_;
866 void setDelegate(NSObject<ProgressDelegate> *delegate) {
867 delegate_ = delegate;
870 NSObject<ProgressDelegate> *getDelegate() const {
874 virtual bool MediaChange(std::string media, std::string drive) {
878 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
881 virtual void Fetch(pkgAcquire::ItemDesc &item) {
882 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
883 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
884 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
887 virtual void Done(pkgAcquire::ItemDesc &item) {
890 virtual void Fail(pkgAcquire::ItemDesc &item) {
892 item.Owner->Status == pkgAcquire::Item::StatIdle ||
893 item.Owner->Status == pkgAcquire::Item::StatDone
897 std::string &error(item.Owner->ErrorText);
901 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
902 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
905 virtual bool Pulse(pkgAcquire *Owner) {
906 bool value = pkgAcquireStatus::Pulse(Owner);
909 double(CurrentBytes + CurrentItems) /
910 double(TotalBytes + TotalItems)
913 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
914 [NSNumber numberWithDouble:percent], @"Percent",
916 [NSNumber numberWithDouble:CurrentBytes], @"Current",
917 [NSNumber numberWithDouble:TotalBytes], @"Total",
918 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
919 nil] waitUntilDone:YES];
921 if (value && ![delegate_ isProgressCancelled])
929 _finline bool WasCancelled() const {
933 virtual void Start() {
934 pkgAcquireStatus::Start();
935 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
938 virtual void Stop() {
939 pkgAcquireStatus::Stop();
940 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
941 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
945 /* Database Interface {{{ */
946 typedef std::map< unsigned long, _H<Source> > SourceMap;
948 @interface Database : NSObject {
955 pkgDepCache::Policy *policy_;
956 pkgRecords *records_;
957 pkgProblemResolver *resolver_;
958 pkgAcquire *fetcher_;
960 SPtr<pkgPackageManager> manager_;
961 pkgSourceList *list_;
963 SourceMap sourceMap_;
964 _H<NSMutableArray> sourceList_;
966 CFMutableArrayRef packages_;
968 _transient NSObject<DatabaseDelegate> *delegate_;
969 _transient NSObject<ProgressDelegate> *progress_;
977 std::map<const char *, _H<NSString> > sections_;
980 + (Database *) sharedInstance;
983 - (void) _readCydia:(NSNumber *)fd;
984 - (void) _readStatus:(NSNumber *)fd;
985 - (void) _readOutput:(NSNumber *)fd;
989 - (Package *) packageWithName:(NSString *)name;
991 - (pkgCacheFile &) cache;
992 - (pkgDepCache::Policy *) policy;
993 - (pkgRecords *) records;
994 - (pkgProblemResolver *) resolver;
995 - (pkgAcquire &) fetcher;
996 - (pkgSourceList &) list;
997 - (NSArray *) packages;
998 - (NSArray *) sources;
999 - (Source *) sourceWithKey:(NSString *)key;
1000 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1008 - (void) updateWithStatus:(Status &)status;
1010 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1012 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1013 - (NSObject<ProgressDelegate> *) progressDelegate;
1015 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1017 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1021 /* ProgressEvent Implementation {{{ */
1022 @implementation CydiaProgressEvent
1024 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1025 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1028 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1029 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1030 [event setPackage:package];
1034 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1035 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1037 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1038 NSArray *fields([description componentsSeparatedByString:@" "]);
1039 [event setItem:fields];
1041 if ([fields count] > 3) {
1042 [event setPackage:[fields objectAtIndex:2]];
1043 [event setVersion:[fields objectAtIndex:3]];
1046 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1051 + (NSArray *) _attributeKeys {
1052 return [NSArray arrayWithObjects:
1062 - (NSArray *) attributeKeys {
1063 return [[self class] _attributeKeys];
1066 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1067 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1070 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1071 if ((self = [super init]) != nil) {
1077 - (NSString *) message {
1081 - (NSString *) type {
1085 - (NSArray *) item {
1086 return (id) item_ ?: [NSNull null];
1089 - (void) setItem:(NSArray *)item {
1093 - (NSString *) package {
1094 return (id) package_ ?: [NSNull null];
1097 - (void) setPackage:(NSString *)package {
1101 - (NSString *) url {
1102 return (id) url_ ?: [NSNull null];
1105 - (void) setURL:(NSString *)url {
1109 - (void) setVersion:(NSString *)version {
1113 - (NSString *) version {
1114 return (id) version_ ?: [NSNull null];
1117 - (NSString *) compound:(NSString *)value {
1119 NSString *mode(nil); {
1120 NSString *type([self type]);
1121 if ([type isEqualToString:kCydiaProgressEventTypeError])
1122 mode = UCLocalize("ERROR");
1123 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1124 mode = UCLocalize("WARNING");
1128 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1134 - (NSString *) compoundMessage {
1135 return [self compound:[self message]];
1138 - (NSString *) compoundTitle {
1141 if (package_ == nil)
1143 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1144 title = [package name];
1148 return [self compound:title];
1154 // Cytore Definitions {{{
1155 struct PackageValue :
1158 Cytore::Offset<PackageValue> next_;
1160 uint32_t index_ : 23;
1161 uint32_t subscribed_ : 1;
1178 Cytore::Offset<PackageValue> packages_[1 << 16];
1181 static Cytore::File<MetaValue> MetaFile_;
1183 // Cytore Helper Functions {{{
1184 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1185 SplitHash nhash = { hashlittle(name, length) };
1187 PackageValue *metadata;
1189 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1190 offset: if (offset->IsNull()) {
1191 *offset = MetaFile_.New<PackageValue>(length + 1);
1192 metadata = &MetaFile_.Get(*offset);
1194 if (metadata == NULL) {
1198 metadata = new PackageValue();
1199 memset(metadata, 0, sizeof(*metadata));
1202 memcpy(metadata->name_, name, length + 1);
1203 metadata->nhash_ = nhash.u16[1];
1205 metadata = &MetaFile_.Get(*offset);
1207 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1208 offset = &metadata->next_;
1216 static void PackageImport(const void *key, const void *value, void *context) {
1217 bool &fail(*reinterpret_cast<bool *>(context));
1220 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1221 NSLog(@"failed to import package %@", key);
1225 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1226 NSDictionary *package((NSDictionary *) value);
1228 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1229 if ([subscribed boolValue] && !metadata->subscribed_)
1230 metadata->subscribed_ = true;
1232 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1233 time_t time([date timeIntervalSince1970]);
1234 if (metadata->first_ > time || metadata->first_ == 0)
1235 metadata->first_ = time;
1238 NSDate *date([package objectForKey:@"LastSeen"]);
1239 NSString *version([package objectForKey:@"LastVersion"]);
1241 if (date != nil && version != nil) {
1242 time_t time([date timeIntervalSince1970]);
1243 if (metadata->last_ < time || metadata->last_ == 0)
1244 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1245 size_t length(strlen(buffer));
1246 uint16_t vhash(hashlittle(buffer, length));
1248 size_t capped(std::min<size_t>(8, length));
1249 char *latest(buffer + length - capped);
1251 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1252 metadata->vhash_ = vhash;
1254 metadata->last_ = time;
1260 /* Source Class {{{ */
1261 @interface Source : NSObject {
1262 CYString depiction_;
1263 CYString description_;
1269 CYString distribution_;
1275 _H<NSString> authority_;
1277 CYString defaultIcon_;
1279 _H<NSDictionary> record_;
1283 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1285 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1287 - (NSString *) depictionForPackage:(NSString *)package;
1288 - (NSString *) supportForPackage:(NSString *)package;
1290 - (NSDictionary *) record;
1294 - (NSString *) distribution;
1295 - (NSString *) type;
1297 - (NSString *) base;
1300 - (NSString *) host;
1302 - (NSString *) name;
1303 - (NSString *) shortDescription;
1304 - (NSString *) label;
1305 - (NSString *) origin;
1306 - (NSString *) version;
1308 - (NSString *) defaultIcon;
1312 @implementation Source
1316 distribution_.clear();
1321 description_.clear();
1327 defaultIcon_.clear();
1334 + (NSArray *) _attributeKeys {
1335 return [NSArray arrayWithObjects:
1342 @"shortDescription",
1350 - (NSArray *) attributeKeys {
1351 return [[self class] _attributeKeys];
1354 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1355 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1358 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1361 trusted_ = index->IsTrusted();
1363 uri_.set(pool, index->GetURI());
1364 distribution_.set(pool, index->GetDist());
1365 type_.set(pool, index->GetType());
1367 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1368 if (dindex != NULL) {
1369 base_.set(pool, dindex->MetaIndexURI(""));
1372 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1375 pkgTagFile tags(&fd);
1377 pkgTagSection section;
1384 {"default-icon", &defaultIcon_},
1385 {"depiction", &depiction_},
1386 {"description", &description_},
1388 {"origin", &origin_},
1389 {"support", &support_},
1390 {"version", &version_},
1393 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1394 const char *start, *end;
1396 if (section.Find(names[i].name_, start, end)) {
1397 CYString &value(*names[i].value_);
1398 value.set(pool, start, end - start);
1404 record_ = [Sources_ objectForKey:[self key]];
1406 NSURL *url([NSURL URLWithString:uri_]);
1410 host_ = [host_ lowercaseString];
1415 authority_ = [url path];
1418 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1419 if ((self = [super init]) != nil) {
1420 [self setMetaIndex:index inPool:pool];
1424 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1425 NSDictionary *lhr = [self record];
1426 NSDictionary *rhr = [source record];
1429 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1431 NSString *lhs = [self name];
1432 NSString *rhs = [source name];
1434 if ([lhs length] != 0 && [rhs length] != 0) {
1435 unichar lhc = [lhs characterAtIndex:0];
1436 unichar rhc = [rhs characterAtIndex:0];
1438 if (isalpha(lhc) && !isalpha(rhc))
1439 return NSOrderedAscending;
1440 else if (!isalpha(lhc) && isalpha(rhc))
1441 return NSOrderedDescending;
1444 return [lhs compare:rhs options:LaxCompareOptions_];
1447 - (NSString *) depictionForPackage:(NSString *)package {
1448 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1451 - (NSString *) supportForPackage:(NSString *)package {
1452 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1455 - (NSDictionary *) record {
1463 - (NSString *) uri {
1467 - (NSString *) distribution {
1468 return distribution_;
1471 - (NSString *) type {
1475 - (NSString *) base {
1479 - (NSString *) key {
1480 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1483 - (NSString *) host {
1487 - (NSString *) name {
1488 return origin_.empty() ? (id) authority_ : origin_;
1491 - (NSString *) shortDescription {
1492 return description_;
1495 - (NSString *) label {
1496 return label_.empty() ? (id) authority_ : label_;
1499 - (NSString *) origin {
1503 - (NSString *) version {
1507 - (NSString *) defaultIcon {
1508 return defaultIcon_;
1513 /* CydiaOperation Class {{{ */
1514 @interface CydiaOperation : NSObject {
1515 _H<NSString> operator_;
1516 _H<NSString> value_;
1519 - (NSString *) operator;
1520 - (NSString *) value;
1524 @implementation CydiaOperation
1526 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1527 if ((self = [super init]) != nil) {
1528 operator_ = [NSString stringWithUTF8String:_operator];
1529 value_ = [NSString stringWithUTF8String:value];
1533 + (NSArray *) _attributeKeys {
1534 return [NSArray arrayWithObjects:
1540 - (NSArray *) attributeKeys {
1541 return [[self class] _attributeKeys];
1544 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1545 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1548 - (NSString *) operator {
1552 - (NSString *) value {
1558 /* CydiaClause Class {{{ */
1559 @interface CydiaClause : NSObject {
1560 _H<NSString> package_;
1561 _H<CydiaOperation> version_;
1564 - (NSString *) package;
1565 - (CydiaOperation *) version;
1569 @implementation CydiaClause
1571 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1572 if ((self = [super init]) != nil) {
1573 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1575 if (const char *version = dep.TargetVer())
1576 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1578 version_ = (id) [NSNull null];
1582 + (NSArray *) _attributeKeys {
1583 return [NSArray arrayWithObjects:
1589 - (NSArray *) attributeKeys {
1590 return [[self class] _attributeKeys];
1593 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1594 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1597 - (NSString *) package {
1601 - (CydiaOperation *) version {
1607 /* CydiaRelation Class {{{ */
1608 @interface CydiaRelation : NSObject {
1609 _H<NSString> relationship_;
1610 _H<NSMutableArray> clauses_;
1613 - (NSString *) relationship;
1614 - (NSArray *) clauses;
1618 @implementation CydiaRelation
1620 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1621 if ((self = [super init]) != nil) {
1622 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1623 clauses_ = [NSMutableArray arrayWithCapacity:8];
1625 pkgCache::DepIterator start;
1626 pkgCache::DepIterator end;
1627 dep.GlobOr(start, end); // ++dep
1630 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1632 // yes, seriously. (wtf?)
1640 + (NSArray *) _attributeKeys {
1641 return [NSArray arrayWithObjects:
1647 - (NSArray *) attributeKeys {
1648 return [[self class] _attributeKeys];
1651 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1652 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1655 - (NSString *) relationship {
1656 return relationship_;
1659 - (NSArray *) clauses {
1663 - (void) addClause:(CydiaClause *)clause {
1664 [clauses_ addObject:clause];
1669 /* Package Class {{{ */
1670 struct ParsedPackage {
1675 CYString depiction_;
1685 @interface Package : NSObject {
1688 uint32_t essential_ : 1;
1689 uint32_t obsolete_ : 1;
1690 uint32_t ignored_ : 1;
1696 _transient Database *database_;
1698 pkgCache::VerIterator version_;
1699 pkgCache::PkgIterator iterator_;
1700 pkgCache::VerFileIterator file_;
1706 CYString installed_;
1708 const char *section_;
1709 _transient NSString *section$_;
1713 PackageValue *metadata_;
1714 ParsedPackage *parsed_;
1716 _H<NSMutableArray> tags_;
1719 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1720 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1722 - (pkgCache::PkgIterator) iterator;
1725 - (NSString *) section;
1726 - (NSString *) simpleSection;
1728 - (NSString *) longSection;
1729 - (NSString *) shortSection;
1733 - (MIMEAddress *) maintainer;
1735 - (NSString *) longDescription;
1736 - (NSString *) shortDescription;
1739 - (PackageValue *) metadata;
1742 - (bool) subscribed;
1743 - (bool) setSubscribed:(bool)subscribed;
1747 - (NSString *) latest;
1748 - (NSString *) installed;
1749 - (BOOL) uninstalled;
1752 - (BOOL) upgradableAndEssential:(BOOL)essential;
1755 - (BOOL) unfiltered;
1759 - (BOOL) halfConfigured;
1760 - (BOOL) halfInstalled;
1762 - (NSString *) mode;
1765 - (NSString *) name;
1767 - (NSString *) homepage;
1768 - (NSString *) depiction;
1769 - (MIMEAddress *) author;
1771 - (NSString *) support;
1773 - (NSArray *) files;
1774 - (NSArray *) warnings;
1775 - (NSArray *) applications;
1777 - (Source *) source;
1780 - (BOOL) matches:(NSArray *)query;
1782 - (bool) hasSupportingRole;
1783 - (BOOL) hasTag:(NSString *)tag;
1784 - (NSString *) primaryPurpose;
1785 - (NSArray *) purposes;
1786 - (bool) isCommercial;
1788 - (void) setIndex:(size_t)index;
1790 - (CYString &) cyname;
1792 - (uint32_t) compareBySection:(NSArray *)sections;
1797 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1798 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1799 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1800 - (bool) isVisibleInSection:(NSString *)section;
1801 - (bool) isVisibleInSource:(Source *)source;
1805 uint32_t PackageChangesRadix(Package *self, void *) {
1810 uint32_t timestamp : 30;
1811 uint32_t ignored : 1;
1812 uint32_t upgradable : 1;
1816 bool upgradable([self upgradableAndEssential:YES]);
1817 value.bits.upgradable = upgradable ? 1 : 0;
1820 value.bits.timestamp = 0;
1821 value.bits.ignored = [self ignored] ? 0 : 1;
1822 value.bits.upgradable = 1;
1824 value.bits.timestamp = [self seen] >> 2;
1825 value.bits.ignored = 0;
1826 value.bits.upgradable = 0;
1829 return _not(uint32_t) - value.key;
1832 uint32_t PackagePrefixRadix(Package *self, void *context) {
1833 size_t offset(reinterpret_cast<size_t>(context));
1834 CYString &name([self cyname]);
1836 size_t size(name.size());
1839 char *text(name.data());
1842 if (!isdigit(text[0]))
1846 while (size != digits && isdigit(text[digits]))
1854 if (offset == 0 && zeros != 0) {
1855 memset(data, '0', zeros);
1856 memcpy(data + zeros, text, 4 - zeros);
1858 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1859 if (size <= offset - zeros)
1862 text += offset - zeros;
1863 size -= offset - zeros;
1866 memcpy(data, text, 4);
1868 memcpy(data, text, size);
1869 memset(data + size, 0, 4 - size);
1872 for (size_t i(0); i != 4; ++i)
1873 if (isalpha(data[i]))
1881 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1883 /* XXX: ntohl may be more honest */
1884 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1887 CYString &(*PackageName)(Package *self, SEL sel);
1889 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1890 _profile(PackageNameCompare)
1891 CYString &lhi(PackageName(lhs, @selector(cyname)));
1892 CYString &rhi(PackageName(rhs, @selector(cyname)));
1893 CFStringRef lhn(lhi), rhn(rhi);
1896 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1897 else if (rhn == NULL)
1898 return NSOrderedDescending;
1900 _profile(PackageNameCompare$NumbersLast)
1901 if (!lhi.empty() && !rhi.empty()) {
1902 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1903 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1904 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1905 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1906 return lha ? NSOrderedAscending : NSOrderedDescending;
1910 CFIndex length = CFStringGetLength(lhn);
1912 _profile(PackageNameCompare$Compare)
1913 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1918 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1919 return PackageNameCompare(*lhs, *rhs, context);
1922 struct PackageNameOrdering :
1923 std::binary_function<Package *, Package *, bool>
1925 _finline bool operator ()(Package *lhs, Package *rhs) const {
1926 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1930 @implementation Package
1932 - (NSString *) description {
1933 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1937 if (parsed_ != NULL)
1942 + (NSString *) webScriptNameForSelector:(SEL)selector {
1944 else if (selector == @selector(clear))
1946 else if (selector == @selector(getField:))
1948 else if (selector == @selector(hasTag:))
1950 else if (selector == @selector(install))
1952 else if (selector == @selector(remove))
1958 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1959 return [self webScriptNameForSelector:selector] == nil;
1962 + (NSArray *) _attributeKeys {
1963 return [NSArray arrayWithObjects:
1982 @"shortDescription",
1995 - (NSArray *) attributeKeys {
1996 return [[self class] _attributeKeys];
1999 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2000 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2003 - (NSArray *) relations {
2004 @synchronized (database_) {
2005 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2006 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2007 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2011 - (NSString *) getField:(NSString *)name {
2012 @synchronized (database_) {
2013 if ([database_ era] != era_ || file_.end())
2016 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2018 const char *start, *end;
2019 if (!parser.Find([name UTF8String], start, end))
2020 return (NSString *) [NSNull null];
2022 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2026 if (parsed_ != NULL)
2028 @synchronized (database_) {
2029 if ([database_ era] != era_ || file_.end())
2032 ParsedPackage *parsed(new ParsedPackage);
2035 _profile(Package$parse)
2036 pkgRecords::Parser *parser;
2038 _profile(Package$parse$Lookup)
2039 parser = &[database_ records]->Lookup(file_);
2044 _profile(Package$parse$Find)
2049 {"icon", &parsed->icon_},
2050 {"depiction", &parsed->depiction_},
2051 {"homepage", &parsed->homepage_},
2052 {"website", &website},
2053 {"bugs", &parsed->bugs_},
2054 {"support", &parsed->support_},
2055 {"sponsor", &parsed->sponsor_},
2056 {"author", &parsed->author_},
2059 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2060 const char *start, *end;
2062 if (parser->Find(names[i].name_, start, end)) {
2063 CYString &value(*names[i].value_);
2064 _profile(Package$parse$Value)
2065 value.set(pool_, start, end - start);
2071 _profile(Package$parse$Tagline)
2072 const char *start, *end;
2073 if (parser->ShortDesc(start, end)) {
2074 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2077 while (stop != start && stop[-1] == '\r')
2079 parsed->tagline_.set(pool_, start, stop - start);
2083 _profile(Package$parse$Retain)
2084 if (parsed->homepage_.empty())
2085 parsed->homepage_ = website;
2086 if (parsed->homepage_ == parsed->depiction_)
2087 parsed->homepage_.clear();
2092 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2093 if ((self = [super init]) != nil) {
2094 _profile(Package$initWithVersion)
2097 database_ = database;
2098 era_ = [database era];
2102 pkgCache::PkgIterator iterator(version.ParentPkg());
2103 iterator_ = iterator;
2105 _profile(Package$initWithVersion$Version)
2106 if (!version_.end())
2107 file_ = version_.FileList();
2109 pkgCache &cache([database_ cache]);
2110 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2114 _profile(Package$initWithVersion$Cache)
2115 name_.set(NULL, iterator.Display());
2117 latest_.set(NULL, StripVersion_(version_.VerStr()));
2119 pkgCache::VerIterator current(iterator.CurrentVer());
2121 installed_.set(NULL, StripVersion_(current.VerStr()));
2124 _profile(Package$initWithVersion$Tags)
2125 pkgCache::TagIterator tag(iterator.TagList());
2127 tags_ = [NSMutableArray arrayWithCapacity:8];
2129 const char *name(tag.Name());
2130 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2132 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2133 if (strcmp(name + 6, "enduser") == 0)
2135 else if (strcmp(name + 6, "hacker") == 0)
2137 else if (strcmp(name + 6, "developer") == 0)
2139 else if (strcmp(name + 6, "cydia") == 0)
2145 if (strncmp(name, "cydia::", 7) == 0) {
2146 if (strcmp(name + 7, "essential") == 0)
2148 else if (strcmp(name + 7, "obsolete") == 0)
2153 } while (!tag.end());
2157 _profile(Package$initWithVersion$Metadata)
2158 const char *mixed(iterator.Name());
2159 size_t size(strlen(mixed));
2160 char lower[size + 1];
2162 for (size_t i(0); i != size; ++i)
2163 lower[i] = mixed[i] | 0x20;
2166 PackageValue *metadata(PackageFind(lower, size));
2167 metadata_ = metadata;
2169 id_.set(NULL, metadata->name_, size);
2171 const char *latest(version_.VerStr());
2172 size_t length(strlen(latest));
2174 uint16_t vhash(hashlittle(latest, length));
2176 size_t capped(std::min<size_t>(8, length));
2177 latest = latest + length - capped;
2179 if (metadata->first_ == 0)
2180 metadata->first_ = now_;
2182 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2183 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2184 metadata->vhash_ = vhash;
2185 metadata->last_ = now_;
2186 } else if (metadata->last_ == 0)
2187 metadata->last_ = metadata->first_;
2190 _profile(Package$initWithVersion$Section)
2191 section_ = iterator.Section();
2194 _profile(Package$initWithVersion$Flags)
2195 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2196 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2201 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2202 pkgCache::VerIterator version;
2204 _profile(Package$packageWithIterator$GetCandidateVer)
2205 version = [database policy]->GetCandidateVer(iterator);
2213 _profile(Package$packageWithIterator$Allocate)
2214 package = [Package allocWithZone:zone];
2217 _profile(Package$packageWithIterator$Initialize)
2219 initWithVersion:version
2226 _profile(Package$packageWithIterator$Autorelease)
2227 package = [package autorelease];
2233 - (pkgCache::PkgIterator) iterator {
2237 - (NSString *) section {
2238 if (section$_ == nil) {
2239 if (section_ == NULL)
2242 _profile(Package$section$mappedSectionForPointer)
2243 section$_ = [database_ mappedSectionForPointer:section_];
2248 - (NSString *) simpleSection {
2249 if (NSString *section = [self section])
2250 return Simplify(section);
2255 - (NSString *) longSection {
2256 return LocalizeSection([self section]);
2259 - (NSString *) shortSection {
2260 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2263 - (NSString *) uri {
2266 pkgIndexFile *index;
2267 pkgCache::PkgFileIterator file(file_.File());
2268 if (![database_ list].FindIndex(file, index))
2270 return [NSString stringWithUTF8String:iterator_->Path];
2271 //return [NSString stringWithUTF8String:file.Site()];
2272 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2276 - (MIMEAddress *) maintainer {
2277 @synchronized (database_) {
2278 if ([database_ era] != era_ || file_.end())
2281 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2282 const std::string &maintainer(parser->Maintainer());
2283 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2287 @synchronized (database_) {
2288 if ([database_ era] != era_ || version_.end())
2291 return version_->InstalledSize;
2294 - (NSString *) longDescription {
2295 @synchronized (database_) {
2296 if ([database_ era] != era_ || file_.end())
2299 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2300 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2302 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2303 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2304 if ([lines count] < 2)
2307 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2308 for (size_t i(1), e([lines count]); i != e; ++i) {
2309 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2310 [trimmed addObject:trim];
2313 return [trimmed componentsJoinedByString:@"\n"];
2316 - (NSString *) shortDescription {
2317 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2321 _profile(Package$index)
2322 CFStringRef name((CFStringRef) [self name]);
2323 if (CFStringGetLength(name) == 0)
2325 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2326 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2328 return toupper(character);
2332 - (PackageValue *) metadata {
2337 PackageValue *metadata([self metadata]);
2338 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2341 - (bool) subscribed {
2342 return [self metadata]->subscribed_;
2345 - (bool) setSubscribed:(bool)subscribed {
2346 PackageValue *metadata([self metadata]);
2347 if (metadata->subscribed_ == subscribed)
2349 metadata->subscribed_ = subscribed;
2357 - (NSString *) latest {
2361 - (NSString *) installed {
2365 - (BOOL) uninstalled {
2366 return installed_.empty();
2370 return !version_.end();
2373 - (BOOL) upgradableAndEssential:(BOOL)essential {
2374 _profile(Package$upgradableAndEssential)
2375 pkgCache::VerIterator current(iterator_.CurrentVer());
2377 return essential && essential_;
2379 return !version_.end() && version_ != current;
2383 - (BOOL) essential {
2388 return [database_ cache][iterator_].InstBroken();
2391 - (BOOL) unfiltered {
2392 _profile(Package$unfiltered$obsolete)
2393 if (_unlikely(obsolete_))
2397 _profile(Package$unfiltered$hasSupportingRole)
2398 if (_unlikely(![self hasSupportingRole]))
2406 if (![self unfiltered])
2411 _profile(Package$visible$section)
2412 section = [self section];
2415 _profile(Package$visible$isSectionVisible)
2416 if (!isSectionVisible(section))
2424 unsigned char current(iterator_->CurrentState);
2425 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2428 - (BOOL) halfConfigured {
2429 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2432 - (BOOL) halfInstalled {
2433 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2437 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2438 return state.Mode != pkgDepCache::ModeKeep;
2441 - (NSString *) mode {
2442 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2444 switch (state.Mode) {
2445 case pkgDepCache::ModeDelete:
2446 if ((state.iFlags & pkgDepCache::Purge) != 0)
2450 case pkgDepCache::ModeKeep:
2451 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2452 return @"REINSTALL";
2453 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2457 case pkgDepCache::ModeInstall:
2458 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2459 return @"REINSTALL";
2460 else*/ switch (state.Status) {
2462 return @"DOWNGRADE";
2468 return @"NEW_INSTALL";
2479 - (NSString *) name {
2480 return name_.empty() ? id_ : name_;
2483 - (UIImage *) icon {
2484 NSString *section = [self simpleSection];
2487 if (parsed_ != NULL)
2488 if (NSString *href = parsed_->icon_)
2489 if ([href hasPrefix:@"file:///"])
2490 // XXX: correct escaping
2491 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2492 if (icon == nil) if (section != nil)
2493 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2494 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2495 if ([dicon hasPrefix:@"file:///"])
2496 // XXX: correct escaping
2497 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2499 icon = [UIImage applicationImageNamed:@"unknown.png"];
2503 - (NSString *) homepage {
2504 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2507 - (NSString *) depiction {
2508 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2511 - (MIMEAddress *) sponsor {
2512 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2515 - (MIMEAddress *) author {
2516 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2519 - (NSString *) support {
2520 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2523 - (NSArray *) files {
2524 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2525 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2528 fin.open([path UTF8String]);
2533 while (std::getline(fin, line))
2534 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2539 - (NSString *) state {
2540 @synchronized (database_) {
2541 if ([database_ era] != era_ || file_.end())
2544 switch (iterator_->CurrentState) {
2545 case pkgCache::State::NotInstalled:
2546 return @"NotInstalled";
2547 case pkgCache::State::UnPacked:
2549 case pkgCache::State::HalfConfigured:
2550 return @"HalfConfigured";
2551 case pkgCache::State::HalfInstalled:
2552 return @"HalfInstalled";
2553 case pkgCache::State::ConfigFiles:
2554 return @"ConfigFiles";
2555 case pkgCache::State::Installed:
2556 return @"Installed";
2557 case pkgCache::State::TriggersAwaited:
2558 return @"TriggersAwaited";
2559 case pkgCache::State::TriggersPending:
2560 return @"TriggersPending";
2563 return (NSString *) [NSNull null];
2566 - (NSString *) selection {
2567 @synchronized (database_) {
2568 if ([database_ era] != era_ || file_.end())
2571 switch (iterator_->SelectedState) {
2572 case pkgCache::State::Unknown:
2574 case pkgCache::State::Install:
2576 case pkgCache::State::Hold:
2578 case pkgCache::State::DeInstall:
2579 return @"DeInstall";
2580 case pkgCache::State::Purge:
2584 return (NSString *) [NSNull null];
2587 - (NSArray *) warnings {
2588 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2589 const char *name(iterator_.Name());
2591 size_t length(strlen(name));
2592 if (length < 2) invalid:
2593 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2594 else for (size_t i(0); i != length; ++i)
2596 /* XXX: technically this is not allowed */
2597 (name[i] < 'A' || name[i] > 'Z') &&
2598 (name[i] < 'a' || name[i] > 'z') &&
2599 (name[i] < '0' || name[i] > '9') &&
2600 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2603 if (strcmp(name, "cydia") != 0) {
2606 bool _private = false;
2609 bool repository = [[self section] isEqualToString:@"Repositories"];
2611 if (NSArray *files = [self files])
2612 for (NSString *file in files)
2613 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2615 else if (!user && [file isEqualToString:@"/User"])
2617 else if (!_private && [file isEqualToString:@"/private"])
2619 else if (!stash && [file isEqualToString:@"/var/stash"])
2622 /* XXX: this is not sensitive enough. only some folders are valid. */
2623 if (cydia && !repository)
2624 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2626 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2628 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2630 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2633 return [warnings count] == 0 ? nil : warnings;
2636 - (NSArray *) applications {
2637 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2639 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2641 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2642 if (NSArray *files = [self files])
2643 for (NSString *file in files)
2644 if (application_r(file)) {
2645 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2646 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2647 if ([id isEqualToString:me])
2650 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2652 display = application_r[1];
2654 NSString *bundle([file stringByDeletingLastPathComponent]);
2655 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2656 if (icon == nil || [icon length] == 0)
2658 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2660 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2661 [applications addObject:application];
2663 [application addObject:id];
2664 [application addObject:display];
2665 [application addObject:url];
2668 return [applications count] == 0 ? nil : applications;
2671 - (Source *) source {
2672 if (source_ == nil) {
2673 @synchronized (database_) {
2674 if ([database_ era] != era_ || file_.end())
2675 source_ = (Source *) [NSNull null];
2677 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2681 return source_ == (Source *) [NSNull null] ? nil : source_;
2688 - (BOOL) matches:(NSArray *)query {
2689 if (query == nil || [query count] == 0)
2701 length = [string length];
2703 for (NSString *term in query) {
2704 range = [string rangeOfString:term options:MatchCompareOptions_];
2705 if (range.location != NSNotFound)
2706 rank_ -= 10 * 100000 / length;
2709 string = [self name];
2711 for (NSString *term in query) {
2712 range = [string rangeOfString:term options:MatchCompareOptions_];
2713 if (range.location != NSNotFound)
2714 rank_ -= 6 * 100000 / length;
2717 string = [self shortDescription];
2718 length = [string length];
2719 NSUInteger stop(std::min<NSUInteger>(length, 100));
2721 for (NSString *term in query) {
2722 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2723 if (range.location != NSNotFound)
2724 rank_ -= 2 * 100000 / length;
2730 - (bool) hasSupportingRole {
2735 if ([Role_ isEqualToString:@"User"])
2739 if ([Role_ isEqualToString:@"Hacker"])
2743 if ([Role_ isEqualToString:@"Developer"])
2748 - (NSArray *) tags {
2752 - (BOOL) hasTag:(NSString *)tag {
2753 return tags_ == nil ? NO : [tags_ containsObject:tag];
2756 - (NSString *) primaryPurpose {
2757 for (NSString *tag in (NSArray *) tags_)
2758 if ([tag hasPrefix:@"purpose::"])
2759 return [tag substringFromIndex:9];
2763 - (NSArray *) purposes {
2764 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2765 for (NSString *tag in (NSArray *) tags_)
2766 if ([tag hasPrefix:@"purpose::"])
2767 [purposes addObject:[tag substringFromIndex:9]];
2768 return [purposes count] == 0 ? nil : purposes;
2771 - (bool) isCommercial {
2772 return [self hasTag:@"cydia::commercial"];
2775 - (void) setIndex:(size_t)index {
2776 if (metadata_->index_ != index)
2777 metadata_->index_ = index;
2780 - (CYString &) cyname {
2781 return name_.empty() ? id_ : name_;
2784 - (uint32_t) compareBySection:(NSArray *)sections {
2785 NSString *section([self section]);
2786 for (size_t i(0), e([sections count]); i != e; ++i) {
2787 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2791 return _not(uint32_t);
2795 @synchronized (database_) {
2796 pkgProblemResolver *resolver = [database_ resolver];
2797 resolver->Clear(iterator_);
2799 pkgCacheFile &cache([database_ cache]);
2800 cache->SetReInstall(iterator_, false);
2801 cache->MarkKeep(iterator_, false);
2805 @synchronized (database_) {
2806 pkgProblemResolver *resolver = [database_ resolver];
2807 resolver->Clear(iterator_);
2808 resolver->Protect(iterator_);
2810 pkgCacheFile &cache([database_ cache]);
2811 cache->SetReInstall(iterator_, false);
2812 cache->MarkInstall(iterator_, false);
2814 pkgDepCache::StateCache &state((*cache)[iterator_]);
2815 if (!state.Install())
2816 cache->SetReInstall(iterator_, true);
2820 @synchronized (database_) {
2821 pkgProblemResolver *resolver = [database_ resolver];
2822 resolver->Clear(iterator_);
2823 resolver->Remove(iterator_);
2824 resolver->Protect(iterator_);
2826 pkgCacheFile &cache([database_ cache]);
2827 cache->SetReInstall(iterator_, false);
2828 cache->MarkDelete(iterator_, true);
2831 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2832 _profile(Package$isUnfilteredAndSearchedForBy)
2835 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2836 value &= [self unfiltered];
2839 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2840 value &= [self matches:query];
2847 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2848 if ([search length] == 0)
2851 _profile(Package$isUnfilteredAndSelectedForBy)
2854 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2855 value &= [self unfiltered];
2858 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2859 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2866 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2867 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2870 - (bool) isVisibleInSection:(NSString *)name {
2871 NSString *section([self section]);
2875 section == nil && [name length] == 0 ||
2876 [name isEqualToString:section]
2877 ) && [self visible];
2880 - (bool) isVisibleInSource:(Source *)source {
2881 return [self source] == source && [self visible];
2886 /* Section Class {{{ */
2887 @interface Section : NSObject {
2892 _H<NSString> localized_;
2895 - (NSComparisonResult) compareByLocalized:(Section *)section;
2896 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2897 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2898 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2899 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2900 - (NSString *) name;
2907 - (void) addToCount;
2909 - (void) setCount:(size_t)count;
2910 - (NSString *) localized;
2914 @implementation Section
2916 - (NSComparisonResult) compareByLocalized:(Section *)section {
2917 NSString *lhs(localized_);
2918 NSString *rhs([section localized]);
2920 /*if ([lhs length] != 0 && [rhs length] != 0) {
2921 unichar lhc = [lhs characterAtIndex:0];
2922 unichar rhc = [rhs characterAtIndex:0];
2924 if (isalpha(lhc) && !isalpha(rhc))
2925 return NSOrderedAscending;
2926 else if (!isalpha(lhc) && isalpha(rhc))
2927 return NSOrderedDescending;
2930 return [lhs compare:rhs options:LaxCompareOptions_];
2933 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2934 if ((self = [self initWithName:name localize:NO]) != nil) {
2935 if (localized != nil)
2936 localized_ = localized;
2940 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2941 return [self initWithName:name row:0 localize:localize];
2944 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2945 if ((self = [super init]) != nil) {
2950 localized_ = LocalizeSection(name_);
2954 /* XXX: localize the index thingees */
2955 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2956 if ((self = [super init]) != nil) {
2957 name_ = [NSString stringWithCharacters:&index length:1];
2963 - (NSString *) name {
2983 - (void) addToCount {
2987 - (void) setCount:(size_t)count {
2991 - (NSString *) localized {
2998 static NSString *Colon_;
3000 static NSString *Error_;
3001 static NSString *Warning_;
3003 class CydiaLogCleaner :
3004 public pkgArchiveCleaner
3007 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3012 /* Database Implementation {{{ */
3013 @implementation Database
3015 + (Database *) sharedInstance {
3016 static _H<Database> instance;
3017 if (instance == nil)
3018 instance = [[[Database alloc] init] autorelease];
3026 - (void) releasePackages {
3027 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3028 CFArrayRemoveAllValues(packages_);
3032 // XXX: actually implement this thing
3034 [self releasePackages];
3035 apr_pool_destroy(pool_);
3036 NSRecycleZone(zone_);
3040 - (void) _readCydia:(NSNumber *)fd {
3041 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3042 std::istream is(&ib);
3045 static Pcre finish_r("^finish:([^:]*)$");
3047 while (std::getline(is, line)) {
3048 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3050 const char *data(line.c_str());
3051 size_t size = line.size();
3052 lprintf("C:%s\n", data);
3054 if (finish_r(data, size)) {
3055 NSString *finish = finish_r[1];
3056 int index = [Finishes_ indexOfObject:finish];
3057 if (index != INT_MAX && index > Finish_)
3067 - (void) _readStatus:(NSNumber *)fd {
3068 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3069 std::istream is(&ib);
3072 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3073 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3075 while (std::getline(is, line)) {
3076 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3078 const char *data(line.c_str());
3079 size_t size(line.size());
3080 lprintf("S:%s\n", data);
3082 if (conffile_r(data, size)) {
3083 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3084 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3085 } else if (strncmp(data, "status: ", 8) == 0) {
3086 // status: <package>: {unpacked,half-configured,installed}
3087 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3088 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3089 } else if (strncmp(data, "processing: ", 12) == 0) {
3090 // processing: configure: config-test
3091 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3092 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3093 } else if (pmstatus_r(data, size)) {
3094 std::string type([pmstatus_r[1] UTF8String]);
3096 NSString *package = pmstatus_r[2];
3097 if ([package isEqualToString:@"dpkg-exec"])
3100 float percent([pmstatus_r[3] floatValue]);
3101 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3103 NSString *string = pmstatus_r[4];
3105 if (type == "pmerror") {
3106 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3107 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3108 } else if (type == "pmstatus") {
3109 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3110 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3111 } else if (type == "pmconffile")
3112 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3114 lprintf("E:unknown pmstatus\n");
3116 lprintf("E:unknown status\n");
3124 - (void) _readOutput:(NSNumber *)fd {
3125 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3126 std::istream is(&ib);
3129 while (std::getline(is, line)) {
3130 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3132 lprintf("O:%s\n", line.c_str());
3134 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3135 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3147 - (Package *) packageWithName:(NSString *)name {
3148 @synchronized (self) {
3149 if (static_cast<pkgDepCache *>(cache_) == NULL)
3151 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3152 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3156 if ((self = [super init]) != nil) {
3163 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3164 apr_pool_create(&pool_, NULL);
3166 size_t capacity(MetaFile_->active_);
3172 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3173 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3177 _assert(pipe(fds) != -1);
3180 _config->Set("APT::Keep-Fds::", cydiafd_);
3181 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3184 detachNewThreadSelector:@selector(_readCydia:)
3186 withObject:[NSNumber numberWithInt:fds[0]]
3189 _assert(pipe(fds) != -1);
3193 detachNewThreadSelector:@selector(_readStatus:)
3195 withObject:[NSNumber numberWithInt:fds[0]]
3198 _assert(pipe(fds) != -1);
3199 _assert(dup2(fds[0], 0) != -1);
3200 _assert(close(fds[0]) != -1);
3202 input_ = fdopen(fds[1], "a");
3204 _assert(pipe(fds) != -1);
3205 _assert(dup2(fds[1], 1) != -1);
3206 _assert(close(fds[1]) != -1);
3209 detachNewThreadSelector:@selector(_readOutput:)
3211 withObject:[NSNumber numberWithInt:fds[0]]
3216 - (pkgCacheFile &) cache {
3220 - (pkgDepCache::Policy *) policy {
3224 - (pkgRecords *) records {
3228 - (pkgProblemResolver *) resolver {
3232 - (pkgAcquire &) fetcher {
3236 - (pkgSourceList &) list {
3240 - (NSArray *) packages {
3241 return (NSArray *) packages_;
3244 - (NSArray *) sources {
3248 - (Source *) sourceWithKey:(NSString *)key {
3249 for (Source *source in [self sources]) {
3250 if ([[source key] isEqualToString:key])
3255 - (bool) popErrorWithTitle:(NSString *)title {
3258 while (!_error->empty()) {
3260 bool warning(!_error->PopMessage(error));
3265 size_t size(error.size());
3266 if (size == 0 || error[size - 1] != '\n')
3268 error.resize(size - 1);
3271 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3273 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3279 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3280 return [self popErrorWithTitle:title] || !success;
3283 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3284 @synchronized (self) {
3287 [self releasePackages];
3290 [sourceList_ removeAllObjects];
3310 apr_pool_clear(pool_);
3312 NSRecycleZone(zone_);
3313 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3315 int chk(creat("/tmp/cydia.chk", 0644));
3319 if (invocation != nil)
3320 [invocation invoke];
3322 NSString *title(UCLocalize("DATABASE"));
3325 OpProgress progress;
3326 while (!cache_.Open(progress, true)) { pop:
3328 bool warning(!_error->PopMessage(error));
3329 lprintf("cache_.Open():[%s]\n", error.c_str());
3331 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3332 [delegate_ repairWithSelector:@selector(configure)];
3333 else if (error == "The package lists or status file could not be parsed or opened.")
3334 [delegate_ repairWithSelector:@selector(update)];
3335 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3336 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3337 // else if (error == "Malformed Status line")
3338 // else if (error == "The list of sources could not be read.")
3340 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3350 unlink("/tmp/cydia.chk");
3352 now_ = [[NSDate date] timeIntervalSince1970];
3354 policy_ = new pkgDepCache::Policy();
3355 records_ = new pkgRecords(cache_);
3356 resolver_ = new pkgProblemResolver(cache_);
3357 fetcher_ = new pkgAcquire(&status_);
3360 list_ = new pkgSourceList();
3361 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3364 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3365 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3369 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3372 if (cache_->BrokenCount() != 0) {
3373 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3376 if (cache_->BrokenCount() != 0) {
3377 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3381 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3385 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3386 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3387 [sourceList_ addObject:object];
3389 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3390 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3391 // XXX: this could be more intelligent
3392 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3393 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3395 sourceMap_[cached->ID] = object;
3400 /*std::vector<Package *> packages;
3401 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3406 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3407 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3408 //packages.push_back(package);
3409 CFArrayAppendValue(packages_, CFRetain(package));
3413 /*if (packages.empty())
3414 packages_ = [[NSArray alloc] init];
3416 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3419 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3420 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3421 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3429 /*if (!packages.empty())
3430 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3431 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3433 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3435 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3437 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3441 size_t count(CFArrayGetCount(packages_));
3442 MetaFile_->active_ = count;
3444 for (size_t index(0); index != count; ++index)
3445 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3452 @synchronized (self) {
3454 resolver_ = new pkgProblemResolver(cache_);
3456 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3457 if (!cache_[iterator].Keep())
3458 cache_->MarkKeep(iterator, false);
3459 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3460 cache_->SetReInstall(iterator, false);
3463 - (void) configure {
3464 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3466 system([dpkg UTF8String]);
3471 // XXX: I don't remember this condition
3476 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3478 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3480 if ([self popErrorWithTitle:title])
3484 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3486 CydiaLogCleaner cleaner;
3487 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3494 fetcher_->Shutdown();
3496 pkgRecords records(cache_);
3498 lock_ = new FileFd();
3499 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3501 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3503 if ([self popErrorWithTitle:title])
3507 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3510 manager_ = (_system->CreatePM(cache_));
3511 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3518 bool substrate(RestartSubstrate_);
3519 RestartSubstrate_ = false;
3521 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3523 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3525 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3527 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3528 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3531 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3533 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3535 [self popErrorWithTitle:title];
3539 bool failed = false;
3540 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3541 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3543 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3549 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3557 RestartSubstrate_ = true;
3560 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3562 if (_error->PendingError()) {
3567 if (result == pkgPackageManager::Failed) {
3572 if (result != pkgPackageManager::Completed) {
3577 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3579 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3581 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3582 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3585 if (![before isEqualToArray:after])
3590 NSString *title(UCLocalize("UPGRADE"));
3591 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3597 [self updateWithStatus:status_];
3600 - (void) updateWithStatus:(Status &)status {
3601 NSString *title(UCLocalize("REFRESHING_DATA"));
3604 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3608 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3609 if ([self popErrorWithTitle:title])
3612 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3614 bool success(ListUpdate(status, list, PulseInterval_));
3615 if (status.WasCancelled())
3618 [self popErrorWithTitle:title forOperation:success];
3619 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3623 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3626 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3627 delegate_ = delegate;
3630 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3631 progress_ = delegate;
3632 status_.setDelegate(delegate);
3635 - (NSObject<ProgressDelegate> *) progressDelegate {
3639 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3640 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3641 return i == sourceMap_.end() ? nil : i->second;
3644 - (NSString *) mappedSectionForPointer:(const char *)section {
3645 _H<NSString> *mapped;
3647 _profile(Database$mappedSectionForPointer$Cache)
3648 mapped = §ions_[section];
3651 if (*mapped == NULL) {
3652 size_t length(strlen(section));
3653 char spaced[length + 1];
3655 _profile(Database$mappedSectionForPointer$Replace)
3656 for (size_t index(0); index != length; ++index)
3657 spaced[index] = section[index] == '_' ? ' ' : section[index];
3658 spaced[length] = '\0';
3663 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3664 string = [NSString stringWithUTF8String:spaced];
3667 _profile(Database$mappedSectionForPointer$Map)
3668 string = [SectionMap_ objectForKey:string] ?: string;
3678 static _H<NSMutableSet> Diversions_;
3680 @interface Diversion : NSObject {
3683 _H<NSString> format_;
3688 @implementation Diversion
3690 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3691 if ((self = [super init]) != nil) {
3692 pattern_ = [from UTF8String];
3698 - (NSString *) divert:(NSString *)url {
3699 return !pattern_(url) ? nil : pattern_->*format_;
3702 + (NSURL *) divertURL:(NSURL *)url {
3704 NSString *href([url absoluteString]);
3706 for (Diversion *diversion in (id) Diversions_)
3707 if (NSString *diverted = [diversion divert:href]) {
3709 NSLog(@"div: %@", diverted);
3711 url = [NSURL URLWithString:diverted];
3718 - (NSString *) key {
3722 - (NSUInteger) hash {
3726 - (BOOL) isEqual:(Diversion *)object {
3727 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3732 @interface CydiaObject : NSObject {
3733 _H<IndirectDelegate> indirect_;
3734 _transient id delegate_;
3737 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3741 @interface CydiaWebViewController : CyteWebViewController {
3742 _H<CydiaObject> cydia_;
3745 + (void) addDiversion:(Diversion *)diversion;
3749 /* Web Scripting {{{ */
3750 @implementation CydiaObject
3752 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3753 if ((self = [super init]) != nil) {
3754 indirect_ = indirect;
3758 - (void) setDelegate:(id)delegate {
3759 delegate_ = delegate;
3762 + (NSArray *) _attributeKeys {
3763 return [NSArray arrayWithObjects:
3779 - (NSArray *) attributeKeys {
3780 return [[self class] _attributeKeys];
3783 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3784 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3787 - (NSString *) version {
3791 - (NSString *) device {
3792 return [[UIDevice currentDevice] uniqueIdentifier];
3795 - (NSString *) firmware {
3796 return [[UIDevice currentDevice] systemVersion];
3799 - (NSString *) hostname {
3800 return [[UIDevice currentDevice] name];
3803 - (NSString *) idiom {
3804 return (id) Idiom_ ?: [NSNull null];
3807 - (NSString *) plmn {
3808 return (id) PLMN_ ?: [NSNull null];
3811 - (NSString *) bbsnum {
3812 return (id) BBSNum_ ?: [NSNull null];
3815 - (NSString *) ecid {
3816 return (id) ChipID_ ?: [NSNull null];
3819 - (NSString *) serial {
3820 return SerialNumber_;
3823 - (NSString *) role {
3824 return (id) Role_ ?: [NSNull null];
3827 - (NSString *) model {
3828 return [NSString stringWithUTF8String:Machine_];
3831 - (NSString *) token {
3832 return (id) Token_ ?: [NSNull null];
3835 + (NSString *) webScriptNameForSelector:(SEL)selector {
3837 else if (selector == @selector(addBridgedHost:))
3838 return @"addBridgedHost";
3839 else if (selector == @selector(addInternalRedirect::))
3840 return @"addInternalRedirect";
3841 else if (selector == @selector(addPipelinedHost:scheme:))
3842 return @"addPipelinedHost";
3843 else if (selector == @selector(addTrivialSource:))
3844 return @"addTrivialSource";
3845 else if (selector == @selector(close))
3847 else if (selector == @selector(du:))
3849 else if (selector == @selector(stringWithFormat:arguments:))
3851 else if (selector == @selector(getAllSources))
3852 return @"getAllSourcs";
3853 else if (selector == @selector(getKernelNumber:))
3854 return @"getKernelNumber";
3855 else if (selector == @selector(getKernelString:))
3856 return @"getKernelString";
3857 else if (selector == @selector(getInstalledPackages))
3858 return @"getInstalledPackages";
3859 else if (selector == @selector(getIORegistryEntry::))
3860 return @"getIORegistryEntry";
3861 else if (selector == @selector(getLocaleIdentifier))
3862 return @"getLocaleIdentifier";
3863 else if (selector == @selector(getPreferredLanguages))
3864 return @"getPreferredLanguages";
3865 else if (selector == @selector(getPackageById:))
3866 return @"getPackageById";
3867 else if (selector == @selector(getSessionValue:))
3868 return @"getSessionValue";
3869 else if (selector == @selector(installPackages:))
3870 return @"installPackages";
3871 else if (selector == @selector(localizedStringForKey:value:table:))
3873 else if (selector == @selector(popViewController:))
3874 return @"popViewController";
3875 else if (selector == @selector(refreshSources))
3876 return @"refreshSources";
3877 else if (selector == @selector(removeButton))
3878 return @"removeButton";
3879 else if (selector == @selector(setSessionValue::))
3880 return @"setSessionValue";
3881 else if (selector == @selector(substitutePackageNames:))
3882 return @"substitutePackageNames";
3883 else if (selector == @selector(scrollToBottom:))
3884 return @"scrollToBottom";
3885 else if (selector == @selector(setAllowsNavigationAction:))
3886 return @"setAllowsNavigationAction";
3887 else if (selector == @selector(setBadgeValue:))
3888 return @"setBadgeValue";
3889 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3890 return @"setButtonImage";
3891 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3892 return @"setButtonTitle";
3893 else if (selector == @selector(setHidesBackButton:))
3894 return @"setHidesBackButton";
3895 else if (selector == @selector(setHidesNavigationBar:))
3896 return @"setHidesNavigationBar";
3897 else if (selector == @selector(setNavigationBarStyle:))
3898 return @"setNavigationBarStyle";
3899 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3900 return @"setNavigationBarTintColor";
3901 else if (selector == @selector(setPasteboardString:))
3902 return @"setPasteboardString";
3903 else if (selector == @selector(setPasteboardURL:))
3904 return @"setPasteboardURL";
3905 else if (selector == @selector(setToken:))
3907 else if (selector == @selector(setViewportWidth:))
3908 return @"setViewportWidth";
3909 else if (selector == @selector(statfs:))
3911 else if (selector == @selector(supports:))
3913 else if (selector == @selector(unload))
3919 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3920 return [self webScriptNameForSelector:selector] == nil;
3923 - (BOOL) supports:(NSString *)feature {
3924 return [feature isEqualToString:@"window.open"];
3928 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
3931 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3932 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3935 - (NSNumber *) getKernelNumber:(NSString *)name {
3936 const char *string([name UTF8String]);
3939 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3940 return (id) [NSNull null];
3942 if (size != sizeof(int))
3943 return (id) [NSNull null];
3946 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3947 return (id) [NSNull null];
3949 return [NSNumber numberWithInt:value];
3952 - (NSString *) getKernelString:(NSString *)name {
3953 const char *string([name UTF8String]);
3956 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3957 return (id) [NSNull null];
3959 char value[size + 1];
3960 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3961 return (id) [NSNull null];
3963 // XXX: just in case you request something ludicrous
3966 return [NSString stringWithCString:value];
3969 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3970 NSObject *value(CYIOGetValue([path UTF8String], entry));
3973 if ([value isKindOfClass:[NSData class]])
3974 value = CYHex((NSData *) value);
3979 - (id) getSessionValue:(NSString *)key {
3980 @synchronized (SessionData_) {
3981 return [SessionData_ objectForKey:key];
3984 - (void) setSessionValue:(NSString *)key :(NSString *)value {
3985 @synchronized (SessionData_) {
3986 if (value == (id) [WebUndefined undefined])
3987 [SessionData_ removeObjectForKey:key];
3989 [SessionData_ setObject:value forKey:key];
3992 - (void) addBridgedHost:(NSString *)host {
3993 @synchronized (HostConfig_) {
3994 [BridgedHosts_ addObject:host];
3997 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
3998 @synchronized (HostConfig_) {
3999 if (scheme != (id) [WebUndefined undefined])
4000 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4002 [PipelinedHosts_ addObject:host];
4005 - (void) popViewController:(NSNumber *)value {
4006 if (value == (id) [WebUndefined undefined])
4007 value = [NSNumber numberWithBool:YES];
4008 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4011 - (void) addTrivialSource:(NSString *)href {
4012 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4015 - (void) refreshSources {
4016 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4019 - (NSArray *) getAllSources {
4020 return [[Database sharedInstance] sources];
4023 - (NSArray *) getInstalledPackages {
4024 Database *database([Database sharedInstance]);
4025 @synchronized (database) {
4026 NSArray *packages([database packages]);
4027 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4028 for (Package *package in packages)
4029 if (![package uninstalled])
4030 [installed addObject:package];
4034 - (Package *) getPackageById:(NSString *)id {
4035 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4039 return (Package *) [NSNull null];
4042 - (NSString *) getLocaleIdentifier {
4043 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4046 - (NSArray *) getPreferredLanguages {
4050 - (NSArray *) statfs:(NSString *)path {
4053 if (path == nil || statfs([path UTF8String], &stat) == -1)
4056 return [NSArray arrayWithObjects:
4057 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4058 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4059 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4063 - (NSNumber *) du:(NSString *)path {
4064 NSNumber *value(nil);
4067 _assert(pipe(fds) != -1);
4069 pid_t pid(ExecFork());
4071 _assert(dup2(fds[1], 1) != -1);
4072 _assert(close(fds[0]) != -1);
4073 _assert(close(fds[1]) != -1);
4074 /* XXX: this should probably not use du */
4075 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4080 _assert(close(fds[1]) != -1);
4082 if (FILE *du = fdopen(fds[0], "r")) {
4084 while (fgets(line, sizeof(line), du) != NULL) {
4085 size_t length(strlen(line));
4086 while (length != 0 && line[length - 1] == '\n')
4087 line[--length] = '\0';
4088 if (char *tab = strchr(line, '\t')) {
4090 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4095 } else _assert(close(fds[0]));
4099 if (waitpid(pid, &status, 0) == -1)
4102 else _assert(false);
4108 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4111 - (void) installPackages:(NSArray *)packages {
4112 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4115 - (NSString *) substitutePackageNames:(NSString *)message {
4116 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4117 for (size_t i(0), e([words count]); i != e; ++i) {
4118 NSString *word([words objectAtIndex:i]);
4119 if (Package *package = [[Database sharedInstance] packageWithName:word])
4120 [words replaceObjectAtIndex:i withObject:[package name]];
4123 return [words componentsJoinedByString:@" "];
4126 - (void) removeButton {
4127 [indirect_ removeButton];
4130 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4131 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4134 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4135 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4138 - (void) setBadgeValue:(id)value {
4139 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4142 - (void) setAllowsNavigationAction:(NSString *)value {
4143 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4146 - (void) setHidesBackButton:(NSString *)value {
4147 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4150 - (void) setHidesNavigationBar:(NSString *)value {
4151 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4154 - (void) setNavigationBarStyle:(NSString *)value {
4155 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4158 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4159 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4160 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4161 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4164 - (void) setPasteboardString:(NSString *)value {
4165 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4168 - (void) setPasteboardURL:(NSString *)value {
4169 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4172 - (void) _setToken:(NSString *)token {
4176 [Metadata_ removeObjectForKey:@"Token"];
4178 [Metadata_ setObject:Token_ forKey:@"Token"];
4183 - (void) setToken:(NSString *)token {
4184 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4187 - (void) scrollToBottom:(NSNumber *)animated {
4188 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4191 - (void) setViewportWidth:(float)width {
4192 [indirect_ setViewportWidthOnMainThread:width];
4195 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4196 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4197 unsigned count([arguments count]);
4199 for (unsigned i(0); i != count; ++i)
4200 values[i] = [arguments objectAtIndex:i];
4201 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4204 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4205 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4207 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4209 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4216 /* Cydia Browser Controller {{{ */
4217 @implementation CydiaWebViewController
4219 - (NSURL *) navigationURL {
4220 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4223 + (void) initialize {
4224 Diversions_ = [NSMutableSet setWithCapacity:0];
4227 + (void) addDiversion:(Diversion *)diversion {
4228 [Diversions_ addObject:diversion];
4231 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4232 [super webView:view didClearWindowObject:window forFrame:frame];
4234 WebDataSource *source([frame dataSource]);
4235 NSURLResponse *response([source response]);
4236 NSURL *url([response URL]);
4237 NSString *scheme([[url scheme] lowercaseString]);
4239 bool bridged(false);
4241 @synchronized (HostConfig_) {
4242 if ([scheme isEqualToString:@"file"])
4244 else if ([scheme isEqualToString:@"https"])
4245 if ([BridgedHosts_ containsObject:[url host]])
4250 [window setValue:cydia_ forKey:@"cydia"];
4253 - (void) _setupMail:(MFMailComposeViewController *)controller {
4254 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4256 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4257 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4260 - (NSURL *) URLWithURL:(NSURL *)url {
4261 return [Diversion divertURL:url];
4264 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4265 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4267 if (System_ != NULL)
4268 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4269 if (Machine_ != NULL)
4270 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4272 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4277 - (void) setDelegate:(id)delegate {
4278 [super setDelegate:delegate];
4279 [cydia_ setDelegate:delegate];
4283 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4284 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4286 WebView *webview([[webview_ _documentView] webView]);
4288 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4291 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4293 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4294 if (Product_ != nil)
4295 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4297 [webview setApplicationNameForUserAgent:application];
4305 @interface NSObject (CydiaScript)
4306 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4309 @implementation NSObject (CydiaScript)
4311 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4317 @implementation NSArray (CydiaScript)
4319 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4320 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4321 for (size_t i(0), e([self count]); i != e; ++i)
4322 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4328 @implementation NSDictionary (CydiaScript)
4330 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4331 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4333 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4340 /* Confirmation Controller {{{ */
4341 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4342 if (!iterator.end())
4343 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4344 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4346 pkgCache::PkgIterator package(dep.TargetPkg());
4349 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4356 @protocol ConfirmationControllerDelegate
4357 - (void) cancelAndClear:(bool)clear;
4358 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4362 @interface ConfirmationController : CydiaWebViewController {
4363 _transient Database *database_;
4365 _H<UIAlertView> essential_;
4367 _H<NSDictionary> changes_;
4368 _H<NSMutableArray> issues_;
4369 _H<NSDictionary> sizes_;
4374 - (id) initWithDatabase:(Database *)database;
4378 @implementation ConfirmationController
4382 RestartSubstrate_ = true;
4383 [delegate_ confirmWithNavigationController:[self navigationController]];
4386 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4387 NSString *context([alert context]);
4389 if ([context isEqualToString:@"remove"]) {
4390 if (button == [alert cancelButtonIndex])
4391 [self dismissModalViewControllerAnimated:YES];
4392 else if (button == [alert firstOtherButtonIndex]) {
4396 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4397 } else if ([context isEqualToString:@"unable"]) {
4398 [self dismissModalViewControllerAnimated:YES];
4399 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4401 [super alertView:alert clickedButtonAtIndex:button];
4405 - (void) _doContinue {
4406 [self dismissModalViewControllerAnimated:YES];
4407 [delegate_ cancelAndClear:NO];
4410 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4411 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4415 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4416 [super webView:view didClearWindowObject:window forFrame:frame];
4418 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4419 (id) changes_, @"changes",
4420 (id) issues_, @"issues",
4421 (id) sizes_, @"sizes",
4423 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4426 - (id) initWithDatabase:(Database *)database {
4427 if ((self = [super init]) != nil) {
4428 database_ = database;
4430 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4431 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4432 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4433 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4434 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4438 pkgCacheFile &cache([database_ cache]);
4439 NSArray *packages([database_ packages]);
4440 pkgDepCache::Policy *policy([database_ policy]);
4442 issues_ = [NSMutableArray arrayWithCapacity:4];
4444 for (Package *package in packages) {
4445 pkgCache::PkgIterator iterator([package iterator]);
4446 NSString *name([package id]);
4448 if ([package broken]) {
4449 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4451 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4453 reasons, @"reasons",
4456 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4460 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4461 pkgCache::DepIterator start;
4462 pkgCache::DepIterator end;
4463 dep.GlobOr(start, end); // ++dep
4465 if (!cache->IsImportantDep(end))
4467 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4470 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4472 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4473 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4474 clauses, @"clauses",
4478 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4480 pkgCache::PkgIterator target(start.TargetPkg());
4481 if (target->ProvidesList != 0)
4482 reason = @"missing";
4484 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4486 reason = @"installed";
4487 installed = [NSString stringWithUTF8String:ver.VerStr()];
4488 } else if (!cache[target].CandidateVerIter(cache).end())
4489 reason = @"uninstalled";
4490 else if (target->ProvidesList == 0)
4491 reason = @"uninstallable";
4493 reason = @"virtual";
4496 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4497 [NSString stringWithUTF8String:start.CompType()], @"operator",
4498 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4501 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4502 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4503 version, @"version",
4505 installed, @"installed",
4508 // yes, seriously. (wtf?)
4516 pkgDepCache::StateCache &state(cache[iterator]);
4518 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4520 if (state.NewInstall())
4521 [installs addObject:name];
4522 // XXX: else if (state.Install())
4523 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4524 [reinstalls addObject:name];
4525 // XXX: move before previous if
4526 else if (state.Upgrade())
4527 [upgrades addObject:name];
4528 else if (state.Downgrade())
4529 [downgrades addObject:name];
4530 else if (!state.Delete())
4531 // XXX: _assert(state.Keep());
4533 else if (special_r(name))
4534 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4535 [NSNull null], @"package",
4536 [NSArray arrayWithObjects:
4537 [NSDictionary dictionaryWithObjectsAndKeys:
4538 @"Conflicts", @"relationship",
4539 [NSArray arrayWithObjects:
4540 [NSDictionary dictionaryWithObjectsAndKeys:
4542 [NSNull null], @"version",
4543 @"installed", @"reason",
4550 if ([package essential])
4552 [removes addObject:name];
4555 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4556 substrate_ |= DepSubstrate(iterator.CurrentVer());
4561 else if (Advanced_) {
4562 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4564 essential_ = [[[UIAlertView alloc]
4565 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4566 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4568 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4570 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4574 [essential_ setContext:@"remove"];
4576 essential_ = [[[UIAlertView alloc]
4577 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4578 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4580 cancelButtonTitle:UCLocalize("OKAY")
4581 otherButtonTitles:nil
4584 [essential_ setContext:@"unable"];
4587 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4588 installs, @"installs",
4589 reinstalls, @"reinstalls",
4590 upgrades, @"upgrades",
4591 downgrades, @"downgrades",
4592 removes, @"removes",
4595 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4596 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4597 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4600 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4604 - (UIBarButtonItem *) leftButton {
4605 return [[[UIBarButtonItem alloc]
4606 initWithTitle:UCLocalize("CANCEL")
4607 style:UIBarButtonItemStylePlain
4609 action:@selector(cancelButtonClicked)
4614 - (void) applyRightButton {
4615 if ([issues_ count] == 0 && ![self isLoading])
4616 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4617 initWithTitle:UCLocalize("CONFIRM")
4618 style:UIBarButtonItemStyleDone
4620 action:@selector(confirmButtonClicked)
4623 [[self navigationItem] setRightBarButtonItem:nil];
4627 - (void) cancelButtonClicked {
4628 [self dismissModalViewControllerAnimated:YES];
4629 [delegate_ cancelAndClear:YES];
4633 - (void) confirmButtonClicked {
4634 if (essential_ != nil)
4644 /* Progress Data {{{ */
4645 @interface CydiaProgressData : NSObject {
4646 _transient id delegate_;
4655 _H<NSMutableArray> events_;
4656 _H<NSString> title_;
4658 _H<NSString> status_;
4659 _H<NSString> finish_;
4664 @implementation CydiaProgressData
4666 + (NSArray *) _attributeKeys {
4667 return [NSArray arrayWithObjects:
4679 - (NSArray *) attributeKeys {
4680 return [[self class] _attributeKeys];
4683 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4684 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4688 if ((self = [super init]) != nil) {
4689 events_ = [NSMutableArray arrayWithCapacity:32];
4693 - (void) setDelegate:(id)delegate {
4694 delegate_ = delegate;
4697 - (void) setPercent:(float)value {
4701 - (NSNumber *) percent {
4702 return [NSNumber numberWithFloat:percent_];
4705 - (void) setCurrent:(float)value {
4709 - (NSNumber *) current {
4710 return [NSNumber numberWithFloat:current_];
4713 - (void) setTotal:(float)value {
4717 - (NSNumber *) total {
4718 return [NSNumber numberWithFloat:total_];
4721 - (void) setSpeed:(float)value {
4725 - (NSNumber *) speed {
4726 return [NSNumber numberWithFloat:speed_];
4729 - (NSArray *) events {
4733 - (void) removeAllEvents {
4734 [events_ removeAllObjects];
4737 - (void) addEvent:(CydiaProgressEvent *)event {
4738 [events_ addObject:event];
4741 - (void) setTitle:(NSString *)text {
4745 - (NSString *) title {
4749 - (void) setFinish:(NSString *)text {
4753 - (NSString *) finish {
4754 return (id) finish_ ?: [NSNull null];
4757 - (void) setRunning:(bool)running {
4761 - (NSNumber *) running {
4762 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4767 /* Progress Controller {{{ */
4768 @interface ProgressController : CydiaWebViewController <
4771 _transient Database *database_;
4772 _H<CydiaProgressData, 1> progress_;
4776 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4778 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4780 - (void) setTitle:(NSString *)title;
4781 - (void) setCancellable:(bool)cancellable;
4785 @implementation ProgressController
4788 [database_ setProgressDelegate:nil];
4792 - (UIBarButtonItem *) leftButton {
4793 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4794 initWithTitle:UCLocalize("CANCEL")
4795 style:UIBarButtonItemStylePlain
4797 action:@selector(cancel)
4798 ] autorelease] : nil;
4801 - (void) updateCancel {
4802 [super applyLeftButton];
4805 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4806 if ((self = [super init]) != nil) {
4807 database_ = database;
4808 delegate_ = delegate;
4810 [database_ setProgressDelegate:self];
4812 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4813 [progress_ setDelegate:self];
4815 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4817 [scroller_ setBackgroundColor:[UIColor blackColor]];
4819 [[self navigationItem] setHidesBackButton:YES];
4821 [self updateCancel];
4825 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4826 [super webView:view didClearWindowObject:window forFrame:frame];
4827 [window setValue:progress_ forKey:@"cydiaProgress"];
4830 - (void) updateProgress {
4831 [self dispatchEvent:@"CydiaProgressUpdate"];
4834 - (void) viewWillAppear:(BOOL)animated {
4835 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4836 [super viewWillAppear:animated];
4840 UpdateExternalStatus(0);
4847 [delegate_ terminateWithSuccess];
4848 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4849 [delegate_ suspendWithAnimation:YES];
4851 [delegate_ suspend];*/
4863 system("/usr/bin/sbreload");
4869 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4870 SBReboot(SBSSpringBoardServerPort());
4872 reboot2(RB_AUTOBOOT);
4879 - (void) setTitle:(NSString *)title {
4880 [progress_ setTitle:title];
4881 [self updateProgress];
4884 - (UIBarButtonItem *) rightButton {
4885 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4886 initWithTitle:UCLocalize("CLOSE")
4887 style:UIBarButtonItemStylePlain
4889 action:@selector(close)
4893 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4894 UpdateExternalStatus(1);
4896 [progress_ setRunning:true];
4897 [self setTitle:title];
4898 // implicit updateProgress
4900 SHA1SumValue notifyconf; {
4902 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4905 MMap mmap(file, MMap::ReadOnly);
4907 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4908 notifyconf = sha1.Result();
4912 SHA1SumValue springlist; {
4914 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4917 MMap mmap(file, MMap::ReadOnly);
4919 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4920 springlist = sha1.Result();
4924 if (invocation != nil) {
4925 [invocation yieldToSelector:@selector(invoke)];
4926 [self setTitle:@"COMPLETE"];
4931 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4934 MMap mmap(file, MMap::ReadOnly);
4936 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4937 if (!(notifyconf == sha1.Result()))
4944 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4947 MMap mmap(file, MMap::ReadOnly);
4949 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4950 if (!(springlist == sha1.Result()))
4956 if (RestartSubstrate_)
4960 RestartSubstrate_ = false;
4963 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4964 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
4965 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
4966 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4967 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
4971 system("su -c /usr/bin/uicache mobile");
4974 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
4976 [progress_ setRunning:false];
4977 [self updateProgress];
4979 [self applyRightButton];
4982 - (void) addProgressEvent:(CydiaProgressEvent *)event {
4983 [progress_ addEvent:event];
4984 [self updateProgress];
4987 - (bool) isProgressCancelled {
4988 return cancel_ == 2;
4993 [self updateCancel];
4996 - (void) setCancellable:(bool)cancellable {
4997 unsigned cancel(cancel_);
5001 else if (cancel_ == 0)
5004 if (cancel != cancel_)
5005 [self updateCancel];
5008 - (void) setProgressCancellable:(NSNumber *)cancellable {
5009 [self setCancellable:[cancellable boolValue]];
5012 - (void) setProgressPercent:(NSNumber *)percent {
5013 [progress_ setPercent:[percent floatValue]];
5014 [self updateProgress];
5017 - (void) setProgressStatus:(NSDictionary *)status {
5018 if (status == nil) {
5019 [progress_ setCurrent:0];
5020 [progress_ setTotal:0];
5021 [progress_ setSpeed:0];
5023 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5025 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5026 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5027 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5030 [self updateProgress];
5036 /* Package Cell {{{ */
5037 @interface PackageCell : CyteTableViewCell <
5038 CyteTableViewCellDelegate
5042 _H<NSString> description_;
5044 _H<NSString> source_;
5046 _H<Package> package_;
5047 _H<UIImage> placard_;
5051 - (PackageCell *) init;
5052 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5054 - (void) drawContentRect:(CGRect)rect;
5058 @implementation PackageCell
5060 - (PackageCell *) init {
5061 CGRect frame(CGRectMake(0, 0, 320, 74));
5062 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5063 UIView *content([self contentView]);
5064 CGRect bounds([content bounds]);
5066 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5067 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5068 [content addSubview:content_];
5070 [content_ setDelegate:self];
5071 [content_ setOpaque:YES];
5075 - (NSString *) accessibilityLabel {
5076 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5079 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5080 summarized_ = summary;
5092 Source *source = [package source];
5094 icon_ = [package icon];
5095 name_ = [NSString stringWithString:[package name]];
5097 NSString *description(nil);
5098 if (description == nil && IsWildcat_)
5099 description = [package longDescription];
5100 if (description == nil)
5101 description = [package shortDescription];
5103 description_ = [NSString stringWithString:description];
5105 commercial_ = [package isCommercial];
5109 NSString *label = nil;
5110 bool trusted = false;
5112 if (source != nil) {
5113 label = [source label];
5114 trusted = [source trusted];
5115 } else if ([[package id] isEqualToString:@"firmware"])
5116 label = UCLocalize("APPLE");
5118 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5120 NSString *from(label);
5122 NSString *section = [package simpleSection];
5123 if (section != nil && ![section isEqualToString:label]) {
5124 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5125 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5128 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5130 if (NSString *purpose = [package primaryPurpose])
5131 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5136 if (NSString *mode = [package_ mode]) {
5137 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5138 color = RemovingColor_;
5139 //placard = @"removing";
5141 color = InstallingColor_;
5142 //placard = @"installing";
5145 // XXX: the removing/installing placards are not @2x
5148 color = [UIColor whiteColor];
5150 if ([package installed] != nil)
5151 placard = @"installed";
5156 [content_ setBackgroundColor:color];
5159 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5161 [self setNeedsDisplay];
5162 [content_ setNeedsDisplay];
5165 - (void) drawSummaryContentRect:(CGRect)rect {
5166 bool highlighted(highlighted_);
5167 float width([self bounds].size.width);
5171 rect.size = [(UIImage *) icon_ size];
5173 rect.size.width /= 4;
5174 rect.size.height /= 4;
5176 rect.origin.x = 14 - rect.size.width / 4;
5177 rect.origin.y = 14 - rect.size.height / 4;
5179 [icon_ drawInRect:rect];
5182 if (badge_ != nil) {
5184 rect.size = [(UIImage *) badge_ size];
5186 rect.size.width /= 4;
5187 rect.size.height /= 4;
5189 rect.origin.x = 20 - rect.size.width / 4;
5190 rect.origin.y = 20 - rect.size.height / 4;
5192 [badge_ drawInRect:rect];
5199 UISetColor(commercial_ ? Purple_ : Black_);
5200 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5202 if (placard_ != nil)
5203 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5206 - (void) drawNormalContentRect:(CGRect)rect {
5207 bool highlighted(highlighted_);
5208 float width([self bounds].size.width);
5212 rect.size = [(UIImage *) icon_ size];
5214 rect.size.width /= 2;
5215 rect.size.height /= 2;
5217 rect.origin.x = 25 - rect.size.width / 2;
5218 rect.origin.y = 25 - rect.size.height / 2;
5220 [icon_ drawInRect:rect];
5223 if (badge_ != nil) {
5225 rect.size = [(UIImage *) badge_ size];
5227 rect.size.width /= 2;
5228 rect.size.height /= 2;
5230 rect.origin.x = 36 - rect.size.width / 2;
5231 rect.origin.y = 36 - rect.size.height / 2;
5233 [badge_ drawInRect:rect];
5240 UISetColor(commercial_ ? Purple_ : Black_);
5241 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5242 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5245 UISetColor(commercial_ ? Purplish_ : Gray_);
5246 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5248 if (placard_ != nil)
5249 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5252 - (void) drawContentRect:(CGRect)rect {
5254 [self drawSummaryContentRect:rect];
5256 [self drawNormalContentRect:rect];
5261 /* Section Cell {{{ */
5262 @interface SectionCell : CyteTableViewCell <
5263 CyteTableViewCellDelegate
5265 _H<NSString> basic_;
5266 _H<NSString> section_;
5268 _H<NSString> count_;
5270 _H<UISwitch> switch_;
5274 - (void) setSection:(Section *)section editing:(BOOL)editing;
5278 @implementation SectionCell
5280 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5281 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5282 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5283 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5284 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5286 UIView *content([self contentView]);
5287 CGRect bounds([content bounds]);
5289 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5290 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5291 [content addSubview:content_];
5292 [content_ setBackgroundColor:[UIColor whiteColor]];
5294 [content_ setDelegate:self];
5298 - (void) onSwitch:(id)sender {
5299 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5300 if (metadata == nil) {
5301 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5302 [Sections_ setObject:metadata forKey:basic_];
5305 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5309 - (void) setSection:(Section *)section editing:(BOOL)editing {
5310 if (editing != editing_) {
5312 [switch_ removeFromSuperview];
5314 [self addSubview:switch_];
5323 if (section == nil) {
5324 name_ = UCLocalize("ALL_PACKAGES");
5327 basic_ = [section name];
5328 section_ = [section localized];
5330 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5331 count_ = [NSString stringWithFormat:@"%d", [section count]];
5334 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5337 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5338 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5340 [content_ setNeedsDisplay];
5343 - (void) setFrame:(CGRect)frame {
5344 [super setFrame:frame];
5346 CGRect rect([switch_ frame]);
5347 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5350 - (NSString *) accessibilityLabel {
5354 - (void) drawContentRect:(CGRect)rect {
5355 bool highlighted(highlighted_ && !editing_);
5357 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5362 float width(rect.size.width);
5368 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5370 CGSize size = [count_ sizeWithFont:Font14_];
5374 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5380 /* File Table {{{ */
5381 @interface FileTable : CyteViewController <
5382 UITableViewDataSource,
5385 _transient Database *database_;
5386 _H<Package> package_;
5388 _H<NSMutableArray> files_;
5389 _H<UITableView, 2> list_;
5392 - (id) initWithDatabase:(Database *)database;
5393 - (void) setPackage:(Package *)package;
5397 @implementation FileTable
5399 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5400 return files_ == nil ? 0 : [files_ count];
5403 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5407 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5408 static NSString *reuseIdentifier = @"Cell";
5410 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5412 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5413 [cell setFont:[UIFont systemFontOfSize:16]];
5415 [cell setText:[files_ objectAtIndex:indexPath.row]];
5416 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5421 - (NSURL *) navigationURL {
5422 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5426 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5428 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5429 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5430 [list_ setRowHeight:24.0f];
5431 [(UITableView *) list_ setDataSource:self];
5432 [list_ setDelegate:self];
5433 [[self view] addSubview:list_];
5436 - (void) viewDidLoad {
5437 [super viewDidLoad];
5439 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5442 - (void) releaseSubviews {
5445 [super releaseSubviews];
5448 - (id) initWithDatabase:(Database *)database {
5449 if ((self = [super init]) != nil) {
5450 database_ = database;
5452 files_ = [NSMutableArray arrayWithCapacity:32];
5456 - (void) setPackage:(Package *)package {
5460 [files_ removeAllObjects];
5462 if (package != nil) {
5464 name_ = [package id];
5466 if (NSArray *files = [package files])
5467 [files_ addObjectsFromArray:files];
5469 if ([files_ count] != 0) {
5470 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5471 [files_ removeObjectAtIndex:0];
5472 [files_ sortUsingSelector:@selector(compareByPath:)];
5474 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5475 [stack addObject:@"/"];
5477 for (int i(0), e([files_ count]); i != e; ++i) {
5478 NSString *file = [files_ objectAtIndex:i];
5479 while (![file hasPrefix:[stack lastObject]])
5480 [stack removeLastObject];
5481 NSString *directory = [stack lastObject];
5482 [stack addObject:[file stringByAppendingString:@"/"]];
5483 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5484 ([stack count] - 2) * 3, "",
5485 [file substringFromIndex:[directory length]]
5494 - (void) reloadData {
5497 [self setPackage:[database_ packageWithName:name_]];
5502 /* Package Controller {{{ */
5503 @interface CYPackageController : CydiaWebViewController <
5504 UIActionSheetDelegate
5506 _transient Database *database_;
5507 _H<Package> package_;
5510 _H<NSMutableArray> buttons_;
5511 _H<UIBarButtonItem> button_;
5514 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5518 @implementation CYPackageController
5520 - (NSURL *) navigationURL {
5521 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5524 /* XXX: this is not safe at all... localization of /fail/ */
5525 - (void) _clickButtonWithName:(NSString *)name {
5526 if ([name isEqualToString:UCLocalize("CLEAR")])
5527 [delegate_ clearPackage:package_];
5528 else if ([name isEqualToString:UCLocalize("INSTALL")])
5529 [delegate_ installPackage:package_];
5530 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5531 [delegate_ installPackage:package_];
5532 else if ([name isEqualToString:UCLocalize("REMOVE")])
5533 [delegate_ removePackage:package_];
5534 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5535 [delegate_ installPackage:package_];
5536 else _assert(false);
5539 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5540 NSString *context([sheet context]);
5542 if ([context isEqualToString:@"modify"]) {
5543 if (button != [sheet cancelButtonIndex]) {
5544 NSString *buttonName = [buttons_ objectAtIndex:button];
5545 [self _clickButtonWithName:buttonName];
5548 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5552 - (bool) _allowJavaScriptPanel {
5557 - (void) _customButtonClicked {
5558 int count([buttons_ count]);
5563 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5565 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5566 [buttons addObjectsFromArray:buttons_];
5568 UIActionSheet *sheet = [[[UIActionSheet alloc]
5571 cancelButtonTitle:nil
5572 destructiveButtonTitle:nil
5573 otherButtonTitles:nil
5576 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5578 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5579 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5581 [sheet setContext:@"modify"];
5583 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5587 // We don't want to allow non-commercial packages to do custom things to the install button,
5588 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5589 - (void) customButtonClicked {
5591 [super customButtonClicked];
5593 [self _customButtonClicked];
5596 - (void) reloadButtonClicked {
5597 // Don't reload a commerical package by tapping the loading button,
5598 // but if it's not an Install button, we should forward it on.
5599 if (![package_ uninstalled])
5600 [self _customButtonClicked];
5603 - (void) applyLoadingTitle {
5604 // Don't show "Loading" as the title. Ever.
5607 - (UIBarButtonItem *) rightButton {
5612 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5613 if ((self = [super init]) != nil) {
5614 database_ = database;
5615 buttons_ = [NSMutableArray arrayWithCapacity:4];
5616 name_ = [NSString stringWithString:name];
5617 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5621 - (void) reloadData {
5624 package_ = [database_ packageWithName:name_];
5626 [buttons_ removeAllObjects];
5628 if (package_ != nil) {
5629 [(Package *) package_ parse];
5631 commercial_ = [package_ isCommercial];
5633 if ([package_ mode] != nil)
5634 [buttons_ addObject:UCLocalize("CLEAR")];
5635 if ([package_ source] == nil);
5636 else if ([package_ upgradableAndEssential:NO])
5637 [buttons_ addObject:UCLocalize("UPGRADE")];
5638 else if ([package_ uninstalled])
5639 [buttons_ addObject:UCLocalize("INSTALL")];
5641 [buttons_ addObject:UCLocalize("REINSTALL")];
5642 if (![package_ uninstalled])
5643 [buttons_ addObject:UCLocalize("REMOVE")];
5647 switch ([buttons_ count]) {
5648 case 0: title = nil; break;
5649 case 1: title = [buttons_ objectAtIndex:0]; break;
5650 default: title = UCLocalize("MODIFY"); break;
5653 button_ = [[[UIBarButtonItem alloc]
5655 style:UIBarButtonItemStylePlain
5657 action:@selector(customButtonClicked)
5661 - (bool) isLoading {
5662 return commercial_ ? [super isLoading] : false;
5668 /* Package List Controller {{{ */
5669 @interface PackageListController : CyteViewController <
5670 UITableViewDataSource,
5673 _transient Database *database_;
5675 _H<NSArray> packages_;
5676 _H<NSMutableArray> sections_;
5677 _H<UITableView, 2> list_;
5678 _H<NSMutableArray> index_;
5679 _H<NSMutableDictionary> indices_;
5680 _H<NSString> title_;
5681 unsigned reloading_;
5684 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5685 - (void) setDelegate:(id)delegate;
5686 - (void) resetCursor;
5691 @implementation PackageListController
5693 - (bool) isSummarized {
5697 - (bool) showsSections {
5701 - (void) deselectWithAnimation:(BOOL)animated {
5702 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5705 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5706 CGRect base = [[self view] bounds];
5707 base.size.height -= bounds.size.height;
5708 base.origin = [list_ frame].origin;
5710 [UIView beginAnimations:nil context:NULL];
5711 [UIView setAnimationBeginsFromCurrentState:YES];
5712 [UIView setAnimationCurve:curve];
5713 [UIView setAnimationDuration:duration];
5714 [list_ setFrame:base];
5715 [UIView commitAnimations];
5718 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5719 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5722 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5723 [self resizeForKeyboardBounds:bounds duration:0];
5726 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5727 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5728 *curve = UIViewAnimationCurveEaseInOut;
5730 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5732 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5735 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5738 - (void) keyboardWillShow:(NSNotification *)notification {
5741 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5742 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5744 NSTimeInterval duration;
5745 UIViewAnimationCurve curve;
5746 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5748 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);
5749 UIViewController *base = self;
5750 while ([base parentViewController] != nil)
5751 base = [base parentViewController];
5752 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5753 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5755 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5756 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5758 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5761 - (void) keyboardWillHide:(NSNotification *)notification {
5762 NSTimeInterval duration;
5763 UIViewAnimationCurve curve;
5764 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5766 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5769 - (void) viewWillAppear:(BOOL)animated {
5770 [super viewWillAppear:animated];
5772 [self resizeForKeyboardBounds:CGRectZero];
5773 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5774 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5777 - (void) viewWillDisappear:(BOOL)animated {
5778 [super viewWillDisappear:animated];
5780 [self resizeForKeyboardBounds:CGRectZero];
5781 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5782 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5785 - (void) viewDidAppear:(BOOL)animated {
5786 [super viewDidAppear:animated];
5787 [self deselectWithAnimation:animated];
5790 - (void) didSelectPackage:(Package *)package {
5791 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5792 [view setDelegate:delegate_];
5793 [[self navigationController] pushViewController:view animated:YES];
5796 #if TryIndexedCollation
5797 + (BOOL) hasIndexedCollation {
5798 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5802 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5803 NSInteger count([sections_ count]);
5804 return count == 0 ? 1 : count;
5807 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5808 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5810 return [[sections_ objectAtIndex:section] name];
5813 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5814 if ([sections_ count] == 0)
5816 return [[sections_ objectAtIndex:section] count];
5819 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5820 @synchronized (database_) {
5821 if ([database_ era] != era_)
5824 Section *section([sections_ objectAtIndex:[path section]]);
5825 NSInteger row([path row]);
5826 Package *package([packages_ objectAtIndex:([section row] + row)]);
5827 return [[package retain] autorelease];
5830 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5831 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5833 cell = [[[PackageCell alloc] init] autorelease];
5834 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5838 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5839 Package *package([self packageAtIndexPath:path]);
5840 package = [database_ packageWithName:[package id]];
5841 [self didSelectPackage:package];
5844 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5845 if ([self showsSections])
5851 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5852 #if TryIndexedCollation
5853 if ([[self class] hasIndexedCollation]) {
5854 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5861 - (void) updateHeight {
5862 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5865 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5866 if ((self = [super init]) != nil) {
5867 database_ = database;
5868 title_ = [title copy];
5869 [[self navigationItem] setTitle:title_];
5871 #if TryIndexedCollation
5872 if ([[self class] hasIndexedCollation])
5873 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5876 index_ = [NSMutableArray arrayWithCapacity:32];
5878 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5880 packages_ = [NSArray array];
5881 sections_ = [NSMutableArray arrayWithCapacity:16];
5886 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5888 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5889 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5890 [[self view] addSubview:list_];
5892 // XXX: is 20 the most optimal number here?
5893 [list_ setSectionIndexMinimumDisplayRowCount:20];
5895 [(UITableView *) list_ setDataSource:self];
5896 [list_ setDelegate:self];
5898 [self updateHeight];
5901 - (void) releaseSubviews {
5904 [super releaseSubviews];
5907 - (void) setDelegate:(id)delegate {
5908 delegate_ = delegate;
5911 - (bool) shouldYield {
5915 - (bool) shouldBlock {
5919 - (NSMutableArray *) _reloadPackages {
5920 @synchronized (database_) {
5921 era_ = [database_ era];
5922 NSArray *packages([database_ packages]);
5924 return [NSMutableArray arrayWithArray:packages];
5927 - (void) _reloadData {
5928 if (reloading_ != 0) {
5935 if ([self shouldYield]) {
5939 if (![self shouldBlock])
5942 hud = [delegate_ addProgressHUD];
5943 [hud setText:UCLocalize("LOADING")];
5947 packages = [self yieldToSelector:@selector(_reloadPackages)];
5950 [delegate_ removeProgressHUD:hud];
5951 } while (reloading_ == 2);
5955 packages = [self _reloadPackages];
5958 packages_ = packages;
5960 [indices_ removeAllObjects];
5961 [sections_ removeAllObjects];
5963 Section *section = nil;
5965 #if TryIndexedCollation
5966 if ([[self class] hasIndexedCollation]) {
5967 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5968 NSArray *titles = [collation sectionIndexTitles];
5971 _profile(PackageTable$reloadData$Section)
5972 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5976 _profile(PackageTable$reloadData$Section$Package)
5977 package = [packages_ objectAtIndex:offset];
5978 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5981 while (secidx < index) {
5984 _profile(PackageTable$reloadData$Section$Allocate)
5985 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5988 _profile(PackageTable$reloadData$Section$Add)
5989 [sections_ addObject:section];
5993 [section addToCount];
5999 [index_ removeAllObjects];
6001 bool sectioned([self showsSections]);
6003 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6004 [sections_ addObject:section];
6007 _profile(PackageTable$reloadData$Section)
6008 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6012 _profile(PackageTable$reloadData$Section$Package)
6013 package = [packages_ objectAtIndex:offset];
6014 index = [package index];
6017 if (sectioned && (section == nil || [section index] != index)) {
6018 _profile(PackageTable$reloadData$Section$Allocate)
6019 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6022 [index_ addObject:[section name]];
6023 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6025 _profile(PackageTable$reloadData$Section$Add)
6026 [sections_ addObject:section];
6030 [section addToCount];
6035 [self updateHeight];
6037 _profile(PackageTable$reloadData$List)
6038 [(UITableView *) list_ setDataSource:self];
6043 - (void) reloadData {
6045 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6048 - (void) resetCursor {
6049 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6052 - (void) clearData {
6053 [self updateHeight];
6055 [list_ setDataSource:nil];
6063 /* Filtered Package List Controller {{{ */
6064 @interface FilteredPackageListController : PackageListController {
6067 _H<NSObject> object_;
6070 - (void) setObject:(id)object;
6071 - (void) setObject:(id)object forFilter:(SEL)filter;
6074 - (void) setFilter:(SEL)filter;
6076 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6080 @implementation FilteredPackageListController
6086 - (void) setFilter:(SEL)filter {
6087 @synchronized (self) {
6090 /* XXX: this is an unsafe optimization of doomy hell */
6091 Method method(class_getInstanceMethod([Package class], filter));
6092 _assert(method != NULL);
6093 imp_ = method_getImplementation(method);
6094 _assert(imp_ != NULL);
6097 - (void) setObject:(id)object {
6098 @synchronized (self) {
6102 - (void) setObject:(id)object forFilter:(SEL)filter {
6103 @synchronized (self) {
6104 [self setFilter:filter];
6105 [self setObject:object];
6108 - (NSMutableArray *) _reloadPackages {
6109 @synchronized (database_) {
6110 era_ = [database_ era];
6111 NSArray *packages([database_ packages]);
6113 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6117 _H<NSObject> object;
6119 @synchronized (self) {
6125 _profile(PackageTable$reloadData$Filter)
6126 for (Package *package in packages)
6127 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6128 [filtered addObject:package];
6134 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6135 if ((self = [super initWithDatabase:database title:title]) != nil) {
6136 [self setFilter:filter];
6137 [self setObject:object];
6144 /* Home Controller {{{ */
6145 @interface HomeController : CydiaWebViewController {
6150 @implementation HomeController
6153 if ((self = [super init]) != nil) {
6154 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6159 - (NSURL *) navigationURL {
6160 return [NSURL URLWithString:@"cydia://home"];
6163 - (void) aboutButtonClicked {
6164 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6166 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6167 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6168 [alert setCancelButtonIndex:0];
6171 @"Copyright \u00a9 2008-2011\n"
6174 "Jay Freeman (saurik)\n"
6175 "saurik@saurik.com\n"
6176 "http://www.saurik.com/"
6182 - (UIBarButtonItem *) leftButton {
6183 return [[[UIBarButtonItem alloc]
6184 initWithTitle:UCLocalize("ABOUT")
6185 style:UIBarButtonItemStylePlain
6187 action:@selector(aboutButtonClicked)
6193 /* Manage Controller {{{ */
6194 @interface ManageController : CydiaWebViewController {
6197 - (void) queueStatusDidChange;
6201 @implementation ManageController
6204 if ((self = [super init]) != nil) {
6205 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6209 - (NSURL *) navigationURL {
6210 return [NSURL URLWithString:@"cydia://manage"];
6213 - (UIBarButtonItem *) leftButton {
6214 return [[[UIBarButtonItem alloc]
6215 initWithTitle:UCLocalize("SETTINGS")
6216 style:UIBarButtonItemStylePlain
6218 action:@selector(settingsButtonClicked)
6222 - (void) settingsButtonClicked {
6223 [delegate_ showSettings];
6226 - (void) queueButtonClicked {
6230 - (UIBarButtonItem *) customButton {
6231 return Queuing_ ? [[[UIBarButtonItem alloc]
6232 initWithTitle:UCLocalize("QUEUE")
6233 style:UIBarButtonItemStyleDone
6235 action:@selector(queueButtonClicked)
6236 ] autorelease] : [super customButton];
6239 - (void) queueStatusDidChange {
6240 [self applyRightButton];
6243 - (bool) isLoading {
6244 return !Queuing_ && [super isLoading];
6250 /* Refresh Bar {{{ */
6251 @interface RefreshBar : UINavigationBar {
6252 _H<UIProgressIndicator> indicator_;
6253 _H<UITextLabel> prompt_;
6254 _H<UIProgressBar> progress_;
6255 _H<UINavigationButton> cancel_;
6260 @implementation RefreshBar
6262 - (void) positionViews {
6263 CGRect frame = [cancel_ frame];
6264 frame.size = [cancel_ sizeThatFits:frame.size];
6265 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6266 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6267 [cancel_ setFrame:frame];
6269 CGSize prgsize = {75, 100};
6271 [self frame].size.width - prgsize.width - 10,
6272 ([self frame].size.height - prgsize.height) / 2
6274 [progress_ setFrame:prgrect];
6276 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6277 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6278 CGRect indrect = {{indoffset, indoffset}, indsize};
6279 [indicator_ setFrame:indrect];
6281 CGSize prmsize = {215, indsize.height + 4};
6283 indoffset * 2 + indsize.width,
6284 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6286 [prompt_ setFrame:prmrect];
6289 - (void) setFrame:(CGRect)frame {
6290 [super setFrame:frame];
6291 [self positionViews];
6294 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6295 if ((self = [super initWithFrame:frame]) != nil) {
6296 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6298 [self setBarStyle:UIBarStyleBlack];
6300 UIBarStyle barstyle([self _barStyle:NO]);
6301 bool ugly(barstyle == UIBarStyleDefault);
6303 UIProgressIndicatorStyle style = ugly ?
6304 UIProgressIndicatorStyleMediumBrown :
6305 UIProgressIndicatorStyleMediumWhite;
6307 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6308 [(UIProgressIndicator *) indicator_ setStyle:style];
6309 [indicator_ startAnimation];
6310 [self addSubview:indicator_];
6312 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6313 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6314 [prompt_ setBackgroundColor:[UIColor clearColor]];
6315 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6316 [self addSubview:prompt_];
6318 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6319 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6320 [(UIProgressBar *) progress_ setStyle:0];
6321 [self addSubview:progress_];
6323 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6324 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6325 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6326 [cancel_ setBarStyle:barstyle];
6328 [self positionViews];
6332 - (void) setCancellable:(bool)cancellable {
6334 [self addSubview:cancel_];
6336 [cancel_ removeFromSuperview];
6340 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6341 [progress_ setProgress:0];
6345 [self setCancellable:NO];
6348 - (void) setPrompt:(NSString *)prompt {
6349 [prompt_ setText:prompt];
6352 - (void) setProgress:(float)progress {
6353 [progress_ setProgress:progress];
6359 /* Cydia Navigation Controller Interface {{{ */
6360 @interface UINavigationController (Cydia)
6362 - (NSArray *) navigationURLCollection;
6363 - (void) unloadData;
6368 /* Cydia Tab Bar Controller {{{ */
6369 @interface CYTabBarController : UITabBarController <
6370 UITabBarControllerDelegate,
6373 _transient Database *database_;
6374 _H<RefreshBar, 1> refreshbar_;
6378 // XXX: ok, "updatedelegate_"?...
6379 _transient NSObject<CydiaDelegate> *updatedelegate_;
6381 _H<UIViewController> remembered_;
6382 _transient UIViewController *transient_;
6385 - (NSArray *) navigationURLCollection;
6386 - (void) dropBar:(BOOL)animated;
6387 - (void) beginUpdate;
6388 - (void) raiseBar:(BOOL)animated;
6390 - (void) unloadData;
6394 @implementation CYTabBarController
6396 - (void) setUnselectedViewController:(UIViewController *)transient {
6397 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6398 if (transient != nil) {
6399 if (transient_ == nil)
6400 remembered_ = [controllers objectAtIndex:0];
6401 transient_ = transient;
6402 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6403 [controllers replaceObjectAtIndex:0 withObject:transient_];
6404 [self setSelectedIndex:0];
6405 [self setViewControllers:controllers];
6406 [self concealTabBarSelection];
6407 } else if (remembered_ != nil) {
6408 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6409 transient_ = transient;
6410 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6412 [self setViewControllers:controllers];
6413 [self revealTabBarSelection];
6417 - (UIViewController *) unselectedViewController {
6421 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6422 if ([self unselectedViewController])
6423 [self setUnselectedViewController:nil];
6426 - (NSArray *) navigationURLCollection {
6427 NSMutableArray *items([NSMutableArray array]);
6429 // XXX: Should this deal with transient view controllers?
6430 for (id navigation in [self viewControllers]) {
6431 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6433 [items addObject:stack];
6439 - (void) unloadData {
6442 for (UINavigationController *controller in [self viewControllers])
6443 [controller unloadData];
6445 if (UIViewController *selected = [self selectedViewController])
6446 [selected reloadData];
6448 if (UIViewController *unselected = [self unselectedViewController]) {
6449 [unselected unloadData];
6450 [unselected reloadData];
6455 [[NSNotificationCenter defaultCenter] removeObserver:self];
6460 - (id) initWithDatabase:(Database *)database {
6461 if ((self = [super init]) != nil) {
6462 database_ = database;
6463 [self setDelegate:self];
6465 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6466 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6468 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6472 - (void) setUpdate:(NSDate *)date {
6476 - (void) beginUpdate {
6477 [(RefreshBar *) refreshbar_ start];
6480 [updatedelegate_ retainNetworkActivityIndicator];
6484 detachNewThreadSelector:@selector(performUpdate)
6490 - (void) performUpdate {
6491 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6494 status.setDelegate(self);
6495 [database_ updateWithStatus:status];
6498 performSelectorOnMainThread:@selector(completeUpdate)
6506 - (void) stopUpdateWithSelector:(SEL)selector {
6508 [updatedelegate_ releaseNetworkActivityIndicator];
6510 [self raiseBar:YES];
6513 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6516 - (void) completeUpdate {
6519 [self stopUpdateWithSelector:@selector(reloadData)];
6522 - (void) cancelUpdate {
6523 [self stopUpdateWithSelector:@selector(updateData)];
6526 - (void) cancelPressed {
6527 [self cancelUpdate];
6534 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6535 [refreshbar_ setPrompt:[event compoundMessage]];
6538 - (bool) isProgressCancelled {
6542 - (void) setProgressCancellable:(NSNumber *)cancellable {
6543 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6546 - (void) setProgressPercent:(NSNumber *)percent {
6547 [refreshbar_ setProgress:[percent floatValue]];
6550 - (void) setProgressStatus:(NSDictionary *)status {
6552 [self setProgressPercent:[status objectForKey:@"Percent"]];
6555 - (void) setUpdateDelegate:(id)delegate {
6556 updatedelegate_ = delegate;
6559 - (UIView *) transitionView {
6560 if ([self respondsToSelector:@selector(_transitionView)])
6561 return [self _transitionView];
6563 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6566 - (void) dropBar:(BOOL)animated {
6571 UIView *transition([self transitionView]);
6572 [[self view] addSubview:refreshbar_];
6574 CGRect barframe([refreshbar_ frame]);
6576 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6577 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6579 barframe.origin.y = 0;
6581 [refreshbar_ setFrame:barframe];
6584 [UIView beginAnimations:nil context:NULL];
6586 CGRect viewframe = [transition frame];
6587 viewframe.origin.y += barframe.size.height;
6588 viewframe.size.height -= barframe.size.height;
6589 [transition setFrame:viewframe];
6592 [UIView commitAnimations];
6594 // Ensure bar has the proper width for our view, it might have changed
6595 barframe.size.width = viewframe.size.width;
6596 [refreshbar_ setFrame:barframe];
6599 - (void) raiseBar:(BOOL)animated {
6604 UIView *transition([self transitionView]);
6605 [refreshbar_ removeFromSuperview];
6607 CGRect barframe([refreshbar_ frame]);
6610 [UIView beginAnimations:nil context:NULL];
6612 CGRect viewframe = [transition frame];
6613 viewframe.origin.y -= barframe.size.height;
6614 viewframe.size.height += barframe.size.height;
6615 [transition setFrame:viewframe];
6618 [UIView commitAnimations];
6621 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6622 bool dropped(dropped_);
6627 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6633 - (void) statusBarFrameChanged:(NSNotification *)notification {
6643 /* Cydia Navigation Controller Implementation {{{ */
6644 @implementation UINavigationController (Cydia)
6646 - (NSArray *) navigationURLCollection {
6647 NSMutableArray *stack([NSMutableArray array]);
6649 for (CyteViewController *controller in [self viewControllers]) {
6650 NSString *url = [[controller navigationURL] absoluteString];
6652 [stack addObject:url];
6658 - (void) reloadData {
6661 if (UIViewController *visible = [self visibleViewController])
6662 [visible reloadData];
6665 - (void) unloadData {
6666 for (CyteViewController *page in [self viewControllers])
6675 /* Cydia:// Protocol {{{ */
6676 @interface CydiaURLProtocol : NSURLProtocol {
6681 @implementation CydiaURLProtocol
6683 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6684 NSURL *url([request URL]);
6688 NSString *scheme([[url scheme] lowercaseString]);
6689 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6691 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6697 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6701 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6702 id<NSURLProtocolClient> client([self client]);
6704 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6706 NSData *data(UIImagePNGRepresentation(icon));
6708 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6709 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6710 [client URLProtocol:self didLoadData:data];
6711 [client URLProtocolDidFinishLoading:self];
6715 - (void) startLoading {
6716 id<NSURLProtocolClient> client([self client]);
6717 NSURLRequest *request([self request]);
6719 NSURL *url([request URL]);
6720 NSString *href([url absoluteString]);
6721 NSString *scheme([[url scheme] lowercaseString]);
6725 if ([scheme isEqualToString:@"cydia"])
6726 path = [href substringFromIndex:8];
6727 else if ([scheme isEqualToString:@"about"])
6728 path = [href substringFromIndex:12];
6729 else _assert(false);
6731 NSRange slash([path rangeOfString:@"/"]);
6734 if (slash.location == NSNotFound) {
6738 command = [path substringToIndex:slash.location];
6739 path = [path substringFromIndex:(slash.location + 1)];
6742 Database *database([Database sharedInstance]);
6744 if ([command isEqualToString:@"package-icon"]) {
6747 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6748 Package *package([database packageWithName:path]);
6752 UIImage *icon([package icon]);
6753 [self _returnPNGWithImage:icon forRequest:request];
6754 } else if ([command isEqualToString:@"source-icon"]) {
6757 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6758 NSString *source(Simplify(path));
6759 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6761 icon = [UIImage applicationImageNamed:@"unknown.png"];
6762 [self _returnPNGWithImage:icon forRequest:request];
6763 } else if ([command isEqualToString:@"uikit-image"]) {
6766 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6767 UIImage *icon(_UIImageWithName(path));
6768 [self _returnPNGWithImage:icon forRequest:request];
6769 } else if ([command isEqualToString:@"section-icon"]) {
6772 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6773 NSString *section(Simplify(path));
6774 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6776 icon = [UIImage applicationImageNamed:@"unknown.png"];
6777 [self _returnPNGWithImage:icon forRequest:request];
6779 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6783 - (void) stopLoading {
6789 /* Section Controller {{{ */
6790 @interface SectionController : FilteredPackageListController {
6791 _H<NSString> section_;
6794 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6798 @implementation SectionController
6800 - (NSURL *) navigationURL {
6801 NSString *name = section_;
6805 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6808 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6811 title = UCLocalize("ALL_PACKAGES");
6812 else if (![name isEqual:@""])
6813 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6815 title = UCLocalize("NO_SECTION");
6817 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6824 /* Sections Controller {{{ */
6825 @interface SectionsController : CyteViewController <
6826 UITableViewDataSource,
6829 _transient Database *database_;
6830 _H<NSMutableArray> sections_;
6831 _H<NSMutableArray> filtered_;
6832 _H<UITableView, 2> list_;
6835 - (id) initWithDatabase:(Database *)database;
6836 - (void) editButtonClicked;
6840 @implementation SectionsController
6842 - (NSURL *) navigationURL {
6843 return [NSURL URLWithString:@"cydia://sections"];
6846 - (void) updateNavigationItem {
6847 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6848 if ([sections_ count] == 0) {
6849 [[self navigationItem] setRightBarButtonItem:nil];
6851 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6852 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6854 action:@selector(editButtonClicked)
6855 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6859 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6860 [super setEditing:editing animated:animated];
6865 [delegate_ updateData];
6867 [self updateNavigationItem];
6870 - (void) viewDidAppear:(BOOL)animated {
6871 [super viewDidAppear:animated];
6872 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6875 - (void) viewWillDisappear:(BOOL)animated {
6876 [super viewWillDisappear:animated];
6877 if ([self isEditing]) [self setEditing:NO];
6880 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6881 Section *section = nil;
6882 int index = [indexPath row];
6883 if (![self isEditing]) {
6886 section = [filtered_ objectAtIndex:index];
6888 section = [sections_ objectAtIndex:index];
6893 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6894 if ([self isEditing])
6895 return [sections_ count];
6897 return [filtered_ count] + 1;
6900 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6904 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6905 static NSString *reuseIdentifier = @"SectionCell";
6907 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6909 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6911 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6916 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6917 if ([self isEditing])
6920 Section *section = [self sectionAtIndexPath:indexPath];
6922 SectionController *controller = [[[SectionController alloc]
6923 initWithDatabase:database_
6924 section:[section name]
6926 [controller setDelegate:delegate_];
6928 [[self navigationController] pushViewController:controller animated:YES];
6932 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6934 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6935 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6936 [list_ setRowHeight:45.0f];
6937 [(UITableView *) list_ setDataSource:self];
6938 [list_ setDelegate:self];
6939 [[self view] addSubview:list_];
6942 - (void) viewDidLoad {
6943 [super viewDidLoad];
6945 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6948 - (void) releaseSubviews {
6951 [super releaseSubviews];
6954 - (id) initWithDatabase:(Database *)database {
6955 if ((self = [super init]) != nil) {
6956 database_ = database;
6958 sections_ = [NSMutableArray arrayWithCapacity:16];
6959 filtered_ = [NSMutableArray arrayWithCapacity:16];
6963 - (void) reloadData {
6966 NSArray *packages = [database_ packages];
6968 [sections_ removeAllObjects];
6969 [filtered_ removeAllObjects];
6971 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6974 for (Package *package in packages) {
6975 NSString *name([package section]);
6976 NSString *key(name == nil ? @"" : name);
6980 _profile(SectionsView$reloadData$Section)
6981 section = [sections objectForKey:key];
6982 if (section == nil) {
6983 _profile(SectionsView$reloadData$Section$Allocate)
6984 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6985 [sections setObject:section forKey:key];
6990 [section addToCount];
6992 _profile(SectionsView$reloadData$Filter)
6993 if (![package valid] || ![package visible])
7001 [sections_ addObjectsFromArray:[sections allValues]];
7003 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7005 for (Section *section in (id) sections_) {
7006 size_t count([section row]);
7010 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7011 [section setCount:count];
7012 [filtered_ addObject:section];
7015 [self updateNavigationItem];
7020 - (void) editButtonClicked {
7021 [self setEditing:![self isEditing] animated:YES];
7027 /* Changes Controller {{{ */
7028 @interface ChangesController : CyteViewController <
7029 UITableViewDataSource,
7032 _transient Database *database_;
7034 _H<NSArray> packages_;
7035 _H<NSMutableArray> sections_;
7036 _H<UITableView, 2> list_;
7040 - (id) initWithDatabase:(Database *)database;
7044 @implementation ChangesController
7046 - (NSURL *) navigationURL {
7047 return [NSURL URLWithString:@"cydia://changes"];
7050 - (void) viewDidAppear:(BOOL)animated {
7051 [super viewDidAppear:animated];
7052 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7055 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7056 NSInteger count([sections_ count]);
7057 return count == 0 ? 1 : count;
7060 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7061 if ([sections_ count] == 0)
7063 return [[sections_ objectAtIndex:section] name];
7066 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7067 if ([sections_ count] == 0)
7069 return [[sections_ objectAtIndex:section] count];
7072 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7073 @synchronized (database_) {
7074 if ([database_ era] != era_)
7077 NSUInteger sectionIndex([path section]);
7078 if (sectionIndex >= [sections_ count])
7080 Section *section([sections_ objectAtIndex:sectionIndex]);
7081 NSInteger row([path row]);
7082 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7085 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7086 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7088 cell = [[[PackageCell alloc] init] autorelease];
7089 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7093 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7094 Package *package([self packageAtIndexPath:path]);
7095 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7096 [view setDelegate:delegate_];
7097 [[self navigationController] pushViewController:view animated:YES];
7101 - (void) refreshButtonClicked {
7102 [delegate_ beginUpdate];
7103 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7106 - (void) upgradeButtonClicked {
7107 [delegate_ distUpgrade];
7111 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7113 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7114 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7115 [list_ setRowHeight:73];
7116 [(UITableView *) list_ setDataSource:self];
7117 [list_ setDelegate:self];
7118 [[self view] addSubview:list_];
7121 - (void) viewDidLoad {
7122 [super viewDidLoad];
7124 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7127 - (void) releaseSubviews {
7130 [super releaseSubviews];
7133 - (id) initWithDatabase:(Database *)database {
7134 if ((self = [super init]) != nil) {
7135 database_ = database;
7137 packages_ = [NSArray array];
7138 sections_ = [NSMutableArray arrayWithCapacity:16];
7142 - (NSMutableArray *) _reloadPackages {
7143 @synchronized (database_) {
7144 era_ = [database_ era];
7145 NSArray *packages([database_ packages]);
7147 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7150 _profile(ChangesController$_reloadPackages$Filter)
7151 for (Package *package in packages)
7152 if ([package upgradableAndEssential:YES] || [package visible])
7153 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7156 _profile(ChangesController$_reloadPackages$radixSort)
7157 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7164 - (void) _reloadData {
7169 UIProgressHUD *hud([delegate_ addProgressHUD]);
7170 [hud setText:UCLocalize("LOADING")];
7171 //NSLog(@"HUD:%@::%@", delegate_, hud);
7172 packages = [self yieldToSelector:@selector(_reloadPackages)];
7173 [delegate_ removeProgressHUD:hud];
7175 packages = [self _reloadPackages];
7178 @synchronized (database_) {
7179 if (era_ != [database_ era])
7182 packages_ = packages;
7183 [sections_ removeAllObjects];
7185 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7186 Section *ignored = nil;
7187 Section *section = nil;
7191 bool unseens = false;
7193 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7195 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7196 Package *package = [packages_ objectAtIndex:offset];
7198 BOOL uae = [package upgradableAndEssential:YES];
7202 time_t seen([package seen]);
7204 if (section == nil || last != seen) {
7208 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7211 _profile(ChangesController$reloadData$Allocate)
7212 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7213 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7214 [sections_ addObject:section];
7218 [section addToCount];
7219 } else if ([package ignored]) {
7220 if (ignored == nil) {
7221 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7223 [ignored addToCount];
7226 [upgradable addToCount];
7231 CFRelease(formatter);
7234 Section *last = [sections_ lastObject];
7235 size_t count = [last count];
7236 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7237 [sections_ removeLastObject];
7240 if ([ignored count] != 0)
7241 [sections_ insertObject:ignored atIndex:0];
7243 [sections_ insertObject:upgradable atIndex:0];
7248 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7249 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7250 style:UIBarButtonItemStylePlain
7252 action:@selector(upgradeButtonClicked)
7255 if (![delegate_ updating])
7256 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7257 initWithTitle:UCLocalize("REFRESH")
7258 style:UIBarButtonItemStylePlain
7260 action:@selector(refreshButtonClicked)
7266 - (void) reloadData {
7268 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7273 /* Search Controller {{{ */
7274 @interface SearchController : FilteredPackageListController <
7277 _H<UISearchBar, 1> search_;
7281 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7282 - (void) reloadData;
7286 @implementation SearchController
7288 - (NSURL *) navigationURL {
7289 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7290 return [NSURL URLWithString:@"cydia://search"];
7292 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7295 - (void) useSearch {
7296 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7301 - (void) viewWillAppear:(BOOL)animated {
7302 [super viewWillAppear:animated];
7304 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7308 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7309 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7314 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7315 [search_ resignFirstResponder];
7319 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7320 [search_ setText:@""];
7321 [self searchBarButtonClicked:searchBar];
7324 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7325 [self searchBarButtonClicked:searchBar];
7328 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7329 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7333 - (bool) shouldYield {
7337 - (bool) shouldBlock {
7338 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7341 - (bool) isSummarized {
7342 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7345 - (bool) showsSections {
7349 - (NSMutableArray *) _reloadPackages {
7350 NSMutableArray *packages([super _reloadPackages]);
7351 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7352 [packages radixSortUsingSelector:@selector(rank)];
7356 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7357 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7358 search_ = [[[UISearchBar alloc] init] autorelease];
7359 [search_ setDelegate:self];
7362 [search_ setText:query];
7366 - (void) viewDidAppear:(BOOL)animated {
7367 [super viewDidAppear:animated];
7369 if (!searchloaded_) {
7370 searchloaded_ = YES;
7371 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7372 [search_ layoutSubviews];
7373 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7375 UITextField *textField;
7376 if ([search_ respondsToSelector:@selector(searchField)])
7377 textField = [search_ searchField];
7379 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7381 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7382 [textField setEnablesReturnKeyAutomatically:NO];
7383 [[self navigationItem] setTitleView:textField];
7387 - (void) reloadData {
7388 id object([search_ text]);
7389 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7390 object = [object componentsSeparatedByString:@" "];
7392 [self setObject:object];
7398 - (void) didSelectPackage:(Package *)package {
7399 [search_ resignFirstResponder];
7400 [super didSelectPackage:package];
7405 /* Package Settings Controller {{{ */
7406 @interface PackageSettingsController : CyteViewController <
7407 UITableViewDataSource,
7410 _transient Database *database_;
7412 _H<Package> package_;
7413 _H<UITableView, 2> table_;
7414 _H<UISwitch> subscribedSwitch_;
7415 _H<UISwitch> ignoredSwitch_;
7416 _H<UITableViewCell> subscribedCell_;
7417 _H<UITableViewCell> ignoredCell_;
7420 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7424 @implementation PackageSettingsController
7426 - (NSURL *) navigationURL {
7427 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7430 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7431 if (package_ == nil)
7434 if ([package_ installed] == nil)
7440 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7441 if (package_ == nil)
7444 // both sections contain just one item right now.
7448 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7452 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7454 return UCLocalize("SHOW_ALL_CHANGES_EX");
7456 return UCLocalize("IGNORE_UPGRADES_EX");
7459 - (void) onSubscribed:(id)control {
7460 bool value([control isOn]);
7461 if (package_ == nil)
7463 if ([package_ setSubscribed:value])
7464 [delegate_ updateData];
7467 - (void) _updateIgnored {
7468 const char *package([name_ UTF8String]);
7469 bool on([ignoredSwitch_ isOn]);
7471 pid_t pid(ExecFork());
7473 FILE *dpkg(popen("dpkg --set-selections", "w"));
7474 fwrite(package, strlen(package), 1, dpkg);
7477 fwrite(" hold\n", 6, 1, dpkg);
7479 fwrite(" install\n", 9, 1, dpkg);
7489 int result(waitpid(pid, &status, 0));
7492 _assert(result == pid);
7498 - (void) onIgnored:(id)control {
7499 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7500 [invocation setTarget:self];
7501 [invocation setSelector:@selector(_updateIgnored)];
7503 [delegate_ reloadDataWithInvocation:invocation];
7506 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7507 if (package_ == nil)
7510 switch ([indexPath section]) {
7511 case 0: return subscribedCell_;
7512 case 1: return ignoredCell_;
7521 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7523 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7524 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7525 [(UITableView *) table_ setDataSource:self];
7526 [table_ setDelegate:self];
7527 [[self view] addSubview:table_];
7529 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7530 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7531 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7533 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7534 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7535 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7537 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7538 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7539 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7540 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7542 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7543 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7544 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7545 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7548 - (void) viewDidLoad {
7549 [super viewDidLoad];
7551 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7554 - (void) releaseSubviews {
7556 subscribedCell_ = nil;
7558 ignoredSwitch_ = nil;
7559 subscribedSwitch_ = nil;
7561 [super releaseSubviews];
7564 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7565 if ((self = [super init]) != nil) {
7566 database_ = database;
7571 - (void) reloadData {
7574 package_ = [database_ packageWithName:name_];
7576 if (package_ != nil) {
7577 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7578 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7579 } // XXX: what now, G?
7581 [table_ reloadData];
7587 /* Installed Controller {{{ */
7588 @interface InstalledController : FilteredPackageListController {
7592 - (id) initWithDatabase:(Database *)database;
7594 - (void) updateRoleButton;
7595 - (void) queueStatusDidChange;
7599 @implementation InstalledController
7601 - (NSURL *) navigationURL {
7602 return [NSURL URLWithString:@"cydia://installed"];
7605 - (id) initWithDatabase:(Database *)database {
7606 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7607 [self updateRoleButton];
7608 [self queueStatusDidChange];
7613 - (void) queueButtonClicked {
7618 - (void) queueStatusDidChange {
7622 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7623 initWithTitle:UCLocalize("QUEUE")
7624 style:UIBarButtonItemStyleDone
7626 action:@selector(queueButtonClicked)
7629 [[self navigationItem] setLeftBarButtonItem:nil];
7635 - (void) updateRoleButton {
7636 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7637 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7638 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7639 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7641 action:@selector(roleButtonClicked)
7645 - (void) roleButtonClicked {
7646 [self setObject:[NSNumber numberWithBool:expert_]];
7650 [self updateRoleButton];
7656 /* Source Cell {{{ */
7657 @interface SourceCell : CyteTableViewCell <
7658 CyteTableViewCellDelegate
7661 _H<NSString> origin_;
7662 _H<NSString> label_;
7665 - (void) setSource:(Source *)source;
7669 @implementation SourceCell
7671 - (void) _setImage:(UIImage *)image {
7673 [content_ setNeedsDisplay];
7676 - (void) _setSource:(Source *)source {
7677 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7679 if (NSString *base = [source base])
7680 if ([base length] != 0) {
7681 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7683 if (NSData *data = [NSURLConnection
7684 sendSynchronousRequest:[NSURLRequest
7686 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7690 returningResponse:NULL
7693 if (UIImage *image = [UIImage imageWithData:data])
7694 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7700 - (void) setSource:(Source *)source {
7701 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7703 origin_ = [source name];
7704 label_ = [source uri];
7706 [content_ setNeedsDisplay];
7708 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7711 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7712 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7713 UIView *content([self contentView]);
7714 CGRect bounds([content bounds]);
7716 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7717 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7718 [content_ setBackgroundColor:[UIColor whiteColor]];
7719 [content addSubview:content_];
7721 [content_ setDelegate:self];
7722 [content_ setOpaque:YES];
7726 - (NSString *) accessibilityLabel {
7730 - (void) drawContentRect:(CGRect)rect {
7731 bool highlighted(highlighted_);
7732 float width(rect.size.width);
7735 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7742 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7746 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7751 /* Source Controller {{{ */
7752 @interface SourceController : FilteredPackageListController {
7753 _transient Source *source_;
7757 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7761 @implementation SourceController
7763 - (NSURL *) navigationURL {
7764 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7767 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7768 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7770 key_ = [source key];
7774 - (void) reloadData {
7775 source_ = [database_ sourceWithKey:key_];
7776 key_ = [source_ key];
7777 [self setObject:source_];
7779 [[self navigationItem] setTitle:[source_ label]];
7786 /* Sources Controller {{{ */
7787 @interface SourcesController : CyteViewController <
7788 UITableViewDataSource,
7791 _transient Database *database_;
7792 _H<UITableView, 2> list_;
7793 _H<NSMutableArray> sources_;
7797 _H<UIProgressHUD> hud_;
7800 //NSURLConnection *installer_;
7801 NSURLConnection *trivial_;
7802 NSURLConnection *trivial_bz2_;
7803 NSURLConnection *trivial_gz_;
7804 //NSURLConnection *automatic_;
7809 - (id) initWithDatabase:(Database *)database;
7810 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7814 @implementation SourcesController
7816 - (void) _releaseConnection:(NSURLConnection *)connection {
7817 if (connection != nil) {
7818 [connection cancel];
7819 //[connection setDelegate:nil];
7820 [connection release];
7825 //[self _releaseConnection:installer_];
7826 [self _releaseConnection:trivial_];
7827 [self _releaseConnection:trivial_gz_];
7828 [self _releaseConnection:trivial_bz2_];
7829 //[self _releaseConnection:automatic_];
7834 - (NSURL *) navigationURL {
7835 return [NSURL URLWithString:@"cydia://sources"];
7838 - (void) viewDidAppear:(BOOL)animated {
7839 [super viewDidAppear:animated];
7840 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7843 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7844 return offset_ == 0 ? 1 : 2;
7847 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7848 switch (section + (offset_ == 0 ? 1 : 0)) {
7849 case 0: return UCLocalize("ENTERED_BY_USER");
7850 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7856 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7857 int count = [sources_ count];
7859 case 0: return (offset_ == 0 ? count : offset_);
7860 case 1: return count - offset_;
7866 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7868 switch (indexPath.section) {
7869 case 0: idx = indexPath.row; break;
7870 case 1: idx = indexPath.row + offset_; break;
7874 return [sources_ objectAtIndex:idx];
7877 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7878 static NSString *cellIdentifier = @"SourceCell";
7880 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7881 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7882 [cell setSource:[self sourceAtIndexPath:indexPath]];
7883 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7888 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7889 Source *source = [self sourceAtIndexPath:indexPath];
7891 SourceController *controller = [[[SourceController alloc]
7892 initWithDatabase:database_
7896 [controller setDelegate:delegate_];
7898 [[self navigationController] pushViewController:controller animated:YES];
7901 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7902 Source *source = [self sourceAtIndexPath:indexPath];
7903 return [source record] != nil;
7906 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7907 if (editingStyle == UITableViewCellEditingStyleDelete) {
7908 Source *source = [self sourceAtIndexPath:indexPath];
7909 [Sources_ removeObjectForKey:[source key]];
7910 [delegate_ syncData];
7915 [delegate_ addTrivialSource:href_];
7916 [delegate_ syncData];
7919 - (NSString *) getWarning {
7920 NSString *href(href_);
7921 NSRange colon([href rangeOfString:@"://"]);
7922 if (colon.location != NSNotFound)
7923 href = [href substringFromIndex:(colon.location + 3)];
7924 href = [href stringByAddingPercentEscapes];
7925 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7926 href = [href stringByCachingURLWithCurrentCDN];
7928 NSURL *url([NSURL URLWithString:href]);
7930 NSStringEncoding encoding;
7931 NSError *error(nil);
7933 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7934 return [warning length] == 0 ? nil : warning;
7938 - (void) _endConnection:(NSURLConnection *)connection {
7939 // XXX: the memory management in this method is horribly awkward
7941 NSURLConnection **field = NULL;
7942 if (connection == trivial_)
7944 else if (connection == trivial_bz2_)
7945 field = &trivial_bz2_;
7946 else if (connection == trivial_gz_)
7947 field = &trivial_gz_;
7948 _assert(field != NULL);
7949 [connection release];
7954 trivial_bz2_ == nil &&
7957 [delegate_ releaseNetworkActivityIndicator];
7959 [delegate_ removeProgressHUD:hud_];
7965 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7968 UIAlertView *alert = [[[UIAlertView alloc]
7969 initWithTitle:UCLocalize("SOURCE_WARNING")
7972 cancelButtonTitle:UCLocalize("CANCEL")
7974 UCLocalize("ADD_ANYWAY"),
7978 [alert setContext:@"warning"];
7979 [alert setNumberOfRows:1];
7983 } else if (error_ != nil) {
7984 UIAlertView *alert = [[[UIAlertView alloc]
7985 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7986 message:[error_ localizedDescription]
7988 cancelButtonTitle:UCLocalize("OK")
7989 otherButtonTitles:nil
7992 [alert setContext:@"urlerror"];
7995 UIAlertView *alert = [[[UIAlertView alloc]
7996 initWithTitle:UCLocalize("NOT_REPOSITORY")
7997 message:UCLocalize("NOT_REPOSITORY_EX")
7999 cancelButtonTitle:UCLocalize("OK")
8000 otherButtonTitles:nil
8003 [alert setContext:@"trivial"];
8012 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8013 switch ([response statusCode]) {
8019 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8020 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8022 [self _endConnection:connection];
8025 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8026 [self _endConnection:connection];
8029 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8030 NSMutableURLRequest *request = [NSMutableURLRequest
8031 requestWithURL:[NSURL URLWithString:href]
8032 cachePolicy:NSURLRequestUseProtocolCachePolicy
8033 timeoutInterval:120.0
8036 [request setHTTPMethod:method];
8038 if (Machine_ != NULL)
8039 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8040 if (UniqueID_ != nil)
8041 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8043 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8046 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8047 NSString *context([alert context]);
8049 if ([context isEqualToString:@"source"]) {
8052 NSString *href = [[alert textField] text];
8054 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8056 if (![href hasSuffix:@"/"])
8057 href_ = [href stringByAppendingString:@"/"];
8061 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8062 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8063 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8064 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8068 // XXX: this is stupid
8069 hud_ = [delegate_ addProgressHUD];
8070 [hud_ setText:UCLocalize("VERIFYING_URL")];
8071 [delegate_ retainNetworkActivityIndicator];
8080 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8081 } else if ([context isEqualToString:@"trivial"])
8082 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8083 else if ([context isEqualToString:@"urlerror"])
8084 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8085 else if ([context isEqualToString:@"warning"]) {
8099 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8104 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8106 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8107 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8108 [list_ setRowHeight:56];
8109 [(UITableView *) list_ setDataSource:self];
8110 [list_ setDelegate:self];
8111 [[self view] addSubview:list_];
8114 - (void) viewDidLoad {
8115 [super viewDidLoad];
8117 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8118 [self updateButtonsForEditingStatus:NO animated:NO];
8121 - (void) releaseSubviews {
8124 [super releaseSubviews];
8127 - (id) initWithDatabase:(Database *)database {
8128 if ((self = [super init]) != nil) {
8129 database_ = database;
8130 sources_ = [NSMutableArray arrayWithCapacity:16];
8134 - (void) reloadData {
8138 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8141 [sources_ removeAllObjects];
8142 [sources_ addObjectsFromArray:[database_ sources]];
8144 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8147 int count([sources_ count]);
8149 for (int i = 0; i != count; i++) {
8150 if ([[sources_ objectAtIndex:i] record] == nil)
8155 [list_ setEditing:NO];
8156 [self updateButtonsForEditingStatus:NO animated:NO];
8160 - (void) showAddSourcePrompt {
8161 UIAlertView *alert = [[[UIAlertView alloc]
8162 initWithTitle:UCLocalize("ENTER_APT_URL")
8165 cancelButtonTitle:UCLocalize("CANCEL")
8167 UCLocalize("ADD_SOURCE"),
8171 [alert setContext:@"source"];
8173 [alert setNumberOfRows:1];
8174 [alert addTextFieldWithValue:@"http://" label:@""];
8176 UITextInputTraits *traits = [[alert textField] textInputTraits];
8177 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8178 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8179 [traits setKeyboardType:UIKeyboardTypeURL];
8180 // XXX: UIReturnKeyDone
8181 [traits setReturnKeyType:UIReturnKeyNext];
8186 - (void) addButtonClicked {
8187 [self showAddSourcePrompt];
8190 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8191 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8192 initWithTitle:UCLocalize("ADD")
8193 style:UIBarButtonItemStylePlain
8195 action:@selector(addButtonClicked)
8196 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8198 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8199 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8200 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8202 action:@selector(editButtonClicked)
8203 ] autorelease] animated:animated];
8205 if (IsWildcat_ && !editing)
8206 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8207 initWithTitle:UCLocalize("SETTINGS")
8208 style:UIBarButtonItemStylePlain
8210 action:@selector(settingsButtonClicked)
8214 - (void) settingsButtonClicked {
8215 [delegate_ showSettings];
8218 - (void) editButtonClicked {
8219 [list_ setEditing:![list_ isEditing] animated:YES];
8221 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8227 /* Settings Controller {{{ */
8228 @interface SettingsController : CyteViewController <
8229 UITableViewDataSource,
8232 _transient Database *database_;
8233 // XXX: ok, "roledelegate_"?...
8234 _transient id roledelegate_;
8235 _H<UITableView, 2> table_;
8236 _H<UISegmentedControl> segment_;
8237 _H<UIView> container_;
8240 - (void) showDoneButton;
8241 - (void) resizeSegmentedControl;
8245 @implementation SettingsController
8248 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8250 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8251 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8252 [table_ setDelegate:self];
8253 [(UITableView *) table_ setDataSource:self];
8254 [[self view] addSubview:table_];
8256 NSArray *items = [NSArray arrayWithObjects:
8258 UCLocalize("HACKER"),
8259 UCLocalize("DEVELOPER"),
8261 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8262 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8263 [container_ addSubview:segment_];
8266 - (void) viewDidLoad {
8267 [super viewDidLoad];
8269 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8272 if ([Role_ isEqualToString:@"User"]) index = 0;
8273 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8274 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8276 [segment_ setSelectedSegmentIndex:index];
8277 [self showDoneButton];
8280 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8281 [self resizeSegmentedControl];
8284 - (void) releaseSubviews {
8289 [super releaseSubviews];
8292 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8293 if ((self = [super init]) != nil) {
8294 database_ = database;
8295 roledelegate_ = delegate;
8299 - (void) resizeSegmentedControl {
8300 CGFloat width = [[self view] frame].size.width;
8301 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8304 - (void) viewWillAppear:(BOOL)animated {
8305 [super viewWillAppear:animated];
8307 [self resizeSegmentedControl];
8310 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8311 [self resizeSegmentedControl];
8314 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8315 [self resizeSegmentedControl];
8319 NSString *role(nil);
8321 switch ([segment_ selectedSegmentIndex]) {
8322 case 0: role = @"User"; break;
8323 case 1: role = @"Hacker"; break;
8324 case 2: role = @"Developer"; break;
8329 if (![role isEqualToString:Role_]) {
8330 bool rolling(Role_ == nil);
8333 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8337 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8341 [roledelegate_ loadData];
8343 [roledelegate_ updateData];
8347 - (void) segmentChanged:(UISegmentedControl *)control {
8348 [self showDoneButton];
8351 - (void) saveAndClose {
8354 [[self navigationItem] setRightBarButtonItem:nil];
8355 [[self navigationController] dismissModalViewControllerAnimated:YES];
8358 - (void) doneButtonClicked {
8359 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8360 [spinner startAnimating];
8361 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8362 [[self navigationItem] setRightBarButtonItem:spinItem];
8364 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8367 - (void) showDoneButton {
8368 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8369 initWithTitle:UCLocalize("DONE")
8370 style:UIBarButtonItemStyleDone
8372 action:@selector(doneButtonClicked)
8373 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8376 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8377 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8381 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8385 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8386 return nil; // This method is required by the protocol.
8389 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8391 return UCLocalize("ROLE_EX");
8393 return [NSString stringWithFormat:
8394 @"%@: %@\n%@: %@\n%@: %@",
8395 UCLocalize("USER"), UCLocalize("USER_EX"),
8396 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8397 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8402 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8403 return section == 3 ? 44.0f : 0;
8406 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8407 return section == 3 ? container_ : nil;
8410 - (void) reloadData {
8413 [table_ reloadData];
8418 /* Stash Controller {{{ */
8419 @interface StashController : CyteViewController {
8420 _H<UIActivityIndicatorView> spinner_;
8421 _H<UILabel> status_;
8422 _H<UILabel> caption_;
8427 @implementation StashController
8430 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8431 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8433 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8434 CGRect spinrect = [spinner_ frame];
8435 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8436 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8437 [spinner_ setFrame:spinrect];
8438 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8439 [[self view] addSubview:spinner_];
8440 [spinner_ startAnimating];
8443 captrect.size.width = [[self view] frame].size.width;
8444 captrect.size.height = 40.0f;
8445 captrect.origin.x = 0;
8446 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8447 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8448 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8449 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8450 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8451 [caption_ setTextColor:[UIColor whiteColor]];
8452 [caption_ setBackgroundColor:[UIColor clearColor]];
8453 [caption_ setShadowColor:[UIColor blackColor]];
8454 [caption_ setTextAlignment:UITextAlignmentCenter];
8455 [[self view] addSubview:caption_];
8458 statusrect.size.width = [[self view] frame].size.width;
8459 statusrect.size.height = 30.0f;
8460 statusrect.origin.x = 0;
8461 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8462 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8463 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8464 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8465 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8466 [status_ setTextColor:[UIColor whiteColor]];
8467 [status_ setBackgroundColor:[UIColor clearColor]];
8468 [status_ setShadowColor:[UIColor blackColor]];
8469 [status_ setTextAlignment:UITextAlignmentCenter];
8470 [[self view] addSubview:status_];
8473 - (void) releaseSubviews {
8478 [super releaseSubviews];
8484 @interface CYURLCache : SDURLCache {
8489 @implementation CYURLCache
8491 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8494 else if ([event isEqualToString:@"no-cache"])
8496 else if ([event isEqualToString:@"store"])
8498 else if ([event isEqualToString:@"invalid"])
8500 else if ([event isEqualToString:@"memory"])
8502 else if ([event isEqualToString:@"disk"])
8504 else if ([event isEqualToString:@"miss"])
8507 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8511 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8512 if (NSURLResponse *response = [cached response])
8513 if (NSString *mime = [response MIMEType])
8514 if ([mime isEqualToString:@"text/cache-manifest"]) {
8515 NSURL *url([response URL]);
8518 NSLog(@"###: %@", [url absoluteString]);
8521 @synchronized (HostConfig_) {
8522 [CachedURLs_ addObject:url];
8526 [super storeCachedResponse:cached forRequest:request];
8531 @interface Cydia : UIApplication <
8532 ConfirmationControllerDelegate,
8535 UINavigationControllerDelegate,
8536 UITabBarControllerDelegate
8538 _H<UIWindow> window_;
8539 _H<CYTabBarController> tabbar_;
8540 _H<CydiaLoadingViewController> emulated_;
8542 _H<NSMutableArray> essential_;
8543 _H<NSMutableArray> broken_;
8545 Database *database_;
8547 _H<NSURL> starturl_;
8552 _H<StashController> stash_;
8561 @implementation Cydia
8563 - (void) beginUpdate {
8564 [tabbar_ beginUpdate];
8568 return [tabbar_ updating];
8572 if ([broken_ count] != 0) {
8573 int count = [broken_ count];
8575 UIAlertView *alert = [[[UIAlertView alloc]
8576 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8577 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8579 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8581 UCLocalize("TEMPORARY_IGNORE"),
8585 [alert setContext:@"fixhalf"];
8586 [alert setNumberOfRows:2];
8588 } else if (!Ignored_ && [essential_ count] != 0) {
8589 int count = [essential_ count];
8591 UIAlertView *alert = [[[UIAlertView alloc]
8592 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8593 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8595 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8597 UCLocalize("UPGRADE_ESSENTIAL"),
8598 UCLocalize("COMPLETE_UPGRADE"),
8602 [alert setContext:@"upgrade"];
8607 - (void) _saveConfig {
8613 NSString *error(nil);
8615 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8617 NSError *error(nil);
8618 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8619 NSLog(@"failure to save metadata data: %@", error);
8624 NSLog(@"failure to serialize metadata: %@", error);
8629 // Navigation controller for the queuing badge.
8630 - (UINavigationController *) queueNavigationController {
8631 NSArray *controllers = [tabbar_ viewControllers];
8632 return [controllers objectAtIndex:3];
8635 - (void) unloadData {
8636 [tabbar_ unloadData];
8639 - (void) _updateData {
8644 UINavigationController *navigation = [self queueNavigationController];
8646 id queuedelegate = nil;
8647 if ([[navigation viewControllers] count] > 0)
8648 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8650 [queuedelegate queueStatusDidChange];
8651 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8654 - (void) _refreshIfPossible:(NSDate *)update {
8655 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8657 bool recently = false;
8658 if (update != nil) {
8659 NSTimeInterval interval([update timeIntervalSinceNow]);
8660 if (interval <= 0 && interval > -(15*60))
8664 // Don't automatic refresh if:
8665 // - We already refreshed recently.
8666 // - We already auto-refreshed this launch.
8667 // - Auto-refresh is disabled.
8668 if (recently || loaded_ || ManualRefresh) {
8669 // If we are cancelling, we need to make sure it knows it's already loaded.
8672 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8674 // We are going to load, so remember that.
8677 SCNetworkReachabilityFlags flags; {
8678 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8679 SCNetworkReachabilityGetFlags(reachability, &flags);
8680 CFRelease(reachability);
8683 // XXX: this elaborate mess is what Apple is using to determine this? :(
8684 // XXX: do we care if the user has to intervene? maybe that's ok?
8686 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8687 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8688 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8689 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8690 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8691 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8695 // If we can reach the server, auto-refresh!
8697 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8703 - (void) refreshIfPossible {
8704 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8707 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8708 @synchronized (self) {
8709 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8710 [hud setText:UCLocalize("RELOADING_DATA")];
8712 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8715 [self removeProgressHUD:hud];
8719 [essential_ removeAllObjects];
8720 [broken_ removeAllObjects];
8722 NSArray *packages([database_ packages]);
8723 for (Package *package in packages) {
8725 [broken_ addObject:package];
8726 if ([package upgradableAndEssential:NO]) {
8727 if ([package essential])
8728 [essential_ addObject:package];
8733 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8736 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8737 [changesItem setBadgeValue:badge];
8738 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8739 [self setApplicationIconBadgeNumber:changes];
8742 [changesItem setBadgeValue:nil];
8743 [changesItem setAnimatedBadge:NO];
8744 [self setApplicationIconBadgeNumber:0];
8749 [self refreshIfPossible];
8752 - (void) updateData {
8758 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8761 - (void) disemulate {
8762 if (emulated_ == nil)
8765 [window_ addSubview:[tabbar_ view]];
8766 [[emulated_ view] removeFromSuperview];
8768 [window_ setUserInteractionEnabled:YES];
8771 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8772 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8774 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8776 UIViewController *parent;
8777 if (emulated_ == nil)
8786 [parent presentModalViewController:navigation animated:YES];
8789 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8790 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8792 if (navigation != nil)
8793 [navigation pushViewController:progress animated:YES];
8795 [self presentModalViewController:progress force:YES];
8797 [progress invoke:invocation withTitle:title];
8801 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8802 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8805 - (void) repairWithInvocation:(NSInvocation *)invocation {
8807 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8811 - (void) repairWithSelector:(SEL)selector {
8812 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8815 - (void) reloadData {
8816 [self reloadDataWithInvocation:nil];
8822 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8823 _assert(file != NULL);
8825 for (NSString *key in [Sources_ allKeys]) {
8826 NSDictionary *source([Sources_ objectForKey:key]);
8828 fprintf(file, "%s %s %s\n",
8829 [[source objectForKey:@"Type"] UTF8String],
8830 [[source objectForKey:@"URI"] UTF8String],
8831 [[source objectForKey:@"Distribution"] UTF8String]
8837 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8840 - (void) addTrivialSource:(NSString *)href {
8841 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8844 @"./", @"Distribution",
8845 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8851 pkgProblemResolver *resolver = [database_ resolver];
8853 resolver->InstallProtect();
8854 if (!resolver->Resolve(true))
8859 // XXX: this is a really crappy way of doing this.
8860 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8861 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8862 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8863 if ([tabbar_ updating])
8864 [tabbar_ cancelUpdate];
8866 if (![database_ prepare])
8869 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8870 [page setDelegate:self];
8871 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8874 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8875 [tabbar_ presentModalViewController:confirm_ animated:YES];
8881 @synchronized (self) {
8886 - (void) clearPackage:(Package *)package {
8887 @synchronized (self) {
8894 - (void) installPackages:(NSArray *)packages {
8895 @synchronized (self) {
8896 for (Package *package in packages)
8903 - (void) installPackage:(Package *)package {
8904 @synchronized (self) {
8911 - (void) removePackage:(Package *)package {
8912 @synchronized (self) {
8919 - (void) distUpgrade {
8920 @synchronized (self) {
8921 if (![database_ upgrade])
8928 [database_ perform];
8929 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8932 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8935 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8939 - (void) showSettings {
8940 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8943 - (void) retainNetworkActivityIndicator {
8944 if (activity_++ == 0)
8945 [self setNetworkActivityIndicatorVisible:YES];
8948 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8952 - (void) releaseNetworkActivityIndicator {
8953 if (--activity_ == 0)
8954 [self setNetworkActivityIndicatorVisible:NO];
8957 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8962 - (void) cancelAndClear:(bool)clear {
8963 @synchronized (self) {
8975 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8976 NSString *context([alert context]);
8978 if ([context isEqualToString:@"conffile"]) {
8979 FILE *input = [database_ input];
8980 if (button == [alert cancelButtonIndex])
8981 fprintf(input, "N\n");
8982 else if (button == [alert firstOtherButtonIndex])
8983 fprintf(input, "Y\n");
8986 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8987 } else if ([context isEqualToString:@"fixhalf"]) {
8988 if (button == [alert cancelButtonIndex]) {
8989 @synchronized (self) {
8990 for (Package *broken in (id) broken_) {
8993 NSString *id = [broken id];
8994 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8995 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8996 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8997 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9003 } else if (button == [alert firstOtherButtonIndex]) {
9004 [broken_ removeAllObjects];
9008 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9009 } else if ([context isEqualToString:@"upgrade"]) {
9010 if (button == [alert firstOtherButtonIndex]) {
9011 @synchronized (self) {
9012 for (Package *essential in (id) essential_)
9013 [essential install];
9018 } else if (button == [alert firstOtherButtonIndex] + 1) {
9020 } else if (button == [alert cancelButtonIndex]) {
9024 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9028 - (void) system:(NSString *)command {
9029 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9032 system([command UTF8String]);
9038 - (void) applicationWillSuspend {
9040 [super applicationWillSuspend];
9043 - (BOOL) isSafeToSuspend {
9046 NSLog(@"isSafeToSuspend: locked_ != 0");
9051 // Use external process status API internally.
9052 // This is probably a really bad idea.
9053 // XXX: what is the point of this? does this solve anything at all?
9054 uint64_t status = 0;
9056 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9057 notify_get_state(notify_token, &status);
9058 notify_cancel(notify_token);
9063 NSLog(@"isSafeToSuspend: status != 0");
9069 NSLog(@"isSafeToSuspend: -> true");
9074 - (void) applicationSuspend:(__GSEvent *)event {
9075 if ([self isSafeToSuspend])
9076 [super applicationSuspend:event];
9079 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9080 if ([self isSafeToSuspend])
9081 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9084 - (void) _setSuspended:(BOOL)value {
9085 if ([self isSafeToSuspend])
9086 [super _setSuspended:value];
9089 - (UIProgressHUD *) addProgressHUD {
9090 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9091 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9093 [window_ setUserInteractionEnabled:NO];
9095 UIViewController *target(tabbar_);
9096 if (UIViewController *modal = [target modalViewController])
9099 UIView *view([target view]);
9100 [view addSubview:hud];
9108 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9111 [hud removeFromSuperview];
9112 [window_ setUserInteractionEnabled:YES];
9115 - (CyteViewController *) pageForPackage:(NSString *)name {
9116 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9119 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9120 NSString *scheme([[url scheme] lowercaseString]);
9121 if ([[url absoluteString] length] <= [scheme length] + 3)
9123 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9124 NSArray *components([path pathComponents]);
9126 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9127 return [self pageForPackage:[components objectAtIndex:1]];
9129 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9132 NSString *base([components objectAtIndex:0]);
9134 CyteViewController *controller = nil;
9136 if ([base isEqualToString:@"url"]) {
9137 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9138 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9139 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9140 } else if (!external && [components count] == 1) {
9141 if ([base isEqualToString:@"manage"]) {
9142 controller = [[[ManageController alloc] init] autorelease];
9145 if ([base isEqualToString:@"sources"]) {
9146 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9149 if ([base isEqualToString:@"home"]) {
9150 controller = [[[HomeController alloc] init] autorelease];
9153 if ([base isEqualToString:@"sections"]) {
9154 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9157 if ([base isEqualToString:@"search"]) {
9158 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9161 if ([base isEqualToString:@"changes"]) {
9162 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9165 if ([base isEqualToString:@"installed"]) {
9166 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9168 } else if ([components count] == 2) {
9169 NSString *argument = [components objectAtIndex:1];
9171 if ([base isEqualToString:@"package"]) {
9172 controller = [self pageForPackage:argument];
9175 if (!external && [base isEqualToString:@"search"]) {
9176 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9179 if (!external && [base isEqualToString:@"sections"]) {
9180 if ([argument isEqualToString:@"all"])
9182 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9185 if (!external && [base isEqualToString:@"sources"]) {
9186 if ([argument isEqualToString:@"add"]) {
9187 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9188 [(SourcesController *)controller showAddSourcePrompt];
9190 Source *source = [database_ sourceWithKey:argument];
9191 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9195 if (!external && [base isEqualToString:@"launch"]) {
9196 [self launchApplicationWithIdentifier:argument suspended:NO];
9199 } else if (!external && [components count] == 3) {
9200 NSString *arg1 = [components objectAtIndex:1];
9201 NSString *arg2 = [components objectAtIndex:2];
9203 if ([base isEqualToString:@"package"]) {
9204 if ([arg2 isEqualToString:@"settings"]) {
9205 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9206 } else if ([arg2 isEqualToString:@"files"]) {
9207 if (Package *package = [database_ packageWithName:arg1]) {
9208 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9209 [(FileTable *)controller setPackage:package];
9215 [controller setDelegate:self];
9219 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9220 CyteViewController *page([self pageForURL:url forExternal:external]);
9223 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9224 [nav setViewControllers:[NSArray arrayWithObject:page]];
9225 [tabbar_ setUnselectedViewController:nav];
9231 - (void) applicationOpenURL:(NSURL *)url {
9232 [super applicationOpenURL:url];
9237 [self openCydiaURL:url forExternal:YES];
9240 - (void) applicationWillResignActive:(UIApplication *)application {
9241 // Stop refreshing if you get a phone call or lock the device.
9242 if ([tabbar_ updating])
9243 [tabbar_ cancelUpdate];
9245 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9246 [super applicationWillResignActive:application];
9249 - (void) applicationWillTerminate:(UIApplication *)application {
9251 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9252 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9253 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9258 - (void) setConfigurationData:(NSString *)data {
9259 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9261 if (!conffile_r(data)) {
9262 lprintf("E:invalid conffile\n");
9266 NSString *ofile = conffile_r[1];
9267 //NSString *nfile = conffile_r[2];
9269 UIAlertView *alert = [[[UIAlertView alloc]
9270 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9271 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9273 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9275 UCLocalize("ACCEPT_NEW_COPY"),
9276 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9280 [alert setContext:@"conffile"];
9281 [alert setNumberOfRows:2];
9285 - (void) addStashController {
9287 stash_ = [[[StashController alloc] init] autorelease];
9288 [window_ addSubview:[stash_ view]];
9291 - (void) removeStashController {
9292 [[stash_ view] removeFromSuperview];
9298 [self setIdleTimerDisabled:YES];
9300 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9301 UpdateExternalStatus(1);
9302 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9303 UpdateExternalStatus(0);
9305 [self removeStashController];
9307 if (ExecFork() == 0) {
9308 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9309 perror("launchctl stop");
9313 - (void) setupViewControllers {
9314 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9316 NSMutableArray *items([NSMutableArray arrayWithObjects:
9317 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9318 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9319 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9320 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9324 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9325 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9327 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9330 NSMutableArray *controllers([NSMutableArray array]);
9331 for (UITabBarItem *item in items) {
9332 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9333 [controller setTabBarItem:item];
9334 [controllers addObject:controller];
9336 [tabbar_ setViewControllers:controllers];
9338 [tabbar_ setUpdateDelegate:self];
9341 - (void) applicationDidFinishLaunching:(id)unused {
9343 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9344 [self setApplicationSupportsShakeToEdit:NO];
9346 @synchronized (HostConfig_) {
9347 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9350 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9351 initWithMemoryCapacity:524288
9352 diskCapacity:10485760
9353 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9356 [CydiaWebViewController _initialize];
9358 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9360 // this would disallow http{,s} URLs from accessing this data
9361 //[WebView registerURLSchemeAsLocal:@"cydia"];
9363 Font12_ = [UIFont systemFontOfSize:12];
9364 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9365 Font14_ = [UIFont systemFontOfSize:14];
9366 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9367 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9369 essential_ = [NSMutableArray arrayWithCapacity:4];
9370 broken_ = [NSMutableArray arrayWithCapacity:4];
9372 // XXX: I really need this thing... like, seriously... I'm sorry
9373 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9375 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9376 [window_ orderFront:self];
9377 [window_ makeKey:self];
9378 [window_ setHidden:NO];
9381 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9382 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9383 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9384 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9385 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9386 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9387 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9388 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9389 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9392 [self addStashController];
9393 // XXX: this would be much cleaner as a yieldToSelector:
9394 // that way the removeStashController could happen right here inline
9395 // we also could no longer require the useless stash_ field anymore
9396 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9400 database_ = [Database sharedInstance];
9401 [database_ setDelegate:self];
9403 [window_ setUserInteractionEnabled:NO];
9404 [self setupViewControllers];
9406 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9407 [window_ addSubview:[emulated_ view]];
9409 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9413 - (NSArray *) defaultStartPages {
9414 NSMutableArray *standard = [NSMutableArray array];
9415 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9416 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9417 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9419 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9421 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9422 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9424 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9431 [window_ setUserInteractionEnabled:YES];
9432 [self showSettings];
9435 if ([emulated_ modalViewController] != nil)
9436 [emulated_ dismissModalViewControllerAnimated:YES];
9437 [window_ setUserInteractionEnabled:NO];
9445 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9446 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9447 int standardIndex = 0;
9448 NSArray *standard = [self defaultStartPages];
9455 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9456 if (valid && closed != nil) {
9457 NSTimeInterval interval([closed timeIntervalSinceNow]);
9458 // XXX: Is 15 minutes the optimal time here?
9459 if (interval > 0 && interval <= -(15*60))
9463 if (valid && [saved count] != [standard count])
9467 for (unsigned int i = 0; i < [standard count]; i++) {
9468 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9469 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9470 // but it's good enough for now.
9471 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9478 NSArray *items = nil;
9480 [tabbar_ setSelectedIndex:savedIndex];
9483 [tabbar_ setSelectedIndex:standardIndex];
9487 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9488 NSArray *stack = [items objectAtIndex:tab];
9489 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9490 NSMutableArray *current = [NSMutableArray array];
9492 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9493 NSString *addr = [stack objectAtIndex:nav];
9494 NSURL *url = [NSURL URLWithString:addr];
9495 CyteViewController *page = [self pageForURL:url forExternal:NO];
9497 [current addObject:page];
9500 [navigation setViewControllers:current];
9503 // (Try to) show the startup URL.
9504 if (starturl_ != nil) {
9505 [self openCydiaURL:starturl_ forExternal:NO];
9510 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9511 if (item != nil && IsWildcat_) {
9512 [sheet showFromBarButtonItem:item animated:YES];
9514 [sheet showInView:window_];
9518 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9519 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9520 [progress setTitle:task];
9521 [progress addProgressEvent:event];
9524 - (void) addProgressEventForTask:(NSArray *)data {
9525 CydiaProgressEvent *event([data objectAtIndex:0]);
9526 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9527 [self addProgressEvent:event forTask:task];
9530 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9531 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9537 id Alloc_(id self, SEL selector) {
9538 id object = alloc_(self, selector);
9539 lprintf("[%s]A-%p\n", self->isa->name, object);
9544 id Dealloc_(id self, SEL selector) {
9545 id object = dealloc_(self, selector);
9546 lprintf("[%s]D-%p\n", self->isa->name, object);
9550 Class $WebDefaultUIKitDelegate;
9552 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9553 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9554 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9555 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9558 static NSSet *MobilizedFiles_;
9560 static NSURL *MobilizeURL(NSURL *url) {
9561 NSString *path([url path]);
9562 if ([path hasPrefix:@"/var/root/"]) {
9563 NSString *file([path substringFromIndex:10]);
9564 if ([MobilizedFiles_ containsObject:file])
9565 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9571 Class $CFXPreferencesPropertyListSource;
9572 @class CFXPreferencesPropertyListSource;
9574 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9575 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9576 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9577 url = MobilizeURL(url);
9578 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9579 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9585 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9586 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9587 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9588 url = MobilizeURL(url);
9589 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9590 //NSLog(@"%@ %@", [url absoluteString], value);
9596 Class $NSURLConnection;
9598 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9599 NSMutableURLRequest *copy([request mutableCopy]);
9601 NSURL *url([copy URL]);
9603 NSString *href([url absoluteString]);
9604 NSString *host([url host]);
9605 NSString *scheme([[url scheme] lowercaseString]);
9607 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9609 @synchronized (HostConfig_) {
9610 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9611 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9612 [copy setHTTPShouldUsePipelining:YES];
9614 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9615 if ([control isEqualToString:@"max-age=0"])
9616 if ([CachedURLs_ containsObject:href]) {
9618 NSLog(@"~~~: %@", href);
9621 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9623 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9624 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9625 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9629 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9633 int main(int argc, char *argv[]) {
9634 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9638 UpdateExternalStatus(0);
9640 if (Class $UIDevice = objc_getClass("UIDevice")) {
9641 UIDevice *device([$UIDevice currentDevice]);
9642 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9646 UIScreen *screen([UIScreen mainScreen]);
9647 if ([screen respondsToSelector:@selector(scale)])
9648 ScreenScale_ = [screen scale];
9652 UIDevice *device([UIDevice currentDevice]);
9653 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9656 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9657 if (idiom == UIUserInterfaceIdiomPhone)
9659 else if (idiom == UIUserInterfaceIdiomPad)
9662 NSLog(@"unknown UIUserInterfaceIdiom!");
9665 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9667 HostConfig_ = [[[NSObject alloc] init] autorelease];
9668 @synchronized (HostConfig_) {
9669 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9670 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9671 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9674 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9676 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9678 MobilizedFiles_ = [NSMutableSet setWithObjects:
9679 @"Library/Preferences/com.apple.Accessibility.plist",
9680 @"Library/Preferences/com.apple.preferences.sounds.plist",
9683 /* Library Hacks {{{ */
9684 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9686 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9688 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9689 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9690 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9691 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9694 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9695 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9696 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9697 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9700 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9701 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9702 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9703 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9704 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9707 $NSURLConnection = objc_getClass("NSURLConnection");
9708 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9709 if (NSURLConnection$init$ != NULL) {
9710 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9711 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9714 /* Set Locale {{{ */
9715 Locale_ = CFLocaleCopyCurrent();
9716 Languages_ = [NSLocale preferredLanguages];
9718 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9719 //NSLog(@"%@", [Languages_ description]);
9722 if (Locale_ != NULL)
9723 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9724 else if (Languages_ != nil && [Languages_ count] != 0)
9725 lang = [[Languages_ objectAtIndex:0] UTF8String];
9727 // XXX: consider just setting to C and then falling through?
9731 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9732 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9735 NSLog(@"Setting Language: %s", lang);
9738 setenv("LANG", lang, true);
9739 std::setlocale(LC_ALL, lang);
9743 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9745 /* Parse Arguments {{{ */
9746 bool substrate(false);
9752 for (int argi(1); argi != argc; ++argi)
9753 if (strcmp(argv[argi], "--") == 0) {
9755 argv[argi] = argv[0];
9761 for (int argi(1); argi != arge; ++argi)
9762 if (strcmp(args[argi], "--substrate") == 0)
9765 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9769 App_ = [[NSBundle mainBundle] bundlePath];
9775 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9776 alloc_ = alloc->method_imp;
9777 alloc->method_imp = (IMP) &Alloc_;*/
9779 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9780 dealloc_ = dealloc->method_imp;
9781 dealloc->method_imp = (IMP) &Dealloc_;*/
9783 /* System Information {{{ */
9787 size = sizeof(maxproc);
9788 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9789 perror("sysctlbyname(\"kern.maxproc\", ?)");
9790 else if (maxproc < 64) {
9792 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9793 perror("sysctlbyname(\"kern.maxproc\", #)");
9796 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9797 char *osversion = new char[size];
9798 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9799 perror("sysctlbyname(\"kern.osversion\", ?)");
9801 System_ = [NSString stringWithUTF8String:osversion];
9803 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9804 char *machine = new char[size];
9805 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9806 perror("sysctlbyname(\"hw.machine\", ?)");
9810 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9811 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9812 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9814 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9816 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9817 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9818 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9820 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9821 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9822 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9824 if (mcc != NULL && mnc != NULL)
9825 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9832 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9833 Build_ = [system objectForKey:@"ProductBuildVersion"];
9834 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9835 Product_ = [info objectForKey:@"SafariProductVersion"];
9836 Safari_ = [info objectForKey:@"CFBundleVersion"];
9839 /* Load Database {{{ */
9841 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9843 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9845 if (Metadata_ == NULL)
9846 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9848 Settings_ = [Metadata_ objectForKey:@"Settings"];
9850 Packages_ = [Metadata_ objectForKey:@"Packages"];
9851 Sections_ = [Metadata_ objectForKey:@"Sections"];
9852 Sources_ = [Metadata_ objectForKey:@"Sources"];
9854 Token_ = [Metadata_ objectForKey:@"Token"];
9857 if (Settings_ != nil)
9858 Role_ = [Settings_ objectForKey:@"Role"];
9860 if (Sections_ == nil) {
9861 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9862 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9865 if (Sources_ == nil) {
9866 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9867 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9872 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9875 if (Packages_ != nil) {
9877 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9881 [Metadata_ removeObjectForKey:@"Packages"];
9887 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9889 #define MobileSubstrate_(name) \
9890 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9891 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9892 if (handle == NULL) \
9893 NSLog(@"%s", dlerror()); \
9896 MobileSubstrate_(Activator)
9897 MobileSubstrate_(libstatusbar)
9898 MobileSubstrate_(SimulatedKeyEvents)
9899 MobileSubstrate_(WinterBoard)
9901 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9902 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9904 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9906 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9907 unlink("/tmp/.cydia.fw");
9909 } else if (access("/User", F_OK) != 0 || version < 4) {
9912 system("/usr/libexec/cydia/firmware.sh");
9916 _assert([[NSFileManager defaultManager]
9917 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9918 withIntermediateDirectories:YES
9923 if (access("/tmp/cydia.chk", F_OK) == 0) {
9924 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9925 _assert(errno == ENOENT);
9926 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9927 _assert(errno == ENOENT);
9930 /* APT Initialization {{{ */
9931 _assert(pkgInitConfig(*_config));
9932 _assert(pkgInitSystem(*_config, _system));
9935 _config->Set("APT::Acquire::Translation", lang);
9937 // XXX: this timeout might be important :(
9938 //_config->Set("Acquire::http::Timeout", 15);
9940 _config->Set("Acquire::http::MaxParallel", 3);
9942 /* Color Choices {{{ */
9943 space_ = CGColorSpaceCreateDeviceRGB();
9945 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9946 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9947 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9948 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9949 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9950 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9951 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9952 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9953 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9955 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9956 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9958 /* UIKit Configuration {{{ */
9959 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9960 if ($GSFontSetUseLegacyFontMetrics != NULL)
9961 $GSFontSetUseLegacyFontMetrics(YES);
9963 // XXX: I have a feeling this was important
9964 //UIKeyboardDisableAutomaticAppearance();
9967 Colon_ = UCLocalize("COLON_DELIMITED");
9968 Elision_ = UCLocalize("ELISION");
9969 Error_ = UCLocalize("ERROR");
9970 Warning_ = UCLocalize("WARNING");
9973 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9975 CGColorSpaceRelease(space_);