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