]> git.saurik.com Git - cydia.git/blame_incremental - MobileCydia.mm
If you have cydia. access, get Token_.
[cydia.git] / MobileCydia.mm
... / ...
CommitLineData
1/* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
3*/
4
5/* Modified BSD License {{{ */
6/*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
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
18 * distribution.
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.
22 *
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.
37*/
38/* }}} */
39
40// XXX: wtf/FastMalloc.h... wtf?
41#define USE_SYSTEM_MALLOC 1
42
43/* #include Directives {{{ */
44#include "CyteKit/UCPlatform.h"
45#include "CyteKit/Localize.h"
46
47#include <objc/objc.h>
48#include <objc/runtime.h>
49
50#include <CoreGraphics/CoreGraphics.h>
51#include <Foundation/Foundation.h>
52
53#if 0
54#define DEPLOYMENT_TARGET_MACOSX 1
55#define CF_BUILDING_CF 1
56#include <CoreFoundation/CFInternal.h>
57#endif
58
59#include <CoreFoundation/CFPriv.h>
60#include <CoreFoundation/CFUniChar.h>
61
62#include <SystemConfiguration/SystemConfiguration.h>
63
64#include <UIKit/UIKit.h>
65#include "iPhonePrivate.h"
66
67#include <IOKit/IOKitLib.h>
68
69#include <WebCore/WebCoreThread.h>
70
71#include <algorithm>
72#include <iomanip>
73#include <sstream>
74#include <string>
75
76#include <ext/stdio_filebuf.h>
77
78#undef ABS
79
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>
97
98#include <apr-1/apr_pools.h>
99
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>
106
107#include <fcntl.h>
108#include <notify.h>
109#include <dlfcn.h>
110
111extern "C" {
112#include <mach-o/nlist.h>
113}
114
115#include <cstdio>
116#include <cstdlib>
117#include <cstring>
118
119#include <errno.h>
120
121#include <Cytore.hpp>
122
123#include <CydiaSubstrate/CydiaSubstrate.h>
124#include "Menes/Menes.h"
125
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"
131
132#include "Cydia/MIMEAddress.h"
133#include "Cydia/LoadingViewController.h"
134#include "Cydia/ProgressEvent.h"
135
136#include "SDURLCache/SDURLCache.h"
137/* }}} */
138
139/* Profiler {{{ */
140struct timeval _ltv;
141bool _itv;
142
143#define _timestamp ({ \
144 struct timeval tv; \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
147})
148
149typedef std::vector<class ProfileTime *> TimeList;
150TimeList times_;
151
152class ProfileTime {
153 private:
154 const char *name_;
155 uint64_t total_;
156 uint64_t count_;
157
158 public:
159 ProfileTime(const char *name) :
160 name_(name),
161 total_(0)
162 {
163 times_.push_back(this);
164 }
165
166 void AddTime(uint64_t time) {
167 total_ += time;
168 ++count_;
169 }
170
171 void Print() {
172 if (total_ != 0)
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 total_ = 0;
175 count_ = 0;
176 }
177};
178
179class ProfileTimer {
180 private:
181 ProfileTime &time_;
182 uint64_t start_;
183
184 public:
185 ProfileTimer(ProfileTime &time) :
186 time_(time),
187 start_(_timestamp)
188 {
189 }
190
191 ~ProfileTimer() {
192 time_.AddTime(_timestamp - start_);
193 }
194};
195
196void PrintTimes() {
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
198 (*i)->Print();
199 std::cerr << "========" << std::endl;
200}
201
202#define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
205
206#define _end }
207/* }}} */
208
209#include "Version.h"
210#define Cydia_ CYDIA_VERSION
211
212#define lprintf(args...) fprintf(stderr, args)
213
214#define ForRelease 1
215#define TraceLogging (1 && !ForRelease)
216#define HistogramInsertionSort (!ForRelease ? 0 : 0)
217#define ProfileTimes (0 && !ForRelease)
218#define ForSaurik (0 && !ForRelease)
219#define LogBrowser (0 && !ForRelease)
220#define TrackResize (0 && !ForRelease)
221#define ManualRefresh (1 && !ForRelease)
222#define ShowInternals (0 && !ForRelease)
223#define AlwaysReload (0 && !ForRelease)
224#define TryIndexedCollation (0 && !ForRelease)
225
226#if !TraceLogging
227#undef _trace
228#define _trace(args...)
229#endif
230
231#if !ProfileTimes
232#undef _profile
233#define _profile(name) {
234#undef _end
235#define _end }
236#define PrintTimes() do {} while (false)
237#endif
238
239// Hash Functions/Structures {{{
240extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
241
242union SplitHash {
243 uint32_t u32;
244 uint16_t u16[2];
245};
246// }}}
247
248static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
249
250static _finline NSString *CydiaURL(NSString *path) {
251 char page[26];
252 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
253 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
254 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
255 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
256 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
257 page[25] = '\0';
258 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
259}
260
261static _finline void UpdateExternalStatus(uint64_t newStatus) {
262 int notify_token;
263 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
264 notify_set_state(notify_token, newStatus);
265 notify_cancel(notify_token);
266 }
267 notify_post("com.saurik.Cydia.status");
268}
269
270static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
271 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
272 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
273}
274
275/* NSForcedOrderingSearch doesn't work on the iPhone */
276static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
277static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
278static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
279
280/* Insertion Sort {{{ */
281
282CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
283 const char *ptr = (const char *)list;
284 while (0 < count) {
285 CFIndex half = count / 2;
286 const char *probe = ptr + elementSize * half;
287 CFComparisonResult cr = comparator(element, probe, context);
288 if (0 == cr) return (probe - (const char *)list) / elementSize;
289 ptr = (cr < 0) ? ptr : probe + elementSize;
290 count = (cr < 0) ? half : (half + (count & 1) - 1);
291 }
292 return (ptr - (const char *)list) / elementSize;
293}
294
295CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
296 const char *ptr = (const char *)list;
297 while (0 < count) {
298 CFIndex half = count / 2;
299 const char *probe = ptr + elementSize * half;
300 CFComparisonResult cr = comparator(element, probe, context);
301 if (0 == cr) return (probe - (const char *)list) / elementSize;
302 ptr = (cr < 0) ? ptr : probe + elementSize;
303 count = (cr < 0) ? half : (half + (count & 1) - 1);
304 }
305 return (ptr - (const char *)list) / elementSize;
306}
307
308void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
309 if (range.length == 0)
310 return;
311 const void **values(new const void *[range.length]);
312 CFArrayGetValues(array, range, values);
313
314#if HistogramInsertionSort > 0
315 uint32_t total(0), *offsets(new uint32_t[range.length]);
316#endif
317
318 for (CFIndex index(1); index != range.length; ++index) {
319 const void *value(values[index]);
320 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
321 CFIndex correct(index);
322 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
323#if HistogramInsertionSort > 1
324 NSLog(@"%@ < %@", value, values[correct - 1]);
325#endif
326 if (--correct == 0)
327 break;
328 }
329 if (correct != index) {
330 size_t offset(index - correct);
331#if HistogramInsertionSort
332 total += offset;
333 ++offsets[offset];
334 if (offset > 10)
335 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
336#endif
337 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
338 values[correct] = value;
339 }
340 }
341
342 CFArrayReplaceValues(array, range, values, range.length);
343 delete [] values;
344
345#if HistogramInsertionSort > 0
346 for (CFIndex index(0); index != range.length; ++index)
347 if (offsets[index] != 0)
348 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
349 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
350 delete [] offsets;
351#endif
352}
353
354/* }}} */
355
356/* Apple Bug Fixes {{{ */
357@implementation UIWebDocumentView (Cydia)
358
359- (void) _setScrollerOffset:(CGPoint)offset {
360 UIScroller *scroller([self _scroller]);
361
362 CGSize size([scroller contentSize]);
363 CGSize bounds([scroller bounds].size);
364
365 CGPoint max;
366 max.x = size.width - bounds.width;
367 max.y = size.height - bounds.height;
368
369 // wtf Apple?!
370 if (max.x < 0)
371 max.x = 0;
372 if (max.y < 0)
373 max.y = 0;
374
375 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
376 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
377
378 [scroller setOffset:offset];
379}
380
381@end
382/* }}} */
383
384NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
385 size_t length([self length] - state->state);
386 if (length <= 0)
387 return 0;
388 else if (length > count)
389 length = count;
390 for (size_t i(0); i != length; ++i)
391 objects[i] = [self item:state->state++];
392 state->itemsPtr = objects;
393 state->mutationsPtr = (unsigned long *) self;
394 return length;
395}
396
397/* Cydia NSString Additions {{{ */
398@interface NSString (Cydia)
399- (NSComparisonResult) compareByPath:(NSString *)other;
400- (NSString *) stringByCachingURLWithCurrentCDN;
401- (NSString *) stringByAddingPercentEscapesIncludingReserved;
402@end
403
404@implementation NSString (Cydia)
405
406- (NSComparisonResult) compareByPath:(NSString *)other {
407 NSString *prefix = [self commonPrefixWithString:other options:0];
408 size_t length = [prefix length];
409
410 NSRange lrange = NSMakeRange(length, [self length] - length);
411 NSRange rrange = NSMakeRange(length, [other length] - length);
412
413 lrange = [self rangeOfString:@"/" options:0 range:lrange];
414 rrange = [other rangeOfString:@"/" options:0 range:rrange];
415
416 NSComparisonResult value;
417
418 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
419 value = NSOrderedSame;
420 else if (lrange.location == NSNotFound)
421 value = NSOrderedAscending;
422 else if (rrange.location == NSNotFound)
423 value = NSOrderedDescending;
424 else
425 value = NSOrderedSame;
426
427 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
428 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
429 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
430 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
431
432 NSComparisonResult result = [lpath compare:rpath];
433 return result == NSOrderedSame ? value : result;
434}
435
436- (NSString *) stringByCachingURLWithCurrentCDN {
437 return [self
438 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
439 withString:@"://cache.cydia.saurik.com/"
440 ];
441}
442
443- (NSString *) stringByAddingPercentEscapesIncludingReserved {
444 return [(id)CFURLCreateStringByAddingPercentEscapes(
445 kCFAllocatorDefault,
446 (CFStringRef) self,
447 NULL,
448 CFSTR(";/?:@&=+$,"),
449 kCFStringEncodingUTF8
450 ) autorelease];
451}
452
453@end
454/* }}} */
455
456/* C++ NSString Wrapper Cache {{{ */
457static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
458 return size == 0 ? NULL :
459 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
460 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
461}
462
463static _finline CFStringRef CYStringCreate(const char *data) {
464 return CYStringCreate(data, strlen(data));
465}
466
467class CYString {
468 private:
469 char *data_;
470 size_t size_;
471 CFStringRef cache_;
472
473 _finline void clear_() {
474 if (cache_ != NULL) {
475 CFRelease(cache_);
476 cache_ = NULL;
477 }
478 }
479
480 public:
481 _finline bool empty() const {
482 return size_ == 0;
483 }
484
485 _finline size_t size() const {
486 return size_;
487 }
488
489 _finline char *data() const {
490 return data_;
491 }
492
493 _finline void clear() {
494 size_ = 0;
495 clear_();
496 }
497
498 _finline CYString() :
499 data_(0),
500 size_(0),
501 cache_(NULL)
502 {
503 }
504
505 _finline ~CYString() {
506 clear_();
507 }
508
509 void operator =(const CYString &rhs) {
510 data_ = rhs.data_;
511 size_ = rhs.size_;
512
513 if (rhs.cache_ == nil)
514 cache_ = NULL;
515 else
516 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
517 }
518
519 void copy(apr_pool_t *pool) {
520 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
521 memcpy(temp, data_, size_);
522 temp[size_] = '\0';
523 data_ = temp;
524 }
525
526 void set(apr_pool_t *pool, const char *data, size_t size) {
527 if (size == 0)
528 clear();
529 else {
530 clear_();
531
532 data_ = const_cast<char *>(data);
533 size_ = size;
534
535 if (pool != NULL)
536 copy(pool);
537 }
538 }
539
540 _finline void set(apr_pool_t *pool, const char *data) {
541 set(pool, data, data == NULL ? 0 : strlen(data));
542 }
543
544 _finline void set(apr_pool_t *pool, const std::string &rhs) {
545 set(pool, rhs.data(), rhs.size());
546 }
547
548 bool operator ==(const CYString &rhs) const {
549 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
550 }
551
552 _finline operator CFStringRef() {
553 if (cache_ == NULL)
554 cache_ = CYStringCreate(data_, size_);
555 return cache_;
556 }
557
558 _finline operator id() {
559 return (NSString *) static_cast<CFStringRef>(*this);
560 }
561
562 _finline operator const char *() {
563 return reinterpret_cast<const char *>(data_);
564 }
565};
566/* }}} */
567/* C++ NSString Algorithm Adapters {{{ */
568extern "C" {
569 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
570}
571
572struct NSStringMapHash :
573 std::unary_function<NSString *, size_t>
574{
575 _finline size_t operator ()(NSString *value) const {
576 return CFStringHashNSString((CFStringRef) value);
577 }
578};
579
580struct NSStringMapLess :
581 std::binary_function<NSString *, NSString *, bool>
582{
583 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
584 return [lhs compare:rhs] == NSOrderedAscending;
585 }
586};
587
588struct NSStringMapEqual :
589 std::binary_function<NSString *, NSString *, bool>
590{
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
593 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
594 //[lhs isEqualToString:rhs];
595 }
596};
597/* }}} */
598
599/* CoreGraphics Primitives {{{ */
600class CYColor {
601 private:
602 CGColorRef color_;
603
604 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
605 CGFloat color[] = {red, green, blue, alpha};
606 return CGColorCreate(space, color);
607 }
608
609 public:
610 CYColor() :
611 color_(NULL)
612 {
613 }
614
615 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
616 color_(Create_(space, red, green, blue, alpha))
617 {
618 Set(space, red, green, blue, alpha);
619 }
620
621 void Clear() {
622 if (color_ != NULL)
623 CGColorRelease(color_);
624 }
625
626 ~CYColor() {
627 Clear();
628 }
629
630 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
631 Clear();
632 color_ = Create_(space, red, green, blue, alpha);
633 }
634
635 operator CGColorRef() {
636 return color_;
637 }
638};
639/* }}} */
640
641/* Random Global Variables {{{ */
642static const int PulseInterval_ = 50000;
643
644static const NSString *UI_;
645
646static int Finish_;
647static bool RestartSubstrate_;
648static NSArray *Finishes_;
649
650#define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
651#define NotifyConfig_ "/etc/notify.conf"
652
653static bool Queuing_;
654
655static CYColor Blue_;
656static CYColor Blueish_;
657static CYColor Black_;
658static CYColor Off_;
659static CYColor White_;
660static CYColor Gray_;
661static CYColor Green_;
662static CYColor Purple_;
663static CYColor Purplish_;
664
665static UIColor *InstallingColor_;
666static UIColor *RemovingColor_;
667
668static NSString *App_;
669
670static BOOL Advanced_;
671static BOOL Ignored_;
672
673static _H<UIFont> Font12_;
674static _H<UIFont> Font12Bold_;
675static _H<UIFont> Font14_;
676static _H<UIFont> Font18Bold_;
677static _H<UIFont> Font22Bold_;
678
679static const char *Machine_ = NULL;
680static NSString *System_ = nil;
681static NSString *SerialNumber_ = nil;
682static NSString *ChipID_ = nil;
683static NSString *BBSNum_ = nil;
684static _H<NSString> Token_;
685static NSString *UniqueID_ = nil;
686static NSString *PLMN_ = nil;
687static NSString *Build_ = nil;
688static NSString *Product_ = nil;
689static NSString *Safari_ = nil;
690
691static CFLocaleRef Locale_;
692static NSArray *Languages_;
693static CGColorSpaceRef space_;
694
695static NSDictionary *SectionMap_;
696static NSMutableDictionary *Metadata_;
697static _transient NSMutableDictionary *Settings_;
698static _transient NSString *Role_;
699static _transient NSMutableDictionary *Packages_;
700static _transient NSMutableDictionary *Sections_;
701static _transient NSMutableDictionary *Sources_;
702static bool Changed_;
703static time_t now_;
704
705bool IsWildcat_;
706static CGFloat ScreenScale_;
707static NSString *Idiom_;
708
709static _H<NSMutableDictionary> SessionData_;
710static _H<NSObject> HostConfig_;
711static _H<NSMutableSet> BridgedHosts_;
712static _H<NSMutableSet> TokenHosts_;
713static _H<NSMutableSet> InsecureHosts_;
714static _H<NSMutableSet> PipelinedHosts_;
715static _H<NSMutableSet> CachedURLs_;
716
717static NSString *kCydiaProgressEventTypeError = @"Error";
718static NSString *kCydiaProgressEventTypeInformation = @"Information";
719static NSString *kCydiaProgressEventTypeStatus = @"Status";
720static NSString *kCydiaProgressEventTypeWarning = @"Warning";
721/* }}} */
722
723/* Display Helpers {{{ */
724inline float Interpolate(float begin, float end, float fraction) {
725 return (end - begin) * fraction + begin;
726}
727
728static _finline const char *StripVersion_(const char *version) {
729 const char *colon(strchr(version, ':'));
730 return colon == NULL ? version : colon + 1;
731}
732
733NSString *LocalizeSection(NSString *section) {
734 static Pcre title_r("^(.*?) \\((.*)\\)$");
735 if (title_r(section)) {
736 NSString *parent(title_r[1]);
737 NSString *child(title_r[2]);
738
739 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
740 LocalizeSection(parent),
741 LocalizeSection(child)
742 ];
743 }
744
745 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
746}
747
748NSString *Simplify(NSString *title) {
749 const char *data = [title UTF8String];
750 size_t size = [title length];
751
752 static Pcre square_r("^\\[(.*)\\]$");
753 if (square_r(data, size))
754 return Simplify(square_r[1]);
755
756 static Pcre paren_r("^\\((.*)\\)$");
757 if (paren_r(data, size))
758 return Simplify(paren_r[1]);
759
760 static Pcre title_r("^(.*?) \\((.*)\\)$");
761 if (title_r(data, size))
762 return Simplify(title_r[1]);
763
764 return title;
765}
766/* }}} */
767
768NSString *GetLastUpdate() {
769 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
770
771 if (update == nil)
772 return UCLocalize("NEVER_OR_UNKNOWN");
773
774 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
775 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
776
777 CFRelease(formatter);
778
779 return [(NSString *) formatted autorelease];
780}
781
782bool isSectionVisible(NSString *section) {
783 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
784 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
785 return hidden == nil || ![hidden boolValue];
786}
787
788static NSObject *CYIOGetValue(const char *path, NSString *property) {
789 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
790 if (entry == MACH_PORT_NULL)
791 return nil;
792
793 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
794 IOObjectRelease(entry);
795
796 if (value == NULL)
797 return nil;
798 return [(id) value autorelease];
799}
800
801static NSString *CYHex(NSData *data, bool reverse = false) {
802 if (data == nil)
803 return nil;
804
805 size_t length([data length]);
806 uint8_t bytes[length];
807 [data getBytes:bytes];
808
809 char string[length * 2 + 1];
810 for (size_t i(0); i != length; ++i)
811 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
812
813 return [NSString stringWithUTF8String:string];
814}
815
816@class Cydia;
817
818/* Delegate Prototypes {{{ */
819@class Package;
820@class Source;
821@class CydiaProgressEvent;
822
823@protocol DatabaseDelegate
824- (void) repairWithSelector:(SEL)selector;
825- (void) setConfigurationData:(NSString *)data;
826- (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
827@end
828
829@class CYPackageController;
830
831@protocol CydiaDelegate
832- (void) retainNetworkActivityIndicator;
833- (void) releaseNetworkActivityIndicator;
834- (void) clearPackage:(Package *)package;
835- (void) installPackage:(Package *)package;
836- (void) installPackages:(NSArray *)packages;
837- (void) removePackage:(Package *)package;
838- (void) beginUpdate;
839- (BOOL) updating;
840- (void) distUpgrade;
841- (void) loadData;
842- (void) updateData;
843- (void) syncData;
844- (void) addTrivialSource:(NSString *)href;
845- (void) showSettings;
846- (UIProgressHUD *) addProgressHUD;
847- (void) removeProgressHUD:(UIProgressHUD *)hud;
848- (CyteViewController *) pageForPackage:(NSString *)name;
849- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
850- (void) reloadDataWithInvocation:(NSInvocation *)invocation;
851@end
852/* }}} */
853
854/* Status Delegation {{{ */
855class Status :
856 public pkgAcquireStatus
857{
858 private:
859 _transient NSObject<ProgressDelegate> *delegate_;
860 bool cancelled_;
861
862 public:
863 Status() :
864 delegate_(nil),
865 cancelled_(false)
866 {
867 }
868
869 void setDelegate(NSObject<ProgressDelegate> *delegate) {
870 delegate_ = delegate;
871 }
872
873 NSObject<ProgressDelegate> *getDelegate() const {
874 return delegate_;
875 }
876
877 virtual bool MediaChange(std::string media, std::string drive) {
878 return false;
879 }
880
881 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
882 }
883
884 virtual void Fetch(pkgAcquire::ItemDesc &item) {
885 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
886 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
887 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
888 }
889
890 virtual void Done(pkgAcquire::ItemDesc &item) {
891 }
892
893 virtual void Fail(pkgAcquire::ItemDesc &item) {
894 if (
895 item.Owner->Status == pkgAcquire::Item::StatIdle ||
896 item.Owner->Status == pkgAcquire::Item::StatDone
897 )
898 return;
899
900 std::string &error(item.Owner->ErrorText);
901 if (error.empty())
902 return;
903
904 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
905 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
906 }
907
908 virtual bool Pulse(pkgAcquire *Owner) {
909 bool value = pkgAcquireStatus::Pulse(Owner);
910
911 double percent(
912 double(CurrentBytes + CurrentItems) /
913 double(TotalBytes + TotalItems)
914 );
915
916 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
917 [NSNumber numberWithDouble:percent], @"Percent",
918
919 [NSNumber numberWithDouble:CurrentBytes], @"Current",
920 [NSNumber numberWithDouble:TotalBytes], @"Total",
921 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
922 nil] waitUntilDone:YES];
923
924 if (value && ![delegate_ isProgressCancelled])
925 return true;
926 else {
927 cancelled_ = true;
928 return false;
929 }
930 }
931
932 _finline bool WasCancelled() const {
933 return cancelled_;
934 }
935
936 virtual void Start() {
937 pkgAcquireStatus::Start();
938 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
939 }
940
941 virtual void Stop() {
942 pkgAcquireStatus::Stop();
943 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
944 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
945 }
946};
947/* }}} */
948/* Database Interface {{{ */
949typedef std::map< unsigned long, _H<Source> > SourceMap;
950
951@interface Database : NSObject {
952 NSZone *zone_;
953 apr_pool_t *pool_;
954
955 unsigned era_;
956
957 pkgCacheFile cache_;
958 pkgDepCache::Policy *policy_;
959 pkgRecords *records_;
960 pkgProblemResolver *resolver_;
961 pkgAcquire *fetcher_;
962 FileFd *lock_;
963 SPtr<pkgPackageManager> manager_;
964 pkgSourceList *list_;
965
966 SourceMap sourceMap_;
967 _H<NSMutableArray> sourceList_;
968
969 CFMutableArrayRef packages_;
970
971 _transient NSObject<DatabaseDelegate> *delegate_;
972 _transient NSObject<ProgressDelegate> *progress_;
973
974 Status status_;
975
976 int cydiafd_;
977 int statusfd_;
978 FILE *input_;
979
980 std::map<const char *, _H<NSString> > sections_;
981}
982
983+ (Database *) sharedInstance;
984- (unsigned) era;
985
986- (void) _readCydia:(NSNumber *)fd;
987- (void) _readStatus:(NSNumber *)fd;
988- (void) _readOutput:(NSNumber *)fd;
989
990- (FILE *) input;
991
992- (Package *) packageWithName:(NSString *)name;
993
994- (pkgCacheFile &) cache;
995- (pkgDepCache::Policy *) policy;
996- (pkgRecords *) records;
997- (pkgProblemResolver *) resolver;
998- (pkgAcquire &) fetcher;
999- (pkgSourceList &) list;
1000- (NSArray *) packages;
1001- (NSArray *) sources;
1002- (Source *) sourceWithKey:(NSString *)key;
1003- (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1004
1005- (void) configure;
1006- (bool) prepare;
1007- (void) perform;
1008- (bool) upgrade;
1009- (void) update;
1010
1011- (void) updateWithStatus:(Status &)status;
1012
1013- (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1014
1015- (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1016- (NSObject<ProgressDelegate> *) progressDelegate;
1017
1018- (Source *) getSource:(pkgCache::PkgFileIterator)file;
1019
1020- (NSString *) mappedSectionForPointer:(const char *)pointer;
1021
1022@end
1023/* }}} */
1024/* ProgressEvent Implementation {{{ */
1025@implementation CydiaProgressEvent
1026
1027+ (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1028 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1029}
1030
1031+ (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1032 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1033 [event setPackage:package];
1034 return event;
1035}
1036
1037+ (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1038 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1039
1040 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1041 NSArray *fields([description componentsSeparatedByString:@" "]);
1042 [event setItem:fields];
1043
1044 if ([fields count] > 3) {
1045 [event setPackage:[fields objectAtIndex:2]];
1046 [event setVersion:[fields objectAtIndex:3]];
1047 }
1048
1049 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1050
1051 return event;
1052}
1053
1054+ (NSArray *) _attributeKeys {
1055 return [NSArray arrayWithObjects:
1056 @"item",
1057 @"message",
1058 @"package",
1059 @"type",
1060 @"url",
1061 @"version",
1062 nil];
1063}
1064
1065- (NSArray *) attributeKeys {
1066 return [[self class] _attributeKeys];
1067}
1068
1069+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1070 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1071}
1072
1073- (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1074 if ((self = [super init]) != nil) {
1075 message_ = message;
1076 type_ = type;
1077 } return self;
1078}
1079
1080- (NSString *) message {
1081 return message_;
1082}
1083
1084- (NSString *) type {
1085 return type_;
1086}
1087
1088- (NSArray *) item {
1089 return (id) item_ ?: [NSNull null];
1090}
1091
1092- (void) setItem:(NSArray *)item {
1093 item_ = item;
1094}
1095
1096- (NSString *) package {
1097 return (id) package_ ?: [NSNull null];
1098}
1099
1100- (void) setPackage:(NSString *)package {
1101 package_ = package;
1102}
1103
1104- (NSString *) url {
1105 return (id) url_ ?: [NSNull null];
1106}
1107
1108- (void) setURL:(NSString *)url {
1109 url_ = url;
1110}
1111
1112- (void) setVersion:(NSString *)version {
1113 version_ = version;
1114}
1115
1116- (NSString *) version {
1117 return (id) version_ ?: [NSNull null];
1118}
1119
1120- (NSString *) compound:(NSString *)value {
1121 if (value != nil) {
1122 NSString *mode(nil); {
1123 NSString *type([self type]);
1124 if ([type isEqualToString:kCydiaProgressEventTypeError])
1125 mode = UCLocalize("ERROR");
1126 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1127 mode = UCLocalize("WARNING");
1128 }
1129
1130 if (mode != nil)
1131 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1132 }
1133
1134 return value;
1135}
1136
1137- (NSString *) compoundMessage {
1138 return [self compound:[self message]];
1139}
1140
1141- (NSString *) compoundTitle {
1142 NSString *title;
1143
1144 if (package_ == nil)
1145 title = nil;
1146 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1147 title = [package name];
1148 else
1149 title = package_;
1150
1151 return [self compound:title];
1152}
1153
1154@end
1155/* }}} */
1156
1157// Cytore Definitions {{{
1158struct PackageValue :
1159 Cytore::Block
1160{
1161 Cytore::Offset<PackageValue> next_;
1162
1163 uint32_t index_ : 23;
1164 uint32_t subscribed_ : 1;
1165 uint32_t : 8;
1166
1167 int32_t first_;
1168 int32_t last_;
1169
1170 uint16_t vhash_;
1171 uint16_t nhash_;
1172
1173 char version_[8];
1174 char name_[];
1175};
1176
1177struct MetaValue :
1178 Cytore::Block
1179{
1180 uint32_t active_;
1181 Cytore::Offset<PackageValue> packages_[1 << 16];
1182};
1183
1184static Cytore::File<MetaValue> MetaFile_;
1185// }}}
1186// Cytore Helper Functions {{{
1187static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1188 SplitHash nhash = { hashlittle(name, length) };
1189
1190 PackageValue *metadata;
1191
1192 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1193 offset: if (offset->IsNull()) {
1194 *offset = MetaFile_.New<PackageValue>(length + 1);
1195 metadata = &MetaFile_.Get(*offset);
1196
1197 if (metadata == NULL) {
1198 if (fail != NULL)
1199 *fail = true;
1200
1201 metadata = new PackageValue();
1202 memset(metadata, 0, sizeof(*metadata));
1203 }
1204
1205 memcpy(metadata->name_, name, length + 1);
1206 metadata->nhash_ = nhash.u16[1];
1207 } else {
1208 metadata = &MetaFile_.Get(*offset);
1209
1210 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1211 offset = &metadata->next_;
1212 goto offset;
1213 }
1214 }
1215
1216 return metadata;
1217}
1218
1219static void PackageImport(const void *key, const void *value, void *context) {
1220 bool &fail(*reinterpret_cast<bool *>(context));
1221
1222 char buffer[1024];
1223 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1224 NSLog(@"failed to import package %@", key);
1225 return;
1226 }
1227
1228 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1229 NSDictionary *package((NSDictionary *) value);
1230
1231 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1232 if ([subscribed boolValue] && !metadata->subscribed_)
1233 metadata->subscribed_ = true;
1234
1235 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1236 time_t time([date timeIntervalSince1970]);
1237 if (metadata->first_ > time || metadata->first_ == 0)
1238 metadata->first_ = time;
1239 }
1240
1241 NSDate *date([package objectForKey:@"LastSeen"]);
1242 NSString *version([package objectForKey:@"LastVersion"]);
1243
1244 if (date != nil && version != nil) {
1245 time_t time([date timeIntervalSince1970]);
1246 if (metadata->last_ < time || metadata->last_ == 0)
1247 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1248 size_t length(strlen(buffer));
1249 uint16_t vhash(hashlittle(buffer, length));
1250
1251 size_t capped(std::min<size_t>(8, length));
1252 char *latest(buffer + length - capped);
1253
1254 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1255 metadata->vhash_ = vhash;
1256
1257 metadata->last_ = time;
1258 }
1259 }
1260}
1261// }}}
1262
1263/* Source Class {{{ */
1264@interface Source : NSObject {
1265 CYString depiction_;
1266 CYString description_;
1267 CYString label_;
1268 CYString origin_;
1269 CYString support_;
1270
1271 CYString uri_;
1272 CYString distribution_;
1273 CYString type_;
1274 CYString base_;
1275 CYString version_;
1276
1277 _H<NSString> host_;
1278 _H<NSString> authority_;
1279
1280 CYString defaultIcon_;
1281
1282 _H<NSDictionary> record_;
1283 BOOL trusted_;
1284}
1285
1286- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1287
1288- (NSComparisonResult) compareByNameAndType:(Source *)source;
1289
1290- (NSString *) depictionForPackage:(NSString *)package;
1291- (NSString *) supportForPackage:(NSString *)package;
1292
1293- (NSDictionary *) record;
1294- (BOOL) trusted;
1295
1296- (NSString *) uri;
1297- (NSString *) distribution;
1298- (NSString *) type;
1299
1300- (NSString *) base;
1301
1302- (NSString *) key;
1303- (NSString *) host;
1304
1305- (NSString *) name;
1306- (NSString *) shortDescription;
1307- (NSString *) label;
1308- (NSString *) origin;
1309- (NSString *) version;
1310
1311- (NSString *) defaultIcon;
1312
1313@end
1314
1315@implementation Source
1316
1317- (void) _clear {
1318 uri_.clear();
1319 distribution_.clear();
1320 type_.clear();
1321
1322 base_.clear();
1323
1324 description_.clear();
1325 label_.clear();
1326 origin_.clear();
1327 depiction_.clear();
1328 support_.clear();
1329 version_.clear();
1330 defaultIcon_.clear();
1331
1332 record_ = nil;
1333 host_ = nil;
1334 authority_ = nil;
1335}
1336
1337+ (NSArray *) _attributeKeys {
1338 return [NSArray arrayWithObjects:
1339 @"distribution",
1340 @"host",
1341 @"key",
1342 @"label",
1343 @"name",
1344 @"origin",
1345 @"shortDescription",
1346 @"trusted",
1347 @"type",
1348 @"uri",
1349 @"version",
1350 nil];
1351}
1352
1353- (NSArray *) attributeKeys {
1354 return [[self class] _attributeKeys];
1355}
1356
1357+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1358 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1359}
1360
1361- (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1362 [self _clear];
1363
1364 trusted_ = index->IsTrusted();
1365
1366 uri_.set(pool, index->GetURI());
1367 distribution_.set(pool, index->GetDist());
1368 type_.set(pool, index->GetType());
1369
1370 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1371 if (dindex != NULL) {
1372 base_.set(pool, dindex->MetaIndexURI(""));
1373
1374 FileFd fd;
1375 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1376 _error->Discard();
1377 else {
1378 pkgTagFile tags(&fd);
1379
1380 pkgTagSection section;
1381 tags.Step(section);
1382
1383 struct {
1384 const char *name_;
1385 CYString *value_;
1386 } names[] = {
1387 {"default-icon", &defaultIcon_},
1388 {"depiction", &depiction_},
1389 {"description", &description_},
1390 {"label", &label_},
1391 {"origin", &origin_},
1392 {"support", &support_},
1393 {"version", &version_},
1394 };
1395
1396 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1397 const char *start, *end;
1398
1399 if (section.Find(names[i].name_, start, end)) {
1400 CYString &value(*names[i].value_);
1401 value.set(pool, start, end - start);
1402 }
1403 }
1404 }
1405 }
1406
1407 record_ = [Sources_ objectForKey:[self key]];
1408
1409 NSURL *url([NSURL URLWithString:uri_]);
1410
1411 host_ = [url host];
1412 if (host_ != nil)
1413 host_ = [host_ lowercaseString];
1414
1415 if (host_ != nil)
1416 authority_ = host_;
1417 else
1418 authority_ = [url path];
1419}
1420
1421- (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1422 if ((self = [super init]) != nil) {
1423 [self setMetaIndex:index inPool:pool];
1424 } return self;
1425}
1426
1427- (NSComparisonResult) compareByNameAndType:(Source *)source {
1428 NSDictionary *lhr = [self record];
1429 NSDictionary *rhr = [source record];
1430
1431 if (lhr != rhr)
1432 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1433
1434 NSString *lhs = [self name];
1435 NSString *rhs = [source name];
1436
1437 if ([lhs length] != 0 && [rhs length] != 0) {
1438 unichar lhc = [lhs characterAtIndex:0];
1439 unichar rhc = [rhs characterAtIndex:0];
1440
1441 if (isalpha(lhc) && !isalpha(rhc))
1442 return NSOrderedAscending;
1443 else if (!isalpha(lhc) && isalpha(rhc))
1444 return NSOrderedDescending;
1445 }
1446
1447 return [lhs compare:rhs options:LaxCompareOptions_];
1448}
1449
1450- (NSString *) depictionForPackage:(NSString *)package {
1451 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1452}
1453
1454- (NSString *) supportForPackage:(NSString *)package {
1455 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1456}
1457
1458- (NSDictionary *) record {
1459 return record_;
1460}
1461
1462- (BOOL) trusted {
1463 return trusted_;
1464}
1465
1466- (NSString *) uri {
1467 return uri_;
1468}
1469
1470- (NSString *) distribution {
1471 return distribution_;
1472}
1473
1474- (NSString *) type {
1475 return type_;
1476}
1477
1478- (NSString *) base {
1479 return base_;
1480}
1481
1482- (NSString *) key {
1483 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1484}
1485
1486- (NSString *) host {
1487 return host_;
1488}
1489
1490- (NSString *) name {
1491 return origin_.empty() ? (id) authority_ : origin_;
1492}
1493
1494- (NSString *) shortDescription {
1495 return description_;
1496}
1497
1498- (NSString *) label {
1499 return label_.empty() ? (id) authority_ : label_;
1500}
1501
1502- (NSString *) origin {
1503 return origin_;
1504}
1505
1506- (NSString *) version {
1507 return version_;
1508}
1509
1510- (NSString *) defaultIcon {
1511 return defaultIcon_;
1512}
1513
1514@end
1515/* }}} */
1516/* CydiaOperation Class {{{ */
1517@interface CydiaOperation : NSObject {
1518 _H<NSString> operator_;
1519 _H<NSString> value_;
1520}
1521
1522- (NSString *) operator;
1523- (NSString *) value;
1524
1525@end
1526
1527@implementation CydiaOperation
1528
1529- (id) initWithOperator:(const char *)_operator value:(const char *)value {
1530 if ((self = [super init]) != nil) {
1531 operator_ = [NSString stringWithUTF8String:_operator];
1532 value_ = [NSString stringWithUTF8String:value];
1533 } return self;
1534}
1535
1536+ (NSArray *) _attributeKeys {
1537 return [NSArray arrayWithObjects:
1538 @"operator",
1539 @"value",
1540 nil];
1541}
1542
1543- (NSArray *) attributeKeys {
1544 return [[self class] _attributeKeys];
1545}
1546
1547+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1548 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1549}
1550
1551- (NSString *) operator {
1552 return operator_;
1553}
1554
1555- (NSString *) value {
1556 return value_;
1557}
1558
1559@end
1560/* }}} */
1561/* CydiaClause Class {{{ */
1562@interface CydiaClause : NSObject {
1563 _H<NSString> package_;
1564 _H<CydiaOperation> version_;
1565}
1566
1567- (NSString *) package;
1568- (CydiaOperation *) version;
1569
1570@end
1571
1572@implementation CydiaClause
1573
1574- (id) initWithIterator:(pkgCache::DepIterator &)dep {
1575 if ((self = [super init]) != nil) {
1576 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1577
1578 if (const char *version = dep.TargetVer())
1579 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1580 else
1581 version_ = (id) [NSNull null];
1582 } return self;
1583}
1584
1585+ (NSArray *) _attributeKeys {
1586 return [NSArray arrayWithObjects:
1587 @"package",
1588 @"version",
1589 nil];
1590}
1591
1592- (NSArray *) attributeKeys {
1593 return [[self class] _attributeKeys];
1594}
1595
1596+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1597 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1598}
1599
1600- (NSString *) package {
1601 return package_;
1602}
1603
1604- (CydiaOperation *) version {
1605 return version_;
1606}
1607
1608@end
1609/* }}} */
1610/* CydiaRelation Class {{{ */
1611@interface CydiaRelation : NSObject {
1612 _H<NSString> relationship_;
1613 _H<NSMutableArray> clauses_;
1614}
1615
1616- (NSString *) relationship;
1617- (NSArray *) clauses;
1618
1619@end
1620
1621@implementation CydiaRelation
1622
1623- (id) initWithIterator:(pkgCache::DepIterator &)dep {
1624 if ((self = [super init]) != nil) {
1625 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1626 clauses_ = [NSMutableArray arrayWithCapacity:8];
1627
1628 pkgCache::DepIterator start;
1629 pkgCache::DepIterator end;
1630 dep.GlobOr(start, end); // ++dep
1631
1632 _forever {
1633 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1634
1635 // yes, seriously. (wtf?)
1636 if (start == end)
1637 break;
1638 ++start;
1639 }
1640 } return self;
1641}
1642
1643+ (NSArray *) _attributeKeys {
1644 return [NSArray arrayWithObjects:
1645 @"clauses",
1646 @"relationship",
1647 nil];
1648}
1649
1650- (NSArray *) attributeKeys {
1651 return [[self class] _attributeKeys];
1652}
1653
1654+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1655 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1656}
1657
1658- (NSString *) relationship {
1659 return relationship_;
1660}
1661
1662- (NSArray *) clauses {
1663 return clauses_;
1664}
1665
1666- (void) addClause:(CydiaClause *)clause {
1667 [clauses_ addObject:clause];
1668}
1669
1670@end
1671/* }}} */
1672/* Package Class {{{ */
1673struct ParsedPackage {
1674 CYString tagline_;
1675
1676 CYString icon_;
1677
1678 CYString depiction_;
1679 CYString homepage_;
1680
1681 CYString sponsor_;
1682 CYString author_;
1683
1684 CYString bugs_;
1685 CYString support_;
1686};
1687
1688@interface Package : NSObject {
1689 uint32_t era_ : 26;
1690 uint32_t role_ : 3;
1691 uint32_t essential_ : 1;
1692 uint32_t obsolete_ : 1;
1693 uint32_t ignored_ : 1;
1694
1695 apr_pool_t *pool_;
1696
1697 uint32_t rank_;
1698
1699 _transient Database *database_;
1700
1701 pkgCache::VerIterator version_;
1702 pkgCache::PkgIterator iterator_;
1703 pkgCache::VerFileIterator file_;
1704
1705 CYString id_;
1706 CYString name_;
1707
1708 CYString latest_;
1709 CYString installed_;
1710
1711 const char *section_;
1712 _transient NSString *section$_;
1713
1714 _H<Source> source_;
1715
1716 PackageValue *metadata_;
1717 ParsedPackage *parsed_;
1718
1719 _H<NSMutableArray> tags_;
1720}
1721
1722- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1723+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1724
1725- (pkgCache::PkgIterator) iterator;
1726- (void) parse;
1727
1728- (NSString *) section;
1729- (NSString *) simpleSection;
1730
1731- (NSString *) longSection;
1732- (NSString *) shortSection;
1733
1734- (NSString *) uri;
1735
1736- (MIMEAddress *) maintainer;
1737- (size_t) size;
1738- (NSString *) longDescription;
1739- (NSString *) shortDescription;
1740- (unichar) index;
1741
1742- (PackageValue *) metadata;
1743- (time_t) seen;
1744
1745- (bool) subscribed;
1746- (bool) setSubscribed:(bool)subscribed;
1747
1748- (BOOL) ignored;
1749
1750- (NSString *) latest;
1751- (NSString *) installed;
1752- (BOOL) uninstalled;
1753
1754- (BOOL) valid;
1755- (BOOL) upgradableAndEssential:(BOOL)essential;
1756- (BOOL) essential;
1757- (BOOL) broken;
1758- (BOOL) unfiltered;
1759- (BOOL) visible;
1760
1761- (BOOL) half;
1762- (BOOL) halfConfigured;
1763- (BOOL) halfInstalled;
1764- (BOOL) hasMode;
1765- (NSString *) mode;
1766
1767- (NSString *) id;
1768- (NSString *) name;
1769- (UIImage *) icon;
1770- (NSString *) homepage;
1771- (NSString *) depiction;
1772- (MIMEAddress *) author;
1773
1774- (NSString *) support;
1775
1776- (NSArray *) files;
1777- (NSArray *) warnings;
1778- (NSArray *) applications;
1779
1780- (Source *) source;
1781
1782- (uint32_t) rank;
1783- (BOOL) matches:(NSArray *)query;
1784
1785- (bool) hasSupportingRole;
1786- (BOOL) hasTag:(NSString *)tag;
1787- (NSString *) primaryPurpose;
1788- (NSArray *) purposes;
1789- (bool) isCommercial;
1790
1791- (void) setIndex:(size_t)index;
1792
1793- (CYString &) cyname;
1794
1795- (uint32_t) compareBySection:(NSArray *)sections;
1796
1797- (void) install;
1798- (void) remove;
1799
1800- (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1801- (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1802- (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1803- (bool) isVisibleInSection:(NSString *)section;
1804- (bool) isVisibleInSource:(Source *)source;
1805
1806@end
1807
1808uint32_t PackageChangesRadix(Package *self, void *) {
1809 union {
1810 uint32_t key;
1811
1812 struct {
1813 uint32_t timestamp : 30;
1814 uint32_t ignored : 1;
1815 uint32_t upgradable : 1;
1816 } bits;
1817 } value;
1818
1819 bool upgradable([self upgradableAndEssential:YES]);
1820 value.bits.upgradable = upgradable ? 1 : 0;
1821
1822 if (upgradable) {
1823 value.bits.timestamp = 0;
1824 value.bits.ignored = [self ignored] ? 0 : 1;
1825 value.bits.upgradable = 1;
1826 } else {
1827 value.bits.timestamp = [self seen] >> 2;
1828 value.bits.ignored = 0;
1829 value.bits.upgradable = 0;
1830 }
1831
1832 return _not(uint32_t) - value.key;
1833}
1834
1835uint32_t PackagePrefixRadix(Package *self, void *context) {
1836 size_t offset(reinterpret_cast<size_t>(context));
1837 CYString &name([self cyname]);
1838
1839 size_t size(name.size());
1840 if (size == 0)
1841 return 0;
1842 char *text(name.data());
1843
1844 size_t zeros;
1845 if (!isdigit(text[0]))
1846 zeros = 0;
1847 else {
1848 size_t digits(1);
1849 while (size != digits && isdigit(text[digits]))
1850 if (++digits == 4)
1851 break;
1852 zeros = 4 - digits;
1853 }
1854
1855 uint8_t data[4];
1856
1857 if (offset == 0 && zeros != 0) {
1858 memset(data, '0', zeros);
1859 memcpy(data + zeros, text, 4 - zeros);
1860 } else {
1861 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1862 if (size <= offset - zeros)
1863 return 0;
1864
1865 text += offset - zeros;
1866 size -= offset - zeros;
1867
1868 if (size >= 4)
1869 memcpy(data, text, 4);
1870 else {
1871 memcpy(data, text, size);
1872 memset(data + size, 0, 4 - size);
1873 }
1874
1875 for (size_t i(0); i != 4; ++i)
1876 if (isalpha(data[i]))
1877 data[i] |= 0x20;
1878 }
1879
1880 if (offset == 0)
1881 if (data[0] == '@')
1882 data[0] = 0x7f;
1883 else
1884 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1885
1886 /* XXX: ntohl may be more honest */
1887 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1888}
1889
1890CYString &(*PackageName)(Package *self, SEL sel);
1891
1892CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1893 _profile(PackageNameCompare)
1894 CYString &lhi(PackageName(lhs, @selector(cyname)));
1895 CYString &rhi(PackageName(rhs, @selector(cyname)));
1896 CFStringRef lhn(lhi), rhn(rhi);
1897
1898 if (lhn == NULL)
1899 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1900 else if (rhn == NULL)
1901 return NSOrderedDescending;
1902
1903 _profile(PackageNameCompare$NumbersLast)
1904 if (!lhi.empty() && !rhi.empty()) {
1905 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1906 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1907 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1908 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1909 return lha ? NSOrderedAscending : NSOrderedDescending;
1910 }
1911 _end
1912
1913 CFIndex length = CFStringGetLength(lhn);
1914
1915 _profile(PackageNameCompare$Compare)
1916 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1917 _end
1918 _end
1919}
1920
1921CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1922 return PackageNameCompare(*lhs, *rhs, context);
1923}
1924
1925struct PackageNameOrdering :
1926 std::binary_function<Package *, Package *, bool>
1927{
1928 _finline bool operator ()(Package *lhs, Package *rhs) const {
1929 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1930 }
1931};
1932
1933@implementation Package
1934
1935- (NSString *) description {
1936 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1937}
1938
1939- (void) dealloc {
1940 if (parsed_ != NULL)
1941 delete parsed_;
1942 [super dealloc];
1943}
1944
1945+ (NSString *) webScriptNameForSelector:(SEL)selector {
1946 if (false);
1947 else if (selector == @selector(clear))
1948 return @"clear";
1949 else if (selector == @selector(getField:))
1950 return @"getField";
1951 else if (selector == @selector(hasTag:))
1952 return @"hasTag";
1953 else if (selector == @selector(install))
1954 return @"install";
1955 else if (selector == @selector(remove))
1956 return @"remove";
1957 else
1958 return nil;
1959}
1960
1961+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1962 return [self webScriptNameForSelector:selector] == nil;
1963}
1964
1965+ (NSArray *) _attributeKeys {
1966 return [NSArray arrayWithObjects:
1967 @"applications",
1968 @"author",
1969 @"depiction",
1970 @"essential",
1971 @"homepage",
1972 @"icon",
1973 @"id",
1974 @"installed",
1975 @"latest",
1976 @"longDescription",
1977 @"longSection",
1978 @"maintainer",
1979 @"mode",
1980 @"name",
1981 @"purposes",
1982 @"relations",
1983 @"section",
1984 @"selection",
1985 @"shortDescription",
1986 @"shortSection",
1987 @"simpleSection",
1988 @"size",
1989 @"source",
1990 @"sponsor",
1991 @"state",
1992 @"support",
1993 @"tags",
1994 @"warnings",
1995 nil];
1996}
1997
1998- (NSArray *) attributeKeys {
1999 return [[self class] _attributeKeys];
2000}
2001
2002+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2003 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2004}
2005
2006- (NSArray *) relations {
2007@synchronized (database_) {
2008 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2009 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2010 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2011 return relations;
2012} }
2013
2014- (NSString *) getField:(NSString *)name {
2015@synchronized (database_) {
2016 if ([database_ era] != era_ || file_.end())
2017 return nil;
2018
2019 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2020
2021 const char *start, *end;
2022 if (!parser.Find([name UTF8String], start, end))
2023 return (NSString *) [NSNull null];
2024
2025 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2026} }
2027
2028- (void) parse {
2029 if (parsed_ != NULL)
2030 return;
2031@synchronized (database_) {
2032 if ([database_ era] != era_ || file_.end())
2033 return;
2034
2035 ParsedPackage *parsed(new ParsedPackage);
2036 parsed_ = parsed;
2037
2038 _profile(Package$parse)
2039 pkgRecords::Parser *parser;
2040
2041 _profile(Package$parse$Lookup)
2042 parser = &[database_ records]->Lookup(file_);
2043 _end
2044
2045 CYString website;
2046
2047 _profile(Package$parse$Find)
2048 struct {
2049 const char *name_;
2050 CYString *value_;
2051 } names[] = {
2052 {"icon", &parsed->icon_},
2053 {"depiction", &parsed->depiction_},
2054 {"homepage", &parsed->homepage_},
2055 {"website", &website},
2056 {"bugs", &parsed->bugs_},
2057 {"support", &parsed->support_},
2058 {"sponsor", &parsed->sponsor_},
2059 {"author", &parsed->author_},
2060 };
2061
2062 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2063 const char *start, *end;
2064
2065 if (parser->Find(names[i].name_, start, end)) {
2066 CYString &value(*names[i].value_);
2067 _profile(Package$parse$Value)
2068 value.set(pool_, start, end - start);
2069 _end
2070 }
2071 }
2072 _end
2073
2074 _profile(Package$parse$Tagline)
2075 const char *start, *end;
2076 if (parser->ShortDesc(start, end)) {
2077 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2078 if (stop == NULL)
2079 stop = end;
2080 while (stop != start && stop[-1] == '\r')
2081 --stop;
2082 parsed->tagline_.set(pool_, start, stop - start);
2083 }
2084 _end
2085
2086 _profile(Package$parse$Retain)
2087 if (parsed->homepage_.empty())
2088 parsed->homepage_ = website;
2089 if (parsed->homepage_ == parsed->depiction_)
2090 parsed->homepage_.clear();
2091 _end
2092 _end
2093} }
2094
2095- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2096 if ((self = [super init]) != nil) {
2097 _profile(Package$initWithVersion)
2098 pool_ = pool;
2099
2100 database_ = database;
2101 era_ = [database era];
2102
2103 version_ = version;
2104
2105 pkgCache::PkgIterator iterator(version.ParentPkg());
2106 iterator_ = iterator;
2107
2108 _profile(Package$initWithVersion$Version)
2109 if (!version_.end())
2110 file_ = version_.FileList();
2111 else {
2112 pkgCache &cache([database_ cache]);
2113 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2114 }
2115 _end
2116
2117 _profile(Package$initWithVersion$Cache)
2118 name_.set(NULL, iterator.Display());
2119
2120 latest_.set(NULL, StripVersion_(version_.VerStr()));
2121
2122 pkgCache::VerIterator current(iterator.CurrentVer());
2123 if (!current.end())
2124 installed_.set(NULL, StripVersion_(current.VerStr()));
2125 _end
2126
2127 _profile(Package$initWithVersion$Tags)
2128 pkgCache::TagIterator tag(iterator.TagList());
2129 if (!tag.end()) {
2130 tags_ = [NSMutableArray arrayWithCapacity:8];
2131 do {
2132 const char *name(tag.Name());
2133 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2134
2135 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2136 if (strcmp(name + 6, "enduser") == 0)
2137 role_ = 1;
2138 else if (strcmp(name + 6, "hacker") == 0)
2139 role_ = 2;
2140 else if (strcmp(name + 6, "developer") == 0)
2141 role_ = 3;
2142 else if (strcmp(name + 6, "cydia") == 0)
2143 role_ = 7;
2144 else
2145 role_ = 4;
2146 }
2147
2148 if (strncmp(name, "cydia::", 7) == 0) {
2149 if (strcmp(name + 7, "essential") == 0)
2150 essential_ = true;
2151 else if (strcmp(name + 7, "obsolete") == 0)
2152 obsolete_ = true;
2153 }
2154
2155 ++tag;
2156 } while (!tag.end());
2157 }
2158 _end
2159
2160 _profile(Package$initWithVersion$Metadata)
2161 const char *mixed(iterator.Name());
2162 size_t size(strlen(mixed));
2163 char lower[size + 1];
2164
2165 for (size_t i(0); i != size; ++i)
2166 lower[i] = mixed[i] | 0x20;
2167 lower[size] = '\0';
2168
2169 PackageValue *metadata(PackageFind(lower, size));
2170 metadata_ = metadata;
2171
2172 id_.set(NULL, metadata->name_, size);
2173
2174 const char *latest(version_.VerStr());
2175 size_t length(strlen(latest));
2176
2177 uint16_t vhash(hashlittle(latest, length));
2178
2179 size_t capped(std::min<size_t>(8, length));
2180 latest = latest + length - capped;
2181
2182 if (metadata->first_ == 0)
2183 metadata->first_ = now_;
2184
2185 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2186 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2187 metadata->vhash_ = vhash;
2188 metadata->last_ = now_;
2189 } else if (metadata->last_ == 0)
2190 metadata->last_ = metadata->first_;
2191 _end
2192
2193 _profile(Package$initWithVersion$Section)
2194 section_ = iterator.Section();
2195 _end
2196
2197 _profile(Package$initWithVersion$Flags)
2198 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2199 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2200 _end
2201 _end } return self;
2202}
2203
2204+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2205 pkgCache::VerIterator version;
2206
2207 _profile(Package$packageWithIterator$GetCandidateVer)
2208 version = [database policy]->GetCandidateVer(iterator);
2209 _end
2210
2211 if (version.end())
2212 return nil;
2213
2214 Package *package;
2215
2216 _profile(Package$packageWithIterator$Allocate)
2217 package = [Package allocWithZone:zone];
2218 _end
2219
2220 _profile(Package$packageWithIterator$Initialize)
2221 package = [package
2222 initWithVersion:version
2223 withZone:zone
2224 inPool:pool
2225 database:database
2226 ];
2227 _end
2228
2229 _profile(Package$packageWithIterator$Autorelease)
2230 package = [package autorelease];
2231 _end
2232
2233 return package;
2234}
2235
2236- (pkgCache::PkgIterator) iterator {
2237 return iterator_;
2238}
2239
2240- (NSString *) section {
2241 if (section$_ == nil) {
2242 if (section_ == NULL)
2243 return nil;
2244
2245 _profile(Package$section$mappedSectionForPointer)
2246 section$_ = [database_ mappedSectionForPointer:section_];
2247 _end
2248 } return section$_;
2249}
2250
2251- (NSString *) simpleSection {
2252 if (NSString *section = [self section])
2253 return Simplify(section);
2254 else
2255 return nil;
2256}
2257
2258- (NSString *) longSection {
2259 return LocalizeSection([self section]);
2260}
2261
2262- (NSString *) shortSection {
2263 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2264}
2265
2266- (NSString *) uri {
2267 return nil;
2268#if 0
2269 pkgIndexFile *index;
2270 pkgCache::PkgFileIterator file(file_.File());
2271 if (![database_ list].FindIndex(file, index))
2272 return nil;
2273 return [NSString stringWithUTF8String:iterator_->Path];
2274 //return [NSString stringWithUTF8String:file.Site()];
2275 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2276#endif
2277}
2278
2279- (MIMEAddress *) maintainer {
2280@synchronized (database_) {
2281 if ([database_ era] != era_ || file_.end())
2282 return nil;
2283
2284 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2285 const std::string &maintainer(parser->Maintainer());
2286 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2287} }
2288
2289- (size_t) size {
2290@synchronized (database_) {
2291 if ([database_ era] != era_ || version_.end())
2292 return 0;
2293
2294 return version_->InstalledSize;
2295} }
2296
2297- (NSString *) longDescription {
2298@synchronized (database_) {
2299 if ([database_ era] != era_ || file_.end())
2300 return nil;
2301
2302 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2303 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2304
2305 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2306 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2307 if ([lines count] < 2)
2308 return nil;
2309
2310 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2311 for (size_t i(1), e([lines count]); i != e; ++i) {
2312 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2313 [trimmed addObject:trim];
2314 }
2315
2316 return [trimmed componentsJoinedByString:@"\n"];
2317} }
2318
2319- (NSString *) shortDescription {
2320 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2321}
2322
2323- (unichar) index {
2324 _profile(Package$index)
2325 CFStringRef name((CFStringRef) [self name]);
2326 if (CFStringGetLength(name) == 0)
2327 return '#';
2328 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2329 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2330 return '#';
2331 return toupper(character);
2332 _end
2333}
2334
2335- (PackageValue *) metadata {
2336 return metadata_;
2337}
2338
2339- (time_t) seen {
2340 PackageValue *metadata([self metadata]);
2341 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2342}
2343
2344- (bool) subscribed {
2345 return [self metadata]->subscribed_;
2346}
2347
2348- (bool) setSubscribed:(bool)subscribed {
2349 PackageValue *metadata([self metadata]);
2350 if (metadata->subscribed_ == subscribed)
2351 return false;
2352 metadata->subscribed_ = subscribed;
2353 return true;
2354}
2355
2356- (BOOL) ignored {
2357 return ignored_;
2358}
2359
2360- (NSString *) latest {
2361 return latest_;
2362}
2363
2364- (NSString *) installed {
2365 return installed_;
2366}
2367
2368- (BOOL) uninstalled {
2369 return installed_.empty();
2370}
2371
2372- (BOOL) valid {
2373 return !version_.end();
2374}
2375
2376- (BOOL) upgradableAndEssential:(BOOL)essential {
2377 _profile(Package$upgradableAndEssential)
2378 pkgCache::VerIterator current(iterator_.CurrentVer());
2379 if (current.end())
2380 return essential && essential_;
2381 else
2382 return !version_.end() && version_ != current;
2383 _end
2384}
2385
2386- (BOOL) essential {
2387 return essential_;
2388}
2389
2390- (BOOL) broken {
2391 return [database_ cache][iterator_].InstBroken();
2392}
2393
2394- (BOOL) unfiltered {
2395 _profile(Package$unfiltered$obsolete)
2396 if (_unlikely(obsolete_))
2397 return false;
2398 _end
2399
2400 _profile(Package$unfiltered$hasSupportingRole)
2401 if (_unlikely(![self hasSupportingRole]))
2402 return false;
2403 _end
2404
2405 return true;
2406}
2407
2408- (BOOL) visible {
2409 if (![self unfiltered])
2410 return false;
2411
2412 NSString *section;
2413
2414 _profile(Package$visible$section)
2415 section = [self section];
2416 _end
2417
2418 _profile(Package$visible$isSectionVisible)
2419 if (!isSectionVisible(section))
2420 return false;
2421 _end
2422
2423 return true;
2424}
2425
2426- (BOOL) half {
2427 unsigned char current(iterator_->CurrentState);
2428 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2429}
2430
2431- (BOOL) halfConfigured {
2432 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2433}
2434
2435- (BOOL) halfInstalled {
2436 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2437}
2438
2439- (BOOL) hasMode {
2440 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2441 return state.Mode != pkgDepCache::ModeKeep;
2442}
2443
2444- (NSString *) mode {
2445 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2446
2447 switch (state.Mode) {
2448 case pkgDepCache::ModeDelete:
2449 if ((state.iFlags & pkgDepCache::Purge) != 0)
2450 return @"PURGE";
2451 else
2452 return @"REMOVE";
2453 case pkgDepCache::ModeKeep:
2454 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2455 return @"REINSTALL";
2456 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2457 return nil;*/
2458 else
2459 return nil;
2460 case pkgDepCache::ModeInstall:
2461 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2462 return @"REINSTALL";
2463 else*/ switch (state.Status) {
2464 case -1:
2465 return @"DOWNGRADE";
2466 case 0:
2467 return @"INSTALL";
2468 case 1:
2469 return @"UPGRADE";
2470 case 2:
2471 return @"NEW_INSTALL";
2472 _nodefault
2473 }
2474 _nodefault
2475 }
2476}
2477
2478- (NSString *) id {
2479 return id_;
2480}
2481
2482- (NSString *) name {
2483 return name_.empty() ? id_ : name_;
2484}
2485
2486- (UIImage *) icon {
2487 NSString *section = [self simpleSection];
2488
2489 UIImage *icon(nil);
2490 if (parsed_ != NULL)
2491 if (NSString *href = parsed_->icon_)
2492 if ([href hasPrefix:@"file:///"])
2493 // XXX: correct escaping
2494 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2495 if (icon == nil) if (section != nil)
2496 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2497 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2498 if ([dicon hasPrefix:@"file:///"])
2499 // XXX: correct escaping
2500 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2501 if (icon == nil)
2502 icon = [UIImage applicationImageNamed:@"unknown.png"];
2503 return icon;
2504}
2505
2506- (NSString *) homepage {
2507 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2508}
2509
2510- (NSString *) depiction {
2511 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2512}
2513
2514- (MIMEAddress *) sponsor {
2515 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2516}
2517
2518- (MIMEAddress *) author {
2519 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2520}
2521
2522- (NSString *) support {
2523 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2524}
2525
2526- (NSArray *) files {
2527 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2528 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2529
2530 std::ifstream fin;
2531 fin.open([path UTF8String]);
2532 if (!fin.is_open())
2533 return nil;
2534
2535 std::string line;
2536 while (std::getline(fin, line))
2537 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2538
2539 return files;
2540}
2541
2542- (NSString *) state {
2543@synchronized (database_) {
2544 if ([database_ era] != era_ || file_.end())
2545 return nil;
2546
2547 switch (iterator_->CurrentState) {
2548 case pkgCache::State::NotInstalled:
2549 return @"NotInstalled";
2550 case pkgCache::State::UnPacked:
2551 return @"UnPacked";
2552 case pkgCache::State::HalfConfigured:
2553 return @"HalfConfigured";
2554 case pkgCache::State::HalfInstalled:
2555 return @"HalfInstalled";
2556 case pkgCache::State::ConfigFiles:
2557 return @"ConfigFiles";
2558 case pkgCache::State::Installed:
2559 return @"Installed";
2560 case pkgCache::State::TriggersAwaited:
2561 return @"TriggersAwaited";
2562 case pkgCache::State::TriggersPending:
2563 return @"TriggersPending";
2564 }
2565
2566 return (NSString *) [NSNull null];
2567} }
2568
2569- (NSString *) selection {
2570@synchronized (database_) {
2571 if ([database_ era] != era_ || file_.end())
2572 return nil;
2573
2574 switch (iterator_->SelectedState) {
2575 case pkgCache::State::Unknown:
2576 return @"Unknown";
2577 case pkgCache::State::Install:
2578 return @"Install";
2579 case pkgCache::State::Hold:
2580 return @"Hold";
2581 case pkgCache::State::DeInstall:
2582 return @"DeInstall";
2583 case pkgCache::State::Purge:
2584 return @"Purge";
2585 }
2586
2587 return (NSString *) [NSNull null];
2588} }
2589
2590- (NSArray *) warnings {
2591 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2592 const char *name(iterator_.Name());
2593
2594 size_t length(strlen(name));
2595 if (length < 2) invalid:
2596 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2597 else for (size_t i(0); i != length; ++i)
2598 if (
2599 /* XXX: technically this is not allowed */
2600 (name[i] < 'A' || name[i] > 'Z') &&
2601 (name[i] < 'a' || name[i] > 'z') &&
2602 (name[i] < '0' || name[i] > '9') &&
2603 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2604 ) goto invalid;
2605
2606 if (strcmp(name, "cydia") != 0) {
2607 bool cydia = false;
2608 bool user = false;
2609 bool _private = false;
2610 bool stash = false;
2611
2612 bool repository = [[self section] isEqualToString:@"Repositories"];
2613
2614 if (NSArray *files = [self files])
2615 for (NSString *file in files)
2616 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2617 cydia = true;
2618 else if (!user && [file isEqualToString:@"/User"])
2619 user = true;
2620 else if (!_private && [file isEqualToString:@"/private"])
2621 _private = true;
2622 else if (!stash && [file isEqualToString:@"/var/stash"])
2623 stash = true;
2624
2625 /* XXX: this is not sensitive enough. only some folders are valid. */
2626 if (cydia && !repository)
2627 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2628 if (user)
2629 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2630 if (_private)
2631 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2632 if (stash)
2633 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2634 }
2635
2636 return [warnings count] == 0 ? nil : warnings;
2637}
2638
2639- (NSArray *) applications {
2640 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2641
2642 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2643
2644 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2645 if (NSArray *files = [self files])
2646 for (NSString *file in files)
2647 if (application_r(file)) {
2648 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2649 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2650 if ([id isEqualToString:me])
2651 continue;
2652
2653 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2654 if (display == nil)
2655 display = application_r[1];
2656
2657 NSString *bundle([file stringByDeletingLastPathComponent]);
2658 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2659 if (icon == nil || [icon length] == 0)
2660 icon = @"icon.png";
2661 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2662
2663 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2664 [applications addObject:application];
2665
2666 [application addObject:id];
2667 [application addObject:display];
2668 [application addObject:url];
2669 }
2670
2671 return [applications count] == 0 ? nil : applications;
2672}
2673
2674- (Source *) source {
2675 if (source_ == nil) {
2676 @synchronized (database_) {
2677 if ([database_ era] != era_ || file_.end())
2678 source_ = (Source *) [NSNull null];
2679 else
2680 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2681 }
2682 }
2683
2684 return source_ == (Source *) [NSNull null] ? nil : source_;
2685}
2686
2687- (uint32_t) rank {
2688 return rank_;
2689}
2690
2691- (BOOL) matches:(NSArray *)query {
2692 if (query == nil || [query count] == 0)
2693 return NO;
2694
2695 rank_ = 0;
2696
2697 NSString *string;
2698 NSRange range;
2699 NSUInteger length;
2700
2701 [self parse];
2702
2703 string = [self id];
2704 length = [string length];
2705
2706 for (NSString *term in query) {
2707 range = [string rangeOfString:term options:MatchCompareOptions_];
2708 if (range.location != NSNotFound)
2709 rank_ -= 10 * 100000 / length;
2710 }
2711
2712 string = [self name];
2713
2714 for (NSString *term in query) {
2715 range = [string rangeOfString:term options:MatchCompareOptions_];
2716 if (range.location != NSNotFound)
2717 rank_ -= 6 * 100000 / length;
2718 }
2719
2720 string = [self shortDescription];
2721 length = [string length];
2722 NSUInteger stop(std::min<NSUInteger>(length, 100));
2723
2724 for (NSString *term in query) {
2725 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2726 if (range.location != NSNotFound)
2727 rank_ -= 2 * 100000 / length;
2728 }
2729
2730 return rank_ != 0;
2731}
2732
2733- (bool) hasSupportingRole {
2734 if (role_ == 0)
2735 return true;
2736 if (role_ == 1)
2737 return true;
2738 if ([Role_ isEqualToString:@"User"])
2739 return false;
2740 if (role_ == 2)
2741 return true;
2742 if ([Role_ isEqualToString:@"Hacker"])
2743 return false;
2744 if (role_ == 3)
2745 return true;
2746 if ([Role_ isEqualToString:@"Developer"])
2747 return false;
2748 _assert(false);
2749}
2750
2751- (NSArray *) tags {
2752 return tags_;
2753}
2754
2755- (BOOL) hasTag:(NSString *)tag {
2756 return tags_ == nil ? NO : [tags_ containsObject:tag];
2757}
2758
2759- (NSString *) primaryPurpose {
2760 for (NSString *tag in (NSArray *) tags_)
2761 if ([tag hasPrefix:@"purpose::"])
2762 return [tag substringFromIndex:9];
2763 return nil;
2764}
2765
2766- (NSArray *) purposes {
2767 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2768 for (NSString *tag in (NSArray *) tags_)
2769 if ([tag hasPrefix:@"purpose::"])
2770 [purposes addObject:[tag substringFromIndex:9]];
2771 return [purposes count] == 0 ? nil : purposes;
2772}
2773
2774- (bool) isCommercial {
2775 return [self hasTag:@"cydia::commercial"];
2776}
2777
2778- (void) setIndex:(size_t)index {
2779 if (metadata_->index_ != index)
2780 metadata_->index_ = index;
2781}
2782
2783- (CYString &) cyname {
2784 return name_.empty() ? id_ : name_;
2785}
2786
2787- (uint32_t) compareBySection:(NSArray *)sections {
2788 NSString *section([self section]);
2789 for (size_t i(0), e([sections count]); i != e; ++i) {
2790 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2791 return i;
2792 }
2793
2794 return _not(uint32_t);
2795}
2796
2797- (void) clear {
2798@synchronized (database_) {
2799 pkgProblemResolver *resolver = [database_ resolver];
2800 resolver->Clear(iterator_);
2801
2802 pkgCacheFile &cache([database_ cache]);
2803 cache->SetReInstall(iterator_, false);
2804 cache->MarkKeep(iterator_, false);
2805} }
2806
2807- (void) install {
2808@synchronized (database_) {
2809 pkgProblemResolver *resolver = [database_ resolver];
2810 resolver->Clear(iterator_);
2811 resolver->Protect(iterator_);
2812
2813 pkgCacheFile &cache([database_ cache]);
2814 cache->SetReInstall(iterator_, false);
2815 cache->MarkInstall(iterator_, false);
2816
2817 pkgDepCache::StateCache &state((*cache)[iterator_]);
2818 if (!state.Install())
2819 cache->SetReInstall(iterator_, true);
2820} }
2821
2822- (void) remove {
2823@synchronized (database_) {
2824 pkgProblemResolver *resolver = [database_ resolver];
2825 resolver->Clear(iterator_);
2826 resolver->Remove(iterator_);
2827 resolver->Protect(iterator_);
2828
2829 pkgCacheFile &cache([database_ cache]);
2830 cache->SetReInstall(iterator_, false);
2831 cache->MarkDelete(iterator_, true);
2832} }
2833
2834- (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2835 _profile(Package$isUnfilteredAndSearchedForBy)
2836 bool value(true);
2837
2838 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2839 value &= [self unfiltered];
2840 _end
2841
2842 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2843 value &= [self matches:query];
2844 _end
2845
2846 return value;
2847 _end
2848}
2849
2850- (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2851 if ([search length] == 0)
2852 return false;
2853
2854 _profile(Package$isUnfilteredAndSelectedForBy)
2855 bool value(true);
2856
2857 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2858 value &= [self unfiltered];
2859 _end
2860
2861 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2862 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2863 _end
2864
2865 return value;
2866 _end
2867}
2868
2869- (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2870 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2871}
2872
2873- (bool) isVisibleInSection:(NSString *)name {
2874 NSString *section([self section]);
2875
2876 return (
2877 name == nil ||
2878 section == nil && [name length] == 0 ||
2879 [name isEqualToString:section]
2880 ) && [self visible];
2881}
2882
2883- (bool) isVisibleInSource:(Source *)source {
2884 return [self source] == source && [self visible];
2885}
2886
2887@end
2888/* }}} */
2889/* Section Class {{{ */
2890@interface Section : NSObject {
2891 _H<NSString> name_;
2892 unichar index_;
2893 size_t row_;
2894 size_t count_;
2895 _H<NSString> localized_;
2896}
2897
2898- (NSComparisonResult) compareByLocalized:(Section *)section;
2899- (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2900- (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2901- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2902- (Section *) initWithIndex:(unichar)index row:(size_t)row;
2903- (NSString *) name;
2904- (unichar) index;
2905
2906- (size_t) row;
2907- (size_t) count;
2908
2909- (void) addToRow;
2910- (void) addToCount;
2911
2912- (void) setCount:(size_t)count;
2913- (NSString *) localized;
2914
2915@end
2916
2917@implementation Section
2918
2919- (NSComparisonResult) compareByLocalized:(Section *)section {
2920 NSString *lhs(localized_);
2921 NSString *rhs([section localized]);
2922
2923 /*if ([lhs length] != 0 && [rhs length] != 0) {
2924 unichar lhc = [lhs characterAtIndex:0];
2925 unichar rhc = [rhs characterAtIndex:0];
2926
2927 if (isalpha(lhc) && !isalpha(rhc))
2928 return NSOrderedAscending;
2929 else if (!isalpha(lhc) && isalpha(rhc))
2930 return NSOrderedDescending;
2931 }*/
2932
2933 return [lhs compare:rhs options:LaxCompareOptions_];
2934}
2935
2936- (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2937 if ((self = [self initWithName:name localize:NO]) != nil) {
2938 if (localized != nil)
2939 localized_ = localized;
2940 } return self;
2941}
2942
2943- (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2944 return [self initWithName:name row:0 localize:localize];
2945}
2946
2947- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2948 if ((self = [super init]) != nil) {
2949 name_ = name;
2950 index_ = '\0';
2951 row_ = row;
2952 if (localize)
2953 localized_ = LocalizeSection(name_);
2954 } return self;
2955}
2956
2957/* XXX: localize the index thingees */
2958- (Section *) initWithIndex:(unichar)index row:(size_t)row {
2959 if ((self = [super init]) != nil) {
2960 name_ = [NSString stringWithCharacters:&index length:1];
2961 index_ = index;
2962 row_ = row;
2963 } return self;
2964}
2965
2966- (NSString *) name {
2967 return name_;
2968}
2969
2970- (unichar) index {
2971 return index_;
2972}
2973
2974- (size_t) row {
2975 return row_;
2976}
2977
2978- (size_t) count {
2979 return count_;
2980}
2981
2982- (void) addToRow {
2983 ++row_;
2984}
2985
2986- (void) addToCount {
2987 ++count_;
2988}
2989
2990- (void) setCount:(size_t)count {
2991 count_ = count;
2992}
2993
2994- (NSString *) localized {
2995 return localized_;
2996}
2997
2998@end
2999/* }}} */
3000
3001static NSString *Colon_;
3002NSString *Elision_;
3003static NSString *Error_;
3004static NSString *Warning_;
3005
3006class CydiaLogCleaner :
3007 public pkgArchiveCleaner
3008{
3009 protected:
3010 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3011 unlink(File);
3012 }
3013};
3014
3015/* Database Implementation {{{ */
3016@implementation Database
3017
3018+ (Database *) sharedInstance {
3019 static _H<Database> instance;
3020 if (instance == nil)
3021 instance = [[[Database alloc] init] autorelease];
3022 return instance;
3023}
3024
3025- (unsigned) era {
3026 return era_;
3027}
3028
3029- (void) releasePackages {
3030 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3031 CFArrayRemoveAllValues(packages_);
3032}
3033
3034- (void) dealloc {
3035 // XXX: actually implement this thing
3036 _assert(false);
3037 [self releasePackages];
3038 apr_pool_destroy(pool_);
3039 NSRecycleZone(zone_);
3040 [super dealloc];
3041}
3042
3043- (void) _readCydia:(NSNumber *)fd {
3044 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3045 std::istream is(&ib);
3046 std::string line;
3047
3048 static Pcre finish_r("^finish:([^:]*)$");
3049
3050 while (std::getline(is, line)) {
3051 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3052
3053 const char *data(line.c_str());
3054 size_t size = line.size();
3055 lprintf("C:%s\n", data);
3056
3057 if (finish_r(data, size)) {
3058 NSString *finish = finish_r[1];
3059 int index = [Finishes_ indexOfObject:finish];
3060 if (index != INT_MAX && index > Finish_)
3061 Finish_ = index;
3062 }
3063
3064 [pool release];
3065 }
3066
3067 _assume(false);
3068}
3069
3070- (void) _readStatus:(NSNumber *)fd {
3071 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3072 std::istream is(&ib);
3073 std::string line;
3074
3075 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3076 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3077
3078 while (std::getline(is, line)) {
3079 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3080
3081 const char *data(line.c_str());
3082 size_t size(line.size());
3083 lprintf("S:%s\n", data);
3084
3085 if (conffile_r(data, size)) {
3086 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3087 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3088 } else if (strncmp(data, "status: ", 8) == 0) {
3089 // status: <package>: {unpacked,half-configured,installed}
3090 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3091 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3092 } else if (strncmp(data, "processing: ", 12) == 0) {
3093 // processing: configure: config-test
3094 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3095 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3096 } else if (pmstatus_r(data, size)) {
3097 std::string type([pmstatus_r[1] UTF8String]);
3098
3099 NSString *package = pmstatus_r[2];
3100 if ([package isEqualToString:@"dpkg-exec"])
3101 package = nil;
3102
3103 float percent([pmstatus_r[3] floatValue]);
3104 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3105
3106 NSString *string = pmstatus_r[4];
3107
3108 if (type == "pmerror") {
3109 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3110 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3111 } else if (type == "pmstatus") {
3112 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3113 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3114 } else if (type == "pmconffile")
3115 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3116 else
3117 lprintf("E:unknown pmstatus\n");
3118 } else
3119 lprintf("E:unknown status\n");
3120
3121 [pool release];
3122 }
3123
3124 _assume(false);
3125}
3126
3127- (void) _readOutput:(NSNumber *)fd {
3128 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3129 std::istream is(&ib);
3130 std::string line;
3131
3132 while (std::getline(is, line)) {
3133 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3134
3135 lprintf("O:%s\n", line.c_str());
3136
3137 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3138 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3139
3140 [pool release];
3141 }
3142
3143 _assume(false);
3144}
3145
3146- (FILE *) input {
3147 return input_;
3148}
3149
3150- (Package *) packageWithName:(NSString *)name {
3151@synchronized (self) {
3152 if (static_cast<pkgDepCache *>(cache_) == NULL)
3153 return nil;
3154 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3155 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3156} }
3157
3158- (id) init {
3159 if ((self = [super init]) != nil) {
3160 policy_ = NULL;
3161 records_ = NULL;
3162 resolver_ = NULL;
3163 fetcher_ = NULL;
3164 lock_ = NULL;
3165
3166 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3167 apr_pool_create(&pool_, NULL);
3168
3169 size_t capacity(MetaFile_->active_);
3170 if (capacity == 0)
3171 capacity = 16384;
3172 else
3173 capacity += 1024;
3174
3175 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3176 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3177
3178 int fds[2];
3179
3180 _assert(pipe(fds) != -1);
3181 cydiafd_ = fds[1];
3182
3183 _config->Set("APT::Keep-Fds::", cydiafd_);
3184 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3185
3186 [NSThread
3187 detachNewThreadSelector:@selector(_readCydia:)
3188 toTarget:self
3189 withObject:[NSNumber numberWithInt:fds[0]]
3190 ];
3191
3192 _assert(pipe(fds) != -1);
3193 statusfd_ = fds[1];
3194
3195 [NSThread
3196 detachNewThreadSelector:@selector(_readStatus:)
3197 toTarget:self
3198 withObject:[NSNumber numberWithInt:fds[0]]
3199 ];
3200
3201 _assert(pipe(fds) != -1);
3202 _assert(dup2(fds[0], 0) != -1);
3203 _assert(close(fds[0]) != -1);
3204
3205 input_ = fdopen(fds[1], "a");
3206
3207 _assert(pipe(fds) != -1);
3208 _assert(dup2(fds[1], 1) != -1);
3209 _assert(close(fds[1]) != -1);
3210
3211 [NSThread
3212 detachNewThreadSelector:@selector(_readOutput:)
3213 toTarget:self
3214 withObject:[NSNumber numberWithInt:fds[0]]
3215 ];
3216 } return self;
3217}
3218
3219- (pkgCacheFile &) cache {
3220 return cache_;
3221}
3222
3223- (pkgDepCache::Policy *) policy {
3224 return policy_;
3225}
3226
3227- (pkgRecords *) records {
3228 return records_;
3229}
3230
3231- (pkgProblemResolver *) resolver {
3232 return resolver_;
3233}
3234
3235- (pkgAcquire &) fetcher {
3236 return *fetcher_;
3237}
3238
3239- (pkgSourceList &) list {
3240 return *list_;
3241}
3242
3243- (NSArray *) packages {
3244 return (NSArray *) packages_;
3245}
3246
3247- (NSArray *) sources {
3248 return sourceList_;
3249}
3250
3251- (Source *) sourceWithKey:(NSString *)key {
3252 for (Source *source in [self sources]) {
3253 if ([[source key] isEqualToString:key])
3254 return source;
3255 } return nil;
3256}
3257
3258- (bool) popErrorWithTitle:(NSString *)title {
3259 bool fatal(false);
3260
3261 while (!_error->empty()) {
3262 std::string error;
3263 bool warning(!_error->PopMessage(error));
3264 if (!warning)
3265 fatal = true;
3266
3267 for (;;) {
3268 size_t size(error.size());
3269 if (size == 0 || error[size - 1] != '\n')
3270 break;
3271 error.resize(size - 1);
3272 }
3273
3274 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3275
3276 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3277 }
3278
3279 return fatal;
3280}
3281
3282- (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3283 return [self popErrorWithTitle:title] || !success;
3284}
3285
3286- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3287@synchronized (self) {
3288 ++era_;
3289
3290 [self releasePackages];
3291
3292 sourceMap_.clear();
3293 [sourceList_ removeAllObjects];
3294
3295 _error->Discard();
3296
3297 delete list_;
3298 list_ = NULL;
3299 manager_ = NULL;
3300 delete lock_;
3301 lock_ = NULL;
3302 delete fetcher_;
3303 fetcher_ = NULL;
3304 delete resolver_;
3305 resolver_ = NULL;
3306 delete records_;
3307 records_ = NULL;
3308 delete policy_;
3309 policy_ = NULL;
3310
3311 cache_.Close();
3312
3313 apr_pool_clear(pool_);
3314
3315 NSRecycleZone(zone_);
3316 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3317
3318 int chk(creat("/tmp/cydia.chk", 0644));
3319 if (chk != -1)
3320 close(chk);
3321
3322 if (invocation != nil)
3323 [invocation invoke];
3324
3325 NSString *title(UCLocalize("DATABASE"));
3326
3327 _trace();
3328 OpProgress progress;
3329 while (!cache_.Open(progress, true)) { pop:
3330 std::string error;
3331 bool warning(!_error->PopMessage(error));
3332 lprintf("cache_.Open():[%s]\n", error.c_str());
3333
3334 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3335 [delegate_ repairWithSelector:@selector(configure)];
3336 else if (error == "The package lists or status file could not be parsed or opened.")
3337 [delegate_ repairWithSelector:@selector(update)];
3338 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3339 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3340 // else if (error == "Malformed Status line")
3341 // else if (error == "The list of sources could not be read.")
3342 else {
3343 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3344 return;
3345 }
3346
3347 if (warning)
3348 goto pop;
3349 _error->Discard();
3350 }
3351 _trace();
3352
3353 unlink("/tmp/cydia.chk");
3354
3355 now_ = [[NSDate date] timeIntervalSince1970];
3356
3357 policy_ = new pkgDepCache::Policy();
3358 records_ = new pkgRecords(cache_);
3359 resolver_ = new pkgProblemResolver(cache_);
3360 fetcher_ = new pkgAcquire(&status_);
3361 lock_ = NULL;
3362
3363 list_ = new pkgSourceList();
3364 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3365 return;
3366
3367 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3368 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3369 return;
3370 }
3371
3372 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3373 return;
3374
3375 if (cache_->BrokenCount() != 0) {
3376 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3377 return;
3378
3379 if (cache_->BrokenCount() != 0) {
3380 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3381 return;
3382 }
3383
3384 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3385 return;
3386 }
3387
3388 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3389 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3390 [sourceList_ addObject:object];
3391
3392 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3393 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3394 // XXX: this could be more intelligent
3395 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3396 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3397 if (!cached.end())
3398 sourceMap_[cached->ID] = object;
3399 }
3400 }
3401
3402 {
3403 /*std::vector<Package *> packages;
3404 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3405 packages_ = nil;*/
3406
3407 _trace();
3408
3409 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3410 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3411 //packages.push_back(package);
3412 CFArrayAppendValue(packages_, CFRetain(package));
3413
3414 _trace();
3415
3416 /*if (packages.empty())
3417 packages_ = [[NSArray alloc] init];
3418 else
3419 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3420 _trace();*/
3421
3422 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3423 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3424 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3425
3426 /*_trace();
3427 PrintTimes();
3428 _trace();*/
3429
3430 _trace();
3431
3432 /*if (!packages.empty())
3433 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3434 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3435
3436 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3437
3438 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3439
3440 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3441
3442 _trace();
3443
3444 size_t count(CFArrayGetCount(packages_));
3445 MetaFile_->active_ = count;
3446
3447 for (size_t index(0); index != count; ++index)
3448 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3449
3450 _trace();
3451 }
3452} }
3453
3454- (void) clear {
3455@synchronized (self) {
3456 delete resolver_;
3457 resolver_ = new pkgProblemResolver(cache_);
3458
3459 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3460 if (!cache_[iterator].Keep())
3461 cache_->MarkKeep(iterator, false);
3462 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3463 cache_->SetReInstall(iterator, false);
3464} }
3465
3466- (void) configure {
3467 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3468 _trace();
3469 system([dpkg UTF8String]);
3470 _trace();
3471}
3472
3473- (bool) clean {
3474 // XXX: I don't remember this condition
3475 if (lock_ != NULL)
3476 return false;
3477
3478 FileFd Lock;
3479 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3480
3481 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3482
3483 if ([self popErrorWithTitle:title])
3484 return false;
3485
3486 pkgAcquire fetcher;
3487 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3488
3489 CydiaLogCleaner cleaner;
3490 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3491 return false;
3492
3493 return true;
3494}
3495
3496- (bool) prepare {
3497 fetcher_->Shutdown();
3498
3499 pkgRecords records(cache_);
3500
3501 lock_ = new FileFd();
3502 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3503
3504 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3505
3506 if ([self popErrorWithTitle:title])
3507 return false;
3508
3509 pkgSourceList list;
3510 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3511 return false;
3512
3513 manager_ = (_system->CreatePM(cache_));
3514 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3515 return false;
3516
3517 return true;
3518}
3519
3520- (void) perform {
3521 bool substrate(RestartSubstrate_);
3522 RestartSubstrate_ = false;
3523
3524 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3525
3526 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3527 pkgSourceList list;
3528 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3529 return;
3530 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3531 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3532 }
3533
3534 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3535
3536 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3537 _trace();
3538 [self popErrorWithTitle:title];
3539 return;
3540 }
3541
3542 bool failed = false;
3543 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3544 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3545 continue;
3546 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3547 continue;
3548
3549 failed = true;
3550 }
3551
3552 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3553
3554 if (failed) {
3555 _trace();
3556 return;
3557 }
3558
3559 if (substrate)
3560 RestartSubstrate_ = true;
3561
3562 _system->UnLock();
3563 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3564
3565 if (_error->PendingError()) {
3566 _trace();
3567 return;
3568 }
3569
3570 if (result == pkgPackageManager::Failed) {
3571 _trace();
3572 return;
3573 }
3574
3575 if (result != pkgPackageManager::Completed) {
3576 _trace();
3577 return;
3578 }
3579
3580 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3581 pkgSourceList list;
3582 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3583 return;
3584 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3585 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3586 }
3587
3588 if (![before isEqualToArray:after])
3589 [self update];
3590}
3591
3592- (bool) upgrade {
3593 NSString *title(UCLocalize("UPGRADE"));
3594 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3595 return false;
3596 return true;
3597}
3598
3599- (void) update {
3600 [self updateWithStatus:status_];
3601}
3602
3603- (void) updateWithStatus:(Status &)status {
3604 NSString *title(UCLocalize("REFRESHING_DATA"));
3605
3606 pkgSourceList list;
3607 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3608 return;
3609
3610 FileFd lock;
3611 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3612 if ([self popErrorWithTitle:title])
3613 return;
3614
3615 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3616
3617 bool success(ListUpdate(status, list, PulseInterval_));
3618 if (status.WasCancelled())
3619 _error->Discard();
3620 else {
3621 [self popErrorWithTitle:title forOperation:success];
3622 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3623 Changed_ = true;
3624 }
3625
3626 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3627}
3628
3629- (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3630 delegate_ = delegate;
3631}
3632
3633- (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3634 progress_ = delegate;
3635 status_.setDelegate(delegate);
3636}
3637
3638- (NSObject<ProgressDelegate> *) progressDelegate {
3639 return progress_;
3640}
3641
3642- (Source *) getSource:(pkgCache::PkgFileIterator)file {
3643 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3644 return i == sourceMap_.end() ? nil : i->second;
3645}
3646
3647- (NSString *) mappedSectionForPointer:(const char *)section {
3648 _H<NSString> *mapped;
3649
3650 _profile(Database$mappedSectionForPointer$Cache)
3651 mapped = &sections_[section];
3652 _end
3653
3654 if (*mapped == NULL) {
3655 size_t length(strlen(section));
3656 char spaced[length + 1];
3657
3658 _profile(Database$mappedSectionForPointer$Replace)
3659 for (size_t index(0); index != length; ++index)
3660 spaced[index] = section[index] == '_' ? ' ' : section[index];
3661 spaced[length] = '\0';
3662 _end
3663
3664 NSString *string;
3665
3666 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3667 string = [NSString stringWithUTF8String:spaced];
3668 _end
3669
3670 _profile(Database$mappedSectionForPointer$Map)
3671 string = [SectionMap_ objectForKey:string] ?: string;
3672 _end
3673
3674 *mapped = string;
3675 } return *mapped;
3676}
3677
3678@end
3679/* }}} */
3680
3681static _H<NSMutableSet> Diversions_;
3682
3683@interface Diversion : NSObject {
3684 Pcre pattern_;
3685 _H<NSString> key_;
3686 _H<NSString> format_;
3687}
3688
3689@end
3690
3691@implementation Diversion
3692
3693- (id) initWithFrom:(NSString *)from to:(NSString *)to {
3694 if ((self = [super init]) != nil) {
3695 pattern_ = [from UTF8String];
3696 key_ = from;
3697 format_ = to;
3698 } return self;
3699}
3700
3701- (NSString *) divert:(NSString *)url {
3702 return !pattern_(url) ? nil : pattern_->*format_;
3703}
3704
3705+ (NSURL *) divertURL:(NSURL *)url {
3706 divert:
3707 NSString *href([url absoluteString]);
3708
3709 for (Diversion *diversion in (id) Diversions_)
3710 if (NSString *diverted = [diversion divert:href]) {
3711#if !ForRelease
3712 NSLog(@"div: %@", diverted);
3713#endif
3714 url = [NSURL URLWithString:diverted];
3715 goto divert;
3716 }
3717
3718 return url;
3719}
3720
3721- (NSString *) key {
3722 return key_;
3723}
3724
3725- (NSUInteger) hash {
3726 return [key_ hash];
3727}
3728
3729- (BOOL) isEqual:(Diversion *)object {
3730 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3731}
3732
3733@end
3734
3735@interface CydiaObject : NSObject {
3736 _H<IndirectDelegate> indirect_;
3737 _transient id delegate_;
3738}
3739
3740- (id) initWithDelegate:(IndirectDelegate *)indirect;
3741
3742@end
3743
3744@interface CydiaWebViewController : CyteWebViewController {
3745 _H<CydiaObject> cydia_;
3746}
3747
3748+ (void) addDiversion:(Diversion *)diversion;
3749
3750@end
3751
3752/* Web Scripting {{{ */
3753@implementation CydiaObject
3754
3755- (id) initWithDelegate:(IndirectDelegate *)indirect {
3756 if ((self = [super init]) != nil) {
3757 indirect_ = indirect;
3758 } return self;
3759}
3760
3761- (void) setDelegate:(id)delegate {
3762 delegate_ = delegate;
3763}
3764
3765+ (NSArray *) _attributeKeys {
3766 return [NSArray arrayWithObjects:
3767 @"bbsnum",
3768 @"device",
3769 @"ecid",
3770 @"firmware",
3771 @"hostname",
3772 @"idiom",
3773 @"model",
3774 @"plmn",
3775 @"role",
3776 @"serial",
3777 @"token",
3778 @"version",
3779 nil];
3780}
3781
3782- (NSArray *) attributeKeys {
3783 return [[self class] _attributeKeys];
3784}
3785
3786+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3787 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3788}
3789
3790- (NSString *) version {
3791 return @ Cydia_;
3792}
3793
3794- (NSString *) device {
3795 return [[UIDevice currentDevice] uniqueIdentifier];
3796}
3797
3798- (NSString *) firmware {
3799 return [[UIDevice currentDevice] systemVersion];
3800}
3801
3802- (NSString *) hostname {
3803 return [[UIDevice currentDevice] name];
3804}
3805
3806- (NSString *) idiom {
3807 return (id) Idiom_ ?: [NSNull null];
3808}
3809
3810- (NSString *) plmn {
3811 return (id) PLMN_ ?: [NSNull null];
3812}
3813
3814- (NSString *) bbsnum {
3815 return (id) BBSNum_ ?: [NSNull null];
3816}
3817
3818- (NSString *) ecid {
3819 return (id) ChipID_ ?: [NSNull null];
3820}
3821
3822- (NSString *) serial {
3823 return SerialNumber_;
3824}
3825
3826- (NSString *) role {
3827 return (id) Role_ ?: [NSNull null];
3828}
3829
3830- (NSString *) model {
3831 return [NSString stringWithUTF8String:Machine_];
3832}
3833
3834- (NSString *) token {
3835 return (id) Token_ ?: [NSNull null];
3836}
3837
3838+ (NSString *) webScriptNameForSelector:(SEL)selector {
3839 if (false);
3840 else if (selector == @selector(addBridgedHost:))
3841 return @"addBridgedHost";
3842 else if (selector == @selector(addInsecureHost:))
3843 return @"addInsecureHost";
3844 else if (selector == @selector(addInternalRedirect::))
3845 return @"addInternalRedirect";
3846 else if (selector == @selector(addPipelinedHost:scheme:))
3847 return @"addPipelinedHost";
3848 else if (selector == @selector(addTokenHost:))
3849 return @"addTokenHost";
3850 else if (selector == @selector(addTrivialSource:))
3851 return @"addTrivialSource";
3852 else if (selector == @selector(close))
3853 return @"close";
3854 else if (selector == @selector(du:))
3855 return @"du";
3856 else if (selector == @selector(stringWithFormat:arguments:))
3857 return @"format";
3858 else if (selector == @selector(getAllSources))
3859 return @"getAllSourcs";
3860 else if (selector == @selector(getKernelNumber:))
3861 return @"getKernelNumber";
3862 else if (selector == @selector(getKernelString:))
3863 return @"getKernelString";
3864 else if (selector == @selector(getInstalledPackages))
3865 return @"getInstalledPackages";
3866 else if (selector == @selector(getIORegistryEntry::))
3867 return @"getIORegistryEntry";
3868 else if (selector == @selector(getLocaleIdentifier))
3869 return @"getLocaleIdentifier";
3870 else if (selector == @selector(getPreferredLanguages))
3871 return @"getPreferredLanguages";
3872 else if (selector == @selector(getPackageById:))
3873 return @"getPackageById";
3874 else if (selector == @selector(getSessionValue:))
3875 return @"getSessionValue";
3876 else if (selector == @selector(installPackages:))
3877 return @"installPackages";
3878 else if (selector == @selector(localizedStringForKey:value:table:))
3879 return @"localize";
3880 else if (selector == @selector(popViewController:))
3881 return @"popViewController";
3882 else if (selector == @selector(refreshSources))
3883 return @"refreshSources";
3884 else if (selector == @selector(removeButton))
3885 return @"removeButton";
3886 else if (selector == @selector(setSessionValue::))
3887 return @"setSessionValue";
3888 else if (selector == @selector(substitutePackageNames:))
3889 return @"substitutePackageNames";
3890 else if (selector == @selector(scrollToBottom:))
3891 return @"scrollToBottom";
3892 else if (selector == @selector(setAllowsNavigationAction:))
3893 return @"setAllowsNavigationAction";
3894 else if (selector == @selector(setBadgeValue:))
3895 return @"setBadgeValue";
3896 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3897 return @"setButtonImage";
3898 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3899 return @"setButtonTitle";
3900 else if (selector == @selector(setHidesBackButton:))
3901 return @"setHidesBackButton";
3902 else if (selector == @selector(setHidesNavigationBar:))
3903 return @"setHidesNavigationBar";
3904 else if (selector == @selector(setNavigationBarStyle:))
3905 return @"setNavigationBarStyle";
3906 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3907 return @"setNavigationBarTintColor";
3908 else if (selector == @selector(setPasteboardString:))
3909 return @"setPasteboardString";
3910 else if (selector == @selector(setPasteboardURL:))
3911 return @"setPasteboardURL";
3912 else if (selector == @selector(setToken:))
3913 return @"setToken";
3914 else if (selector == @selector(setViewportWidth:))
3915 return @"setViewportWidth";
3916 else if (selector == @selector(statfs:))
3917 return @"statfs";
3918 else if (selector == @selector(supports:))
3919 return @"supports";
3920 else if (selector == @selector(unload))
3921 return @"unload";
3922 else
3923 return nil;
3924}
3925
3926+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3927 return [self webScriptNameForSelector:selector] == nil;
3928}
3929
3930- (BOOL) supports:(NSString *)feature {
3931 return [feature isEqualToString:@"window.open"];
3932}
3933
3934- (void) unload {
3935 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
3936}
3937
3938- (void) addInternalRedirect:(NSString *)from :(NSString *)to {
3939 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
3940}
3941
3942- (NSNumber *) getKernelNumber:(NSString *)name {
3943 const char *string([name UTF8String]);
3944
3945 size_t size;
3946 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3947 return (id) [NSNull null];
3948
3949 if (size != sizeof(int))
3950 return (id) [NSNull null];
3951
3952 int value;
3953 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
3954 return (id) [NSNull null];
3955
3956 return [NSNumber numberWithInt:value];
3957}
3958
3959- (NSString *) getKernelString:(NSString *)name {
3960 const char *string([name UTF8String]);
3961
3962 size_t size;
3963 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
3964 return (id) [NSNull null];
3965
3966 char value[size + 1];
3967 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
3968 return (id) [NSNull null];
3969
3970 // XXX: just in case you request something ludicrous
3971 value[size] = '\0';
3972
3973 return [NSString stringWithCString:value];
3974}
3975
3976- (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
3977 NSObject *value(CYIOGetValue([path UTF8String], entry));
3978
3979 if (value != nil)
3980 if ([value isKindOfClass:[NSData class]])
3981 value = CYHex((NSData *) value);
3982
3983 return value;
3984}
3985
3986- (id) getSessionValue:(NSString *)key {
3987@synchronized (SessionData_) {
3988 return [SessionData_ objectForKey:key];
3989} }
3990
3991- (void) setSessionValue:(NSString *)key :(NSString *)value {
3992@synchronized (SessionData_) {
3993 if (value == (id) [WebUndefined undefined])
3994 [SessionData_ removeObjectForKey:key];
3995 else
3996 [SessionData_ setObject:value forKey:key];
3997} }
3998
3999- (void) addBridgedHost:(NSString *)host {
4000@synchronized (HostConfig_) {
4001 [BridgedHosts_ addObject:host];
4002} }
4003
4004- (void) addInsecureHost:(NSString *)host {
4005@synchronized (HostConfig_) {
4006 [InsecureHosts_ addObject:host];
4007} }
4008
4009- (void) addTokenHost:(NSString *)host {
4010@synchronized (HostConfig_) {
4011 [TokenHosts_ addObject:host];
4012} }
4013
4014- (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4015@synchronized (HostConfig_) {
4016 if (scheme != (id) [WebUndefined undefined])
4017 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4018
4019 [PipelinedHosts_ addObject:host];
4020} }
4021
4022- (void) popViewController:(NSNumber *)value {
4023 if (value == (id) [WebUndefined undefined])
4024 value = [NSNumber numberWithBool:YES];
4025 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4026}
4027
4028- (void) addTrivialSource:(NSString *)href {
4029 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4030}
4031
4032- (void) refreshSources {
4033 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4034}
4035
4036- (NSArray *) getAllSources {
4037 return [[Database sharedInstance] sources];
4038}
4039
4040- (NSArray *) getInstalledPackages {
4041 Database *database([Database sharedInstance]);
4042@synchronized (database) {
4043 NSArray *packages([database packages]);
4044 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4045 for (Package *package in packages)
4046 if (![package uninstalled])
4047 [installed addObject:package];
4048 return installed;
4049} }
4050
4051- (Package *) getPackageById:(NSString *)id {
4052 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4053 [package parse];
4054 return package;
4055 } else
4056 return (Package *) [NSNull null];
4057}
4058
4059- (NSString *) getLocaleIdentifier {
4060 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4061}
4062
4063- (NSArray *) getPreferredLanguages {
4064 return Languages_;
4065}
4066
4067- (NSArray *) statfs:(NSString *)path {
4068 struct statfs stat;
4069
4070 if (path == nil || statfs([path UTF8String], &stat) == -1)
4071 return nil;
4072
4073 return [NSArray arrayWithObjects:
4074 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4075 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4076 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4077 nil];
4078}
4079
4080- (NSNumber *) du:(NSString *)path {
4081 NSNumber *value(nil);
4082
4083 int fds[2];
4084 _assert(pipe(fds) != -1);
4085
4086 pid_t pid(ExecFork());
4087 if (pid == 0) {
4088 _assert(dup2(fds[1], 1) != -1);
4089 _assert(close(fds[0]) != -1);
4090 _assert(close(fds[1]) != -1);
4091 /* XXX: this should probably not use du */
4092 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4093 exit(1);
4094 _assert(false);
4095 }
4096
4097 _assert(close(fds[1]) != -1);
4098
4099 if (FILE *du = fdopen(fds[0], "r")) {
4100 char line[1024];
4101 while (fgets(line, sizeof(line), du) != NULL) {
4102 size_t length(strlen(line));
4103 while (length != 0 && line[length - 1] == '\n')
4104 line[--length] = '\0';
4105 if (char *tab = strchr(line, '\t')) {
4106 *tab = '\0';
4107 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4108 }
4109 }
4110
4111 fclose(du);
4112 } else _assert(close(fds[0]));
4113
4114 int status;
4115 wait:
4116 if (waitpid(pid, &status, 0) == -1)
4117 if (errno == EINTR)
4118 goto wait;
4119 else _assert(false);
4120
4121 return value;
4122}
4123
4124- (void) close {
4125 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4126}
4127
4128- (void) installPackages:(NSArray *)packages {
4129 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4130}
4131
4132- (NSString *) substitutePackageNames:(NSString *)message {
4133 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4134 for (size_t i(0), e([words count]); i != e; ++i) {
4135 NSString *word([words objectAtIndex:i]);
4136 if (Package *package = [[Database sharedInstance] packageWithName:word])
4137 [words replaceObjectAtIndex:i withObject:[package name]];
4138 }
4139
4140 return [words componentsJoinedByString:@" "];
4141}
4142
4143- (void) removeButton {
4144 [indirect_ removeButton];
4145}
4146
4147- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4148 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4149}
4150
4151- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4152 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4153}
4154
4155- (void) setBadgeValue:(id)value {
4156 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4157}
4158
4159- (void) setAllowsNavigationAction:(NSString *)value {
4160 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4161}
4162
4163- (void) setHidesBackButton:(NSString *)value {
4164 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4165}
4166
4167- (void) setHidesNavigationBar:(NSString *)value {
4168 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4169}
4170
4171- (void) setNavigationBarStyle:(NSString *)value {
4172 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4173}
4174
4175- (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4176 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4177 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4178 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4179}
4180
4181- (void) setPasteboardString:(NSString *)value {
4182 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4183}
4184
4185- (void) setPasteboardURL:(NSString *)value {
4186 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4187}
4188
4189- (void) _setToken:(NSString *)token {
4190 Token_ = token;
4191
4192 if (token == nil)
4193 [Metadata_ removeObjectForKey:@"Token"];
4194 else
4195 [Metadata_ setObject:Token_ forKey:@"Token"];
4196
4197 Changed_ = true;
4198}
4199
4200- (void) setToken:(NSString *)token {
4201 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4202}
4203
4204- (void) scrollToBottom:(NSNumber *)animated {
4205 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4206}
4207
4208- (void) setViewportWidth:(float)width {
4209 [indirect_ setViewportWidthOnMainThread:width];
4210}
4211
4212- (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4213 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4214 unsigned count([arguments count]);
4215 id values[count];
4216 for (unsigned i(0); i != count; ++i)
4217 values[i] = [arguments objectAtIndex:i];
4218 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4219}
4220
4221- (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4222 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4223 value = nil;
4224 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4225 table = nil;
4226 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4227}
4228
4229@end
4230/* }}} */
4231
4232@interface NSURL (CydiaSecure)
4233@end
4234
4235@implementation NSURL (CydiaSecure)
4236
4237- (bool) isCydiaSecure {
4238 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4239 return true;
4240
4241 @synchronized (HostConfig_) {
4242 if ([InsecureHosts_ containsObject:[self host]])
4243 return true;
4244 }
4245
4246 return false;
4247}
4248
4249@end
4250
4251/* Cydia Browser Controller {{{ */
4252@implementation CydiaWebViewController
4253
4254- (NSURL *) navigationURL {
4255 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4256}
4257
4258+ (void) initialize {
4259 Diversions_ = [NSMutableSet setWithCapacity:0];
4260}
4261
4262+ (void) addDiversion:(Diversion *)diversion {
4263 [Diversions_ addObject:diversion];
4264}
4265
4266- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4267 [super webView:view didClearWindowObject:window forFrame:frame];
4268
4269 WebDataSource *source([frame dataSource]);
4270 NSURLResponse *response([source response]);
4271 NSURL *url([response URL]);
4272 NSString *scheme([[url scheme] lowercaseString]);
4273
4274 bool bridged(false);
4275
4276 @synchronized (HostConfig_) {
4277 if ([scheme isEqualToString:@"file"])
4278 bridged = true;
4279 else if ([scheme isEqualToString:@"https"])
4280 if ([BridgedHosts_ containsObject:[url host]])
4281 bridged = true;
4282 }
4283
4284 if (bridged)
4285 [window setValue:cydia_ forKey:@"cydia"];
4286}
4287
4288- (void) _setupMail:(MFMailComposeViewController *)controller {
4289 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4290
4291 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4292 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4293}
4294
4295- (NSURL *) URLWithURL:(NSURL *)url {
4296 return [Diversion divertURL:url];
4297}
4298
4299- (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4300 NSURL *url([request URL]);
4301 NSString *host([url host]);
4302
4303 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4304
4305 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4306 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4307 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4308 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4309
4310 bool token;
4311 @synchronized (HostConfig_) {
4312 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4313 }
4314
4315 if ([url isCydiaSecure] && token) {
4316 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4317 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4318 }
4319
4320 return copy;
4321}
4322
4323- (void) setDelegate:(id)delegate {
4324 [super setDelegate:delegate];
4325 [cydia_ setDelegate:delegate];
4326}
4327
4328- (NSString *) applicationNameForUserAgent {
4329 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4330
4331 if (Safari_ != nil)
4332 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4333 if (Build_ != nil)
4334 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4335 if (Product_ != nil)
4336 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4337
4338 return application;
4339}
4340
4341- (id) init {
4342 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4343 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4344 } return self;
4345}
4346
4347@end
4348/* }}} */
4349
4350// CydiaScript {{{
4351@interface NSObject (CydiaScript)
4352- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4353@end
4354
4355@implementation NSObject (CydiaScript)
4356
4357- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4358 return self;
4359}
4360
4361@end
4362
4363@implementation NSArray (CydiaScript)
4364
4365- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4366 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4367 for (size_t i(0), e([self count]); i != e; ++i)
4368 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4369 return object;
4370}
4371
4372@end
4373
4374@implementation NSDictionary (CydiaScript)
4375
4376- (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4377 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4378 for (id i in self)
4379 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4380 return object;
4381}
4382
4383@end
4384// }}}
4385
4386/* Confirmation Controller {{{ */
4387bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4388 if (!iterator.end())
4389 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4390 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4391 continue;
4392 pkgCache::PkgIterator package(dep.TargetPkg());
4393 if (package.end())
4394 continue;
4395 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4396 return true;
4397 }
4398
4399 return false;
4400}
4401
4402@protocol ConfirmationControllerDelegate
4403- (void) cancelAndClear:(bool)clear;
4404- (void) confirmWithNavigationController:(UINavigationController *)navigation;
4405- (void) queue;
4406@end
4407
4408@interface ConfirmationController : CydiaWebViewController {
4409 _transient Database *database_;
4410
4411 _H<UIAlertView> essential_;
4412
4413 _H<NSDictionary> changes_;
4414 _H<NSMutableArray> issues_;
4415 _H<NSDictionary> sizes_;
4416
4417 BOOL substrate_;
4418}
4419
4420- (id) initWithDatabase:(Database *)database;
4421
4422@end
4423
4424@implementation ConfirmationController
4425
4426- (void) complete {
4427 if (substrate_)
4428 RestartSubstrate_ = true;
4429 [delegate_ confirmWithNavigationController:[self navigationController]];
4430}
4431
4432- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4433 NSString *context([alert context]);
4434
4435 if ([context isEqualToString:@"remove"]) {
4436 if (button == [alert cancelButtonIndex])
4437 [self dismissModalViewControllerAnimated:YES];
4438 else if (button == [alert firstOtherButtonIndex]) {
4439 [self complete];
4440 }
4441
4442 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4443 } else if ([context isEqualToString:@"unable"]) {
4444 [self dismissModalViewControllerAnimated:YES];
4445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4446 } else {
4447 [super alertView:alert clickedButtonAtIndex:button];
4448 }
4449}
4450
4451- (void) _doContinue {
4452 [self dismissModalViewControllerAnimated:YES];
4453 [delegate_ cancelAndClear:NO];
4454}
4455
4456- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4457 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4458 return nil;
4459}
4460
4461- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4462 [super webView:view didClearWindowObject:window forFrame:frame];
4463
4464 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4465 (id) changes_, @"changes",
4466 (id) issues_, @"issues",
4467 (id) sizes_, @"sizes",
4468 self, @"queue",
4469 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4470}
4471
4472- (id) initWithDatabase:(Database *)database {
4473 if ((self = [super init]) != nil) {
4474 database_ = database;
4475
4476 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4477 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4478 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4479 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4480 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4481
4482 bool remove(false);
4483
4484 pkgCacheFile &cache([database_ cache]);
4485 NSArray *packages([database_ packages]);
4486 pkgDepCache::Policy *policy([database_ policy]);
4487
4488 issues_ = [NSMutableArray arrayWithCapacity:4];
4489
4490 for (Package *package in packages) {
4491 pkgCache::PkgIterator iterator([package iterator]);
4492 NSString *name([package id]);
4493
4494 if ([package broken]) {
4495 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4496
4497 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4498 name, @"package",
4499 reasons, @"reasons",
4500 nil]];
4501
4502 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4503 if (ver.end())
4504 continue;
4505
4506 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4507 pkgCache::DepIterator start;
4508 pkgCache::DepIterator end;
4509 dep.GlobOr(start, end); // ++dep
4510
4511 if (!cache->IsImportantDep(end))
4512 continue;
4513 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4514 continue;
4515
4516 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4517
4518 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4519 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4520 clauses, @"clauses",
4521 nil]];
4522
4523 _forever {
4524 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4525
4526 pkgCache::PkgIterator target(start.TargetPkg());
4527 if (target->ProvidesList != 0)
4528 reason = @"missing";
4529 else {
4530 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4531 if (!ver.end()) {
4532 reason = @"installed";
4533 installed = [NSString stringWithUTF8String:ver.VerStr()];
4534 } else if (!cache[target].CandidateVerIter(cache).end())
4535 reason = @"uninstalled";
4536 else if (target->ProvidesList == 0)
4537 reason = @"uninstallable";
4538 else
4539 reason = @"virtual";
4540 }
4541
4542 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4543 [NSString stringWithUTF8String:start.CompType()], @"operator",
4544 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4545 nil]);
4546
4547 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4548 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4549 version, @"version",
4550 reason, @"reason",
4551 installed, @"installed",
4552 nil]];
4553
4554 // yes, seriously. (wtf?)
4555 if (start == end)
4556 break;
4557 ++start;
4558 }
4559 }
4560 }
4561
4562 pkgDepCache::StateCache &state(cache[iterator]);
4563
4564 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4565
4566 if (state.NewInstall())
4567 [installs addObject:name];
4568 // XXX: else if (state.Install())
4569 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4570 [reinstalls addObject:name];
4571 // XXX: move before previous if
4572 else if (state.Upgrade())
4573 [upgrades addObject:name];
4574 else if (state.Downgrade())
4575 [downgrades addObject:name];
4576 else if (!state.Delete())
4577 // XXX: _assert(state.Keep());
4578 continue;
4579 else if (special_r(name))
4580 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4581 [NSNull null], @"package",
4582 [NSArray arrayWithObjects:
4583 [NSDictionary dictionaryWithObjectsAndKeys:
4584 @"Conflicts", @"relationship",
4585 [NSArray arrayWithObjects:
4586 [NSDictionary dictionaryWithObjectsAndKeys:
4587 name, @"package",
4588 [NSNull null], @"version",
4589 @"installed", @"reason",
4590 nil],
4591 nil], @"clauses",
4592 nil],
4593 nil], @"reasons",
4594 nil]];
4595 else {
4596 if ([package essential])
4597 remove = true;
4598 [removes addObject:name];
4599 }
4600
4601 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4602 substrate_ |= DepSubstrate(iterator.CurrentVer());
4603 }
4604
4605 if (!remove)
4606 essential_ = nil;
4607 else if (Advanced_) {
4608 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4609
4610 essential_ = [[[UIAlertView alloc]
4611 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4612 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4613 delegate:self
4614 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4615 otherButtonTitles:
4616 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4617 nil
4618 ] autorelease];
4619
4620 [essential_ setContext:@"remove"];
4621 } else {
4622 essential_ = [[[UIAlertView alloc]
4623 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4624 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4625 delegate:self
4626 cancelButtonTitle:UCLocalize("OKAY")
4627 otherButtonTitles:nil
4628 ] autorelease];
4629
4630 [essential_ setContext:@"unable"];
4631 }
4632
4633 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4634 installs, @"installs",
4635 reinstalls, @"reinstalls",
4636 upgrades, @"upgrades",
4637 downgrades, @"downgrades",
4638 removes, @"removes",
4639 nil];
4640
4641 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4642 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4643 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4644 nil];
4645
4646 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4647 } return self;
4648}
4649
4650- (UIBarButtonItem *) leftButton {
4651 return [[[UIBarButtonItem alloc]
4652 initWithTitle:UCLocalize("CANCEL")
4653 style:UIBarButtonItemStylePlain
4654 target:self
4655 action:@selector(cancelButtonClicked)
4656 ] autorelease];
4657}
4658
4659#if !AlwaysReload
4660- (void) applyRightButton {
4661 if ([issues_ count] == 0 && ![self isLoading])
4662 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4663 initWithTitle:UCLocalize("CONFIRM")
4664 style:UIBarButtonItemStyleDone
4665 target:self
4666 action:@selector(confirmButtonClicked)
4667 ] autorelease]];
4668 else
4669 [[self navigationItem] setRightBarButtonItem:nil];
4670}
4671#endif
4672
4673- (void) cancelButtonClicked {
4674 [self dismissModalViewControllerAnimated:YES];
4675 [delegate_ cancelAndClear:YES];
4676}
4677
4678#if !AlwaysReload
4679- (void) confirmButtonClicked {
4680 if (essential_ != nil)
4681 [essential_ show];
4682 else
4683 [self complete];
4684}
4685#endif
4686
4687@end
4688/* }}} */
4689
4690/* Progress Data {{{ */
4691@interface CydiaProgressData : NSObject {
4692 _transient id delegate_;
4693
4694 bool running_;
4695 float percent_;
4696
4697 float current_;
4698 float total_;
4699 float speed_;
4700
4701 _H<NSMutableArray> events_;
4702 _H<NSString> title_;
4703
4704 _H<NSString> status_;
4705 _H<NSString> finish_;
4706}
4707
4708@end
4709
4710@implementation CydiaProgressData
4711
4712+ (NSArray *) _attributeKeys {
4713 return [NSArray arrayWithObjects:
4714 @"current",
4715 @"events",
4716 @"finish",
4717 @"percent",
4718 @"running",
4719 @"speed",
4720 @"title",
4721 @"total",
4722 nil];
4723}
4724
4725- (NSArray *) attributeKeys {
4726 return [[self class] _attributeKeys];
4727}
4728
4729+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4730 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4731}
4732
4733- (id) init {
4734 if ((self = [super init]) != nil) {
4735 events_ = [NSMutableArray arrayWithCapacity:32];
4736 } return self;
4737}
4738
4739- (void) setDelegate:(id)delegate {
4740 delegate_ = delegate;
4741}
4742
4743- (void) setPercent:(float)value {
4744 percent_ = value;
4745}
4746
4747- (NSNumber *) percent {
4748 return [NSNumber numberWithFloat:percent_];
4749}
4750
4751- (void) setCurrent:(float)value {
4752 current_ = value;
4753}
4754
4755- (NSNumber *) current {
4756 return [NSNumber numberWithFloat:current_];
4757}
4758
4759- (void) setTotal:(float)value {
4760 total_ = value;
4761}
4762
4763- (NSNumber *) total {
4764 return [NSNumber numberWithFloat:total_];
4765}
4766
4767- (void) setSpeed:(float)value {
4768 speed_ = value;
4769}
4770
4771- (NSNumber *) speed {
4772 return [NSNumber numberWithFloat:speed_];
4773}
4774
4775- (NSArray *) events {
4776 return events_;
4777}
4778
4779- (void) removeAllEvents {
4780 [events_ removeAllObjects];
4781}
4782
4783- (void) addEvent:(CydiaProgressEvent *)event {
4784 [events_ addObject:event];
4785}
4786
4787- (void) setTitle:(NSString *)text {
4788 title_ = text;
4789}
4790
4791- (NSString *) title {
4792 return title_;
4793}
4794
4795- (void) setFinish:(NSString *)text {
4796 finish_ = text;
4797}
4798
4799- (NSString *) finish {
4800 return (id) finish_ ?: [NSNull null];
4801}
4802
4803- (void) setRunning:(bool)running {
4804 running_ = running;
4805}
4806
4807- (NSNumber *) running {
4808 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4809}
4810
4811@end
4812/* }}} */
4813/* Progress Controller {{{ */
4814@interface ProgressController : CydiaWebViewController <
4815 ProgressDelegate
4816> {
4817 _transient Database *database_;
4818 _H<CydiaProgressData, 1> progress_;
4819 unsigned cancel_;
4820}
4821
4822- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4823
4824- (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4825
4826- (void) setTitle:(NSString *)title;
4827- (void) setCancellable:(bool)cancellable;
4828
4829@end
4830
4831@implementation ProgressController
4832
4833- (void) dealloc {
4834 [database_ setProgressDelegate:nil];
4835 [super dealloc];
4836}
4837
4838- (UIBarButtonItem *) leftButton {
4839 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4840 initWithTitle:UCLocalize("CANCEL")
4841 style:UIBarButtonItemStylePlain
4842 target:self
4843 action:@selector(cancel)
4844 ] autorelease] : nil;
4845}
4846
4847- (void) updateCancel {
4848 [super applyLeftButton];
4849}
4850
4851- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4852 if ((self = [super init]) != nil) {
4853 database_ = database;
4854 delegate_ = delegate;
4855
4856 [database_ setProgressDelegate:self];
4857
4858 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4859 [progress_ setDelegate:self];
4860
4861 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4862
4863 [scroller_ setBackgroundColor:[UIColor blackColor]];
4864
4865 [[self navigationItem] setHidesBackButton:YES];
4866
4867 [self updateCancel];
4868 } return self;
4869}
4870
4871- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4872 [super webView:view didClearWindowObject:window forFrame:frame];
4873 [window setValue:progress_ forKey:@"cydiaProgress"];
4874}
4875
4876- (void) updateProgress {
4877 [self dispatchEvent:@"CydiaProgressUpdate"];
4878}
4879
4880- (void) viewWillAppear:(BOOL)animated {
4881 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4882 [super viewWillAppear:animated];
4883}
4884
4885- (void) close {
4886 UpdateExternalStatus(0);
4887
4888 switch (Finish_) {
4889 case 0:
4890 break;
4891
4892 case 1:
4893 [delegate_ terminateWithSuccess];
4894 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4895 [delegate_ suspendWithAnimation:YES];
4896 else
4897 [delegate_ suspend];*/
4898 break;
4899
4900 case 2:
4901 _trace();
4902 goto reload;
4903
4904 case 3:
4905 _trace();
4906 goto reload;
4907
4908 reload:
4909 system("/usr/bin/sbreload");
4910 _trace();
4911 break;
4912
4913 case 4:
4914 _trace();
4915 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4916 SBReboot(SBSSpringBoardServerPort());
4917 else
4918 reboot2(RB_AUTOBOOT);
4919 break;
4920 }
4921
4922 [super close];
4923}
4924
4925- (void) setTitle:(NSString *)title {
4926 [progress_ setTitle:title];
4927 [self updateProgress];
4928}
4929
4930- (UIBarButtonItem *) rightButton {
4931 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4932 initWithTitle:UCLocalize("CLOSE")
4933 style:UIBarButtonItemStylePlain
4934 target:self
4935 action:@selector(close)
4936 ] autorelease];
4937}
4938
4939- (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4940 UpdateExternalStatus(1);
4941
4942 [progress_ setRunning:true];
4943 [self setTitle:title];
4944 // implicit updateProgress
4945
4946 SHA1SumValue notifyconf; {
4947 FileFd file;
4948 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4949 _error->Discard();
4950 else {
4951 MMap mmap(file, MMap::ReadOnly);
4952 SHA1Summation sha1;
4953 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4954 notifyconf = sha1.Result();
4955 }
4956 }
4957
4958 SHA1SumValue springlist; {
4959 FileFd file;
4960 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4961 _error->Discard();
4962 else {
4963 MMap mmap(file, MMap::ReadOnly);
4964 SHA1Summation sha1;
4965 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4966 springlist = sha1.Result();
4967 }
4968 }
4969
4970 if (invocation != nil) {
4971 [invocation yieldToSelector:@selector(invoke)];
4972 [self setTitle:@"COMPLETE"];
4973 }
4974
4975 if (Finish_ < 4) {
4976 FileFd file;
4977 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4978 _error->Discard();
4979 else {
4980 MMap mmap(file, MMap::ReadOnly);
4981 SHA1Summation sha1;
4982 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4983 if (!(notifyconf == sha1.Result()))
4984 Finish_ = 4;
4985 }
4986 }
4987
4988 if (Finish_ < 3) {
4989 FileFd file;
4990 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4991 _error->Discard();
4992 else {
4993 MMap mmap(file, MMap::ReadOnly);
4994 SHA1Summation sha1;
4995 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4996 if (!(springlist == sha1.Result()))
4997 Finish_ = 3;
4998 }
4999 }
5000
5001 if (Finish_ < 2) {
5002 if (RestartSubstrate_)
5003 Finish_ = 2;
5004 }
5005
5006 RestartSubstrate_ = false;
5007
5008 switch (Finish_) {
5009 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5010 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5011 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5012 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5013 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5014 }
5015
5016 _trace();
5017 system("su -c /usr/bin/uicache mobile");
5018 _trace();
5019
5020 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5021
5022 [progress_ setRunning:false];
5023 [self updateProgress];
5024
5025 [self applyRightButton];
5026}
5027
5028- (void) addProgressEvent:(CydiaProgressEvent *)event {
5029 [progress_ addEvent:event];
5030 [self updateProgress];
5031}
5032
5033- (bool) isProgressCancelled {
5034 return cancel_ == 2;
5035}
5036
5037- (void) cancel {
5038 cancel_ = 2;
5039 [self updateCancel];
5040}
5041
5042- (void) setCancellable:(bool)cancellable {
5043 unsigned cancel(cancel_);
5044
5045 if (!cancellable)
5046 cancel_ = 0;
5047 else if (cancel_ == 0)
5048 cancel_ = 1;
5049
5050 if (cancel != cancel_)
5051 [self updateCancel];
5052}
5053
5054- (void) setProgressCancellable:(NSNumber *)cancellable {
5055 [self setCancellable:[cancellable boolValue]];
5056}
5057
5058- (void) setProgressPercent:(NSNumber *)percent {
5059 [progress_ setPercent:[percent floatValue]];
5060 [self updateProgress];
5061}
5062
5063- (void) setProgressStatus:(NSDictionary *)status {
5064 if (status == nil) {
5065 [progress_ setCurrent:0];
5066 [progress_ setTotal:0];
5067 [progress_ setSpeed:0];
5068 } else {
5069 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5070
5071 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5072 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5073 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5074 }
5075
5076 [self updateProgress];
5077}
5078
5079@end
5080/* }}} */
5081
5082/* Package Cell {{{ */
5083@interface PackageCell : CyteTableViewCell <
5084 CyteTableViewCellDelegate
5085> {
5086 _H<UIImage> icon_;
5087 _H<NSString> name_;
5088 _H<NSString> description_;
5089 bool commercial_;
5090 _H<NSString> source_;
5091 _H<UIImage> badge_;
5092 _H<Package> package_;
5093 _H<UIImage> placard_;
5094 bool summarized_;
5095}
5096
5097- (PackageCell *) init;
5098- (void) setPackage:(Package *)package asSummary:(bool)summary;
5099
5100- (void) drawContentRect:(CGRect)rect;
5101
5102@end
5103
5104@implementation PackageCell
5105
5106- (PackageCell *) init {
5107 CGRect frame(CGRectMake(0, 0, 320, 74));
5108 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5109 UIView *content([self contentView]);
5110 CGRect bounds([content bounds]);
5111
5112 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5113 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5114 [content addSubview:content_];
5115
5116 [content_ setDelegate:self];
5117 [content_ setOpaque:YES];
5118 } return self;
5119}
5120
5121- (NSString *) accessibilityLabel {
5122 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5123}
5124
5125- (void) setPackage:(Package *)package asSummary:(bool)summary {
5126 summarized_ = summary;
5127
5128 icon_ = nil;
5129 name_ = nil;
5130 description_ = nil;
5131 source_ = nil;
5132 badge_ = nil;
5133 placard_ = nil;
5134 package_ = nil;
5135
5136 [package parse];
5137
5138 Source *source = [package source];
5139
5140 icon_ = [package icon];
5141
5142 if (NSString *name = [package name])
5143 name_ = [NSString stringWithString:name];
5144
5145 NSString *description(nil);
5146
5147 if (description == nil && IsWildcat_)
5148 description = [package longDescription];
5149 if (description == nil)
5150 description = [package shortDescription];
5151
5152 if (description != nil)
5153 description_ = [NSString stringWithString:description];
5154
5155 commercial_ = [package isCommercial];
5156
5157 package_ = package;
5158
5159 NSString *label = nil;
5160 bool trusted = false;
5161
5162 if (source != nil) {
5163 label = [source label];
5164 trusted = [source trusted];
5165 } else if ([[package id] isEqualToString:@"firmware"])
5166 label = UCLocalize("APPLE");
5167 else
5168 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5169
5170 NSString *from(label);
5171
5172 NSString *section = [package simpleSection];
5173 if (section != nil && ![section isEqualToString:label]) {
5174 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5175 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5176 }
5177
5178 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5179
5180 if (NSString *purpose = [package primaryPurpose])
5181 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5182
5183 UIColor *color;
5184 NSString *placard;
5185
5186 if (NSString *mode = [package_ mode]) {
5187 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5188 color = RemovingColor_;
5189 //placard = @"removing";
5190 } else {
5191 color = InstallingColor_;
5192 //placard = @"installing";
5193 }
5194
5195 // XXX: the removing/installing placards are not @2x
5196 placard = nil;
5197 } else {
5198 color = [UIColor whiteColor];
5199
5200 if ([package installed] != nil)
5201 placard = @"installed";
5202 else
5203 placard = nil;
5204 }
5205
5206 [content_ setBackgroundColor:color];
5207
5208 if (placard != nil)
5209 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5210
5211 [self setNeedsDisplay];
5212 [content_ setNeedsDisplay];
5213}
5214
5215- (void) drawSummaryContentRect:(CGRect)rect {
5216 bool highlighted(highlighted_);
5217 float width([self bounds].size.width);
5218
5219 if (icon_ != nil) {
5220 CGRect rect;
5221 rect.size = [(UIImage *) icon_ size];
5222
5223 rect.size.width /= 4;
5224 rect.size.height /= 4;
5225
5226 rect.origin.x = 14 - rect.size.width / 4;
5227 rect.origin.y = 14 - rect.size.height / 4;
5228
5229 [icon_ drawInRect:rect];
5230 }
5231
5232 if (badge_ != nil) {
5233 CGRect rect;
5234 rect.size = [(UIImage *) badge_ size];
5235
5236 rect.size.width /= 4;
5237 rect.size.height /= 4;
5238
5239 rect.origin.x = 20 - rect.size.width / 4;
5240 rect.origin.y = 20 - rect.size.height / 4;
5241
5242 [badge_ drawInRect:rect];
5243 }
5244
5245 if (highlighted)
5246 UISetColor(White_);
5247
5248 if (!highlighted)
5249 UISetColor(commercial_ ? Purple_ : Black_);
5250 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5251
5252 if (placard_ != nil)
5253 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5254}
5255
5256- (void) drawNormalContentRect:(CGRect)rect {
5257 bool highlighted(highlighted_);
5258 float width([self bounds].size.width);
5259
5260 if (icon_ != nil) {
5261 CGRect rect;
5262 rect.size = [(UIImage *) icon_ size];
5263
5264 rect.size.width /= 2;
5265 rect.size.height /= 2;
5266
5267 rect.origin.x = 25 - rect.size.width / 2;
5268 rect.origin.y = 25 - rect.size.height / 2;
5269
5270 [icon_ drawInRect:rect];
5271 }
5272
5273 if (badge_ != nil) {
5274 CGRect rect;
5275 rect.size = [(UIImage *) badge_ size];
5276
5277 rect.size.width /= 2;
5278 rect.size.height /= 2;
5279
5280 rect.origin.x = 36 - rect.size.width / 2;
5281 rect.origin.y = 36 - rect.size.height / 2;
5282
5283 [badge_ drawInRect:rect];
5284 }
5285
5286 if (highlighted)
5287 UISetColor(White_);
5288
5289 if (!highlighted)
5290 UISetColor(commercial_ ? Purple_ : Black_);
5291 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5292 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5293
5294 if (!highlighted)
5295 UISetColor(commercial_ ? Purplish_ : Gray_);
5296 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5297
5298 if (placard_ != nil)
5299 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5300}
5301
5302- (void) drawContentRect:(CGRect)rect {
5303 if (summarized_)
5304 [self drawSummaryContentRect:rect];
5305 else
5306 [self drawNormalContentRect:rect];
5307}
5308
5309@end
5310/* }}} */
5311/* Section Cell {{{ */
5312@interface SectionCell : CyteTableViewCell <
5313 CyteTableViewCellDelegate
5314> {
5315 _H<NSString> basic_;
5316 _H<NSString> section_;
5317 _H<NSString> name_;
5318 _H<NSString> count_;
5319 _H<UIImage> icon_;
5320 _H<UISwitch> switch_;
5321 BOOL editing_;
5322}
5323
5324- (void) setSection:(Section *)section editing:(BOOL)editing;
5325
5326@end
5327
5328@implementation SectionCell
5329
5330- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5331 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5332 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5333 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5334 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5335
5336 UIView *content([self contentView]);
5337 CGRect bounds([content bounds]);
5338
5339 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5340 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5341 [content addSubview:content_];
5342 [content_ setBackgroundColor:[UIColor whiteColor]];
5343
5344 [content_ setDelegate:self];
5345 } return self;
5346}
5347
5348- (void) onSwitch:(id)sender {
5349 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5350 if (metadata == nil) {
5351 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5352 [Sections_ setObject:metadata forKey:basic_];
5353 }
5354
5355 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5356 Changed_ = true;
5357}
5358
5359- (void) setSection:(Section *)section editing:(BOOL)editing {
5360 if (editing != editing_) {
5361 if (editing_)
5362 [switch_ removeFromSuperview];
5363 else
5364 [self addSubview:switch_];
5365 editing_ = editing;
5366 }
5367
5368 basic_ = nil;
5369 section_ = nil;
5370 name_ = nil;
5371 count_ = nil;
5372
5373 if (section == nil) {
5374 name_ = UCLocalize("ALL_PACKAGES");
5375 count_ = nil;
5376 } else {
5377 basic_ = [section name];
5378 section_ = [section localized];
5379
5380 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5381 count_ = [NSString stringWithFormat:@"%d", [section count]];
5382
5383 if (editing_)
5384 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5385 }
5386
5387 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5388 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5389
5390 [content_ setNeedsDisplay];
5391}
5392
5393- (void) setFrame:(CGRect)frame {
5394 [super setFrame:frame];
5395
5396 CGRect rect([switch_ frame]);
5397 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5398}
5399
5400- (NSString *) accessibilityLabel {
5401 return name_;
5402}
5403
5404- (void) drawContentRect:(CGRect)rect {
5405 bool highlighted(highlighted_ && !editing_);
5406
5407 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5408
5409 if (highlighted)
5410 UISetColor(White_);
5411
5412 float width(rect.size.width);
5413 if (editing_)
5414 width -= 87;
5415
5416 if (!highlighted)
5417 UISetColor(Black_);
5418 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5419
5420 CGSize size = [count_ sizeWithFont:Font14_];
5421
5422 UISetColor(White_);
5423 if (count_ != nil)
5424 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5425}
5426
5427@end
5428/* }}} */
5429
5430/* File Table {{{ */
5431@interface FileTable : CyteViewController <
5432 UITableViewDataSource,
5433 UITableViewDelegate
5434> {
5435 _transient Database *database_;
5436 _H<Package> package_;
5437 _H<NSString> name_;
5438 _H<NSMutableArray> files_;
5439 _H<UITableView, 2> list_;
5440}
5441
5442- (id) initWithDatabase:(Database *)database;
5443- (void) setPackage:(Package *)package;
5444
5445@end
5446
5447@implementation FileTable
5448
5449- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5450 return files_ == nil ? 0 : [files_ count];
5451}
5452
5453/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5454 return 24.0f;
5455}*/
5456
5457- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5458 static NSString *reuseIdentifier = @"Cell";
5459
5460 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5461 if (cell == nil) {
5462 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5463 [cell setFont:[UIFont systemFontOfSize:16]];
5464 }
5465 [cell setText:[files_ objectAtIndex:indexPath.row]];
5466 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5467
5468 return cell;
5469}
5470
5471- (NSURL *) navigationURL {
5472 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5473}
5474
5475- (void) loadView {
5476 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5477
5478 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5479 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5480 [list_ setRowHeight:24.0f];
5481 [(UITableView *) list_ setDataSource:self];
5482 [list_ setDelegate:self];
5483 [[self view] addSubview:list_];
5484}
5485
5486- (void) viewDidLoad {
5487 [super viewDidLoad];
5488
5489 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5490}
5491
5492- (void) releaseSubviews {
5493 list_ = nil;
5494
5495 [super releaseSubviews];
5496}
5497
5498- (id) initWithDatabase:(Database *)database {
5499 if ((self = [super init]) != nil) {
5500 database_ = database;
5501
5502 files_ = [NSMutableArray arrayWithCapacity:32];
5503 } return self;
5504}
5505
5506- (void) setPackage:(Package *)package {
5507 package_ = nil;
5508 name_ = nil;
5509
5510 [files_ removeAllObjects];
5511
5512 if (package != nil) {
5513 package_ = package;
5514 name_ = [package id];
5515
5516 if (NSArray *files = [package files])
5517 [files_ addObjectsFromArray:files];
5518
5519 if ([files_ count] != 0) {
5520 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5521 [files_ removeObjectAtIndex:0];
5522 [files_ sortUsingSelector:@selector(compareByPath:)];
5523
5524 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5525 [stack addObject:@"/"];
5526
5527 for (int i(0), e([files_ count]); i != e; ++i) {
5528 NSString *file = [files_ objectAtIndex:i];
5529 while (![file hasPrefix:[stack lastObject]])
5530 [stack removeLastObject];
5531 NSString *directory = [stack lastObject];
5532 [stack addObject:[file stringByAppendingString:@"/"]];
5533 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5534 ([stack count] - 2) * 3, "",
5535 [file substringFromIndex:[directory length]]
5536 ]];
5537 }
5538 }
5539 }
5540
5541 [list_ reloadData];
5542}
5543
5544- (void) reloadData {
5545 [super reloadData];
5546
5547 [self setPackage:[database_ packageWithName:name_]];
5548}
5549
5550@end
5551/* }}} */
5552/* Package Controller {{{ */
5553@interface CYPackageController : CydiaWebViewController <
5554 UIActionSheetDelegate
5555> {
5556 _transient Database *database_;
5557 _H<Package> package_;
5558 _H<NSString> name_;
5559 bool commercial_;
5560 _H<NSMutableArray> buttons_;
5561 _H<UIBarButtonItem> button_;
5562}
5563
5564- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5565
5566@end
5567
5568@implementation CYPackageController
5569
5570- (NSURL *) navigationURL {
5571 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5572}
5573
5574/* XXX: this is not safe at all... localization of /fail/ */
5575- (void) _clickButtonWithName:(NSString *)name {
5576 if ([name isEqualToString:UCLocalize("CLEAR")])
5577 [delegate_ clearPackage:package_];
5578 else if ([name isEqualToString:UCLocalize("INSTALL")])
5579 [delegate_ installPackage:package_];
5580 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5581 [delegate_ installPackage:package_];
5582 else if ([name isEqualToString:UCLocalize("REMOVE")])
5583 [delegate_ removePackage:package_];
5584 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5585 [delegate_ installPackage:package_];
5586 else _assert(false);
5587}
5588
5589- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5590 NSString *context([sheet context]);
5591
5592 if ([context isEqualToString:@"modify"]) {
5593 if (button != [sheet cancelButtonIndex]) {
5594 NSString *buttonName = [buttons_ objectAtIndex:button];
5595 [self _clickButtonWithName:buttonName];
5596 }
5597
5598 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5599 }
5600}
5601
5602- (bool) _allowJavaScriptPanel {
5603 return commercial_;
5604}
5605
5606#if !AlwaysReload
5607- (void) _customButtonClicked {
5608 int count([buttons_ count]);
5609 if (count == 0)
5610 return;
5611
5612 if (count == 1)
5613 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5614 else {
5615 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5616 [buttons addObjectsFromArray:buttons_];
5617
5618 UIActionSheet *sheet = [[[UIActionSheet alloc]
5619 initWithTitle:nil
5620 delegate:self
5621 cancelButtonTitle:nil
5622 destructiveButtonTitle:nil
5623 otherButtonTitles:nil
5624 ] autorelease];
5625
5626 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5627 if (!IsWildcat_) {
5628 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5629 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5630 }
5631 [sheet setContext:@"modify"];
5632
5633 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5634 }
5635}
5636
5637// We don't want to allow non-commercial packages to do custom things to the install button,
5638// so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5639- (void) customButtonClicked {
5640 if (commercial_)
5641 [super customButtonClicked];
5642 else
5643 [self _customButtonClicked];
5644}
5645
5646- (void) reloadButtonClicked {
5647 // Don't reload a commerical package by tapping the loading button,
5648 // but if it's not an Install button, we should forward it on.
5649 if (![package_ uninstalled])
5650 [self _customButtonClicked];
5651}
5652
5653- (void) applyLoadingTitle {
5654 // Don't show "Loading" as the title. Ever.
5655}
5656
5657- (UIBarButtonItem *) rightButton {
5658 return button_;
5659}
5660#endif
5661
5662- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5663 if ((self = [super init]) != nil) {
5664 database_ = database;
5665 buttons_ = [NSMutableArray arrayWithCapacity:4];
5666 name_ = [NSString stringWithString:name];
5667 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5668 } return self;
5669}
5670
5671- (void) reloadData {
5672 [super reloadData];
5673
5674 package_ = [database_ packageWithName:name_];
5675
5676 [buttons_ removeAllObjects];
5677
5678 if (package_ != nil) {
5679 [(Package *) package_ parse];
5680
5681 commercial_ = [package_ isCommercial];
5682
5683 if ([package_ mode] != nil)
5684 [buttons_ addObject:UCLocalize("CLEAR")];
5685 if ([package_ source] == nil);
5686 else if ([package_ upgradableAndEssential:NO])
5687 [buttons_ addObject:UCLocalize("UPGRADE")];
5688 else if ([package_ uninstalled])
5689 [buttons_ addObject:UCLocalize("INSTALL")];
5690 else
5691 [buttons_ addObject:UCLocalize("REINSTALL")];
5692 if (![package_ uninstalled])
5693 [buttons_ addObject:UCLocalize("REMOVE")];
5694 }
5695
5696 NSString *title;
5697 switch ([buttons_ count]) {
5698 case 0: title = nil; break;
5699 case 1: title = [buttons_ objectAtIndex:0]; break;
5700 default: title = UCLocalize("MODIFY"); break;
5701 }
5702
5703 button_ = [[[UIBarButtonItem alloc]
5704 initWithTitle:title
5705 style:UIBarButtonItemStylePlain
5706 target:self
5707 action:@selector(customButtonClicked)
5708 ] autorelease];
5709}
5710
5711- (bool) isLoading {
5712 return commercial_ ? [super isLoading] : false;
5713}
5714
5715@end
5716/* }}} */
5717
5718/* Package List Controller {{{ */
5719@interface PackageListController : CyteViewController <
5720 UITableViewDataSource,
5721 UITableViewDelegate
5722> {
5723 _transient Database *database_;
5724 unsigned era_;
5725 _H<NSArray> packages_;
5726 _H<NSMutableArray> sections_;
5727 _H<UITableView, 2> list_;
5728 _H<NSMutableArray> index_;
5729 _H<NSMutableDictionary> indices_;
5730 _H<NSString> title_;
5731 unsigned reloading_;
5732}
5733
5734- (id) initWithDatabase:(Database *)database title:(NSString *)title;
5735- (void) setDelegate:(id)delegate;
5736- (void) resetCursor;
5737- (void) clearData;
5738
5739@end
5740
5741@implementation PackageListController
5742
5743- (bool) isSummarized {
5744 return false;
5745}
5746
5747- (bool) showsSections {
5748 return true;
5749}
5750
5751- (void) deselectWithAnimation:(BOOL)animated {
5752 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5753}
5754
5755- (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5756 CGRect base = [[self view] bounds];
5757 base.size.height -= bounds.size.height;
5758 base.origin = [list_ frame].origin;
5759
5760 [UIView beginAnimations:nil context:NULL];
5761 [UIView setAnimationBeginsFromCurrentState:YES];
5762 [UIView setAnimationCurve:curve];
5763 [UIView setAnimationDuration:duration];
5764 [list_ setFrame:base];
5765 [UIView commitAnimations];
5766}
5767
5768- (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5769 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5770}
5771
5772- (void) resizeForKeyboardBounds:(CGRect)bounds {
5773 [self resizeForKeyboardBounds:bounds duration:0];
5774}
5775
5776- (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5777 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5778 *curve = UIViewAnimationCurveEaseInOut;
5779 else
5780 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5781
5782 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5783 *duration = 0.3;
5784 else
5785 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5786}
5787
5788- (void) keyboardWillShow:(NSNotification *)notification {
5789 CGRect bounds;
5790 CGPoint center;
5791 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5792 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
5793
5794 NSTimeInterval duration;
5795 UIViewAnimationCurve curve;
5796 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5797
5798 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);
5799 UIViewController *base = self;
5800 while ([base parentViewController] != nil)
5801 base = [base parentViewController];
5802 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5803 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5804
5805 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5806 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5807
5808 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5809}
5810
5811- (void) keyboardWillHide:(NSNotification *)notification {
5812 NSTimeInterval duration;
5813 UIViewAnimationCurve curve;
5814 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5815
5816 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5817}
5818
5819- (void) viewWillAppear:(BOOL)animated {
5820 [super viewWillAppear:animated];
5821
5822 [self resizeForKeyboardBounds:CGRectZero];
5823 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5824 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5825}
5826
5827- (void) viewWillDisappear:(BOOL)animated {
5828 [super viewWillDisappear:animated];
5829
5830 [self resizeForKeyboardBounds:CGRectZero];
5831 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5832 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5833}
5834
5835- (void) viewDidAppear:(BOOL)animated {
5836 [super viewDidAppear:animated];
5837 [self deselectWithAnimation:animated];
5838}
5839
5840- (void) didSelectPackage:(Package *)package {
5841 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5842 [view setDelegate:delegate_];
5843 [[self navigationController] pushViewController:view animated:YES];
5844}
5845
5846#if TryIndexedCollation
5847+ (BOOL) hasIndexedCollation {
5848 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5849}
5850#endif
5851
5852- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5853 NSInteger count([sections_ count]);
5854 return count == 0 ? 1 : count;
5855}
5856
5857- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5858 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5859 return nil;
5860 return [[sections_ objectAtIndex:section] name];
5861}
5862
5863- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5864 if ([sections_ count] == 0)
5865 return 0;
5866 return [[sections_ objectAtIndex:section] count];
5867}
5868
5869- (Package *) packageAtIndexPath:(NSIndexPath *)path {
5870@synchronized (database_) {
5871 if ([database_ era] != era_)
5872 return nil;
5873
5874 Section *section([sections_ objectAtIndex:[path section]]);
5875 NSInteger row([path row]);
5876 Package *package([packages_ objectAtIndex:([section row] + row)]);
5877 return [[package retain] autorelease];
5878} }
5879
5880- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5881 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5882 if (cell == nil)
5883 cell = [[[PackageCell alloc] init] autorelease];
5884 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5885 return cell;
5886}
5887
5888- (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5889 Package *package([self packageAtIndexPath:path]);
5890 package = [database_ packageWithName:[package id]];
5891 [self didSelectPackage:package];
5892}
5893
5894- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5895 if ([self showsSections])
5896 return nil;
5897
5898 return index_;
5899}
5900
5901- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5902#if TryIndexedCollation
5903 if ([[self class] hasIndexedCollation]) {
5904 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5905 }
5906#endif
5907
5908 return index;
5909}
5910
5911- (void) updateHeight {
5912 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5913}
5914
5915- (id) initWithDatabase:(Database *)database title:(NSString *)title {
5916 if ((self = [super init]) != nil) {
5917 database_ = database;
5918 title_ = [title copy];
5919 [[self navigationItem] setTitle:title_];
5920
5921#if TryIndexedCollation
5922 if ([[self class] hasIndexedCollation])
5923 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5924 else
5925#endif
5926 index_ = [NSMutableArray arrayWithCapacity:32];
5927
5928 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5929
5930 packages_ = [NSArray array];
5931 sections_ = [NSMutableArray arrayWithCapacity:16];
5932 } return self;
5933}
5934
5935- (void) loadView {
5936 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5937
5938 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5939 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5940 [[self view] addSubview:list_];
5941
5942 // XXX: is 20 the most optimal number here?
5943 [list_ setSectionIndexMinimumDisplayRowCount:20];
5944
5945 [(UITableView *) list_ setDataSource:self];
5946 [list_ setDelegate:self];
5947
5948 [self updateHeight];
5949}
5950
5951- (void) releaseSubviews {
5952 list_ = nil;
5953
5954 [super releaseSubviews];
5955}
5956
5957- (void) setDelegate:(id)delegate {
5958 delegate_ = delegate;
5959}
5960
5961- (bool) shouldYield {
5962 return false;
5963}
5964
5965- (bool) shouldBlock {
5966 return false;
5967}
5968
5969- (NSMutableArray *) _reloadPackages {
5970@synchronized (database_) {
5971 era_ = [database_ era];
5972 NSArray *packages([database_ packages]);
5973
5974 return [NSMutableArray arrayWithArray:packages];
5975} }
5976
5977- (void) _reloadData {
5978 if (reloading_ != 0) {
5979 reloading_ = 2;
5980 return;
5981 }
5982
5983 NSArray *packages;
5984
5985 if ([self shouldYield]) {
5986 do {
5987 UIProgressHUD *hud;
5988
5989 if (![self shouldBlock])
5990 hud = nil;
5991 else {
5992 hud = [delegate_ addProgressHUD];
5993 [hud setText:UCLocalize("LOADING")];
5994 }
5995
5996 reloading_ = 1;
5997 packages = [self yieldToSelector:@selector(_reloadPackages)];
5998
5999 if (hud != nil)
6000 [delegate_ removeProgressHUD:hud];
6001 } while (reloading_ == 2);
6002
6003 reloading_ = 0;
6004 } else {
6005 packages = [self _reloadPackages];
6006 }
6007
6008 packages_ = packages;
6009
6010 [indices_ removeAllObjects];
6011 [sections_ removeAllObjects];
6012
6013 Section *section = nil;
6014
6015#if TryIndexedCollation
6016 if ([[self class] hasIndexedCollation]) {
6017 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6018 NSArray *titles = [collation sectionIndexTitles];
6019 int secidx = -1;
6020
6021 _profile(PackageTable$reloadData$Section)
6022 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6023 Package *package;
6024 int index;
6025
6026 _profile(PackageTable$reloadData$Section$Package)
6027 package = [packages_ objectAtIndex:offset];
6028 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6029 _end
6030
6031 while (secidx < index) {
6032 secidx += 1;
6033
6034 _profile(PackageTable$reloadData$Section$Allocate)
6035 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6036 _end
6037
6038 _profile(PackageTable$reloadData$Section$Add)
6039 [sections_ addObject:section];
6040 _end
6041 }
6042
6043 [section addToCount];
6044 }
6045 _end
6046 } else
6047#endif
6048 {
6049 [index_ removeAllObjects];
6050
6051 bool sectioned([self showsSections]);
6052 if (!sectioned) {
6053 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6054 [sections_ addObject:section];
6055 }
6056
6057 _profile(PackageTable$reloadData$Section)
6058 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6059 Package *package;
6060 unichar index;
6061
6062 _profile(PackageTable$reloadData$Section$Package)
6063 package = [packages_ objectAtIndex:offset];
6064 index = [package index];
6065 _end
6066
6067 if (sectioned && (section == nil || [section index] != index)) {
6068 _profile(PackageTable$reloadData$Section$Allocate)
6069 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6070 _end
6071
6072 [index_ addObject:[section name]];
6073 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6074
6075 _profile(PackageTable$reloadData$Section$Add)
6076 [sections_ addObject:section];
6077 _end
6078 }
6079
6080 [section addToCount];
6081 }
6082 _end
6083 }
6084
6085 [self updateHeight];
6086
6087 _profile(PackageTable$reloadData$List)
6088 [(UITableView *) list_ setDataSource:self];
6089 [list_ reloadData];
6090 _end
6091}
6092
6093- (void) reloadData {
6094 [super reloadData];
6095 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6096}
6097
6098- (void) resetCursor {
6099 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6100}
6101
6102- (void) clearData {
6103 [self updateHeight];
6104
6105 [list_ setDataSource:nil];
6106 [list_ reloadData];
6107
6108 [self resetCursor];
6109}
6110
6111@end
6112/* }}} */
6113/* Filtered Package List Controller {{{ */
6114@interface FilteredPackageListController : PackageListController {
6115 SEL filter_;
6116 IMP imp_;
6117 _H<NSObject> object_;
6118}
6119
6120- (void) setObject:(id)object;
6121- (void) setObject:(id)object forFilter:(SEL)filter;
6122
6123- (SEL) filter;
6124- (void) setFilter:(SEL)filter;
6125
6126- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6127
6128@end
6129
6130@implementation FilteredPackageListController
6131
6132- (SEL) filter {
6133 return filter_;
6134}
6135
6136- (void) setFilter:(SEL)filter {
6137@synchronized (self) {
6138 filter_ = filter;
6139
6140 /* XXX: this is an unsafe optimization of doomy hell */
6141 Method method(class_getInstanceMethod([Package class], filter));
6142 _assert(method != NULL);
6143 imp_ = method_getImplementation(method);
6144 _assert(imp_ != NULL);
6145} }
6146
6147- (void) setObject:(id)object {
6148@synchronized (self) {
6149 object_ = object;
6150} }
6151
6152- (void) setObject:(id)object forFilter:(SEL)filter {
6153@synchronized (self) {
6154 [self setFilter:filter];
6155 [self setObject:object];
6156} }
6157
6158- (NSMutableArray *) _reloadPackages {
6159@synchronized (database_) {
6160 era_ = [database_ era];
6161 NSArray *packages([database_ packages]);
6162
6163 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6164
6165 IMP imp;
6166 SEL filter;
6167 _H<NSObject> object;
6168
6169 @synchronized (self) {
6170 imp = imp_;
6171 filter = filter_;
6172 object = object_;
6173 }
6174
6175 _profile(PackageTable$reloadData$Filter)
6176 for (Package *package in packages)
6177 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6178 [filtered addObject:package];
6179 _end
6180
6181 return filtered;
6182} }
6183
6184- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6185 if ((self = [super initWithDatabase:database title:title]) != nil) {
6186 [self setFilter:filter];
6187 [self setObject:object];
6188 } return self;
6189}
6190
6191@end
6192/* }}} */
6193
6194/* Home Controller {{{ */
6195@interface HomeController : CydiaWebViewController {
6196}
6197
6198@end
6199
6200@implementation HomeController
6201
6202- (id) init {
6203 if ((self = [super init]) != nil) {
6204 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6205 [self reloadData];
6206 } return self;
6207}
6208
6209- (NSURL *) navigationURL {
6210 return [NSURL URLWithString:@"cydia://home"];
6211}
6212
6213- (void) aboutButtonClicked {
6214 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6215
6216 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6217 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6218 [alert setCancelButtonIndex:0];
6219
6220 [alert setMessage:
6221 @"Copyright \u00a9 2008-2011\n"
6222 "SaurikIT, LLC\n"
6223 "\n"
6224 "Jay Freeman (saurik)\n"
6225 "saurik@saurik.com\n"
6226 "http://www.saurik.com/"
6227 ];
6228
6229 [alert show];
6230}
6231
6232- (UIBarButtonItem *) leftButton {
6233 return [[[UIBarButtonItem alloc]
6234 initWithTitle:UCLocalize("ABOUT")
6235 style:UIBarButtonItemStylePlain
6236 target:self
6237 action:@selector(aboutButtonClicked)
6238 ] autorelease];
6239}
6240
6241@end
6242/* }}} */
6243/* Manage Controller {{{ */
6244@interface ManageController : CydiaWebViewController {
6245}
6246
6247- (void) queueStatusDidChange;
6248
6249@end
6250
6251@implementation ManageController
6252
6253- (id) init {
6254 if ((self = [super init]) != nil) {
6255 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6256 } return self;
6257}
6258
6259- (NSURL *) navigationURL {
6260 return [NSURL URLWithString:@"cydia://manage"];
6261}
6262
6263- (UIBarButtonItem *) leftButton {
6264 return [[[UIBarButtonItem alloc]
6265 initWithTitle:UCLocalize("SETTINGS")
6266 style:UIBarButtonItemStylePlain
6267 target:self
6268 action:@selector(settingsButtonClicked)
6269 ] autorelease];
6270}
6271
6272- (void) settingsButtonClicked {
6273 [delegate_ showSettings];
6274}
6275
6276- (void) queueButtonClicked {
6277 [delegate_ queue];
6278}
6279
6280- (UIBarButtonItem *) customButton {
6281 return Queuing_ ? [[[UIBarButtonItem alloc]
6282 initWithTitle:UCLocalize("QUEUE")
6283 style:UIBarButtonItemStyleDone
6284 target:self
6285 action:@selector(queueButtonClicked)
6286 ] autorelease] : [super customButton];
6287}
6288
6289- (void) queueStatusDidChange {
6290 [self applyRightButton];
6291}
6292
6293- (bool) isLoading {
6294 return !Queuing_ && [super isLoading];
6295}
6296
6297@end
6298/* }}} */
6299
6300/* Refresh Bar {{{ */
6301@interface RefreshBar : UINavigationBar {
6302 _H<UIProgressIndicator> indicator_;
6303 _H<UITextLabel> prompt_;
6304 _H<UIProgressBar> progress_;
6305 _H<UINavigationButton> cancel_;
6306}
6307
6308@end
6309
6310@implementation RefreshBar
6311
6312- (void) positionViews {
6313 CGRect frame = [cancel_ frame];
6314 frame.size = [cancel_ sizeThatFits:frame.size];
6315 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6316 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6317 [cancel_ setFrame:frame];
6318
6319 CGSize prgsize = {75, 100};
6320 CGRect prgrect = {{
6321 [self frame].size.width - prgsize.width - 10,
6322 ([self frame].size.height - prgsize.height) / 2
6323 } , prgsize};
6324 [progress_ setFrame:prgrect];
6325
6326 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6327 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6328 CGRect indrect = {{indoffset, indoffset}, indsize};
6329 [indicator_ setFrame:indrect];
6330
6331 CGSize prmsize = {215, indsize.height + 4};
6332 CGRect prmrect = {{
6333 indoffset * 2 + indsize.width,
6334 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6335 }, prmsize};
6336 [prompt_ setFrame:prmrect];
6337}
6338
6339- (void) setFrame:(CGRect)frame {
6340 [super setFrame:frame];
6341 [self positionViews];
6342}
6343
6344- (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6345 if ((self = [super initWithFrame:frame]) != nil) {
6346 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6347
6348 [self setBarStyle:UIBarStyleBlack];
6349
6350 UIBarStyle barstyle([self _barStyle:NO]);
6351 bool ugly(barstyle == UIBarStyleDefault);
6352
6353 UIProgressIndicatorStyle style = ugly ?
6354 UIProgressIndicatorStyleMediumBrown :
6355 UIProgressIndicatorStyleMediumWhite;
6356
6357 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6358 [(UIProgressIndicator *) indicator_ setStyle:style];
6359 [indicator_ startAnimation];
6360 [self addSubview:indicator_];
6361
6362 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6363 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6364 [prompt_ setBackgroundColor:[UIColor clearColor]];
6365 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6366 [self addSubview:prompt_];
6367
6368 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6369 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6370 [(UIProgressBar *) progress_ setStyle:0];
6371 [self addSubview:progress_];
6372
6373 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6374 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6375 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6376 [cancel_ setBarStyle:barstyle];
6377
6378 [self positionViews];
6379 } return self;
6380}
6381
6382- (void) setCancellable:(bool)cancellable {
6383 if (cancellable)
6384 [self addSubview:cancel_];
6385 else
6386 [cancel_ removeFromSuperview];
6387}
6388
6389- (void) start {
6390 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6391 [progress_ setProgress:0];
6392}
6393
6394- (void) stop {
6395 [self setCancellable:NO];
6396}
6397
6398- (void) setPrompt:(NSString *)prompt {
6399 [prompt_ setText:prompt];
6400}
6401
6402- (void) setProgress:(float)progress {
6403 [progress_ setProgress:progress];
6404}
6405
6406@end
6407/* }}} */
6408
6409/* Cydia Navigation Controller Interface {{{ */
6410@interface UINavigationController (Cydia)
6411
6412- (NSArray *) navigationURLCollection;
6413- (void) unloadData;
6414
6415@end
6416/* }}} */
6417
6418/* Cydia Tab Bar Controller {{{ */
6419@interface CYTabBarController : UITabBarController <
6420 UITabBarControllerDelegate,
6421 ProgressDelegate
6422> {
6423 _transient Database *database_;
6424 _H<RefreshBar, 1> refreshbar_;
6425
6426 bool dropped_;
6427 bool updating_;
6428 // XXX: ok, "updatedelegate_"?...
6429 _transient NSObject<CydiaDelegate> *updatedelegate_;
6430
6431 _H<UIViewController> remembered_;
6432 _transient UIViewController *transient_;
6433}
6434
6435- (NSArray *) navigationURLCollection;
6436- (void) dropBar:(BOOL)animated;
6437- (void) beginUpdate;
6438- (void) raiseBar:(BOOL)animated;
6439- (BOOL) updating;
6440- (void) unloadData;
6441
6442@end
6443
6444@implementation CYTabBarController
6445
6446- (void) setUnselectedViewController:(UIViewController *)transient {
6447 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6448 if (transient != nil) {
6449 if (transient_ == nil)
6450 remembered_ = [controllers objectAtIndex:0];
6451 transient_ = transient;
6452 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6453 [controllers replaceObjectAtIndex:0 withObject:transient_];
6454 [self setSelectedIndex:0];
6455 [self setViewControllers:controllers];
6456 [self concealTabBarSelection];
6457 } else if (remembered_ != nil) {
6458 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6459 transient_ = transient;
6460 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6461 remembered_ = nil;
6462 [self setViewControllers:controllers];
6463 [self revealTabBarSelection];
6464 }
6465}
6466
6467- (UIViewController *) unselectedViewController {
6468 return transient_;
6469}
6470
6471- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6472 if ([self unselectedViewController])
6473 [self setUnselectedViewController:nil];
6474}
6475
6476- (NSArray *) navigationURLCollection {
6477 NSMutableArray *items([NSMutableArray array]);
6478
6479 // XXX: Should this deal with transient view controllers?
6480 for (id navigation in [self viewControllers]) {
6481 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6482 if (stack != nil)
6483 [items addObject:stack];
6484 }
6485
6486 return items;
6487}
6488
6489- (void) unloadData {
6490 [super unloadData];
6491
6492 for (UINavigationController *controller in [self viewControllers])
6493 [controller unloadData];
6494
6495 if (UIViewController *selected = [self selectedViewController])
6496 [selected reloadData];
6497
6498 if (UIViewController *unselected = [self unselectedViewController]) {
6499 [unselected unloadData];
6500 [unselected reloadData];
6501 }
6502}
6503
6504- (void) dealloc {
6505 [[NSNotificationCenter defaultCenter] removeObserver:self];
6506
6507 [super dealloc];
6508}
6509
6510- (id) initWithDatabase:(Database *)database {
6511 if ((self = [super init]) != nil) {
6512 database_ = database;
6513 [self setDelegate:self];
6514
6515 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6516 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6517
6518 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6519 } return self;
6520}
6521
6522- (void) setUpdate:(NSDate *)date {
6523 [self beginUpdate];
6524}
6525
6526- (void) beginUpdate {
6527 [(RefreshBar *) refreshbar_ start];
6528 [self dropBar:YES];
6529
6530 [updatedelegate_ retainNetworkActivityIndicator];
6531 updating_ = true;
6532
6533 [NSThread
6534 detachNewThreadSelector:@selector(performUpdate)
6535 toTarget:self
6536 withObject:nil
6537 ];
6538}
6539
6540- (void) performUpdate {
6541 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6542
6543 Status status;
6544 status.setDelegate(self);
6545 [database_ updateWithStatus:status];
6546
6547 [self
6548 performSelectorOnMainThread:@selector(completeUpdate)
6549 withObject:nil
6550 waitUntilDone:NO
6551 ];
6552
6553 [pool release];
6554}
6555
6556- (void) stopUpdateWithSelector:(SEL)selector {
6557 updating_ = false;
6558 [updatedelegate_ releaseNetworkActivityIndicator];
6559
6560 [self raiseBar:YES];
6561 [refreshbar_ stop];
6562
6563 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6564}
6565
6566- (void) completeUpdate {
6567 if (!updating_)
6568 return;
6569 [self stopUpdateWithSelector:@selector(reloadData)];
6570}
6571
6572- (void) cancelUpdate {
6573 [self stopUpdateWithSelector:@selector(updateData)];
6574}
6575
6576- (void) cancelPressed {
6577 [self cancelUpdate];
6578}
6579
6580- (BOOL) updating {
6581 return updating_;
6582}
6583
6584- (void) addProgressEvent:(CydiaProgressEvent *)event {
6585 [refreshbar_ setPrompt:[event compoundMessage]];
6586}
6587
6588- (bool) isProgressCancelled {
6589 return !updating_;
6590}
6591
6592- (void) setProgressCancellable:(NSNumber *)cancellable {
6593 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6594}
6595
6596- (void) setProgressPercent:(NSNumber *)percent {
6597 [refreshbar_ setProgress:[percent floatValue]];
6598}
6599
6600- (void) setProgressStatus:(NSDictionary *)status {
6601 if (status != nil)
6602 [self setProgressPercent:[status objectForKey:@"Percent"]];
6603}
6604
6605- (void) setUpdateDelegate:(id)delegate {
6606 updatedelegate_ = delegate;
6607}
6608
6609- (UIView *) transitionView {
6610 if ([self respondsToSelector:@selector(_transitionView)])
6611 return [self _transitionView];
6612 else
6613 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6614}
6615
6616- (void) dropBar:(BOOL)animated {
6617 if (dropped_)
6618 return;
6619 dropped_ = true;
6620
6621 UIView *transition([self transitionView]);
6622 [[self view] addSubview:refreshbar_];
6623
6624 CGRect barframe([refreshbar_ frame]);
6625
6626 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6627 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6628 else
6629 barframe.origin.y = 0;
6630
6631 [refreshbar_ setFrame:barframe];
6632
6633 if (animated)
6634 [UIView beginAnimations:nil context:NULL];
6635
6636 CGRect viewframe = [transition frame];
6637 viewframe.origin.y += barframe.size.height;
6638 viewframe.size.height -= barframe.size.height;
6639 [transition setFrame:viewframe];
6640
6641 if (animated)
6642 [UIView commitAnimations];
6643
6644 // Ensure bar has the proper width for our view, it might have changed
6645 barframe.size.width = viewframe.size.width;
6646 [refreshbar_ setFrame:barframe];
6647}
6648
6649- (void) raiseBar:(BOOL)animated {
6650 if (!dropped_)
6651 return;
6652 dropped_ = false;
6653
6654 UIView *transition([self transitionView]);
6655 [refreshbar_ removeFromSuperview];
6656
6657 CGRect barframe([refreshbar_ frame]);
6658
6659 if (animated)
6660 [UIView beginAnimations:nil context:NULL];
6661
6662 CGRect viewframe = [transition frame];
6663 viewframe.origin.y -= barframe.size.height;
6664 viewframe.size.height += barframe.size.height;
6665 [transition setFrame:viewframe];
6666
6667 if (animated)
6668 [UIView commitAnimations];
6669}
6670
6671- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6672 bool dropped(dropped_);
6673
6674 if (dropped)
6675 [self raiseBar:NO];
6676
6677 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6678
6679 if (dropped)
6680 [self dropBar:NO];
6681}
6682
6683- (void) statusBarFrameChanged:(NSNotification *)notification {
6684 if (dropped_) {
6685 [self raiseBar:NO];
6686 [self dropBar:NO];
6687 }
6688}
6689
6690@end
6691/* }}} */
6692
6693/* Cydia Navigation Controller Implementation {{{ */
6694@implementation UINavigationController (Cydia)
6695
6696- (NSArray *) navigationURLCollection {
6697 NSMutableArray *stack([NSMutableArray array]);
6698
6699 for (CyteViewController *controller in [self viewControllers]) {
6700 NSString *url = [[controller navigationURL] absoluteString];
6701 if (url != nil)
6702 [stack addObject:url];
6703 }
6704
6705 return stack;
6706}
6707
6708- (void) reloadData {
6709 [super reloadData];
6710
6711 if (UIViewController *visible = [self visibleViewController])
6712 [visible reloadData];
6713}
6714
6715- (void) unloadData {
6716 for (CyteViewController *page in [self viewControllers])
6717 [page unloadData];
6718
6719 [super unloadData];
6720}
6721
6722@end
6723/* }}} */
6724
6725/* Cydia:// Protocol {{{ */
6726@interface CydiaURLProtocol : NSURLProtocol {
6727}
6728
6729@end
6730
6731@implementation CydiaURLProtocol
6732
6733+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
6734 NSURL *url([request URL]);
6735 if (url == nil)
6736 return NO;
6737
6738 NSString *scheme([[url scheme] lowercaseString]);
6739 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6740 return YES;
6741 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6742 return YES;
6743
6744 return NO;
6745}
6746
6747+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6748 return request;
6749}
6750
6751- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6752 id<NSURLProtocolClient> client([self client]);
6753 if (icon == nil)
6754 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6755 else {
6756 NSData *data(UIImagePNGRepresentation(icon));
6757
6758 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6759 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6760 [client URLProtocol:self didLoadData:data];
6761 [client URLProtocolDidFinishLoading:self];
6762 }
6763}
6764
6765- (void) startLoading {
6766 id<NSURLProtocolClient> client([self client]);
6767 NSURLRequest *request([self request]);
6768
6769 NSURL *url([request URL]);
6770 NSString *href([url absoluteString]);
6771 NSString *scheme([[url scheme] lowercaseString]);
6772
6773 NSString *path;
6774
6775 if ([scheme isEqualToString:@"cydia"])
6776 path = [href substringFromIndex:8];
6777 else if ([scheme isEqualToString:@"about"])
6778 path = [href substringFromIndex:12];
6779 else _assert(false);
6780
6781 NSRange slash([path rangeOfString:@"/"]);
6782
6783 NSString *command;
6784 if (slash.location == NSNotFound) {
6785 command = path;
6786 path = nil;
6787 } else {
6788 command = [path substringToIndex:slash.location];
6789 path = [path substringFromIndex:(slash.location + 1)];
6790 }
6791
6792 Database *database([Database sharedInstance]);
6793
6794 if ([command isEqualToString:@"package-icon"]) {
6795 if (path == nil)
6796 goto fail;
6797 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6798 Package *package([database packageWithName:path]);
6799 if (package == nil)
6800 goto fail;
6801 [package parse];
6802 UIImage *icon([package icon]);
6803 [self _returnPNGWithImage:icon forRequest:request];
6804 } else if ([command isEqualToString:@"source-icon"]) {
6805 if (path == nil)
6806 goto fail;
6807 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6808 NSString *source(Simplify(path));
6809 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6810 if (icon == nil)
6811 icon = [UIImage applicationImageNamed:@"unknown.png"];
6812 [self _returnPNGWithImage:icon forRequest:request];
6813 } else if ([command isEqualToString:@"uikit-image"]) {
6814 if (path == nil)
6815 goto fail;
6816 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6817 UIImage *icon(_UIImageWithName(path));
6818 [self _returnPNGWithImage:icon forRequest:request];
6819 } else if ([command isEqualToString:@"section-icon"]) {
6820 if (path == nil)
6821 goto fail;
6822 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6823 NSString *section(Simplify(path));
6824 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6825 if (icon == nil)
6826 icon = [UIImage applicationImageNamed:@"unknown.png"];
6827 [self _returnPNGWithImage:icon forRequest:request];
6828 } else fail: {
6829 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6830 }
6831}
6832
6833- (void) stopLoading {
6834}
6835
6836@end
6837/* }}} */
6838
6839/* Section Controller {{{ */
6840@interface SectionController : FilteredPackageListController {
6841 _H<NSString> section_;
6842}
6843
6844- (id) initWithDatabase:(Database *)database section:(NSString *)section;
6845
6846@end
6847
6848@implementation SectionController
6849
6850- (NSURL *) navigationURL {
6851 NSString *name = section_;
6852 if (name == nil)
6853 name = @"all";
6854
6855 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6856}
6857
6858- (id) initWithDatabase:(Database *)database section:(NSString *)name {
6859 NSString *title;
6860 if (name == nil)
6861 title = UCLocalize("ALL_PACKAGES");
6862 else if (![name isEqual:@""])
6863 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6864 else
6865 title = UCLocalize("NO_SECTION");
6866
6867 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6868 section_ = name;
6869 } return self;
6870}
6871
6872@end
6873/* }}} */
6874/* Sections Controller {{{ */
6875@interface SectionsController : CyteViewController <
6876 UITableViewDataSource,
6877 UITableViewDelegate
6878> {
6879 _transient Database *database_;
6880 _H<NSMutableArray> sections_;
6881 _H<NSMutableArray> filtered_;
6882 _H<UITableView, 2> list_;
6883}
6884
6885- (id) initWithDatabase:(Database *)database;
6886- (void) editButtonClicked;
6887
6888@end
6889
6890@implementation SectionsController
6891
6892- (NSURL *) navigationURL {
6893 return [NSURL URLWithString:@"cydia://sections"];
6894}
6895
6896- (void) updateNavigationItem {
6897 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6898 if ([sections_ count] == 0) {
6899 [[self navigationItem] setRightBarButtonItem:nil];
6900 } else {
6901 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6902 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6903 target:self
6904 action:@selector(editButtonClicked)
6905 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6906 }
6907}
6908
6909- (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6910 [super setEditing:editing animated:animated];
6911
6912 if (editing)
6913 [list_ reloadData];
6914 else
6915 [delegate_ updateData];
6916
6917 [self updateNavigationItem];
6918}
6919
6920- (void) viewDidAppear:(BOOL)animated {
6921 [super viewDidAppear:animated];
6922 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6923}
6924
6925- (void) viewWillDisappear:(BOOL)animated {
6926 [super viewWillDisappear:animated];
6927 if ([self isEditing]) [self setEditing:NO];
6928}
6929
6930- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6931 Section *section = nil;
6932 int index = [indexPath row];
6933 if (![self isEditing]) {
6934 index -= 1;
6935 if (index >= 0)
6936 section = [filtered_ objectAtIndex:index];
6937 } else {
6938 section = [sections_ objectAtIndex:index];
6939 }
6940 return section;
6941}
6942
6943- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6944 if ([self isEditing])
6945 return [sections_ count];
6946 else
6947 return [filtered_ count] + 1;
6948}
6949
6950/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6951 return 45.0f;
6952}*/
6953
6954- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6955 static NSString *reuseIdentifier = @"SectionCell";
6956
6957 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6958 if (cell == nil)
6959 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6960
6961 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6962
6963 return cell;
6964}
6965
6966- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6967 if ([self isEditing])
6968 return;
6969
6970 Section *section = [self sectionAtIndexPath:indexPath];
6971
6972 SectionController *controller = [[[SectionController alloc]
6973 initWithDatabase:database_
6974 section:[section name]
6975 ] autorelease];
6976 [controller setDelegate:delegate_];
6977
6978 [[self navigationController] pushViewController:controller animated:YES];
6979}
6980
6981- (void) loadView {
6982 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6983
6984 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6985 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6986 [list_ setRowHeight:45.0f];
6987 [(UITableView *) list_ setDataSource:self];
6988 [list_ setDelegate:self];
6989 [[self view] addSubview:list_];
6990}
6991
6992- (void) viewDidLoad {
6993 [super viewDidLoad];
6994
6995 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6996}
6997
6998- (void) releaseSubviews {
6999 list_ = nil;
7000
7001 [super releaseSubviews];
7002}
7003
7004- (id) initWithDatabase:(Database *)database {
7005 if ((self = [super init]) != nil) {
7006 database_ = database;
7007
7008 sections_ = [NSMutableArray arrayWithCapacity:16];
7009 filtered_ = [NSMutableArray arrayWithCapacity:16];
7010 } return self;
7011}
7012
7013- (void) reloadData {
7014 [super reloadData];
7015
7016 NSArray *packages = [database_ packages];
7017
7018 [sections_ removeAllObjects];
7019 [filtered_ removeAllObjects];
7020
7021 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7022
7023 _trace();
7024 for (Package *package in packages) {
7025 NSString *name([package section]);
7026 NSString *key(name == nil ? @"" : name);
7027
7028 Section *section;
7029
7030 _profile(SectionsView$reloadData$Section)
7031 section = [sections objectForKey:key];
7032 if (section == nil) {
7033 _profile(SectionsView$reloadData$Section$Allocate)
7034 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7035 [sections setObject:section forKey:key];
7036 _end
7037 }
7038 _end
7039
7040 [section addToCount];
7041
7042 _profile(SectionsView$reloadData$Filter)
7043 if (![package valid] || ![package visible])
7044 continue;
7045 _end
7046
7047 [section addToRow];
7048 }
7049 _trace();
7050
7051 [sections_ addObjectsFromArray:[sections allValues]];
7052
7053 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7054
7055 for (Section *section in (id) sections_) {
7056 size_t count([section row]);
7057 if (count == 0)
7058 continue;
7059
7060 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7061 [section setCount:count];
7062 [filtered_ addObject:section];
7063 }
7064
7065 [self updateNavigationItem];
7066 [list_ reloadData];
7067 _trace();
7068}
7069
7070- (void) editButtonClicked {
7071 [self setEditing:![self isEditing] animated:YES];
7072}
7073
7074@end
7075/* }}} */
7076
7077/* Changes Controller {{{ */
7078@interface ChangesController : CyteViewController <
7079 UITableViewDataSource,
7080 UITableViewDelegate
7081> {
7082 _transient Database *database_;
7083 unsigned era_;
7084 _H<NSArray> packages_;
7085 _H<NSMutableArray> sections_;
7086 _H<UITableView, 2> list_;
7087 unsigned upgrades_;
7088}
7089
7090- (id) initWithDatabase:(Database *)database;
7091
7092@end
7093
7094@implementation ChangesController
7095
7096- (NSURL *) navigationURL {
7097 return [NSURL URLWithString:@"cydia://changes"];
7098}
7099
7100- (void) viewDidAppear:(BOOL)animated {
7101 [super viewDidAppear:animated];
7102 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7103}
7104
7105- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7106 NSInteger count([sections_ count]);
7107 return count == 0 ? 1 : count;
7108}
7109
7110- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7111 if ([sections_ count] == 0)
7112 return nil;
7113 return [[sections_ objectAtIndex:section] name];
7114}
7115
7116- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7117 if ([sections_ count] == 0)
7118 return 0;
7119 return [[sections_ objectAtIndex:section] count];
7120}
7121
7122- (Package *) packageAtIndexPath:(NSIndexPath *)path {
7123@synchronized (database_) {
7124 if ([database_ era] != era_)
7125 return nil;
7126
7127 NSUInteger sectionIndex([path section]);
7128 if (sectionIndex >= [sections_ count])
7129 return nil;
7130 Section *section([sections_ objectAtIndex:sectionIndex]);
7131 NSInteger row([path row]);
7132 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7133} }
7134
7135- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7136 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7137 if (cell == nil)
7138 cell = [[[PackageCell alloc] init] autorelease];
7139 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7140 return cell;
7141}
7142
7143- (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7144 Package *package([self packageAtIndexPath:path]);
7145 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7146 [view setDelegate:delegate_];
7147 [[self navigationController] pushViewController:view animated:YES];
7148 return path;
7149}
7150
7151- (void) refreshButtonClicked {
7152 [delegate_ beginUpdate];
7153 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7154}
7155
7156- (void) upgradeButtonClicked {
7157 [delegate_ distUpgrade];
7158}
7159
7160- (void) loadView {
7161 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7162
7163 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7164 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7165 [list_ setRowHeight:73];
7166 [(UITableView *) list_ setDataSource:self];
7167 [list_ setDelegate:self];
7168 [[self view] addSubview:list_];
7169}
7170
7171- (void) viewDidLoad {
7172 [super viewDidLoad];
7173
7174 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7175}
7176
7177- (void) releaseSubviews {
7178 list_ = nil;
7179
7180 [super releaseSubviews];
7181}
7182
7183- (id) initWithDatabase:(Database *)database {
7184 if ((self = [super init]) != nil) {
7185 database_ = database;
7186
7187 packages_ = [NSArray array];
7188 sections_ = [NSMutableArray arrayWithCapacity:16];
7189 } return self;
7190}
7191
7192- (NSMutableArray *) _reloadPackages {
7193@synchronized (database_) {
7194 era_ = [database_ era];
7195 NSArray *packages([database_ packages]);
7196
7197 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7198
7199 _trace();
7200 _profile(ChangesController$_reloadPackages$Filter)
7201 for (Package *package in packages)
7202 if ([package upgradableAndEssential:YES] || [package visible])
7203 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7204 _end
7205 _trace();
7206 _profile(ChangesController$_reloadPackages$radixSort)
7207 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7208 _end
7209 _trace();
7210
7211 return filtered;
7212} }
7213
7214- (void) _reloadData {
7215 NSArray *packages;
7216
7217 reload:
7218 if (true) {
7219 UIProgressHUD *hud([delegate_ addProgressHUD]);
7220 [hud setText:UCLocalize("LOADING")];
7221 //NSLog(@"HUD:%@::%@", delegate_, hud);
7222 packages = [self yieldToSelector:@selector(_reloadPackages)];
7223 [delegate_ removeProgressHUD:hud];
7224 } else {
7225 packages = [self _reloadPackages];
7226 }
7227
7228@synchronized (database_) {
7229 if (era_ != [database_ era])
7230 goto reload;
7231
7232 packages_ = packages;
7233 [sections_ removeAllObjects];
7234
7235 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7236 Section *ignored = nil;
7237 Section *section = nil;
7238 time_t last = 0;
7239
7240 upgrades_ = 0;
7241 bool unseens = false;
7242
7243 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7244
7245 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7246 Package *package = [packages_ objectAtIndex:offset];
7247
7248 BOOL uae = [package upgradableAndEssential:YES];
7249
7250 if (!uae) {
7251 unseens = true;
7252 time_t seen([package seen]);
7253
7254 if (section == nil || last != seen) {
7255 last = seen;
7256
7257 NSString *name;
7258 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7259 [name autorelease];
7260
7261 _profile(ChangesController$reloadData$Allocate)
7262 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7263 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7264 [sections_ addObject:section];
7265 _end
7266 }
7267
7268 [section addToCount];
7269 } else if ([package ignored]) {
7270 if (ignored == nil) {
7271 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7272 }
7273 [ignored addToCount];
7274 } else {
7275 ++upgrades_;
7276 [upgradable addToCount];
7277 }
7278 }
7279 _trace();
7280
7281 CFRelease(formatter);
7282
7283 if (unseens) {
7284 Section *last = [sections_ lastObject];
7285 size_t count = [last count];
7286 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7287 [sections_ removeLastObject];
7288 }
7289
7290 if ([ignored count] != 0)
7291 [sections_ insertObject:ignored atIndex:0];
7292 if (upgrades_ != 0)
7293 [sections_ insertObject:upgradable atIndex:0];
7294
7295 [list_ reloadData];
7296
7297 if (upgrades_ > 0)
7298 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7299 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7300 style:UIBarButtonItemStylePlain
7301 target:self
7302 action:@selector(upgradeButtonClicked)
7303 ] autorelease]];
7304
7305 if (![delegate_ updating])
7306 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7307 initWithTitle:UCLocalize("REFRESH")
7308 style:UIBarButtonItemStylePlain
7309 target:self
7310 action:@selector(refreshButtonClicked)
7311 ] autorelease]];
7312
7313 PrintTimes();
7314} }
7315
7316- (void) reloadData {
7317 [super reloadData];
7318 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7319}
7320
7321@end
7322/* }}} */
7323/* Search Controller {{{ */
7324@interface SearchController : FilteredPackageListController <
7325 UISearchBarDelegate
7326> {
7327 _H<UISearchBar, 1> search_;
7328 BOOL searchloaded_;
7329}
7330
7331- (id) initWithDatabase:(Database *)database query:(NSString *)query;
7332- (void) reloadData;
7333
7334@end
7335
7336@implementation SearchController
7337
7338- (NSURL *) navigationURL {
7339 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7340 return [NSURL URLWithString:@"cydia://search"];
7341 else
7342 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7343}
7344
7345- (void) useSearch {
7346 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7347 [self clearData];
7348 [self reloadData];
7349}
7350
7351- (void) viewWillAppear:(BOOL)animated {
7352 [super viewWillAppear:animated];
7353
7354 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7355 [self useSearch];
7356}
7357
7358- (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7359 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7360 [self clearData];
7361 [self reloadData];
7362}
7363
7364- (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7365 [search_ resignFirstResponder];
7366 [self useSearch];
7367}
7368
7369- (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7370 [search_ setText:@""];
7371 [self searchBarButtonClicked:searchBar];
7372}
7373
7374- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7375 [self searchBarButtonClicked:searchBar];
7376}
7377
7378- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7379 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7380 [self reloadData];
7381}
7382
7383- (bool) shouldYield {
7384 return YES;
7385}
7386
7387- (bool) shouldBlock {
7388 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7389}
7390
7391- (bool) isSummarized {
7392 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7393}
7394
7395- (bool) showsSections {
7396 return false;
7397}
7398
7399- (NSMutableArray *) _reloadPackages {
7400 NSMutableArray *packages([super _reloadPackages]);
7401 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7402 [packages radixSortUsingSelector:@selector(rank)];
7403 return packages;
7404}
7405
7406- (id) initWithDatabase:(Database *)database query:(NSString *)query {
7407 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7408 search_ = [[[UISearchBar alloc] init] autorelease];
7409 [search_ setDelegate:self];
7410
7411 if (query != nil)
7412 [search_ setText:query];
7413 } return self;
7414}
7415
7416- (void) viewDidAppear:(BOOL)animated {
7417 [super viewDidAppear:animated];
7418
7419 if (!searchloaded_) {
7420 searchloaded_ = YES;
7421 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7422 [search_ layoutSubviews];
7423 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7424
7425 UITextField *textField;
7426 if ([search_ respondsToSelector:@selector(searchField)])
7427 textField = [search_ searchField];
7428 else
7429 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7430
7431 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7432 [textField setEnablesReturnKeyAutomatically:NO];
7433 [[self navigationItem] setTitleView:textField];
7434 }
7435}
7436
7437- (void) reloadData {
7438 id object([search_ text]);
7439 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7440 object = [object componentsSeparatedByString:@" "];
7441
7442 [self setObject:object];
7443 [self resetCursor];
7444
7445 [super reloadData];
7446}
7447
7448- (void) didSelectPackage:(Package *)package {
7449 [search_ resignFirstResponder];
7450 [super didSelectPackage:package];
7451}
7452
7453@end
7454/* }}} */
7455/* Package Settings Controller {{{ */
7456@interface PackageSettingsController : CyteViewController <
7457 UITableViewDataSource,
7458 UITableViewDelegate
7459> {
7460 _transient Database *database_;
7461 _H<NSString> name_;
7462 _H<Package> package_;
7463 _H<UITableView, 2> table_;
7464 _H<UISwitch> subscribedSwitch_;
7465 _H<UISwitch> ignoredSwitch_;
7466 _H<UITableViewCell> subscribedCell_;
7467 _H<UITableViewCell> ignoredCell_;
7468}
7469
7470- (id) initWithDatabase:(Database *)database package:(NSString *)package;
7471
7472@end
7473
7474@implementation PackageSettingsController
7475
7476- (NSURL *) navigationURL {
7477 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7478}
7479
7480- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7481 if (package_ == nil)
7482 return 0;
7483
7484 if ([package_ installed] == nil)
7485 return 1;
7486 else
7487 return 2;
7488}
7489
7490- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7491 if (package_ == nil)
7492 return 0;
7493
7494 // both sections contain just one item right now.
7495 return 1;
7496}
7497
7498- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7499 return nil;
7500}
7501
7502- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7503 if (section == 0)
7504 return UCLocalize("SHOW_ALL_CHANGES_EX");
7505 else
7506 return UCLocalize("IGNORE_UPGRADES_EX");
7507}
7508
7509- (void) onSubscribed:(id)control {
7510 bool value([control isOn]);
7511 if (package_ == nil)
7512 return;
7513 if ([package_ setSubscribed:value])
7514 [delegate_ updateData];
7515}
7516
7517- (void) _updateIgnored {
7518 const char *package([name_ UTF8String]);
7519 bool on([ignoredSwitch_ isOn]);
7520
7521 pid_t pid(ExecFork());
7522 if (pid == 0) {
7523 FILE *dpkg(popen("dpkg --set-selections", "w"));
7524 fwrite(package, strlen(package), 1, dpkg);
7525
7526 if (on)
7527 fwrite(" hold\n", 6, 1, dpkg);
7528 else
7529 fwrite(" install\n", 9, 1, dpkg);
7530
7531 pclose(dpkg);
7532
7533 exit(0);
7534 _assert(false);
7535 }
7536
7537 _forever {
7538 int status;
7539 int result(waitpid(pid, &status, 0));
7540
7541 if (result != -1) {
7542 _assert(result == pid);
7543 break;
7544 }
7545 }
7546}
7547
7548- (void) onIgnored:(id)control {
7549 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7550 [invocation setTarget:self];
7551 [invocation setSelector:@selector(_updateIgnored)];
7552
7553 [delegate_ reloadDataWithInvocation:invocation];
7554}
7555
7556- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7557 if (package_ == nil)
7558 return nil;
7559
7560 switch ([indexPath section]) {
7561 case 0: return subscribedCell_;
7562 case 1: return ignoredCell_;
7563
7564 _nodefault
7565 }
7566
7567 return nil;
7568}
7569
7570- (void) loadView {
7571 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7572
7573 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7574 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7575 [(UITableView *) table_ setDataSource:self];
7576 [table_ setDelegate:self];
7577 [[self view] addSubview:table_];
7578
7579 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7580 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7581 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7582
7583 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7584 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7585 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7586
7587 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7588 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7589 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7590 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7591
7592 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7593 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7594 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7595 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7596}
7597
7598- (void) viewDidLoad {
7599 [super viewDidLoad];
7600
7601 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7602}
7603
7604- (void) releaseSubviews {
7605 ignoredCell_ = nil;
7606 subscribedCell_ = nil;
7607 table_ = nil;
7608 ignoredSwitch_ = nil;
7609 subscribedSwitch_ = nil;
7610
7611 [super releaseSubviews];
7612}
7613
7614- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7615 if ((self = [super init]) != nil) {
7616 database_ = database;
7617 name_ = package;
7618 } return self;
7619}
7620
7621- (void) reloadData {
7622 [super reloadData];
7623
7624 package_ = [database_ packageWithName:name_];
7625
7626 if (package_ != nil) {
7627 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7628 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7629 } // XXX: what now, G?
7630
7631 [table_ reloadData];
7632}
7633
7634@end
7635/* }}} */
7636
7637/* Installed Controller {{{ */
7638@interface InstalledController : FilteredPackageListController {
7639 BOOL expert_;
7640}
7641
7642- (id) initWithDatabase:(Database *)database;
7643
7644- (void) updateRoleButton;
7645- (void) queueStatusDidChange;
7646
7647@end
7648
7649@implementation InstalledController
7650
7651- (NSURL *) navigationURL {
7652 return [NSURL URLWithString:@"cydia://installed"];
7653}
7654
7655- (id) initWithDatabase:(Database *)database {
7656 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7657 [self updateRoleButton];
7658 [self queueStatusDidChange];
7659 } return self;
7660}
7661
7662#if !AlwaysReload
7663- (void) queueButtonClicked {
7664 [delegate_ queue];
7665}
7666#endif
7667
7668- (void) queueStatusDidChange {
7669#if !AlwaysReload
7670 if (IsWildcat_) {
7671 if (Queuing_) {
7672 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7673 initWithTitle:UCLocalize("QUEUE")
7674 style:UIBarButtonItemStyleDone
7675 target:self
7676 action:@selector(queueButtonClicked)
7677 ] autorelease]];
7678 } else {
7679 [[self navigationItem] setLeftBarButtonItem:nil];
7680 }
7681 }
7682#endif
7683}
7684
7685- (void) updateRoleButton {
7686 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7687 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7688 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7689 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7690 target:self
7691 action:@selector(roleButtonClicked)
7692 ] autorelease]];
7693}
7694
7695- (void) roleButtonClicked {
7696 [self setObject:[NSNumber numberWithBool:expert_]];
7697 [self reloadData];
7698 expert_ = !expert_;
7699
7700 [self updateRoleButton];
7701}
7702
7703@end
7704/* }}} */
7705
7706/* Source Cell {{{ */
7707@interface SourceCell : CyteTableViewCell <
7708 CyteTableViewCellDelegate
7709> {
7710 _H<UIImage> icon_;
7711 _H<NSString> origin_;
7712 _H<NSString> label_;
7713}
7714
7715- (void) setSource:(Source *)source;
7716
7717@end
7718
7719@implementation SourceCell
7720
7721- (void) _setImage:(UIImage *)image {
7722 icon_ = image;
7723 [content_ setNeedsDisplay];
7724}
7725
7726- (void) _setSource:(Source *)source {
7727 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7728
7729 if (NSString *base = [source base])
7730 if ([base length] != 0) {
7731 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7732
7733 if (NSData *data = [NSURLConnection
7734 sendSynchronousRequest:[NSURLRequest
7735 requestWithURL:url
7736 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7737 //timeoutInterval:5
7738 ]
7739
7740 returningResponse:NULL
7741 error:NULL
7742 ])
7743 if (UIImage *image = [UIImage imageWithData:data])
7744 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7745 }
7746
7747 [pool release];
7748}
7749
7750- (void) setSource:(Source *)source {
7751 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7752
7753 origin_ = [source name];
7754 label_ = [source uri];
7755
7756 [content_ setNeedsDisplay];
7757
7758 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7759}
7760
7761- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7762 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7763 UIView *content([self contentView]);
7764 CGRect bounds([content bounds]);
7765
7766 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7767 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7768 [content_ setBackgroundColor:[UIColor whiteColor]];
7769 [content addSubview:content_];
7770
7771 [content_ setDelegate:self];
7772 [content_ setOpaque:YES];
7773 } return self;
7774}
7775
7776- (NSString *) accessibilityLabel {
7777 return label_;
7778}
7779
7780- (void) drawContentRect:(CGRect)rect {
7781 bool highlighted(highlighted_);
7782 float width(rect.size.width);
7783
7784 if (icon_ != nil)
7785 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7786
7787 if (highlighted)
7788 UISetColor(White_);
7789
7790 if (!highlighted)
7791 UISetColor(Black_);
7792 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7793
7794 if (!highlighted)
7795 UISetColor(Blue_);
7796 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7797}
7798
7799@end
7800/* }}} */
7801/* Source Controller {{{ */
7802@interface SourceController : FilteredPackageListController {
7803 _transient Source *source_;
7804 _H<NSString> key_;
7805}
7806
7807- (id) initWithDatabase:(Database *)database source:(Source *)source;
7808
7809@end
7810
7811@implementation SourceController
7812
7813- (NSURL *) navigationURL {
7814 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7815}
7816
7817- (id) initWithDatabase:(Database *)database source:(Source *)source {
7818 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7819 source_ = source;
7820 key_ = [source key];
7821 } return self;
7822}
7823
7824- (void) reloadData {
7825 source_ = [database_ sourceWithKey:key_];
7826 key_ = [source_ key];
7827 [self setObject:source_];
7828
7829 [[self navigationItem] setTitle:[source_ label]];
7830
7831 [super reloadData];
7832}
7833
7834@end
7835/* }}} */
7836/* Sources Controller {{{ */
7837@interface SourcesController : CyteViewController <
7838 UITableViewDataSource,
7839 UITableViewDelegate
7840> {
7841 _transient Database *database_;
7842 _H<UITableView, 2> list_;
7843 _H<NSMutableArray> sources_;
7844 int offset_;
7845
7846 _H<NSString> href_;
7847 _H<UIProgressHUD> hud_;
7848 _H<NSError> error_;
7849
7850 //NSURLConnection *installer_;
7851 NSURLConnection *trivial_;
7852 NSURLConnection *trivial_bz2_;
7853 NSURLConnection *trivial_gz_;
7854 //NSURLConnection *automatic_;
7855
7856 BOOL cydia_;
7857}
7858
7859- (id) initWithDatabase:(Database *)database;
7860- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7861
7862@end
7863
7864@implementation SourcesController
7865
7866- (void) _releaseConnection:(NSURLConnection *)connection {
7867 if (connection != nil) {
7868 [connection cancel];
7869 //[connection setDelegate:nil];
7870 [connection release];
7871 }
7872}
7873
7874- (void) dealloc {
7875 //[self _releaseConnection:installer_];
7876 [self _releaseConnection:trivial_];
7877 [self _releaseConnection:trivial_gz_];
7878 [self _releaseConnection:trivial_bz2_];
7879 //[self _releaseConnection:automatic_];
7880
7881 [super dealloc];
7882}
7883
7884- (NSURL *) navigationURL {
7885 return [NSURL URLWithString:@"cydia://sources"];
7886}
7887
7888- (void) viewDidAppear:(BOOL)animated {
7889 [super viewDidAppear:animated];
7890 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7891}
7892
7893- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7894 return offset_ == 0 ? 1 : 2;
7895}
7896
7897- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7898 switch (section + (offset_ == 0 ? 1 : 0)) {
7899 case 0: return UCLocalize("ENTERED_BY_USER");
7900 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7901
7902 _nodefault
7903 }
7904}
7905
7906- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7907 int count = [sources_ count];
7908 switch (section) {
7909 case 0: return (offset_ == 0 ? count : offset_);
7910 case 1: return count - offset_;
7911
7912 _nodefault
7913 }
7914}
7915
7916- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7917 unsigned idx = 0;
7918 switch (indexPath.section) {
7919 case 0: idx = indexPath.row; break;
7920 case 1: idx = indexPath.row + offset_; break;
7921
7922 _nodefault
7923 }
7924 return [sources_ objectAtIndex:idx];
7925}
7926
7927- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7928 static NSString *cellIdentifier = @"SourceCell";
7929
7930 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7931 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7932 [cell setSource:[self sourceAtIndexPath:indexPath]];
7933 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7934
7935 return cell;
7936}
7937
7938- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7939 Source *source = [self sourceAtIndexPath:indexPath];
7940
7941 SourceController *controller = [[[SourceController alloc]
7942 initWithDatabase:database_
7943 source:source
7944 ] autorelease];
7945
7946 [controller setDelegate:delegate_];
7947
7948 [[self navigationController] pushViewController:controller animated:YES];
7949}
7950
7951- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7952 Source *source = [self sourceAtIndexPath:indexPath];
7953 return [source record] != nil;
7954}
7955
7956- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7957 if (editingStyle == UITableViewCellEditingStyleDelete) {
7958 Source *source = [self sourceAtIndexPath:indexPath];
7959 [Sources_ removeObjectForKey:[source key]];
7960 [delegate_ syncData];
7961 }
7962}
7963
7964- (void) complete {
7965 [delegate_ addTrivialSource:href_];
7966 [delegate_ syncData];
7967}
7968
7969- (NSString *) getWarning {
7970 NSString *href(href_);
7971 NSRange colon([href rangeOfString:@"://"]);
7972 if (colon.location != NSNotFound)
7973 href = [href substringFromIndex:(colon.location + 3)];
7974 href = [href stringByAddingPercentEscapes];
7975 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7976 href = [href stringByCachingURLWithCurrentCDN];
7977
7978 NSURL *url([NSURL URLWithString:href]);
7979
7980 NSStringEncoding encoding;
7981 NSError *error(nil);
7982
7983 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7984 return [warning length] == 0 ? nil : warning;
7985 return nil;
7986}
7987
7988- (void) _endConnection:(NSURLConnection *)connection {
7989 // XXX: the memory management in this method is horribly awkward
7990
7991 NSURLConnection **field = NULL;
7992 if (connection == trivial_)
7993 field = &trivial_;
7994 else if (connection == trivial_bz2_)
7995 field = &trivial_bz2_;
7996 else if (connection == trivial_gz_)
7997 field = &trivial_gz_;
7998 _assert(field != NULL);
7999 [connection release];
8000 *field = nil;
8001
8002 if (
8003 trivial_ == nil &&
8004 trivial_bz2_ == nil &&
8005 trivial_gz_ == nil
8006 ) {
8007 [delegate_ releaseNetworkActivityIndicator];
8008
8009 [delegate_ removeProgressHUD:hud_];
8010 hud_ = nil;
8011
8012 bool defer(false);
8013
8014 if (cydia_) {
8015 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8016 defer = true;
8017
8018 UIAlertView *alert = [[[UIAlertView alloc]
8019 initWithTitle:UCLocalize("SOURCE_WARNING")
8020 message:warning
8021 delegate:self
8022 cancelButtonTitle:UCLocalize("CANCEL")
8023 otherButtonTitles:
8024 UCLocalize("ADD_ANYWAY"),
8025 nil
8026 ] autorelease];
8027
8028 [alert setContext:@"warning"];
8029 [alert setNumberOfRows:1];
8030 [alert show];
8031 } else
8032 [self complete];
8033 } else if (error_ != nil) {
8034 UIAlertView *alert = [[[UIAlertView alloc]
8035 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8036 message:[error_ localizedDescription]
8037 delegate:self
8038 cancelButtonTitle:UCLocalize("OK")
8039 otherButtonTitles:nil
8040 ] autorelease];
8041
8042 [alert setContext:@"urlerror"];
8043 [alert show];
8044 } else {
8045 UIAlertView *alert = [[[UIAlertView alloc]
8046 initWithTitle:UCLocalize("NOT_REPOSITORY")
8047 message:UCLocalize("NOT_REPOSITORY_EX")
8048 delegate:self
8049 cancelButtonTitle:UCLocalize("OK")
8050 otherButtonTitles:nil
8051 ] autorelease];
8052
8053 [alert setContext:@"trivial"];
8054 [alert show];
8055 }
8056
8057 href_ = nil;
8058 error_ = nil;
8059 }
8060}
8061
8062- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8063 switch ([response statusCode]) {
8064 case 200:
8065 cydia_ = YES;
8066 }
8067}
8068
8069- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8070 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8071 error_ = error;
8072 [self _endConnection:connection];
8073}
8074
8075- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8076 [self _endConnection:connection];
8077}
8078
8079- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8080 NSURL *url([NSURL URLWithString:href]);
8081
8082 NSMutableURLRequest *request = [NSMutableURLRequest
8083 requestWithURL:url
8084 cachePolicy:NSURLRequestUseProtocolCachePolicy
8085 timeoutInterval:120.0
8086 ];
8087
8088 [request setHTTPMethod:method];
8089
8090 if (Machine_ != NULL)
8091 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8092
8093 if ([url isCydiaSecure]) {
8094 if (UniqueID_ != nil)
8095 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8096 }
8097
8098 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8099}
8100
8101- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8102 NSString *context([alert context]);
8103
8104 if ([context isEqualToString:@"source"]) {
8105 switch (button) {
8106 case 1: {
8107 NSString *href = [[alert textField] text];
8108
8109 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8110
8111 if (![href hasSuffix:@"/"])
8112 href_ = [href stringByAppendingString:@"/"];
8113 else
8114 href_ = href;
8115
8116 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8117 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8118 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8119 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8120
8121 cydia_ = false;
8122
8123 // XXX: this is stupid
8124 hud_ = [delegate_ addProgressHUD];
8125 [hud_ setText:UCLocalize("VERIFYING_URL")];
8126 [delegate_ retainNetworkActivityIndicator];
8127 } break;
8128
8129 case 0:
8130 break;
8131
8132 _nodefault
8133 }
8134
8135 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8136 } else if ([context isEqualToString:@"trivial"])
8137 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8138 else if ([context isEqualToString:@"urlerror"])
8139 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8140 else if ([context isEqualToString:@"warning"]) {
8141 switch (button) {
8142 case 1:
8143 [self complete];
8144 break;
8145
8146 case 0:
8147 break;
8148
8149 _nodefault
8150 }
8151
8152 href_ = nil;
8153
8154 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8155 }
8156}
8157
8158- (void) loadView {
8159 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8160
8161 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8162 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8163 [list_ setRowHeight:56];
8164 [(UITableView *) list_ setDataSource:self];
8165 [list_ setDelegate:self];
8166 [[self view] addSubview:list_];
8167}
8168
8169- (void) viewDidLoad {
8170 [super viewDidLoad];
8171
8172 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8173 [self updateButtonsForEditingStatus:NO animated:NO];
8174}
8175
8176- (void) releaseSubviews {
8177 list_ = nil;
8178
8179 [super releaseSubviews];
8180}
8181
8182- (id) initWithDatabase:(Database *)database {
8183 if ((self = [super init]) != nil) {
8184 database_ = database;
8185 sources_ = [NSMutableArray arrayWithCapacity:16];
8186 } return self;
8187}
8188
8189- (void) reloadData {
8190 [super reloadData];
8191
8192 pkgSourceList list;
8193 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8194 return;
8195
8196 [sources_ removeAllObjects];
8197 [sources_ addObjectsFromArray:[database_ sources]];
8198 _trace();
8199 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8200 _trace();
8201
8202 int count([sources_ count]);
8203 offset_ = 0;
8204 for (int i = 0; i != count; i++) {
8205 if ([[sources_ objectAtIndex:i] record] == nil)
8206 break;
8207 offset_++;
8208 }
8209
8210 [list_ setEditing:NO];
8211 [self updateButtonsForEditingStatus:NO animated:NO];
8212 [list_ reloadData];
8213}
8214
8215- (void) showAddSourcePrompt {
8216 UIAlertView *alert = [[[UIAlertView alloc]
8217 initWithTitle:UCLocalize("ENTER_APT_URL")
8218 message:nil
8219 delegate:self
8220 cancelButtonTitle:UCLocalize("CANCEL")
8221 otherButtonTitles:
8222 UCLocalize("ADD_SOURCE"),
8223 nil
8224 ] autorelease];
8225
8226 [alert setContext:@"source"];
8227
8228 [alert setNumberOfRows:1];
8229 [alert addTextFieldWithValue:@"http://" label:@""];
8230
8231 UITextInputTraits *traits = [[alert textField] textInputTraits];
8232 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8233 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8234 [traits setKeyboardType:UIKeyboardTypeURL];
8235 // XXX: UIReturnKeyDone
8236 [traits setReturnKeyType:UIReturnKeyNext];
8237
8238 [alert show];
8239}
8240
8241- (void) addButtonClicked {
8242 [self showAddSourcePrompt];
8243}
8244
8245- (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8246 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8247 initWithTitle:UCLocalize("ADD")
8248 style:UIBarButtonItemStylePlain
8249 target:self
8250 action:@selector(addButtonClicked)
8251 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8252
8253 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8254 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8255 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8256 target:self
8257 action:@selector(editButtonClicked)
8258 ] autorelease] animated:animated];
8259
8260 if (IsWildcat_ && !editing)
8261 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8262 initWithTitle:UCLocalize("SETTINGS")
8263 style:UIBarButtonItemStylePlain
8264 target:self
8265 action:@selector(settingsButtonClicked)
8266 ] autorelease]];
8267}
8268
8269- (void) settingsButtonClicked {
8270 [delegate_ showSettings];
8271}
8272
8273- (void) editButtonClicked {
8274 [list_ setEditing:![list_ isEditing] animated:YES];
8275
8276 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8277}
8278
8279@end
8280/* }}} */
8281
8282/* Settings Controller {{{ */
8283@interface SettingsController : CyteViewController <
8284 UITableViewDataSource,
8285 UITableViewDelegate
8286> {
8287 _transient Database *database_;
8288 // XXX: ok, "roledelegate_"?...
8289 _transient id roledelegate_;
8290 _H<UITableView, 2> table_;
8291 _H<UISegmentedControl> segment_;
8292 _H<UIView> container_;
8293}
8294
8295- (void) showDoneButton;
8296- (void) resizeSegmentedControl;
8297
8298@end
8299
8300@implementation SettingsController
8301
8302- (void) loadView {
8303 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8304
8305 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8306 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8307 [table_ setDelegate:self];
8308 [(UITableView *) table_ setDataSource:self];
8309 [[self view] addSubview:table_];
8310
8311 NSArray *items = [NSArray arrayWithObjects:
8312 UCLocalize("USER"),
8313 UCLocalize("HACKER"),
8314 UCLocalize("DEVELOPER"),
8315 nil];
8316 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8317 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8318 [container_ addSubview:segment_];
8319}
8320
8321- (void) viewDidLoad {
8322 [super viewDidLoad];
8323
8324 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8325
8326 int index = -1;
8327 if ([Role_ isEqualToString:@"User"]) index = 0;
8328 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8329 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8330 if (index != -1) {
8331 [segment_ setSelectedSegmentIndex:index];
8332 [self showDoneButton];
8333 }
8334
8335 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8336 [self resizeSegmentedControl];
8337}
8338
8339- (void) releaseSubviews {
8340 table_ = nil;
8341 segment_ = nil;
8342 container_ = nil;
8343
8344 [super releaseSubviews];
8345}
8346
8347- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8348 if ((self = [super init]) != nil) {
8349 database_ = database;
8350 roledelegate_ = delegate;
8351 } return self;
8352}
8353
8354- (void) resizeSegmentedControl {
8355 CGFloat width = [[self view] frame].size.width;
8356 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8357}
8358
8359- (void) viewWillAppear:(BOOL)animated {
8360 [super viewWillAppear:animated];
8361
8362 [self resizeSegmentedControl];
8363}
8364
8365- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8366 [self resizeSegmentedControl];
8367}
8368
8369- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8370 [self resizeSegmentedControl];
8371}
8372
8373- (void) save {
8374 NSString *role(nil);
8375
8376 switch ([segment_ selectedSegmentIndex]) {
8377 case 0: role = @"User"; break;
8378 case 1: role = @"Hacker"; break;
8379 case 2: role = @"Developer"; break;
8380
8381 _nodefault
8382 }
8383
8384 if (![role isEqualToString:Role_]) {
8385 bool rolling(Role_ == nil);
8386 Role_ = role;
8387
8388 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8389 Role_, @"Role",
8390 nil];
8391
8392 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8393 Changed_ = true;
8394
8395 if (rolling)
8396 [roledelegate_ loadData];
8397 else
8398 [roledelegate_ updateData];
8399 }
8400}
8401
8402- (void) segmentChanged:(UISegmentedControl *)control {
8403 [self showDoneButton];
8404}
8405
8406- (void) saveAndClose {
8407 [self save];
8408
8409 [[self navigationItem] setRightBarButtonItem:nil];
8410 [[self navigationController] dismissModalViewControllerAnimated:YES];
8411}
8412
8413- (void) doneButtonClicked {
8414 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8415 [spinner startAnimating];
8416 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8417 [[self navigationItem] setRightBarButtonItem:spinItem];
8418
8419 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8420}
8421
8422- (void) showDoneButton {
8423 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8424 initWithTitle:UCLocalize("DONE")
8425 style:UIBarButtonItemStyleDone
8426 target:self
8427 action:@selector(doneButtonClicked)
8428 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8429}
8430
8431- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8432 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8433 return 6;
8434}
8435
8436- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8437 return 0; // :(
8438}
8439
8440- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8441 return nil; // This method is required by the protocol.
8442}
8443
8444- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8445 if (section == 1)
8446 return UCLocalize("ROLE_EX");
8447 if (section == 4)
8448 return [NSString stringWithFormat:
8449 @"%@: %@\n%@: %@\n%@: %@",
8450 UCLocalize("USER"), UCLocalize("USER_EX"),
8451 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8452 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8453 ];
8454 else return nil;
8455}
8456
8457- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8458 return section == 3 ? 44.0f : 0;
8459}
8460
8461- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8462 return section == 3 ? container_ : nil;
8463}
8464
8465- (void) reloadData {
8466 [super reloadData];
8467
8468 [table_ reloadData];
8469}
8470
8471@end
8472/* }}} */
8473/* Stash Controller {{{ */
8474@interface StashController : CyteViewController {
8475 _H<UIActivityIndicatorView> spinner_;
8476 _H<UILabel> status_;
8477 _H<UILabel> caption_;
8478}
8479
8480@end
8481
8482@implementation StashController
8483
8484- (void) loadView {
8485 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8486 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8487
8488 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8489 CGRect spinrect = [spinner_ frame];
8490 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8491 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8492 [spinner_ setFrame:spinrect];
8493 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8494 [[self view] addSubview:spinner_];
8495 [spinner_ startAnimating];
8496
8497 CGRect captrect;
8498 captrect.size.width = [[self view] frame].size.width;
8499 captrect.size.height = 40.0f;
8500 captrect.origin.x = 0;
8501 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8502 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8503 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8504 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8505 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8506 [caption_ setTextColor:[UIColor whiteColor]];
8507 [caption_ setBackgroundColor:[UIColor clearColor]];
8508 [caption_ setShadowColor:[UIColor blackColor]];
8509 [caption_ setTextAlignment:UITextAlignmentCenter];
8510 [[self view] addSubview:caption_];
8511
8512 CGRect statusrect;
8513 statusrect.size.width = [[self view] frame].size.width;
8514 statusrect.size.height = 30.0f;
8515 statusrect.origin.x = 0;
8516 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8517 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8518 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8519 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8520 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8521 [status_ setTextColor:[UIColor whiteColor]];
8522 [status_ setBackgroundColor:[UIColor clearColor]];
8523 [status_ setShadowColor:[UIColor blackColor]];
8524 [status_ setTextAlignment:UITextAlignmentCenter];
8525 [[self view] addSubview:status_];
8526}
8527
8528- (void) releaseSubviews {
8529 spinner_ = nil;
8530 status_ = nil;
8531 caption_ = nil;
8532
8533 [super releaseSubviews];
8534}
8535
8536@end
8537/* }}} */
8538
8539@interface CYURLCache : SDURLCache {
8540}
8541
8542@end
8543
8544@implementation CYURLCache
8545
8546- (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8547#if !ForRelease
8548 if (false);
8549 else if ([event isEqualToString:@"no-cache"])
8550 event = @"!!!";
8551 else if ([event isEqualToString:@"store"])
8552 event = @">>>";
8553 else if ([event isEqualToString:@"invalid"])
8554 event = @"???";
8555 else if ([event isEqualToString:@"memory"])
8556 event = @"mem";
8557 else if ([event isEqualToString:@"disk"])
8558 event = @"ssd";
8559 else if ([event isEqualToString:@"miss"])
8560 event = @"---";
8561
8562 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8563#endif
8564}
8565
8566- (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8567 if (NSURLResponse *response = [cached response])
8568 if (NSString *mime = [response MIMEType])
8569 if ([mime isEqualToString:@"text/cache-manifest"]) {
8570 NSURL *url([response URL]);
8571
8572#if !ForRelease
8573 NSLog(@"###: %@", [url absoluteString]);
8574#endif
8575
8576 @synchronized (HostConfig_) {
8577 [CachedURLs_ addObject:url];
8578 }
8579 }
8580
8581 [super storeCachedResponse:cached forRequest:request];
8582}
8583
8584@end
8585
8586@interface Cydia : UIApplication <
8587 ConfirmationControllerDelegate,
8588 DatabaseDelegate,
8589 CydiaDelegate,
8590 UINavigationControllerDelegate,
8591 UITabBarControllerDelegate
8592> {
8593 _H<UIWindow> window_;
8594 _H<CYTabBarController> tabbar_;
8595 _H<CydiaLoadingViewController> emulated_;
8596
8597 _H<NSMutableArray> essential_;
8598 _H<NSMutableArray> broken_;
8599
8600 Database *database_;
8601
8602 _H<NSURL> starturl_;
8603
8604 unsigned locked_;
8605 unsigned activity_;
8606
8607 _H<StashController> stash_;
8608
8609 bool loaded_;
8610}
8611
8612- (void) loadData;
8613
8614@end
8615
8616@implementation Cydia
8617
8618- (void) beginUpdate {
8619 [tabbar_ beginUpdate];
8620}
8621
8622- (BOOL) updating {
8623 return [tabbar_ updating];
8624}
8625
8626- (void) _loaded {
8627 if ([broken_ count] != 0) {
8628 int count = [broken_ count];
8629
8630 UIAlertView *alert = [[[UIAlertView alloc]
8631 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8632 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8633 delegate:self
8634 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8635 otherButtonTitles:
8636 UCLocalize("TEMPORARY_IGNORE"),
8637 nil
8638 ] autorelease];
8639
8640 [alert setContext:@"fixhalf"];
8641 [alert setNumberOfRows:2];
8642 [alert show];
8643 } else if (!Ignored_ && [essential_ count] != 0) {
8644 int count = [essential_ count];
8645
8646 UIAlertView *alert = [[[UIAlertView alloc]
8647 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8648 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8649 delegate:self
8650 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8651 otherButtonTitles:
8652 UCLocalize("UPGRADE_ESSENTIAL"),
8653 UCLocalize("COMPLETE_UPGRADE"),
8654 nil
8655 ] autorelease];
8656
8657 [alert setContext:@"upgrade"];
8658 [alert show];
8659 }
8660}
8661
8662- (void) _saveConfig {
8663 _trace();
8664 MetaFile_.Sync();
8665 _trace();
8666
8667 if (Changed_) {
8668 NSString *error(nil);
8669
8670 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8671 _trace();
8672 NSError *error(nil);
8673 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8674 NSLog(@"failure to save metadata data: %@", error);
8675 _trace();
8676
8677 Changed_ = false;
8678 } else {
8679 NSLog(@"failure to serialize metadata: %@", error);
8680 }
8681 }
8682}
8683
8684// Navigation controller for the queuing badge.
8685- (UINavigationController *) queueNavigationController {
8686 NSArray *controllers = [tabbar_ viewControllers];
8687 return [controllers objectAtIndex:3];
8688}
8689
8690- (void) unloadData {
8691 [tabbar_ unloadData];
8692}
8693
8694- (void) _updateData {
8695 [self _saveConfig];
8696
8697 [self unloadData];
8698
8699 UINavigationController *navigation = [self queueNavigationController];
8700
8701 id queuedelegate = nil;
8702 if ([[navigation viewControllers] count] > 0)
8703 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8704
8705 [queuedelegate queueStatusDidChange];
8706 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8707}
8708
8709- (void) _refreshIfPossible:(NSDate *)update {
8710 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8711
8712 bool recently = false;
8713 if (update != nil) {
8714 NSTimeInterval interval([update timeIntervalSinceNow]);
8715 if (interval <= 0 && interval > -(15*60))
8716 recently = true;
8717 }
8718
8719 // Don't automatic refresh if:
8720 // - We already refreshed recently.
8721 // - We already auto-refreshed this launch.
8722 // - Auto-refresh is disabled.
8723 if (recently || loaded_ || ManualRefresh) {
8724 // If we are cancelling, we need to make sure it knows it's already loaded.
8725 loaded_ = true;
8726
8727 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8728 } else {
8729 // We are going to load, so remember that.
8730 loaded_ = true;
8731
8732 SCNetworkReachabilityFlags flags; {
8733 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8734 SCNetworkReachabilityGetFlags(reachability, &flags);
8735 CFRelease(reachability);
8736 }
8737
8738 // XXX: this elaborate mess is what Apple is using to determine this? :(
8739 // XXX: do we care if the user has to intervene? maybe that's ok?
8740 bool reachable(
8741 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8742 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8743 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8744 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8745 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8746 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8747 )
8748 );
8749
8750 // If we can reach the server, auto-refresh!
8751 if (reachable)
8752 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8753 }
8754
8755 [pool release];
8756}
8757
8758- (void) refreshIfPossible {
8759 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8760}
8761
8762- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8763@synchronized (self) {
8764 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8765 [hud setText:UCLocalize("RELOADING_DATA")];
8766
8767 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8768
8769 if (hud != nil)
8770 [self removeProgressHUD:hud];
8771
8772 size_t changes(0);
8773
8774 [essential_ removeAllObjects];
8775 [broken_ removeAllObjects];
8776
8777 NSArray *packages([database_ packages]);
8778 for (Package *package in packages) {
8779 if ([package half])
8780 [broken_ addObject:package];
8781 if ([package upgradableAndEssential:NO]) {
8782 if ([package essential])
8783 [essential_ addObject:package];
8784 ++changes;
8785 }
8786 }
8787
8788 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8789 if (changes != 0) {
8790 _trace();
8791 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8792 [changesItem setBadgeValue:badge];
8793 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8794 [self setApplicationIconBadgeNumber:changes];
8795 } else {
8796 _trace();
8797 [changesItem setBadgeValue:nil];
8798 [changesItem setAnimatedBadge:NO];
8799 [self setApplicationIconBadgeNumber:0];
8800 }
8801
8802 [self _updateData];
8803
8804 [self refreshIfPossible];
8805} }
8806
8807- (void) updateData {
8808 [self _updateData];
8809}
8810
8811- (void) update_ {
8812 [database_ update];
8813 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8814}
8815
8816- (void) disemulate {
8817 if (emulated_ == nil)
8818 return;
8819
8820 [window_ addSubview:[tabbar_ view]];
8821 [[emulated_ view] removeFromSuperview];
8822 emulated_ = nil;
8823 [window_ setUserInteractionEnabled:YES];
8824}
8825
8826- (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8827 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8828 if (IsWildcat_)
8829 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8830
8831 UIViewController *parent;
8832 if (emulated_ == nil)
8833 parent = tabbar_;
8834 else if (!force)
8835 parent = emulated_;
8836 else {
8837 [self disemulate];
8838 parent = tabbar_;
8839 }
8840
8841 [parent presentModalViewController:navigation animated:YES];
8842}
8843
8844- (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8845 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8846
8847 if (navigation != nil)
8848 [navigation pushViewController:progress animated:YES];
8849 else
8850 [self presentModalViewController:progress force:YES];
8851
8852 [progress invoke:invocation withTitle:title];
8853 return progress;
8854}
8855
8856- (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8857 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8858}
8859
8860- (void) repairWithInvocation:(NSInvocation *)invocation {
8861 _trace();
8862 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8863 _trace();
8864}
8865
8866- (void) repairWithSelector:(SEL)selector {
8867 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8868}
8869
8870- (void) reloadData {
8871 [self reloadDataWithInvocation:nil];
8872}
8873
8874- (void) syncData {
8875 [self _saveConfig];
8876
8877 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8878 _assert(file != NULL);
8879
8880 for (NSString *key in [Sources_ allKeys]) {
8881 NSDictionary *source([Sources_ objectForKey:key]);
8882
8883 fprintf(file, "%s %s %s\n",
8884 [[source objectForKey:@"Type"] UTF8String],
8885 [[source objectForKey:@"URI"] UTF8String],
8886 [[source objectForKey:@"Distribution"] UTF8String]
8887 );
8888 }
8889
8890 fclose(file);
8891
8892 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8893}
8894
8895- (void) addTrivialSource:(NSString *)href {
8896 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8897 @"deb", @"Type",
8898 href, @"URI",
8899 @"./", @"Distribution",
8900 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8901
8902 Changed_ = true;
8903}
8904
8905- (void) resolve {
8906 pkgProblemResolver *resolver = [database_ resolver];
8907
8908 resolver->InstallProtect();
8909 if (!resolver->Resolve(true))
8910 _error->Discard();
8911}
8912
8913- (bool) perform {
8914 // XXX: this is a really crappy way of doing this.
8915 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8916 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8917 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8918 if ([tabbar_ updating])
8919 [tabbar_ cancelUpdate];
8920
8921 if (![database_ prepare])
8922 return false;
8923
8924 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8925 [page setDelegate:self];
8926 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8927
8928 if (IsWildcat_)
8929 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8930 [tabbar_ presentModalViewController:confirm_ animated:YES];
8931
8932 return true;
8933}
8934
8935- (void) queue {
8936 @synchronized (self) {
8937 [self perform];
8938 }
8939}
8940
8941- (void) clearPackage:(Package *)package {
8942 @synchronized (self) {
8943 [package clear];
8944 [self resolve];
8945 [self perform];
8946 }
8947}
8948
8949- (void) installPackages:(NSArray *)packages {
8950 @synchronized (self) {
8951 for (Package *package in packages)
8952 [package install];
8953 [self resolve];
8954 [self perform];
8955 }
8956}
8957
8958- (void) installPackage:(Package *)package {
8959 @synchronized (self) {
8960 [package install];
8961 [self resolve];
8962 [self perform];
8963 }
8964}
8965
8966- (void) removePackage:(Package *)package {
8967 @synchronized (self) {
8968 [package remove];
8969 [self resolve];
8970 [self perform];
8971 }
8972}
8973
8974- (void) distUpgrade {
8975 @synchronized (self) {
8976 if (![database_ upgrade])
8977 return;
8978 [self perform];
8979 }
8980}
8981
8982- (void) perform_ {
8983 [database_ perform];
8984 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8985}
8986
8987- (void) confirmWithNavigationController:(UINavigationController *)navigation {
8988 Queuing_ = false;
8989 ++locked_;
8990 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8991 --locked_;
8992}
8993
8994- (void) showSettings {
8995 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8996}
8997
8998- (void) retainNetworkActivityIndicator {
8999 if (activity_++ == 0)
9000 [self setNetworkActivityIndicatorVisible:YES];
9001
9002#if TraceLogging
9003 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9004#endif
9005}
9006
9007- (void) releaseNetworkActivityIndicator {
9008 if (--activity_ == 0)
9009 [self setNetworkActivityIndicatorVisible:NO];
9010
9011#if TraceLogging
9012 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9013#endif
9014
9015}
9016
9017- (void) cancelAndClear:(bool)clear {
9018 @synchronized (self) {
9019 if (clear) {
9020 [database_ clear];
9021 Queuing_ = false;
9022 } else {
9023 Queuing_ = true;
9024 }
9025
9026 [self _updateData];
9027 }
9028}
9029
9030- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9031 NSString *context([alert context]);
9032
9033 if ([context isEqualToString:@"conffile"]) {
9034 FILE *input = [database_ input];
9035 if (button == [alert cancelButtonIndex])
9036 fprintf(input, "N\n");
9037 else if (button == [alert firstOtherButtonIndex])
9038 fprintf(input, "Y\n");
9039 fflush(input);
9040
9041 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9042 } else if ([context isEqualToString:@"fixhalf"]) {
9043 if (button == [alert cancelButtonIndex]) {
9044 @synchronized (self) {
9045 for (Package *broken in (id) broken_) {
9046 [broken remove];
9047
9048 NSString *id = [broken id];
9049 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9050 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9051 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9052 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9053 }
9054
9055 [self resolve];
9056 [self perform];
9057 }
9058 } else if (button == [alert firstOtherButtonIndex]) {
9059 [broken_ removeAllObjects];
9060 [self _loaded];
9061 }
9062
9063 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9064 } else if ([context isEqualToString:@"upgrade"]) {
9065 if (button == [alert firstOtherButtonIndex]) {
9066 @synchronized (self) {
9067 for (Package *essential in (id) essential_)
9068 [essential install];
9069
9070 [self resolve];
9071 [self perform];
9072 }
9073 } else if (button == [alert firstOtherButtonIndex] + 1) {
9074 [self distUpgrade];
9075 } else if (button == [alert cancelButtonIndex]) {
9076 Ignored_ = YES;
9077 }
9078
9079 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9080 }
9081}
9082
9083- (void) system:(NSString *)command {
9084 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9085
9086 _trace();
9087 system([command UTF8String]);
9088 _trace();
9089
9090 [pool release];
9091}
9092
9093- (void) applicationWillSuspend {
9094 [database_ clean];
9095 [super applicationWillSuspend];
9096}
9097
9098- (BOOL) isSafeToSuspend {
9099 if (locked_ != 0) {
9100#if !ForRelease
9101 NSLog(@"isSafeToSuspend: locked_ != 0");
9102#endif
9103 return false;
9104 }
9105
9106 // Use external process status API internally.
9107 // This is probably a really bad idea.
9108 // XXX: what is the point of this? does this solve anything at all?
9109 uint64_t status = 0;
9110 int notify_token;
9111 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9112 notify_get_state(notify_token, &status);
9113 notify_cancel(notify_token);
9114 }
9115
9116 if (status != 0) {
9117#if !ForRelease
9118 NSLog(@"isSafeToSuspend: status != 0");
9119#endif
9120 return false;
9121 }
9122
9123#if !ForRelease
9124 NSLog(@"isSafeToSuspend: -> true");
9125#endif
9126 return true;
9127}
9128
9129- (void) applicationSuspend:(__GSEvent *)event {
9130 if ([self isSafeToSuspend])
9131 [super applicationSuspend:event];
9132}
9133
9134- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9135 if ([self isSafeToSuspend])
9136 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9137}
9138
9139- (void) _setSuspended:(BOOL)value {
9140 if ([self isSafeToSuspend])
9141 [super _setSuspended:value];
9142}
9143
9144- (UIProgressHUD *) addProgressHUD {
9145 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9146 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9147
9148 [window_ setUserInteractionEnabled:NO];
9149
9150 UIViewController *target(tabbar_);
9151 if (UIViewController *modal = [target modalViewController])
9152 target = modal;
9153
9154 UIView *view([target view]);
9155 [view addSubview:hud];
9156
9157 [hud show:YES];
9158
9159 ++locked_;
9160 return hud;
9161}
9162
9163- (void) removeProgressHUD:(UIProgressHUD *)hud {
9164 --locked_;
9165 [hud show:NO];
9166 [hud removeFromSuperview];
9167 [window_ setUserInteractionEnabled:YES];
9168}
9169
9170- (CyteViewController *) pageForPackage:(NSString *)name {
9171 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9172}
9173
9174- (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9175 NSString *scheme([[url scheme] lowercaseString]);
9176 if ([[url absoluteString] length] <= [scheme length] + 3)
9177 return nil;
9178 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9179 NSArray *components([path pathComponents]);
9180
9181 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9182 return [self pageForPackage:[components objectAtIndex:1]];
9183
9184 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9185 return nil;
9186
9187 NSString *base([components objectAtIndex:0]);
9188
9189 CyteViewController *controller = nil;
9190
9191 if ([base isEqualToString:@"url"]) {
9192 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9193 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9194 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9195 } else if (!external && [components count] == 1) {
9196 if ([base isEqualToString:@"manage"]) {
9197 controller = [[[ManageController alloc] init] autorelease];
9198 }
9199
9200 if ([base isEqualToString:@"sources"]) {
9201 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9202 }
9203
9204 if ([base isEqualToString:@"home"]) {
9205 controller = [[[HomeController alloc] init] autorelease];
9206 }
9207
9208 if ([base isEqualToString:@"sections"]) {
9209 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9210 }
9211
9212 if ([base isEqualToString:@"search"]) {
9213 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9214 }
9215
9216 if ([base isEqualToString:@"changes"]) {
9217 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9218 }
9219
9220 if ([base isEqualToString:@"installed"]) {
9221 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9222 }
9223 } else if ([components count] == 2) {
9224 NSString *argument = [components objectAtIndex:1];
9225
9226 if ([base isEqualToString:@"package"]) {
9227 controller = [self pageForPackage:argument];
9228 }
9229
9230 if (!external && [base isEqualToString:@"search"]) {
9231 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9232 }
9233
9234 if (!external && [base isEqualToString:@"sections"]) {
9235 if ([argument isEqualToString:@"all"])
9236 argument = nil;
9237 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9238 }
9239
9240 if (!external && [base isEqualToString:@"sources"]) {
9241 if ([argument isEqualToString:@"add"]) {
9242 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9243 [(SourcesController *)controller showAddSourcePrompt];
9244 } else {
9245 Source *source = [database_ sourceWithKey:argument];
9246 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9247 }
9248 }
9249
9250 if (!external && [base isEqualToString:@"launch"]) {
9251 [self launchApplicationWithIdentifier:argument suspended:NO];
9252 return nil;
9253 }
9254 } else if (!external && [components count] == 3) {
9255 NSString *arg1 = [components objectAtIndex:1];
9256 NSString *arg2 = [components objectAtIndex:2];
9257
9258 if ([base isEqualToString:@"package"]) {
9259 if ([arg2 isEqualToString:@"settings"]) {
9260 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9261 } else if ([arg2 isEqualToString:@"files"]) {
9262 if (Package *package = [database_ packageWithName:arg1]) {
9263 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9264 [(FileTable *)controller setPackage:package];
9265 }
9266 }
9267 }
9268 }
9269
9270 [controller setDelegate:self];
9271 return controller;
9272}
9273
9274- (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9275 CyteViewController *page([self pageForURL:url forExternal:external]);
9276
9277 if (page != nil) {
9278 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9279 [nav setViewControllers:[NSArray arrayWithObject:page]];
9280 [tabbar_ setUnselectedViewController:nav];
9281 }
9282
9283 return page != nil;
9284}
9285
9286- (void) applicationOpenURL:(NSURL *)url {
9287 [super applicationOpenURL:url];
9288
9289 if (!loaded_)
9290 starturl_ = url;
9291 else
9292 [self openCydiaURL:url forExternal:YES];
9293}
9294
9295- (void) applicationWillResignActive:(UIApplication *)application {
9296 // Stop refreshing if you get a phone call or lock the device.
9297 if ([tabbar_ updating])
9298 [tabbar_ cancelUpdate];
9299
9300 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9301 [super applicationWillResignActive:application];
9302}
9303
9304- (void) applicationWillTerminate:(UIApplication *)application {
9305 Changed_ = true;
9306 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9307 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9308 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9309
9310 [self _saveConfig];
9311}
9312
9313- (void) setConfigurationData:(NSString *)data {
9314 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9315
9316 if (!conffile_r(data)) {
9317 lprintf("E:invalid conffile\n");
9318 return;
9319 }
9320
9321 NSString *ofile = conffile_r[1];
9322 //NSString *nfile = conffile_r[2];
9323
9324 UIAlertView *alert = [[[UIAlertView alloc]
9325 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9326 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9327 delegate:self
9328 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9329 otherButtonTitles:
9330 UCLocalize("ACCEPT_NEW_COPY"),
9331 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9332 nil
9333 ] autorelease];
9334
9335 [alert setContext:@"conffile"];
9336 [alert setNumberOfRows:2];
9337 [alert show];
9338}
9339
9340- (void) addStashController {
9341 ++locked_;
9342 stash_ = [[[StashController alloc] init] autorelease];
9343 [window_ addSubview:[stash_ view]];
9344}
9345
9346- (void) removeStashController {
9347 [[stash_ view] removeFromSuperview];
9348 stash_ = nil;
9349 --locked_;
9350}
9351
9352- (void) stash {
9353 [self setIdleTimerDisabled:YES];
9354
9355 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9356 UpdateExternalStatus(1);
9357 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9358 UpdateExternalStatus(0);
9359
9360 [self removeStashController];
9361
9362 if (ExecFork() == 0) {
9363 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9364 perror("launchctl stop");
9365 }
9366}
9367
9368- (void) setupViewControllers {
9369 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9370
9371 NSMutableArray *items([NSMutableArray arrayWithObjects:
9372 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9373 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9374 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9375 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9376 nil]);
9377
9378 if (IsWildcat_) {
9379 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9380 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9381 } else {
9382 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9383 }
9384
9385 NSMutableArray *controllers([NSMutableArray array]);
9386 for (UITabBarItem *item in items) {
9387 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9388 [controller setTabBarItem:item];
9389 [controllers addObject:controller];
9390 }
9391 [tabbar_ setViewControllers:controllers];
9392
9393 [tabbar_ setUpdateDelegate:self];
9394}
9395
9396- (void) applicationDidFinishLaunching:(id)unused {
9397_trace();
9398 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9399 [self setApplicationSupportsShakeToEdit:NO];
9400
9401 @synchronized (HostConfig_) {
9402 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9403 }
9404
9405 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9406 initWithMemoryCapacity:524288
9407 diskCapacity:10485760
9408 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9409 ] autorelease]];
9410
9411 [CydiaWebViewController _initialize];
9412
9413 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9414
9415 // this would disallow http{,s} URLs from accessing this data
9416 //[WebView registerURLSchemeAsLocal:@"cydia"];
9417
9418 Font12_ = [UIFont systemFontOfSize:12];
9419 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9420 Font14_ = [UIFont systemFontOfSize:14];
9421 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9422 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9423
9424 essential_ = [NSMutableArray arrayWithCapacity:4];
9425 broken_ = [NSMutableArray arrayWithCapacity:4];
9426
9427 // XXX: I really need this thing... like, seriously... I'm sorry
9428 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9429
9430 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9431 [window_ orderFront:self];
9432 [window_ makeKey:self];
9433 [window_ setHidden:NO];
9434
9435 if (
9436 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9437 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9438 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9439 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9440 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9441 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9442 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9443 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9444 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9445 false
9446 ) {
9447 [self addStashController];
9448 // XXX: this would be much cleaner as a yieldToSelector:
9449 // that way the removeStashController could happen right here inline
9450 // we also could no longer require the useless stash_ field anymore
9451 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9452 return;
9453 }
9454
9455 database_ = [Database sharedInstance];
9456 [database_ setDelegate:self];
9457
9458 [window_ setUserInteractionEnabled:NO];
9459 [self setupViewControllers];
9460
9461 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9462 [window_ addSubview:[emulated_ view]];
9463
9464 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9465_trace();
9466}
9467
9468- (NSArray *) defaultStartPages {
9469 NSMutableArray *standard = [NSMutableArray array];
9470 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9471 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9472 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9473 if (!IsWildcat_) {
9474 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9475 } else {
9476 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9477 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9478 }
9479 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9480 return standard;
9481}
9482
9483- (void) loadData {
9484_trace();
9485 if (Role_ == nil) {
9486 [window_ setUserInteractionEnabled:YES];
9487 [self showSettings];
9488 return;
9489 } else {
9490 if ([emulated_ modalViewController] != nil)
9491 [emulated_ dismissModalViewControllerAnimated:YES];
9492 [window_ setUserInteractionEnabled:NO];
9493 }
9494
9495 [self reloadData];
9496 PrintTimes();
9497
9498 [self disemulate];
9499
9500 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9501 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9502 int standardIndex = 0;
9503 NSArray *standard = [self defaultStartPages];
9504
9505 BOOL valid = YES;
9506
9507 if (saved == nil)
9508 valid = NO;
9509
9510 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9511 if (valid && closed != nil) {
9512 NSTimeInterval interval([closed timeIntervalSinceNow]);
9513 // XXX: Is 15 minutes the optimal time here?
9514 if (interval > 0 && interval <= -(15*60))
9515 valid = NO;
9516 }
9517
9518 if (valid && [saved count] != [standard count])
9519 valid = NO;
9520
9521 if (valid) {
9522 for (unsigned int i = 0; i < [standard count]; i++) {
9523 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9524 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9525 // but it's good enough for now.
9526 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9527 valid = NO;
9528 break;
9529 }
9530 }
9531 }
9532
9533 NSArray *items = nil;
9534 if (valid) {
9535 [tabbar_ setSelectedIndex:savedIndex];
9536 items = saved;
9537 } else {
9538 [tabbar_ setSelectedIndex:standardIndex];
9539 items = standard;
9540 }
9541
9542 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9543 NSArray *stack = [items objectAtIndex:tab];
9544 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9545 NSMutableArray *current = [NSMutableArray array];
9546
9547 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9548 NSString *addr = [stack objectAtIndex:nav];
9549 NSURL *url = [NSURL URLWithString:addr];
9550 CyteViewController *page = [self pageForURL:url forExternal:NO];
9551 if (page != nil)
9552 [current addObject:page];
9553 }
9554
9555 [navigation setViewControllers:current];
9556 }
9557
9558 // (Try to) show the startup URL.
9559 if (starturl_ != nil) {
9560 [self openCydiaURL:starturl_ forExternal:NO];
9561 starturl_ = nil;
9562 }
9563}
9564
9565- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9566 if (item != nil && IsWildcat_) {
9567 [sheet showFromBarButtonItem:item animated:YES];
9568 } else {
9569 [sheet showInView:window_];
9570 }
9571}
9572
9573- (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9574 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9575 [progress setTitle:task];
9576 [progress addProgressEvent:event];
9577}
9578
9579- (void) addProgressEventForTask:(NSArray *)data {
9580 CydiaProgressEvent *event([data objectAtIndex:0]);
9581 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9582 [self addProgressEvent:event forTask:task];
9583}
9584
9585- (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9586 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9587}
9588
9589@end
9590
9591/*IMP alloc_;
9592id Alloc_(id self, SEL selector) {
9593 id object = alloc_(self, selector);
9594 lprintf("[%s]A-%p\n", self->isa->name, object);
9595 return object;
9596}*/
9597
9598/*IMP dealloc_;
9599id Dealloc_(id self, SEL selector) {
9600 id object = dealloc_(self, selector);
9601 lprintf("[%s]D-%p\n", self->isa->name, object);
9602 return object;
9603}*/
9604
9605Class $WebDefaultUIKitDelegate;
9606
9607MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9608 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9609 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9610 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9611}
9612
9613static NSSet *MobilizedFiles_;
9614
9615static NSURL *MobilizeURL(NSURL *url) {
9616 NSString *path([url path]);
9617 if ([path hasPrefix:@"/var/root/"]) {
9618 NSString *file([path substringFromIndex:10]);
9619 if ([MobilizedFiles_ containsObject:file])
9620 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9621 }
9622
9623 return url;
9624}
9625
9626Class $CFXPreferencesPropertyListSource;
9627@class CFXPreferencesPropertyListSource;
9628
9629MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9630 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9631 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9632 url = MobilizeURL(url);
9633 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9634 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9635 url = old;
9636 [pool release];
9637 return value;
9638}
9639
9640MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9641 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9642 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9643 url = MobilizeURL(url);
9644 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9645 //NSLog(@"%@ %@", [url absoluteString], value);
9646 url = old;
9647 [pool release];
9648 return value;
9649}
9650
9651Class $NSURLConnection;
9652
9653MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9654 NSMutableURLRequest *copy([request mutableCopy]);
9655
9656 NSURL *url([copy URL]);
9657
9658 NSString *href([url absoluteString]);
9659 NSString *host([url host]);
9660 NSString *scheme([[url scheme] lowercaseString]);
9661
9662 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9663
9664 @synchronized (HostConfig_) {
9665 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9666 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9667 [copy setHTTPShouldUsePipelining:YES];
9668
9669 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9670 if ([control isEqualToString:@"max-age=0"])
9671 if ([CachedURLs_ containsObject:href]) {
9672#if !ForRelease
9673 NSLog(@"~~~: %@", href);
9674#endif
9675
9676 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9677
9678 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9679 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9680 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9681 }
9682 }
9683
9684 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9685 } return self;
9686}
9687
9688int main(int argc, char *argv[]) {
9689 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9690
9691 _trace();
9692
9693 UpdateExternalStatus(0);
9694
9695 if (Class $UIDevice = objc_getClass("UIDevice")) {
9696 UIDevice *device([$UIDevice currentDevice]);
9697 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9698 } else
9699 IsWildcat_ = false;
9700
9701 UIScreen *screen([UIScreen mainScreen]);
9702 if ([screen respondsToSelector:@selector(scale)])
9703 ScreenScale_ = [screen scale];
9704 else
9705 ScreenScale_ = 1;
9706
9707 UIDevice *device([UIDevice currentDevice]);
9708 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9709 Idiom_ = @"iphone";
9710 else {
9711 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9712 if (idiom == UIUserInterfaceIdiomPhone)
9713 Idiom_ = @"iphone";
9714 else if (idiom == UIUserInterfaceIdiomPad)
9715 Idiom_ = @"ipad";
9716 else
9717 NSLog(@"unknown UIUserInterfaceIdiom!");
9718 }
9719
9720 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9721
9722 HostConfig_ = [[[NSObject alloc] init] autorelease];
9723 @synchronized (HostConfig_) {
9724 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9725 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9726 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9727 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9728 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9729 }
9730
9731 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9732
9733 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9734
9735 MobilizedFiles_ = [NSMutableSet setWithObjects:
9736 @"Library/Preferences/com.apple.Accessibility.plist",
9737 @"Library/Preferences/com.apple.preferences.sounds.plist",
9738 nil];
9739
9740 /* Library Hacks {{{ */
9741 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9742
9743 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9744
9745 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9746 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9747 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9748 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9749 }
9750
9751 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9752 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9753 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9754 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9755 }
9756
9757 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9758 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9759 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9760 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9761 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9762 }
9763
9764 $NSURLConnection = objc_getClass("NSURLConnection");
9765 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9766 if (NSURLConnection$init$ != NULL) {
9767 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9768 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9769 }
9770 /* }}} */
9771 /* Set Locale {{{ */
9772 Locale_ = CFLocaleCopyCurrent();
9773 Languages_ = [NSLocale preferredLanguages];
9774
9775 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9776 //NSLog(@"%@", [Languages_ description]);
9777
9778 const char *lang;
9779 if (Locale_ != NULL)
9780 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9781 else if (Languages_ != nil && [Languages_ count] != 0)
9782 lang = [[Languages_ objectAtIndex:0] UTF8String];
9783 else
9784 // XXX: consider just setting to C and then falling through?
9785 lang = NULL;
9786
9787 if (lang != NULL) {
9788 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9789 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9790 }
9791
9792 NSLog(@"Setting Language: %s", lang);
9793
9794 if (lang != NULL) {
9795 setenv("LANG", lang, true);
9796 std::setlocale(LC_ALL, lang);
9797 }
9798 /* }}} */
9799
9800 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9801
9802 /* Parse Arguments {{{ */
9803 bool substrate(false);
9804
9805 if (argc != 0) {
9806 char **args(argv);
9807 int arge(1);
9808
9809 for (int argi(1); argi != argc; ++argi)
9810 if (strcmp(argv[argi], "--") == 0) {
9811 arge = argi;
9812 argv[argi] = argv[0];
9813 argv += argi;
9814 argc -= argi;
9815 break;
9816 }
9817
9818 for (int argi(1); argi != arge; ++argi)
9819 if (strcmp(args[argi], "--substrate") == 0)
9820 substrate = true;
9821 else
9822 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9823 }
9824 /* }}} */
9825
9826 App_ = [[NSBundle mainBundle] bundlePath];
9827 Advanced_ = YES;
9828
9829 setuid(0);
9830 setgid(0);
9831
9832 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9833 alloc_ = alloc->method_imp;
9834 alloc->method_imp = (IMP) &Alloc_;*/
9835
9836 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9837 dealloc_ = dealloc->method_imp;
9838 dealloc->method_imp = (IMP) &Dealloc_;*/
9839
9840 /* System Information {{{ */
9841 size_t size;
9842
9843 int maxproc;
9844 size = sizeof(maxproc);
9845 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9846 perror("sysctlbyname(\"kern.maxproc\", ?)");
9847 else if (maxproc < 64) {
9848 maxproc = 64;
9849 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9850 perror("sysctlbyname(\"kern.maxproc\", #)");
9851 }
9852
9853 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9854 char *osversion = new char[size];
9855 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9856 perror("sysctlbyname(\"kern.osversion\", ?)");
9857 else
9858 System_ = [NSString stringWithUTF8String:osversion];
9859
9860 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9861 char *machine = new char[size];
9862 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9863 perror("sysctlbyname(\"hw.machine\", ?)");
9864 else
9865 Machine_ = machine;
9866
9867 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9868 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9869 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9870
9871 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9872
9873 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9874 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9875 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9876
9877 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9878 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9879 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9880
9881 if (mcc != NULL && mnc != NULL)
9882 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9883
9884 if (mnc != NULL)
9885 CFRelease(mnc);
9886 if (mcc != NULL)
9887 CFRelease(mcc);
9888
9889 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9890 Build_ = [system objectForKey:@"ProductBuildVersion"];
9891 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9892 Product_ = [info objectForKey:@"SafariProductVersion"];
9893 Safari_ = [info objectForKey:@"CFBundleVersion"];
9894 }
9895 /* }}} */
9896 /* Load Database {{{ */
9897 _trace();
9898 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9899 _trace();
9900 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9901
9902 if (Metadata_ == NULL)
9903 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9904 else {
9905 Settings_ = [Metadata_ objectForKey:@"Settings"];
9906
9907 Packages_ = [Metadata_ objectForKey:@"Packages"];
9908 Sections_ = [Metadata_ objectForKey:@"Sections"];
9909 Sources_ = [Metadata_ objectForKey:@"Sources"];
9910
9911 Token_ = [Metadata_ objectForKey:@"Token"];
9912 }
9913
9914 if (Settings_ != nil)
9915 Role_ = [Settings_ objectForKey:@"Role"];
9916
9917 if (Sections_ == nil) {
9918 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9919 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9920 }
9921
9922 if (Sources_ == nil) {
9923 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9924 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9925 }
9926 /* }}} */
9927
9928 _trace();
9929 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9930 _trace();
9931
9932 if (Packages_ != nil) {
9933 bool fail(false);
9934 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9935 _trace();
9936
9937 if (!fail) {
9938 [Metadata_ removeObjectForKey:@"Packages"];
9939 Packages_ = nil;
9940 Changed_ = true;
9941 }
9942 }
9943
9944 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9945
9946#define MobileSubstrate_(name) \
9947 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9948 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9949 if (handle == NULL) \
9950 NSLog(@"%s", dlerror()); \
9951 }
9952
9953 MobileSubstrate_(Activator)
9954 MobileSubstrate_(libstatusbar)
9955 MobileSubstrate_(SimulatedKeyEvents)
9956 MobileSubstrate_(WinterBoard)
9957
9958 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9959 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9960
9961 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9962
9963 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9964 unlink("/tmp/.cydia.fw");
9965 goto firmware;
9966 } else if (access("/User", F_OK) != 0 || version < 4) {
9967 firmware:
9968 _trace();
9969 system("/usr/libexec/cydia/firmware.sh");
9970 _trace();
9971 }
9972
9973 _assert([[NSFileManager defaultManager]
9974 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9975 withIntermediateDirectories:YES
9976 attributes:nil
9977 error:NULL
9978 ]);
9979
9980 if (access("/tmp/cydia.chk", F_OK) == 0) {
9981 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9982 _assert(errno == ENOENT);
9983 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9984 _assert(errno == ENOENT);
9985 }
9986
9987 /* APT Initialization {{{ */
9988 _assert(pkgInitConfig(*_config));
9989 _assert(pkgInitSystem(*_config, _system));
9990
9991 if (lang != NULL)
9992 _config->Set("APT::Acquire::Translation", lang);
9993
9994 // XXX: this timeout might be important :(
9995 //_config->Set("Acquire::http::Timeout", 15);
9996
9997 _config->Set("Acquire::http::MaxParallel", 3);
9998 /* }}} */
9999 /* Color Choices {{{ */
10000 space_ = CGColorSpaceCreateDeviceRGB();
10001
10002 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10003 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10004 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10005 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10006 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10007 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10008 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10009 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10010 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10011
10012 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10013 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10014 /* }}}*/
10015 /* UIKit Configuration {{{ */
10016 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10017 if ($GSFontSetUseLegacyFontMetrics != NULL)
10018 $GSFontSetUseLegacyFontMetrics(YES);
10019
10020 // XXX: I have a feeling this was important
10021 //UIKeyboardDisableAutomaticAppearance();
10022 /* }}} */
10023
10024 Colon_ = UCLocalize("COLON_DELIMITED");
10025 Elision_ = UCLocalize("ELISION");
10026 Error_ = UCLocalize("ERROR");
10027 Warning_ = UCLocalize("WARNING");
10028
10029 _trace();
10030 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10031
10032 CGColorSpaceRelease(space_);
10033 CFRelease(Locale_);
10034
10035 [pool release];
10036 return value;
10037}