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