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