]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Add cydia.setScrollIndicatorStyle().
[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(setScrollIndicatorStyle:))
4117 return @"setScrollIndicatorStyle";
4118 else if (selector == @selector(setToken:))
4119 return @"setToken";
4120 else if (selector == @selector(setViewportWidth:))
4121 return @"setViewportWidth";
4122 else if (selector == @selector(statfs:))
4123 return @"statfs";
4124 else if (selector == @selector(supports:))
4125 return @"supports";
4126 else if (selector == @selector(unload))
4127 return @"unload";
4128 else
4129 return nil;
4130 }
4131
4132 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4133 return [self webScriptNameForSelector:selector] == nil;
4134 }
4135
4136 - (BOOL) supports:(NSString *)feature {
4137 return [feature isEqualToString:@"window.open"];
4138 }
4139
4140 - (void) unload {
4141 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4142 }
4143
4144 - (void) setScrollIndicatorStyle:(NSString *)style {
4145 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4146 }
4147
4148 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4149 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4150 }
4151
4152 - (NSNumber *) getKernelNumber:(NSString *)name {
4153 const char *string([name UTF8String]);
4154
4155 size_t size;
4156 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4157 return (id) [NSNull null];
4158
4159 if (size != sizeof(int))
4160 return (id) [NSNull null];
4161
4162 int value;
4163 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4164 return (id) [NSNull null];
4165
4166 return [NSNumber numberWithInt:value];
4167 }
4168
4169 - (NSString *) getKernelString:(NSString *)name {
4170 const char *string([name UTF8String]);
4171
4172 size_t size;
4173 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4174 return (id) [NSNull null];
4175
4176 char value[size + 1];
4177 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4178 return (id) [NSNull null];
4179
4180 // XXX: just in case you request something ludicrous
4181 value[size] = '\0';
4182
4183 return [NSString stringWithCString:value];
4184 }
4185
4186 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4187 NSObject *value(CYIOGetValue([path UTF8String], entry));
4188
4189 if (value != nil)
4190 if ([value isKindOfClass:[NSData class]])
4191 value = CYHex((NSData *) value);
4192
4193 return value;
4194 }
4195
4196 - (void) _setCydiaSource:(NSString *)source {
4197 @synchronized (HostConfig_) {
4198 CydiaSource_ = source;
4199 [Metadata_ setObject:source forKey:@"CydiaSource"];
4200 }
4201
4202 Changed_ = true;
4203 }
4204
4205 - (void) setCydiaSource:(NSString *)source {
4206 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4207 }
4208
4209 - (NSString *) cydiaSource {
4210 @synchronized (HostConfig_) {
4211 return (id) CydiaSource_ ?: [NSNull null];
4212 }
4213 }
4214
4215 - (NSArray *) getMetadataKeys {
4216 @synchronized (Values_) {
4217 return [Values_ allKeys];
4218 } }
4219
4220 - (id) getMetadataValue:(NSString *)key {
4221 @synchronized (Values_) {
4222 return [Values_ objectForKey:key];
4223 } }
4224
4225 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4226 @synchronized (Values_) {
4227 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4228 [Values_ removeObjectForKey:key];
4229 else
4230 [Values_ setObject:value forKey:key];
4231
4232 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4233 } }
4234
4235 - (id) getSessionValue:(NSString *)key {
4236 @synchronized (SessionData_) {
4237 return [SessionData_ objectForKey:key];
4238 } }
4239
4240 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4241 @synchronized (SessionData_) {
4242 if (value == (id) [WebUndefined undefined])
4243 [SessionData_ removeObjectForKey:key];
4244 else
4245 [SessionData_ setObject:value forKey:key];
4246 } }
4247
4248 - (void) addBridgedHost:(NSString *)host {
4249 @synchronized (HostConfig_) {
4250 [BridgedHosts_ addObject:host];
4251 } }
4252
4253 - (void) addInsecureHost:(NSString *)host {
4254 @synchronized (HostConfig_) {
4255 [InsecureHosts_ addObject:host];
4256 } }
4257
4258 - (void) addTokenHost:(NSString *)host {
4259 @synchronized (HostConfig_) {
4260 [TokenHosts_ addObject:host];
4261 } }
4262
4263 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4264 @synchronized (HostConfig_) {
4265 if (scheme != (id) [WebUndefined undefined])
4266 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4267
4268 [PipelinedHosts_ addObject:host];
4269 } }
4270
4271 - (void) popViewController:(NSNumber *)value {
4272 if (value == (id) [WebUndefined undefined])
4273 value = [NSNumber numberWithBool:YES];
4274 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4275 }
4276
4277 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4278 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4279
4280 for (NSString *section in sections)
4281 [array addObject:section];
4282
4283 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4284 @"deb", @"Type",
4285 href, @"URI",
4286 distribution, @"Distribution",
4287 array, @"Sections",
4288 nil] waitUntilDone:NO];
4289 }
4290
4291 - (void) addTrivialSource:(NSString *)href {
4292 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4293 }
4294
4295 - (void) refreshSources {
4296 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4297 }
4298
4299 - (void) saveConfig {
4300 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4301 }
4302
4303 - (NSArray *) getAllSources {
4304 return [[Database sharedInstance] sources];
4305 }
4306
4307 - (NSArray *) getInstalledPackages {
4308 Database *database([Database sharedInstance]);
4309 @synchronized (database) {
4310 NSArray *packages([database packages]);
4311 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4312 for (Package *package in packages)
4313 if (![package uninstalled])
4314 [installed addObject:package];
4315 return installed;
4316 } }
4317
4318 - (Package *) getPackageById:(NSString *)id {
4319 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4320 [package parse];
4321 return package;
4322 } else
4323 return (Package *) [NSNull null];
4324 }
4325
4326 - (NSString *) getLocaleIdentifier {
4327 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4328 }
4329
4330 - (NSArray *) getPreferredLanguages {
4331 return Languages_;
4332 }
4333
4334 - (NSArray *) statfs:(NSString *)path {
4335 struct statfs stat;
4336
4337 if (path == nil || statfs([path UTF8String], &stat) == -1)
4338 return nil;
4339
4340 return [NSArray arrayWithObjects:
4341 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4342 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4343 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4344 nil];
4345 }
4346
4347 - (NSNumber *) du:(NSString *)path {
4348 NSNumber *value(nil);
4349
4350 int fds[2];
4351 _assert(pipe(fds) != -1);
4352
4353 pid_t pid(ExecFork());
4354 if (pid == 0) {
4355 _assert(dup2(fds[1], 1) != -1);
4356 _assert(close(fds[0]) != -1);
4357 _assert(close(fds[1]) != -1);
4358 /* XXX: this should probably not use du */
4359 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4360 exit(1);
4361 _assert(false);
4362 }
4363
4364 _assert(close(fds[1]) != -1);
4365
4366 if (FILE *du = fdopen(fds[0], "r")) {
4367 char line[1024];
4368 while (fgets(line, sizeof(line), du) != NULL) {
4369 size_t length(strlen(line));
4370 while (length != 0 && line[length - 1] == '\n')
4371 line[--length] = '\0';
4372 if (char *tab = strchr(line, '\t')) {
4373 *tab = '\0';
4374 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4375 }
4376 }
4377
4378 fclose(du);
4379 } else _assert(close(fds[0]));
4380
4381 ReapZombie(pid);
4382
4383 return value;
4384 }
4385
4386 - (void) close {
4387 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4388 }
4389
4390 - (void) installPackages:(NSArray *)packages {
4391 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4392 }
4393
4394 - (NSString *) substitutePackageNames:(NSString *)message {
4395 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4396 for (size_t i(0), e([words count]); i != e; ++i) {
4397 NSString *word([words objectAtIndex:i]);
4398 if (Package *package = [[Database sharedInstance] packageWithName:word])
4399 [words replaceObjectAtIndex:i withObject:[package name]];
4400 }
4401
4402 return [words componentsJoinedByString:@" "];
4403 }
4404
4405 - (void) removeButton {
4406 [indirect_ removeButton];
4407 }
4408
4409 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4410 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4411 }
4412
4413 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4414 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4415 }
4416
4417 - (void) setBadgeValue:(id)value {
4418 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4419 }
4420
4421 - (void) setAllowsNavigationAction:(NSString *)value {
4422 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4423 }
4424
4425 - (void) setHidesBackButton:(NSString *)value {
4426 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4427 }
4428
4429 - (void) setHidesNavigationBar:(NSString *)value {
4430 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4431 }
4432
4433 - (void) setNavigationBarStyle:(NSString *)value {
4434 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4435 }
4436
4437 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4438 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4439 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4440 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4441 }
4442
4443 - (void) setPasteboardString:(NSString *)value {
4444 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4445 }
4446
4447 - (void) setPasteboardURL:(NSString *)value {
4448 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4449 }
4450
4451 - (void) _setToken:(NSString *)token {
4452 Token_ = token;
4453
4454 if (token == nil)
4455 [Metadata_ removeObjectForKey:@"Token"];
4456 else
4457 [Metadata_ setObject:Token_ forKey:@"Token"];
4458
4459 Changed_ = true;
4460 }
4461
4462 - (void) setToken:(NSString *)token {
4463 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4464 }
4465
4466 - (void) scrollToBottom:(NSNumber *)animated {
4467 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4468 }
4469
4470 - (void) setViewportWidth:(float)width {
4471 [indirect_ setViewportWidthOnMainThread:width];
4472 }
4473
4474 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4475 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4476 unsigned count([arguments count]);
4477 id values[count];
4478 for (unsigned i(0); i != count; ++i)
4479 values[i] = [arguments objectAtIndex:i];
4480 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4481 }
4482
4483 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4484 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4485 value = nil;
4486 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4487 table = nil;
4488 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4489 }
4490
4491 @end
4492 /* }}} */
4493
4494 @interface NSURL (CydiaSecure)
4495 @end
4496
4497 @implementation NSURL (CydiaSecure)
4498
4499 - (bool) isCydiaSecure {
4500 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4501 return true;
4502
4503 @synchronized (HostConfig_) {
4504 if ([InsecureHosts_ containsObject:[self host]])
4505 return true;
4506 }
4507
4508 return false;
4509 }
4510
4511 @end
4512
4513 /* Cydia Browser Controller {{{ */
4514 @implementation CydiaWebViewController
4515
4516 - (NSURL *) navigationURL {
4517 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4518 }
4519
4520 + (void) _initialize {
4521 [super _initialize];
4522
4523 Diversions_ = [NSMutableSet setWithCapacity:0];
4524 }
4525
4526 + (void) addDiversion:(Diversion *)diversion {
4527 [Diversions_ addObject:diversion];
4528 }
4529
4530 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4531 [super webView:view didClearWindowObject:window forFrame:frame];
4532
4533 WebDataSource *source([frame dataSource]);
4534 NSURLResponse *response([source response]);
4535 NSURL *url([response URL]);
4536 NSString *scheme([[url scheme] lowercaseString]);
4537
4538 bool bridged(false);
4539
4540 @synchronized (HostConfig_) {
4541 if ([scheme isEqualToString:@"file"])
4542 bridged = true;
4543 else if ([scheme isEqualToString:@"https"])
4544 if ([BridgedHosts_ containsObject:[url host]])
4545 bridged = true;
4546 }
4547
4548 if (bridged)
4549 [window setValue:cydia_ forKey:@"cydia"];
4550 }
4551
4552 - (void) _setupMail:(MFMailComposeViewController *)controller {
4553 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4554
4555 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4556 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4557 }
4558
4559 - (NSURL *) URLWithURL:(NSURL *)url {
4560 return [Diversion divertURL:url];
4561 }
4562
4563 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4564 NSURL *url([request URL]);
4565 NSString *host([url host]);
4566
4567 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4568
4569 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4570 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4571 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4572 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4573
4574 bool bridged;
4575 bool token;
4576
4577 @synchronized (HostConfig_) {
4578 bridged = [BridgedHosts_ containsObject:host];
4579 token = [TokenHosts_ containsObject:host];
4580 }
4581
4582 if ([url isCydiaSecure]) {
4583 if (bridged) {
4584 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4585 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4586 } else if (token) {
4587 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4588 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4589 }
4590 }
4591
4592 return copy;
4593 }
4594
4595 - (void) setDelegate:(id)delegate {
4596 [super setDelegate:delegate];
4597 [cydia_ setDelegate:delegate];
4598 }
4599
4600 - (NSString *) applicationNameForUserAgent {
4601 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4602
4603 if (Safari_ != nil)
4604 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4605 if (Build_ != nil)
4606 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4607 if (Product_ != nil)
4608 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4609
4610 return application;
4611 }
4612
4613 - (id) init {
4614 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4615 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4616 } return self;
4617 }
4618
4619 @end
4620
4621 @interface AppCacheController : CydiaWebViewController {
4622 }
4623
4624 @end
4625
4626 @implementation AppCacheController
4627
4628 - (void) didReceiveMemoryWarning {
4629 }
4630
4631 @end
4632 /* }}} */
4633
4634 // CydiaScript {{{
4635 @interface NSObject (CydiaScript)
4636 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4637 @end
4638
4639 @implementation NSObject (CydiaScript)
4640
4641 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4642 return self;
4643 }
4644
4645 @end
4646
4647 @implementation NSArray (CydiaScript)
4648
4649 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4650 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4651 for (size_t i(0), e([self count]); i != e; ++i)
4652 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4653 return object;
4654 }
4655
4656 @end
4657
4658 @implementation NSDictionary (CydiaScript)
4659
4660 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4661 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4662 for (id i in self)
4663 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4664 return object;
4665 }
4666
4667 @end
4668 // }}}
4669
4670 /* Confirmation Controller {{{ */
4671 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4672 if (!iterator.end())
4673 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4674 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4675 continue;
4676 pkgCache::PkgIterator package(dep.TargetPkg());
4677 if (package.end())
4678 continue;
4679 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4680 return true;
4681 }
4682
4683 return false;
4684 }
4685
4686 @protocol ConfirmationControllerDelegate
4687 - (void) cancelAndClear:(bool)clear;
4688 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4689 - (void) queue;
4690 @end
4691
4692 @interface ConfirmationController : CydiaWebViewController {
4693 _transient Database *database_;
4694
4695 _H<UIAlertView> essential_;
4696
4697 _H<NSDictionary> changes_;
4698 _H<NSMutableArray> issues_;
4699 _H<NSDictionary> sizes_;
4700
4701 BOOL substrate_;
4702 }
4703
4704 - (id) initWithDatabase:(Database *)database;
4705
4706 @end
4707
4708 @implementation ConfirmationController
4709
4710 - (void) complete {
4711 if (substrate_)
4712 RestartSubstrate_ = true;
4713 [delegate_ confirmWithNavigationController:[self navigationController]];
4714 }
4715
4716 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4717 NSString *context([alert context]);
4718
4719 if ([context isEqualToString:@"remove"]) {
4720 if (button == [alert cancelButtonIndex])
4721 [self dismissModalViewControllerAnimated:YES];
4722 else if (button == [alert firstOtherButtonIndex]) {
4723 [self complete];
4724 }
4725
4726 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4727 } else if ([context isEqualToString:@"unable"]) {
4728 [self dismissModalViewControllerAnimated:YES];
4729 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4730 } else {
4731 [super alertView:alert clickedButtonAtIndex:button];
4732 }
4733 }
4734
4735 - (void) _doContinue {
4736 [delegate_ cancelAndClear:NO];
4737 [self dismissModalViewControllerAnimated:YES];
4738 }
4739
4740 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4741 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4742 return nil;
4743 }
4744
4745 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4746 [super webView:view didClearWindowObject:window forFrame:frame];
4747
4748 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4749 (id) changes_, @"changes",
4750 (id) issues_, @"issues",
4751 (id) sizes_, @"sizes",
4752 self, @"queue",
4753 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4754 }
4755
4756 - (id) initWithDatabase:(Database *)database {
4757 if ((self = [super init]) != nil) {
4758 database_ = database;
4759
4760 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4761 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4762 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4763 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4764 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4765
4766 bool remove(false);
4767
4768 pkgCacheFile &cache([database_ cache]);
4769 NSArray *packages([database_ packages]);
4770 pkgDepCache::Policy *policy([database_ policy]);
4771
4772 issues_ = [NSMutableArray arrayWithCapacity:4];
4773
4774 for (Package *package in packages) {
4775 pkgCache::PkgIterator iterator([package iterator]);
4776 NSString *name([package id]);
4777
4778 if ([package broken]) {
4779 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4780
4781 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4782 name, @"package",
4783 reasons, @"reasons",
4784 nil]];
4785
4786 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4787 if (ver.end())
4788 continue;
4789
4790 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4791 pkgCache::DepIterator start;
4792 pkgCache::DepIterator end;
4793 dep.GlobOr(start, end); // ++dep
4794
4795 if (!cache->IsImportantDep(end))
4796 continue;
4797 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4798 continue;
4799
4800 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4801
4802 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4803 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4804 clauses, @"clauses",
4805 nil]];
4806
4807 _forever {
4808 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4809
4810 pkgCache::PkgIterator target(start.TargetPkg());
4811 if (target->ProvidesList != 0)
4812 reason = @"missing";
4813 else {
4814 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4815 if (!ver.end()) {
4816 reason = @"installed";
4817 installed = [NSString stringWithUTF8String:ver.VerStr()];
4818 } else if (!cache[target].CandidateVerIter(cache).end())
4819 reason = @"uninstalled";
4820 else if (target->ProvidesList == 0)
4821 reason = @"uninstallable";
4822 else
4823 reason = @"virtual";
4824 }
4825
4826 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4827 [NSString stringWithUTF8String:start.CompType()], @"operator",
4828 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4829 nil]);
4830
4831 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4832 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4833 version, @"version",
4834 reason, @"reason",
4835 installed, @"installed",
4836 nil]];
4837
4838 // yes, seriously. (wtf?)
4839 if (start == end)
4840 break;
4841 ++start;
4842 }
4843 }
4844 }
4845
4846 pkgDepCache::StateCache &state(cache[iterator]);
4847
4848 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4849
4850 if (state.NewInstall())
4851 [installs addObject:name];
4852 // XXX: else if (state.Install())
4853 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4854 [reinstalls addObject:name];
4855 // XXX: move before previous if
4856 else if (state.Upgrade())
4857 [upgrades addObject:name];
4858 else if (state.Downgrade())
4859 [downgrades addObject:name];
4860 else if (!state.Delete())
4861 // XXX: _assert(state.Keep());
4862 continue;
4863 else if (special_r(name))
4864 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4865 [NSNull null], @"package",
4866 [NSArray arrayWithObjects:
4867 [NSDictionary dictionaryWithObjectsAndKeys:
4868 @"Conflicts", @"relationship",
4869 [NSArray arrayWithObjects:
4870 [NSDictionary dictionaryWithObjectsAndKeys:
4871 name, @"package",
4872 [NSNull null], @"version",
4873 @"installed", @"reason",
4874 nil],
4875 nil], @"clauses",
4876 nil],
4877 nil], @"reasons",
4878 nil]];
4879 else {
4880 if ([package essential])
4881 remove = true;
4882 [removes addObject:name];
4883 }
4884
4885 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4886 substrate_ |= DepSubstrate(iterator.CurrentVer());
4887 }
4888
4889 if (!remove)
4890 essential_ = nil;
4891 else if (Advanced_) {
4892 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4893
4894 essential_ = [[[UIAlertView alloc]
4895 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4896 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4897 delegate:self
4898 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4899 otherButtonTitles:
4900 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4901 nil
4902 ] autorelease];
4903
4904 [essential_ setContext:@"remove"];
4905 } else {
4906 essential_ = [[[UIAlertView alloc]
4907 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4908 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4909 delegate:self
4910 cancelButtonTitle:UCLocalize("OKAY")
4911 otherButtonTitles:nil
4912 ] autorelease];
4913
4914 [essential_ setContext:@"unable"];
4915 }
4916
4917 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4918 installs, @"installs",
4919 reinstalls, @"reinstalls",
4920 upgrades, @"upgrades",
4921 downgrades, @"downgrades",
4922 removes, @"removes",
4923 nil];
4924
4925 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4926 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4927 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4928 nil];
4929
4930 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4931 } return self;
4932 }
4933
4934 - (UIBarButtonItem *) leftButton {
4935 return [[[UIBarButtonItem alloc]
4936 initWithTitle:UCLocalize("CANCEL")
4937 style:UIBarButtonItemStylePlain
4938 target:self
4939 action:@selector(cancelButtonClicked)
4940 ] autorelease];
4941 }
4942
4943 #if !AlwaysReload
4944 - (void) applyRightButton {
4945 if ([issues_ count] == 0 && ![self isLoading])
4946 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4947 initWithTitle:UCLocalize("CONFIRM")
4948 style:UIBarButtonItemStyleDone
4949 target:self
4950 action:@selector(confirmButtonClicked)
4951 ] autorelease]];
4952 else
4953 [[self navigationItem] setRightBarButtonItem:nil];
4954 }
4955 #endif
4956
4957 - (void) cancelButtonClicked {
4958 [self dismissModalViewControllerAnimated:YES];
4959 [delegate_ cancelAndClear:YES];
4960 }
4961
4962 #if !AlwaysReload
4963 - (void) confirmButtonClicked {
4964 if (essential_ != nil)
4965 [essential_ show];
4966 else
4967 [self complete];
4968 }
4969 #endif
4970
4971 @end
4972 /* }}} */
4973
4974 /* Progress Data {{{ */
4975 @interface CydiaProgressData : NSObject {
4976 _transient id delegate_;
4977
4978 bool running_;
4979 float percent_;
4980
4981 float current_;
4982 float total_;
4983 float speed_;
4984
4985 _H<NSMutableArray> events_;
4986 _H<NSString> title_;
4987
4988 _H<NSString> status_;
4989 _H<NSString> finish_;
4990 }
4991
4992 @end
4993
4994 @implementation CydiaProgressData
4995
4996 + (NSArray *) _attributeKeys {
4997 return [NSArray arrayWithObjects:
4998 @"current",
4999 @"events",
5000 @"finish",
5001 @"percent",
5002 @"running",
5003 @"speed",
5004 @"title",
5005 @"total",
5006 nil];
5007 }
5008
5009 - (NSArray *) attributeKeys {
5010 return [[self class] _attributeKeys];
5011 }
5012
5013 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5014 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5015 }
5016
5017 - (id) init {
5018 if ((self = [super init]) != nil) {
5019 events_ = [NSMutableArray arrayWithCapacity:32];
5020 } return self;
5021 }
5022
5023 - (void) setDelegate:(id)delegate {
5024 delegate_ = delegate;
5025 }
5026
5027 - (void) setPercent:(float)value {
5028 percent_ = value;
5029 }
5030
5031 - (NSNumber *) percent {
5032 return [NSNumber numberWithFloat:percent_];
5033 }
5034
5035 - (void) setCurrent:(float)value {
5036 current_ = value;
5037 }
5038
5039 - (NSNumber *) current {
5040 return [NSNumber numberWithFloat:current_];
5041 }
5042
5043 - (void) setTotal:(float)value {
5044 total_ = value;
5045 }
5046
5047 - (NSNumber *) total {
5048 return [NSNumber numberWithFloat:total_];
5049 }
5050
5051 - (void) setSpeed:(float)value {
5052 speed_ = value;
5053 }
5054
5055 - (NSNumber *) speed {
5056 return [NSNumber numberWithFloat:speed_];
5057 }
5058
5059 - (NSArray *) events {
5060 return events_;
5061 }
5062
5063 - (void) removeAllEvents {
5064 [events_ removeAllObjects];
5065 }
5066
5067 - (void) addEvent:(CydiaProgressEvent *)event {
5068 [events_ addObject:event];
5069 }
5070
5071 - (void) setTitle:(NSString *)text {
5072 title_ = text;
5073 }
5074
5075 - (NSString *) title {
5076 return title_;
5077 }
5078
5079 - (void) setFinish:(NSString *)text {
5080 finish_ = text;
5081 }
5082
5083 - (NSString *) finish {
5084 return (id) finish_ ?: [NSNull null];
5085 }
5086
5087 - (void) setRunning:(bool)running {
5088 running_ = running;
5089 }
5090
5091 - (NSNumber *) running {
5092 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5093 }
5094
5095 @end
5096 /* }}} */
5097 /* Progress Controller {{{ */
5098 @interface ProgressController : CydiaWebViewController <
5099 ProgressDelegate
5100 > {
5101 _transient Database *database_;
5102 _H<CydiaProgressData, 1> progress_;
5103 unsigned cancel_;
5104 }
5105
5106 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5107
5108 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5109
5110 - (void) setTitle:(NSString *)title;
5111 - (void) setCancellable:(bool)cancellable;
5112
5113 @end
5114
5115 @implementation ProgressController
5116
5117 - (void) dealloc {
5118 [database_ setProgressDelegate:nil];
5119 [super dealloc];
5120 }
5121
5122 - (UIBarButtonItem *) leftButton {
5123 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5124 initWithTitle:UCLocalize("CANCEL")
5125 style:UIBarButtonItemStylePlain
5126 target:self
5127 action:@selector(cancel)
5128 ] autorelease] : nil;
5129 }
5130
5131 - (void) updateCancel {
5132 [super applyLeftButton];
5133 }
5134
5135 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5136 if ((self = [super init]) != nil) {
5137 database_ = database;
5138 delegate_ = delegate;
5139
5140 [database_ setProgressDelegate:self];
5141
5142 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5143 [progress_ setDelegate:self];
5144
5145 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5146
5147 [scroller_ setBackgroundColor:[UIColor blackColor]];
5148
5149 [[self navigationItem] setHidesBackButton:YES];
5150
5151 [self updateCancel];
5152 } return self;
5153 }
5154
5155 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5156 [super webView:view didClearWindowObject:window forFrame:frame];
5157 [window setValue:progress_ forKey:@"cydiaProgress"];
5158 }
5159
5160 - (void) updateProgress {
5161 [self dispatchEvent:@"CydiaProgressUpdate"];
5162 }
5163
5164 - (void) viewWillAppear:(BOOL)animated {
5165 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5166 [super viewWillAppear:animated];
5167 }
5168
5169 - (void) close {
5170 UpdateExternalStatus(0);
5171
5172 if (Finish_ > 1)
5173 [delegate_ saveState];
5174
5175 switch (Finish_) {
5176 case 0:
5177 [delegate_ returnToCydia];
5178 break;
5179
5180 case 1:
5181 [delegate_ terminateWithSuccess];
5182 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5183 [delegate_ suspendWithAnimation:YES];
5184 else
5185 [delegate_ suspend];*/
5186 break;
5187
5188 case 2:
5189 _trace();
5190 goto reload;
5191
5192 case 3:
5193 _trace();
5194 goto reload;
5195
5196 reload:
5197 system("/usr/bin/sbreload");
5198 _trace();
5199 break;
5200
5201 case 4:
5202 _trace();
5203 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5204 SBReboot(SBSSpringBoardServerPort());
5205 else
5206 reboot2(RB_AUTOBOOT);
5207 break;
5208 }
5209
5210 [super close];
5211 }
5212
5213 - (void) setTitle:(NSString *)title {
5214 [progress_ setTitle:title];
5215 [self updateProgress];
5216 }
5217
5218 - (UIBarButtonItem *) rightButton {
5219 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5220 initWithTitle:UCLocalize("CLOSE")
5221 style:UIBarButtonItemStylePlain
5222 target:self
5223 action:@selector(close)
5224 ] autorelease];
5225 }
5226
5227 - (void) uicache {
5228 _trace();
5229 system("su -c /usr/bin/uicache mobile");
5230 _trace();
5231 }
5232
5233 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5234 UpdateExternalStatus(1);
5235
5236 [progress_ setRunning:true];
5237 [self setTitle:title];
5238 // implicit updateProgress
5239
5240 SHA1SumValue notifyconf; {
5241 FileFd file;
5242 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5243 _error->Discard();
5244 else {
5245 MMap mmap(file, MMap::ReadOnly);
5246 SHA1Summation sha1;
5247 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5248 notifyconf = sha1.Result();
5249 }
5250 }
5251
5252 SHA1SumValue springlist; {
5253 FileFd file;
5254 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5255 _error->Discard();
5256 else {
5257 MMap mmap(file, MMap::ReadOnly);
5258 SHA1Summation sha1;
5259 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5260 springlist = sha1.Result();
5261 }
5262 }
5263
5264 if (invocation != nil) {
5265 [invocation yieldToSelector:@selector(invoke)];
5266 [self setTitle:@"COMPLETE"];
5267 }
5268
5269 if (Finish_ < 4) {
5270 FileFd file;
5271 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5272 _error->Discard();
5273 else {
5274 MMap mmap(file, MMap::ReadOnly);
5275 SHA1Summation sha1;
5276 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5277 if (!(notifyconf == sha1.Result()))
5278 Finish_ = 4;
5279 }
5280 }
5281
5282 if (Finish_ < 3) {
5283 FileFd file;
5284 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5285 _error->Discard();
5286 else {
5287 MMap mmap(file, MMap::ReadOnly);
5288 SHA1Summation sha1;
5289 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5290 if (!(springlist == sha1.Result()))
5291 Finish_ = 3;
5292 }
5293 }
5294
5295 if (Finish_ < 2) {
5296 if (RestartSubstrate_)
5297 Finish_ = 2;
5298 }
5299
5300 RestartSubstrate_ = false;
5301
5302 switch (Finish_) {
5303 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5304 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5305 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5306 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5307 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5308 }
5309
5310 UIProgressHUD *hud([delegate_ addProgressHUD]);
5311 [hud setText:UCLocalize("LOADING")];
5312 [self yieldToSelector:@selector(uicache)];
5313 [delegate_ removeProgressHUD:hud];
5314
5315 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5316
5317 [progress_ setRunning:false];
5318 [self updateProgress];
5319
5320 [self applyRightButton];
5321 }
5322
5323 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5324 [progress_ addEvent:event];
5325 [self updateProgress];
5326 }
5327
5328 - (bool) isProgressCancelled {
5329 return cancel_ == 2;
5330 }
5331
5332 - (void) cancel {
5333 cancel_ = 2;
5334 [self updateCancel];
5335 }
5336
5337 - (void) setCancellable:(bool)cancellable {
5338 unsigned cancel(cancel_);
5339
5340 if (!cancellable)
5341 cancel_ = 0;
5342 else if (cancel_ == 0)
5343 cancel_ = 1;
5344
5345 if (cancel != cancel_)
5346 [self updateCancel];
5347 }
5348
5349 - (void) setProgressCancellable:(NSNumber *)cancellable {
5350 [self setCancellable:[cancellable boolValue]];
5351 }
5352
5353 - (void) setProgressPercent:(NSNumber *)percent {
5354 [progress_ setPercent:[percent floatValue]];
5355 [self updateProgress];
5356 }
5357
5358 - (void) setProgressStatus:(NSDictionary *)status {
5359 if (status == nil) {
5360 [progress_ setCurrent:0];
5361 [progress_ setTotal:0];
5362 [progress_ setSpeed:0];
5363 } else {
5364 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5365
5366 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5367 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5368 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5369 }
5370
5371 [self updateProgress];
5372 }
5373
5374 @end
5375 /* }}} */
5376
5377 /* Package Cell {{{ */
5378 @interface PackageCell : CyteTableViewCell <
5379 CyteTableViewCellDelegate
5380 > {
5381 _H<UIImage> icon_;
5382 _H<NSString> name_;
5383 _H<NSString> description_;
5384 bool commercial_;
5385 _H<NSString> source_;
5386 _H<UIImage> badge_;
5387 _H<UIImage> placard_;
5388 bool summarized_;
5389 }
5390
5391 - (PackageCell *) init;
5392 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5393
5394 - (void) drawContentRect:(CGRect)rect;
5395
5396 @end
5397
5398 @implementation PackageCell
5399
5400 - (PackageCell *) init {
5401 CGRect frame(CGRectMake(0, 0, 320, 74));
5402 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5403 UIView *content([self contentView]);
5404 CGRect bounds([content bounds]);
5405
5406 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5407 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5408 [content addSubview:content_];
5409
5410 [content_ setDelegate:self];
5411 [content_ setOpaque:YES];
5412 } return self;
5413 }
5414
5415 - (NSString *) accessibilityLabel {
5416 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5417 }
5418
5419 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5420 summarized_ = summary;
5421
5422 icon_ = nil;
5423 name_ = nil;
5424 description_ = nil;
5425 source_ = nil;
5426 badge_ = nil;
5427 placard_ = nil;
5428
5429 if (package == nil)
5430 [content_ setBackgroundColor:[UIColor whiteColor]];
5431 else {
5432 [package parse];
5433
5434 Source *source = [package source];
5435
5436 icon_ = [package icon];
5437
5438 if (NSString *name = [package name])
5439 name_ = [NSString stringWithString:name];
5440
5441 NSString *description(nil);
5442
5443 if (description == nil && IsWildcat_)
5444 description = [package longDescription];
5445 if (description == nil)
5446 description = [package shortDescription];
5447
5448 if (description != nil)
5449 description_ = [NSString stringWithString:description];
5450
5451 commercial_ = [package isCommercial];
5452
5453 NSString *label = nil;
5454 bool trusted = false;
5455
5456 if (source != nil) {
5457 label = [source label];
5458 trusted = [source trusted];
5459 } else if ([[package id] isEqualToString:@"firmware"])
5460 label = UCLocalize("APPLE");
5461 else
5462 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5463
5464 NSString *from(label);
5465
5466 NSString *section = [package simpleSection];
5467 if (section != nil && ![section isEqualToString:label]) {
5468 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5469 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5470 }
5471
5472 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5473
5474 if (NSString *purpose = [package primaryPurpose])
5475 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5476
5477 UIColor *color;
5478 NSString *placard;
5479
5480 if (NSString *mode = [package mode]) {
5481 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5482 color = RemovingColor_;
5483 //placard = @"removing";
5484 } else {
5485 color = InstallingColor_;
5486 //placard = @"installing";
5487 }
5488
5489 // XXX: the removing/installing placards are not @2x
5490 placard = nil;
5491 } else {
5492 color = [UIColor whiteColor];
5493
5494 if ([package installed] != nil)
5495 placard = @"installed";
5496 else
5497 placard = nil;
5498 }
5499
5500 [content_ setBackgroundColor:color];
5501
5502 if (placard != nil)
5503 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5504 }
5505
5506 [self setNeedsDisplay];
5507 [content_ setNeedsDisplay];
5508 }
5509
5510 - (void) drawSummaryContentRect:(CGRect)rect {
5511 bool highlighted(highlighted_);
5512 float width([self bounds].size.width);
5513
5514 if (icon_ != nil) {
5515 CGRect rect;
5516 rect.size = [(UIImage *) icon_ size];
5517
5518 while (rect.size.width > 16 || rect.size.height > 16) {
5519 rect.size.width /= 2;
5520 rect.size.height /= 2;
5521 }
5522
5523 rect.origin.x = 18 - rect.size.width / 2;
5524 rect.origin.y = 18 - rect.size.height / 2;
5525
5526 [icon_ drawInRect:rect];
5527 }
5528
5529 if (badge_ != nil) {
5530 CGRect rect;
5531 rect.size = [(UIImage *) badge_ size];
5532
5533 rect.size.width /= 4;
5534 rect.size.height /= 4;
5535
5536 rect.origin.x = 23 - rect.size.width / 2;
5537 rect.origin.y = 23 - rect.size.height / 2;
5538
5539 [badge_ drawInRect:rect];
5540 }
5541
5542 if (highlighted)
5543 UISetColor(White_);
5544
5545 if (!highlighted)
5546 UISetColor(commercial_ ? Purple_ : Black_);
5547 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5548
5549 if (placard_ != nil)
5550 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5551 }
5552
5553 - (void) drawNormalContentRect:(CGRect)rect {
5554 bool highlighted(highlighted_);
5555 float width([self bounds].size.width);
5556
5557 if (icon_ != nil) {
5558 CGRect rect;
5559 rect.size = [(UIImage *) icon_ size];
5560
5561 while (rect.size.width > 32 || rect.size.height > 32) {
5562 rect.size.width /= 2;
5563 rect.size.height /= 2;
5564 }
5565
5566 rect.origin.x = 25 - rect.size.width / 2;
5567 rect.origin.y = 25 - rect.size.height / 2;
5568
5569 [icon_ drawInRect:rect];
5570 }
5571
5572 if (badge_ != nil) {
5573 CGRect rect;
5574 rect.size = [(UIImage *) badge_ size];
5575
5576 rect.size.width /= 2;
5577 rect.size.height /= 2;
5578
5579 rect.origin.x = 36 - rect.size.width / 2;
5580 rect.origin.y = 36 - rect.size.height / 2;
5581
5582 [badge_ drawInRect:rect];
5583 }
5584
5585 if (highlighted)
5586 UISetColor(White_);
5587
5588 if (!highlighted)
5589 UISetColor(commercial_ ? Purple_ : Black_);
5590 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5591 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5592
5593 if (!highlighted)
5594 UISetColor(commercial_ ? Purplish_ : Gray_);
5595 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5596
5597 if (placard_ != nil)
5598 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5599 }
5600
5601 - (void) drawContentRect:(CGRect)rect {
5602 if (summarized_)
5603 [self drawSummaryContentRect:rect];
5604 else
5605 [self drawNormalContentRect:rect];
5606 }
5607
5608 @end
5609 /* }}} */
5610 /* Section Cell {{{ */
5611 @interface SectionCell : CyteTableViewCell <
5612 CyteTableViewCellDelegate
5613 > {
5614 _H<NSString> basic_;
5615 _H<NSString> section_;
5616 _H<NSString> name_;
5617 _H<NSString> count_;
5618 _H<UIImage> icon_;
5619 _H<UISwitch> switch_;
5620 BOOL editing_;
5621 }
5622
5623 - (void) setSection:(Section *)section editing:(BOOL)editing;
5624
5625 @end
5626
5627 @implementation SectionCell
5628
5629 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5630 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5631 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5632 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5633 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5634
5635 UIView *content([self contentView]);
5636 CGRect bounds([content bounds]);
5637
5638 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5639 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5640 [content addSubview:content_];
5641 [content_ setBackgroundColor:[UIColor whiteColor]];
5642
5643 [content_ setDelegate:self];
5644 } return self;
5645 }
5646
5647 - (void) onSwitch:(id)sender {
5648 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5649 if (metadata == nil) {
5650 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5651 [Sections_ setObject:metadata forKey:basic_];
5652 }
5653
5654 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5655 Changed_ = true;
5656 }
5657
5658 - (void) setSection:(Section *)section editing:(BOOL)editing {
5659 if (editing != editing_) {
5660 if (editing_)
5661 [switch_ removeFromSuperview];
5662 else
5663 [self addSubview:switch_];
5664 editing_ = editing;
5665 }
5666
5667 basic_ = nil;
5668 section_ = nil;
5669 name_ = nil;
5670 count_ = nil;
5671
5672 if (section == nil) {
5673 name_ = UCLocalize("ALL_PACKAGES");
5674 count_ = nil;
5675 } else {
5676 basic_ = [section name];
5677 section_ = [section localized];
5678
5679 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5680 count_ = [NSString stringWithFormat:@"%d", [section count]];
5681
5682 if (editing_)
5683 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5684 }
5685
5686 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5687 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5688
5689 [content_ setNeedsDisplay];
5690 }
5691
5692 - (void) setFrame:(CGRect)frame {
5693 [super setFrame:frame];
5694
5695 CGRect rect([switch_ frame]);
5696 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5697 }
5698
5699 - (NSString *) accessibilityLabel {
5700 return name_;
5701 }
5702
5703 - (void) drawContentRect:(CGRect)rect {
5704 bool highlighted(highlighted_ && !editing_);
5705
5706 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5707
5708 if (highlighted)
5709 UISetColor(White_);
5710
5711 float width(rect.size.width);
5712 if (editing_)
5713 width -= 87;
5714
5715 if (!highlighted)
5716 UISetColor(Black_);
5717 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5718
5719 CGSize size = [count_ sizeWithFont:Font14_];
5720
5721 UISetColor(White_);
5722 if (count_ != nil)
5723 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5724 }
5725
5726 @end
5727 /* }}} */
5728
5729 /* File Table {{{ */
5730 @interface FileTable : CyteViewController <
5731 UITableViewDataSource,
5732 UITableViewDelegate
5733 > {
5734 _transient Database *database_;
5735 _H<Package> package_;
5736 _H<NSString> name_;
5737 _H<NSMutableArray> files_;
5738 _H<UITableView, 2> list_;
5739 }
5740
5741 - (id) initWithDatabase:(Database *)database;
5742 - (void) setPackage:(Package *)package;
5743
5744 @end
5745
5746 @implementation FileTable
5747
5748 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5749 return files_ == nil ? 0 : [files_ count];
5750 }
5751
5752 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5753 return 24.0f;
5754 }*/
5755
5756 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5757 static NSString *reuseIdentifier = @"Cell";
5758
5759 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5760 if (cell == nil) {
5761 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5762 [cell setFont:[UIFont systemFontOfSize:16]];
5763 }
5764 [cell setText:[files_ objectAtIndex:indexPath.row]];
5765 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5766
5767 return cell;
5768 }
5769
5770 - (NSURL *) navigationURL {
5771 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5772 }
5773
5774 - (void) loadView {
5775 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5776
5777 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5778 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5779 [list_ setRowHeight:24.0f];
5780 [(UITableView *) list_ setDataSource:self];
5781 [list_ setDelegate:self];
5782 [[self view] addSubview:list_];
5783 }
5784
5785 - (void) viewDidLoad {
5786 [super viewDidLoad];
5787
5788 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5789 }
5790
5791 - (void) releaseSubviews {
5792 list_ = nil;
5793
5794 package_ = nil;
5795 files_ = nil;
5796
5797 [super releaseSubviews];
5798 }
5799
5800 - (id) initWithDatabase:(Database *)database {
5801 if ((self = [super init]) != nil) {
5802 database_ = database;
5803 } return self;
5804 }
5805
5806 - (void) setPackage:(Package *)package {
5807 package_ = nil;
5808 name_ = nil;
5809
5810 files_ = [NSMutableArray arrayWithCapacity:32];
5811
5812 if (package != nil) {
5813 package_ = package;
5814 name_ = [package id];
5815
5816 if (NSArray *files = [package files])
5817 [files_ addObjectsFromArray:files];
5818
5819 if ([files_ count] != 0) {
5820 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5821 [files_ removeObjectAtIndex:0];
5822 [files_ sortUsingSelector:@selector(compareByPath:)];
5823
5824 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5825 [stack addObject:@"/"];
5826
5827 for (int i(0), e([files_ count]); i != e; ++i) {
5828 NSString *file = [files_ objectAtIndex:i];
5829 while (![file hasPrefix:[stack lastObject]])
5830 [stack removeLastObject];
5831 NSString *directory = [stack lastObject];
5832 [stack addObject:[file stringByAppendingString:@"/"]];
5833 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5834 ([stack count] - 2) * 3, "",
5835 [file substringFromIndex:[directory length]]
5836 ]];
5837 }
5838 }
5839 }
5840
5841 [list_ reloadData];
5842 }
5843
5844 - (void) reloadData {
5845 [super reloadData];
5846
5847 [self setPackage:[database_ packageWithName:name_]];
5848 }
5849
5850 @end
5851 /* }}} */
5852 /* Package Controller {{{ */
5853 @interface CYPackageController : CydiaWebViewController <
5854 UIActionSheetDelegate
5855 > {
5856 _transient Database *database_;
5857 _H<Package> package_;
5858 _H<NSString> name_;
5859 bool commercial_;
5860 _H<NSMutableArray> buttons_;
5861 _H<UIBarButtonItem> button_;
5862 }
5863
5864 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5865
5866 @end
5867
5868 @implementation CYPackageController
5869
5870 - (NSURL *) navigationURL {
5871 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5872 }
5873
5874 /* XXX: this is not safe at all... localization of /fail/ */
5875 - (void) _clickButtonWithName:(NSString *)name {
5876 if ([name isEqualToString:UCLocalize("CLEAR")])
5877 [delegate_ clearPackage:package_];
5878 else if ([name isEqualToString:UCLocalize("INSTALL")])
5879 [delegate_ installPackage:package_];
5880 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5881 [delegate_ installPackage:package_];
5882 else if ([name isEqualToString:UCLocalize("REMOVE")])
5883 [delegate_ removePackage:package_];
5884 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5885 [delegate_ installPackage:package_];
5886 else _assert(false);
5887 }
5888
5889 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5890 NSString *context([sheet context]);
5891
5892 if ([context isEqualToString:@"modify"]) {
5893 if (button != [sheet cancelButtonIndex]) {
5894 NSString *buttonName = [buttons_ objectAtIndex:button];
5895 [self _clickButtonWithName:buttonName];
5896 }
5897
5898 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5899 }
5900 }
5901
5902 - (bool) _allowJavaScriptPanel {
5903 return commercial_;
5904 }
5905
5906 #if !AlwaysReload
5907 - (void) _customButtonClicked {
5908 int count([buttons_ count]);
5909 if (count == 0)
5910 return;
5911
5912 if (count == 1)
5913 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5914 else {
5915 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5916 [buttons addObjectsFromArray:buttons_];
5917
5918 UIActionSheet *sheet = [[[UIActionSheet alloc]
5919 initWithTitle:nil
5920 delegate:self
5921 cancelButtonTitle:nil
5922 destructiveButtonTitle:nil
5923 otherButtonTitles:nil
5924 ] autorelease];
5925
5926 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5927 if (!IsWildcat_) {
5928 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5929 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5930 }
5931 [sheet setContext:@"modify"];
5932
5933 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5934 }
5935 }
5936
5937 // We don't want to allow non-commercial packages to do custom things to the install button,
5938 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5939 - (void) customButtonClicked {
5940 if (commercial_)
5941 [super customButtonClicked];
5942 else
5943 [self _customButtonClicked];
5944 }
5945
5946 - (void) reloadButtonClicked {
5947 // Don't reload a commerical package by tapping the loading button,
5948 // but if it's not an Install button, we should forward it on.
5949 if (![package_ uninstalled])
5950 [self _customButtonClicked];
5951 }
5952
5953 - (void) applyLoadingTitle {
5954 // Don't show "Loading" as the title. Ever.
5955 }
5956
5957 - (UIBarButtonItem *) rightButton {
5958 return button_;
5959 }
5960 #endif
5961
5962 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5963 if ((self = [super init]) != nil) {
5964 database_ = database;
5965 buttons_ = [NSMutableArray arrayWithCapacity:4];
5966 name_ = name == nil ? @"" : [NSString stringWithString:name];
5967 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5968 } return self;
5969 }
5970
5971 - (void) reloadData {
5972 [super reloadData];
5973
5974 package_ = [database_ packageWithName:name_];
5975
5976 [buttons_ removeAllObjects];
5977
5978 if (package_ != nil) {
5979 [(Package *) package_ parse];
5980
5981 commercial_ = [package_ isCommercial];
5982
5983 if ([package_ mode] != nil)
5984 [buttons_ addObject:UCLocalize("CLEAR")];
5985 if ([package_ source] == nil);
5986 else if ([package_ upgradableAndEssential:NO])
5987 [buttons_ addObject:UCLocalize("UPGRADE")];
5988 else if ([package_ uninstalled])
5989 [buttons_ addObject:UCLocalize("INSTALL")];
5990 else
5991 [buttons_ addObject:UCLocalize("REINSTALL")];
5992 if (![package_ uninstalled])
5993 [buttons_ addObject:UCLocalize("REMOVE")];
5994 }
5995
5996 NSString *title;
5997 switch ([buttons_ count]) {
5998 case 0: title = nil; break;
5999 case 1: title = [buttons_ objectAtIndex:0]; break;
6000 default: title = UCLocalize("MODIFY"); break;
6001 }
6002
6003 button_ = [[[UIBarButtonItem alloc]
6004 initWithTitle:title
6005 style:UIBarButtonItemStylePlain
6006 target:self
6007 action:@selector(customButtonClicked)
6008 ] autorelease];
6009 }
6010
6011 - (bool) isLoading {
6012 return commercial_ ? [super isLoading] : false;
6013 }
6014
6015 @end
6016 /* }}} */
6017
6018 /* Package List Controller {{{ */
6019 @interface PackageListController : CyteViewController <
6020 UITableViewDataSource,
6021 UITableViewDelegate
6022 > {
6023 _transient Database *database_;
6024 unsigned era_;
6025 _H<NSArray> packages_;
6026 _H<NSMutableArray> sections_;
6027 _H<UITableView, 2> list_;
6028 _H<NSMutableArray> index_;
6029 _H<NSMutableDictionary> indices_;
6030 _H<NSString> title_;
6031 unsigned reloading_;
6032 }
6033
6034 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6035 - (void) setDelegate:(id)delegate;
6036 - (void) resetCursor;
6037 - (void) clearData;
6038
6039 @end
6040
6041 @implementation PackageListController
6042
6043 - (bool) isSummarized {
6044 return false;
6045 }
6046
6047 - (bool) showsSections {
6048 return true;
6049 }
6050
6051 - (void) deselectWithAnimation:(BOOL)animated {
6052 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6053 }
6054
6055 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6056 CGRect base = [[self view] bounds];
6057 base.size.height -= bounds.size.height;
6058 base.origin = [list_ frame].origin;
6059
6060 [UIView beginAnimations:nil context:NULL];
6061 [UIView setAnimationBeginsFromCurrentState:YES];
6062 [UIView setAnimationCurve:curve];
6063 [UIView setAnimationDuration:duration];
6064 [list_ setFrame:base];
6065 [UIView commitAnimations];
6066 }
6067
6068 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6069 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6070 }
6071
6072 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6073 [self resizeForKeyboardBounds:bounds duration:0];
6074 }
6075
6076 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6077 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6078 *curve = UIViewAnimationCurveEaseInOut;
6079 else
6080 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6081
6082 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6083 *duration = 0.3;
6084 else
6085 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6086 }
6087
6088 - (void) keyboardWillShow:(NSNotification *)notification {
6089 CGRect bounds;
6090 CGPoint center;
6091 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6092 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6093
6094 NSTimeInterval duration;
6095 UIViewAnimationCurve curve;
6096 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6097
6098 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);
6099 UIViewController *base = self;
6100 while ([base parentViewController] != nil)
6101 base = [base parentViewController];
6102 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6103 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6104
6105 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6106 intersection.size.height += CYStatusBarHeight();
6107
6108 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6109 }
6110
6111 - (void) keyboardWillHide:(NSNotification *)notification {
6112 NSTimeInterval duration;
6113 UIViewAnimationCurve curve;
6114 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6115
6116 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6117 }
6118
6119 - (void) viewWillAppear:(BOOL)animated {
6120 [super viewWillAppear:animated];
6121
6122 [self resizeForKeyboardBounds:CGRectZero];
6123 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6124 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6125 }
6126
6127 - (void) viewWillDisappear:(BOOL)animated {
6128 [super viewWillDisappear:animated];
6129
6130 [self resizeForKeyboardBounds:CGRectZero];
6131 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6132 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6133 }
6134
6135 - (void) viewDidAppear:(BOOL)animated {
6136 [super viewDidAppear:animated];
6137 [self deselectWithAnimation:animated];
6138 }
6139
6140 - (void) didSelectPackage:(Package *)package {
6141 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6142 [view setDelegate:delegate_];
6143 [[self navigationController] pushViewController:view animated:YES];
6144 }
6145
6146 #if TryIndexedCollation
6147 + (BOOL) hasIndexedCollation {
6148 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6149 }
6150 #endif
6151
6152 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6153 NSInteger count([sections_ count]);
6154 return count == 0 ? 1 : count;
6155 }
6156
6157 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6158 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6159 return nil;
6160 return [[sections_ objectAtIndex:section] name];
6161 }
6162
6163 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6164 if ([sections_ count] == 0)
6165 return 0;
6166 return [[sections_ objectAtIndex:section] count];
6167 }
6168
6169 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6170 @synchronized (database_) {
6171 if ([database_ era] != era_)
6172 return nil;
6173
6174 Section *section([sections_ objectAtIndex:[path section]]);
6175 NSInteger row([path row]);
6176 Package *package([packages_ objectAtIndex:([section row] + row)]);
6177 return [[package retain] autorelease];
6178 } }
6179
6180 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6181 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6182 if (cell == nil)
6183 cell = [[[PackageCell alloc] init] autorelease];
6184
6185 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6186 [cell setPackage:package asSummary:[self isSummarized]];
6187 return cell;
6188 }
6189
6190 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6191 Package *package([self packageAtIndexPath:path]);
6192 package = [database_ packageWithName:[package id]];
6193 [self didSelectPackage:package];
6194 }
6195
6196 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6197 if (![self showsSections])
6198 return nil;
6199
6200 return index_;
6201 }
6202
6203 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6204 #if TryIndexedCollation
6205 if ([[self class] hasIndexedCollation]) {
6206 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6207 }
6208 #endif
6209
6210 return index;
6211 }
6212
6213 - (void) updateHeight {
6214 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6215 }
6216
6217 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6218 if ((self = [super init]) != nil) {
6219 database_ = database;
6220 title_ = [title copy];
6221 [[self navigationItem] setTitle:title_];
6222 } return self;
6223 }
6224
6225 - (void) loadView {
6226 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6227
6228 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6229 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6230 [[self view] addSubview:list_];
6231
6232 // XXX: is 20 the most optimal number here?
6233 [list_ setSectionIndexMinimumDisplayRowCount:20];
6234
6235 [(UITableView *) list_ setDataSource:self];
6236 [list_ setDelegate:self];
6237
6238 [self updateHeight];
6239 }
6240
6241 - (void) releaseSubviews {
6242 list_ = nil;
6243
6244 packages_ = nil;
6245 sections_ = nil;
6246 index_ = nil;
6247 indices_ = nil;
6248
6249 [super releaseSubviews];
6250 }
6251
6252 - (void) setDelegate:(id)delegate {
6253 delegate_ = delegate;
6254 }
6255
6256 - (bool) shouldYield {
6257 return false;
6258 }
6259
6260 - (bool) shouldBlock {
6261 return false;
6262 }
6263
6264 - (NSMutableArray *) _reloadPackages {
6265 @synchronized (database_) {
6266 era_ = [database_ era];
6267 NSArray *packages([database_ packages]);
6268
6269 return [NSMutableArray arrayWithArray:packages];
6270 } }
6271
6272 - (void) _reloadData {
6273 if (reloading_ != 0) {
6274 reloading_ = 2;
6275 return;
6276 }
6277
6278 NSArray *packages;
6279
6280 if ([self shouldYield]) {
6281 do {
6282 UIProgressHUD *hud;
6283
6284 if (![self shouldBlock])
6285 hud = nil;
6286 else {
6287 hud = [delegate_ addProgressHUD];
6288 [hud setText:UCLocalize("LOADING")];
6289 }
6290
6291 reloading_ = 1;
6292 packages = [self yieldToSelector:@selector(_reloadPackages)];
6293
6294 if (hud != nil)
6295 [delegate_ removeProgressHUD:hud];
6296 } while (reloading_ == 2);
6297
6298 reloading_ = 0;
6299 } else {
6300 packages = [self _reloadPackages];
6301 }
6302
6303 packages_ = packages;
6304
6305 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6306 sections_ = [NSMutableArray arrayWithCapacity:16];
6307
6308 Section *section = nil;
6309
6310 #if TryIndexedCollation
6311 if ([[self class] hasIndexedCollation]) {
6312 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6313
6314 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6315 NSArray *titles = [collation sectionIndexTitles];
6316 int secidx = -1;
6317
6318 _profile(PackageTable$reloadData$Section)
6319 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6320 Package *package;
6321 int index;
6322
6323 _profile(PackageTable$reloadData$Section$Package)
6324 package = [packages_ objectAtIndex:offset];
6325 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6326 _end
6327
6328 while (secidx < index) {
6329 secidx += 1;
6330
6331 _profile(PackageTable$reloadData$Section$Allocate)
6332 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6333 _end
6334
6335 _profile(PackageTable$reloadData$Section$Add)
6336 [sections_ addObject:section];
6337 _end
6338 }
6339
6340 [section addToCount];
6341 }
6342 _end
6343 } else
6344 #endif
6345 {
6346 index_ = [NSMutableArray arrayWithCapacity:32];
6347
6348 bool sectioned([self showsSections]);
6349 if (!sectioned) {
6350 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6351 [sections_ addObject:section];
6352 }
6353
6354 _profile(PackageTable$reloadData$Section)
6355 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6356 Package *package;
6357 unichar index;
6358
6359 _profile(PackageTable$reloadData$Section$Package)
6360 package = [packages_ objectAtIndex:offset];
6361 index = [package index];
6362 _end
6363
6364 if (sectioned && (section == nil || [section index] != index)) {
6365 _profile(PackageTable$reloadData$Section$Allocate)
6366 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6367 _end
6368
6369 [index_ addObject:[section name]];
6370 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6371
6372 _profile(PackageTable$reloadData$Section$Add)
6373 [sections_ addObject:section];
6374 _end
6375 }
6376
6377 [section addToCount];
6378 }
6379 _end
6380 }
6381
6382 [self updateHeight];
6383
6384 _profile(PackageTable$reloadData$List)
6385 [(UITableView *) list_ setDataSource:self];
6386 [list_ reloadData];
6387 _end
6388 }
6389
6390 - (void) reloadData {
6391 [super reloadData];
6392
6393 if ([self shouldYield])
6394 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6395 else
6396 [self _reloadData];
6397 }
6398
6399 - (void) resetCursor {
6400 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6401 }
6402
6403 - (void) clearData {
6404 [self updateHeight];
6405
6406 [list_ setDataSource:nil];
6407 [list_ reloadData];
6408
6409 [self resetCursor];
6410 }
6411
6412 @end
6413 /* }}} */
6414 /* Filtered Package List Controller {{{ */
6415 @interface FilteredPackageListController : PackageListController {
6416 SEL filter_;
6417 IMP imp_;
6418 _H<NSObject> object_;
6419 }
6420
6421 - (void) setObject:(id)object;
6422 - (void) setObject:(id)object forFilter:(SEL)filter;
6423
6424 - (SEL) filter;
6425 - (void) setFilter:(SEL)filter;
6426
6427 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6428
6429 @end
6430
6431 @implementation FilteredPackageListController
6432
6433 - (SEL) filter {
6434 return filter_;
6435 }
6436
6437 - (void) setFilter:(SEL)filter {
6438 @synchronized (self) {
6439 filter_ = filter;
6440
6441 /* XXX: this is an unsafe optimization of doomy hell */
6442 Method method(class_getInstanceMethod([Package class], filter));
6443 _assert(method != NULL);
6444 imp_ = method_getImplementation(method);
6445 _assert(imp_ != NULL);
6446 } }
6447
6448 - (void) setObject:(id)object {
6449 @synchronized (self) {
6450 object_ = object;
6451 } }
6452
6453 - (void) setObject:(id)object forFilter:(SEL)filter {
6454 @synchronized (self) {
6455 [self setFilter:filter];
6456 [self setObject:object];
6457 } }
6458
6459 - (NSMutableArray *) _reloadPackages {
6460 @synchronized (database_) {
6461 era_ = [database_ era];
6462 NSArray *packages([database_ packages]);
6463
6464 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6465
6466 IMP imp;
6467 SEL filter;
6468 _H<NSObject> object;
6469
6470 @synchronized (self) {
6471 imp = imp_;
6472 filter = filter_;
6473 object = object_;
6474 }
6475
6476 _profile(PackageTable$reloadData$Filter)
6477 for (Package *package in packages)
6478 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6479 [filtered addObject:package];
6480 _end
6481
6482 return filtered;
6483 } }
6484
6485 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6486 if ((self = [super initWithDatabase:database title:title]) != nil) {
6487 [self setFilter:filter];
6488 [self setObject:object];
6489 } return self;
6490 }
6491
6492 @end
6493 /* }}} */
6494
6495 /* Home Controller {{{ */
6496 @interface HomeController : CydiaWebViewController {
6497 }
6498
6499 @end
6500
6501 @implementation HomeController
6502
6503 - (id) init {
6504 if ((self = [super init]) != nil) {
6505 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6506 [self reloadData];
6507 } return self;
6508 }
6509
6510 - (NSURL *) navigationURL {
6511 return [NSURL URLWithString:@"cydia://home"];
6512 }
6513
6514 - (void) didReceiveMemoryWarning {
6515 }
6516
6517 - (void) aboutButtonClicked {
6518 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6519
6520 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6521 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6522 [alert setCancelButtonIndex:0];
6523
6524 [alert setMessage:
6525 @"Copyright \u00a9 2008-2011\n"
6526 "SaurikIT, LLC\n"
6527 "\n"
6528 "Jay Freeman (saurik)\n"
6529 "saurik@saurik.com\n"
6530 "http://www.saurik.com/"
6531 ];
6532
6533 [alert show];
6534 }
6535
6536 - (UIBarButtonItem *) leftButton {
6537 return [[[UIBarButtonItem alloc]
6538 initWithTitle:UCLocalize("ABOUT")
6539 style:UIBarButtonItemStylePlain
6540 target:self
6541 action:@selector(aboutButtonClicked)
6542 ] autorelease];
6543 }
6544
6545 @end
6546 /* }}} */
6547 /* Manage Controller {{{ */
6548 @interface ManageController : CydiaWebViewController {
6549 }
6550
6551 - (void) queueStatusDidChange;
6552
6553 @end
6554
6555 @implementation ManageController
6556
6557 - (id) init {
6558 if ((self = [super init]) != nil) {
6559 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6560 } return self;
6561 }
6562
6563 - (NSURL *) navigationURL {
6564 return [NSURL URLWithString:@"cydia://manage"];
6565 }
6566
6567 - (UIBarButtonItem *) leftButton {
6568 return [[[UIBarButtonItem alloc]
6569 initWithTitle:UCLocalize("SETTINGS")
6570 style:UIBarButtonItemStylePlain
6571 target:self
6572 action:@selector(settingsButtonClicked)
6573 ] autorelease];
6574 }
6575
6576 - (void) settingsButtonClicked {
6577 [delegate_ showSettings];
6578 }
6579
6580 - (void) queueButtonClicked {
6581 [delegate_ queue];
6582 }
6583
6584 - (UIBarButtonItem *) rightButton {
6585 return Queuing_ ? [[[UIBarButtonItem alloc]
6586 initWithTitle:UCLocalize("QUEUE")
6587 style:UIBarButtonItemStyleDone
6588 target:self
6589 action:@selector(queueButtonClicked)
6590 ] autorelease] : nil;
6591 }
6592
6593 - (void) queueStatusDidChange {
6594 [self applyRightButton];
6595 }
6596
6597 - (bool) isLoading {
6598 return !Queuing_ && [super isLoading];
6599 }
6600
6601 @end
6602 /* }}} */
6603
6604 /* Refresh Bar {{{ */
6605 @interface RefreshBar : UINavigationBar {
6606 _H<UIProgressIndicator> indicator_;
6607 _H<UITextLabel> prompt_;
6608 _H<UIProgressBar> progress_;
6609 _H<UINavigationButton> cancel_;
6610 }
6611
6612 @end
6613
6614 @implementation RefreshBar
6615
6616 - (void) positionViews {
6617 CGRect frame = [cancel_ frame];
6618 frame.size = [cancel_ sizeThatFits:frame.size];
6619 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6620 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6621 [cancel_ setFrame:frame];
6622
6623 CGSize prgsize = {75, 100};
6624 CGRect prgrect = {{
6625 [self frame].size.width - prgsize.width - 10,
6626 ([self frame].size.height - prgsize.height) / 2
6627 } , prgsize};
6628 [progress_ setFrame:prgrect];
6629
6630 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6631 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6632 CGRect indrect = {{indoffset, indoffset}, indsize};
6633 [indicator_ setFrame:indrect];
6634
6635 CGSize prmsize = {215, indsize.height + 4};
6636 CGRect prmrect = {{
6637 indoffset * 2 + indsize.width,
6638 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6639 }, prmsize};
6640 [prompt_ setFrame:prmrect];
6641 }
6642
6643 - (void) setFrame:(CGRect)frame {
6644 [super setFrame:frame];
6645 [self positionViews];
6646 }
6647
6648 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6649 if ((self = [super initWithFrame:frame]) != nil) {
6650 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6651
6652 [self setBarStyle:UIBarStyleBlack];
6653
6654 UIBarStyle barstyle([self _barStyle:NO]);
6655 bool ugly(barstyle == UIBarStyleDefault);
6656
6657 UIProgressIndicatorStyle style = ugly ?
6658 UIProgressIndicatorStyleMediumBrown :
6659 UIProgressIndicatorStyleMediumWhite;
6660
6661 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6662 [(UIProgressIndicator *) indicator_ setStyle:style];
6663 [indicator_ startAnimation];
6664 [self addSubview:indicator_];
6665
6666 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6667 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6668 [prompt_ setBackgroundColor:[UIColor clearColor]];
6669 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6670 [self addSubview:prompt_];
6671
6672 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6673 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6674 [(UIProgressBar *) progress_ setStyle:0];
6675 [self addSubview:progress_];
6676
6677 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6678 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6679 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6680 [cancel_ setBarStyle:barstyle];
6681
6682 [self positionViews];
6683 } return self;
6684 }
6685
6686 - (void) setCancellable:(bool)cancellable {
6687 if (cancellable)
6688 [self addSubview:cancel_];
6689 else
6690 [cancel_ removeFromSuperview];
6691 }
6692
6693 - (void) start {
6694 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6695 [progress_ setProgress:0];
6696 }
6697
6698 - (void) stop {
6699 [self setCancellable:NO];
6700 }
6701
6702 - (void) setPrompt:(NSString *)prompt {
6703 [prompt_ setText:prompt];
6704 }
6705
6706 - (void) setProgress:(float)progress {
6707 [progress_ setProgress:progress];
6708 }
6709
6710 @end
6711 /* }}} */
6712
6713 /* Cydia Navigation Controller Interface {{{ */
6714 @interface UINavigationController (Cydia)
6715
6716 - (NSArray *) navigationURLCollection;
6717 - (void) unloadData;
6718
6719 @end
6720 /* }}} */
6721
6722 /* Cydia Tab Bar Controller {{{ */
6723 @interface CYTabBarController : UITabBarController <
6724 UITabBarControllerDelegate,
6725 ProgressDelegate
6726 > {
6727 _transient Database *database_;
6728 _H<RefreshBar, 1> refreshbar_;
6729
6730 bool dropped_;
6731 bool updating_;
6732 // XXX: ok, "updatedelegate_"?...
6733 _transient NSObject<CydiaDelegate> *updatedelegate_;
6734
6735 _H<UIViewController> remembered_;
6736 _transient UIViewController *transient_;
6737 }
6738
6739 - (NSArray *) navigationURLCollection;
6740 - (void) dropBar:(BOOL)animated;
6741 - (void) beginUpdate;
6742 - (void) raiseBar:(BOOL)animated;
6743 - (BOOL) updating;
6744 - (void) unloadData;
6745
6746 @end
6747
6748 @implementation CYTabBarController
6749
6750 - (void) setUnselectedViewController:(UIViewController *)transient {
6751 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6752 if (transient != nil) {
6753 if (transient_ == nil)
6754 remembered_ = [controllers objectAtIndex:0];
6755 transient_ = transient;
6756 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6757 [controllers replaceObjectAtIndex:0 withObject:transient_];
6758 [self setSelectedIndex:0];
6759 [self setViewControllers:controllers];
6760 [self concealTabBarSelection];
6761 } else if (remembered_ != nil) {
6762 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6763 transient_ = transient;
6764 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6765 remembered_ = nil;
6766 [self setViewControllers:controllers];
6767 [self revealTabBarSelection];
6768 }
6769 }
6770
6771 - (UIViewController *) unselectedViewController {
6772 return transient_;
6773 }
6774
6775 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6776 if ([self unselectedViewController])
6777 [self setUnselectedViewController:nil];
6778 }
6779
6780 - (NSArray *) navigationURLCollection {
6781 NSMutableArray *items([NSMutableArray array]);
6782
6783 // XXX: Should this deal with transient view controllers?
6784 for (id navigation in [self viewControllers]) {
6785 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6786 if (stack != nil)
6787 [items addObject:stack];
6788 }
6789
6790 return items;
6791 }
6792
6793 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6794 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6795 [self setUnselectedViewController:nil];
6796 else
6797 [super dismissModalViewControllerAnimated:YES];
6798 }
6799
6800 - (void) unloadData {
6801 [super unloadData];
6802
6803 for (UINavigationController *controller in [self viewControllers])
6804 [controller unloadData];
6805
6806 if (UIViewController *selected = [self selectedViewController])
6807 [selected reloadData];
6808
6809 if (UIViewController *unselected = [self unselectedViewController]) {
6810 [unselected unloadData];
6811 [unselected reloadData];
6812 }
6813 }
6814
6815 - (void) dealloc {
6816 [[NSNotificationCenter defaultCenter] removeObserver:self];
6817
6818 [super dealloc];
6819 }
6820
6821 - (id) initWithDatabase:(Database *)database {
6822 if ((self = [super init]) != nil) {
6823 database_ = database;
6824 [self setDelegate:self];
6825
6826 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6827 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6828
6829 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6830 } return self;
6831 }
6832
6833 - (void) setUpdate:(NSDate *)date {
6834 [self beginUpdate];
6835 }
6836
6837 - (void) beginUpdate {
6838 [(RefreshBar *) refreshbar_ start];
6839 [self dropBar:YES];
6840
6841 [updatedelegate_ retainNetworkActivityIndicator];
6842 updating_ = true;
6843
6844 [NSThread
6845 detachNewThreadSelector:@selector(performUpdate)
6846 toTarget:self
6847 withObject:nil
6848 ];
6849 }
6850
6851 - (void) performUpdate {
6852 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6853
6854 Status status;
6855 status.setDelegate(self);
6856 [database_ updateWithStatus:status];
6857
6858 [self
6859 performSelectorOnMainThread:@selector(completeUpdate)
6860 withObject:nil
6861 waitUntilDone:NO
6862 ];
6863
6864 [pool release];
6865 }
6866
6867 - (void) stopUpdateWithSelector:(SEL)selector {
6868 updating_ = false;
6869 [updatedelegate_ releaseNetworkActivityIndicator];
6870
6871 [self raiseBar:YES];
6872 [refreshbar_ stop];
6873
6874 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6875 }
6876
6877 - (void) completeUpdate {
6878 if (!updating_)
6879 return;
6880 [self stopUpdateWithSelector:@selector(reloadData)];
6881 }
6882
6883 - (void) cancelUpdate {
6884 [self stopUpdateWithSelector:@selector(updateData)];
6885 }
6886
6887 - (void) cancelPressed {
6888 [self cancelUpdate];
6889 }
6890
6891 - (BOOL) updating {
6892 return updating_;
6893 }
6894
6895 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6896 [refreshbar_ setPrompt:[event compoundMessage]];
6897 }
6898
6899 - (bool) isProgressCancelled {
6900 return !updating_;
6901 }
6902
6903 - (void) setProgressCancellable:(NSNumber *)cancellable {
6904 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6905 }
6906
6907 - (void) setProgressPercent:(NSNumber *)percent {
6908 [refreshbar_ setProgress:[percent floatValue]];
6909 }
6910
6911 - (void) setProgressStatus:(NSDictionary *)status {
6912 if (status != nil)
6913 [self setProgressPercent:[status objectForKey:@"Percent"]];
6914 }
6915
6916 - (void) setUpdateDelegate:(id)delegate {
6917 updatedelegate_ = delegate;
6918 }
6919
6920 - (UIView *) transitionView {
6921 if ([self respondsToSelector:@selector(_transitionView)])
6922 return [self _transitionView];
6923 else
6924 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6925 }
6926
6927 - (void) dropBar:(BOOL)animated {
6928 if (dropped_)
6929 return;
6930 dropped_ = true;
6931
6932 UIView *transition([self transitionView]);
6933 [[self view] addSubview:refreshbar_];
6934
6935 CGRect barframe([refreshbar_ frame]);
6936
6937 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6938 barframe.origin.y = CYStatusBarHeight();
6939 else
6940 barframe.origin.y = 0;
6941
6942 [refreshbar_ setFrame:barframe];
6943
6944 if (animated)
6945 [UIView beginAnimations:nil context:NULL];
6946
6947 CGRect viewframe = [transition frame];
6948 viewframe.origin.y += barframe.size.height;
6949 viewframe.size.height -= barframe.size.height;
6950 [transition setFrame:viewframe];
6951
6952 if (animated)
6953 [UIView commitAnimations];
6954
6955 // Ensure bar has the proper width for our view, it might have changed
6956 barframe.size.width = viewframe.size.width;
6957 [refreshbar_ setFrame:barframe];
6958 }
6959
6960 - (void) raiseBar:(BOOL)animated {
6961 if (!dropped_)
6962 return;
6963 dropped_ = false;
6964
6965 UIView *transition([self transitionView]);
6966 [refreshbar_ removeFromSuperview];
6967
6968 CGRect barframe([refreshbar_ frame]);
6969
6970 if (animated)
6971 [UIView beginAnimations:nil context:NULL];
6972
6973 CGRect viewframe = [transition frame];
6974 viewframe.origin.y -= barframe.size.height;
6975 viewframe.size.height += barframe.size.height;
6976 [transition setFrame:viewframe];
6977
6978 if (animated)
6979 [UIView commitAnimations];
6980 }
6981
6982 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6983 bool dropped(dropped_);
6984
6985 if (dropped)
6986 [self raiseBar:NO];
6987
6988 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6989
6990 if (dropped)
6991 [self dropBar:NO];
6992 }
6993
6994 - (void) statusBarFrameChanged:(NSNotification *)notification {
6995 if (dropped_) {
6996 [self raiseBar:NO];
6997 [self dropBar:NO];
6998 }
6999 }
7000
7001 @end
7002 /* }}} */
7003
7004 /* Cydia Navigation Controller Implementation {{{ */
7005 @implementation UINavigationController (Cydia)
7006
7007 - (NSArray *) navigationURLCollection {
7008 NSMutableArray *stack([NSMutableArray array]);
7009
7010 for (CyteViewController *controller in [self viewControllers]) {
7011 NSString *url = [[controller navigationURL] absoluteString];
7012 if (url != nil)
7013 [stack addObject:url];
7014 }
7015
7016 return stack;
7017 }
7018
7019 - (void) reloadData {
7020 [super reloadData];
7021
7022 UIViewController *visible([self visibleViewController]);
7023 if (visible != nil)
7024 [visible reloadData];
7025
7026 // on the iPad, this view controller is ALSO visible. :(
7027 if (IsWildcat_)
7028 if (UIViewController *top = [self topViewController])
7029 if (top != visible)
7030 [top reloadData];
7031 }
7032
7033 - (void) unloadData {
7034 for (CyteViewController *page in [self viewControllers])
7035 [page unloadData];
7036
7037 [super unloadData];
7038 }
7039
7040 @end
7041 /* }}} */
7042
7043 /* Cydia:// Protocol {{{ */
7044 @interface CydiaURLProtocol : NSURLProtocol {
7045 }
7046
7047 @end
7048
7049 @implementation CydiaURLProtocol
7050
7051 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7052 NSURL *url([request URL]);
7053 if (url == nil)
7054 return NO;
7055
7056 NSString *scheme([[url scheme] lowercaseString]);
7057 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7058 return YES;
7059 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7060 return YES;
7061
7062 return NO;
7063 }
7064
7065 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7066 return request;
7067 }
7068
7069 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7070 id<NSURLProtocolClient> client([self client]);
7071 if (icon == nil)
7072 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7073 else {
7074 NSData *data(UIImagePNGRepresentation(icon));
7075
7076 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7077 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7078 [client URLProtocol:self didLoadData:data];
7079 [client URLProtocolDidFinishLoading:self];
7080 }
7081 }
7082
7083 - (void) startLoading {
7084 id<NSURLProtocolClient> client([self client]);
7085 NSURLRequest *request([self request]);
7086
7087 NSURL *url([request URL]);
7088 NSString *href([url absoluteString]);
7089 NSString *scheme([[url scheme] lowercaseString]);
7090
7091 NSString *path;
7092
7093 if ([scheme isEqualToString:@"cydia"])
7094 path = [href substringFromIndex:8];
7095 else if ([scheme isEqualToString:@"about"])
7096 path = [href substringFromIndex:12];
7097 else _assert(false);
7098
7099 NSRange slash([path rangeOfString:@"/"]);
7100
7101 NSString *command;
7102 if (slash.location == NSNotFound) {
7103 command = path;
7104 path = nil;
7105 } else {
7106 command = [path substringToIndex:slash.location];
7107 path = [path substringFromIndex:(slash.location + 1)];
7108 }
7109
7110 Database *database([Database sharedInstance]);
7111
7112 if ([command isEqualToString:@"package-icon"]) {
7113 if (path == nil)
7114 goto fail;
7115 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7116 Package *package([database packageWithName:path]);
7117 if (package == nil)
7118 goto fail;
7119 [package parse];
7120 UIImage *icon([package icon]);
7121 [self _returnPNGWithImage:icon forRequest:request];
7122 } else if ([command isEqualToString:@"uikit-image"]) {
7123 if (path == nil)
7124 goto fail;
7125 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7126 UIImage *icon(_UIImageWithName(path));
7127 [self _returnPNGWithImage:icon forRequest:request];
7128 } else if ([command isEqualToString:@"section-icon"]) {
7129 if (path == nil)
7130 goto fail;
7131 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7132 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7133 if (icon == nil)
7134 icon = [UIImage applicationImageNamed:@"unknown.png"];
7135 [self _returnPNGWithImage:icon forRequest:request];
7136 } else fail: {
7137 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7138 }
7139 }
7140
7141 - (void) stopLoading {
7142 }
7143
7144 @end
7145 /* }}} */
7146
7147 /* Section Controller {{{ */
7148 @interface SectionController : FilteredPackageListController {
7149 _H<NSString> section_;
7150 }
7151
7152 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7153
7154 @end
7155
7156 @implementation SectionController
7157
7158 - (NSURL *) navigationURL {
7159 NSString *name = section_;
7160 if (name == nil)
7161 name = @"all";
7162
7163 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7164 }
7165
7166 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7167 NSString *title;
7168 if (name == nil)
7169 title = UCLocalize("ALL_PACKAGES");
7170 else if (![name isEqual:@""])
7171 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7172 else
7173 title = UCLocalize("NO_SECTION");
7174
7175 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7176 section_ = name;
7177 } return self;
7178 }
7179
7180 @end
7181 /* }}} */
7182 /* Sections Controller {{{ */
7183 @interface SectionsController : CyteViewController <
7184 UITableViewDataSource,
7185 UITableViewDelegate
7186 > {
7187 _transient Database *database_;
7188 _H<NSMutableArray> sections_;
7189 _H<NSMutableArray> filtered_;
7190 _H<UITableView, 2> list_;
7191 }
7192
7193 - (id) initWithDatabase:(Database *)database;
7194 - (void) editButtonClicked;
7195
7196 @end
7197
7198 @implementation SectionsController
7199
7200 - (NSURL *) navigationURL {
7201 return [NSURL URLWithString:@"cydia://sections"];
7202 }
7203
7204 - (void) updateNavigationItem {
7205 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7206 if ([sections_ count] == 0) {
7207 [[self navigationItem] setRightBarButtonItem:nil];
7208 } else {
7209 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7210 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7211 target:self
7212 action:@selector(editButtonClicked)
7213 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7214 }
7215 }
7216
7217 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7218 [super setEditing:editing animated:animated];
7219
7220 if (editing)
7221 [list_ reloadData];
7222 else
7223 [delegate_ updateData];
7224
7225 [self updateNavigationItem];
7226 }
7227
7228 - (void) viewDidAppear:(BOOL)animated {
7229 [super viewDidAppear:animated];
7230 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7231 }
7232
7233 - (void) viewWillDisappear:(BOOL)animated {
7234 [super viewWillDisappear:animated];
7235 if ([self isEditing]) [self setEditing:NO];
7236 }
7237
7238 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7239 Section *section = nil;
7240 int index = [indexPath row];
7241 if (![self isEditing]) {
7242 index -= 1;
7243 if (index >= 0)
7244 section = [filtered_ objectAtIndex:index];
7245 } else {
7246 section = [sections_ objectAtIndex:index];
7247 }
7248 return section;
7249 }
7250
7251 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7252 if ([self isEditing])
7253 return [sections_ count];
7254 else
7255 return [filtered_ count] + 1;
7256 }
7257
7258 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7259 return 45.0f;
7260 }*/
7261
7262 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7263 static NSString *reuseIdentifier = @"SectionCell";
7264
7265 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7266 if (cell == nil)
7267 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7268
7269 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7270
7271 return cell;
7272 }
7273
7274 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7275 if ([self isEditing])
7276 return;
7277
7278 Section *section = [self sectionAtIndexPath:indexPath];
7279
7280 SectionController *controller = [[[SectionController alloc]
7281 initWithDatabase:database_
7282 section:[section name]
7283 ] autorelease];
7284 [controller setDelegate:delegate_];
7285
7286 [[self navigationController] pushViewController:controller animated:YES];
7287 }
7288
7289 - (void) loadView {
7290 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7291
7292 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7293 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7294 [list_ setRowHeight:45.0f];
7295 [(UITableView *) list_ setDataSource:self];
7296 [list_ setDelegate:self];
7297 [[self view] addSubview:list_];
7298 }
7299
7300 - (void) viewDidLoad {
7301 [super viewDidLoad];
7302
7303 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7304 }
7305
7306 - (void) releaseSubviews {
7307 list_ = nil;
7308
7309 sections_ = nil;
7310 filtered_ = nil;
7311
7312 [super releaseSubviews];
7313 }
7314
7315 - (id) initWithDatabase:(Database *)database {
7316 if ((self = [super init]) != nil) {
7317 database_ = database;
7318 } return self;
7319 }
7320
7321 - (void) reloadData {
7322 [super reloadData];
7323
7324 NSArray *packages = [database_ packages];
7325
7326 sections_ = [NSMutableArray arrayWithCapacity:16];
7327 filtered_ = [NSMutableArray arrayWithCapacity:16];
7328
7329 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7330
7331 _trace();
7332 for (Package *package in packages) {
7333 NSString *name([package section]);
7334 NSString *key(name == nil ? @"" : name);
7335
7336 Section *section;
7337
7338 _profile(SectionsView$reloadData$Section)
7339 section = [sections objectForKey:key];
7340 if (section == nil) {
7341 _profile(SectionsView$reloadData$Section$Allocate)
7342 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7343 [sections setObject:section forKey:key];
7344 _end
7345 }
7346 _end
7347
7348 [section addToCount];
7349
7350 _profile(SectionsView$reloadData$Filter)
7351 if (![package valid] || ![package visible])
7352 continue;
7353 _end
7354
7355 [section addToRow];
7356 }
7357 _trace();
7358
7359 [sections_ addObjectsFromArray:[sections allValues]];
7360
7361 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7362
7363 for (Section *section in (id) sections_) {
7364 size_t count([section row]);
7365 if (count == 0)
7366 continue;
7367
7368 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7369 [section setCount:count];
7370 [filtered_ addObject:section];
7371 }
7372
7373 [self updateNavigationItem];
7374 [list_ reloadData];
7375 _trace();
7376 }
7377
7378 - (void) editButtonClicked {
7379 [self setEditing:![self isEditing] animated:YES];
7380 }
7381
7382 @end
7383 /* }}} */
7384
7385 /* Changes Controller {{{ */
7386 @interface ChangesController : CyteViewController <
7387 UITableViewDataSource,
7388 UITableViewDelegate
7389 > {
7390 _transient Database *database_;
7391 unsigned era_;
7392 _H<NSArray> packages_;
7393 _H<NSMutableArray> sections_;
7394 _H<UITableView, 2> list_;
7395 unsigned upgrades_;
7396 }
7397
7398 - (id) initWithDatabase:(Database *)database;
7399
7400 @end
7401
7402 @implementation ChangesController
7403
7404 - (NSURL *) navigationURL {
7405 return [NSURL URLWithString:@"cydia://changes"];
7406 }
7407
7408 - (void) viewDidAppear:(BOOL)animated {
7409 [super viewDidAppear:animated];
7410 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7411 }
7412
7413 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7414 NSInteger count([sections_ count]);
7415 return count == 0 ? 1 : count;
7416 }
7417
7418 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7419 if ([sections_ count] == 0)
7420 return nil;
7421 return [[sections_ objectAtIndex:section] name];
7422 }
7423
7424 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7425 if ([sections_ count] == 0)
7426 return 0;
7427 return [[sections_ objectAtIndex:section] count];
7428 }
7429
7430 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7431 @synchronized (database_) {
7432 if ([database_ era] != era_)
7433 return nil;
7434
7435 NSUInteger sectionIndex([path section]);
7436 if (sectionIndex >= [sections_ count])
7437 return nil;
7438 Section *section([sections_ objectAtIndex:sectionIndex]);
7439 NSInteger row([path row]);
7440 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7441 } }
7442
7443 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7444 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7445 if (cell == nil)
7446 cell = [[[PackageCell alloc] init] autorelease];
7447
7448 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7449 [cell setPackage:package asSummary:false];
7450 return cell;
7451 }
7452
7453 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7454 Package *package([self packageAtIndexPath:path]);
7455 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7456 [view setDelegate:delegate_];
7457 [[self navigationController] pushViewController:view animated:YES];
7458 return path;
7459 }
7460
7461 - (void) refreshButtonClicked {
7462 [delegate_ beginUpdate];
7463 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7464 }
7465
7466 - (void) upgradeButtonClicked {
7467 [delegate_ distUpgrade];
7468 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7469 }
7470
7471 - (void) loadView {
7472 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7473
7474 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7475 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7476 [list_ setRowHeight:73];
7477 [(UITableView *) list_ setDataSource:self];
7478 [list_ setDelegate:self];
7479 [[self view] addSubview:list_];
7480 }
7481
7482 - (void) viewDidLoad {
7483 [super viewDidLoad];
7484
7485 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7486 }
7487
7488 - (void) releaseSubviews {
7489 list_ = nil;
7490
7491 packages_ = nil;
7492 sections_ = nil;
7493
7494 [super releaseSubviews];
7495 }
7496
7497 - (id) initWithDatabase:(Database *)database {
7498 if ((self = [super init]) != nil) {
7499 database_ = database;
7500 } return self;
7501 }
7502
7503 - (NSMutableArray *) _reloadPackages {
7504 @synchronized (database_) {
7505 era_ = [database_ era];
7506 NSArray *packages([database_ packages]);
7507
7508 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7509
7510 _trace();
7511 _profile(ChangesController$_reloadPackages$Filter)
7512 for (Package *package in packages)
7513 if ([package upgradableAndEssential:YES] || [package visible])
7514 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7515 _end
7516 _trace();
7517 _profile(ChangesController$_reloadPackages$radixSort)
7518 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7519 _end
7520 _trace();
7521
7522 return filtered;
7523 } }
7524
7525 - (void) _reloadData {
7526 NSArray *packages;
7527
7528 reload:
7529 if (true) {
7530 UIProgressHUD *hud([delegate_ addProgressHUD]);
7531 [hud setText:UCLocalize("LOADING")];
7532 //NSLog(@"HUD:%@::%@", delegate_, hud);
7533 packages = [self yieldToSelector:@selector(_reloadPackages)];
7534 [delegate_ removeProgressHUD:hud];
7535 } else {
7536 packages = [self _reloadPackages];
7537 }
7538
7539 @synchronized (database_) {
7540 if (era_ != [database_ era])
7541 goto reload;
7542
7543 packages_ = packages;
7544 sections_ = [NSMutableArray arrayWithCapacity:16];
7545
7546 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7547 Section *ignored = nil;
7548 Section *section = nil;
7549 time_t last = 0;
7550
7551 upgrades_ = 0;
7552 bool unseens = false;
7553
7554 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7555
7556 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7557 Package *package = [packages_ objectAtIndex:offset];
7558
7559 BOOL uae = [package upgradableAndEssential:YES];
7560
7561 if (!uae) {
7562 unseens = true;
7563 time_t seen([package seen]);
7564
7565 if (section == nil || last != seen) {
7566 last = seen;
7567
7568 NSString *name;
7569 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7570 [name autorelease];
7571
7572 _profile(ChangesController$reloadData$Allocate)
7573 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7574 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7575 [sections_ addObject:section];
7576 _end
7577 }
7578
7579 [section addToCount];
7580 } else if ([package ignored]) {
7581 if (ignored == nil) {
7582 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7583 }
7584 [ignored addToCount];
7585 } else {
7586 ++upgrades_;
7587 [upgradable addToCount];
7588 }
7589 }
7590 _trace();
7591
7592 CFRelease(formatter);
7593
7594 if (unseens) {
7595 Section *last = [sections_ lastObject];
7596 size_t count = [last count];
7597 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7598 [sections_ removeLastObject];
7599 }
7600
7601 if ([ignored count] != 0)
7602 [sections_ insertObject:ignored atIndex:0];
7603 if (upgrades_ != 0)
7604 [sections_ insertObject:upgradable atIndex:0];
7605
7606 [list_ reloadData];
7607
7608 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7609 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7610 style:UIBarButtonItemStylePlain
7611 target:self
7612 action:@selector(upgradeButtonClicked)
7613 ] autorelease]) animated:YES];
7614
7615 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7616 initWithTitle:UCLocalize("REFRESH")
7617 style:UIBarButtonItemStylePlain
7618 target:self
7619 action:@selector(refreshButtonClicked)
7620 ] autorelease]) animated:YES];
7621
7622 PrintTimes();
7623 } }
7624
7625 - (void) reloadData {
7626 [super reloadData];
7627 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7628 }
7629
7630 @end
7631 /* }}} */
7632 /* Search Controller {{{ */
7633 @interface SearchController : FilteredPackageListController <
7634 UISearchBarDelegate
7635 > {
7636 _H<UISearchBar, 1> search_;
7637 BOOL searchloaded_;
7638 }
7639
7640 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7641 - (void) reloadData;
7642
7643 @end
7644
7645 @implementation SearchController
7646
7647 - (NSURL *) navigationURL {
7648 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7649 return [NSURL URLWithString:@"cydia://search"];
7650 else
7651 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7652 }
7653
7654 - (void) useSearch {
7655 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7656 [self clearData];
7657 [self reloadData];
7658 }
7659
7660 - (void) viewWillAppear:(BOOL)animated {
7661 [super viewWillAppear:animated];
7662
7663 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7664 [self useSearch];
7665 }
7666
7667 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7668 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7669 [self clearData];
7670 [self reloadData];
7671 }
7672
7673 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7674 [search_ resignFirstResponder];
7675 [self useSearch];
7676 }
7677
7678 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7679 [search_ setText:@""];
7680 [self searchBarButtonClicked:searchBar];
7681 }
7682
7683 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7684 [self searchBarButtonClicked:searchBar];
7685 }
7686
7687 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7688 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7689 [self reloadData];
7690 }
7691
7692 - (bool) shouldYield {
7693 return YES;
7694 }
7695
7696 - (bool) shouldBlock {
7697 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7698 }
7699
7700 - (bool) isSummarized {
7701 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7702 }
7703
7704 - (bool) showsSections {
7705 return false;
7706 }
7707
7708 - (NSMutableArray *) _reloadPackages {
7709 NSMutableArray *packages([super _reloadPackages]);
7710 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7711 [packages radixSortUsingSelector:@selector(rank)];
7712 return packages;
7713 }
7714
7715 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7716 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7717 search_ = [[[UISearchBar alloc] init] autorelease];
7718 [search_ setDelegate:self];
7719
7720 if (query != nil)
7721 [search_ setText:query];
7722 } return self;
7723 }
7724
7725 - (void) viewDidAppear:(BOOL)animated {
7726 [super viewDidAppear:animated];
7727
7728 if (!searchloaded_) {
7729 searchloaded_ = YES;
7730 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7731 [search_ layoutSubviews];
7732 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7733
7734 UITextField *textField;
7735 if ([search_ respondsToSelector:@selector(searchField)])
7736 textField = [search_ searchField];
7737 else
7738 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7739
7740 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7741 [textField setEnablesReturnKeyAutomatically:NO];
7742 [[self navigationItem] setTitleView:textField];
7743 }
7744 }
7745
7746 - (void) reloadData {
7747 id object([search_ text]);
7748 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7749 object = [object componentsSeparatedByString:@" "];
7750
7751 [self setObject:object];
7752 [self resetCursor];
7753
7754 [super reloadData];
7755 }
7756
7757 - (void) didSelectPackage:(Package *)package {
7758 [search_ resignFirstResponder];
7759 [super didSelectPackage:package];
7760 }
7761
7762 @end
7763 /* }}} */
7764 /* Package Settings Controller {{{ */
7765 @interface PackageSettingsController : CyteViewController <
7766 UITableViewDataSource,
7767 UITableViewDelegate
7768 > {
7769 _transient Database *database_;
7770 _H<NSString> name_;
7771 _H<Package> package_;
7772 _H<UITableView, 2> table_;
7773 _H<UISwitch> subscribedSwitch_;
7774 _H<UISwitch> ignoredSwitch_;
7775 _H<UITableViewCell> subscribedCell_;
7776 _H<UITableViewCell> ignoredCell_;
7777 }
7778
7779 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7780
7781 @end
7782
7783 @implementation PackageSettingsController
7784
7785 - (NSURL *) navigationURL {
7786 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7787 }
7788
7789 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7790 if (package_ == nil)
7791 return 0;
7792
7793 if ([package_ installed] == nil)
7794 return 1;
7795 else
7796 return 2;
7797 }
7798
7799 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7800 if (package_ == nil)
7801 return 0;
7802
7803 // both sections contain just one item right now.
7804 return 1;
7805 }
7806
7807 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7808 return nil;
7809 }
7810
7811 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7812 if (section == 0)
7813 return UCLocalize("SHOW_ALL_CHANGES_EX");
7814 else
7815 return UCLocalize("IGNORE_UPGRADES_EX");
7816 }
7817
7818 - (void) onSubscribed:(id)control {
7819 bool value([control isOn]);
7820 if (package_ == nil)
7821 return;
7822 if ([package_ setSubscribed:value])
7823 [delegate_ updateData];
7824 }
7825
7826 - (void) _updateIgnored {
7827 const char *package([name_ UTF8String]);
7828 bool on([ignoredSwitch_ isOn]);
7829
7830 pid_t pid(ExecFork());
7831 if (pid == 0) {
7832 FILE *dpkg(popen("dpkg --set-selections", "w"));
7833 fwrite(package, strlen(package), 1, dpkg);
7834
7835 if (on)
7836 fwrite(" hold\n", 6, 1, dpkg);
7837 else
7838 fwrite(" install\n", 9, 1, dpkg);
7839
7840 pclose(dpkg);
7841
7842 exit(0);
7843 _assert(false);
7844 }
7845
7846 ReapZombie(pid);
7847 }
7848
7849 - (void) onIgnored:(id)control {
7850 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7851 [invocation setTarget:self];
7852 [invocation setSelector:@selector(_updateIgnored)];
7853
7854 [delegate_ reloadDataWithInvocation:invocation];
7855 }
7856
7857 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7858 if (package_ == nil)
7859 return nil;
7860
7861 switch ([indexPath section]) {
7862 case 0: return subscribedCell_;
7863 case 1: return ignoredCell_;
7864
7865 _nodefault
7866 }
7867
7868 return nil;
7869 }
7870
7871 - (void) loadView {
7872 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7873
7874 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7875 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7876 [(UITableView *) table_ setDataSource:self];
7877 [table_ setDelegate:self];
7878 [[self view] addSubview:table_];
7879
7880 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7881 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7882 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7883
7884 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7885 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7886 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7887
7888 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7889 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7890 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7891 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7892
7893 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7894 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7895 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7896 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7897 }
7898
7899 - (void) viewDidLoad {
7900 [super viewDidLoad];
7901
7902 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7903 }
7904
7905 - (void) releaseSubviews {
7906 ignoredCell_ = nil;
7907 subscribedCell_ = nil;
7908 table_ = nil;
7909 ignoredSwitch_ = nil;
7910 subscribedSwitch_ = nil;
7911
7912 [super releaseSubviews];
7913 }
7914
7915 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7916 if ((self = [super init]) != nil) {
7917 database_ = database;
7918 name_ = package;
7919 } return self;
7920 }
7921
7922 - (void) reloadData {
7923 [super reloadData];
7924
7925 package_ = [database_ packageWithName:name_];
7926
7927 if (package_ != nil) {
7928 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7929 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7930 } // XXX: what now, G?
7931
7932 [table_ reloadData];
7933 }
7934
7935 @end
7936 /* }}} */
7937
7938 /* Installed Controller {{{ */
7939 @interface InstalledController : FilteredPackageListController {
7940 BOOL expert_;
7941 }
7942
7943 - (id) initWithDatabase:(Database *)database;
7944
7945 - (void) updateRoleButton;
7946 - (void) queueStatusDidChange;
7947
7948 @end
7949
7950 @implementation InstalledController
7951
7952 - (NSURL *) navigationURL {
7953 return [NSURL URLWithString:@"cydia://installed"];
7954 }
7955
7956 - (id) initWithDatabase:(Database *)database {
7957 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7958 [self updateRoleButton];
7959 [self queueStatusDidChange];
7960 } return self;
7961 }
7962
7963 #if !AlwaysReload
7964 - (void) queueButtonClicked {
7965 [delegate_ queue];
7966 }
7967 #endif
7968
7969 - (void) queueStatusDidChange {
7970 #if !AlwaysReload
7971 if (IsWildcat_) {
7972 if (Queuing_) {
7973 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7974 initWithTitle:UCLocalize("QUEUE")
7975 style:UIBarButtonItemStyleDone
7976 target:self
7977 action:@selector(queueButtonClicked)
7978 ] autorelease]];
7979 } else {
7980 [[self navigationItem] setLeftBarButtonItem:nil];
7981 }
7982 }
7983 #endif
7984 }
7985
7986 - (void) updateRoleButton {
7987 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7988 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7989 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7990 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7991 target:self
7992 action:@selector(roleButtonClicked)
7993 ] autorelease]];
7994 }
7995
7996 - (void) roleButtonClicked {
7997 [self setObject:[NSNumber numberWithBool:expert_]];
7998 [self reloadData];
7999 expert_ = !expert_;
8000
8001 [self updateRoleButton];
8002 }
8003
8004 @end
8005 /* }}} */
8006
8007 /* Source Cell {{{ */
8008 @interface SourceCell : CyteTableViewCell <
8009 CyteTableViewCellDelegate
8010 > {
8011 _H<NSURL> url_;
8012 _H<UIImage> icon_;
8013 _H<NSString> origin_;
8014 _H<NSString> label_;
8015 }
8016
8017 - (void) setSource:(Source *)source;
8018
8019 @end
8020
8021 @implementation SourceCell
8022
8023 - (void) _setImage:(NSArray *)data {
8024 if ([url_ isEqual:[data objectAtIndex:0]]) {
8025 icon_ = [data objectAtIndex:1];
8026 [content_ setNeedsDisplay];
8027 }
8028 }
8029
8030 - (void) _setSource:(NSURL *) url {
8031 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8032
8033 if (NSData *data = [NSURLConnection
8034 sendSynchronousRequest:[NSURLRequest
8035 requestWithURL:url
8036 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8037 //timeoutInterval:5
8038 ]
8039
8040 returningResponse:NULL
8041 error:NULL
8042 ])
8043 if (UIImage *image = [UIImage imageWithData:data])
8044 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8045
8046 [pool release];
8047 }
8048
8049 - (void) setSource:(Source *)source {
8050 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8051
8052 origin_ = [source name];
8053 label_ = [source rooturi];
8054
8055 [content_ setNeedsDisplay];
8056
8057 url_ = [source iconURL];
8058 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8059 }
8060
8061 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8062 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8063 UIView *content([self contentView]);
8064 CGRect bounds([content bounds]);
8065
8066 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8067 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8068 [content_ setBackgroundColor:[UIColor whiteColor]];
8069 [content addSubview:content_];
8070
8071 [content_ setDelegate:self];
8072 [content_ setOpaque:YES];
8073
8074 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8075 } return self;
8076 }
8077
8078 - (NSString *) accessibilityLabel {
8079 return label_;
8080 }
8081
8082 - (void) drawContentRect:(CGRect)rect {
8083 bool highlighted(highlighted_);
8084 float width(rect.size.width);
8085
8086 if (icon_ != nil) {
8087 CGRect rect;
8088 rect.size = [(UIImage *) icon_ size];
8089
8090 while (rect.size.width > 32 || rect.size.height > 32) {
8091 rect.size.width /= 2;
8092 rect.size.height /= 2;
8093 }
8094
8095 rect.origin.x = 25 - rect.size.width / 2;
8096 rect.origin.y = 25 - rect.size.height / 2;
8097
8098 [icon_ drawInRect:rect];
8099 }
8100
8101 if (highlighted)
8102 UISetColor(White_);
8103
8104 if (!highlighted)
8105 UISetColor(Black_);
8106 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8107
8108 if (!highlighted)
8109 UISetColor(Gray_);
8110 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8111 }
8112
8113 @end
8114 /* }}} */
8115 /* Source Controller {{{ */
8116 @interface SourceController : FilteredPackageListController {
8117 _transient Source *source_;
8118 _H<NSString> key_;
8119 }
8120
8121 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8122
8123 @end
8124
8125 @implementation SourceController
8126
8127 - (NSURL *) navigationURL {
8128 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8129 }
8130
8131 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8132 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8133 source_ = source;
8134 key_ = [source key];
8135 } return self;
8136 }
8137
8138 - (void) reloadData {
8139 source_ = [database_ sourceWithKey:key_];
8140 key_ = [source_ key];
8141 [self setObject:source_];
8142
8143 [[self navigationItem] setTitle:[source_ label]];
8144
8145 [super reloadData];
8146 }
8147
8148 @end
8149 /* }}} */
8150 /* Sources Controller {{{ */
8151 @interface SourcesController : CyteViewController <
8152 UITableViewDataSource,
8153 UITableViewDelegate
8154 > {
8155 _transient Database *database_;
8156 unsigned era_;
8157
8158 _H<UITableView, 2> list_;
8159 _H<NSMutableArray> sources_;
8160 int offset_;
8161
8162 _H<NSString> href_;
8163 _H<UIProgressHUD> hud_;
8164 _H<NSError> error_;
8165
8166 //NSURLConnection *installer_;
8167 NSURLConnection *trivial_;
8168 NSURLConnection *trivial_bz2_;
8169 NSURLConnection *trivial_gz_;
8170 //NSURLConnection *automatic_;
8171
8172 BOOL cydia_;
8173 }
8174
8175 - (id) initWithDatabase:(Database *)database;
8176 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8177
8178 @end
8179
8180 @implementation SourcesController
8181
8182 - (void) _releaseConnection:(NSURLConnection *)connection {
8183 if (connection != nil) {
8184 [connection cancel];
8185 //[connection setDelegate:nil];
8186 [connection release];
8187 }
8188 }
8189
8190 - (void) dealloc {
8191 //[self _releaseConnection:installer_];
8192 [self _releaseConnection:trivial_];
8193 [self _releaseConnection:trivial_gz_];
8194 [self _releaseConnection:trivial_bz2_];
8195 //[self _releaseConnection:automatic_];
8196
8197 [super dealloc];
8198 }
8199
8200 - (NSURL *) navigationURL {
8201 return [NSURL URLWithString:@"cydia://sources"];
8202 }
8203
8204 - (void) viewDidAppear:(BOOL)animated {
8205 [super viewDidAppear:animated];
8206 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8207 }
8208
8209 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8210 return 1;
8211 }
8212
8213 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8214 return nil;
8215 }
8216
8217 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8218 return [sources_ count];
8219 }
8220
8221 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8222 @synchronized (database_) {
8223 if ([database_ era] != era_)
8224 return nil;
8225
8226 return [sources_ objectAtIndex:[indexPath row]];
8227 } }
8228
8229 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8230 static NSString *cellIdentifier = @"SourceCell";
8231
8232 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8233 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8234 [cell setSource:[self sourceAtIndexPath:indexPath]];
8235 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8236
8237 return cell;
8238 }
8239
8240 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8241 Source *source = [self sourceAtIndexPath:indexPath];
8242
8243 SourceController *controller = [[[SourceController alloc]
8244 initWithDatabase:database_
8245 source:source
8246 ] autorelease];
8247
8248 [controller setDelegate:delegate_];
8249
8250 [[self navigationController] pushViewController:controller animated:YES];
8251 }
8252
8253 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8254 Source *source = [self sourceAtIndexPath:indexPath];
8255 return [source record] != nil;
8256 }
8257
8258 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8259 if (editingStyle == UITableViewCellEditingStyleDelete) {
8260 Source *source = [self sourceAtIndexPath:indexPath];
8261 [Sources_ removeObjectForKey:[source key]];
8262 [delegate_ syncData];
8263 }
8264 }
8265
8266 - (void) complete {
8267 [delegate_ addTrivialSource:href_];
8268 href_ = nil;
8269
8270 [delegate_ syncData];
8271 }
8272
8273 - (NSString *) getWarning {
8274 NSString *href(href_);
8275 NSRange colon([href rangeOfString:@"://"]);
8276 if (colon.location != NSNotFound)
8277 href = [href substringFromIndex:(colon.location + 3)];
8278 href = [href stringByAddingPercentEscapes];
8279 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8280
8281 NSURL *url([NSURL URLWithString:href]);
8282
8283 NSStringEncoding encoding;
8284 NSError *error(nil);
8285
8286 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8287 return [warning length] == 0 ? nil : warning;
8288 return nil;
8289 }
8290
8291 - (void) _endConnection:(NSURLConnection *)connection {
8292 // XXX: the memory management in this method is horribly awkward
8293
8294 NSURLConnection **field = NULL;
8295 if (connection == trivial_)
8296 field = &trivial_;
8297 else if (connection == trivial_bz2_)
8298 field = &trivial_bz2_;
8299 else if (connection == trivial_gz_)
8300 field = &trivial_gz_;
8301 _assert(field != NULL);
8302 [connection release];
8303 *field = nil;
8304
8305 if (
8306 trivial_ == nil &&
8307 trivial_bz2_ == nil &&
8308 trivial_gz_ == nil
8309 ) {
8310 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8311
8312 [delegate_ releaseNetworkActivityIndicator];
8313
8314 [delegate_ removeProgressHUD:hud_];
8315 hud_ = nil;
8316
8317 if (cydia_) {
8318 if (warning != nil) {
8319 UIAlertView *alert = [[[UIAlertView alloc]
8320 initWithTitle:UCLocalize("SOURCE_WARNING")
8321 message:warning
8322 delegate:self
8323 cancelButtonTitle:UCLocalize("CANCEL")
8324 otherButtonTitles:
8325 UCLocalize("ADD_ANYWAY"),
8326 nil
8327 ] autorelease];
8328
8329 [alert setContext:@"warning"];
8330 [alert setNumberOfRows:1];
8331 [alert show];
8332
8333 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8334 error_ = nil;
8335 return;
8336 }
8337
8338 [self complete];
8339 } else if (error_ != nil) {
8340 UIAlertView *alert = [[[UIAlertView alloc]
8341 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8342 message:[error_ localizedDescription]
8343 delegate:self
8344 cancelButtonTitle:UCLocalize("OK")
8345 otherButtonTitles:nil
8346 ] autorelease];
8347
8348 [alert setContext:@"urlerror"];
8349 [alert show];
8350
8351 href_ = nil;
8352 } else {
8353 UIAlertView *alert = [[[UIAlertView alloc]
8354 initWithTitle:UCLocalize("NOT_REPOSITORY")
8355 message:UCLocalize("NOT_REPOSITORY_EX")
8356 delegate:self
8357 cancelButtonTitle:UCLocalize("OK")
8358 otherButtonTitles:nil
8359 ] autorelease];
8360
8361 [alert setContext:@"trivial"];
8362 [alert show];
8363
8364 href_ = nil;
8365 }
8366
8367 error_ = nil;
8368 }
8369 }
8370
8371 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8372 switch ([response statusCode]) {
8373 case 200:
8374 cydia_ = YES;
8375 }
8376 }
8377
8378 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8379 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8380 error_ = error;
8381 [self _endConnection:connection];
8382 }
8383
8384 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8385 [self _endConnection:connection];
8386 }
8387
8388 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8389 NSURL *url([NSURL URLWithString:href]);
8390
8391 NSMutableURLRequest *request = [NSMutableURLRequest
8392 requestWithURL:url
8393 cachePolicy:NSURLRequestUseProtocolCachePolicy
8394 timeoutInterval:120.0
8395 ];
8396
8397 [request setHTTPMethod:method];
8398
8399 if (Machine_ != NULL)
8400 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8401
8402 if ([url isCydiaSecure]) {
8403 if (UniqueID_ != nil) {
8404 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8405 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8406 }
8407 }
8408
8409 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8410 }
8411
8412 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8413 NSString *context([alert context]);
8414
8415 if ([context isEqualToString:@"source"]) {
8416 switch (button) {
8417 case 1: {
8418 NSString *href = [[alert textField] text];
8419
8420 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8421
8422 if (![href hasSuffix:@"/"])
8423 href_ = [href stringByAppendingString:@"/"];
8424 else
8425 href_ = href;
8426
8427 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8428 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8429 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8430 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8431
8432 cydia_ = false;
8433
8434 // XXX: this is stupid
8435 hud_ = [delegate_ addProgressHUD];
8436 [hud_ setText:UCLocalize("VERIFYING_URL")];
8437 [delegate_ retainNetworkActivityIndicator];
8438 } break;
8439
8440 case 0:
8441 break;
8442
8443 _nodefault
8444 }
8445
8446 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8447 } else if ([context isEqualToString:@"trivial"])
8448 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8449 else if ([context isEqualToString:@"urlerror"])
8450 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8451 else if ([context isEqualToString:@"warning"]) {
8452 switch (button) {
8453 case 1:
8454 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8455 break;
8456
8457 case 0:
8458 break;
8459
8460 _nodefault
8461 }
8462
8463 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8464 }
8465 }
8466
8467 - (void) loadView {
8468 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8469
8470 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8471 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8472 [list_ setRowHeight:53];
8473 [(UITableView *) list_ setDataSource:self];
8474 [list_ setDelegate:self];
8475 [[self view] addSubview:list_];
8476 }
8477
8478 - (void) viewDidLoad {
8479 [super viewDidLoad];
8480
8481 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8482 [self updateButtonsForEditingStatus:NO animated:NO];
8483 }
8484
8485 - (void) releaseSubviews {
8486 list_ = nil;
8487
8488 sources_ = nil;
8489
8490 [super releaseSubviews];
8491 }
8492
8493 - (id) initWithDatabase:(Database *)database {
8494 if ((self = [super init]) != nil) {
8495 database_ = database;
8496 } return self;
8497 }
8498
8499 - (void) reloadData {
8500 [super reloadData];
8501
8502 @synchronized (database_) {
8503 era_ = [database_ era];
8504
8505 pkgSourceList list;
8506 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8507 return;
8508
8509 sources_ = [NSMutableArray arrayWithCapacity:16];
8510 [sources_ addObjectsFromArray:[database_ sources]];
8511 _trace();
8512 [sources_ sortUsingSelector:@selector(compareByName:)];
8513 _trace();
8514
8515 int count([sources_ count]);
8516 offset_ = 0;
8517 for (int i = 0; i != count; i++) {
8518 if ([[sources_ objectAtIndex:i] record] == nil)
8519 break;
8520 offset_++;
8521 }
8522
8523 [list_ setEditing:NO];
8524 [self updateButtonsForEditingStatus:NO animated:NO];
8525 [list_ reloadData];
8526 } }
8527
8528 - (void) showAddSourcePrompt {
8529 UIAlertView *alert = [[[UIAlertView alloc]
8530 initWithTitle:UCLocalize("ENTER_APT_URL")
8531 message:nil
8532 delegate:self
8533 cancelButtonTitle:UCLocalize("CANCEL")
8534 otherButtonTitles:
8535 UCLocalize("ADD_SOURCE"),
8536 nil
8537 ] autorelease];
8538
8539 [alert setContext:@"source"];
8540
8541 [alert setNumberOfRows:1];
8542 [alert addTextFieldWithValue:@"http://" label:@""];
8543
8544 UITextInputTraits *traits = [[alert textField] textInputTraits];
8545 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8546 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8547 [traits setKeyboardType:UIKeyboardTypeURL];
8548 // XXX: UIReturnKeyDone
8549 [traits setReturnKeyType:UIReturnKeyNext];
8550
8551 [alert show];
8552 }
8553
8554 - (void) addButtonClicked {
8555 [self showAddSourcePrompt];
8556 }
8557
8558 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8559 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8560 initWithTitle:UCLocalize("ADD")
8561 style:UIBarButtonItemStylePlain
8562 target:self
8563 action:@selector(addButtonClicked)
8564 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8565
8566 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8567 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8568 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8569 target:self
8570 action:@selector(editButtonClicked)
8571 ] autorelease] animated:animated];
8572
8573 if (IsWildcat_ && !editing)
8574 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8575 initWithTitle:UCLocalize("SETTINGS")
8576 style:UIBarButtonItemStylePlain
8577 target:self
8578 action:@selector(settingsButtonClicked)
8579 ] autorelease]];
8580 }
8581
8582 - (void) settingsButtonClicked {
8583 [delegate_ showSettings];
8584 }
8585
8586 - (void) editButtonClicked {
8587 [list_ setEditing:![list_ isEditing] animated:YES];
8588
8589 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8590 }
8591
8592 @end
8593 /* }}} */
8594
8595 /* Settings Controller {{{ */
8596 @interface SettingsController : CyteViewController <
8597 UITableViewDataSource,
8598 UITableViewDelegate
8599 > {
8600 _transient Database *database_;
8601 // XXX: ok, "roledelegate_"?...
8602 _transient id roledelegate_;
8603 _H<UITableView, 2> table_;
8604 _H<UISegmentedControl> segment_;
8605 _H<UIView> container_;
8606 }
8607
8608 - (void) showDoneButton;
8609 - (void) resizeSegmentedControl;
8610
8611 @end
8612
8613 @implementation SettingsController
8614
8615 - (void) loadView {
8616 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8617
8618 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8619 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8620 [table_ setDelegate:self];
8621 [(UITableView *) table_ setDataSource:self];
8622 [[self view] addSubview:table_];
8623
8624 NSArray *items = [NSArray arrayWithObjects:
8625 UCLocalize("USER"),
8626 UCLocalize("HACKER"),
8627 UCLocalize("DEVELOPER"),
8628 nil];
8629 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8630 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8631 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8632 [container_ addSubview:segment_];
8633 }
8634
8635 - (void) viewDidLoad {
8636 [super viewDidLoad];
8637
8638 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8639
8640 int index = -1;
8641 if ([Role_ isEqualToString:@"User"]) index = 0;
8642 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8643 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8644 if (index != -1) {
8645 [segment_ setSelectedSegmentIndex:index];
8646 [self showDoneButton];
8647 }
8648
8649 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8650 [self resizeSegmentedControl];
8651 }
8652
8653 - (void) releaseSubviews {
8654 table_ = nil;
8655 segment_ = nil;
8656 container_ = nil;
8657
8658 [super releaseSubviews];
8659 }
8660
8661 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8662 if ((self = [super init]) != nil) {
8663 database_ = database;
8664 roledelegate_ = delegate;
8665 } return self;
8666 }
8667
8668 - (void) resizeSegmentedControl {
8669 CGFloat width = [[self view] frame].size.width;
8670 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8671 }
8672
8673 - (void) viewWillAppear:(BOOL)animated {
8674 [super viewWillAppear:animated];
8675
8676 [self resizeSegmentedControl];
8677 }
8678
8679 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8680 [self resizeSegmentedControl];
8681 }
8682
8683 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8684 [self resizeSegmentedControl];
8685 }
8686
8687 - (void) save {
8688 NSString *role(nil);
8689
8690 switch ([segment_ selectedSegmentIndex]) {
8691 case 0: role = @"User"; break;
8692 case 1: role = @"Hacker"; break;
8693 case 2: role = @"Developer"; break;
8694
8695 _nodefault
8696 }
8697
8698 if (![role isEqualToString:Role_]) {
8699 bool rolling(Role_ == nil);
8700 Role_ = role;
8701
8702 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8703 Role_, @"Role",
8704 nil];
8705
8706 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8707 Changed_ = true;
8708
8709 if (rolling)
8710 [roledelegate_ loadData];
8711 else
8712 [roledelegate_ updateData];
8713 }
8714 }
8715
8716 - (void) segmentChanged:(UISegmentedControl *)control {
8717 [self showDoneButton];
8718 }
8719
8720 - (void) saveAndClose {
8721 [self save];
8722
8723 [[self navigationItem] setRightBarButtonItem:nil];
8724 [[self navigationController] dismissModalViewControllerAnimated:YES];
8725 }
8726
8727 - (void) doneButtonClicked {
8728 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8729 [spinner startAnimating];
8730 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8731 [[self navigationItem] setRightBarButtonItem:spinItem];
8732
8733 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8734 }
8735
8736 - (void) showDoneButton {
8737 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8738 initWithTitle:UCLocalize("DONE")
8739 style:UIBarButtonItemStyleDone
8740 target:self
8741 action:@selector(doneButtonClicked)
8742 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8743 }
8744
8745 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8746 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8747 return 6;
8748 }
8749
8750 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8751 return 0; // :(
8752 }
8753
8754 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8755 return nil; // This method is required by the protocol.
8756 }
8757
8758 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8759 if (section == 1)
8760 return UCLocalize("ROLE_EX");
8761 if (section == 4)
8762 return [NSString stringWithFormat:
8763 @"%@: %@\n%@: %@\n%@: %@",
8764 UCLocalize("USER"), UCLocalize("USER_EX"),
8765 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8766 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8767 ];
8768 else return nil;
8769 }
8770
8771 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8772 return section == 3 ? 44.0f : 0;
8773 }
8774
8775 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8776 return section == 3 ? container_ : nil;
8777 }
8778
8779 - (void) reloadData {
8780 [super reloadData];
8781
8782 [table_ reloadData];
8783 }
8784
8785 @end
8786 /* }}} */
8787 /* Stash Controller {{{ */
8788 @interface StashController : CyteViewController {
8789 _H<UIActivityIndicatorView> spinner_;
8790 _H<UILabel> status_;
8791 _H<UILabel> caption_;
8792 }
8793
8794 @end
8795
8796 @implementation StashController
8797
8798 - (void) loadView {
8799 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8800 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8801
8802 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8803 CGRect spinrect = [spinner_ frame];
8804 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8805 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8806 [spinner_ setFrame:spinrect];
8807 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8808 [[self view] addSubview:spinner_];
8809 [spinner_ startAnimating];
8810
8811 CGRect captrect;
8812 captrect.size.width = [[self view] frame].size.width;
8813 captrect.size.height = 40.0f;
8814 captrect.origin.x = 0;
8815 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8816 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8817 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8818 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8819 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8820 [caption_ setTextColor:[UIColor whiteColor]];
8821 [caption_ setBackgroundColor:[UIColor clearColor]];
8822 [caption_ setShadowColor:[UIColor blackColor]];
8823 [caption_ setTextAlignment:UITextAlignmentCenter];
8824 [[self view] addSubview:caption_];
8825
8826 CGRect statusrect;
8827 statusrect.size.width = [[self view] frame].size.width;
8828 statusrect.size.height = 30.0f;
8829 statusrect.origin.x = 0;
8830 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8831 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8832 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8833 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8834 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8835 [status_ setTextColor:[UIColor whiteColor]];
8836 [status_ setBackgroundColor:[UIColor clearColor]];
8837 [status_ setShadowColor:[UIColor blackColor]];
8838 [status_ setTextAlignment:UITextAlignmentCenter];
8839 [[self view] addSubview:status_];
8840 }
8841
8842 - (void) releaseSubviews {
8843 spinner_ = nil;
8844 status_ = nil;
8845 caption_ = nil;
8846
8847 [super releaseSubviews];
8848 }
8849
8850 @end
8851 /* }}} */
8852
8853 @interface CYURLCache : SDURLCache {
8854 }
8855
8856 @end
8857
8858 @implementation CYURLCache
8859
8860 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8861 #if !ForRelease
8862 if (false);
8863 else if ([event isEqualToString:@"no-cache"])
8864 event = @"!!!";
8865 else if ([event isEqualToString:@"store"])
8866 event = @">>>";
8867 else if ([event isEqualToString:@"invalid"])
8868 event = @"???";
8869 else if ([event isEqualToString:@"memory"])
8870 event = @"mem";
8871 else if ([event isEqualToString:@"disk"])
8872 event = @"ssd";
8873 else if ([event isEqualToString:@"miss"])
8874 event = @"---";
8875
8876 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8877 #endif
8878 }
8879
8880 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8881 if (NSURLResponse *response = [cached response])
8882 if (NSString *mime = [response MIMEType])
8883 if ([mime isEqualToString:@"text/cache-manifest"]) {
8884 NSURL *url([response URL]);
8885
8886 #if !ForRelease
8887 NSLog(@"###: %@", [url absoluteString]);
8888 #endif
8889
8890 @synchronized (HostConfig_) {
8891 [CachedURLs_ addObject:url];
8892 }
8893 }
8894
8895 [super storeCachedResponse:cached forRequest:request];
8896 }
8897
8898 @end
8899
8900 @interface Cydia : UIApplication <
8901 ConfirmationControllerDelegate,
8902 DatabaseDelegate,
8903 CydiaDelegate,
8904 UINavigationControllerDelegate,
8905 UITabBarControllerDelegate
8906 > {
8907 _H<UIWindow> window_;
8908 _H<CYTabBarController> tabbar_;
8909 _H<CydiaLoadingViewController> emulated_;
8910
8911 _H<NSMutableArray> essential_;
8912 _H<NSMutableArray> broken_;
8913
8914 Database *database_;
8915
8916 _H<NSURL> starturl_;
8917
8918 unsigned locked_;
8919 unsigned activity_;
8920
8921 _H<StashController> stash_;
8922
8923 bool loaded_;
8924 }
8925
8926 - (void) loadData;
8927
8928 @end
8929
8930 @implementation Cydia
8931
8932 - (void) beginUpdate {
8933 [tabbar_ beginUpdate];
8934 }
8935
8936 - (BOOL) updating {
8937 return [tabbar_ updating];
8938 }
8939
8940 - (void) _loaded {
8941 if ([broken_ count] != 0) {
8942 int count = [broken_ count];
8943
8944 UIAlertView *alert = [[[UIAlertView alloc]
8945 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8946 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8947 delegate:self
8948 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8949 otherButtonTitles:
8950 UCLocalize("TEMPORARY_IGNORE"),
8951 nil
8952 ] autorelease];
8953
8954 [alert setContext:@"fixhalf"];
8955 [alert setNumberOfRows:2];
8956 [alert show];
8957 } else if (!Ignored_ && [essential_ count] != 0) {
8958 int count = [essential_ count];
8959
8960 UIAlertView *alert = [[[UIAlertView alloc]
8961 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8962 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8963 delegate:self
8964 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8965 otherButtonTitles:
8966 UCLocalize("UPGRADE_ESSENTIAL"),
8967 UCLocalize("COMPLETE_UPGRADE"),
8968 nil
8969 ] autorelease];
8970
8971 [alert setContext:@"upgrade"];
8972 [alert show];
8973 }
8974 }
8975
8976 - (void) returnToCydia {
8977 [self _loaded];
8978 }
8979
8980 - (void) _saveConfig {
8981 @synchronized (database_) {
8982 _trace();
8983 MetaFile_.Sync();
8984 _trace();
8985 }
8986
8987 if (Changed_) {
8988 NSString *error(nil);
8989
8990 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8991 _trace();
8992 NSError *error(nil);
8993 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8994 NSLog(@"failure to save metadata data: %@", error);
8995 _trace();
8996
8997 Changed_ = false;
8998 } else {
8999 NSLog(@"failure to serialize metadata: %@", error);
9000 }
9001 }
9002
9003 CydiaWriteSources();
9004 }
9005
9006 // Navigation controller for the queuing badge.
9007 - (UINavigationController *) queueNavigationController {
9008 NSArray *controllers = [tabbar_ viewControllers];
9009 return [controllers objectAtIndex:3];
9010 }
9011
9012 - (void) unloadData {
9013 [tabbar_ unloadData];
9014 }
9015
9016 - (void) _updateData {
9017 [self _saveConfig];
9018 [self unloadData];
9019
9020 UINavigationController *navigation = [self queueNavigationController];
9021
9022 id queuedelegate = nil;
9023 if ([[navigation viewControllers] count] > 0)
9024 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9025
9026 [queuedelegate queueStatusDidChange];
9027 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9028 }
9029
9030 - (void) _refreshIfPossible:(NSDate *)update {
9031 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9032
9033 bool recently = false;
9034 if (update != nil) {
9035 NSTimeInterval interval([update timeIntervalSinceNow]);
9036 if (interval <= 0 && interval > -(15*60))
9037 recently = true;
9038 }
9039
9040 // Don't automatic refresh if:
9041 // - We already refreshed recently.
9042 // - We already auto-refreshed this launch.
9043 // - Auto-refresh is disabled.
9044 if (recently || loaded_ || ManualRefresh) {
9045 // If we are cancelling, we need to make sure it knows it's already loaded.
9046 loaded_ = true;
9047
9048 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9049 } else {
9050 // We are going to load, so remember that.
9051 loaded_ = true;
9052
9053 SCNetworkReachabilityFlags flags; {
9054 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9055 SCNetworkReachabilityGetFlags(reachability, &flags);
9056 CFRelease(reachability);
9057 }
9058
9059 // XXX: this elaborate mess is what Apple is using to determine this? :(
9060 // XXX: do we care if the user has to intervene? maybe that's ok?
9061 bool reachable(
9062 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9063 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9064 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9065 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9066 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9067 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9068 )
9069 );
9070
9071 // If we can reach the server, auto-refresh!
9072 if (reachable)
9073 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9074 }
9075
9076 [pool release];
9077 }
9078
9079 - (void) refreshIfPossible {
9080 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9081 }
9082
9083 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9084 @synchronized (self) {
9085 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9086 [hud setText:UCLocalize("RELOADING_DATA")];
9087
9088 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9089
9090 size_t changes(0);
9091
9092 [essential_ removeAllObjects];
9093 [broken_ removeAllObjects];
9094
9095 NSArray *packages([database_ packages]);
9096 for (Package *package in packages) {
9097 if ([package half])
9098 [broken_ addObject:package];
9099 if ([package upgradableAndEssential:NO]) {
9100 if ([package essential])
9101 [essential_ addObject:package];
9102 ++changes;
9103 }
9104 }
9105
9106 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9107 if (changes != 0) {
9108 _trace();
9109 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9110 [changesItem setBadgeValue:badge];
9111 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9112 [self setApplicationIconBadgeNumber:changes];
9113 } else {
9114 _trace();
9115 [changesItem setBadgeValue:nil];
9116 [changesItem setAnimatedBadge:NO];
9117 [self setApplicationIconBadgeNumber:0];
9118 }
9119
9120 [self _updateData];
9121
9122 if (hud != nil)
9123 [self removeProgressHUD:hud];
9124 } }
9125
9126 - (void) updateData {
9127 [self _updateData];
9128 }
9129
9130 - (void) update_ {
9131 [database_ update];
9132 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9133 }
9134
9135 - (void) disemulate {
9136 if (emulated_ == nil)
9137 return;
9138
9139 [window_ addSubview:[tabbar_ view]];
9140 [[emulated_ view] removeFromSuperview];
9141 emulated_ = nil;
9142 [window_ setUserInteractionEnabled:YES];
9143 }
9144
9145 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9146 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9147 if (IsWildcat_)
9148 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9149
9150 UIViewController *parent;
9151 if (emulated_ == nil)
9152 parent = tabbar_;
9153 else if (!force)
9154 parent = emulated_;
9155 else {
9156 [self disemulate];
9157 parent = tabbar_;
9158 }
9159
9160 [parent presentModalViewController:navigation animated:YES];
9161 }
9162
9163 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9164 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9165
9166 if (navigation != nil)
9167 [navigation pushViewController:progress animated:YES];
9168 else
9169 [self presentModalViewController:progress force:YES];
9170
9171 [progress invoke:invocation withTitle:title];
9172 return progress;
9173 }
9174
9175 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9176 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9177 }
9178
9179 - (void) repairWithInvocation:(NSInvocation *)invocation {
9180 _trace();
9181 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9182 _trace();
9183 }
9184
9185 - (void) repairWithSelector:(SEL)selector {
9186 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9187 }
9188
9189 - (void) reloadData {
9190 [self reloadDataWithInvocation:nil];
9191 if ([database_ progressDelegate] == nil)
9192 [self _loaded];
9193 }
9194
9195 - (void) syncData {
9196 [self _saveConfig];
9197 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9198 }
9199
9200 - (void) addSource:(NSDictionary *) source {
9201 CydiaAddSource(source);
9202 }
9203
9204 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9205 CydiaAddSource(href, distribution, sections);
9206 }
9207
9208 - (void) addTrivialSource:(NSString *)href {
9209 CydiaAddSource(href, @"./");
9210 }
9211
9212 - (void) updateValues {
9213 Changed_ = true;
9214 }
9215
9216 - (void) resolve {
9217 pkgProblemResolver *resolver = [database_ resolver];
9218
9219 resolver->InstallProtect();
9220 if (!resolver->Resolve(true))
9221 _error->Discard();
9222 }
9223
9224 - (bool) perform {
9225 // XXX: this is a really crappy way of doing this.
9226 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9227 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9228 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9229 if ([tabbar_ updating])
9230 [tabbar_ cancelUpdate];
9231
9232 if (![database_ prepare])
9233 return false;
9234
9235 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9236 [page setDelegate:self];
9237 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9238
9239 if (IsWildcat_)
9240 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9241 [tabbar_ presentModalViewController:confirm_ animated:YES];
9242
9243 return true;
9244 }
9245
9246 - (void) queue {
9247 @synchronized (self) {
9248 [self perform];
9249 }
9250 }
9251
9252 - (void) clearPackage:(Package *)package {
9253 @synchronized (self) {
9254 [package clear];
9255 [self resolve];
9256 [self perform];
9257 }
9258 }
9259
9260 - (void) installPackages:(NSArray *)packages {
9261 @synchronized (self) {
9262 for (Package *package in packages)
9263 [package install];
9264 [self resolve];
9265 [self perform];
9266 }
9267 }
9268
9269 - (void) installPackage:(Package *)package {
9270 @synchronized (self) {
9271 [package install];
9272 [self resolve];
9273 [self perform];
9274 }
9275 }
9276
9277 - (void) removePackage:(Package *)package {
9278 @synchronized (self) {
9279 [package remove];
9280 [self resolve];
9281 [self perform];
9282 }
9283 }
9284
9285 - (void) distUpgrade {
9286 @synchronized (self) {
9287 if (![database_ upgrade])
9288 return;
9289 [self perform];
9290 }
9291 }
9292
9293 - (void) perform_ {
9294 [database_ perform];
9295 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9296 }
9297
9298 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9299 Queuing_ = false;
9300 ++locked_;
9301 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9302 --locked_;
9303 [self refreshIfPossible];
9304 }
9305
9306 - (void) showSettings {
9307 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9308 }
9309
9310 - (void) retainNetworkActivityIndicator {
9311 if (activity_++ == 0)
9312 [self setNetworkActivityIndicatorVisible:YES];
9313
9314 #if TraceLogging
9315 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9316 #endif
9317 }
9318
9319 - (void) releaseNetworkActivityIndicator {
9320 if (--activity_ == 0)
9321 [self setNetworkActivityIndicatorVisible:NO];
9322
9323 #if TraceLogging
9324 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9325 #endif
9326
9327 }
9328
9329 - (void) cancelAndClear:(bool)clear {
9330 @synchronized (self) {
9331 if (clear) {
9332 [database_ clear];
9333 Queuing_ = false;
9334 } else {
9335 Queuing_ = true;
9336 }
9337
9338 [self _updateData];
9339 }
9340 }
9341
9342 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9343 NSString *context([alert context]);
9344
9345 if ([context isEqualToString:@"conffile"]) {
9346 FILE *input = [database_ input];
9347 if (button == [alert cancelButtonIndex])
9348 fprintf(input, "N\n");
9349 else if (button == [alert firstOtherButtonIndex])
9350 fprintf(input, "Y\n");
9351 fflush(input);
9352
9353 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9354 } else if ([context isEqualToString:@"fixhalf"]) {
9355 if (button == [alert cancelButtonIndex]) {
9356 @synchronized (self) {
9357 for (Package *broken in (id) broken_) {
9358 [broken remove];
9359
9360 NSString *id = [broken id];
9361 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9362 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9363 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9364 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9365 }
9366
9367 [self resolve];
9368 [self perform];
9369 }
9370 } else if (button == [alert firstOtherButtonIndex]) {
9371 [broken_ removeAllObjects];
9372 [self _loaded];
9373 }
9374
9375 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9376 } else if ([context isEqualToString:@"upgrade"]) {
9377 if (button == [alert firstOtherButtonIndex]) {
9378 @synchronized (self) {
9379 for (Package *essential in (id) essential_)
9380 [essential install];
9381
9382 [self resolve];
9383 [self perform];
9384 }
9385 } else if (button == [alert firstOtherButtonIndex] + 1) {
9386 [self distUpgrade];
9387 } else if (button == [alert cancelButtonIndex]) {
9388 Ignored_ = YES;
9389 }
9390
9391 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9392 }
9393 }
9394
9395 - (void) system:(NSString *)command {
9396 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9397
9398 _trace();
9399 system([command UTF8String]);
9400 _trace();
9401
9402 [pool release];
9403 }
9404
9405 - (void) applicationWillSuspend {
9406 [database_ clean];
9407 [super applicationWillSuspend];
9408 }
9409
9410 - (BOOL) isSafeToSuspend {
9411 if (locked_ != 0) {
9412 #if !ForRelease
9413 NSLog(@"isSafeToSuspend: locked_ != 0");
9414 #endif
9415 return false;
9416 }
9417
9418 // Use external process status API internally.
9419 // This is probably a really bad idea.
9420 // XXX: what is the point of this? does this solve anything at all?
9421 uint64_t status = 0;
9422 int notify_token;
9423 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9424 notify_get_state(notify_token, &status);
9425 notify_cancel(notify_token);
9426 }
9427
9428 if (status != 0) {
9429 #if !ForRelease
9430 NSLog(@"isSafeToSuspend: status != 0");
9431 #endif
9432 return false;
9433 }
9434
9435 #if !ForRelease
9436 NSLog(@"isSafeToSuspend: -> true");
9437 #endif
9438 return true;
9439 }
9440
9441 - (void) applicationSuspend:(__GSEvent *)event {
9442 if ([self isSafeToSuspend])
9443 [super applicationSuspend:event];
9444 }
9445
9446 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9447 if ([self isSafeToSuspend])
9448 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9449 }
9450
9451 - (void) _setSuspended:(BOOL)value {
9452 if ([self isSafeToSuspend])
9453 [super _setSuspended:value];
9454 }
9455
9456 - (UIProgressHUD *) addProgressHUD {
9457 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9458 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9459
9460 [window_ setUserInteractionEnabled:NO];
9461
9462 UIViewController *target(tabbar_);
9463 if (UIViewController *modal = [target modalViewController])
9464 target = modal;
9465
9466 [hud showInView:[target view]];
9467
9468 ++locked_;
9469 return hud;
9470 }
9471
9472 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9473 --locked_;
9474 [hud hide];
9475 [hud removeFromSuperview];
9476 [window_ setUserInteractionEnabled:YES];
9477 }
9478
9479 - (CyteViewController *) pageForPackage:(NSString *)name {
9480 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9481 }
9482
9483 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9484 NSString *scheme([[url scheme] lowercaseString]);
9485 if ([[url absoluteString] length] <= [scheme length] + 3)
9486 return nil;
9487 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9488 NSArray *components([path componentsSeparatedByString:@"/"]);
9489
9490 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9491 return [self pageForPackage:[components objectAtIndex:1]];
9492
9493 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9494 return nil;
9495
9496 NSString *base([components objectAtIndex:0]);
9497
9498 CyteViewController *controller = nil;
9499
9500 if ([base isEqualToString:@"url"]) {
9501 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9502 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9503 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9504 } else if (!external && [components count] == 1) {
9505 if ([base isEqualToString:@"manage"]) {
9506 controller = [[[ManageController alloc] init] autorelease];
9507 }
9508
9509 if ([base isEqualToString:@"storage"]) {
9510 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9511 }
9512
9513 if ([base isEqualToString:@"sources"]) {
9514 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9515 }
9516
9517 if ([base isEqualToString:@"home"]) {
9518 controller = [[[HomeController alloc] init] autorelease];
9519 }
9520
9521 if ([base isEqualToString:@"sections"]) {
9522 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9523 }
9524
9525 if ([base isEqualToString:@"search"]) {
9526 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9527 }
9528
9529 if ([base isEqualToString:@"changes"]) {
9530 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9531 }
9532
9533 if ([base isEqualToString:@"installed"]) {
9534 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9535 }
9536 } else if ([components count] == 2) {
9537 NSString *argument = [components objectAtIndex:1];
9538
9539 if ([base isEqualToString:@"package"]) {
9540 controller = [self pageForPackage:argument];
9541 }
9542
9543 if (!external && [base isEqualToString:@"search"]) {
9544 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9545 }
9546
9547 if (!external && [base isEqualToString:@"sections"]) {
9548 if ([argument isEqualToString:@"all"])
9549 argument = nil;
9550 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9551 }
9552
9553 if (!external && [base isEqualToString:@"sources"]) {
9554 if ([argument isEqualToString:@"add"]) {
9555 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9556 [(SourcesController *)controller showAddSourcePrompt];
9557 } else {
9558 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9559 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9560 }
9561 }
9562
9563 if (!external && [base isEqualToString:@"launch"]) {
9564 [self launchApplicationWithIdentifier:argument suspended:NO];
9565 return nil;
9566 }
9567 } else if (!external && [components count] == 3) {
9568 NSString *arg1 = [components objectAtIndex:1];
9569 NSString *arg2 = [components objectAtIndex:2];
9570
9571 if ([base isEqualToString:@"package"]) {
9572 if ([arg2 isEqualToString:@"settings"]) {
9573 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9574 } else if ([arg2 isEqualToString:@"files"]) {
9575 if (Package *package = [database_ packageWithName:arg1]) {
9576 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9577 [(FileTable *)controller setPackage:package];
9578 }
9579 }
9580 }
9581 }
9582
9583 [controller setDelegate:self];
9584 return controller;
9585 }
9586
9587 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9588 CyteViewController *page([self pageForURL:url forExternal:external]);
9589
9590 if (page != nil) {
9591 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9592 [nav setViewControllers:[NSArray arrayWithObject:page]];
9593 [tabbar_ setUnselectedViewController:nav];
9594 }
9595
9596 return page != nil;
9597 }
9598
9599 - (void) applicationOpenURL:(NSURL *)url {
9600 [super applicationOpenURL:url];
9601
9602 if (!loaded_)
9603 starturl_ = url;
9604 else
9605 [self openCydiaURL:url forExternal:YES];
9606 }
9607
9608 - (void) applicationWillResignActive:(UIApplication *)application {
9609 // Stop refreshing if you get a phone call or lock the device.
9610 if ([tabbar_ updating])
9611 [tabbar_ cancelUpdate];
9612
9613 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9614 [super applicationWillResignActive:application];
9615 }
9616
9617 - (void) saveState {
9618 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9619 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9620 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9621 Changed_ = true;
9622
9623 [self _saveConfig];
9624 }
9625
9626 - (void) applicationWillTerminate:(UIApplication *)application {
9627 [self saveState];
9628 }
9629
9630 - (void) setConfigurationData:(NSString *)data {
9631 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9632
9633 if (!conffile_r(data)) {
9634 lprintf("E:invalid conffile\n");
9635 return;
9636 }
9637
9638 NSString *ofile = conffile_r[1];
9639 //NSString *nfile = conffile_r[2];
9640
9641 UIAlertView *alert = [[[UIAlertView alloc]
9642 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9643 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9644 delegate:self
9645 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9646 otherButtonTitles:
9647 UCLocalize("ACCEPT_NEW_COPY"),
9648 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9649 nil
9650 ] autorelease];
9651
9652 [alert setContext:@"conffile"];
9653 [alert setNumberOfRows:2];
9654 [alert show];
9655 }
9656
9657 - (void) addStashController {
9658 ++locked_;
9659 stash_ = [[[StashController alloc] init] autorelease];
9660 [window_ addSubview:[stash_ view]];
9661 }
9662
9663 - (void) removeStashController {
9664 [[stash_ view] removeFromSuperview];
9665 stash_ = nil;
9666 --locked_;
9667 }
9668
9669 - (void) stash {
9670 [self setIdleTimerDisabled:YES];
9671
9672 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9673 UpdateExternalStatus(1);
9674 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9675 UpdateExternalStatus(0);
9676
9677 [self removeStashController];
9678
9679 pid_t pid(ExecFork());
9680 if (pid == 0) {
9681 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9682 perror("launchctl stop");
9683 exit(0);
9684 }
9685
9686 ReapZombie(pid);
9687 }
9688
9689 - (void) setupViewControllers {
9690 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9691
9692 NSMutableArray *items([NSMutableArray arrayWithObjects:
9693 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9694 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9695 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9696 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9697 nil]);
9698
9699 if (IsWildcat_) {
9700 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9701 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9702 } else {
9703 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9704 }
9705
9706 NSMutableArray *controllers([NSMutableArray array]);
9707 for (UITabBarItem *item in items) {
9708 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9709 [controller setTabBarItem:item];
9710 [controllers addObject:controller];
9711 }
9712 [tabbar_ setViewControllers:controllers];
9713
9714 [tabbar_ setUpdateDelegate:self];
9715 }
9716
9717 - (void) _sendMemoryWarningNotification {
9718 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9719 }
9720
9721 - (void) _sendMemoryWarningNotifications {
9722 while (true) {
9723 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9724 usleep(250000);
9725 }
9726 }
9727
9728 - (void) applicationDidFinishLaunching:(id)unused {
9729 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9730
9731 _trace();
9732 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9733 [self setApplicationSupportsShakeToEdit:NO];
9734
9735 @synchronized (HostConfig_) {
9736 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9737 }
9738
9739 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9740 initWithMemoryCapacity:524288
9741 diskCapacity:10485760
9742 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9743 ] autorelease]];
9744
9745 [CydiaWebViewController _initialize];
9746
9747 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9748
9749 // this would disallow http{,s} URLs from accessing this data
9750 //[WebView registerURLSchemeAsLocal:@"cydia"];
9751
9752 Font12_ = [UIFont systemFontOfSize:12];
9753 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9754 Font14_ = [UIFont systemFontOfSize:14];
9755 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9756 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9757
9758 essential_ = [NSMutableArray arrayWithCapacity:4];
9759 broken_ = [NSMutableArray arrayWithCapacity:4];
9760
9761 // XXX: I really need this thing... like, seriously... I'm sorry
9762 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9763
9764 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9765 [window_ orderFront:self];
9766 [window_ makeKey:self];
9767 [window_ setHidden:NO];
9768
9769 if (
9770 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9771 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9772 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9773 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9774 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9775 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9776 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9777 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9778 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9779 false
9780 ) {
9781 [self addStashController];
9782 // XXX: this would be much cleaner as a yieldToSelector:
9783 // that way the removeStashController could happen right here inline
9784 // we also could no longer require the useless stash_ field anymore
9785 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9786 return;
9787 }
9788
9789 database_ = [Database sharedInstance];
9790 [database_ setDelegate:self];
9791
9792 [window_ setUserInteractionEnabled:NO];
9793 [self setupViewControllers];
9794
9795 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9796 [window_ addSubview:[emulated_ view]];
9797
9798 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9799 _trace();
9800 }
9801
9802 - (NSArray *) defaultStartPages {
9803 NSMutableArray *standard = [NSMutableArray array];
9804 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9805 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9806 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9807 if (!IsWildcat_) {
9808 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9809 } else {
9810 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9811 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9812 }
9813 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9814 return standard;
9815 }
9816
9817 - (void) loadData {
9818 _trace();
9819 if (Role_ == nil) {
9820 [window_ setUserInteractionEnabled:YES];
9821 [self showSettings];
9822 return;
9823 } else {
9824 if ([emulated_ modalViewController] != nil)
9825 [emulated_ dismissModalViewControllerAnimated:YES];
9826 [window_ setUserInteractionEnabled:NO];
9827 }
9828
9829 [self reloadDataWithInvocation:nil];
9830 [self refreshIfPossible];
9831 PrintTimes();
9832
9833 [self disemulate];
9834
9835 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9836 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9837 int standardIndex = 0;
9838 NSArray *standard = [self defaultStartPages];
9839
9840 BOOL valid = YES;
9841
9842 if (saved == nil)
9843 valid = NO;
9844
9845 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9846 if (valid && closed != nil) {
9847 NSTimeInterval interval([closed timeIntervalSinceNow]);
9848 // XXX: Is 15 minutes the optimal time here?
9849 if (interval > 0 && interval <= -(15*60))
9850 valid = NO;
9851 }
9852
9853 if (valid && [saved count] != [standard count])
9854 valid = NO;
9855
9856 if (valid) {
9857 for (unsigned int i = 0; i < [standard count]; i++) {
9858 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9859 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9860 // but it's good enough for now.
9861 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9862 valid = NO;
9863 break;
9864 }
9865 }
9866 }
9867
9868 NSArray *items = nil;
9869 if (valid) {
9870 [tabbar_ setSelectedIndex:savedIndex];
9871 items = saved;
9872 } else {
9873 [tabbar_ setSelectedIndex:standardIndex];
9874 items = standard;
9875 }
9876
9877 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9878 NSArray *stack = [items objectAtIndex:tab];
9879 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9880 NSMutableArray *current = [NSMutableArray array];
9881
9882 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9883 NSString *addr = [stack objectAtIndex:nav];
9884 NSURL *url = [NSURL URLWithString:addr];
9885 CyteViewController *page = [self pageForURL:url forExternal:NO];
9886 if (page != nil)
9887 [current addObject:page];
9888 }
9889
9890 [navigation setViewControllers:current];
9891 }
9892
9893 // (Try to) show the startup URL.
9894 if (starturl_ != nil) {
9895 [self openCydiaURL:starturl_ forExternal:NO];
9896 starturl_ = nil;
9897 }
9898 }
9899
9900 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9901 if (item != nil && IsWildcat_) {
9902 [sheet showFromBarButtonItem:item animated:YES];
9903 } else {
9904 [sheet showInView:window_];
9905 }
9906 }
9907
9908 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9909 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9910 [progress setTitle:task];
9911 [progress addProgressEvent:event];
9912 }
9913
9914 - (void) addProgressEventForTask:(NSArray *)data {
9915 CydiaProgressEvent *event([data objectAtIndex:0]);
9916 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9917 [self addProgressEvent:event forTask:task];
9918 }
9919
9920 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9921 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9922 }
9923
9924 @end
9925
9926 /*IMP alloc_;
9927 id Alloc_(id self, SEL selector) {
9928 id object = alloc_(self, selector);
9929 lprintf("[%s]A-%p\n", self->isa->name, object);
9930 return object;
9931 }*/
9932
9933 /*IMP dealloc_;
9934 id Dealloc_(id self, SEL selector) {
9935 id object = dealloc_(self, selector);
9936 lprintf("[%s]D-%p\n", self->isa->name, object);
9937 return object;
9938 }*/
9939
9940 Class $WebDefaultUIKitDelegate;
9941
9942 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9943 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9944 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9945 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9946 }
9947
9948 static NSSet *MobilizedFiles_;
9949
9950 static NSURL *MobilizeURL(NSURL *url) {
9951 NSString *path([url path]);
9952 if ([path hasPrefix:@"/var/root/"]) {
9953 NSString *file([path substringFromIndex:10]);
9954 if ([MobilizedFiles_ containsObject:file])
9955 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9956 }
9957
9958 return url;
9959 }
9960
9961 Class $CFXPreferencesPropertyListSource;
9962 @class CFXPreferencesPropertyListSource;
9963
9964 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9965 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9966 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9967 url = MobilizeURL(url);
9968 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9969 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9970 url = old;
9971 [pool release];
9972 return value;
9973 }
9974
9975 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9976 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9977 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9978 url = MobilizeURL(url);
9979 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9980 //NSLog(@"%@ %@", [url absoluteString], value);
9981 url = old;
9982 [pool release];
9983 return value;
9984 }
9985
9986 Class $NSURLConnection;
9987
9988 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9989 NSMutableURLRequest *copy([request mutableCopy]);
9990
9991 NSURL *url([copy URL]);
9992
9993 NSString *host([url host]);
9994 NSString *scheme([[url scheme] lowercaseString]);
9995
9996 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9997
9998 @synchronized (HostConfig_) {
9999 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10000 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10001 [copy setHTTPShouldUsePipelining:YES];
10002
10003 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10004 if ([control isEqualToString:@"max-age=0"])
10005 if ([CachedURLs_ containsObject:url]) {
10006 #if !ForRelease
10007 NSLog(@"~~~: %@", url);
10008 #endif
10009
10010 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10011
10012 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10013 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10014 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10015 }
10016 }
10017
10018 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10019 } return self;
10020 }
10021
10022 int main(int argc, char *argv[]) {
10023 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10024
10025 _trace();
10026
10027 UpdateExternalStatus(0);
10028
10029 if (Class $UIDevice = objc_getClass("UIDevice")) {
10030 UIDevice *device([$UIDevice currentDevice]);
10031 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10032 } else
10033 IsWildcat_ = false;
10034
10035 UIScreen *screen([UIScreen mainScreen]);
10036 if ([screen respondsToSelector:@selector(scale)])
10037 ScreenScale_ = [screen scale];
10038 else
10039 ScreenScale_ = 1;
10040
10041 UIDevice *device([UIDevice currentDevice]);
10042 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10043 Idiom_ = @"iphone";
10044 else {
10045 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10046 if (idiom == UIUserInterfaceIdiomPhone)
10047 Idiom_ = @"iphone";
10048 else if (idiom == UIUserInterfaceIdiomPad)
10049 Idiom_ = @"ipad";
10050 else
10051 NSLog(@"unknown UIUserInterfaceIdiom!");
10052 }
10053
10054 Pcre pattern("^([0-9]+\\.[0-9]+)");
10055
10056 if (pattern([device systemVersion]))
10057 Firmware_ = pattern[1];
10058 if (pattern(Cydia_))
10059 Major_ = pattern[1];
10060
10061 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10062
10063 HostConfig_ = [[[NSObject alloc] init] autorelease];
10064 @synchronized (HostConfig_) {
10065 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10066 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10067 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10068 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10069 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10070 }
10071
10072 NSString *ui(@"ui/ios");
10073 if (Idiom_ != nil)
10074 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10075 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10076 UI_ = CydiaURL(ui);
10077
10078 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10079
10080 MobilizedFiles_ = [NSMutableSet setWithObjects:
10081 @"Library/Preferences/com.apple.Accessibility.plist",
10082 @"Library/Preferences/com.apple.preferences.sounds.plist",
10083 nil];
10084
10085 /* Library Hacks {{{ */
10086 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10087
10088 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10089
10090 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10091 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10092 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10093 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10094 }
10095
10096 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10097 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10098 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10099 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10100 }
10101
10102 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10103 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10104 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10105 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10106 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10107 }
10108
10109 $NSURLConnection = objc_getClass("NSURLConnection");
10110 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10111 if (NSURLConnection$init$ != NULL) {
10112 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10113 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10114 }
10115 /* }}} */
10116 /* Set Locale {{{ */
10117 Locale_ = CFLocaleCopyCurrent();
10118 Languages_ = [NSLocale preferredLanguages];
10119
10120 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10121 //NSLog(@"%@", [Languages_ description]);
10122
10123 const char *lang;
10124 if (Locale_ != NULL)
10125 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10126 else if (Languages_ != nil && [Languages_ count] != 0)
10127 lang = [[Languages_ objectAtIndex:0] UTF8String];
10128 else
10129 // XXX: consider just setting to C and then falling through?
10130 lang = NULL;
10131
10132 if (lang != NULL) {
10133 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10134 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10135 }
10136
10137 NSLog(@"Setting Language: %s", lang);
10138
10139 if (lang != NULL) {
10140 setenv("LANG", lang, true);
10141 std::setlocale(LC_ALL, lang);
10142 }
10143 /* }}} */
10144
10145 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10146
10147 /* Parse Arguments {{{ */
10148 bool substrate(false);
10149
10150 if (argc != 0) {
10151 char **args(argv);
10152 int arge(1);
10153
10154 for (int argi(1); argi != argc; ++argi)
10155 if (strcmp(argv[argi], "--") == 0) {
10156 arge = argi;
10157 argv[argi] = argv[0];
10158 argv += argi;
10159 argc -= argi;
10160 break;
10161 }
10162
10163 for (int argi(1); argi != arge; ++argi)
10164 if (strcmp(args[argi], "--substrate") == 0)
10165 substrate = true;
10166 else
10167 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10168 }
10169 /* }}} */
10170
10171 App_ = [[NSBundle mainBundle] bundlePath];
10172 Advanced_ = YES;
10173
10174 setuid(0);
10175 setgid(0);
10176
10177 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10178 alloc_ = alloc->method_imp;
10179 alloc->method_imp = (IMP) &Alloc_;*/
10180
10181 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10182 dealloc_ = dealloc->method_imp;
10183 dealloc->method_imp = (IMP) &Dealloc_;*/
10184
10185 /* System Information {{{ */
10186 size_t size;
10187
10188 int maxproc;
10189 size = sizeof(maxproc);
10190 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10191 perror("sysctlbyname(\"kern.maxproc\", ?)");
10192 else if (maxproc < 64) {
10193 maxproc = 64;
10194 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10195 perror("sysctlbyname(\"kern.maxproc\", #)");
10196 }
10197
10198 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10199 char *osversion = new char[size];
10200 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10201 perror("sysctlbyname(\"kern.osversion\", ?)");
10202 else
10203 System_ = [NSString stringWithUTF8String:osversion];
10204
10205 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10206 char *machine = new char[size];
10207 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10208 perror("sysctlbyname(\"hw.machine\", ?)");
10209 else
10210 Machine_ = machine;
10211
10212 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10213 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10214 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10215
10216 UniqueID_ = [device uniqueIdentifier];
10217
10218 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10219 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10220 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10221
10222 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10223 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10224 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10225
10226 if (mcc != NULL && mnc != NULL)
10227 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10228
10229 if (mnc != NULL)
10230 CFRelease(mnc);
10231 if (mcc != NULL)
10232 CFRelease(mcc);
10233
10234 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10235 Build_ = [system objectForKey:@"ProductBuildVersion"];
10236 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10237 Product_ = [info objectForKey:@"SafariProductVersion"];
10238 Safari_ = [info objectForKey:@"CFBundleVersion"];
10239 }
10240 /* }}} */
10241 /* Load Database {{{ */
10242 _trace();
10243 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10244 _trace();
10245 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10246
10247 if (Metadata_ == NULL)
10248 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10249 else {
10250 Settings_ = [Metadata_ objectForKey:@"Settings"];
10251
10252 Packages_ = [Metadata_ objectForKey:@"Packages"];
10253
10254 Values_ = [Metadata_ objectForKey:@"Values"];
10255 Sections_ = [Metadata_ objectForKey:@"Sections"];
10256 Sources_ = [Metadata_ objectForKey:@"Sources"];
10257
10258 Token_ = [Metadata_ objectForKey:@"Token"];
10259
10260 Version_ = [Metadata_ objectForKey:@"Version"];
10261
10262 @synchronized (HostConfig_) {
10263 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10264 }
10265 }
10266
10267 if (Settings_ != nil)
10268 Role_ = [Settings_ objectForKey:@"Role"];
10269
10270 if (Values_ == nil) {
10271 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10272 [Metadata_ setObject:Values_ forKey:@"Values"];
10273 }
10274
10275 if (Sections_ == nil) {
10276 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10277 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10278 }
10279
10280 if (Sources_ == nil) {
10281 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10282 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10283 }
10284
10285 if (Version_ == nil) {
10286 Version_ = [NSNumber numberWithUnsignedInt:0];
10287 [Metadata_ setObject:Version_ forKey:@"Version"];
10288 }
10289
10290 @synchronized (HostConfig_) {
10291 if (CydiaSource_ == nil) {
10292 CydiaSource_ = @"apt.saurik.com";
10293 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10294 }
10295 }
10296
10297 if ([Version_ unsignedIntValue] == 0) {
10298 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10299 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10300 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10301 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10302
10303 Version_ = [NSNumber numberWithUnsignedInt:1];
10304 [Metadata_ setObject:Version_ forKey:@"Version"];
10305
10306 [Metadata_ removeObjectForKey:@"LastUpdate"];
10307
10308 Changed_ = true;
10309 }
10310 /* }}} */
10311
10312 CydiaWriteSources();
10313
10314 _trace();
10315 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10316 _trace();
10317
10318 if (Packages_ != nil) {
10319 bool fail(false);
10320 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10321 _trace();
10322
10323 if (!fail) {
10324 [Metadata_ removeObjectForKey:@"Packages"];
10325 Packages_ = nil;
10326 Changed_ = true;
10327 }
10328 }
10329
10330 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10331
10332 #define MobileSubstrate_(name) \
10333 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10334 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10335 if (handle == NULL) \
10336 NSLog(@"%s", dlerror()); \
10337 }
10338
10339 MobileSubstrate_(Activator)
10340 MobileSubstrate_(libstatusbar)
10341 MobileSubstrate_(SimulatedKeyEvents)
10342 MobileSubstrate_(WinterBoard)
10343
10344 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10345 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10346
10347 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10348
10349 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10350 unlink("/tmp/.cydia.fw");
10351 goto firmware;
10352 } else if (access("/User", F_OK) != 0 || version < 4) {
10353 firmware:
10354 _trace();
10355 system("/usr/libexec/cydia/firmware.sh");
10356 _trace();
10357 }
10358
10359 _assert([[NSFileManager defaultManager]
10360 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10361 withIntermediateDirectories:YES
10362 attributes:nil
10363 error:NULL
10364 ]);
10365
10366 if (access("/tmp/cydia.chk", F_OK) == 0) {
10367 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10368 _assert(errno == ENOENT);
10369 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10370 _assert(errno == ENOENT);
10371 }
10372
10373 /* APT Initialization {{{ */
10374 _assert(pkgInitConfig(*_config));
10375 _assert(pkgInitSystem(*_config, _system));
10376
10377 if (lang != NULL)
10378 _config->Set("APT::Acquire::Translation", lang);
10379
10380 // XXX: this timeout might be important :(
10381 //_config->Set("Acquire::http::Timeout", 15);
10382
10383 _config->Set("Acquire::http::MaxParallel", 3);
10384 /* }}} */
10385 /* Color Choices {{{ */
10386 space_ = CGColorSpaceCreateDeviceRGB();
10387
10388 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10389 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10390 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10391 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10392 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10393 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10394 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10395 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10396 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10397
10398 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10399 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10400 /* }}}*/
10401 /* UIKit Configuration {{{ */
10402 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10403 if ($GSFontSetUseLegacyFontMetrics != NULL)
10404 $GSFontSetUseLegacyFontMetrics(YES);
10405
10406 // XXX: I have a feeling this was important
10407 //UIKeyboardDisableAutomaticAppearance();
10408 /* }}} */
10409
10410 Colon_ = UCLocalize("COLON_DELIMITED");
10411 Elision_ = UCLocalize("ELISION");
10412 Error_ = UCLocalize("ERROR");
10413 Warning_ = UCLocalize("WARNING");
10414
10415 _trace();
10416 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10417
10418 CGColorSpaceRelease(space_);
10419 CFRelease(Locale_);
10420
10421 [pool release];
10422 return value;
10423 }