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