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