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