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