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